source: trunk/admin/remote_site.php @ 600

Last change on this file since 600 was 593, checked in by z0rglub, 20 years ago

update headers to comply with GPL

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