source: trunk/admin/remote_site.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: 20.0 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 * requests the given $url (a remote create_listing_file.php) and fills a
41 * list of lines corresponding to request output
42 *
43 * @param string $url
44 * @return void
45 */
46function remote_output($url)
47{
48  global $template, $errors, $lang;
49 
50  if($lines = @file($url))
51  {
52    $template->assign_block_vars('remote_output', array());
53    // cleaning lines from HTML tags
54    foreach ($lines as $line)
55    {
56      $line = trim(strip_tags($line));
57      if (preg_match('/^PWG-([A-Z]+)-/', $line, $matches))
58      {
59        $template->assign_block_vars(
60          'remote_output.remote_line',
61          array(
62            'CLASS' => 'remote'.ucfirst(strtolower($matches[1])),
63            'CONTENT' => $line
64           )
65         );
66      }
67    }
68  }
69  else
70  {
71    array_push($errors, $lang['remote_site_file_not_found']);
72  }
73}
74
75/**
76 * returns an array where are linked the sub-categories id and there
77 * directories corresponding to the given uppercat id
78 *
79 * @param int site_id
80 * @param mixed id_uppercat
81 * @return array
82 */
83function database_subdirs($site_id, $id_uppercat)
84{
85  $database_dirs = array();
86 
87  $query = '
88SELECT id,dir
89  FROM '.CATEGORIES_TABLE.'
90  WHERE site_id = '.$site_id;
91  if (!is_numeric($id_uppercat))
92  {
93    $query.= '
94    AND id_uppercat IS NULL';
95  }
96  else
97  {
98    $query.= '
99    AND id_uppercat = '.$id_uppercat;
100  }
101  // virtual categories not taken
102  $query.= '
103    AND dir IS NOT NULL
104;';
105  $result = pwg_query($query);
106  while ($row = mysql_fetch_array($result))
107  {
108    $database_dirs[$row['id']] = $row['dir'];
109  }
110
111  return $database_dirs;
112}
113
114/**
115 * read $listing_file and update a remote site according to its id
116 *
117 * @param string listing_file
118 * @param int site_id
119 * @return void
120 */
121function update_remote_site($listing_file, $site_id)
122{
123  global $lang, $counts, $template, $removes, $errors;
124 
125  if (@fopen($listing_file, 'r'))
126  {
127    $counts = array(
128      'new_elements' => 0,
129      'new_categories' => 0,
130      'del_elements' => 0,
131      'del_categories' => 0
132      );
133    $removes = array();
134       
135    $xml_content = getXmlCode($listing_file);
136    insert_remote_category($xml_content, $site_id, 'NULL', 0);
137    update_category();
138       
139    $template->assign_block_vars(
140      'update',
141      array(
142        'NB_NEW_CATEGORIES'=>$counts['new_categories'],
143        'NB_DEL_CATEGORIES'=>$counts['del_categories'],
144        'NB_NEW_ELEMENTS'=>$counts['new_elements'],
145        'NB_DEL_ELEMENTS'=>$counts['del_elements']
146        ));
147       
148    if (count($removes) > 0)
149    {
150      $template->assign_block_vars('update.removes', array());
151    }
152    foreach ($removes as $remove)
153    {
154      $template->assign_block_vars('update.removes.remote_remove',
155                                   array('NAME'=>$remove));
156    }
157  }
158  else
159  {
160    array_push($errors, $lang['remote_site_listing_not_found']);
161  }
162}
163
164/**
165 * searchs the "dir" node of the xml_dir given and insert the contained
166 * categories if the are not in the database yet. The function also deletes
167 * the categories that are in the database and not in the xml_file.
168 *
169 * @param string xml_content
170 * @param int site_id
171 * @param mixed id_uppercat
172 * @param int level
173 * @return void
174 */
175function insert_remote_category($xml_content, $site_id, $id_uppercat, $level)
176{
177  global $counts, $removes;
178 
179  $uppercats = '';
180  // 0. retrieving informations on the category to display
181               
182  if (is_numeric($id_uppercat))
183  {
184    $query = '
185SELECT name,uppercats,dir
186  FROM '.CATEGORIES_TABLE.'
187  WHERE id = '.$id_uppercat.'
188;';
189    $row = mysql_fetch_array(pwg_query($query));
190   
191    $uppercats = $row['uppercats'];
192    $name = $row['name'];
193
194    insert_remote_element($xml_content, $id_uppercat);
195  }
196
197  // $xml_dirs contains dir names contained in the xml file for this
198  // id_uppercat
199  $xml_dirs = array();
200  $temp_dirs = getChildren($xml_content, 'dir'.$level);
201  foreach ($temp_dirs as $temp_dir)
202  {
203    array_push($xml_dirs, getAttribute($temp_dir, 'name'));
204  }
205
206  // $database_dirs contains dir names contained in the database for this
207  // id_uppercat and site_id
208  $database_dirs = database_subdirs($site_id, $id_uppercat);
209 
210  // 3. we have to remove the categories of the database not present anymore
211  $to_delete = array();
212  foreach ($database_dirs as $id => $dir)
213  {
214    if (!in_array($dir, $xml_dirs))
215    {
216      array_push($to_delete, $id);
217      array_push($removes, get_complete_dir($id));
218    }
219  }
220  delete_categories($to_delete);
221
222  // array of new categories to insert
223  $inserts = array();
224 
225  foreach ($xml_dirs as $xml_dir)
226  {
227    // 5. Is the category already existing ? we create a subcat if not
228    //    existing
229    $category_id = array_search($xml_dir, $database_dirs);
230    if (!is_numeric($category_id))
231    {
232      $name = str_replace('_', ' ', $xml_dir);
233
234      $insert = array();
235
236      $insert{'dir'} = $xml_dir;
237      $insert{'name'} = $name;
238      $insert{'site_id'} = $site_id;
239      $insert{'uppercats'} = 'undef';
240      if (is_numeric($id_uppercat))
241      {
242        $insert{'id_uppercat'} = $id_uppercat;
243      }
244      array_push($inserts, $insert);
245    }
246  }
247
248  // we have to create the category
249  if (count($inserts) > 0)
250  {
251    // inserts all found categories
252    $dbfields = array('dir','name','site_id','uppercats','id_uppercat');
253    mass_inserts(CATEGORIES_TABLE, $dbfields, $inserts);
254    $counts{'new_categories'}+= count($inserts);
255   
256    // updating uppercats field
257    $query = '
258UPDATE '.CATEGORIES_TABLE.'
259  SET uppercats = ';
260    if ($uppercats != '')
261    {
262      $query.= "CONCAT('".$uppercats."',',',id)";
263    }
264    else
265    {
266      $query.= 'id';
267    }
268    $query.= '
269  WHERE id_uppercat ';
270    if (!is_numeric($id_uppercat))
271    {
272      $query.= 'IS NULL';
273    }
274    else
275    {
276      $query.= '= '.$id_uppercat;
277    }
278    $query.= '
279;';
280    pwg_query($query);
281  }
282
283  // Recursive call on the sub-categories (not virtual ones)
284  $database_dirs = database_subdirs($site_id, $id_uppercat);
285 
286  foreach ($temp_dirs as $temp_dir)
287  {
288    $dir = getAttribute($temp_dir, 'name');
289    $id_uppercat = array_search($dir, $database_dirs);
290    insert_remote_category($temp_dir, $site_id, $id_uppercat, $level+1);
291  }
292}
293
294/**
295 * searchs the "root" node of $xml_dir (xml string), inserts elements in the
296 * database if new
297 *
298 * @param string xml_dir
299 * @param int category_id
300 * @return void
301 */
302function insert_remote_element($xml_dir, $category_id)
303{
304  global $counts, $lang, $removes;
305
306  $output = '';
307  $root = getChild($xml_dir, 'root');
308
309  $xml_files = array();
310  $xml_elements = getChildren($root, 'element');
311  foreach ($xml_elements as $xml_element)
312  {
313    array_push($xml_files, getAttribute($xml_element,'file'));
314  }
315 
316  // we have to delete all the images from the database that are not in the
317  // directory anymore (not in the XML anymore)
318  $query = '
319SELECT id,file
320  FROM '.IMAGES_TABLE.'
321  WHERE storage_category_id = '.$category_id.'
322;';
323  $result = pwg_query($query);
324  $to_delete = array();
325  while ($row = mysql_fetch_array($result))
326  {
327    if (!in_array($row['file'], $xml_files))
328    {
329      // local_dir is cached
330      if (!isset($local_dir))
331      {
332        $local_dir = get_local_dir($category_id);
333      }
334      array_push($removes, $local_dir.$row['file']);
335      array_push($to_delete, $row['id']);
336    }
337  }
338  delete_elements($to_delete);
339
340  $database_elements = array();
341  $query = '
342SELECT file
343  FROM '.IMAGES_TABLE.'
344  WHERE storage_category_id = '.$category_id.'
345;';
346  $result = pwg_query($query);
347  while ($row = mysql_fetch_array($result))
348  {
349    array_push($database_elements, $row['file']);
350  }
351
352  $inserts = array();
353  foreach ($xml_elements as $xml_element)
354  {
355    // minimal tag : <element file="albatros.jpg"/>
356    $file = getAttribute($xml_element, 'file');
357
358    // is the picture already existing in the database ?
359    if (!in_array($file, $database_elements))
360    {
361      $insert = array();
362      $insert{'file'} = $file;
363      $insert{'storage_category_id'} = $category_id;
364      $insert{'date_available'} = CURRENT_DATE;
365      $optional_atts = array('tn_ext',
366                             'representative_ext',
367                             'filesize',
368                             'width',
369                             'height',
370                             'date_creation',
371                             'author',
372                             'keywords',
373                             'name',
374                             'comment',
375                             'path');
376      foreach ($optional_atts as $att)
377      {
378        if (getAttribute($xml_element, $att) != '')
379        {
380          $insert{$att} = getAttribute($xml_element, $att);
381        }
382      }
383      array_push($inserts, $insert);
384    }
385  }
386
387  if (count($inserts) > 0)
388  {
389    $dbfields = array('file','storage_category_id','date_available','tn_ext',
390                      'filesize','width','height','date_creation','author',
391                      'keywords','name','comment','path');
392    mass_inserts(IMAGES_TABLE, $dbfields, $inserts);
393    $counts{'new_elements'}+= count($inserts);
394
395    // what are the ids of the pictures in the $category_id ?
396    $ids = array();
397
398    $query = '
399SELECT id
400  FROM '.IMAGES_TABLE.'
401  WHERE storage_category_id = '.$category_id.'
402;';
403    $result = pwg_query($query);
404    while ($row = mysql_fetch_array($result))
405    {
406      array_push($ids, $row['id']);
407    }
408
409    // recreation of the links between this storage category pictures and
410    // its storage category
411    $query = '
412DELETE FROM '.IMAGE_CATEGORY_TABLE.'
413  WHERE category_id = '.$category_id.'
414    AND image_id IN ('.implode(',', $ids).')
415;';
416    pwg_query($query);
417
418    $query = '
419INSERT INTO '.IMAGE_CATEGORY_TABLE.'
420  (category_id,image_id)
421  VALUES';
422    foreach ($ids as $num => $image_id)
423    {
424      $query.= '
425  ';
426      if ($num > 0)
427      {
428        $query.= ',';
429      }
430      $query.= '('.$category_id.','.$image_id.')';
431    }
432    $query.= '
433;';
434    pwg_query($query);
435  }
436}
437// +-----------------------------------------------------------------------+
438// |                             template init                             |
439// +-----------------------------------------------------------------------+
440$template->set_filenames(array('remote_site'=>'admin/remote_site.tpl'));
441
442$template->assign_vars(
443  array(
444    'L_SUBMIT'=>$lang['submit'],
445    'L_REMOTE_SITE_CREATE'=>$lang['remote_site_create'],
446    'L_REMOTE_SITE_GENERATE'=>$lang['remote_site_generate'],
447    'L_REMOTE_SITE_GENERATE_HINT'=>$lang['remote_site_generate_hint'],
448    'L_REMOTE_SITE_UPDATE'=>$lang['remote_site_update'],
449    'L_REMOTE_SITE_UPDATE_HINT'=>$lang['remote_site_update_hint'],
450    'L_REMOTE_SITE_CLEAN'=>$lang['remote_site_clean'],
451    'L_REMOTE_SITE_CLEAN_HINT'=>$lang['remote_site_clean_hint'],
452    'L_REMOTE_SITE_DELETE'=>$lang['remote_site_delete'],
453    'L_REMOTE_SITE_DELETE_HINT'=>$lang['remote_site_delete_hint'],
454    'L_NB_NEW_ELEMENTS'=>$lang['update_nb_new_elements'],
455    'L_NB_NEW_CATEGORIES'=>$lang['update_nb_new_categories'],
456    'L_NB_DEL_ELEMENTS'=>$lang['update_nb_del_elements'],
457    'L_NB_DEL_CATEGORIES'=>$lang['update_nb_del_categories'],
458    'L_REMOTE_SITE_REMOVED_TITLE'=>$lang['remote_site_removed_title'],
459    'L_REMOTE_SITE_REMOVED'=>$lang['remote_site_removed'],
460    'L_REMOTE_SITE_LOCAL_FOUND'=>$lang['remote_site_local_found'],
461    'L_REMOTE_SITE_LOCAL_NEW'=>$lang['remote_site_local_new'],
462    'L_REMOTE_SITE_LOCAL_UPDATE'=>$lang['remote_site_local_update'],
463   
464    'F_ACTION'=>add_session_id(PHPWG_ROOT_PATH.'admin.php?page=remote_site')
465   )
466 );
467// +-----------------------------------------------------------------------+
468// |                        new site creation form                         |
469// +-----------------------------------------------------------------------+
470$errors = array();
471
472if (isset($_POST['submit']))
473{
474  // site must start by http:// or https://
475  if (!preg_match('/^https?:\/\/[~\/\.\w-]+$/', $_POST['galleries_url']))
476  {
477    array_push($errors, $lang['remote_site_uncorrect_url']);
478  }
479  else
480  {
481    $page['galleries_url'] = preg_replace('/[\/]*$/',
482                                          '',
483                                          $_POST['galleries_url']);
484    $page['galleries_url'].= '/';
485    // site must not exists
486    $query = '
487SELECT COUNT(id) AS count
488  FROM '.SITES_TABLE.'
489  WHERE galleries_url = \''.$page['galleries_url'].'\'
490;';
491    $row = mysql_fetch_array(pwg_query($query));
492    if ($row['count'] > 0)
493    {
494      array_push($errors, $lang['remote_site_already_exists']);
495    }
496  }
497
498  if (count($errors) == 0)
499  {
500    $url = $page['galleries_url'].'create_listing_file.php';
501    $url.= '?action=test';
502    $url.= '&version='.PHPWG_VERSION;
503    if ($lines = @file($url))
504    {
505      $first_line = strip_tags($lines[0]);
506      if (!preg_match('/^PWG-INFO-2:/', $first_line))
507      {
508        array_push($errors, $lang['remote_site_error'].' : '.$first_line);
509      }
510    }
511    else
512    {
513      array_push($errors, $lang['remote_site_file_not_found']);
514    }
515  }
516 
517  if (count($errors) == 0)
518  {
519    $query = '
520INSERT INTO '.SITES_TABLE.'
521  (galleries_url)
522  VALUES
523  (\''.$page['galleries_url'].'\')
524;';
525    pwg_query($query);
526
527    $template->assign_block_vars(
528      'confirmation',
529      array(
530        'CONTENT'=>$page['galleries_url'].' '.$lang['remote_site_created']
531        ));
532  }
533}
534// +-----------------------------------------------------------------------+
535// |                            actions on site                            |
536// +-----------------------------------------------------------------------+
537if (isset($_GET['site']) and is_numeric($_GET['site']))
538{
539  $page['site'] = $_GET['site'];
540}
541
542if (isset($_GET['action']))
543{
544  if (isset($page['site']))
545  {
546    $query = '
547SELECT galleries_url
548  FROM '.SITES_TABLE.'
549  WHERE id = '.$page['site'].'
550;';
551    list($galleries_url) = mysql_fetch_array(pwg_query($query));
552  }
553
554  switch($_GET['action'])
555  {
556    case 'delete' :
557    {
558      delete_site($page['site']);
559
560      $template->assign_block_vars(
561        'confirmation',
562        array(
563          'CONTENT'=>$galleries_url.' '.$lang['remote_site_deleted']
564          ));
565     
566      break;
567    }
568    case 'generate' :
569    {
570      $title = $galleries_url.' : '.$lang['remote_site_generate'];
571      $template->assign_vars(array('REMOTE_SITE_TITLE'=>$title));
572      remote_output($galleries_url.'create_listing_file.php?action=generate');
573      break;
574    }
575    case 'update' :
576    {
577      $title = $galleries_url.' : '.$lang['remote_site_update'];
578      $template->assign_vars(array('REMOTE_SITE_TITLE'=>$title));
579      update_remote_site($galleries_url.'listing.xml', $page['site']);
580      break;
581    }
582    case 'clean' :
583    {
584      $title = $galleries_url.' : '.$lang['remote_site_clean'];
585      $template->assign_vars(array('REMOTE_SITE_TITLE'=>$title));
586      remote_output($galleries_url.'create_listing_file.php?action=clean');
587      break;
588    }
589    case 'local_update' :
590    {
591      $local_listing = PHPWG_ROOT_PATH.'listing.xml';
592      $xml_content = getXmlCode($local_listing);
593      $url = getAttribute(getChild($xml_content, 'informations'), 'url');
594
595      // is the site already existing ?
596      $query = '
597SELECT id
598  FROM '.SITES_TABLE.'
599  WHERE galleries_url = \''.addslashes($url).'\'
600;';
601      $result = pwg_query($query);
602      if (mysql_num_rows($result) == 0)
603      {
604        // we have to register this site in the database
605        $query = '
606INSERT INTO '.SITES_TABLE.'
607  (galleries_url)
608  VALUES
609  (\''.$url.'\')
610;';
611        pwg_query($query);
612        $site_id = mysql_insert_id();
613      }
614      else
615      {
616        // we get the already registered id
617        $row = mysql_fetch_array($result);
618        $site_id = $row['id'];
619      }
620     
621      $title = $url.' : '.$lang['remote_site_local_update'];
622      $template->assign_vars(array('REMOTE_SITE_TITLE'=>$title));
623      update_remote_site($local_listing, $site_id);
624      break;
625    }
626  }
627}
628else
629{
630  // we search a "local" listing.xml file
631  $local_listing = PHPWG_ROOT_PATH.'listing.xml';
632  if (is_file($local_listing))
633  {
634    $xml_content = getXmlCode($local_listing);
635    $url = getAttribute(getChild($xml_content, 'informations'), 'url');
636
637    $base_url = PHPWG_ROOT_PATH.'admin.php?page=remote_site&amp;action=';
638   
639    $template->assign_block_vars(
640      'local',
641      array(
642        'URL' => $url,
643        'U_UPDATE' => add_session_id($base_url.'local_update')
644        )
645      );
646
647    // is the site already existing ?
648    $query = '
649SELECT COUNT(*)
650  FROM '.SITES_TABLE.'
651  WHERE galleries_url = \''.addslashes($url).'\'
652;';
653    list($count) = mysql_fetch_array(pwg_query($query));
654    if ($count == 0)
655    {
656      $template->assign_block_vars('local.new_site', array());
657    }
658  }
659}
660// +-----------------------------------------------------------------------+
661// |                           remote sites list                           |
662// +-----------------------------------------------------------------------+
663
664// site 1 is the local site, should not be taken into account
665$query = '
666SELECT id, galleries_url
667  FROM '.SITES_TABLE.'
668  WHERE id != 1
669;';
670$result = pwg_query($query);
671while ($row = mysql_fetch_array($result))
672{
673  $base_url = PHPWG_ROOT_PATH.'admin.php';
674  $base_url.= '?page=remote_site';
675  $base_url.= '&amp;site='.$row['id'];
676  $base_url.= '&amp;action=';
677 
678  $template->assign_block_vars(
679    'site',
680    array(
681      'NAME' => $row['galleries_url'],
682      'U_GENERATE' => add_session_id($base_url.'generate'),
683      'U_UPDATE' => add_session_id($base_url.'update'),
684      'U_CLEAN' => add_session_id($base_url.'clean'),
685      'U_DELETE' => add_session_id($base_url.'delete')
686     )
687   );
688}
689// +-----------------------------------------------------------------------+
690// |                             errors display                            |
691// +-----------------------------------------------------------------------+
692if (count($errors) != 0)
693{
694  $template->assign_block_vars('errors',array());
695  foreach ($errors as $error)
696  {
697    $template->assign_block_vars('errors.error',array('ERROR'=>$error));
698  }
699}
700// +-----------------------------------------------------------------------+
701// |                           sending html code                           |
702// +-----------------------------------------------------------------------+
703$template->assign_var_from_handle('ADMIN_CONTENT', 'remote_site');
704?>
Note: See TracBrowser for help on using the repository browser.