source: trunk/admin/update.php @ 587

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