source: trunk/admin/update.php @ 665

Last change on this file since 665 was 665, checked in by plg, 19 years ago
  • admin/update : deletion of useless lines
  • admin/thumbnail : use new process for finding pictures without thumbnails. No more recursivity
  • admin/thumbnail : only show list of directory containing pictures without thumbnails, not the whole directory tree
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.3 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-12-30 00:55:27 +0000 (Thu, 30 Dec 2004) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 665 $
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$error_labels = array('PWG-UPDATE-1' => $lang['update_wrong_dirname_short'],
36                      'PWG-UPDATE-2' => $lang['update_missing_tn_short']);
37$errors = array();
38$infos = array();
39// +-----------------------------------------------------------------------+
40// |                      directories / categories                         |
41// +-----------------------------------------------------------------------+
42if (isset($_POST['submit'])
43    and ($_POST['sync'] == 'dirs' or $_POST['sync'] == 'files'))
44{
45  $counts['new_categories'] = 0;
46  $counts['del_categories'] = 0;
47  $counts['del_elements'] = 0;
48  $counts['new_elements'] = 0;
49
50  // shall we simulate only
51  if (isset($_POST['simulate']) and $_POST['simulate'] == 1)
52  {
53    $simulate = true;
54  }
55  else
56  {
57    $simulate = false;
58  }
59 
60  $start = get_moment();
61  // which categories to update ?
62  $cat_ids = array();
63
64  $query = '
65SELECT id, uppercats, global_rank, status, visible
66  FROM '.CATEGORIES_TABLE.'
67  WHERE dir IS NOT NULL
68    AND site_id = 1';
69  if (isset($_POST['cat']) and is_numeric($_POST['cat']))
70  {
71    if (isset($_POST['subcats-included']) and $_POST['subcats-included'] == 1)
72    {
73      $query.= '
74    AND uppercats REGEXP \'(^|,)'.$_POST['cat'].'(,|$)\'
75';
76    }
77    else
78    {
79      $query.= '
80    AND id = '.$_POST['cat'].'
81';
82    }
83  }
84  $query.= '
85;';
86  $result = pwg_query($query);
87
88  $db_categories = array();
89  while ($row = mysql_fetch_array($result))
90  {
91    $db_categories[$row['id']] = $row;
92  }
93
94  // get categort full directories in an array for comparison with file
95  // system directory tree
96  $db_fulldirs = get_fulldirs(array_keys($db_categories));
97 
98  // what is the base directory to search file system sub-directories ?
99  if (isset($_POST['cat']) and is_numeric($_POST['cat']))
100  {
101    $basedir = $db_fulldirs[$_POST['cat']];
102  }
103  else
104  {
105    $query = '
106SELECT galleries_url
107  FROM '.SITES_TABLE.'
108  WHERE id = 1
109;';
110    list($galleries_url) = mysql_fetch_array(pwg_query($query));
111    $basedir = preg_replace('#/*$#', '', $galleries_url);
112  }
113
114  // we need to have fulldirs as keys to make efficient comparison
115  $db_fulldirs = array_flip($db_fulldirs);
116
117  // finding next rank for each id_uppercat
118  $next_rank['NULL'] = 1;
119 
120  $query = '
121SELECT id_uppercat, MAX(rank)+1 AS next_rank
122  FROM '.CATEGORIES_TABLE.'
123  GROUP BY id_uppercat
124;';
125  $result = pwg_query($query);
126  while ($row = mysql_fetch_array($result))
127  {
128    // for the id_uppercat NULL, we write 'NULL' and not the empty string
129    if (!isset($row['id_uppercat']) or $row['id_uppercat'] == '')
130    {
131      $row['id_uppercat'] = 'NULL';
132    }
133    $next_rank[$row['id_uppercat']] = $row['next_rank'];
134  }
135 
136  // next category id available
137  $query = '
138SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_id
139  FROM '.CATEGORIES_TABLE.'
140;';
141  list($next_id) = mysql_fetch_array(pwg_query($query));
142
143  // retrieve file system sub-directories fulldirs
144  $fs_fulldirs = get_fs_directories($basedir);
145 
146  $inserts = array();
147  // new categories are the directories not present yet in the database
148  foreach (array_diff($fs_fulldirs, array_keys($db_fulldirs)) as $fulldir)
149  {
150    $dir = basename($fulldir);
151    if (preg_match('/^[a-zA-Z0-9-_.]+$/', $dir))
152    {
153      $insert = array();
154     
155      $insert{'id'} = $next_id++;
156      $insert{'dir'} = $dir;
157      $insert{'name'} = str_replace('_', ' ', $dir);
158      $insert{'site_id'} = 1;
159      $insert{'commentable'} = $conf['newcat_default_commentable'];
160      $insert{'uploadable'} = $conf['newcat_default_uploadable'];
161      $insert{'status'} = $conf{'newcat_default_status'};
162      $insert{'visible'} = $conf{'newcat_default_visible'};
163
164      if (isset($db_fulldirs[dirname($fulldir)]))
165      {
166        $parent = $db_fulldirs[dirname($fulldir)];
167
168        $insert{'id_uppercat'} = $parent;
169        $insert{'uppercats'} =
170          $db_categories[$parent]['uppercats'].','.$insert{'id'};
171        $insert{'rank'} = $next_rank[$parent]++;
172        $insert{'global_rank'} =
173          $db_categories[$parent]['global_rank'].'.'.$insert{'rank'};
174        if ('private' == $db_categories[$parent]['status'])
175        {
176          $insert{'status'} = 'private';
177        }
178        if ('false' == $db_categories[$parent]['visible'])
179        {
180          $insert{'visible'} = 'false';
181        }
182      }
183      else
184      {
185        $insert{'uppercats'} = $insert{'id'};
186        $insert{'rank'} = $next_rank['NULL']++;
187        $insert{'global_rank'} = $insert{'rank'};
188      }
189
190      array_push($inserts, $insert);
191      array_push($infos, array('path' => $fulldir,
192                               'info' => $lang['update_research_added']));
193
194      // add the new category to $db_categories and $db_fulldirs array
195      $db_categories[$insert{'id'}] =
196        array(
197          'id' => $insert{'id'},
198          'status' => $insert{'status'},
199          'visible' => $insert{'visible'},
200          'uppercats' => $insert{'uppercats'},
201          'global_rank' => $insert{'global_rank'}
202          );
203      $db_fulldirs[$fulldir] = $insert{'id'};
204      $next_rank[$insert{'id'}] = 1;
205    }
206    else
207    {
208      array_push($errors, array('path' => $fulldir, 'type' => 'PWG-UPDATE-1'));
209    }
210  }
211
212  if (count($inserts) > 0)
213  {
214    if (!$simulate)
215    {
216      $dbfields = array(
217        'id','dir','name','site_id','id_uppercat','uppercats','commentable',
218        'uploadable','visible','status','rank','global_rank'
219        );
220      mass_inserts(CATEGORIES_TABLE, $dbfields, $inserts);
221    }
222   
223    $counts['new_categories'] = count($inserts);
224  }
225
226  // to delete categories
227  $to_delete = array();
228  foreach (array_diff(array_keys($db_fulldirs), $fs_fulldirs) as $fulldir)
229  {
230    array_push($to_delete, $db_fulldirs[$fulldir]);
231    unset($db_fulldirs[$fulldir]);
232    array_push($infos, array('path' => $fulldir,
233                             'info' => $lang['update_research_deleted']));
234  }
235  if (count($to_delete) > 0)
236  {
237    if (!$simulate)
238    {
239      delete_categories($to_delete);
240    }
241    $counts['del_categories'] = count($to_delete);
242  }
243 
244  echo get_elapsed_time($start, get_moment());
245  echo ' for new method scanning directories<br />';
246}
247// +-----------------------------------------------------------------------+
248// |                           files / elements                            |
249// +-----------------------------------------------------------------------+
250if (isset($_POST['submit']) and $_POST['sync'] == 'files')
251{ 
252  $start_files = get_moment();
253  $start= $start_files;
254
255  $fs = get_fs($basedir);
256 
257  echo get_elapsed_time($start, get_moment());
258  echo ' for get_fs<br />';
259 
260  $cat_ids = array_diff(array_keys($db_categories), $to_delete);
261
262  $db_elements = array();
263  $db_unvalidated = array();
264 
265  if (count($cat_ids) > 0)
266  {
267    $query = '
268SELECT id, path
269  FROM '.IMAGES_TABLE.'
270  WHERE storage_category_id IN (
271'.wordwrap(implode(', ', $cat_ids), 80, "\n").')
272;';
273    $result = pwg_query($query);
274    while ($row = mysql_fetch_array($result))
275    {
276      $db_elements[$row['id']] = $row['path'];
277    }
278
279    // searching the unvalidated waiting elements (they must not be taken into
280    // account)
281    $query = '
282SELECT file,storage_category_id
283  FROM '.WAITING_TABLE.'
284  WHERE storage_category_id IN (
285'.wordwrap(implode(', ', $cat_ids), 80, "\n").')
286    AND validated = \'false\'
287;';
288    $result = pwg_query($query);
289    while ($row = mysql_fetch_array($result))
290    {
291      array_push(
292        $db_unvalidated,
293        array_search($row['storage_category_id'],
294                     $db_fulldirs).'/'.$row['file']
295        );
296    }
297  }
298
299  // next element id available
300  $query = '
301SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id
302  FROM '.IMAGES_TABLE.'
303;';
304  list($next_element_id) = mysql_fetch_array(pwg_query($query));
305
306  $start = get_moment();
307
308  // because isset is one hundred time faster than in_array
309  $fs['thumbnails'] = array_flip($fs['thumbnails']);
310  $fs['representatives'] = array_flip($fs['representatives']);
311 
312  $inserts = array();
313  $insert_links = array();
314 
315  foreach (array_diff($fs['elements'], $db_elements, $db_unvalidated) as $path)
316  {
317    $insert = array();
318    // storage category must exist
319    $dirname = dirname($path);
320    if (!isset($db_fulldirs[$dirname]))
321    {
322      continue;
323    }
324    $filename = basename($path);
325    if (!preg_match('/^[a-zA-Z0-9-_.]+$/', $filename))
326    {
327      array_push($errors, array('path' => $path, 'type' => 'PWG-UPDATE-1'));
328      continue;
329    }
330
331    // searching the thumbnail
332    $filename_wo_ext = get_filename_wo_extension($filename);
333    $tn_ext = '';
334    $base_test = $dirname.'/thumbnail/';
335    $base_test.= $conf['prefix_thumbnail'].$filename_wo_ext.'.';
336    foreach ($conf['picture_ext'] as $ext)
337    {
338      $test = $base_test.$ext;
339      if (isset($fs['thumbnails'][$test]))
340      {
341        $tn_ext = $ext;
342        break;
343      }
344    }
345
346    // 2 cases : the element is a picture or not. Indeed, for a picture
347    // thumbnail is mandatory and for non picture element, thumbnail and
348    // representative are optionnal
349    if (in_array(get_extension($filename), $conf['picture_ext']))
350    {
351      // if we found a thumnbnail corresponding to our picture...
352      if ($tn_ext != '')
353      {
354        $insert{'id'} = $next_element_id++;
355        $insert{'file'} = $filename;
356        $insert{'storage_category_id'} = $db_fulldirs[$dirname];
357        $insert{'date_available'} = CURRENT_DATE;
358        $insert{'tn_ext'} = $tn_ext;
359        $insert{'path'} = $path;
360
361        array_push($inserts, $insert);
362        array_push($insert_links,
363                   array('image_id' => $insert{'id'},
364                         'category_id' => $insert{'storage_category_id'}));
365        array_push($infos, array('path' => $insert{'path'},
366                                 'info' => $lang['update_research_added']));
367      }
368      else
369      {
370        array_push($errors, array('path' => $path, 'type' => 'PWG-UPDATE-2'));
371      }
372    }
373    else
374    {
375      // searching a representative
376      $representative_ext = '';
377      $base_test = $dirname.'/pwg_representative/'.$filename_wo_ext.'.';
378      foreach ($conf['picture_ext'] as $ext)
379      {
380        $test = $base_test.$ext;
381        if (isset($fs['representatives'][$test]))
382        {
383          $representative_ext = $ext;
384          break;
385        }
386      }
387
388      $insert{'id'} = $next_element_id++;
389      $insert{'file'} = $filename;
390      $insert{'storage_category_id'} = $db_fulldirs[$dirname];
391      $insert{'date_available'} = CURRENT_DATE;
392      $insert{'path'} = $path;
393       
394      if ($tn_ext != '')
395      {
396        $insert{'tn_ext'} = $tn_ext;
397      }
398      if ($representative_ext != '')
399      {
400        $insert{'representative_ext'} = $representative_ext;
401      }
402     
403      array_push($inserts, $insert);
404      array_push($insert_links,
405                 array('image_id' => $insert{'id'},
406                       'category_id' => $insert{'storage_category_id'}));
407      array_push($infos, array('path' => $insert{'path'},
408                               'info' => $lang['update_research_added']));
409    }
410  }
411
412  if (count($inserts) > 0)
413  {
414    if (!$simulate)
415    {
416      // inserts all new elements
417      $dbfields = array(
418        'id','file','storage_category_id','date_available','tn_ext'
419        ,'representative_ext','path'
420        );
421      mass_inserts(IMAGES_TABLE, $dbfields, $inserts);
422
423      // insert all links between new elements and their storage category
424      $dbfields = array('image_id','category_id');
425      mass_inserts(IMAGE_CATEGORY_TABLE, $dbfields, $insert_links);
426    }
427    $counts['new_elements'] = count($inserts);
428  }
429
430  // delete elements that are in database but not in the filesystem
431  $to_delete_elements = array();
432  foreach (array_diff($db_elements, $fs['elements']) as $path)
433  {
434    array_push($to_delete_elements, array_search($path, $db_elements));
435    array_push($infos, array('path' => $path,
436                             'info' => $lang['update_research_deleted']));
437  }
438  if (count($to_delete_elements) > 0)
439  {
440    if (!$simulate)
441    {
442      delete_elements($to_delete_elements);
443    }
444    $counts['del_elements'] = count($to_delete_elements);
445  }
446 
447  echo get_elapsed_time($start_files, get_moment());
448  echo ' for new method scanning files<br />';
449}
450// +-----------------------------------------------------------------------+
451// |                        template initialization                        |
452// +-----------------------------------------------------------------------+
453$template->set_filenames(array('update'=>'admin/update.tpl'));
454
455$result_title = '';
456if (isset($simulate) and $simulate)
457{
458  $result_title.= $lang['update_simulation_title'].' ';
459}
460$result_title.= $lang['update_part_research'];
461
462$template->assign_vars(
463  array(
464    'L_SUBMIT'=>$lang['submit'],
465    'L_UPDATE_TITLE'=>$lang['update_default_title'],
466    'L_UPDATE_SYNC_FILES'=>$lang['update_sync_files'],
467    'L_UPDATE_SYNC_DIRS'=>$lang['update_sync_dirs'],
468    'L_UPDATE_SYNC_ALL'=>$lang['update_sync_all'],
469    'L_UPDATE_SYNC_METADATA'=>$lang['update_sync_metadata'],
470    'L_UPDATE_SYNC_METADATA_NEW'=>$lang['update_sync_metadata_new'],
471    'L_UPDATE_SYNC_METADATA_ALL'=>$lang['update_sync_metadata_all'],
472    'L_UPDATE_CATS_SUBSET'=>$lang['update_cats_subset'],
473    'L_RESULT_UPDATE'=>$result_title,
474    'L_NB_NEW_ELEMENTS'=>$lang['update_nb_new_elements'],
475    'L_NB_NEW_CATEGORIES'=>$lang['update_nb_new_categories'],
476    'L_NB_DEL_ELEMENTS'=>$lang['update_nb_del_elements'],
477    'L_NB_DEL_CATEGORIES'=>$lang['update_nb_del_categories'],
478    'L_UPDATE_NB_ERRORS'=>$lang['update_nb_errors'],
479    'L_SEARCH_SUBCATS_INCLUDED'=>$lang['search_subcats_included'],
480    'L_UPDATE_WRONG_DIRNAME_INFO'=>$lang['update_wrong_dirname_info'],
481    'L_UPDATE_MISSING_TN_INFO'=>$lang['update_missing_tn_info'],
482    'PICTURE_EXT_LIST'=>implode(',', $conf['picture_ext']),
483    'L_UPDATE_ERROR_LIST_TITLE'=>$lang['update_error_list_title'],
484    'L_UPDATE_ERRORS_CAPTION'=>$lang['update_errors_caption'],
485    'L_UPDATE_DISPLAY_INFO'=>$lang['update_display_info'],
486    'L_UPDATE_SIMULATE'=>$lang['update_simulate'],
487    'L_UPDATE_INFOS_TITLE'=>$lang['update_infos_title']
488    ));
489// +-----------------------------------------------------------------------+
490// |                        introduction : choices                         |
491// +-----------------------------------------------------------------------+
492if (!isset($_POST['submit']))
493{
494  $template->assign_block_vars('introduction', array());
495
496  $query = '
497SELECT id,name,uppercats,global_rank
498  FROM '.CATEGORIES_TABLE.'
499  WHERE site_id = 1
500;';
501  display_select_cat_wrapper($query,
502                             array(),
503                             'introduction.category_option',
504                             false);
505}
506// +-----------------------------------------------------------------------+
507// |                          synchronize files                            |
508// +-----------------------------------------------------------------------+
509else if (isset($_POST['submit'])
510         and ($_POST['sync'] == 'dirs' or $_POST['sync'] == 'files'))
511{
512  $template->assign_block_vars(
513    'update',
514    array(
515      'NB_NEW_CATEGORIES'=>$counts['new_categories'],
516      'NB_DEL_CATEGORIES'=>$counts['del_categories'],
517      'NB_NEW_ELEMENTS'=>$counts['new_elements'],
518      'NB_DEL_ELEMENTS'=>$counts['del_elements'],
519      'NB_ERRORS'=>count($errors),
520      ));
521 
522  if (count($errors) > 0)
523  {
524    $template->assign_block_vars('update.errors', array());
525    foreach ($errors as $error)
526    {
527      $template->assign_block_vars(
528        'update.errors.error',
529        array(
530          'ELEMENT' => $error['path'],
531          'LABEL' => $error['type'].' ('.$error_labels[$error['type']].')'
532          ));
533    }
534  }
535  if (count($infos) > 0
536      and isset($_POST['display_info'])
537      and $_POST['display_info'] == 1)
538  {
539    $template->assign_block_vars('update.infos', array());
540    foreach ($infos as $info)
541    {
542      $template->assign_block_vars(
543        'update.infos.info',
544        array(
545          'ELEMENT' => $info['path'],
546          'LABEL' => $info['info']
547          ));
548    }
549  }
550
551  if (!$simulate)
552  {
553    $start = get_moment();
554    update_category('all');
555    echo get_elapsed_time($start,get_moment());
556    echo ' for update_category(all)<br />';
557    $start = get_moment();
558    ordering();
559    update_global_rank();
560    echo get_elapsed_time($start, get_moment());
561    echo ' for ordering categories<br />';
562  }
563}
564// +-----------------------------------------------------------------------+
565// |                          synchronize metadata                         |
566// +-----------------------------------------------------------------------+
567else if (isset($_POST['submit']) and preg_match('/^metadata/', $_POST['sync']))
568{
569  // sync only never synchronized files ?
570  if ($_POST['sync'] == 'metadata_new')
571  {
572    $opts['only_new'] = true;
573  }
574  else
575  {
576    $opts['only_new'] = false;
577  }
578  $opts['category_id'] = '';
579  $opts['recursive'] = true;
580 
581  if (isset($_POST['cat']))
582  {
583    $opts['category_id'] = $_POST['cat'];
584    // recursive ?
585    if (!isset($_POST['subcats-included']) or $_POST['subcats-included'] != 1)
586    {
587      $opts['recursive'] = false;
588    }
589  }
590  $start = get_moment();
591  $files = get_filelist($opts['category_id'],
592                        $opts['recursive'],
593                        $opts['only_new']);
594  echo get_elapsed_time($start, get_moment()).' for get_filelist<br />';
595 
596  $start = get_moment();
597  update_metadata($files);
598  echo get_elapsed_time($start, get_moment()).' for metadata update<br />';
599}
600// +-----------------------------------------------------------------------+
601// |                          sending html code                            |
602// +-----------------------------------------------------------------------+
603$template->assign_var_from_handle('ADMIN_CONTENT', 'update');
604?>
Note: See TracBrowser for help on using the repository browser.