source: trunk/admin/update.php @ 606

Last change on this file since 606 was 606, checked in by plg, 19 years ago
  • images.path column added to reduce database access
  • function mass_inserts moved from admin/remote_sites.php to admin/include/function.php
  • function mass_inserts used in admin/update.php
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.6 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5// | Copyright (C) 2003-2004 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $RCSfile$
9// | last update   : $Date: 2004-11-16 23:38:34 +0000 (Tue, 16 Nov 2004) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 606 $
12// +-----------------------------------------------------------------------+
13// | This program is free software; you can redistribute it and/or modify  |
14// | it under the terms of the GNU General Public License as published by  |
15// | the Free Software Foundation                                          |
16// |                                                                       |
17// | This program is distributed in the hope that it will be useful, but   |
18// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
19// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
20// | General Public License for more details.                              |
21// |                                                                       |
22// | You should have received a copy of the GNU General Public License     |
23// | along with this program; if not, write to the Free Software           |
24// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
25// | USA.                                                                  |
26// +-----------------------------------------------------------------------+
27
28if( !defined("PHPWG_ROOT_PATH") )
29{
30  die ("Hacking attempt!");
31}
32include_once( PHPWG_ROOT_PATH.'admin/include/isadmin.inc.php');
33
34define('CURRENT_DATE', date('Y-m-d'));
35// +-----------------------------------------------------------------------+
36// |                              functions                                |
37// +-----------------------------------------------------------------------+
38
39/**
40 * order categories (update categories.rank database field)
41 *
42 * the purpose of this function is to give a rank for all categories
43 * (insides its sub-category), even the newer that have none at te
44 * beginning. For this, ordering function selects all categories ordered by
45 * rank ASC then name ASC for each uppercat.
46 *
47 * @returns void
48 */
49function ordering()
50{
51  $current_rank = 0;
52  $current_uppercat = '';
53               
54  $query = '
55SELECT id, if(id_uppercat is null,\'\',id_uppercat) AS id_uppercat
56  FROM '.CATEGORIES_TABLE.'
57  ORDER BY id_uppercat,rank,name
58;';
59  $result = pwg_query($query);
60  while ($row = mysql_fetch_array($result))
61  {
62    if ($row['id_uppercat'] != $current_uppercat)
63    {
64      $current_rank = 0;
65      $current_uppercat = $row['id_uppercat'];
66    }
67    $query = '
68UPDATE '.CATEGORIES_TABLE.'
69  SET rank = '.++$current_rank.'
70  WHERE id = '.$row['id'].'
71;';
72    pwg_query($query);
73  }
74}
75
76function insert_local_category($id_uppercat)
77{
78  global $conf, $page, $user, $lang, $counts;
79 
80  $uppercats = '';
81  $output = '';
82
83  // 0. retrieving informations on the category to display
84  $cat_directory = PHPWG_ROOT_PATH.'galleries';
85  if (is_numeric($id_uppercat))
86  {
87    $query = 'SELECT name,uppercats,dir FROM '.CATEGORIES_TABLE;
88    $query.= ' WHERE id = '.$id_uppercat;
89    $query.= ';';
90    $row = mysql_fetch_array( pwg_query( $query));
91    $uppercats = $row['uppercats'];
92    $name      = $row['name'];
93    $dir       = $row['dir'];
94
95    $upper_array = explode( ',', $uppercats);
96
97    $local_dir = '';
98
99    $database_dirs = array();
100    $query = '
101SELECT id,dir FROM '.CATEGORIES_TABLE.'
102  WHERE id IN ('.$uppercats.')
103;';
104    $result = pwg_query( $query);
105    while ($row = mysql_fetch_array($result))
106    {
107      $database_dirs[$row['id']] = $row['dir'];
108    }
109    foreach ($upper_array as $id)
110    {
111      $local_dir.= $database_dirs[$id].'/';
112    }
113
114    $cat_directory.= '/'.$local_dir;
115
116    // 1. display the category name to update
117    $output = '<ul class="menu">';
118    $output.= '<li><strong>'.$name.'</strong>';
119    $output.= ' [ '.$dir.' ]';
120    $output.= '</li>';
121
122    // 2. we search pictures of the category only if the update is for all
123    //    or a cat_id is specified
124    if ($_POST['sync'] == 'files')
125    {
126      $output.= insert_local_element($cat_directory, $id_uppercat);
127    }
128  }
129
130  $fs_subdirs = get_category_directories($cat_directory);
131
132  $sub_category_dirs = array();
133  $query = '
134SELECT id,dir FROM '.CATEGORIES_TABLE.'
135  WHERE site_id = 1
136';
137  if (!is_numeric($id_uppercat))
138  {
139    $query.= ' AND id_uppercat IS NULL';
140  }
141  else
142  {
143    $query.= ' AND id_uppercat = '.$id_uppercat;
144  }
145  $query.= '
146    AND dir IS NOT NULL'; // virtual categories not taken
147  $query.= '
148;';
149  $result = pwg_query($query);
150  while ($row = mysql_fetch_array($result))
151  {
152    $sub_category_dirs[$row['id']] = $row['dir'];
153  }
154 
155  // 3. we have to remove the categories of the database not present anymore
156  $to_delete_categories = array();
157  foreach ($sub_category_dirs as $id => $dir)
158  {
159    if (!in_array($dir, $fs_subdirs))
160    {
161      array_push($to_delete_categories,$id);
162    }
163  }
164  if (count($to_delete_categories) > 0)
165  {
166    delete_categories($to_delete_categories);
167  }
168
169  // array of new categories to insert
170  $inserts = array();
171 
172  foreach ($fs_subdirs as $fs_subdir)
173  {
174    // 5. Is the category already existing ? we create a subcat if not
175    //    existing
176    $category_id = array_search($fs_subdir, $sub_category_dirs);
177    if (!is_numeric($category_id))
178    {
179      if (preg_match('/^[a-zA-Z0-9-_.]+$/', $fs_subdir))
180      {
181        $name = str_replace('_', ' ', $fs_subdir);
182
183        $value = "('".$fs_subdir."','".$name."',1";
184        if (!is_numeric($id_uppercat))
185        {
186          $value.= ',NULL';
187        }
188        else
189        {
190          $value.= ','.$id_uppercat;
191        }
192        $value.= ",'undef'";
193        $value.= ')';
194        array_push($inserts, $value);
195      }
196      else
197      {
198        $output.= '<span class="update_category_error">"'.$fs_subdir.'" : ';
199        $output.= $lang['update_wrong_dirname'].'</span><br />';
200      }
201    }
202  }
203
204  // we have to create the category
205  if (count($inserts) > 0)
206  {
207    $query = '
208INSERT INTO '.CATEGORIES_TABLE.'
209  (dir,name,site_id,id_uppercat,uppercats) VALUES
210';
211    $query.= implode(',', $inserts);
212    $query.= '
213;';
214    pwg_query($query);
215
216    $counts['new_categories']+= count($inserts);
217    // updating uppercats field
218    $query = '
219UPDATE '.CATEGORIES_TABLE.'
220  SET uppercats = ';
221    if ($uppercats != '')
222    {
223      $query.= "CONCAT('".$uppercats."',',',id)";
224    }
225    else
226    {
227      $query.= 'id';
228    }
229    $query.= '
230  WHERE id_uppercat ';
231    if (!is_numeric($id_uppercat))
232    {
233      $query.= 'IS NULL';
234    }
235    else
236    {
237      $query.= '= '.$id_uppercat;
238    }
239    $query.= '
240;';
241    pwg_query($query);
242  }
243
244  // Recursive call on the sub-categories (not virtual ones)
245  if (!isset($_POST['cat'])
246      or (isset($_POST['subcats-included'])
247          and $_POST['subcats-included'] == 1))
248  {
249    $query = '
250SELECT id
251  FROM '.CATEGORIES_TABLE.'
252  WHERE site_id = 1
253';
254    if (!is_numeric($id_uppercat))
255    {
256      $query.= '    AND id_uppercat IS NULL';
257    }
258    else
259    {
260      $query.= '    AND id_uppercat = '.$id_uppercat;
261    }
262    $query.= '
263    AND dir IS NOT NULL'; // virtual categories not taken
264    $query.= '
265;';
266    $result = pwg_query($query);
267    while ($row = mysql_fetch_array($result))
268    {
269      $output.= insert_local_category($row['id']);
270    }
271  }
272
273  if (is_numeric($id_uppercat))
274  {
275    $output.= '</ul>';
276  }
277  return $output;
278}
279
280function insert_local_element($dir, $category_id)
281{
282  global $lang,$conf,$counts;
283
284  $output = '';
285
286  // fs means FileSystem : $fs_files contains files in the filesystem found
287  // in $dir that can be managed by PhpWebGallery (see get_pwg_files
288  // function), $fs_thumbnails contains thumbnails, $fs_representatives
289  // contains potentially representative pictures for non picture files
290  $fs_files = get_pwg_files($dir);
291  $fs_thumbnails = get_thumb_files($dir);
292  $fs_representatives = get_representative_files($dir);
293
294  // element deletion
295  $to_delete_elements = array();
296  // deletion of element if the correspond file doesn't exist anymore
297  $query = '
298SELECT id,file
299  FROM '.IMAGES_TABLE.'
300  WHERE storage_category_id = '.$category_id.'
301;';
302  $result = pwg_query($query);
303  while ($row = mysql_fetch_array($result))
304  {
305    if (!in_array($row['file'], $fs_files))
306    {
307      $output.= $row['file'];
308      $output.= ' <span style="font-weight:bold;">';
309      $output.= $lang['update_disappeared'].'</span><br />';
310      array_push($to_delete_elements, $row['id']);
311    }
312  }
313  // in picture case, we also delete the element if the thumbnail doesn't
314  // existe anymore
315  $query = '
316SELECT id,file,tn_ext
317  FROM '.IMAGES_TABLE.'
318  WHERE storage_category_id = '.$category_id.'
319    AND ('.implode(' OR ',
320                   array_map(
321                     create_function('$s', 'return "file LIKE \'%".$s."\'";')
322                     , $conf['picture_ext'])).')
323;';
324  $result = pwg_query($query);
325  while ($row = mysql_fetch_array($result))
326  {
327    $thumbnail = $conf['prefix_thumbnail'];
328    $thumbnail.= get_filename_wo_extension($row['file']);
329    $thumbnail.= '.'.$row['tn_ext'];
330    if (!in_array($thumbnail, $fs_thumbnails))
331    {
332      $output.= $row['file'];
333      $output.= ' : <span style="font-weight:bold;">';
334      $output.= $lang['update_disappeared_tn'].'</span><br />';
335      array_push($to_delete_elements, $row['id']);
336    }
337  }
338
339  $to_delete_elements = array_unique($to_delete_elements);
340  if (count($to_delete_elements) > 0)
341  {
342    delete_elements($to_delete_elements);
343  }
344 
345  $registered_elements = array();
346  $query = '
347SELECT file FROM '.IMAGES_TABLE.'
348   WHERE storage_category_id = '.$category_id.'
349;';
350  $result = pwg_query($query);
351  while ($row = mysql_fetch_array($result))
352  {
353    array_push($registered_elements, $row['file']);
354  }
355
356  // unvalidated pictures are picture uploaded by users, but not validated
357  // by an admin (so not registered truly visible yet)
358  $unvalidated_pictures  = array();
359 
360  $query = '
361SELECT file
362  FROM '.WAITING_TABLE.'
363  WHERE storage_category_id = '.$category_id.'
364    AND validated = \'false\'
365;';
366  $result = pwg_query($query);
367  while ($row = mysql_fetch_array($result))
368  {
369    array_push($unvalidated_pictures, $row['file']);
370  }
371
372  // we only search among the picture present in the filesystem and not
373  // present in the database yet. If we know that this picture is known as
374  // an uploaded one but not validated, it's not tested neither
375  $unregistered_elements = array_diff($fs_files
376                                      ,$registered_elements
377                                      ,$unvalidated_pictures);
378
379  $inserts = array();
380 
381  foreach ($unregistered_elements as $unregistered_element)
382  {
383    if (preg_match('/^[a-zA-Z0-9-_.]+$/', $unregistered_element))
384    {
385      $file_wo_ext = get_filename_wo_extension($unregistered_element);
386      $tn_ext = '';
387      foreach ($conf['picture_ext'] as $ext)
388      {
389        $test = $conf['prefix_thumbnail'].$file_wo_ext.'.'.$ext;
390        if (!in_array($test, $fs_thumbnails))
391        {
392          continue;
393        }
394        else
395        {
396          $tn_ext = $ext;
397          break;
398        }
399      }
400
401      // 2 cases : the element is a picture or not. Indeed, for a picture
402      // thumbnail is mandatory and for non picture element, thumbnail and
403      // representative is optionnal
404      if (in_array(get_extension($unregistered_element), $conf['picture_ext']))
405      {
406        // if we found a thumnbnail corresponding to our picture...
407        if ($tn_ext != '')
408        {
409          $insert = array();
410          $insert['file'] = $unregistered_element;
411          $insert['storage_category_id'] = $category_id;
412          $insert['date_available'] = CURRENT_DATE;
413          $insert['tn_ext'] = $tn_ext;
414          $insert['path'] = $dir.$unregistered_element;
415
416          $counts['new_elements']++;
417          array_push($inserts, $insert);
418        }
419        else
420        {
421          $output.= '<span class="update_error_element">';
422          $output.= $lang['update_missing_tn'].' : '.$unregistered_element;
423          $output.= ' (<span style="font-weight:bold;">';
424          $output.= $conf['prefix_thumbnail'];
425          $output.= get_filename_wo_extension($unregistered_element);
426          $output.= '.XXX</span>';
427          $output.= ', XXX = ';
428          $output.= implode(', ', $conf['picture_ext']);
429          $output.= ')</span><br />';
430        }
431      }
432      else
433      {
434        $representative_ext = '';
435        foreach ($conf['picture_ext'] as $ext)
436        {
437          $candidate = $file_wo_ext.'.'.$ext;
438          if (!in_array($candidate, $fs_representatives))
439          {
440            continue;
441          }
442          else
443          {
444            $representative_ext = $ext;
445            break;
446          }
447        }
448
449        $insert = array();
450        $insert['file'] = $unregistered_element;
451        $insert['path'] = $dir.$unregistered_element;
452        $insert['storage_category_id'] = $category_id;
453        $insert['date_available'] = CURRENT_DATE;
454        if ( $tn_ext != '' )
455        {
456          $insert['tn_ext'] = $tn_ext;
457        }
458        if ( $representative_ext != '' )
459        {
460          $insert['representative_ext'] = $representative_ext;
461        }
462
463        $counts['new_elements']++;
464        array_push($inserts, $insert);
465      }
466    }
467    else
468    {
469      $output.= '<span class="update_error_element">"';
470      $output.= $unregistered_element.'" : ';
471      $output.= $lang['update_wrong_dirname'].'</span><br />';
472    }
473  }
474 
475  if (count($inserts) > 0)
476  {
477    // inserts all found pictures
478    $dbfields = array(
479      'file','storage_category_id','date_available','tn_ext'
480      ,'representative_ext','path'
481      );
482    mass_inserts(IMAGES_TABLE, $dbfields, $inserts);
483
484    // what are the ids of the pictures in the $category_id ?
485    $ids = array();
486
487    $query = '
488SELECT id
489  FROM '.IMAGES_TABLE.'
490  WHERE storage_category_id = '.$category_id.'
491;';
492    $result = pwg_query($query);
493    while ($row = mysql_fetch_array($result))
494    {
495      array_push($ids, $row['id']);
496    }
497
498    // recreation of the links between this storage category pictures and
499    // its storage category
500    $query = '
501DELETE FROM '.IMAGE_CATEGORY_TABLE.'
502  WHERE category_id = '.$category_id.'
503    AND image_id IN ('.implode(',', $ids).')
504;';
505    pwg_query($query);
506
507    foreach ($ids as $num => $image_id)
508    {
509      $ids[$num] =  '('.$category_id.','.$image_id.')';
510    }
511    $query = '
512INSERT INTO '.IMAGE_CATEGORY_TABLE.'
513  (category_id,image_id) VALUES
514  '.implode(',', $ids).'
515;';
516    pwg_query($query);
517  }
518  return $output;
519}
520// +-----------------------------------------------------------------------+
521// |                        template initialization                        |
522// +-----------------------------------------------------------------------+
523$template->set_filenames(array('update'=>'admin/update.tpl'));
524
525$base_url = PHPWG_ROOT_PATH.'admin.php?page=update';
526
527$template->assign_vars(
528  array(
529    'L_SUBMIT'=>$lang['submit'],
530    'L_UPDATE_TITLE'=>$lang['update_default_title'],
531    'L_UPDATE_SYNC_FILES'=>$lang['update_sync_files'],
532    'L_UPDATE_SYNC_DIRS'=>$lang['update_sync_dirs'],
533    'L_UPDATE_SYNC_ALL'=>$lang['update_sync_all'],
534    'L_UPDATE_SYNC_METADATA'=>$lang['update_sync_metadata'],
535    'L_UPDATE_SYNC_METADATA_NEW'=>$lang['update_sync_metadata_new'],
536    'L_UPDATE_SYNC_METADATA_ALL'=>$lang['update_sync_metadata_all'],
537    'L_UPDATE_CATS_SUBSET'=>$lang['update_cats_subset'],
538    'L_RESULT_UPDATE'=>$lang['update_part_research'],
539    'L_NB_NEW_ELEMENTS'=>$lang['update_nb_new_elements'],
540    'L_NB_NEW_CATEGORIES'=>$lang['update_nb_new_categories'],
541    'L_NB_DEL_ELEMENTS'=>$lang['update_nb_del_elements'],
542    'L_NB_DEL_CATEGORIES'=>$lang['update_nb_del_categories'],
543    'L_SEARCH_SUBCATS_INCLUDED'=>$lang['search_subcats_included'],
544   
545    'U_SYNC_DIRS'=>add_session_id($base_url.'&amp;update=dirs'),
546    'U_SYNC_ALL'=>add_session_id($base_url.'&amp;update=all'),
547    'U_SYNC_METADATA_NEW'=>add_session_id($base_url.'&amp;metadata=all:new'),
548    'U_SYNC_METADATA_ALL'=>add_session_id($base_url.'&amp;metadata=all')
549    ));
550// +-----------------------------------------------------------------------+
551// |                        introduction : choices                         |
552// +-----------------------------------------------------------------------+
553if (!isset($_POST['submit']))
554{
555  $template->assign_block_vars('introduction', array());
556
557  $query = '
558SELECT id
559  FROM '.CATEGORIES_TABLE.'
560  WHERE site_id != 1
561;';
562  $result = pwg_query($query);
563  while ($row = mysql_fetch_array($result))
564  {
565    array_push($user['restrictions'], $row['id']);
566  }
567  $user['forbidden_categories'] = implode(',', $user['restrictions']);
568  $user['expand'] = true;
569  $structure = create_user_structure('');
570  display_select_categories($structure,
571                            '&nbsp;',
572                            array(),
573                            'introduction.category_option',
574                            array());
575}
576// +-----------------------------------------------------------------------+
577// |                          synchronize files                            |
578// +-----------------------------------------------------------------------+
579else if (isset($_POST['submit'])
580         and ($_POST['sync'] == 'dirs' or $_POST['sync'] == 'files'))
581{
582  $counts = array(
583    'new_elements' => 0,
584    'new_categories' => 0,
585    'del_elements' => 0,
586    'del_categories' => 0
587    );
588
589  if (isset($_POST['cat']))
590  {
591    $opts['category_id'] = $_POST['cat'];
592  }
593  else
594  {
595    $opts['category_id'] = 'NULL';
596  }
597 
598  $start = get_moment();
599  $categories = insert_local_category($opts['category_id']);
600  echo get_elapsed_time($start,get_moment()).' for scanning directories<br />';
601 
602  $template->assign_block_vars(
603    'update',
604    array(
605      'CATEGORIES'=>$categories,
606      'NB_NEW_CATEGORIES'=>$counts['new_categories'],
607      'NB_DEL_CATEGORIES'=>$counts['del_categories'],
608      'NB_NEW_ELEMENTS'=>$counts['new_elements'],
609      'NB_DEL_ELEMENTS'=>$counts['del_elements']
610      ));
611  $start = get_moment();
612  update_category('all');
613  echo get_elapsed_time($start,get_moment()).' for update_category(all)<br />';
614  $start = get_moment();
615  ordering();
616  echo get_elapsed_time($start, get_moment()).' for ordering categories<br />';
617}
618// +-----------------------------------------------------------------------+
619// |                          synchronize metadata                         |
620// +-----------------------------------------------------------------------+
621else if (isset($_POST['submit']) and preg_match('/^metadata/', $_POST['sync']))
622{
623  // sync only never synchronized files ?
624  if ($_POST['sync'] == 'metadata_new')
625  {
626    $opts['only_new'] = true;
627  }
628  else
629  {
630    $opts['only_new'] = false;
631  }
632  $opts['category_id'] = '';
633  $opts['recursive'] = true;
634 
635  if (isset($_POST['cat']))
636  {
637    $opts['category_id'] = $_POST['cat'];
638    // recursive ?
639    if (!isset($_POST['subcats-included']) or $_POST['subcats-included'] != 1)
640    {
641      $opts['recursive'] = false;
642    }
643  }
644  $start = get_moment();
645  $files = get_filelist($opts['category_id'],
646                        $opts['recursive'],
647                        $opts['only_new']);
648  echo get_elapsed_time($start, get_moment()).' for get_filelist<br />';
649 
650  $start = get_moment();
651  update_metadata($files);
652  echo get_elapsed_time($start, get_moment()).' for metadata update<br />';
653}
654// +-----------------------------------------------------------------------+
655// |                          sending html code                            |
656// +-----------------------------------------------------------------------+
657$template->assign_var_from_handle('ADMIN_CONTENT', 'update');
658?>
Note: See TracBrowser for help on using the repository browser.