source: branches/1.7/admin/site_update.php @ 6503

Last change on this file since 6503 was 2307, checked in by rvelices, 16 years ago

merge r 2306 from trunk to branch-1_7

  • merged function ordering() with update_global_rank() and also optimized the queries
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 28.7 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-2007 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | file          : $Id: site_update.php 2307 2008-04-20 22:25:40Z rvelices $
8// | last update   : $Date: 2008-04-20 22:25:40 +0000 (Sun, 20 Apr 2008) $
9// | last modifier : $Author: rvelices $
10// | revision      : $Revision: 2307 $
11// +-----------------------------------------------------------------------+
12// | This program is free software; you can redistribute it and/or modify  |
13// | it under the terms of the GNU General Public License as published by  |
14// | the Free Software Foundation                                          |
15// |                                                                       |
16// | This program is distributed in the hope that it will be useful, but   |
17// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
18// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
19// | General Public License for more details.                              |
20// |                                                                       |
21// | You should have received a copy of the GNU General Public License     |
22// | along with this program; if not, write to the Free Software           |
23// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
24// | USA.                                                                  |
25// +-----------------------------------------------------------------------+
26
27if (!defined('PHPWG_ROOT_PATH'))
28{
29  die('Hacking attempt!');
30}
31
32include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
33
34// +-----------------------------------------------------------------------+
35// | Check Access and exit when user status is not ok                      |
36// +-----------------------------------------------------------------------+
37check_status(ACCESS_ADMINISTRATOR);
38
39if (!is_numeric($_GET['site']))
40{
41  die ('site param missing or invalid');
42}
43$site_id = $_GET['site'];
44
45$query='
46SELECT galleries_url
47  FROM '.SITES_TABLE.'
48  WHERE id = '.$site_id.'
49;';
50list($site_url) = mysql_fetch_row(pwg_query($query));
51if (!isset($site_url))
52{
53  die('site '.$site_id.' does not exist');
54}
55$site_is_remote = url_is_remote($site_url);
56
57list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
58define('CURRENT_DATE', $dbnow);
59
60$error_labels = array(
61  'PWG-UPDATE-1' => array(
62    l10n('update_wrong_dirname_short'),
63    l10n('update_wrong_dirname_info')
64    ),
65  'PWG-UPDATE-2' => array(
66    l10n('update_missing_tn_short'),
67    l10n('update_missing_tn_info').implode(',', $conf['picture_ext'])
68    ),
69  'PWG-ERROR-NO-FS' => array(
70    l10n('update_missing_file_or_dir'),
71    l10n('update_missing_file_or_dir_info')
72    ),
73  'PWG-ERROR-VERSION' => array(
74    l10n('update_err_pwg_version_differs'),
75    l10n('update_err_pwg_version_differs_info')
76    ),
77  'PWG-ERROR-NOLISTING' => array(
78    l10n('update_err_remote_listing_not_found'),
79    l10n('update_err_remote_listing_not_found_info')
80    )
81  );
82$errors = array();
83$infos = array();
84
85if ($site_is_remote)
86{
87  include_once(PHPWG_ROOT_PATH.'admin/site_reader_remote.php');
88  $local_listing = null;
89  if ( isset($_GET['local_listing'])
90      and $_GET['local_listing'] )
91  {
92    $local_listing = PHPWG_ROOT_PATH.'listing.xml';
93  }
94  $site_reader = new RemoteSiteReader($site_url, $local_listing);
95}
96else
97{
98  include_once( PHPWG_ROOT_PATH.'admin/site_reader_local.php');
99  $site_reader = new LocalSiteReader($site_url);
100}
101
102$general_failure = true;
103if (isset($_POST['submit']))
104{
105  if (!isset($conf['flip_picture_ext']))
106  {
107    $conf['flip_picture_ext'] = array_flip($conf['picture_ext']);
108  }
109  if ($site_reader->open())
110  {
111    $general_failure = false;
112  }
113
114  // shall we simulate only
115  if ((isset($_POST['simulate']) and $_POST['simulate'] == 1) or is_adviser())
116  {
117    $simulate = true;
118  }
119  else
120  {
121    $simulate = false;
122  }
123}
124
125// +-----------------------------------------------------------------------+
126// |                      directories / categories                         |
127// +-----------------------------------------------------------------------+
128if (isset($_POST['submit'])
129    and ($_POST['sync'] == 'dirs' or $_POST['sync'] == 'files'))
130{
131  $counts['new_categories'] = 0;
132  $counts['del_categories'] = 0;
133  $counts['del_elements'] = 0;
134  $counts['new_elements'] = 0;
135  $counts['upd_elements'] = 0;
136}
137
138
139if (isset($_POST['submit'])
140    and ($_POST['sync'] == 'dirs' or $_POST['sync'] == 'files')
141    and !$general_failure)
142{
143  $start = get_moment();
144  // which categories to update ?
145  $cat_ids = array();
146
147  $query = '
148SELECT id, uppercats, global_rank, status, visible
149  FROM '.CATEGORIES_TABLE.'
150  WHERE dir IS NOT NULL
151    AND site_id = '.$site_id;
152  if (isset($_POST['cat']) and is_numeric($_POST['cat']))
153  {
154    if (isset($_POST['subcats-included']) and $_POST['subcats-included'] == 1)
155    {
156      $query.= '
157    AND uppercats REGEXP \'(^|,)'.$_POST['cat'].'(,|$)\'
158';
159    }
160    else
161    {
162      $query.= '
163    AND id = '.$_POST['cat'].'
164';
165    }
166  }
167  $query.= '
168;';
169  $result = pwg_query($query);
170
171  $db_categories = array();
172  while ($row = mysql_fetch_array($result))
173  {
174    $db_categories[$row['id']] = $row;
175  }
176
177  // get categort full directories in an array for comparison with file
178  // system directory tree
179  $db_fulldirs = get_fulldirs(array_keys($db_categories));
180
181  // what is the base directory to search file system sub-directories ?
182  if (isset($_POST['cat']) and is_numeric($_POST['cat']))
183  {
184    $basedir = $db_fulldirs[$_POST['cat']];
185  }
186  else
187  {
188    $basedir = preg_replace('#/*$#', '', $site_url);
189  }
190
191  // we need to have fulldirs as keys to make efficient comparison
192  $db_fulldirs = array_flip($db_fulldirs);
193
194  // finding next rank for each id_uppercat. By default, each category id
195  // has 1 for next rank on its sub-categories to create
196  $next_rank['NULL'] = 1;
197
198  $query = '
199SELECT id
200  FROM '.CATEGORIES_TABLE.'
201;';
202  $result = pwg_query($query);
203  while ($row = mysql_fetch_array($result))
204  {
205    $next_rank[$row['id']] = 1;
206  }
207
208  // let's see if some categories already have some sub-categories...
209  $query = '
210SELECT id_uppercat, MAX(rank)+1 AS next_rank
211  FROM '.CATEGORIES_TABLE.'
212  GROUP BY id_uppercat
213;';
214  $result = pwg_query($query);
215  while ($row = mysql_fetch_array($result))
216  {
217    // for the id_uppercat NULL, we write 'NULL' and not the empty string
218    if (!isset($row['id_uppercat']) or $row['id_uppercat'] == '')
219    {
220      $row['id_uppercat'] = 'NULL';
221    }
222    $next_rank[$row['id_uppercat']] = $row['next_rank'];
223  }
224
225  // next category id available
226  $query = '
227SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_id
228  FROM '.CATEGORIES_TABLE.'
229;';
230  list($next_id) = mysql_fetch_array(pwg_query($query));
231
232  // retrieve sub-directories fulldirs from the site reader
233  $fs_fulldirs = $site_reader->get_full_directories($basedir);
234  //print_r( $fs_fulldirs ); echo "<br>";
235
236  // get_full_directories doesn't include the base directory, so if it's a
237  // category directory, we need to include it in our array
238  if (isset($_POST['cat']))
239  {
240    array_push($fs_fulldirs, $basedir);
241  }
242
243  // If $_POST['subcats-included'] != 1 ("Search in subcategories" is unchecked)
244  // $db_fulldirs doesn't include any subdirectories and $fs_fulldirs does
245  // So $fs_fulldirs will be limited to the selected basedir
246  // (if that one is in $fs_fulldirs)
247  if (!isset($_POST['subcats-included']) or $_POST['subcats-included'] != 1)
248  {
249    $fs_fulldirs = array_intersect($fs_fulldirs, array_keys($db_fulldirs));
250  }
251  // print_r( $fs_fulldirs ); echo "<br>";
252  // print_r( $db_fulldirs ); echo "<br>";
253  // print_r( array_diff($fs_fulldirs, array_keys($db_fulldirs)) ); echo "<br>";
254  // die('That\'s why dirs or files synchronizations were duplicating cats.');
255
256  $inserts = array();
257  // new categories are the directories not present yet in the database
258  foreach (array_diff($fs_fulldirs, array_keys($db_fulldirs)) as $fulldir)
259  {
260    $dir = basename($fulldir);
261    if (preg_match('/^[a-zA-Z0-9-_.]+$/', $dir))
262    {
263      $insert = array(
264        'id'          => $next_id++,
265        'dir'         => $dir,
266        'name'        => str_replace('_', ' ', $dir),
267        'site_id'     => $site_id,
268        'commentable' =>
269          boolean_to_string($conf['newcat_default_commentable']),
270        'uploadable'  => $site_is_remote
271          ? 'false'
272          : boolean_to_string($conf['newcat_default_uploadable']),
273        'status'      => $conf{'newcat_default_status'},
274        'visible'     => boolean_to_string($conf{'newcat_default_visible'}),
275        );
276
277      if (isset($db_fulldirs[dirname($fulldir)]))
278      {
279        $parent = $db_fulldirs[dirname($fulldir)];
280
281        $insert{'id_uppercat'} = $parent;
282        $insert{'uppercats'} =
283          $db_categories[$parent]['uppercats'].','.$insert{'id'};
284        $insert{'rank'} = $next_rank[$parent]++;
285        $insert{'global_rank'} =
286          $db_categories[$parent]['global_rank'].'.'.$insert{'rank'};
287        if ('private' == $db_categories[$parent]['status'])
288        {
289          $insert{'status'} = 'private';
290        }
291        if ('false' == $db_categories[$parent]['visible'])
292        {
293          $insert{'visible'} = 'false';
294        }
295      }
296      else
297      {
298        $insert{'uppercats'} = $insert{'id'};
299        $insert{'rank'} = $next_rank['NULL']++;
300        $insert{'global_rank'} = $insert{'rank'};
301      }
302
303      array_push($inserts, $insert);
304      array_push(
305        $infos,
306        array(
307          'path' => $fulldir,
308          'info' => l10n('update_research_added')
309          )
310        );
311
312      // add the new category to $db_categories and $db_fulldirs array
313      $db_categories[$insert{'id'}] =
314        array(
315          'id' => $insert{'id'},
316          'status' => $insert{'status'},
317          'visible' => $insert{'visible'},
318          'uppercats' => $insert{'uppercats'},
319          'global_rank' => $insert{'global_rank'}
320          );
321      $db_fulldirs[$fulldir] = $insert{'id'};
322      $next_rank[$insert{'id'}] = 1;
323    }
324    else
325    {
326      array_push(
327        $errors,
328        array(
329          'path' => $fulldir,
330          'type' => 'PWG-UPDATE-1'
331          )
332        );
333    }
334  }
335
336  if (count($inserts) > 0)
337  {
338    if (!$simulate)
339    {
340      $dbfields = array(
341        'id','dir','name','site_id','id_uppercat','uppercats','commentable',
342        'uploadable','visible','status','rank','global_rank'
343        );
344      mass_inserts(CATEGORIES_TABLE, $dbfields, $inserts);
345    }
346
347    $counts['new_categories'] = count($inserts);
348  }
349
350  // to delete categories
351  $to_delete = array();
352  foreach (array_diff(array_keys($db_fulldirs), $fs_fulldirs) as $fulldir)
353  {
354    array_push($to_delete, $db_fulldirs[$fulldir]);
355    unset($db_fulldirs[$fulldir]);
356    array_push($infos, array('path' => $fulldir,
357                             'info' => l10n('update_research_deleted')));
358  }
359  if (count($to_delete) > 0)
360  {
361    if (!$simulate)
362    {
363      delete_categories($to_delete);
364    }
365    $counts['del_categories'] = count($to_delete);
366  }
367
368  echo '<!-- scanning dirs : ';
369  echo get_elapsed_time($start, get_moment());
370  echo ' -->'."\n";
371}
372// +-----------------------------------------------------------------------+
373// |                           files / elements                            |
374// +-----------------------------------------------------------------------+
375if (isset($_POST['submit']) and $_POST['sync'] == 'files'
376      and !$general_failure)
377{
378  $start_files = get_moment();
379  $start= $start_files;
380
381  $fs = $site_reader->get_elements($basedir);
382  //print_r($fs); echo "<br>";
383  echo '<!-- get_elements: '.get_elapsed_time($start, get_moment())." -->\n";
384
385  $cat_ids = array_diff(array_keys($db_categories), $to_delete);
386
387  $db_elements = array();
388  $db_unvalidated = array();
389
390  if (count($cat_ids) > 0)
391  {
392    $query = '
393SELECT id, path
394  FROM '.IMAGES_TABLE.'
395  WHERE storage_category_id IN ('
396      .wordwrap(
397        implode(', ', $cat_ids),
398        80,
399        "\n"
400        ).')
401;';
402    $result = pwg_query($query);
403    while ($row = mysql_fetch_array($result))
404    {
405      $db_elements[$row['id']] = $row['path'];
406    }
407
408    // searching the unvalidated waiting elements (they must not be taken into
409    // account)
410    $query = '
411SELECT file,storage_category_id
412  FROM '.WAITING_TABLE.'
413  WHERE storage_category_id IN (
414'.wordwrap(implode(', ', $cat_ids), 80, "\n").')
415    AND validated = \'false\'
416;';
417    $result = pwg_query($query);
418    while ($row = mysql_fetch_array($result))
419    {
420      array_push(
421        $db_unvalidated,
422        array_search(
423          $row['storage_category_id'],
424          $db_fulldirs)
425        .'/'.$row['file']
426        );
427    }
428  }
429
430  // next element id available
431  $query = '
432SELECT IF(MAX(id)+1 IS NULL, 1, MAX(id)+1) AS next_element_id
433  FROM '.IMAGES_TABLE.'
434;';
435  list($next_element_id) = mysql_fetch_array(pwg_query($query));
436
437  $start = get_moment();
438
439  $inserts = array();
440  $insert_links = array();
441
442  foreach (array_diff(array_keys($fs), $db_elements, $db_unvalidated) as $path)
443  {
444    $insert = array();
445    // storage category must exist
446    $dirname = dirname($path);
447    if (!isset($db_fulldirs[$dirname]))
448    {
449      continue;
450    }
451    $filename = basename($path);
452    if (!preg_match('/^[a-zA-Z0-9-_.]+$/', $filename))
453    {
454      array_push(
455        $errors,
456        array(
457          'path' => $path,
458          'type' => 'PWG-UPDATE-1'
459          )
460        );
461
462      continue;
463    }
464
465    // 2 cases : the element is a picture or not. Indeed, for a picture
466    // thumbnail is mandatory and for non picture element, thumbnail and
467    // representative are optionnal
468    if ( isset( $conf['flip_picture_ext'][get_extension($filename)] ) )
469    {
470      // if we found a thumnbnail corresponding to our picture...
471      if (isset($fs[$path]['tn_ext']))
472      {
473        $insert = array(
474          'id'             => $next_element_id++,
475          'file'           => $filename,
476          'date_available' => CURRENT_DATE,
477          'tn_ext'         => $fs[$path]['tn_ext'],
478          'path'           => $path,
479          'storage_category_id' => $db_fulldirs[$dirname],
480          );
481
482        array_push(
483          $inserts,
484          $insert
485          );
486
487        array_push(
488          $insert_links,
489          array(
490            'image_id'    => $insert{'id'},
491            'category_id' => $insert['storage_category_id'],
492            )
493          );
494        array_push(
495          $infos,
496          array(
497            'path' => $insert{'path'},
498            'info' => l10n('update_research_added')
499            )
500          );
501
502        $caddiables[] = $insert['id'];
503      }
504      else
505      {
506        array_push(
507          $errors,
508          array(
509            'path' => $path,
510            'type' => 'PWG-UPDATE-2'
511            )
512          );
513      }
514    }
515    else
516    {
517      $insert = array(
518        'id'             => $next_element_id++,
519        'file'           => $filename,
520        'date_available' => CURRENT_DATE,
521        'path'           => $path,
522        'tn_ext'         => isset($fs[$path]['tn_ext'])
523          ? $fs[$path]['tn_ext']
524          : null,
525        'storage_category_id' => $db_fulldirs[$dirname],
526        );
527
528      array_push(
529        $inserts,
530        $insert
531        );
532
533      array_push(
534        $insert_links,
535        array(
536          'image_id'    => $insert{'id'},
537          'category_id' => $insert['storage_category_id'],
538          )
539        );
540
541      array_push(
542        $infos,
543        array(
544          'path' => $insert{'path'},
545          'info' => l10n('update_research_added')
546          )
547        );
548
549      $caddiables[] = $insert['id'];
550    }
551  }
552
553  if (count($inserts) > 0)
554  {
555    if (!$simulate)
556    {
557      // inserts all new elements
558      mass_inserts(
559        IMAGES_TABLE,
560        array_keys($inserts[0]),
561        $inserts
562        );
563
564      // inserts all links between new elements and their storage category
565      mass_inserts(
566        IMAGE_CATEGORY_TABLE,
567        array_keys($insert_links[0]),
568        $insert_links
569        );
570
571      // add new elements to caddie
572      if (isset($_POST['add_to_caddie']) and $_POST['add_to_caddie'] == 1)
573      {
574        fill_caddie($caddiables);
575      }
576    }
577    $counts['new_elements'] = count($inserts);
578  }
579
580  // delete elements that are in database but not in the filesystem
581  $to_delete_elements = array();
582  foreach (array_diff($db_elements, array_keys($fs)) as $path)
583  {
584    array_push($to_delete_elements, array_search($path, $db_elements));
585    array_push($infos, array('path' => $path,
586                             'info' => l10n('update_research_deleted')));
587  }
588  if (count($to_delete_elements) > 0)
589  {
590    if (!$simulate)
591    {
592      delete_elements($to_delete_elements);
593    }
594    $counts['del_elements'] = count($to_delete_elements);
595  }
596
597  echo '<!-- scanning files : ';
598  echo get_elapsed_time($start_files, get_moment());
599  echo ' -->'."\n";
600
601  // retrieving informations given by uploaders
602  if (!$simulate and count($cat_ids) > 0)
603  {
604    $query = '
605SELECT id,file,storage_category_id,infos
606  FROM '.WAITING_TABLE.'
607  WHERE storage_category_id IN (
608'.wordwrap(implode(', ', $cat_ids), 80, "\n").')
609    AND validated = \'true\'
610;';
611    $result = pwg_query($query);
612
613    $datas = array();
614    $fields =
615      array(
616        'primary' => array('id'),
617        'update'  => array('date_creation', 'author', 'name', 'comment')
618        );
619
620    $waiting_to_delete = array();
621
622    while ($row = mysql_fetch_array($result))
623    {
624      $data = array();
625
626      $query = '
627SELECT id
628  FROM '.IMAGES_TABLE.'
629  WHERE storage_category_id = '.$row['storage_category_id'].'
630    AND file = \''.$row['file'].'\'
631;';
632      list($data['id']) = mysql_fetch_array(pwg_query($query));
633
634      foreach ($fields['update'] as $field)
635      {
636        $data[$field] = addslashes( getAttribute($row['infos'], $field) );
637      }
638
639      array_push($datas, $data);
640      array_push($waiting_to_delete, $row['id']);
641    }
642
643    if (count($datas) > 0)
644    {
645      mass_updates(IMAGES_TABLE, $fields, $datas);
646
647      // delete now useless waiting elements
648      $query = '
649DELETE
650  FROM '.WAITING_TABLE.'
651  WHERE id IN ('.implode(',', $waiting_to_delete).')
652;';
653      pwg_query($query);
654    }
655  }
656}
657
658// +-----------------------------------------------------------------------+
659// |                          synchronize files                            |
660// +-----------------------------------------------------------------------+
661if (isset($_POST['submit'])
662    and ($_POST['sync'] == 'dirs' or $_POST['sync'] == 'files')
663    and !$general_failure )
664{
665  if (!$simulate)
666  {
667    $start = get_moment();
668    update_category('all');
669    echo '<!-- update_category(all) : ';
670    echo get_elapsed_time($start,get_moment());
671    echo ' -->'."\n";
672    $start = get_moment();
673    update_global_rank();
674    echo '<!-- ordering categories : ';
675    echo get_elapsed_time($start, get_moment());
676    echo ' -->'."\n";
677  }
678
679  if ($_POST['sync'] == 'files')
680  {
681    $start = get_moment();
682    $opts['category_id'] = '';
683    $opts['recursive'] = true;
684    if (isset($_POST['cat']))
685    {
686      $opts['category_id'] = $_POST['cat'];
687      if (!isset($_POST['subcats-included']) or $_POST['subcats-included'] != 1)
688      {
689        $opts['recursive'] = false;
690      }
691    }
692    $files = get_filelist($opts['category_id'], $site_id,
693                          $opts['recursive'],
694                          false);
695    echo '<!-- get_filelist : ';
696    echo get_elapsed_time($start, get_moment());
697    echo ' -->'."\n";
698    $start = get_moment();
699
700    $datas = array();
701    foreach ( $files as $id=>$file )
702    {
703      $data = $site_reader->get_element_update_attributes($file);
704      if ( !is_array($data) )
705      {
706        continue;
707      }
708      $extension = get_extension($file);
709      if ( isset($conf['flip_picture_ext'][$extension]) )
710      {
711        if ( !isset($data['tn_ext']) )
712        {
713          array_push(
714            $errors,
715            array(
716              'path' => $file,
717              'type' => 'PWG-UPDATE-2'
718              )
719            );
720          continue;
721        }
722      }
723
724      $data['id']=$id;
725      array_push($datas, $data);
726    } // end foreach file
727
728    $counts['upd_elements'] = count($datas);
729    if (!$simulate and count($datas)>0 )
730    {
731      mass_updates(
732        IMAGES_TABLE,
733        // fields
734        array(
735          'primary' => array('id'),
736          'update'  => $site_reader->get_update_attributes(),
737          ),
738        $datas
739        );
740    }
741    echo '<!-- update files : ';
742    echo get_elapsed_time($start,get_moment());
743    echo ' -->'."\n";
744  }// end if sync files
745}
746
747// +-----------------------------------------------------------------------+
748// |                          synchronize files                            |
749// +-----------------------------------------------------------------------+
750if (isset($_POST['submit'])
751    and ($_POST['sync'] == 'dirs' or $_POST['sync'] == 'files'))
752{
753  $template->assign_block_vars(
754    'update_result',
755    array(
756      'NB_NEW_CATEGORIES'=>$counts['new_categories'],
757      'NB_DEL_CATEGORIES'=>$counts['del_categories'],
758      'NB_NEW_ELEMENTS'=>$counts['new_elements'],
759      'NB_DEL_ELEMENTS'=>$counts['del_elements'],
760      'NB_UPD_ELEMENTS'=>$counts['upd_elements'],
761      'NB_ERRORS'=>count($errors),
762      ));
763}
764
765// +-----------------------------------------------------------------------+
766// |                          synchronize metadata                         |
767// +-----------------------------------------------------------------------+
768if (isset($_POST['submit']) and preg_match('/^metadata/', $_POST['sync'])
769         and !$general_failure)
770{
771  // sync only never synchronized files ?
772  if ($_POST['sync'] == 'metadata_new')
773  {
774    $opts['only_new'] = true;
775  }
776  else
777  {
778    $opts['only_new'] = false;
779  }
780  $opts['category_id'] = '';
781  $opts['recursive'] = true;
782
783  if (isset($_POST['cat']))
784  {
785    $opts['category_id'] = $_POST['cat'];
786    // recursive ?
787    if (!isset($_POST['subcats-included']) or $_POST['subcats-included'] != 1)
788    {
789      $opts['recursive'] = false;
790    }
791  }
792  $start = get_moment();
793  $files = get_filelist($opts['category_id'], $site_id,
794                        $opts['recursive'],
795                        $opts['only_new']);
796
797  echo '<!-- get_filelist : ';
798  echo get_elapsed_time($start, get_moment());
799  echo ' -->'."\n";
800
801  $start = get_moment();
802  $datas = array();
803  $tags_of = array();
804
805  $has_high_images = array();
806
807  $image_ids = array();
808  foreach ($files as $id => $file)
809  {
810    array_push($image_ids, $id);
811  }
812
813  if (count($image_ids) > 0)
814  {
815    $query = '
816SELECT id
817  FROM '.IMAGES_TABLE.'
818  WHERE has_high = \'true\'
819    AND id IN (
820'.wordwrap(implode(', ', $image_ids), 80, "\n").'
821)
822;';
823
824    $result = pwg_query($query);
825    while ($row = mysql_fetch_array($result))
826    {
827      array_push($has_high_images, $row['id']);
828    }
829  }
830
831  foreach ( $files as $id=>$file )
832  {
833    $data = $site_reader->get_element_metadata(
834      $file,
835      in_array($id, $has_high_images)
836      );
837
838    if ( is_array($data) )
839    {
840      $data['date_metadata_update'] = CURRENT_DATE;
841      $data['id']=$id;
842      array_push($datas, $data);
843
844      foreach (array('keywords', 'tags') as $key)
845      {
846        if (isset($data[$key]))
847        {
848          if (!isset($tags_of[$id]))
849          {
850            $tags_of[$id] = array();
851          }
852
853          foreach (explode(',', $data[$key]) as $tag_name)
854          {
855            array_push(
856              $tags_of[$id],
857              tag_id_from_tag_name($tag_name)
858              );
859          }
860        }
861      }
862    }
863    else
864    {
865      array_push($errors, array('path' => $file, 'type' => 'PWG-ERROR-NO-FS'));
866    }
867  }
868
869  if (!$simulate)
870  {
871    if (count($datas) > 0)
872    {
873      // echo '<pre>', print_r($datas); echo '</pre>';
874
875      mass_updates(
876        IMAGES_TABLE,
877        // fields
878        array(
879          'primary' => array('id'),
880          'update'  => array_unique(
881            array_merge(
882              array_diff(
883                $site_reader->get_metadata_attributes(),
884                // keywords and tags fields are managed separately
885                array('keywords', 'tags')
886                ),
887              array('date_metadata_update'))
888            )
889          ),
890        $datas
891        );
892    }
893    set_tags_of($tags_of);
894  }
895
896  echo '<!-- metadata update : ';
897  echo get_elapsed_time($start, get_moment());
898  echo ' -->'."\n";
899
900  $template->assign_block_vars(
901    'metadata_result',
902    array(
903      'NB_ELEMENTS_DONE' => count($datas),
904      'NB_ELEMENTS_CANDIDATES' => count($files),
905      'NB_ERRORS' => count($errors),
906      ));
907}
908
909// +-----------------------------------------------------------------------+
910// |                        template initialization                        |
911// +-----------------------------------------------------------------------+
912$template->set_filenames(array('update'=>'admin/site_update.tpl'));
913$result_title = '';
914if (isset($simulate) and $simulate)
915{
916  $result_title.= l10n('update_simulation_title').' ';
917}
918
919// used_metadata string is displayed to inform admin which metadata will be
920// used from files for synchronization
921$used_metadata = implode( ', ', $site_reader->get_metadata_attributes());
922if ($site_is_remote and !isset($_POST['submit']) )
923{
924  $used_metadata.= ' + ...';
925}
926
927$template->assign_vars(
928  array(
929    'SITE_URL'=>$site_url,
930    'U_SITE_MANAGER'=> PHPWG_ROOT_PATH.'admin.php?page=site_manager',
931    'L_RESULT_UPDATE'=>$result_title.l10n('update_part_research'),
932    'L_RESULT_METADATA'=>$result_title.l10n('update_result_metadata'),
933    'METADATA_LIST' => $used_metadata
934    ));
935
936$template->assign_vars(
937  array(
938    'U_HELP' => PHPWG_ROOT_PATH.'popuphelp.php?page=synchronize'
939    )
940  );
941// +-----------------------------------------------------------------------+
942// |                        introduction : choices                         |
943// +-----------------------------------------------------------------------+
944if (!isset($_POST['submit']) or (isset($simulate) and $simulate))
945{
946  $template->assign_block_vars('introduction', array());
947
948  if (isset($simulate) and $simulate)
949  {
950    switch ($_POST['sync'])
951    {
952      case 'dirs' :
953      {
954        $template->assign_vars(
955          array('SYNC_DIRS_CHECKED'=>'checked="checked"'));
956        break;
957      }
958      case 'files' :
959      {
960        $template->assign_vars(
961          array('SYNC_ALL_CHECKED'=>'checked="checked"'));
962        break;
963      }
964      case 'metadata_new' :
965      {
966        $template->assign_vars(
967          array('SYNC_META_NEW_CHECKED'=>'checked="checked"'));
968        break;
969      }
970      case 'metadata_all' :
971      {
972        $template->assign_vars(
973          array('SYNC_META_ALL_CHECKED'=>'checked="checked"'));
974        break;
975      }
976    }
977
978    if (isset($_POST['display_info']) and $_POST['display_info'] == 1)
979    {
980      $template->assign_vars(
981        array('DISPLAY_INFO_CHECKED'=>'checked="checked"'));
982    }
983
984    if (isset($_POST['add_to_caddie']) and $_POST['add_to_caddie'] == 1)
985    {
986      $template->assign_vars(
987        array('ADD_TO_CADDIE_CHECKED'=>'checked="checked"'));
988    }
989
990    if (isset($_POST['subcats-included']) and $_POST['subcats-included'] == 1)
991    {
992      $template->assign_vars(
993        array('SUBCATS_INCLUDED_CHECKED'=>'checked="checked"'));
994    }
995
996    if (isset($_POST['cat']) and is_numeric($_POST['cat']))
997    {
998      $cat_selected = array($_POST['cat']);
999    }
1000    else
1001    {
1002      $cat_selected = array();
1003    }
1004  }
1005  else
1006  {
1007    $template->assign_vars(
1008      array('SYNC_DIRS_CHECKED' => 'checked="checked"',
1009            'SUBCATS_INCLUDED_CHECKED'=>'checked="checked"'));
1010
1011    $cat_selected = array();
1012  }
1013
1014  $query = '
1015SELECT id,name,uppercats,global_rank
1016  FROM '.CATEGORIES_TABLE.'
1017  WHERE site_id = '.$site_id.'
1018;';
1019  display_select_cat_wrapper($query,
1020                             $cat_selected,
1021                             'introduction.category_option',
1022                             false);
1023}
1024
1025if (count($errors) > 0)
1026{
1027  $template->assign_block_vars('sync_errors', array());
1028  foreach ($errors as $error)
1029  {
1030    $template->assign_block_vars(
1031      'sync_errors.error',
1032      array(
1033        'ELEMENT' => $error['path'],
1034        'LABEL' => $error['type'].' ('.$error_labels[$error['type']][0].')'
1035        ));
1036  }
1037
1038  foreach ($error_labels as $error_type=>$error_description)
1039  {
1040    $template->assign_block_vars(
1041      'sync_errors.error_caption',
1042      array(
1043        'TYPE' => $error_type,
1044        'LABEL' => $error_description[1]
1045        ));
1046  }
1047
1048}
1049if (count($infos) > 0
1050    and isset($_POST['display_info'])
1051    and $_POST['display_info'] == 1)
1052{
1053  $template->assign_block_vars('sync_infos', array());
1054  foreach ($infos as $info)
1055  {
1056    $template->assign_block_vars(
1057      'sync_infos.info',
1058      array(
1059        'ELEMENT' => $info['path'],
1060        'LABEL' => $info['info']
1061        ));
1062  }
1063}
1064
1065// +-----------------------------------------------------------------------+
1066// |                          sending html code                            |
1067// +-----------------------------------------------------------------------+
1068$template->assign_var_from_handle('ADMIN_CONTENT', 'update');
1069?>
Note: See TracBrowser for help on using the repository browser.