source: branches/branch-1_5/admin/remote_site.php @ 1005

Last change on this file since 1005 was 1005, checked in by nikrou, 18 years ago

Revert to revision 1002

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