source: branches/1.4/admin/remote_site.php @ 16878

Last change on this file since 16878 was 675, checked in by plg, 19 years ago

all headers adapted to new year 2005, happy new year

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