source: trunk/include/ws_functions.inc.php @ 17675

Last change on this file since 17675 was 17675, checked in by rvelices, 12 years ago

bug 2725: Piwigo isn't compatible with suPHP + better handling of watermark upload errors

  • Property svn:eol-style set to LF
File size: 83.9 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2012 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24/**** IMPLEMENTATION OF WEB SERVICE METHODS ***********************************/
25
26/**
27 * Event handler for method invocation security check. Should return a PwgError
28 * if the preconditions are not satifsied for method invocation.
29 */
30function ws_isInvokeAllowed($res, $methodName, $params)
31{
32  global $conf;
33
34  if ( strpos($methodName,'reflection.')===0 )
35  { // OK for reflection
36    return $res;
37  }
38
39  if ( !is_autorize_status(ACCESS_GUEST) and
40      strpos($methodName,'pwg.session.')!==0 )
41  {
42    return new PwgError(401, 'Access denied');
43  }
44
45  return $res;
46}
47
48/**
49 * returns a "standard" (for our web service) array of sql where clauses that
50 * filters the images (images table only)
51 */
52function ws_std_image_sql_filter( $params, $tbl_name='' )
53{
54  $clauses = array();
55  if ( is_numeric($params['f_min_rate']) )
56  {
57    $clauses[] = $tbl_name.'rating_score>'.$params['f_min_rate'];
58  }
59  if ( is_numeric($params['f_max_rate']) )
60  {
61    $clauses[] = $tbl_name.'rating_score<='.$params['f_max_rate'];
62  }
63  if ( is_numeric($params['f_min_hit']) )
64  {
65    $clauses[] = $tbl_name.'hit>'.$params['f_min_hit'];
66  }
67  if ( is_numeric($params['f_max_hit']) )
68  {
69    $clauses[] = $tbl_name.'hit<='.$params['f_max_hit'];
70  }
71  if ( isset($params['f_min_date_available']) )
72  {
73    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_available']."'";
74  }
75  if ( isset($params['f_max_date_available']) )
76  {
77    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_available']."'";
78  }
79  if ( isset($params['f_min_date_created']) )
80  {
81    $clauses[] = $tbl_name."date_creation>='".$params['f_min_date_created']."'";
82  }
83  if ( isset($params['f_max_date_created']) )
84  {
85    $clauses[] = $tbl_name."date_creation<'".$params['f_max_date_created']."'";
86  }
87  if ( is_numeric($params['f_min_ratio']) )
88  {
89    $clauses[] = $tbl_name.'width/'.$tbl_name.'height>'.$params['f_min_ratio'];
90  }
91  if ( is_numeric($params['f_max_ratio']) )
92  {
93    $clauses[] = $tbl_name.'width/'.$tbl_name.'height<='.$params['f_max_ratio'];
94  }
95  if (is_numeric($params['f_max_level']) )
96  {
97    $clauses[] = $tbl_name.'level <= '.$params['f_max_level'];
98  }
99  return $clauses;
100}
101
102/**
103 * returns a "standard" (for our web service) ORDER BY sql clause for images
104 */
105function ws_std_image_sql_order( $params, $tbl_name='' )
106{
107  $ret = '';
108  if ( empty($params['order']) )
109  {
110    return $ret;
111  }
112  $matches = array();
113  preg_match_all('/([a-z_]+) *(?:(asc|desc)(?:ending)?)? *(?:, *|$)/i',
114    $params['order'], $matches);
115  for ($i=0; $i<count($matches[1]); $i++)
116  {
117    switch ($matches[1][$i])
118    {
119      case 'date_created':
120        $matches[1][$i] = 'date_creation'; break;
121      case 'date_posted':
122        $matches[1][$i] = 'date_available'; break;
123      case 'rand': case 'random':
124        $matches[1][$i] = DB_RANDOM_FUNCTION.'()'; break;
125    }
126    $sortable_fields = array('id', 'file', 'name', 'hit', 'rating_score',
127      'date_creation', 'date_available', DB_RANDOM_FUNCTION.'()' );
128    if ( in_array($matches[1][$i], $sortable_fields) )
129    {
130      if (!empty($ret))
131        $ret .= ', ';
132      if ($matches[1][$i] != DB_RANDOM_FUNCTION.'()' )
133      {
134        $ret .= $tbl_name;
135      }
136      $ret .= $matches[1][$i];
137      $ret .= ' '.$matches[2][$i];
138    }
139  }
140  return $ret;
141}
142
143/**
144 * returns an array map of urls (thumb/element) for image_row - to be returned
145 * in a standard way by different web service methods
146 */
147function ws_std_get_urls($image_row)
148{
149  $ret = array();
150
151  $src_image = new SrcImage($image_row);
152
153  if ( $src_image->is_original() )
154  {// we have a photo
155    global $user;
156    if ($user['enabled_high'])
157    {
158      $ret['element_url'] = $src_image->get_url();
159    }
160  }
161  else
162  {
163    $ret['element_url'] = get_element_url($image_row);
164  }
165
166  $derivatives = DerivativeImage::get_all($src_image);
167  $derivatives_arr = array();
168  foreach($derivatives as $type=>$derivative)
169  {
170    $size = $derivative->get_size();
171    $size != null or $size=array(null,null);
172    $derivatives_arr[$type] = array('url' => $derivative->get_url(), 'width'=>$size[0], 'height'=>$size[1] );
173  }
174  $ret['derivatives'] = $derivatives_arr;;
175  return $ret;
176}
177
178/**
179 * returns an array of image attributes that are to be encoded as xml attributes
180 * instead of xml elements
181 */
182function ws_std_get_image_xml_attributes()
183{
184  return array(
185    'id','element_url', 'file','width','height','hit','date_available','date_creation'
186    );
187}
188
189function ws_getMissingDerivatives($params, &$service)
190{
191  if (!is_admin())
192  {
193    return new PwgError(403, 'Forbidden');
194  }
195
196  if ( empty($params['types']) )
197  {
198    $types = array_keys(ImageStdParams::get_defined_type_map());
199  }
200  else
201  {
202    $types = array_intersect(array_keys(ImageStdParams::get_defined_type_map()), $params['types']);
203    if (count($types)==0)
204    {
205      return new PwgError(WS_ERR_INVALID_PARAM, "Invalid types");
206    }
207  }
208
209  if ( ($max_urls = intval($params['max_urls'])) <= 0)
210  {
211    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid max_urls");
212  }
213
214  list($max_id, $image_count) = pwg_db_fetch_row( pwg_query('SELECT MAX(id)+1, COUNT(*) FROM '.IMAGES_TABLE) );
215
216  if (0 == $image_count)
217  {
218    return array();
219  }
220
221  $start_id = intval($params['prev_page']);
222  if ($start_id<=0)
223  {
224    $start_id = $max_id;
225  }
226
227  $uid = '&b='.time();
228  global $conf;
229  $conf['question_mark_in_urls'] = $conf['php_extension_in_urls'] = true;
230  $conf['derivative_url_style']=2; //script
231
232  $qlimit = min(5000, ceil(max($image_count/500, $max_urls/count($types))));
233  $where_clauses = ws_std_image_sql_filter( $params, '' );
234  $where_clauses[] = 'id<start_id';
235  if ( !empty($params['ids']) )
236  {
237    $where_clauses[] = 'id IN ('.implode(',',$params['ids']).')';
238  }
239
240  $query_model = 'SELECT id, path, representative_ext, width,height,rotation
241  FROM '.IMAGES_TABLE.'
242  WHERE '.implode(' AND ', $where_clauses).'
243  ORDER BY id DESC
244  LIMIT '.$qlimit;
245
246  $urls=array();
247  do
248  {
249    $result = pwg_query( str_replace('start_id', $start_id, $query_model));
250    $is_last = pwg_db_num_rows($result) < $qlimit;
251    while ($row=pwg_db_fetch_assoc($result))
252    {
253      $start_id = $row['id'];
254      $src_image = new SrcImage($row);
255      if ($src_image->is_mimetype())
256        continue;
257      foreach($types as $type)
258      {
259        $derivative = new DerivativeImage($type, $src_image);
260        if ($type != $derivative->get_type())
261          continue;
262        if (@filemtime($derivative->get_path())===false)
263        {
264          $urls[] = $derivative->get_url().$uid;
265        }
266      }
267      if (count($urls)>=$max_urls && !$is_last)
268        break;
269    }
270    if ($is_last)
271    {
272      $start_id = 0;
273    }
274  }while (count($urls)<$max_urls && $start_id);
275
276  $ret = array();
277  if ($start_id)
278  {
279    $ret['next_page']=$start_id;
280  }
281  $ret['urls']=$urls;
282  return $ret;
283}
284
285/**
286 * returns PWG version (web service method)
287 */
288function ws_getVersion($params, &$service)
289{
290  global $conf;
291  if ($conf['show_version'] or is_admin() )
292    return PHPWG_VERSION;
293  else
294    return new PwgError(403, 'Forbidden');
295}
296
297/**
298 * returns general informations (web service method)
299 */
300function ws_getInfos($params, &$service)
301{
302  if (!is_admin())
303  {
304    return new PwgError(403, 'Forbidden');
305  }
306
307  $infos['version'] = PHPWG_VERSION;
308
309  $query = 'SELECT COUNT(*) FROM '.IMAGES_TABLE.';';
310  list($infos['nb_elements']) = pwg_db_fetch_row(pwg_query($query));
311
312  $query = 'SELECT COUNT(*) FROM '.CATEGORIES_TABLE.';';
313  list($infos['nb_categories']) = pwg_db_fetch_row(pwg_query($query));
314
315  $query = 'SELECT COUNT(*) FROM '.CATEGORIES_TABLE.' WHERE dir IS NULL;';
316  list($infos['nb_virtual']) = pwg_db_fetch_row(pwg_query($query));
317
318  $query = 'SELECT COUNT(*) FROM '.CATEGORIES_TABLE.' WHERE dir IS NOT NULL;';
319  list($infos['nb_physical']) = pwg_db_fetch_row(pwg_query($query));
320
321  $query = 'SELECT COUNT(*) FROM '.IMAGE_CATEGORY_TABLE.';';
322  list($infos['nb_image_category']) = pwg_db_fetch_row(pwg_query($query));
323
324  $query = 'SELECT COUNT(*) FROM '.TAGS_TABLE.';';
325  list($infos['nb_tags']) = pwg_db_fetch_row(pwg_query($query));
326
327  $query = 'SELECT COUNT(*) FROM '.IMAGE_TAG_TABLE.';';
328  list($infos['nb_image_tag']) = pwg_db_fetch_row(pwg_query($query));
329
330  $query = 'SELECT COUNT(*) FROM '.USERS_TABLE.';';
331  list($infos['nb_users']) = pwg_db_fetch_row(pwg_query($query));
332
333  $query = 'SELECT COUNT(*) FROM '.GROUPS_TABLE.';';
334  list($infos['nb_groups']) = pwg_db_fetch_row(pwg_query($query));
335
336  $query = 'SELECT COUNT(*) FROM '.COMMENTS_TABLE.';';
337  list($infos['nb_comments']) = pwg_db_fetch_row(pwg_query($query));
338
339  // first element
340  if ($infos['nb_elements'] > 0)
341  {
342    $query = 'SELECT MIN(date_available) FROM '.IMAGES_TABLE.';';
343    list($infos['first_date']) = pwg_db_fetch_row(pwg_query($query));
344  }
345
346  // unvalidated comments
347  if ($infos['nb_comments'] > 0)
348  {
349    $query = 'SELECT COUNT(*) FROM '.COMMENTS_TABLE.' WHERE validated=\'false\';';
350    list($infos['nb_unvalidated_comments']) = pwg_db_fetch_row(pwg_query($query));
351  }
352
353  foreach ($infos as $name => $value)
354  {
355    $output[] = array(
356      'name' => $name,
357      'value' => $value,
358    );
359  }
360
361  return array('infos' => new PwgNamedArray($output, 'item'));
362}
363
364function ws_caddie_add($params, &$service)
365{
366  if (!is_admin())
367  {
368    return new PwgError(401, 'Access denied');
369  }
370  $params['image_id'] = array_map( 'intval',$params['image_id'] );
371  if ( empty($params['image_id']) )
372  {
373    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
374  }
375  global $user;
376  $query = '
377SELECT id
378  FROM '.IMAGES_TABLE.' LEFT JOIN '.CADDIE_TABLE.' ON id=element_id AND user_id='.$user['id'].'
379  WHERE id IN ('.implode(',',$params['image_id']).')
380    AND element_id IS NULL';
381  $datas = array();
382  foreach ( array_from_query($query, 'id') as $id )
383  {
384    array_push($datas, array('element_id'=>$id, 'user_id'=>$user['id']) );
385  }
386  if (count($datas))
387  {
388    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
389    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
390  }
391  return count($datas);
392}
393
394/**
395 * returns images per category (web service method)
396 */
397function ws_categories_getImages($params, &$service)
398{
399  global $user, $conf;
400
401  $images = array();
402
403  //------------------------------------------------- get the related categories
404  $where_clauses = array();
405  foreach($params['cat_id'] as $cat_id)
406  {
407    $cat_id = (int)$cat_id;
408    if ($cat_id<=0)
409      continue;
410    if ($params['recursive'])
411    {
412      $where_clauses[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.$cat_id.'(,|$)\'';
413    }
414    else
415    {
416      $where_clauses[] = 'id='.$cat_id;
417    }
418  }
419  if (!empty($where_clauses))
420  {
421    $where_clauses = array( '('.
422    implode('
423    OR ', $where_clauses) . ')'
424      );
425  }
426  $where_clauses[] = get_sql_condition_FandF(
427        array('forbidden_categories' => 'id'),
428        NULL, true
429      );
430
431  $query = '
432SELECT id, name, permalink, image_order
433  FROM '.CATEGORIES_TABLE.'
434  WHERE '. implode('
435    AND ', $where_clauses);
436  $result = pwg_query($query);
437  $cats = array();
438  while ($row = pwg_db_fetch_assoc($result))
439  {
440    $row['id'] = (int)$row['id'];
441    $cats[ $row['id'] ] = $row;
442  }
443
444  //-------------------------------------------------------- get the images
445  if ( !empty($cats) )
446  {
447    $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
448    $where_clauses[] = 'category_id IN ('
449      .implode(',', array_keys($cats) )
450      .')';
451    $where_clauses[] = get_sql_condition_FandF( array(
452          'visible_images' => 'i.id'
453        ), null, true
454      );
455
456    $order_by = ws_std_image_sql_order($params, 'i.');
457    if ( empty($order_by)
458          and count($params['cat_id'])==1
459          and isset($cats[ $params['cat_id'][0] ]['image_order'])
460        )
461    {
462      $order_by = $cats[ $params['cat_id'][0] ]['image_order'];
463    }
464    $order_by = empty($order_by) ? $conf['order_by'] : 'ORDER BY '.$order_by;
465
466    $query = '
467SELECT i.*, GROUP_CONCAT(category_id) AS cat_ids
468  FROM '.IMAGES_TABLE.' i
469    INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
470  WHERE '. implode('
471    AND ', $where_clauses).'
472GROUP BY i.id
473'.$order_by.'
474LIMIT '.(int)$params['per_page'].' OFFSET '.(int)($params['per_page']*$params['page']);
475
476    $result = pwg_query($query);
477    while ($row = pwg_db_fetch_assoc($result))
478    {
479      $image = array();
480      foreach ( array('id', 'width', 'height', 'hit') as $k )
481      {
482        if (isset($row[$k]))
483        {
484          $image[$k] = (int)$row[$k];
485        }
486      }
487      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
488      {
489        $image[$k] = $row[$k];
490      }
491      $image = array_merge( $image, ws_std_get_urls($row) );
492
493      $image_cats = array();
494      foreach ( explode(',', $row['cat_ids']) as $cat_id )
495      {
496        $url = make_index_url(
497                array(
498                  'category' => $cats[$cat_id],
499                  )
500                );
501        $page_url = make_picture_url(
502                array(
503                  'category' => $cats[$cat_id],
504                  'image_id' => $row['id'],
505                  'image_file' => $row['file'],
506                  )
507                );
508        array_push( $image_cats,  array(
509              WS_XML_ATTRIBUTES => array (
510                  'id' => (int)$cat_id,
511                  'url' => $url,
512                  'page_url' => $page_url,
513                )
514            )
515          );
516      }
517
518      $image['categories'] = new PwgNamedArray(
519            $image_cats,'category', array('id','url','page_url')
520          );
521      array_push($images, $image);
522    }
523  }
524
525  return array( 'images' =>
526    array (
527      WS_XML_ATTRIBUTES =>
528        array(
529            'page' => $params['page'],
530            'per_page' => $params['per_page'],
531            'count' => count($images)
532          ),
533       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
534          ws_std_get_image_xml_attributes() )
535      )
536    );
537}
538
539
540/**
541 * create a tree from a flat list of categories, no recursivity for high speed
542 */
543function categories_flatlist_to_tree($categories)
544{
545  $tree = array();
546  $key_of_cat = array();
547
548  foreach ($categories as $key => &$node)
549  {
550    $key_of_cat[$node['id']] = $key;
551
552    if (!isset($node['id_uppercat']))
553    {
554      $tree[$key] = &$node;
555    }
556    else
557    {
558      if (!isset($categories[ $key_of_cat[ $node['id_uppercat'] ] ]['sub_categories']))
559      {
560        $categories[ $key_of_cat[ $node['id_uppercat'] ] ]['sub_categories'] = array();
561      }
562
563      $categories[ $key_of_cat[ $node['id_uppercat'] ] ]['sub_categories'][$key] = &$node;
564    }
565  }
566
567  return $tree;
568}
569
570/**
571 * returns a list of categories (web service method)
572 */
573function ws_categories_getList($params, &$service)
574{
575  global $user,$conf;
576
577  if ($params['tree_output'])
578  {
579    if (!isset($_GET['format']) or !in_array($_GET['format'], array('php', 'json')))
580    {
581      // the algorithm used to build a tree from a flat list of categories
582      // keeps original array keys, which is not compatible with
583      // PwgNamedArray.
584      //
585      // PwgNamedArray is useful to define which data is an attribute and
586      // which is an element in the XML output. The "hierarchy" output is
587      // only compatible with json/php output.
588
589      return new PwgError(405, "The tree_output option is only compatible with json/php output formats");
590    }
591  }
592
593  $where = array('1=1');
594  $join_type = 'INNER';
595  $join_user = $user['id'];
596
597  if (!$params['recursive'])
598  {
599    if ($params['cat_id']>0)
600      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
601    OR id='.(int)($params['cat_id']).')';
602    else
603      $where[] = 'id_uppercat IS NULL';
604  }
605  else if ($params['cat_id']>0)
606  {
607    $where[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.
608      (int)($params['cat_id'])
609      .'(,|$)\'';
610  }
611
612  if ($params['public'])
613  {
614    $where[] = 'status = "public"';
615    $where[] = 'visible = "true"';
616
617    $join_user = $conf['guest_id'];
618  }
619  elseif (is_admin())
620  {
621    // in this very specific case, we don't want to hide empty
622    // categories. Function calculate_permissions will only return
623    // categories that are either locked or private and not permitted
624    //
625    // calculate_permissions does not consider empty categories as forbidden
626    $forbidden_categories = calculate_permissions($user['id'], $user['status']);
627    $where[]= 'id NOT IN ('.$forbidden_categories.')';
628    $join_type = 'LEFT';
629  }
630
631  $query = '
632SELECT id, name, permalink, uppercats, global_rank, id_uppercat,
633    comment,
634    nb_images, count_images AS total_nb_images,
635    representative_picture_id, user_representative_picture_id, count_images, count_categories,
636    date_last, max_date_last, count_categories AS nb_categories
637  FROM '.CATEGORIES_TABLE.'
638   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
639  WHERE '. implode('
640    AND ', $where);
641
642  $result = pwg_query($query);
643
644  // management of the album thumbnail -- starts here
645  $image_ids = array();
646  $categories = array();
647  $user_representative_updates_for = array();
648  // management of the album thumbnail -- stops here
649
650  $cats = array();
651  while ($row = pwg_db_fetch_assoc($result))
652  {
653    $row['url'] = make_index_url(
654        array(
655          'category' => $row
656          )
657      );
658    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
659    {
660      $row[$key] = (int)$row[$key];
661    }
662
663    if ($params['fullname'])
664    {
665      $row['name'] = strip_tags(get_cat_display_name_cache($row['uppercats'], null, false));
666    }
667    else
668    {
669      $row['name'] = strip_tags(
670        trigger_event(
671          'render_category_name',
672          $row['name'],
673          'ws_categories_getList'
674          )
675        );
676    }
677
678    $row['comment'] = strip_tags(
679      trigger_event(
680        'render_category_description',
681        $row['comment'],
682        'ws_categories_getList'
683        )
684      );
685
686    // management of the album thumbnail -- starts here
687    //
688    // on branch 2.3, the algorithm is duplicated from
689    // include/category_cats, but we should use a common code for Piwigo 2.4
690    //
691    // warning : if the API method is called with $params['public'], the
692    // album thumbnail may be not accurate. The thumbnail can be viewed by
693    // the connected user, but maybe not by the guest. Changing the
694    // filtering method would be too complicated for now. We will simply
695    // avoid to persist the user_representative_picture_id in the database
696    // if $params['public']
697    if (!empty($row['user_representative_picture_id']))
698    {
699      $image_id = $row['user_representative_picture_id'];
700    }
701    else if (!empty($row['representative_picture_id']))
702    { // if a representative picture is set, it has priority
703      $image_id = $row['representative_picture_id'];
704    }
705    else if ($conf['allow_random_representative'])
706    {
707      // searching a random representant among elements in sub-categories
708      $image_id = get_random_image_in_category($row);
709    }
710    else
711    { // searching a random representant among representant of sub-categories
712      if ($row['count_categories']>0 and $row['count_images']>0)
713      {
714        $query = '
715  SELECT representative_picture_id
716    FROM '.CATEGORIES_TABLE.' INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.'
717    ON id = cat_id and user_id = '.$user['id'].'
718    WHERE uppercats LIKE \''.$row['uppercats'].',%\'
719      AND representative_picture_id IS NOT NULL'
720          .get_sql_condition_FandF
721          (
722            array
723            (
724              'visible_categories' => 'id',
725              ),
726            "\n  AND"
727            ).'
728    ORDER BY '.DB_RANDOM_FUNCTION.'()
729    LIMIT 1
730  ;';
731        $subresult = pwg_query($query);
732        if (pwg_db_num_rows($subresult) > 0)
733        {
734          list($image_id) = pwg_db_fetch_row($subresult);
735        }
736      }
737    }
738
739    if (isset($image_id))
740    {
741      if ($conf['representative_cache_on_subcats'] and $row['user_representative_picture_id'] != $image_id)
742      {
743        $user_representative_updates_for[ $user['id'].'#'.$row['id'] ] = $image_id;
744      }
745
746      $row['representative_picture_id'] = $image_id;
747      array_push($image_ids, $image_id);
748      array_push($categories, $row);
749    }
750    unset($image_id);
751    // management of the album thumbnail -- stops here
752
753
754    array_push($cats, $row);
755  }
756  usort($cats, 'global_rank_compare');
757
758  // management of the album thumbnail -- starts here
759  if (count($categories) > 0)
760  {
761    $thumbnail_src_of = array();
762    $new_image_ids = array();
763
764    $query = '
765SELECT id, path, representative_ext, level
766  FROM '.IMAGES_TABLE.'
767  WHERE id IN ('.implode(',', $image_ids).')
768;';
769    $result = pwg_query($query);
770    while ($row = pwg_db_fetch_assoc($result))
771    {
772      if ($row['level'] <= $user['level'])
773      {
774        $thumbnail_src_of[$row['id']] = DerivativeImage::thumb_url($row);
775      }
776      else
777      {
778        // problem: we must not display the thumbnail of a photo which has a
779        // higher privacy level than user privacy level
780        //
781        // * what is the represented category?
782        // * find a random photo matching user permissions
783        // * register it at user_representative_picture_id
784        // * set it as the representative_picture_id for the category
785
786        foreach ($categories as &$category)
787        {
788          if ($row['id'] == $category['representative_picture_id'])
789          {
790            // searching a random representant among elements in sub-categories
791            $image_id = get_random_image_in_category($category);
792
793            if (isset($image_id) and !in_array($image_id, $image_ids))
794            {
795              array_push($new_image_ids, $image_id);
796            }
797
798            if ($conf['representative_cache_on_level'])
799            {
800              $user_representative_updates_for[ $user['id'].'#'.$category['id'] ] = $image_id;
801            }
802
803            $category['representative_picture_id'] = $image_id;
804          }
805        }
806        unset($category);
807      }
808    }
809
810    if (count($new_image_ids) > 0)
811    {
812      $query = '
813SELECT id, path, representative_ext
814  FROM '.IMAGES_TABLE.'
815  WHERE id IN ('.implode(',', $new_image_ids).')
816;';
817      $result = pwg_query($query);
818      while ($row = pwg_db_fetch_assoc($result))
819      {
820        $thumbnail_src_of[$row['id']] = DerivativeImage::thumb_url($row);
821      }
822    }
823  }
824
825  // compared to code in include/category_cats, we only persist the new
826  // user_representative if we have used $user['id'] and not the guest id,
827  // or else the real guest may see thumbnail that he should not
828  if (!$params['public'] and count($user_representative_updates_for))
829  {
830    $updates = array();
831
832    foreach ($user_representative_updates_for as $user_cat => $image_id)
833    {
834      list($user_id, $cat_id) = explode('#', $user_cat);
835
836      array_push(
837        $updates,
838        array(
839          'user_id' => $user_id,
840          'cat_id' => $cat_id,
841          'user_representative_picture_id' => $image_id,
842          )
843        );
844    }
845
846    mass_updates(
847      USER_CACHE_CATEGORIES_TABLE,
848      array(
849        'primary' => array('user_id', 'cat_id'),
850        'update'  => array('user_representative_picture_id')
851        ),
852      $updates
853      );
854  }
855
856  foreach ($cats as &$cat)
857  {
858    foreach ($categories as $category)
859    {
860      if ($category['id'] == $cat['id'] and isset($category['representative_picture_id']))
861      {
862        $cat['tn_url'] = $thumbnail_src_of[$category['representative_picture_id']];
863      }
864    }
865    // we don't want them in the output
866    unset($cat['user_representative_picture_id']);
867    unset($cat['count_images']);
868    unset($cat['count_categories']);
869  }
870  unset($cat);
871  // management of the album thumbnail -- stops here
872
873  if ($params['tree_output'])
874  {
875    return categories_flatlist_to_tree($cats);
876  }
877  else
878  {
879    return array(
880      'categories' => new PwgNamedArray(
881        $cats,
882        'category',
883        array(
884          'id',
885          'url',
886          'nb_images',
887          'total_nb_images',
888          'nb_categories',
889          'date_last',
890          'max_date_last',
891          )
892        )
893      );
894  }
895}
896
897/**
898 * returns the list of categories as you can see them in administration (web
899 * service method).
900 *
901 * Only admin can run this method and permissions are not taken into
902 * account.
903 */
904function ws_categories_getAdminList($params, &$service)
905{
906  if (!is_admin())
907  {
908    return new PwgError(401, 'Access denied');
909  }
910
911  $query = '
912SELECT
913    category_id,
914    COUNT(*) AS counter
915  FROM '.IMAGE_CATEGORY_TABLE.'
916  GROUP BY category_id
917;';
918  $nb_images_of = simple_hash_from_query($query, 'category_id', 'counter');
919
920  $query = '
921SELECT
922    id,
923    name,
924    comment,
925    uppercats,
926    global_rank
927  FROM '.CATEGORIES_TABLE.'
928;';
929  $result = pwg_query($query);
930  $cats = array();
931
932  while ($row = pwg_db_fetch_assoc($result))
933  {
934    $id = $row['id'];
935    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
936    $row['name'] = strip_tags(
937      trigger_event(
938        'render_category_name',
939        $row['name'],
940        'ws_categories_getAdminList'
941        )
942      );
943    $row['comment'] = strip_tags(
944      trigger_event(
945        'render_category_description',
946        $row['comment'],
947        'ws_categories_getAdminList'
948        )
949      );
950    array_push($cats, $row);
951  }
952
953  usort($cats, 'global_rank_compare');
954  return array(
955    'categories' => new PwgNamedArray(
956      $cats,
957      'category',
958      array(
959        'id',
960        'nb_images',
961        'name',
962        'uppercats',
963        'global_rank',
964        )
965      )
966    );
967}
968
969/**
970 * returns detailed information for an element (web service method)
971 */
972function ws_images_addComment($params, &$service)
973{
974  if (!$service->isPost())
975  {
976    return new PwgError(405, "This method requires HTTP POST");
977  }
978  $params['image_id'] = (int)$params['image_id'];
979  $query = '
980SELECT DISTINCT image_id
981  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
982  WHERE commentable="true"
983    AND image_id='.$params['image_id'].
984    get_sql_condition_FandF(
985      array(
986        'forbidden_categories' => 'id',
987        'visible_categories' => 'id',
988        'visible_images' => 'image_id'
989      ),
990      ' AND'
991    );
992  if ( !pwg_db_num_rows( pwg_query( $query ) ) )
993  {
994    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
995  }
996
997  $comm = array(
998    'author' => trim( $params['author'] ),
999    'content' => trim( $params['content'] ),
1000    'image_id' => $params['image_id'],
1001   );
1002
1003  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
1004
1005  $comment_action = insert_user_comment(
1006      $comm, $params['key'], $infos
1007    );
1008
1009  switch ($comment_action)
1010  {
1011    case 'reject':
1012      array_push($infos, l10n('Your comment has NOT been registered because it did not pass the validation rules') );
1013      return new PwgError(403, implode("; ", $infos) );
1014    case 'validate':
1015    case 'moderate':
1016      $ret = array(
1017          'id' => $comm['id'],
1018          'validation' => $comment_action=='validate',
1019        );
1020      return new PwgNamedStruct(
1021          'comment',
1022          $ret,
1023          null, array()
1024        );
1025    default:
1026      return new PwgError(500, "Unknown comment action ".$comment_action );
1027  }
1028}
1029
1030/**
1031 * returns detailed information for an element (web service method)
1032 */
1033function ws_images_getInfo($params, &$service)
1034{
1035  global $user, $conf;
1036  $params['image_id'] = (int)$params['image_id'];
1037  if ( $params['image_id']<=0 )
1038  {
1039    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1040  }
1041
1042  $query='
1043SELECT * FROM '.IMAGES_TABLE.'
1044  WHERE id='.$params['image_id'].
1045    get_sql_condition_FandF(
1046      array('visible_images' => 'id'),
1047      ' AND'
1048    ).'
1049LIMIT 1';
1050
1051  $image_row = pwg_db_fetch_assoc(pwg_query($query));
1052  if ($image_row==null)
1053  {
1054    return new PwgError(404, "image_id not found");
1055  }
1056  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
1057
1058  //-------------------------------------------------------- related categories
1059  $query = '
1060SELECT id, name, permalink, uppercats, global_rank, commentable
1061  FROM '.IMAGE_CATEGORY_TABLE.'
1062    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
1063  WHERE image_id = '.$image_row['id'].
1064  get_sql_condition_FandF(
1065      array( 'forbidden_categories' => 'category_id' ),
1066      ' AND'
1067    ).'
1068;';
1069  $result = pwg_query($query);
1070  $is_commentable = false;
1071  $related_categories = array();
1072  while ($row = pwg_db_fetch_assoc($result))
1073  {
1074    if ($row['commentable']=='true')
1075    {
1076      $is_commentable = true;
1077    }
1078    unset($row['commentable']);
1079    $row['url'] = make_index_url(
1080        array(
1081          'category' => $row
1082          )
1083      );
1084
1085    $row['page_url'] = make_picture_url(
1086        array(
1087          'image_id' => $image_row['id'],
1088          'image_file' => $image_row['file'],
1089          'category' => $row
1090          )
1091      );
1092    $row['id']=(int)$row['id'];
1093    array_push($related_categories, $row);
1094  }
1095  usort($related_categories, 'global_rank_compare');
1096  if ( empty($related_categories) )
1097  {
1098    return new PwgError(401, 'Access denied');
1099  }
1100
1101  //-------------------------------------------------------------- related tags
1102  $related_tags = get_common_tags( array($image_row['id']), -1 );
1103  foreach( $related_tags as $i=>$tag)
1104  {
1105    $tag['url'] = make_index_url(
1106        array(
1107          'tags' => array($tag)
1108          )
1109      );
1110    $tag['page_url'] = make_picture_url(
1111        array(
1112          'image_id' => $image_row['id'],
1113          'image_file' => $image_row['file'],
1114          'tags' => array($tag),
1115          )
1116      );
1117    unset($tag['counter']);
1118    $tag['id']=(int)$tag['id'];
1119    $related_tags[$i]=$tag;
1120  }
1121  //------------------------------------------------------------- related rates
1122        $rating = array('score'=>$image_row['rating_score'], 'count'=>0, 'average'=>null);
1123        if (isset($rating['score']))
1124        {
1125                $query = '
1126SELECT COUNT(rate) AS count
1127     , ROUND(AVG(rate),2) AS average
1128  FROM '.RATE_TABLE.'
1129  WHERE element_id = '.$image_row['id'].'
1130;';
1131                $row = pwg_db_fetch_assoc(pwg_query($query));
1132                $rating['score'] = (float)$rating['score'];
1133                $rating['average'] = (float)$row['average'];
1134                $rating['count'] = (int)$row['count'];
1135        }
1136
1137  //---------------------------------------------------------- related comments
1138  $related_comments = array();
1139
1140  $where_comments = 'image_id = '.$image_row['id'];
1141  if ( !is_admin() )
1142  {
1143    $where_comments .= '
1144    AND validated="true"';
1145  }
1146
1147  $query = '
1148SELECT COUNT(id) AS nb_comments
1149  FROM '.COMMENTS_TABLE.'
1150  WHERE '.$where_comments;
1151  list($nb_comments) = array_from_query($query, 'nb_comments');
1152  $nb_comments = (int)$nb_comments;
1153
1154  if ( $nb_comments>0 and $params['comments_per_page']>0 )
1155  {
1156    $query = '
1157SELECT id, date, author, content
1158  FROM '.COMMENTS_TABLE.'
1159  WHERE '.$where_comments.'
1160  ORDER BY date
1161  LIMIT '.(int)$params['comments_per_page'].
1162    ' OFFSET '.(int)($params['comments_per_page']*$params['comments_page']);
1163
1164    $result = pwg_query($query);
1165    while ($row = pwg_db_fetch_assoc($result))
1166    {
1167      $row['id']=(int)$row['id'];
1168      array_push($related_comments, $row);
1169    }
1170  }
1171
1172  $comment_post_data = null;
1173  if ($is_commentable and
1174      (!is_a_guest()
1175        or (is_a_guest() and $conf['comments_forall'] )
1176      )
1177      )
1178  {
1179    $comment_post_data['author'] = stripslashes($user['username']);
1180    $comment_post_data['key'] = get_ephemeral_key(2, $params['image_id']);
1181  }
1182
1183  $ret = $image_row;
1184  foreach ( array('id','width','height','hit','filesize') as $k )
1185  {
1186    if (isset($ret[$k]))
1187    {
1188      $ret[$k] = (int)$ret[$k];
1189    }
1190  }
1191  foreach ( array('path', 'storage_category_id') as $k )
1192  {
1193    unset($ret[$k]);
1194  }
1195
1196  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
1197  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
1198  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
1199  if ( isset($comment_post_data) )
1200  {
1201    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
1202  }
1203  $ret['comments'] = array(
1204     WS_XML_ATTRIBUTES =>
1205        array(
1206          'page' => $params['comments_page'],
1207          'per_page' => $params['comments_per_page'],
1208          'count' => count($related_comments),
1209          'nb_comments' => $nb_comments,
1210        ),
1211     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id','date') )
1212      );
1213
1214  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
1215}
1216
1217
1218/**
1219 * rates the image_id in the parameter
1220 */
1221function ws_images_Rate($params, &$service)
1222{
1223  $image_id = (int)$params['image_id'];
1224  $query = '
1225SELECT DISTINCT id FROM '.IMAGES_TABLE.'
1226  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
1227  WHERE id='.$image_id
1228  .get_sql_condition_FandF(
1229    array(
1230        'forbidden_categories' => 'category_id',
1231        'forbidden_images' => 'id',
1232      ),
1233    '    AND'
1234    ).'
1235    LIMIT 1';
1236  if ( pwg_db_num_rows( pwg_query($query) )==0 )
1237  {
1238    return new PwgError(404, "Invalid image_id or access denied" );
1239  }
1240  $rate = (int)$params['rate'];
1241  include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
1242  $res = rate_picture( $image_id, $rate );
1243  if ($res==false)
1244  {
1245    global $conf;
1246    return new PwgError( 403, "Forbidden or rate not in ". implode(',',$conf['rate_items']));
1247  }
1248  return $res;
1249}
1250
1251
1252/**
1253 * returns a list of elements corresponding to a query search
1254 */
1255function ws_images_search($params, &$service)
1256{
1257  global $page;
1258  $images = array();
1259  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
1260
1261  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
1262  $order_by = ws_std_image_sql_order($params, 'i.');
1263
1264  $super_order_by = false;
1265  if ( !empty($order_by) )
1266  {
1267    global $conf;
1268    $conf['order_by'] = 'ORDER BY '.$order_by;
1269    $super_order_by=true; // quick_search_result might be faster
1270  }
1271
1272  $search_result = get_quick_search_results($params['query'],
1273      $super_order_by,
1274      implode(',', $where_clauses)
1275    );
1276
1277  $image_ids = array_slice(
1278      $search_result['items'],
1279      $params['page']*$params['per_page'],
1280      $params['per_page']
1281    );
1282
1283  if ( count($image_ids) )
1284  {
1285    $query = '
1286SELECT * FROM '.IMAGES_TABLE.'
1287  WHERE id IN ('.implode(',', $image_ids).')';
1288
1289    $image_ids = array_flip($image_ids);
1290    $result = pwg_query($query);
1291    while ($row = pwg_db_fetch_assoc($result))
1292    {
1293      $image = array();
1294      foreach ( array('id', 'width', 'height', 'hit') as $k )
1295      {
1296        if (isset($row[$k]))
1297        {
1298          $image[$k] = (int)$row[$k];
1299        }
1300      }
1301      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
1302      {
1303        $image[$k] = $row[$k];
1304      }
1305      $image = array_merge( $image, ws_std_get_urls($row) );
1306      $images[$image_ids[$image['id']]] = $image;
1307    }
1308    ksort($images, SORT_NUMERIC);
1309    $images = array_values($images);
1310  }
1311
1312
1313  return array( 'images' =>
1314    array (
1315      WS_XML_ATTRIBUTES =>
1316        array(
1317            'page' => $params['page'],
1318            'per_page' => $params['per_page'],
1319            'count' => count($images)
1320          ),
1321       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1322          ws_std_get_image_xml_attributes() )
1323      )
1324    );
1325}
1326
1327function ws_images_setPrivacyLevel($params, &$service)
1328{
1329  if (!is_admin())
1330  {
1331    return new PwgError(401, 'Access denied');
1332  }
1333  if (!$service->isPost())
1334  {
1335    return new PwgError(405, "This method requires HTTP POST");
1336  }
1337  $params['image_id'] = array_map( 'intval',$params['image_id'] );
1338  if ( empty($params['image_id']) )
1339  {
1340    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1341  }
1342  global $conf;
1343  if ( !in_array( (int)$params['level'], $conf['available_permission_levels']) )
1344  {
1345    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid level");
1346  }
1347
1348  $query = '
1349UPDATE '.IMAGES_TABLE.'
1350  SET level='.(int)$params['level'].'
1351  WHERE id IN ('.implode(',',$params['image_id']).')';
1352  $result = pwg_query($query);
1353  $affected_rows = pwg_db_changes($result);
1354  if ($affected_rows)
1355  {
1356    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1357    invalidate_user_cache();
1358  }
1359  return $affected_rows;
1360}
1361
1362function ws_images_setRank($params, &$service)
1363{
1364  if (!is_admin())
1365  {
1366    return new PwgError(401, 'Access denied');
1367  }
1368
1369  if (!$service->isPost())
1370  {
1371    return new PwgError(405, "This method requires HTTP POST");
1372  }
1373
1374  // is the image_id valid?
1375  $params['image_id'] = (int)$params['image_id'];
1376  if ($params['image_id'] <= 0)
1377  {
1378    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1379  }
1380
1381  // is the category valid?
1382  $params['category_id'] = (int)$params['category_id'];
1383  if ($params['category_id'] <= 0)
1384  {
1385    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
1386  }
1387
1388  // is the rank valid?
1389  $params['rank'] = (int)$params['rank'];
1390  if ($params['rank'] <= 0)
1391  {
1392    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid rank");
1393  }
1394
1395  // does the image really exist?
1396  $query='
1397SELECT
1398    *
1399  FROM '.IMAGES_TABLE.'
1400  WHERE id = '.$params['image_id'].'
1401;';
1402
1403  $image_row = pwg_db_fetch_assoc(pwg_query($query));
1404  if ($image_row == null)
1405  {
1406    return new PwgError(404, "image_id not found");
1407  }
1408
1409  // is the image associated to this category?
1410  $query = '
1411SELECT
1412    image_id,
1413    category_id,
1414    rank
1415  FROM '.IMAGE_CATEGORY_TABLE.'
1416  WHERE image_id = '.$params['image_id'].'
1417    AND category_id = '.$params['category_id'].'
1418;';
1419  $category_row = pwg_db_fetch_assoc(pwg_query($query));
1420  if ($category_row == null)
1421  {
1422    return new PwgError(404, "This image is not associated to this category");
1423  }
1424
1425  // what is the current higher rank for this category?
1426  $query = '
1427SELECT
1428    MAX(rank) AS max_rank
1429  FROM '.IMAGE_CATEGORY_TABLE.'
1430  WHERE category_id = '.$params['category_id'].'
1431;';
1432  $result = pwg_query($query);
1433  $row = pwg_db_fetch_assoc($result);
1434
1435  if (is_numeric($row['max_rank']))
1436  {
1437    if ($params['rank'] > $row['max_rank'])
1438    {
1439      $params['rank'] = $row['max_rank'] + 1;
1440    }
1441  }
1442  else
1443  {
1444    $params['rank'] = 1;
1445  }
1446
1447  // update rank for all other photos in the same category
1448  $query = '
1449UPDATE '.IMAGE_CATEGORY_TABLE.'
1450  SET rank = rank + 1
1451  WHERE category_id = '.$params['category_id'].'
1452    AND rank IS NOT NULL
1453    AND rank >= '.$params['rank'].'
1454;';
1455  pwg_query($query);
1456
1457  // set the new rank for the photo
1458  $query = '
1459UPDATE '.IMAGE_CATEGORY_TABLE.'
1460  SET rank = '.$params['rank'].'
1461  WHERE image_id = '.$params['image_id'].'
1462    AND category_id = '.$params['category_id'].'
1463;';
1464  pwg_query($query);
1465
1466  // return data for client
1467  return array(
1468    'image_id' => $params['image_id'],
1469    'category_id' => $params['category_id'],
1470    'rank' => $params['rank'],
1471    );
1472}
1473
1474function ws_images_add_chunk($params, &$service)
1475{
1476  global $conf;
1477
1478  // data
1479  // original_sum
1480  // type {thumb, file, high}
1481  // position
1482
1483  if (!is_admin())
1484  {
1485    return new PwgError(401, 'Access denied');
1486  }
1487
1488  if (!$service->isPost())
1489  {
1490    return new PwgError(405, "This method requires HTTP POST");
1491  }
1492
1493  foreach ($params as $param_key => $param_value) {
1494    if ('data' == $param_key) {
1495      continue;
1496    }
1497
1498    ws_logfile(
1499      sprintf(
1500        '[ws_images_add_chunk] input param "%s" : "%s"',
1501        $param_key,
1502        is_null($param_value) ? 'NULL' : $param_value
1503        )
1504      );
1505  }
1506
1507  $upload_dir = $conf['upload_dir'].'/buffer';
1508
1509  // create the upload directory tree if not exists
1510  if (!mkgetdir($upload_dir, MKGETDIR_DEFAULT&~MKGETDIR_DIE_ON_ERROR))
1511  {
1512    return new PwgError(500, 'error during buffer directory creation');
1513  }
1514
1515  $filename = sprintf(
1516    '%s-%s-%05u.block',
1517    $params['original_sum'],
1518    $params['type'],
1519    $params['position']
1520    );
1521
1522  ws_logfile('[ws_images_add_chunk] data length : '.strlen($params['data']));
1523
1524  $bytes_written = file_put_contents(
1525    $upload_dir.'/'.$filename,
1526    base64_decode($params['data'])
1527    );
1528
1529  if (false === $bytes_written) {
1530    return new PwgError(
1531      500,
1532      'an error has occured while writting chunk '.$params['position'].' for '.$params['type']
1533      );
1534  }
1535}
1536
1537function merge_chunks($output_filepath, $original_sum, $type)
1538{
1539  global $conf;
1540
1541  ws_logfile('[merge_chunks] input parameter $output_filepath : '.$output_filepath);
1542
1543  if (is_file($output_filepath))
1544  {
1545    unlink($output_filepath);
1546
1547    if (is_file($output_filepath))
1548    {
1549      return new PwgError(500, '[merge_chunks] error while trying to remove existing '.$output_filepath);
1550    }
1551  }
1552
1553  $upload_dir = $conf['upload_dir'].'/buffer';
1554  $pattern = '/'.$original_sum.'-'.$type.'/';
1555  $chunks = array();
1556
1557  if ($handle = opendir($upload_dir))
1558  {
1559    while (false !== ($file = readdir($handle)))
1560    {
1561      if (preg_match($pattern, $file))
1562      {
1563        ws_logfile($file);
1564        array_push($chunks, $upload_dir.'/'.$file);
1565      }
1566    }
1567    closedir($handle);
1568  }
1569
1570  sort($chunks);
1571
1572  if (function_exists('memory_get_usage')) {
1573    ws_logfile('[merge_chunks] memory_get_usage before loading chunks: '.memory_get_usage());
1574  }
1575
1576  $i = 0;
1577
1578  foreach ($chunks as $chunk)
1579  {
1580    $string = file_get_contents($chunk);
1581
1582    if (function_exists('memory_get_usage')) {
1583      ws_logfile('[merge_chunks] memory_get_usage on chunk '.++$i.': '.memory_get_usage());
1584    }
1585
1586    if (!file_put_contents($output_filepath, $string, FILE_APPEND))
1587    {
1588      return new PwgError(500, '[merge_chunks] error while writting chunks for '.$output_filepath);
1589    }
1590
1591    unlink($chunk);
1592  }
1593
1594  if (function_exists('memory_get_usage')) {
1595    ws_logfile('[merge_chunks] memory_get_usage after loading chunks: '.memory_get_usage());
1596  }
1597}
1598
1599/**
1600 * Function introduced for Piwigo 2.4 and the new "multiple size"
1601 * (derivatives) feature. As we only need the biggest sent photo as
1602 * "original", we remove chunks for smaller sizes. We can't make it earlier
1603 * in ws_images_add_chunk because at this moment we don't know which $type
1604 * will be the biggest (we could remove the thumb, but let's use the same
1605 * algorithm)
1606 */
1607function remove_chunks($original_sum, $type)
1608{
1609  global $conf;
1610
1611  $upload_dir = $conf['upload_dir'].'/buffer';
1612  $pattern = '/'.$original_sum.'-'.$type.'/';
1613  $chunks = array();
1614
1615  if ($handle = opendir($upload_dir))
1616  {
1617    while (false !== ($file = readdir($handle)))
1618    {
1619      if (preg_match($pattern, $file))
1620      {
1621        array_push($chunks, $upload_dir.'/'.$file);
1622      }
1623    }
1624    closedir($handle);
1625  }
1626
1627  foreach ($chunks as $chunk)
1628  {
1629    unlink($chunk);
1630  }
1631}
1632
1633function ws_images_addFile($params, &$service)
1634{
1635  ws_logfile(__FUNCTION__.', input :  '.var_export($params, true));
1636  // image_id
1637  // type {thumb, file, high}
1638  // sum -> not used currently (Piwigo 2.4)
1639
1640  global $conf;
1641  if (!is_admin())
1642  {
1643    return new PwgError(401, 'Access denied');
1644  }
1645
1646  $params['image_id'] = (int)$params['image_id'];
1647  if ($params['image_id'] <= 0)
1648  {
1649    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1650  }
1651
1652  //
1653  // what is the path and other infos about the photo?
1654  //
1655  $query = '
1656SELECT
1657    path,
1658    file,
1659    md5sum,
1660    width,
1661    height,
1662    filesize
1663  FROM '.IMAGES_TABLE.'
1664  WHERE id = '.$params['image_id'].'
1665;';
1666  $image = pwg_db_fetch_assoc(pwg_query($query));
1667
1668  if ($image == null)
1669  {
1670    return new PwgError(404, "image_id not found");
1671  }
1672
1673  // since Piwigo 2.4 and derivatives, we do not take the imported "thumb"
1674  // into account
1675  if ('thumb' == $params['type'])
1676  {
1677    remove_chunks($image['md5sum'], $type);
1678    return true;
1679  }
1680
1681  // since Piwigo 2.4 and derivatives, we only care about the "original"
1682  $original_type = 'file';
1683  if ('high' == $params['type'])
1684  {
1685    $original_type = 'high';
1686  }
1687
1688  $file_path = $conf['upload_dir'].'/buffer/'.$image['md5sum'].'-original';
1689
1690  merge_chunks($file_path, $image['md5sum'], $original_type);
1691  chmod($file_path, 0644);
1692
1693  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1694
1695  // if we receive the "file", we only update the original if the "file" is
1696  // bigger than current original
1697  if ('file' == $params['type'])
1698  {
1699    $do_update = false;
1700
1701    $infos = pwg_image_infos($file_path);
1702
1703    foreach (array('width', 'height', 'filesize') as $image_info)
1704    {
1705      if ($infos[$image_info] > $image[$image_info])
1706      {
1707        $do_update = true;
1708      }
1709    }
1710
1711    if (!$do_update)
1712    {
1713      unlink($file_path);
1714      return true;
1715    }
1716  }
1717
1718  $image_id = add_uploaded_file(
1719    $file_path,
1720    $image['file'],
1721    null,
1722    null,
1723    $params['image_id'],
1724    $image['md5sum'] // we force the md5sum to remain the same
1725    );
1726}
1727
1728function ws_images_add($params, &$service)
1729{
1730  global $conf, $user;
1731  if (!is_admin())
1732  {
1733    return new PwgError(401, 'Access denied');
1734  }
1735
1736  foreach ($params as $param_key => $param_value) {
1737    ws_logfile(
1738      sprintf(
1739        '[pwg.images.add] input param "%s" : "%s"',
1740        $param_key,
1741        is_null($param_value) ? 'NULL' : $param_value
1742        )
1743      );
1744  }
1745
1746  $params['image_id'] = (int)$params['image_id'];
1747  if ($params['image_id'] > 0)
1748  {
1749    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1750
1751    $query='
1752SELECT *
1753  FROM '.IMAGES_TABLE.'
1754  WHERE id = '.$params['image_id'].'
1755;';
1756
1757    $image_row = pwg_db_fetch_assoc(pwg_query($query));
1758    if ($image_row == null)
1759    {
1760      return new PwgError(404, "image_id not found");
1761    }
1762  }
1763
1764  // does the image already exists ?
1765  if ($params['check_uniqueness'])
1766  {
1767    if ('md5sum' == $conf['uniqueness_mode'])
1768    {
1769      $where_clause = "md5sum = '".$params['original_sum']."'";
1770    }
1771    if ('filename' == $conf['uniqueness_mode'])
1772    {
1773      $where_clause = "file = '".$params['original_filename']."'";
1774    }
1775
1776    $query = '
1777SELECT
1778    COUNT(*) AS counter
1779  FROM '.IMAGES_TABLE.'
1780  WHERE '.$where_clause.'
1781;';
1782    list($counter) = pwg_db_fetch_row(pwg_query($query));
1783    if ($counter != 0) {
1784      return new PwgError(500, 'file already exists');
1785    }
1786  }
1787
1788  // due to the new feature "derivatives" (multiple sizes) introduced for
1789  // Piwigo 2.4, we only take the biggest photos sent on
1790  // pwg.images.addChunk. If "high" is available we use it as "original"
1791  // else we use "file".
1792  remove_chunks($params['original_sum'], 'thumb');
1793
1794  if (isset($params['high_sum']))
1795  {
1796    $original_type = 'high';
1797    remove_chunks($params['original_sum'], 'file');
1798  }
1799  else
1800  {
1801    $original_type = 'file';
1802  }
1803
1804  $file_path = $conf['upload_dir'].'/buffer/'.$params['original_sum'].'-original';
1805
1806  merge_chunks($file_path, $params['original_sum'], $original_type);
1807  chmod($file_path, 0644);
1808
1809  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1810
1811  $image_id = add_uploaded_file(
1812    $file_path,
1813    $params['original_filename'],
1814    null, // categories
1815    isset($params['level']) ? $params['level'] : null,
1816    $params['image_id'] > 0 ? $params['image_id'] : null,
1817    $params['original_sum']
1818    );
1819
1820  $info_columns = array(
1821    'name',
1822    'author',
1823    'comment',
1824    'date_creation',
1825    );
1826
1827  $update = array();
1828
1829  foreach ($info_columns as $key)
1830  {
1831    if (isset($params[$key]))
1832    {
1833      $update[$key] = $params[$key];
1834    }
1835  }
1836
1837  if (count(array_keys($update)) > 0)
1838  {
1839    single_update(
1840      IMAGES_TABLE,
1841      $update,
1842      array('id' => $image_id)
1843      );
1844  }
1845
1846  $url_params = array('image_id' => $image_id);
1847
1848  // let's add links between the image and the categories
1849  if (isset($params['categories']))
1850  {
1851    ws_add_image_category_relations($image_id, $params['categories']);
1852
1853    if (preg_match('/^\d+/', $params['categories'], $matches)) {
1854      $category_id = $matches[0];
1855
1856      $query = '
1857SELECT id, name, permalink
1858  FROM '.CATEGORIES_TABLE.'
1859  WHERE id = '.$category_id.'
1860;';
1861      $result = pwg_query($query);
1862      $category = pwg_db_fetch_assoc($result);
1863
1864      $url_params['section'] = 'categories';
1865      $url_params['category'] = $category;
1866    }
1867  }
1868
1869  // and now, let's create tag associations
1870  if (isset($params['tag_ids']) and !empty($params['tag_ids']))
1871  {
1872    set_tags(
1873      explode(',', $params['tag_ids']),
1874      $image_id
1875      );
1876  }
1877
1878  invalidate_user_cache();
1879
1880  return array(
1881    'image_id' => $image_id,
1882    'url' => make_picture_url($url_params),
1883    );
1884}
1885
1886function ws_images_addSimple($params, &$service)
1887{
1888  global $conf;
1889  if (!is_admin())
1890  {
1891    return new PwgError(401, 'Access denied');
1892  }
1893
1894  if (!$service->isPost())
1895  {
1896    return new PwgError(405, "This method requires HTTP POST");
1897  }
1898
1899  if (!isset($_FILES['image']))
1900  {
1901    return new PwgError(405, "The image (file) parameter is missing");
1902  }
1903
1904  $params['image_id'] = (int)$params['image_id'];
1905  if ($params['image_id'] > 0)
1906  {
1907    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1908
1909    $query='
1910SELECT *
1911  FROM '.IMAGES_TABLE.'
1912  WHERE id = '.$params['image_id'].'
1913;';
1914
1915    $image_row = pwg_db_fetch_assoc(pwg_query($query));
1916    if ($image_row == null)
1917    {
1918      return new PwgError(404, "image_id not found");
1919    }
1920  }
1921
1922  // category
1923  $params['category'] = (int)$params['category'];
1924  if ($params['category'] <= 0 and $params['image_id'] <= 0)
1925  {
1926    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
1927  }
1928
1929  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1930
1931  $image_id = add_uploaded_file(
1932    $_FILES['image']['tmp_name'],
1933    $_FILES['image']['name'],
1934    $params['category'] > 0 ? array($params['category']) : null,
1935    8,
1936    $params['image_id'] > 0 ? $params['image_id'] : null
1937    );
1938
1939  $info_columns = array(
1940    'name',
1941    'author',
1942    'comment',
1943    'level',
1944    'date_creation',
1945    );
1946
1947  foreach ($info_columns as $key)
1948  {
1949    if (isset($params[$key]))
1950    {
1951      $update[$key] = $params[$key];
1952    }
1953  }
1954
1955  if (count(array_keys($update)) > 0)
1956  {
1957    $update['id'] = $image_id;
1958
1959    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1960    mass_updates(
1961      IMAGES_TABLE,
1962      array(
1963        'primary' => array('id'),
1964        'update'  => array_diff(array_keys($update), array('id'))
1965        ),
1966      array($update)
1967      );
1968  }
1969
1970
1971  if (isset($params['tags']) and !empty($params['tags']))
1972  {
1973    $tag_ids = array();
1974    $tag_names = explode(',', $params['tags']);
1975    foreach ($tag_names as $tag_name)
1976    {
1977      $tag_id = tag_id_from_tag_name($tag_name);
1978      array_push($tag_ids, $tag_id);
1979    }
1980
1981    add_tags($tag_ids, array($image_id));
1982  }
1983
1984  $url_params = array('image_id' => $image_id);
1985
1986  if ($params['category'] > 0)
1987  {
1988    $query = '
1989SELECT id, name, permalink
1990  FROM '.CATEGORIES_TABLE.'
1991  WHERE id = '.$params['category'].'
1992;';
1993    $result = pwg_query($query);
1994    $category = pwg_db_fetch_assoc($result);
1995
1996    $url_params['section'] = 'categories';
1997    $url_params['category'] = $category;
1998  }
1999
2000  // update metadata from the uploaded file (exif/iptc), even if the sync
2001  // was already performed by add_uploaded_file().
2002
2003  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
2004  sync_metadata(array($image_id));
2005
2006  return array(
2007    'image_id' => $image_id,
2008    'url' => make_picture_url($url_params),
2009    );
2010}
2011
2012function ws_rates_delete($params, &$service)
2013{
2014  global $conf;
2015
2016  if (!$service->isPost())
2017  {
2018    return new PwgError(405, 'This method requires HTTP POST');
2019  }
2020
2021  if (!is_admin())
2022  {
2023    return new PwgError(401, 'Access denied');
2024  }
2025
2026  $user_id = (int)$params['user_id'];
2027  if ($user_id<=0)
2028  {
2029    return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid user_id');
2030  }
2031
2032  $query = '
2033DELETE FROM '.RATE_TABLE.'
2034  WHERE user_id='.$user_id;
2035
2036  if (!empty($params['anonymous_id']))
2037  {
2038    $query .= ' AND anonymous_id=\''.$params['anonymous_id'].'\'';
2039  }
2040
2041  $changes = pwg_db_changes(pwg_query($query));
2042  if ($changes)
2043  {
2044    include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
2045    update_rating_score();
2046  }
2047  return $changes;
2048}
2049
2050
2051/**
2052 * perform a login (web service method)
2053 */
2054function ws_session_login($params, &$service)
2055{
2056  global $conf;
2057
2058  if (!$service->isPost())
2059  {
2060    return new PwgError(405, "This method requires HTTP POST");
2061  }
2062  if (try_log_user($params['username'], $params['password'],false))
2063  {
2064    return true;
2065  }
2066  return new PwgError(999, 'Invalid username/password');
2067}
2068
2069
2070/**
2071 * performs a logout (web service method)
2072 */
2073function ws_session_logout($params, &$service)
2074{
2075  if (!is_a_guest())
2076  {
2077    logout_user();
2078  }
2079  return true;
2080}
2081
2082function ws_session_getStatus($params, &$service)
2083{
2084  global $user;
2085  $res = array();
2086  $res['username'] = is_a_guest() ? 'guest' : stripslashes($user['username']);
2087  foreach ( array('status', 'theme', 'language') as $k )
2088  {
2089    $res[$k] = $user[$k];
2090  }
2091  $res['pwg_token'] = get_pwg_token();
2092  $res['charset'] = get_pwg_charset();
2093
2094  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2095  $res['current_datetime'] = $dbnow;
2096
2097  return $res;
2098}
2099
2100
2101/**
2102 * returns a list of tags (web service method)
2103 */
2104function ws_tags_getList($params, &$service)
2105{
2106  $tags = get_available_tags();
2107  if ($params['sort_by_counter'])
2108  {
2109    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
2110  }
2111  else
2112  {
2113    usort($tags, 'tag_alpha_compare');
2114  }
2115  for ($i=0; $i<count($tags); $i++)
2116  {
2117    $tags[$i]['id'] = (int)$tags[$i]['id'];
2118    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
2119    $tags[$i]['url'] = make_index_url(
2120        array(
2121          'section'=>'tags',
2122          'tags'=>array($tags[$i])
2123        )
2124      );
2125  }
2126  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
2127}
2128
2129/**
2130 * returns the list of tags as you can see them in administration (web
2131 * service method).
2132 *
2133 * Only admin can run this method and permissions are not taken into
2134 * account.
2135 */
2136function ws_tags_getAdminList($params, &$service)
2137{
2138  if (!is_admin())
2139  {
2140    return new PwgError(401, 'Access denied');
2141  }
2142
2143  $tags = get_all_tags();
2144  return array(
2145    'tags' => new PwgNamedArray(
2146      $tags,
2147      'tag',
2148      array(
2149        'name',
2150        'id',
2151        'url_name',
2152        )
2153      )
2154    );
2155}
2156
2157/**
2158 * returns a list of images for tags (web service method)
2159 */
2160function ws_tags_getImages($params, &$service)
2161{
2162  global $conf;
2163
2164  // first build all the tag_ids we are interested in
2165  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
2166  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
2167  $tags_by_id = array();
2168  foreach( $tags as $tag )
2169  {
2170    $tags['id'] = (int)$tag['id'];
2171    $tags_by_id[ $tag['id'] ] = $tag;
2172  }
2173  unset($tags);
2174  $tag_ids = array_keys($tags_by_id);
2175
2176
2177  $where_clauses = ws_std_image_sql_filter($params);
2178  if (!empty($where_clauses))
2179  {
2180    $where_clauses = implode( ' AND ', $where_clauses);
2181  }
2182  $image_ids = get_image_ids_for_tags(
2183    $tag_ids,
2184    $params['tag_mode_and'] ? 'AND' : 'OR',
2185    $where_clauses,
2186    ws_std_image_sql_order($params) );
2187
2188
2189  $image_ids = array_slice($image_ids, (int)($params['per_page']*$params['page']), (int)$params['per_page'] );
2190
2191  $image_tag_map = array();
2192  if ( !empty($image_ids) and !$params['tag_mode_and'] )
2193  { // build list of image ids with associated tags per image
2194    $query = '
2195SELECT image_id, GROUP_CONCAT(tag_id) AS tag_ids
2196  FROM '.IMAGE_TAG_TABLE.'
2197  WHERE tag_id IN ('.implode(',',$tag_ids).') AND image_id IN ('.implode(',',$image_ids).')
2198  GROUP BY image_id';
2199    $result = pwg_query($query);
2200    while ( $row=pwg_db_fetch_assoc($result) )
2201    {
2202      $row['image_id'] = (int)$row['image_id'];
2203      array_push( $image_ids, $row['image_id'] );
2204      $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
2205    }
2206  }
2207
2208  $images = array();
2209  if (!empty($image_ids))
2210  {
2211    $rank_of = array_flip($image_ids);
2212    $result = pwg_query('
2213SELECT * FROM '.IMAGES_TABLE.'
2214  WHERE id IN ('.implode(',',$image_ids).')');
2215    while ($row = pwg_db_fetch_assoc($result))
2216    {
2217      $image = array();
2218      $image['rank'] = $rank_of[ $row['id'] ];
2219      foreach ( array('id', 'width', 'height', 'hit') as $k )
2220      {
2221        if (isset($row[$k]))
2222        {
2223          $image[$k] = (int)$row[$k];
2224        }
2225      }
2226      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
2227      {
2228        $image[$k] = $row[$k];
2229      }
2230      $image = array_merge( $image, ws_std_get_urls($row) );
2231
2232      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
2233      $image_tags = array();
2234      foreach ($image_tag_ids as $tag_id)
2235      {
2236        $url = make_index_url(
2237                 array(
2238                  'section'=>'tags',
2239                  'tags'=> array($tags_by_id[$tag_id])
2240                )
2241              );
2242        $page_url = make_picture_url(
2243                 array(
2244                  'section'=>'tags',
2245                  'tags'=> array($tags_by_id[$tag_id]),
2246                  'image_id' => $row['id'],
2247                  'image_file' => $row['file'],
2248                )
2249              );
2250        array_push($image_tags, array(
2251                'id' => (int)$tag_id,
2252                'url' => $url,
2253                'page_url' => $page_url,
2254              )
2255            );
2256      }
2257      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
2258              array('id','url_name','url','page_url')
2259            );
2260      array_push($images, $image);
2261    }
2262    usort($images, 'rank_compare');
2263    unset($rank_of);
2264  }
2265
2266  return array( 'images' =>
2267    array (
2268      WS_XML_ATTRIBUTES =>
2269        array(
2270            'page' => $params['page'],
2271            'per_page' => $params['per_page'],
2272            'count' => count($images)
2273          ),
2274       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
2275          ws_std_get_image_xml_attributes() )
2276      )
2277    );
2278}
2279
2280function ws_categories_add($params, &$service)
2281{
2282  if (!is_admin())
2283  {
2284    return new PwgError(401, 'Access denied');
2285  }
2286
2287  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2288
2289  $options = array();
2290  if (!empty($params['status']) and in_array($params['status'], array('private','public')))
2291  {
2292    $options['status'] = $params['status'];
2293  }
2294 
2295  if (!empty($params['visible']) and in_array($params['visible'], array('true','false')))
2296  {
2297    $options['visible'] = get_boolean($params['visible']);
2298  }
2299 
2300  if (!empty($params['commentable']) and in_array($params['commentable'], array('true','false')) )
2301  {
2302    $options['commentable'] = get_boolean($params['commentable']);
2303  }
2304 
2305  if (!empty($params['comment']))
2306  {
2307    $options['comment'] = $params['comment'];
2308  }
2309 
2310
2311  $creation_output = create_virtual_category(
2312    $params['name'],
2313    $params['parent'],
2314    $options
2315    );
2316
2317  if (isset($creation_output['error']))
2318  {
2319    return new PwgError(500, $creation_output['error']);
2320  }
2321
2322  invalidate_user_cache();
2323
2324  return $creation_output;
2325}
2326
2327function ws_tags_add($params, &$service)
2328{
2329  if (!is_admin())
2330  {
2331    return new PwgError(401, 'Access denied');
2332  }
2333
2334  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2335
2336  $creation_output = create_tag($params['name']);
2337
2338  if (isset($creation_output['error']))
2339  {
2340    return new PwgError(500, $creation_output['error']);
2341  }
2342
2343  return $creation_output;
2344}
2345
2346function ws_images_exist($params, &$service)
2347{
2348  ws_logfile(__FUNCTION__.' '.var_export($params, true));
2349
2350  global $conf;
2351
2352  if (!is_admin())
2353  {
2354    return new PwgError(401, 'Access denied');
2355  }
2356
2357  $split_pattern = '/[\s,;\|]/';
2358
2359  if ('md5sum' == $conf['uniqueness_mode'])
2360  {
2361    // search among photos the list of photos already added, based on md5sum
2362    // list
2363    $md5sums = preg_split(
2364      $split_pattern,
2365      $params['md5sum_list'],
2366      -1,
2367      PREG_SPLIT_NO_EMPTY
2368    );
2369
2370    $query = '
2371SELECT
2372    id,
2373    md5sum
2374  FROM '.IMAGES_TABLE.'
2375  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
2376;';
2377    $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
2378
2379    $result = array();
2380
2381    foreach ($md5sums as $md5sum)
2382    {
2383      $result[$md5sum] = null;
2384      if (isset($id_of_md5[$md5sum]))
2385      {
2386        $result[$md5sum] = $id_of_md5[$md5sum];
2387      }
2388    }
2389  }
2390
2391  if ('filename' == $conf['uniqueness_mode'])
2392  {
2393    // search among photos the list of photos already added, based on
2394    // filename list
2395    $filenames = preg_split(
2396      $split_pattern,
2397      $params['filename_list'],
2398      -1,
2399      PREG_SPLIT_NO_EMPTY
2400    );
2401
2402    $query = '
2403SELECT
2404    id,
2405    file
2406  FROM '.IMAGES_TABLE.'
2407  WHERE file IN (\''.implode("','", $filenames).'\')
2408;';
2409    $id_of_filename = simple_hash_from_query($query, 'file', 'id');
2410
2411    $result = array();
2412
2413    foreach ($filenames as $filename)
2414    {
2415      $result[$filename] = null;
2416      if (isset($id_of_filename[$filename]))
2417      {
2418        $result[$filename] = $id_of_filename[$filename];
2419      }
2420    }
2421  }
2422
2423  return $result;
2424}
2425
2426function ws_images_checkFiles($params, &$service)
2427{
2428  ws_logfile(__FUNCTION__.', input :  '.var_export($params, true));
2429
2430  if (!is_admin())
2431  {
2432    return new PwgError(401, 'Access denied');
2433  }
2434
2435  // input parameters
2436  //
2437  // image_id
2438  // thumbnail_sum
2439  // file_sum
2440  // high_sum
2441
2442  $params['image_id'] = (int)$params['image_id'];
2443  if ($params['image_id'] <= 0)
2444  {
2445    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2446  }
2447
2448  $query = '
2449SELECT
2450    path
2451  FROM '.IMAGES_TABLE.'
2452  WHERE id = '.$params['image_id'].'
2453;';
2454  $result = pwg_query($query);
2455  if (pwg_db_num_rows($result) == 0)
2456  {
2457    return new PwgError(404, "image_id not found");
2458  }
2459  list($path) = pwg_db_fetch_row($result);
2460
2461  $ret = array();
2462
2463  if (isset($params['thumbnail_sum']))
2464  {
2465    // We always say the thumbnail is equal to create no reaction on the
2466    // other side. Since Piwigo 2.4 and derivatives, the thumbnails and web
2467    // sizes are always generated by Piwigo
2468    $ret['thumbnail'] = 'equals';
2469  }
2470
2471  if (isset($params['high_sum']))
2472  {
2473    $ret['file'] = 'equals';
2474    $compare_type = 'high';
2475  }
2476  elseif (isset($params['file_sum']))
2477  {
2478    $compare_type = 'file';
2479  }
2480
2481  if (isset($compare_type))
2482  {
2483    ws_logfile(__FUNCTION__.', md5_file($path) = '.md5_file($path));
2484    if (md5_file($path) != $params[$compare_type.'_sum'])
2485    {
2486      $ret[$compare_type] = 'differs';
2487    }
2488    else
2489    {
2490      $ret[$compare_type] = 'equals';
2491    }
2492  }
2493
2494  ws_logfile(__FUNCTION__.', output :  '.var_export($ret, true));
2495
2496  return $ret;
2497}
2498
2499function ws_images_setInfo($params, &$service)
2500{
2501  global $conf;
2502  if (!is_admin())
2503  {
2504    return new PwgError(401, 'Access denied');
2505  }
2506
2507  if (!$service->isPost())
2508  {
2509    return new PwgError(405, "This method requires HTTP POST");
2510  }
2511
2512  $params['image_id'] = (int)$params['image_id'];
2513  if ($params['image_id'] <= 0)
2514  {
2515    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2516  }
2517
2518  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2519
2520  $query='
2521SELECT *
2522  FROM '.IMAGES_TABLE.'
2523  WHERE id = '.$params['image_id'].'
2524;';
2525
2526  $image_row = pwg_db_fetch_assoc(pwg_query($query));
2527  if ($image_row == null)
2528  {
2529    return new PwgError(404, "image_id not found");
2530  }
2531
2532  // database registration
2533  $update = array();
2534
2535  $info_columns = array(
2536    'name',
2537    'author',
2538    'comment',
2539    'level',
2540    'date_creation',
2541    );
2542
2543  foreach ($info_columns as $key)
2544  {
2545    if (isset($params[$key]))
2546    {
2547      if ('fill_if_empty' == $params['single_value_mode'])
2548      {
2549        if (empty($image_row[$key]))
2550        {
2551          $update[$key] = $params[$key];
2552        }
2553      }
2554      elseif ('replace' == $params['single_value_mode'])
2555      {
2556        $update[$key] = $params[$key];
2557      }
2558      else
2559      {
2560        return new PwgError(
2561          500,
2562          '[ws_images_setInfo]'
2563          .' invalid parameter single_value_mode "'.$params['single_value_mode'].'"'
2564          .', possible values are {fill_if_empty, replace}.'
2565          );
2566      }
2567    }
2568  }
2569
2570  if (isset($params['file']))
2571  {
2572    if (!empty($image_row['storage_category_id']))
2573    {
2574      return new PwgError(500, '[ws_images_setInfo] updating "file" is forbidden on photos added by synchronization');
2575    }
2576
2577    $update['file'] = $params['file'];
2578  }
2579
2580  if (count(array_keys($update)) > 0)
2581  {
2582    $update['id'] = $params['image_id'];
2583
2584    mass_updates(
2585      IMAGES_TABLE,
2586      array(
2587        'primary' => array('id'),
2588        'update'  => array_diff(array_keys($update), array('id'))
2589        ),
2590      array($update)
2591      );
2592  }
2593
2594  if (isset($params['categories']))
2595  {
2596    ws_add_image_category_relations(
2597      $params['image_id'],
2598      $params['categories'],
2599      ('replace' == $params['multiple_value_mode'] ? true : false)
2600      );
2601  }
2602
2603  // and now, let's create tag associations
2604  if (isset($params['tag_ids']))
2605  {
2606    $tag_ids = explode(',', $params['tag_ids']);
2607
2608    if ('replace' == $params['multiple_value_mode'])
2609    {
2610      set_tags(
2611        $tag_ids,
2612        $params['image_id']
2613        );
2614    }
2615    elseif ('append' == $params['multiple_value_mode'])
2616    {
2617      add_tags(
2618        $tag_ids,
2619        array($params['image_id'])
2620        );
2621    }
2622    else
2623    {
2624      return new PwgError(
2625        500,
2626        '[ws_images_setInfo]'
2627        .' invalid parameter multiple_value_mode "'.$params['multiple_value_mode'].'"'
2628        .', possible values are {replace, append}.'
2629        );
2630    }
2631  }
2632
2633  invalidate_user_cache();
2634}
2635
2636function ws_images_delete($params, &$service)
2637{
2638  global $conf;
2639  if (!is_admin())
2640  {
2641    return new PwgError(401, 'Access denied');
2642  }
2643
2644  if (!$service->isPost())
2645  {
2646    return new PwgError(405, "This method requires HTTP POST");
2647  }
2648
2649  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2650  {
2651    return new PwgError(403, 'Invalid security token');
2652  }
2653
2654  $params['image_id'] = preg_split(
2655    '/[\s,;\|]/',
2656    $params['image_id'],
2657    -1,
2658    PREG_SPLIT_NO_EMPTY
2659    );
2660  $params['image_id'] = array_map('intval', $params['image_id']);
2661
2662  $image_ids = array();
2663  foreach ($params['image_id'] as $image_id)
2664  {
2665    if ($image_id > 0)
2666    {
2667      array_push($image_ids, $image_id);
2668    }
2669  }
2670
2671  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2672  delete_elements($image_ids, true);
2673}
2674
2675function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
2676{
2677  // let's add links between the image and the categories
2678  //
2679  // $params['categories'] should look like 123,12;456,auto;789 which means:
2680  //
2681  // 1. associate with category 123 on rank 12
2682  // 2. associate with category 456 on automatic rank
2683  // 3. associate with category 789 on automatic rank
2684  $cat_ids = array();
2685  $rank_on_category = array();
2686  $search_current_ranks = false;
2687
2688  $tokens = explode(';', $categories_string);
2689  foreach ($tokens as $token)
2690  {
2691    @list($cat_id, $rank) = explode(',', $token);
2692
2693    if (!preg_match('/^\d+$/', $cat_id))
2694    {
2695      continue;
2696    }
2697
2698    array_push($cat_ids, $cat_id);
2699
2700    if (!isset($rank))
2701    {
2702      $rank = 'auto';
2703    }
2704    $rank_on_category[$cat_id] = $rank;
2705
2706    if ($rank == 'auto')
2707    {
2708      $search_current_ranks = true;
2709    }
2710  }
2711
2712  $cat_ids = array_unique($cat_ids);
2713
2714  if (count($cat_ids) == 0)
2715  {
2716    return new PwgError(
2717      500,
2718      '[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
2719      );
2720  }
2721
2722  $query = '
2723SELECT
2724    id
2725  FROM '.CATEGORIES_TABLE.'
2726  WHERE id IN ('.implode(',', $cat_ids).')
2727;';
2728  $db_cat_ids = array_from_query($query, 'id');
2729
2730  $unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
2731  if (count($unknown_cat_ids) != 0)
2732  {
2733    return new PwgError(
2734      500,
2735      '[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
2736      );
2737  }
2738
2739  $to_update_cat_ids = array();
2740
2741  // in case of replace mode, we first check the existing associations
2742  $query = '
2743SELECT
2744    category_id
2745  FROM '.IMAGE_CATEGORY_TABLE.'
2746  WHERE image_id = '.$image_id.'
2747;';
2748  $existing_cat_ids = array_from_query($query, 'category_id');
2749
2750  if ($replace_mode)
2751  {
2752    $to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
2753    if (count($to_remove_cat_ids) > 0)
2754    {
2755      $query = '
2756DELETE
2757  FROM '.IMAGE_CATEGORY_TABLE.'
2758  WHERE image_id = '.$image_id.'
2759    AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
2760;';
2761      pwg_query($query);
2762      update_category($to_remove_cat_ids);
2763    }
2764  }
2765
2766  $new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
2767  if (count($new_cat_ids) == 0)
2768  {
2769    return true;
2770  }
2771
2772  if ($search_current_ranks)
2773  {
2774    $query = '
2775SELECT
2776    category_id,
2777    MAX(rank) AS max_rank
2778  FROM '.IMAGE_CATEGORY_TABLE.'
2779  WHERE rank IS NOT NULL
2780    AND category_id IN ('.implode(',', $new_cat_ids).')
2781  GROUP BY category_id
2782;';
2783    $current_rank_of = simple_hash_from_query(
2784      $query,
2785      'category_id',
2786      'max_rank'
2787      );
2788
2789    foreach ($new_cat_ids as $cat_id)
2790    {
2791      if (!isset($current_rank_of[$cat_id]))
2792      {
2793        $current_rank_of[$cat_id] = 0;
2794      }
2795
2796      if ('auto' == $rank_on_category[$cat_id])
2797      {
2798        $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
2799      }
2800    }
2801  }
2802
2803  $inserts = array();
2804
2805  foreach ($new_cat_ids as $cat_id)
2806  {
2807    array_push(
2808      $inserts,
2809      array(
2810        'image_id' => $image_id,
2811        'category_id' => $cat_id,
2812        'rank' => $rank_on_category[$cat_id],
2813        )
2814      );
2815  }
2816
2817  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2818  mass_inserts(
2819    IMAGE_CATEGORY_TABLE,
2820    array_keys($inserts[0]),
2821    $inserts
2822    );
2823
2824  update_category($new_cat_ids);
2825}
2826
2827function ws_categories_setInfo($params, &$service)
2828{
2829  global $conf;
2830  if (!is_admin())
2831  {
2832    return new PwgError(401, 'Access denied');
2833  }
2834
2835  if (!$service->isPost())
2836  {
2837    return new PwgError(405, "This method requires HTTP POST");
2838  }
2839
2840  // category_id
2841  // name
2842  // comment
2843
2844  $params['category_id'] = (int)$params['category_id'];
2845  if ($params['category_id'] <= 0)
2846  {
2847    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2848  }
2849
2850  // database registration
2851  $update = array(
2852    'id' => $params['category_id'],
2853    );
2854
2855  $info_columns = array(
2856    'name',
2857    'comment',
2858    );
2859
2860  $perform_update = false;
2861  foreach ($info_columns as $key)
2862  {
2863    if (isset($params[$key]))
2864    {
2865      $perform_update = true;
2866      $update[$key] = $params[$key];
2867    }
2868  }
2869
2870  if ($perform_update)
2871  {
2872    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2873    mass_updates(
2874      CATEGORIES_TABLE,
2875      array(
2876        'primary' => array('id'),
2877        'update'  => array_diff(array_keys($update), array('id'))
2878        ),
2879      array($update)
2880      );
2881  }
2882
2883}
2884
2885function ws_categories_setRepresentative($params, &$service)
2886{
2887  global $conf;
2888
2889  if (!is_admin())
2890  {
2891    return new PwgError(401, 'Access denied');
2892  }
2893
2894  if (!$service->isPost())
2895  {
2896    return new PwgError(405, "This method requires HTTP POST");
2897  }
2898
2899  // category_id
2900  // image_id
2901
2902  $params['category_id'] = (int)$params['category_id'];
2903  if ($params['category_id'] <= 0)
2904  {
2905    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2906  }
2907
2908  // does the category really exist?
2909  $query='
2910SELECT
2911    *
2912  FROM '.CATEGORIES_TABLE.'
2913  WHERE id = '.$params['category_id'].'
2914;';
2915  $row = pwg_db_fetch_assoc(pwg_query($query));
2916  if ($row == null)
2917  {
2918    return new PwgError(404, "category_id not found");
2919  }
2920
2921  $params['image_id'] = (int)$params['image_id'];
2922  if ($params['image_id'] <= 0)
2923  {
2924    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2925  }
2926
2927  // does the image really exist?
2928  $query='
2929SELECT
2930    *
2931  FROM '.IMAGES_TABLE.'
2932  WHERE id = '.$params['image_id'].'
2933;';
2934
2935  $row = pwg_db_fetch_assoc(pwg_query($query));
2936  if ($row == null)
2937  {
2938    return new PwgError(404, "image_id not found");
2939  }
2940
2941  // apply change
2942  $query = '
2943UPDATE '.CATEGORIES_TABLE.'
2944  SET representative_picture_id = '.$params['image_id'].'
2945  WHERE id = '.$params['category_id'].'
2946;';
2947  pwg_query($query);
2948
2949  $query = '
2950UPDATE '.USER_CACHE_CATEGORIES_TABLE.'
2951  SET user_representative_picture_id = NULL
2952  WHERE cat_id = '.$params['category_id'].'
2953;';
2954  pwg_query($query);
2955}
2956
2957function ws_categories_delete($params, &$service)
2958{
2959  global $conf;
2960  if (!is_admin())
2961  {
2962    return new PwgError(401, 'Access denied');
2963  }
2964
2965  if (!$service->isPost())
2966  {
2967    return new PwgError(405, "This method requires HTTP POST");
2968  }
2969
2970  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2971  {
2972    return new PwgError(403, 'Invalid security token');
2973  }
2974
2975  $modes = array('no_delete', 'delete_orphans', 'force_delete');
2976  if (!in_array($params['photo_deletion_mode'], $modes))
2977  {
2978    return new PwgError(
2979      500,
2980      '[ws_categories_delete]'
2981      .' invalid parameter photo_deletion_mode "'.$params['photo_deletion_mode'].'"'
2982      .', possible values are {'.implode(', ', $modes).'}.'
2983      );
2984  }
2985
2986  $params['category_id'] = preg_split(
2987    '/[\s,;\|]/',
2988    $params['category_id'],
2989    -1,
2990    PREG_SPLIT_NO_EMPTY
2991    );
2992  $params['category_id'] = array_map('intval', $params['category_id']);
2993
2994  $category_ids = array();
2995  foreach ($params['category_id'] as $category_id)
2996  {
2997    if ($category_id > 0)
2998    {
2999      array_push($category_ids, $category_id);
3000    }
3001  }
3002
3003  if (count($category_ids) == 0)
3004  {
3005    return;
3006  }
3007
3008  $query = '
3009SELECT id
3010  FROM '.CATEGORIES_TABLE.'
3011  WHERE id IN ('.implode(',', $category_ids).')
3012;';
3013  $category_ids = array_from_query($query, 'id');
3014
3015  if (count($category_ids) == 0)
3016  {
3017    return;
3018  }
3019
3020  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3021  delete_categories($category_ids, $params['photo_deletion_mode']);
3022  update_global_rank();
3023}
3024
3025function ws_categories_move($params, &$service)
3026{
3027  global $conf, $page;
3028
3029  if (!is_admin())
3030  {
3031    return new PwgError(401, 'Access denied');
3032  }
3033
3034  if (!$service->isPost())
3035  {
3036    return new PwgError(405, "This method requires HTTP POST");
3037  }
3038
3039  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3040  {
3041    return new PwgError(403, 'Invalid security token');
3042  }
3043
3044  $params['category_id'] = preg_split(
3045    '/[\s,;\|]/',
3046    $params['category_id'],
3047    -1,
3048    PREG_SPLIT_NO_EMPTY
3049    );
3050  $params['category_id'] = array_map('intval', $params['category_id']);
3051
3052  $category_ids = array();
3053  foreach ($params['category_id'] as $category_id)
3054  {
3055    if ($category_id > 0)
3056    {
3057      array_push($category_ids, $category_id);
3058    }
3059  }
3060
3061  if (count($category_ids) == 0)
3062  {
3063    return new PwgError(403, 'Invalid category_id input parameter, no category to move');
3064  }
3065
3066  // we can't move physical categories
3067  $categories_in_db = array();
3068
3069  $query = '
3070SELECT
3071    id,
3072    name,
3073    dir
3074  FROM '.CATEGORIES_TABLE.'
3075  WHERE id IN ('.implode(',', $category_ids).')
3076;';
3077  $result = pwg_query($query);
3078  while ($row = pwg_db_fetch_assoc($result))
3079  {
3080    $categories_in_db[$row['id']] = $row;
3081    // we break on error at first physical category detected
3082    if (!empty($row['dir']))
3083    {
3084      $row['name'] = strip_tags(
3085        trigger_event(
3086          'render_category_name',
3087          $row['name'],
3088          'ws_categories_move'
3089          )
3090        );
3091
3092      return new PwgError(
3093        403,
3094        sprintf(
3095          'Category %s (%u) is not a virtual category, you cannot move it',
3096          $row['name'],
3097          $row['id']
3098          )
3099        );
3100    }
3101  }
3102
3103  if (count($categories_in_db) != count($category_ids))
3104  {
3105    $unknown_category_ids = array_diff($category_ids, array_keys($categories_in_db));
3106
3107    return new PwgError(
3108      403,
3109      sprintf(
3110        'Category %u does not exist',
3111        $unknown_category_ids[0]
3112        )
3113      );
3114  }
3115
3116  // does this parent exists? This check should be made in the
3117  // move_categories function, not here
3118  //
3119  // 0 as parent means "move categories at gallery root"
3120  if (!is_numeric($params['parent']))
3121  {
3122    return new PwgError(403, 'Invalid parent input parameter');
3123  }
3124
3125  if (0 != $params['parent']) {
3126    $params['parent'] = intval($params['parent']);
3127    $subcat_ids = get_subcat_ids(array($params['parent']));
3128    if (count($subcat_ids) == 0)
3129    {
3130      return new PwgError(403, 'Unknown parent category id');
3131    }
3132  }
3133
3134  $page['infos'] = array();
3135  $page['errors'] = array();
3136  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3137  move_categories($category_ids, $params['parent']);
3138  invalidate_user_cache();
3139
3140  if (count($page['errors']) != 0)
3141  {
3142    return new PwgError(403, implode('; ', $page['errors']));
3143  }
3144}
3145
3146function ws_logfile($string)
3147{
3148  global $conf;
3149
3150  if (!$conf['ws_enable_log']) {
3151    return true;
3152  }
3153
3154  file_put_contents(
3155    $conf['ws_log_filepath'],
3156    '['.date('c').'] '.$string."\n",
3157    FILE_APPEND
3158    );
3159}
3160
3161function ws_images_checkUpload($params, &$service)
3162{
3163  global $conf;
3164
3165  if (!is_admin())
3166  {
3167    return new PwgError(401, 'Access denied');
3168  }
3169
3170  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
3171  $ret['message'] = ready_for_upload_message();
3172  $ret['ready_for_upload'] = true;
3173
3174  if (!empty($ret['message']))
3175  {
3176    $ret['ready_for_upload'] = false;
3177  }
3178
3179  return $ret;
3180}
3181
3182function ws_plugins_getList($params, &$service)
3183{
3184  global $conf;
3185
3186  if (!is_admin())
3187  {
3188    return new PwgError(401, 'Access denied');
3189  }
3190
3191  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3192  $plugins = new plugins();
3193  $plugins->sort_fs_plugins('name');
3194  $plugin_list = array();
3195
3196  foreach($plugins->fs_plugins as $plugin_id => $fs_plugin)
3197  {
3198    if (isset($plugins->db_plugins_by_id[$plugin_id]))
3199    {
3200      $state = $plugins->db_plugins_by_id[$plugin_id]['state'];
3201    }
3202    else
3203    {
3204      $state = 'uninstalled';
3205    }
3206
3207    array_push(
3208      $plugin_list,
3209      array(
3210        'id' => $plugin_id,
3211        'name' => $fs_plugin['name'],
3212        'version' => $fs_plugin['version'],
3213        'state' => $state,
3214        'description' => $fs_plugin['description'],
3215        )
3216      );
3217  }
3218
3219  return $plugin_list;
3220}
3221
3222function ws_plugins_performAction($params, &$service)
3223{
3224  global $template;
3225
3226  if (!is_admin())
3227  {
3228    return new PwgError(401, 'Access denied');
3229  }
3230
3231  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3232  {
3233    return new PwgError(403, 'Invalid security token');
3234  }
3235
3236  define('IN_ADMIN', true);
3237  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3238  $plugins = new plugins();
3239  $errors = $plugins->perform_action($params['action'], $params['plugin']);
3240
3241
3242  if (!empty($errors))
3243  {
3244    return new PwgError(500, $errors);
3245  }
3246  else
3247  {
3248    if (in_array($params['action'], array('activate', 'deactivate')))
3249    {
3250      $template->delete_compiled_templates();
3251    }
3252    return true;
3253  }
3254}
3255
3256function ws_themes_performAction($params, &$service)
3257{
3258  global $template;
3259
3260  if (!is_admin())
3261  {
3262    return new PwgError(401, 'Access denied');
3263  }
3264
3265  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3266  {
3267    return new PwgError(403, 'Invalid security token');
3268  }
3269
3270  define('IN_ADMIN', true);
3271  include_once(PHPWG_ROOT_PATH.'admin/include/themes.class.php');
3272  $themes = new themes();
3273  $errors = $themes->perform_action($params['action'], $params['theme']);
3274
3275  if (!empty($errors))
3276  {
3277    return new PwgError(500, $errors);
3278  }
3279  else
3280  {
3281    if (in_array($params['action'], array('activate', 'deactivate')))
3282    {
3283      $template->delete_compiled_templates();
3284    }
3285    return true;
3286  }
3287}
3288
3289function ws_extensions_update($params, &$service)
3290{
3291  if (!is_webmaster())
3292  {
3293    return new PwgError(401, l10n('Webmaster status is required.'));
3294  }
3295
3296  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3297  {
3298    return new PwgError(403, 'Invalid security token');
3299  }
3300
3301  if (empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3302  {
3303    return new PwgError(403, "invalid extension type");
3304  }
3305
3306  if (empty($params['id']) or empty($params['revision']))
3307  {
3308    return new PwgError(null, 'Wrong parameters');
3309  }
3310
3311  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3312  include_once(PHPWG_ROOT_PATH.'admin/include/'.$params['type'].'.class.php');
3313
3314  $type = $params['type'];
3315  $extension_id = $params['id'];
3316  $revision = $params['revision'];
3317
3318  $extension = new $type();
3319
3320  if ($type == 'plugins')
3321  {
3322    if (isset($extension->db_plugins_by_id[$extension_id]) and $extension->db_plugins_by_id[$extension_id]['state'] == 'active')
3323    {
3324      $extension->perform_action('deactivate', $extension_id);
3325
3326      redirect(PHPWG_ROOT_PATH
3327        . 'ws.php'
3328        . '?method=pwg.extensions.update'
3329        . '&type=plugins'
3330        . '&id=' . $extension_id
3331        . '&revision=' . $revision
3332        . '&reactivate=true'
3333        . '&pwg_token=' . get_pwg_token()
3334        . '&format=json'
3335      );
3336    }
3337
3338    $upgrade_status = $extension->extract_plugin_files('upgrade', $revision, $extension_id);
3339    $extension_name = $extension->fs_plugins[$extension_id]['name'];
3340
3341    if (isset($params['reactivate']))
3342    {
3343      $extension->perform_action('activate', $extension_id);
3344    }
3345  }
3346  elseif ($type == 'themes')
3347  {
3348    $upgrade_status = $extension->extract_theme_files('upgrade', $revision, $extension_id);
3349    $extension_name = $extension->fs_themes[$extension_id]['name'];
3350  }
3351  elseif ($type == 'languages')
3352  {
3353    $upgrade_status = $extension->extract_language_files('upgrade', $revision, $extension_id);
3354    $extension_name = $extension->fs_languages[$extension_id]['name'];
3355  }
3356
3357  global $template;
3358  $template->delete_compiled_templates();
3359
3360  switch ($upgrade_status)
3361  {
3362    case 'ok':
3363      return sprintf(l10n('%s has been successfully updated.'), $extension_name);
3364
3365    case 'temp_path_error':
3366      return new PwgError(null, l10n('Can\'t create temporary file.'));
3367
3368    case 'dl_archive_error':
3369      return new PwgError(null, l10n('Can\'t download archive.'));
3370
3371    case 'archive_error':
3372      return new PwgError(null, l10n('Can\'t read or extract archive.'));
3373
3374    default:
3375      return new PwgError(null, sprintf(l10n('An error occured during extraction (%s).'), $upgrade_status));
3376  }
3377}
3378
3379function ws_extensions_ignoreupdate($params, &$service)
3380{
3381  global $conf;
3382
3383  define('IN_ADMIN', true);
3384  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3385
3386  if (!is_webmaster())
3387  {
3388    return new PwgError(401, 'Access denied');
3389  }
3390
3391  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3392  {
3393    return new PwgError(403, 'Invalid security token');
3394  }
3395
3396  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3397
3398  // Reset ignored extension
3399  if ($params['reset'])
3400  {
3401    if (!empty($params['type']) and isset($conf['updates_ignored'][$params['type']]))
3402    {
3403      $conf['updates_ignored'][$params['type']] = array();
3404    }
3405    else
3406    {
3407      $conf['updates_ignored'] = array(
3408        'plugins'=>array(),
3409        'themes'=>array(),
3410        'languages'=>array()
3411      );
3412    }
3413    conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3414    unset($_SESSION['extensions_need_update']);
3415    return true;
3416  }
3417
3418  if (empty($params['id']) or empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3419  {
3420    return new PwgError(403, 'Invalid parameters');
3421  }
3422
3423  // Add or remove extension from ignore list
3424  if (!in_array($params['id'], $conf['updates_ignored'][$params['type']]))
3425  {
3426    array_push($conf['updates_ignored'][$params['type']], $params['id']);
3427  }
3428  conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3429  unset($_SESSION['extensions_need_update']);
3430  return true;
3431}
3432
3433function ws_extensions_checkupdates($params, &$service)
3434{
3435  global $conf;
3436
3437  define('IN_ADMIN', true);
3438  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3439  include_once(PHPWG_ROOT_PATH.'admin/include/updates.class.php');
3440  $update = new updates();
3441
3442  if (!is_admin())
3443  {
3444    return new PwgError(401, 'Access denied');
3445  }
3446
3447  $result = array();
3448
3449  if (!isset($_SESSION['need_update']))
3450    $update->check_piwigo_upgrade();
3451
3452  $result['piwigo_need_update'] = $_SESSION['need_update'];
3453
3454  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3455
3456  if (!isset($_SESSION['extensions_need_update']))
3457    $update->check_extensions();
3458  else
3459    $update->check_updated_extensions();
3460
3461  if (!is_array($_SESSION['extensions_need_update']))
3462    $result['ext_need_update'] = null;
3463  else
3464    $result['ext_need_update'] = !empty($_SESSION['extensions_need_update']);
3465
3466  return $result;
3467}
3468?>
Note: See TracBrowser for help on using the repository browser.