source: trunk/admin/remote_site.php @ 534

Last change on this file since 534 was 534, checked in by z0rglub, 20 years ago
  • (re)added feature : in remote site management, if a listing.xml file is found at PhpWebGallery root directory, it can be used to update a remote site
  • size and maxlength of prefix_thumbnail in admin/configuration are 10
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 20.6 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// |                           remote_site.php                             |
4// +-----------------------------------------------------------------------+
5// | application   : PhpWebGallery <http://phpwebgallery.net>              |
6// | branch        : BSF (Best So Far)                                     |
7// +-----------------------------------------------------------------------+
8// | file          : $RCSfile$
9// | last update   : $Date: 2004-09-23 23:41:23 +0000 (Thu, 23 Sep 2004) $
10// | last modifier : $Author: z0rglub $
11// | revision      : $Revision: 534 $
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 = mysql_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  mysql_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(mysql_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    mysql_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 = mysql_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 = mysql_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      foreach ($optional_atts as $att)
418      {
419        if (getAttribute($xml_element, $att) != '')
420        {
421          $insert{$att} = getAttribute($xml_element, $att);
422        }
423      }
424      array_push($inserts, $insert);
425    }
426  }
427
428  if (count($inserts) > 0)
429  {
430    $dbfields = array('file','storage_category_id','date_available','tn_ext',
431                      'filesize','width','height');
432    mass_inserts(IMAGES_TABLE, $dbfields, $inserts);
433    $counts{'new_elements'}+= count($inserts);
434
435    // what are the ids of the pictures in the $category_id ?
436    $ids = array();
437
438    $query = '
439SELECT id
440  FROM '.IMAGES_TABLE.'
441  WHERE storage_category_id = '.$category_id.'
442;';
443    $result = mysql_query($query);
444    while ($row = mysql_fetch_array($result))
445    {
446      array_push($ids, $row['id']);
447    }
448
449    // recreation of the links between this storage category pictures and
450    // its storage category
451    $query = '
452DELETE FROM '.IMAGE_CATEGORY_TABLE.'
453  WHERE category_id = '.$category_id.'
454    AND image_id IN ('.implode(',', $ids).')
455;';
456    mysql_query($query);
457
458    $query = '
459INSERT INTO '.IMAGE_CATEGORY_TABLE.'
460  (category_id,image_id)
461  VALUES';
462    foreach ($ids as $num => $image_id)
463    {
464      $query.= '
465  ';
466      if ($num > 0)
467      {
468        $query.= ',';
469      }
470      $query.= '('.$category_id.','.$image_id.')';
471    }
472    $query.= '
473;';
474    mysql_query($query);
475  }
476}
477// +-----------------------------------------------------------------------+
478// |                             template init                             |
479// +-----------------------------------------------------------------------+
480$template->set_filenames(array('remote_site'=>'admin/remote_site.tpl'));
481
482$action = PHPWG_ROOT_PATH.'admin.php?page=remote_site';
483
484$template->assign_vars(
485  array(
486    'L_SUBMIT'=>$lang['submit'],
487    'L_REMOTE_SITE_CREATE'=>$lang['remote_site_create'],
488    'L_REMOTE_SITE_GENERATE'=>$lang['remote_site_generate'],
489    'L_REMOTE_SITE_GENERATE_HINT'=>$lang['remote_site_generate_hint'],
490    'L_REMOTE_SITE_UPDATE'=>$lang['remote_site_update'],
491    'L_REMOTE_SITE_UPDATE_HINT'=>$lang['remote_site_update_hint'],
492    'L_REMOTE_SITE_CLEAN'=>$lang['remote_site_clean'],
493    'L_REMOTE_SITE_CLEAN_HINT'=>$lang['remote_site_clean_hint'],
494    'L_REMOTE_SITE_DELETE'=>$lang['remote_site_delete'],
495    'L_REMOTE_SITE_DELETE_HINT'=>$lang['remote_site_delete_hint'],
496    'L_NB_NEW_ELEMENTS'=>$lang['update_nb_new_elements'],
497    'L_NB_NEW_CATEGORIES'=>$lang['update_nb_new_categories'],
498    'L_NB_DEL_ELEMENTS'=>$lang['update_nb_del_elements'],
499    'L_NB_DEL_CATEGORIES'=>$lang['update_nb_del_categories'],
500    'L_REMOTE_SITE_REMOVED_TITLE'=>$lang['remote_site_removed_title'],
501    'L_REMOTE_SITE_REMOVED'=>$lang['remote_site_removed'],
502    'L_REMOTE_SITE_LOCAL_FOUND'=>$lang['remote_site_local_found'],
503    'L_REMOTE_SITE_LOCAL_NEW'=>$lang['remote_site_local_new'],
504    'L_REMOTE_SITE_LOCAL_UPDATE'=>$lang['remote_site_local_update'],
505   
506    'F_ACTION'=>add_session_id(PHPWG_ROOT_PATH.'admin.php?page=remote_site')
507   )
508 );
509// +-----------------------------------------------------------------------+
510// |                        new site creation form                         |
511// +-----------------------------------------------------------------------+
512$errors = array();
513
514if (isset($_POST['submit']))
515{
516  // site must start by http:// or https://
517  if (!preg_match('/^https?:\/\/[~\/\.\w-]+$/', $_POST['galleries_url']))
518  {
519    array_push($errors, $lang['remote_site_uncorrect_url']);
520  }
521  else
522  {
523    $page['galleries_url'] = preg_replace('/[\/]*$/',
524                                          '',
525                                          $_POST['galleries_url']);
526    $page['galleries_url'].= '/';
527    // site must not exists
528    $query = '
529SELECT COUNT(id) AS count
530  FROM '.SITES_TABLE.'
531  WHERE galleries_url = \''.$page['galleries_url'].'\'
532;';
533    $row = mysql_fetch_array(mysql_query($query));
534    if ($row['count'] > 0)
535    {
536      array_push($errors, $lang['remote_site_already_exists']);
537    }
538  }
539
540  if (count($errors) == 0)
541  {
542    $url = $page['galleries_url'].'create_listing_file.php';
543    $url.= '?action=test';
544    $url.= '&version='.PHPWG_VERSION;
545    if ($lines = @file($url))
546    {
547      $first_line = strip_tags($lines[0]);
548      if (!preg_match('/^PWG-INFO-2:/', $first_line))
549      {
550        array_push($errors, $lang['remote_site_error'].' : '.$first_line);
551      }
552    }
553    else
554    {
555      array_push($errors, $lang['remote_site_file_not_found']);
556    }
557  }
558 
559  if (count($errors) == 0)
560  {
561    $query = '
562INSERT INTO '.SITES_TABLE.'
563  (galleries_url)
564  VALUES
565  (\''.$page['galleries_url'].'\')
566;';
567    mysql_query($query);
568
569    $template->assign_block_vars(
570      'confirmation',
571      array(
572        'CONTENT'=>$page['galleries_url'].' '.$lang['remote_site_created']
573        ));
574  }
575}
576// +-----------------------------------------------------------------------+
577// |                            actions on site                            |
578// +-----------------------------------------------------------------------+
579if (isset($_GET['site']) and is_numeric($_GET['site']))
580{
581  $page['site'] = $_GET['site'];
582}
583
584if (isset($_GET['action']))
585{
586  if (isset($page['site']))
587  {
588    $query = '
589SELECT galleries_url
590  FROM '.SITES_TABLE.'
591  WHERE id = '.$page['site'].'
592;';
593    list($galleries_url) = mysql_fetch_array(mysql_query($query));
594  }
595
596  switch($_GET['action'])
597  {
598    case 'delete' :
599    {
600      delete_site($page['site']);
601
602      $template->assign_block_vars(
603        'confirmation',
604        array(
605          'CONTENT'=>$galleries_url.' '.$lang['remote_site_deleted']
606          ));
607     
608      break;
609    }
610    case 'generate' :
611    {
612      $title = $galleries_url.' : '.$lang['remote_site_generate'];
613      $template->assign_vars(array('REMOTE_SITE_TITLE'=>$title));
614      remote_output($galleries_url.'create_listing_file.php?action=generate');
615      break;
616    }
617    case 'update' :
618    {
619      $title = $galleries_url.' : '.$lang['remote_site_update'];
620      $template->assign_vars(array('REMOTE_SITE_TITLE'=>$title));
621      update_remote_site($galleries_url.'listing.xml', $page['site']);
622      break;
623    }
624    case 'clean' :
625    {
626      $title = $galleries_url.' : '.$lang['remote_site_clean'];
627      $template->assign_vars(array('REMOTE_SITE_TITLE'=>$title));
628      remote_output($galleries_url.'create_listing_file.php?action=clean');
629      break;
630    }
631    case 'local_update' :
632    {
633      $local_listing = PHPWG_ROOT_PATH.'listing.xml';
634      $xml_content = getXmlCode($local_listing);
635      $url = getAttribute(getChild($xml_content, 'informations'), 'url');
636
637      // is the site already existing ?
638      $query = '
639SELECT id
640  FROM '.SITES_TABLE.'
641  WHERE galleries_url = \''.addslashes($url).'\'
642;';
643      $result = mysql_query($query);
644      if (mysql_num_rows($result) == 0)
645      {
646        // we have to register this site in the database
647        $query = '
648INSERT INTO '.SITES_TABLE.'
649  (galleries_url)
650  VALUES
651  (\''.$url.'\')
652;';
653        mysql_query($query);
654        $site_id = mysql_insert_id();
655      }
656      else
657      {
658        // we get the already registered id
659        $row = mysql_fetch_array($result);
660        $site_id = $row['id'];
661      }
662     
663      $title = $url.' : '.$lang['remote_site_local_update'];
664      $template->assign_vars(array('REMOTE_SITE_TITLE'=>$title));
665      update_remote_site($local_listing, $site_id);
666      break;
667    }
668  }
669}
670else
671{
672  // we search a "local" listing.xml file
673  $local_listing = PHPWG_ROOT_PATH.'listing.xml';
674  if (is_file($local_listing))
675  {
676    $xml_content = getXmlCode($local_listing);
677    $url = getAttribute(getChild($xml_content, 'informations'), 'url');
678
679    $base_url = PHPWG_ROOT_PATH.'admin.php?page=remote_site&amp;action=';
680   
681    $template->assign_block_vars(
682      'local',
683      array(
684        'URL' => $url,
685        'U_UPDATE' => add_session_id($base_url.'local_update')
686        )
687      );
688
689    // is the site already existing ?
690    $query = '
691SELECT COUNT(*)
692  FROM '.SITES_TABLE.'
693  WHERE galleries_url = \''.addslashes($url).'\'
694;';
695    list($count) = mysql_fetch_array(mysql_query($query));
696    if ($count == 0)
697    {
698      $template->assign_block_vars('local.new_site', array());
699    }
700  }
701}
702// +-----------------------------------------------------------------------+
703// |                           remote sites list                           |
704// +-----------------------------------------------------------------------+
705
706// site 1 is the local site, should not be taken into account
707$query = '
708SELECT id, galleries_url
709  FROM '.SITES_TABLE.'
710  WHERE id != 1
711;';
712$result = mysql_query($query);
713while ($row = mysql_fetch_array($result))
714{
715  $base_url = PHPWG_ROOT_PATH.'admin.php';
716  $base_url.= '?page=remote_site';
717  $base_url.= '&amp;site='.$row['id'];
718  $base_url.= '&amp;action=';
719 
720  $template->assign_block_vars(
721    'site',
722    array(
723      'NAME' => $row['galleries_url'],
724      'U_GENERATE' => add_session_id($base_url.'generate'),
725      'U_UPDATE' => add_session_id($base_url.'update'),
726      'U_CLEAN' => add_session_id($base_url.'clean'),
727      'U_DELETE' => add_session_id($base_url.'delete')
728     )
729   );
730}
731// +-----------------------------------------------------------------------+
732// |                             errors display                            |
733// +-----------------------------------------------------------------------+
734if (count($errors) != 0)
735{
736  $template->assign_block_vars('errors',array());
737  foreach ($errors as $error)
738  {
739    $template->assign_block_vars('errors.error',array('ERROR'=>$error));
740  }
741}
742// +-----------------------------------------------------------------------+
743// |                           sending html code                           |
744// +-----------------------------------------------------------------------+
745$template->assign_var_from_handle('ADMIN_CONTENT', 'remote_site');
746?>
Note: See TracBrowser for help on using the repository browser.