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

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

small fix on element_url returned from web service calls (now coherent with picture.php)

  • Property svn:eol-style set to LF
File size: 84.5 KB
RevLine 
[1698]1<?php
2// +-----------------------------------------------------------------------+
[8728]3// | Piwigo - a PHP based photo gallery                                    |
[2297]4// +-----------------------------------------------------------------------+
[12922]5// | Copyright(C) 2008-2012 Piwigo Team                  http://piwigo.org |
[2297]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// +-----------------------------------------------------------------------+
[1698]23
24/**** IMPLEMENTATION OF WEB SERVICE METHODS ***********************************/
25
26/**
[1768]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{
[2572]32  global $conf;
[2119]33
[1849]34  if ( strpos($methodName,'reflection.')===0 )
35  { // OK for reflection
36    return $res;
37  }
[2119]38
[1849]39  if ( !is_autorize_status(ACCESS_GUEST) and
40      strpos($methodName,'pwg.session.')!==0 )
[1768]41  {
[1849]42    return new PwgError(401, 'Access denied');
43  }
[2119]44
[1768]45  return $res;
46}
47
48/**
[1698]49 * returns a "standard" (for our web service) array of sql where clauses that
[1711]50 * filters the images (images table only)
51 */
[1698]52function ws_std_image_sql_filter( $params, $tbl_name='' )
53{
54  $clauses = array();
55  if ( is_numeric($params['f_min_rate']) )
56  {
[11893]57    $clauses[] = $tbl_name.'rating_score>'.$params['f_min_rate'];
[1698]58  }
59  if ( is_numeric($params['f_max_rate']) )
60  {
[11893]61    $clauses[] = $tbl_name.'rating_score<='.$params['f_max_rate'];
[1698]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  }
[9576]71  if ( isset($params['f_min_date_available']) )
[1698]72  {
[9576]73    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_available']."'";
[1698]74  }
[9576]75  if ( isset($params['f_max_date_available']) )
[1698]76  {
[9576]77    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_available']."'";
[1698]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  }
[12865]95  if (is_numeric($params['f_max_level']) )
[1698]96  {
[12865]97    $clauses[] = $tbl_name.'level <= '.$params['f_max_level'];
[1698]98  }
99  return $clauses;
100}
101
102/**
103 * returns a "standard" (for our web service) ORDER BY sql clause for images
[1711]104 */
[1698]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':
[4367]124        $matches[1][$i] = DB_RANDOM_FUNCTION.'()'; break;
[1698]125    }
[11893]126    $sortable_fields = array('id', 'file', 'name', 'hit', 'rating_score',
[4367]127      'date_creation', 'date_available', DB_RANDOM_FUNCTION.'()' );
[1698]128    if ( in_array($matches[1][$i], $sortable_fields) )
129    {
130      if (!empty($ret))
131        $ret .= ', ';
[4367]132      if ($matches[1][$i] != DB_RANDOM_FUNCTION.'()' )
[1698]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
[1711]146 */
[1698]147function ws_std_get_urls($image_row)
148{
[12796]149  $ret = array();
[12865]150
[12855]151  $src_image = new SrcImage($image_row);
152
[17469]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
[1698]162  {
[12796]163    $ret['element_url'] = get_element_url($image_row);
[1698]164  }
[12865]165
[12855]166  $derivatives = DerivativeImage::get_all($src_image);
[12796]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;;
[1698]175  return $ret;
176}
177
[1845]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(
[12796]185    'id','element_url', 'file','width','height','hit','date_available','date_creation'
[1845]186    );
187}
[1698]188
[12865]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) );
[17017]215
216  if (0 == $image_count)
217  {
218    return array();
219  }
220
[12865]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';
[13544]235  if ( !empty($params['ids']) )
236  {
237    $where_clauses[] = 'id IN ('.implode(',',$params['ids']).')';
238  }
[12865]239
[14143]240  $query_model = 'SELECT id, path, representative_ext, width,height,rotation
[12865]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
[1781]285/**
286 * returns PWG version (web service method)
287 */
[1698]288function ws_getVersion($params, &$service)
289{
[1852]290  global $conf;
[9742]291  if ($conf['show_version'] or is_admin() )
[1852]292    return PHPWG_VERSION;
293  else
294    return new PwgError(403, 'Forbidden');
[1698]295}
296
[10017]297/**
298 * returns general informations (web service method)
299 */
300function ws_getInfos($params, &$service)
301{
[10061]302  if (!is_admin())
[10017]303  {
[10061]304    return new PwgError(403, 'Forbidden');
[10017]305  }
[10061]306
307  $infos['version'] = PHPWG_VERSION;
[11893]308
[10017]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
[10061]347  if ($infos['nb_comments'] > 0)
[10017]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
[2429]364function ws_caddie_add($params, &$service)
365{
366  if (!is_admin())
367  {
368    return new PwgError(401, 'Access denied');
369  }
[2770]370  $params['image_id'] = array_map( 'intval',$params['image_id'] );
[2429]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}
[1781]393
[1698]394/**
[1781]395 * returns images per category (web service method)
[1711]396 */
[1698]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    {
[4367]412      $where_clauses[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.$cat_id.'(,|$)\'';
[1698]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  }
[2119]426  $where_clauses[] = get_sql_condition_FandF(
427        array('forbidden_categories' => 'id'),
428        NULL, true
429      );
[1698]430
431  $query = '
[1866]432SELECT id, name, permalink, image_order
[1698]433  FROM '.CATEGORIES_TABLE.'
434  WHERE '. implode('
435    AND ', $where_clauses);
436  $result = pwg_query($query);
437  $cats = array();
[4325]438  while ($row = pwg_db_fetch_assoc($result))
[1698]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      .')';
[1781]451    $where_clauses[] = get_sql_condition_FandF( array(
452          'visible_images' => 'i.id'
453        ), null, true
454      );
[1756]455
[1698]456    $order_by = ws_std_image_sql_order($params, 'i.');
[1852]457    if ( empty($order_by)
458          and count($params['cat_id'])==1
459          and isset($cats[ $params['cat_id'][0] ]['image_order'])
460        )
[1698]461    {
[1852]462      $order_by = $cats[ $params['cat_id'][0] ]['image_order'];
[1698]463    }
[1852]464    $order_by = empty($order_by) ? $conf['order_by'] : 'ORDER BY '.$order_by;
465
[1698]466    $query = '
[6652]467SELECT i.*, GROUP_CONCAT(category_id) AS cat_ids
[1698]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.'
[4334]474LIMIT '.(int)$params['per_page'].' OFFSET '.(int)($params['per_page']*$params['page']);
[1698]475
476    $result = pwg_query($query);
[4325]477    while ($row = pwg_db_fetch_assoc($result))
[1698]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      }
[11116]487      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
[1698]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(
[1861]498                  'category' => $cats[$cat_id],
[1698]499                  )
500                );
501        $page_url = make_picture_url(
502                array(
[1861]503                  'category' => $cats[$cat_id],
[1698]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          ),
[1711]533       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
[1845]534          ws_std_get_image_xml_attributes() )
[1698]535      )
536    );
537}
538
[1781]539
[1698]540/**
[13074]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/**
[1781]571 * returns a list of categories (web service method)
[1698]572 */
573function ws_categories_getList($params, &$service)
574{
[1820]575  global $user,$conf;
[1698]576
[11155]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.
[11893]588
[11155]589      return new PwgError(405, "The tree_output option is only compatible with json/php output formats");
590    }
591  }
592
[4884]593  $where = array('1=1');
594  $join_type = 'INNER';
595  $join_user = $user['id'];
[1698]596
597  if (!$params['recursive'])
598  {
599    if ($params['cat_id']>0)
[1820]600      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
601    OR id='.(int)($params['cat_id']).')';
[1698]602    else
603      $where[] = 'id_uppercat IS NULL';
604  }
[1820]605  else if ($params['cat_id']>0)
606  {
[4367]607    $where[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.
[1820]608      (int)($params['cat_id'])
609      .'(,|$)\'';
610  }
[1698]611
612  if ($params['public'])
613  {
614    $where[] = 'status = "public"';
[1711]615    $where[] = 'visible = "true"';
[11893]616
[4884]617    $join_user = $conf['guest_id'];
[1698]618  }
[4884]619  elseif (is_admin())
[1698]620  {
[4884]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
[11893]624    //
[4884]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';
[1698]629  }
630
[1711]631  $query = '
[11155]632SELECT id, name, permalink, uppercats, global_rank, id_uppercat,
[7550]633    comment,
[1845]634    nb_images, count_images AS total_nb_images,
[12810]635    representative_picture_id, user_representative_picture_id, count_images, count_categories,
[1845]636    date_last, max_date_last, count_categories AS nb_categories
[1711]637  FROM '.CATEGORIES_TABLE.'
[4884]638   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
[1698]639  WHERE '. implode('
640    AND ', $where);
641
642  $result = pwg_query($query);
643
[12543]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
[12865]649
[1698]650  $cats = array();
[4325]651  while ($row = pwg_db_fetch_assoc($result))
[1698]652  {
653    $row['url'] = make_index_url(
654        array(
[1861]655          'category' => $row
[1698]656          )
657      );
[1845]658    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
[1698]659    {
660      $row[$key] = (int)$row[$key];
661    }
[2572]662
[11962]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    }
[11893]677
[7550]678    $row['comment'] = strip_tags(
679      trigger_event(
680        'render_category_description',
681        $row['comment'],
682        'ws_categories_getList'
683        )
684      );
[11893]685
[12543]686    // management of the album thumbnail -- starts here
[12865]687    //
[12543]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    }
[12865]738
[12543]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      }
[12865]745
[12543]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
[1698]754    array_push($cats, $row);
755  }
756  usort($cats, 'global_rank_compare');
[11155]757
[12543]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 = '
[12796]765SELECT id, path, representative_ext, level
[12543]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      {
[12796]774        $thumbnail_src_of[$row['id']] = DerivativeImage::thumb_url($row);
[12543]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
[12865]785
[12543]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);
[12865]792
[12543]793            if (isset($image_id) and !in_array($image_id, $image_ids))
794            {
795              array_push($new_image_ids, $image_id);
796            }
[12865]797
[12543]798            if ($conf['representative_cache_on_level'])
799            {
800              $user_representative_updates_for[ $user['id'].'#'.$category['id'] ] = $image_id;
801            }
[12865]802
[12543]803            $category['representative_picture_id'] = $image_id;
804          }
805        }
806        unset($category);
807      }
808    }
[12865]809
[12543]810    if (count($new_image_ids) > 0)
811    {
812      $query = '
[12796]813SELECT id, path, representative_ext
[12543]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      {
[12796]820        $thumbnail_src_of[$row['id']] = DerivativeImage::thumb_url($row);
[12543]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();
[12865]831
[12543]832    foreach ($user_representative_updates_for as $user_cat => $image_id)
833    {
834      list($user_id, $cat_id) = explode('#', $user_cat);
[12865]835
[12543]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    {
[15586]860      if ($category['id'] == $cat['id'] and isset($category['representative_picture_id']))
[12543]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']);
[12544]868    unset($cat['count_categories']);
[12543]869  }
[12865]870  unset($cat);
[12543]871  // management of the album thumbnail -- stops here
872
[11155]873  if ($params['tree_output'])
[11893]874  {
[11155]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          )
[2548]892        )
[11155]893      );
894  }
[1698]895}
896
[2563]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  }
[1781]910
[2563]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,
[7550]924    comment,
[2563]925    uppercats,
926    global_rank
927  FROM '.CATEGORIES_TABLE.'
928;';
929  $result = pwg_query($query);
930  $cats = array();
931
[4325]932  while ($row = pwg_db_fetch_assoc($result))
[2563]933  {
934    $id = $row['id'];
935    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
[4903]936    $row['name'] = strip_tags(
937      trigger_event(
938        'render_category_name',
939        $row['name'],
940        'ws_categories_getAdminList'
941        )
942      );
[7550]943    $row['comment'] = strip_tags(
944      trigger_event(
945        'render_category_description',
946        $row['comment'],
947        'ws_categories_getAdminList'
948        )
949      );
[2563]950    array_push($cats, $row);
[2585]951  }
952
[2563]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
[1781]969/**
970 * returns detailed information for an element (web service method)
971 */
[1849]972function ws_images_addComment($params, &$service)
973{
[1852]974  if (!$service->isPost())
975  {
976    return new PwgError(405, "This method requires HTTP POST");
977  }
[1849]978  $params['image_id'] = (int)$params['image_id'];
979  $query = '
[2119]980SELECT DISTINCT image_id
[1849]981  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
[2119]982  WHERE commentable="true"
[1849]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    );
[4325]992  if ( !pwg_db_num_rows( pwg_query( $query ) ) )
[1849]993  {
994    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
995  }
[2119]996
[1849]997  $comm = array(
[6437]998    'author' => trim( $params['author'] ),
999    'content' => trim( $params['content'] ),
[1849]1000    'image_id' => $params['image_id'],
1001   );
1002
1003  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
[2119]1004
1005  $comment_action = insert_user_comment(
[1849]1006      $comm, $params['key'], $infos
1007    );
1008
1009  switch ($comment_action)
1010  {
1011    case 'reject':
[5021]1012      array_push($infos, l10n('Your comment has NOT been registered because it did not pass the validation rules') );
[7782]1013      return new PwgError(403, implode("; ", $infos) );
[1849]1014    case 'validate':
1015    case 'moderate':
[2119]1016      $ret = array(
[1849]1017          'id' => $comm['id'],
1018          'validation' => $comment_action=='validate',
1019        );
1020      return new PwgNamedStruct(
1021          'comment',
[2119]1022          $ret,
1023          null, array()
[1849]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 */
[1698]1033function ws_images_getInfo($params, &$service)
1034{
[1849]1035  global $user, $conf;
[1698]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  }
[1781]1041
[1698]1042  $query='
1043SELECT * FROM '.IMAGES_TABLE.'
[1711]1044  WHERE id='.$params['image_id'].
1045    get_sql_condition_FandF(
1046      array('visible_images' => 'id'),
1047      ' AND'
[2516]1048    ).'
1049LIMIT 1';
[1711]1050
[4325]1051  $image_row = pwg_db_fetch_assoc(pwg_query($query));
[1698]1052  if ($image_row==null)
1053  {
[1852]1054    return new PwgError(404, "image_id not found");
[1698]1055  }
[1845]1056  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
[1698]1057
1058  //-------------------------------------------------------- related categories
1059  $query = '
[1866]1060SELECT id, name, permalink, uppercats, global_rank, commentable
[1698]1061  FROM '.IMAGE_CATEGORY_TABLE.'
[1849]1062    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
[2119]1063  WHERE image_id = '.$image_row['id'].
1064  get_sql_condition_FandF(
1065      array( 'forbidden_categories' => 'category_id' ),
1066      ' AND'
1067    ).'
[1698]1068;';
1069  $result = pwg_query($query);
[1849]1070  $is_commentable = false;
[1698]1071  $related_categories = array();
[4325]1072  while ($row = pwg_db_fetch_assoc($result))
[1698]1073  {
[1849]1074    if ($row['commentable']=='true')
1075    {
1076      $is_commentable = true;
1077    }
1078    unset($row['commentable']);
[1698]1079    $row['url'] = make_index_url(
1080        array(
[1861]1081          'category' => $row
[1698]1082          )
1083      );
1084
1085    $row['page_url'] = make_picture_url(
1086        array(
1087          'image_id' => $image_row['id'],
1088          'image_file' => $image_row['file'],
[1861]1089          'category' => $row
[1698]1090          )
1091      );
[1849]1092    $row['id']=(int)$row['id'];
[1698]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
[1815]1102  $related_tags = get_common_tags( array($image_row['id']), -1 );
1103  foreach( $related_tags as $i=>$tag)
[1698]1104  {
[1815]1105    $tag['url'] = make_index_url(
[1698]1106        array(
[1815]1107          'tags' => array($tag)
[1698]1108          )
1109      );
[1815]1110    $tag['page_url'] = make_picture_url(
[1698]1111        array(
1112          'image_id' => $image_row['id'],
1113          'image_file' => $image_row['file'],
[1815]1114          'tags' => array($tag),
[1698]1115          )
1116      );
[1815]1117    unset($tag['counter']);
[1849]1118    $tag['id']=(int)$tag['id'];
[1815]1119    $related_tags[$i]=$tag;
[1698]1120  }
[1849]1121  //------------------------------------------------------------- related rates
[11893]1122        $rating = array('score'=>$image_row['rating_score'], 'count'=>0, 'average'=>null);
[11827]1123        if (isset($rating['score']))
1124        {
1125                $query = '
[1849]1126SELECT COUNT(rate) AS count
1127     , ROUND(AVG(rate),2) AS average
1128  FROM '.RATE_TABLE.'
1129  WHERE element_id = '.$image_row['id'].'
1130;';
[11827]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        }
[1849]1136
[1698]1137  //---------------------------------------------------------- related comments
[1849]1138  $related_comments = array();
[2119]1139
[1849]1140  $where_comments = 'image_id = '.$image_row['id'];
1141  if ( !is_admin() )
1142  {
1143    $where_comments .= '
1144    AND validated="true"';
1145  }
1146
[1698]1147  $query = '
[6652]1148SELECT COUNT(id) AS nb_comments
[1698]1149  FROM '.COMMENTS_TABLE.'
[1849]1150  WHERE '.$where_comments;
[1698]1151  list($nb_comments) = array_from_query($query, 'nb_comments');
[1849]1152  $nb_comments = (int)$nb_comments;
[1698]1153
[1849]1154  if ( $nb_comments>0 and $params['comments_per_page']>0 )
1155  {
1156    $query = '
[1698]1157SELECT id, date, author, content
1158  FROM '.COMMENTS_TABLE.'
[1849]1159  WHERE '.$where_comments.'
1160  ORDER BY date
[4334]1161  LIMIT '.(int)$params['comments_per_page'].
1162    ' OFFSET '.(int)($params['comments_per_page']*$params['comments_page']);
[1698]1163
[1849]1164    $result = pwg_query($query);
[4325]1165    while ($row = pwg_db_fetch_assoc($result))
[1849]1166    {
1167      $row['id']=(int)$row['id'];
1168      array_push($related_comments, $row);
1169    }
1170  }
[2119]1171
[1849]1172  $comment_post_data = null;
[2119]1173  if ($is_commentable and
[2029]1174      (!is_a_guest()
1175        or (is_a_guest() and $conf['comments_forall'] )
[1849]1176      )
1177      )
[1698]1178  {
[4304]1179    $comment_post_data['author'] = stripslashes($user['username']);
[7495]1180    $comment_post_data['key'] = get_ephemeral_key(2, $params['image_id']);
[1698]1181  }
1182
[1849]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  }
[1698]1195
[1849]1196  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
[1698]1197  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
[2585]1198  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
[1849]1199  if ( isset($comment_post_data) )
1200  {
1201    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
1202  }
[1698]1203  $ret['comments'] = array(
[2119]1204     WS_XML_ATTRIBUTES =>
[1849]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') )
[1698]1212      );
[1845]1213
[1698]1214  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
1215}
1216
[2435]1217
[1837]1218/**
[2435]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';
[4325]1236  if ( pwg_db_num_rows( pwg_query($query) )==0 )
[2435]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/**
[1837]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' );
[1698]1260
[2135]1261  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
1262  $order_by = ws_std_image_sql_order($params, 'i.');
[1837]1263
[2451]1264  $super_order_by = false;
[2135]1265  if ( !empty($order_by) )
[1837]1266  {
[2135]1267    global $conf;
1268    $conf['order_by'] = 'ORDER BY '.$order_by;
[2451]1269    $super_order_by=true; // quick_search_result might be faster
[1837]1270  }
1271
[2135]1272  $search_result = get_quick_search_results($params['query'],
[2451]1273      $super_order_by,
1274      implode(',', $where_clauses)
1275    );
[2119]1276
[2451]1277  $image_ids = array_slice(
1278      $search_result['items'],
1279      $params['page']*$params['per_page'],
1280      $params['per_page']
1281    );
[1837]1282
1283  if ( count($image_ids) )
1284  {
1285    $query = '
1286SELECT * FROM '.IMAGES_TABLE.'
[2451]1287  WHERE id IN ('.implode(',', $image_ids).')';
[1837]1288
[2451]1289    $image_ids = array_flip($image_ids);
[1837]1290    $result = pwg_query($query);
[4325]1291    while ($row = pwg_db_fetch_assoc($result))
[1837]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      }
[11116]1301      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
[1837]1302      {
1303        $image[$k] = $row[$k];
1304      }
1305      $image = array_merge( $image, ws_std_get_urls($row) );
[2451]1306      $images[$image_ids[$image['id']]] = $image;
[1837]1307    }
[2451]1308    ksort($images, SORT_NUMERIC);
1309    $images = array_values($images);
[1837]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',
[1845]1322          ws_std_get_image_xml_attributes() )
[1837]1323      )
1324    );
1325}
1326
[2413]1327function ws_images_setPrivacyLevel($params, &$service)
1328{
[8126]1329  if (!is_admin())
[2413]1330  {
1331    return new PwgError(401, 'Access denied');
1332  }
[4513]1333  if (!$service->isPost())
1334  {
1335    return new PwgError(405, "This method requires HTTP POST");
1336  }
[2770]1337  $params['image_id'] = array_map( 'intval',$params['image_id'] );
[2413]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  }
[4513]1347
[2413]1348  $query = '
1349UPDATE '.IMAGES_TABLE.'
1350  SET level='.(int)$params['level'].'
1351  WHERE id IN ('.implode(',',$params['image_id']).')';
1352  $result = pwg_query($query);
[5930]1353  $affected_rows = pwg_db_changes($result);
[2413]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
[11372]1362function ws_images_setRank($params, &$service)
1363{
1364  if (!is_admin())
1365  {
1366    return new PwgError(401, 'Access denied');
1367  }
[11893]1368
[11372]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  }
[11893]1394
[11372]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  }
[11893]1408
[11372]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
[3193]1474function ws_images_add_chunk($params, &$service)
1475{
[5014]1476  global $conf;
[11893]1477
[3193]1478  // data
1479  // original_sum
1480  // type {thumb, file, high}
1481  // position
[3488]1482
[8126]1483  if (!is_admin())
[3193]1484  {
1485    return new PwgError(401, 'Access denied');
1486  }
1487
[4511]1488  if (!$service->isPost())
1489  {
1490    return new PwgError(405, "This method requires HTTP POST");
1491  }
1492
[4900]1493  foreach ($params as $param_key => $param_value) {
1494    if ('data' == $param_key) {
1495      continue;
1496    }
[11893]1497
[4900]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
[5014]1507  $upload_dir = $conf['upload_dir'].'/buffer';
[3193]1508
1509  // create the upload directory tree if not exists
1510  if (!is_dir($upload_dir)) {
1511    umask(0000);
[12796]1512    if (!@mkdir($upload_dir, 0777, true))
[3193]1513    {
1514      return new PwgError(500, 'error during buffer directory creation');
1515    }
1516  }
1517
1518  if (!is_writable($upload_dir))
1519  {
1520    // last chance to make the directory writable
1521    @chmod($upload_dir, 0777);
1522
1523    if (!is_writable($upload_dir))
1524    {
1525      return new PwgError(500, 'buffer directory has no write access');
1526    }
1527  }
1528
1529  secure_directory($upload_dir);
1530
1531  $filename = sprintf(
1532    '%s-%s-%05u.block',
1533    $params['original_sum'],
1534    $params['type'],
1535    $params['position']
1536    );
1537
[3240]1538  ws_logfile('[ws_images_add_chunk] data length : '.strlen($params['data']));
1539
[3193]1540  $bytes_written = file_put_contents(
1541    $upload_dir.'/'.$filename,
[3240]1542    base64_decode($params['data'])
[3193]1543    );
1544
1545  if (false === $bytes_written) {
1546    return new PwgError(
1547      500,
1548      'an error has occured while writting chunk '.$params['position'].' for '.$params['type']
1549      );
1550  }
1551}
1552
1553function merge_chunks($output_filepath, $original_sum, $type)
1554{
[5014]1555  global $conf;
[11893]1556
[3193]1557  ws_logfile('[merge_chunks] input parameter $output_filepath : '.$output_filepath);
1558
[4348]1559  if (is_file($output_filepath))
1560  {
1561    unlink($output_filepath);
[4513]1562
[4348]1563    if (is_file($output_filepath))
1564    {
[12796]1565      return new PwgError(500, '[merge_chunks] error while trying to remove existing '.$output_filepath);
[4348]1566    }
1567  }
[4513]1568
[5014]1569  $upload_dir = $conf['upload_dir'].'/buffer';
[3193]1570  $pattern = '/'.$original_sum.'-'.$type.'/';
1571  $chunks = array();
[3488]1572
[3193]1573  if ($handle = opendir($upload_dir))
1574  {
1575    while (false !== ($file = readdir($handle)))
1576    {
1577      if (preg_match($pattern, $file))
1578      {
1579        ws_logfile($file);
1580        array_push($chunks, $upload_dir.'/'.$file);
1581      }
1582    }
1583    closedir($handle);
1584  }
1585
1586  sort($chunks);
[3240]1587
[4425]1588  if (function_exists('memory_get_usage')) {
1589    ws_logfile('[merge_chunks] memory_get_usage before loading chunks: '.memory_get_usage());
1590  }
[3488]1591
[3514]1592  $i = 0;
[4513]1593
[3240]1594  foreach ($chunks as $chunk)
1595  {
1596    $string = file_get_contents($chunk);
[3488]1597
[4425]1598    if (function_exists('memory_get_usage')) {
1599      ws_logfile('[merge_chunks] memory_get_usage on chunk '.++$i.': '.memory_get_usage());
1600    }
[3488]1601
[3240]1602    if (!file_put_contents($output_filepath, $string, FILE_APPEND))
1603    {
[12796]1604      return new PwgError(500, '[merge_chunks] error while writting chunks for '.$output_filepath);
[3240]1605    }
[3488]1606
[3193]1607    unlink($chunk);
1608  }
[3240]1609
[4425]1610  if (function_exists('memory_get_usage')) {
1611    ws_logfile('[merge_chunks] memory_get_usage after loading chunks: '.memory_get_usage());
1612  }
[3193]1613}
1614
[12906]1615/**
1616 * Function introduced for Piwigo 2.4 and the new "multiple size"
1617 * (derivatives) feature. As we only need the biggest sent photo as
1618 * "original", we remove chunks for smaller sizes. We can't make it earlier
1619 * in ws_images_add_chunk because at this moment we don't know which $type
1620 * will be the biggest (we could remove the thumb, but let's use the same
1621 * algorithm)
1622 */
1623function remove_chunks($original_sum, $type)
1624{
1625  global $conf;
1626
1627  $upload_dir = $conf['upload_dir'].'/buffer';
1628  $pattern = '/'.$original_sum.'-'.$type.'/';
1629  $chunks = array();
1630
1631  if ($handle = opendir($upload_dir))
1632  {
1633    while (false !== ($file = readdir($handle)))
1634    {
1635      if (preg_match($pattern, $file))
1636      {
1637        array_push($chunks, $upload_dir.'/'.$file);
1638      }
1639    }
1640    closedir($handle);
1641  }
1642
1643  foreach ($chunks as $chunk)
1644  {
1645    unlink($chunk);
1646  }
1647}
1648
[4348]1649function ws_images_addFile($params, &$service)
1650{
[12906]1651  ws_logfile(__FUNCTION__.', input :  '.var_export($params, true));
[4348]1652  // image_id
1653  // type {thumb, file, high}
[12906]1654  // sum -> not used currently (Piwigo 2.4)
[4348]1655
1656  global $conf;
[8126]1657  if (!is_admin())
[4348]1658  {
1659    return new PwgError(401, 'Access denied');
1660  }
1661
1662  $params['image_id'] = (int)$params['image_id'];
1663  if ($params['image_id'] <= 0)
1664  {
1665    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1666  }
1667
1668  //
[12906]1669  // what is the path and other infos about the photo?
[4348]1670  //
1671  $query = '
1672SELECT
1673    path,
[12906]1674    file,
1675    md5sum,
1676    width,
1677    height,
1678    filesize
[4348]1679  FROM '.IMAGES_TABLE.'
1680  WHERE id = '.$params['image_id'].'
1681;';
[12906]1682  $image = pwg_db_fetch_assoc(pwg_query($query));
[4348]1683
[12906]1684  if ($image == null)
1685  {
1686    return new PwgError(404, "image_id not found");
1687  }
[4348]1688
[12906]1689  // since Piwigo 2.4 and derivatives, we do not take the imported "thumb"
1690  // into account
1691  if ('thumb' == $params['type'])
1692  {
1693    remove_chunks($image['md5sum'], $type);
1694    return true;
1695  }
[4348]1696
[12906]1697  // since Piwigo 2.4 and derivatives, we only care about the "original"
1698  $original_type = 'file';
[4348]1699  if ('high' == $params['type'])
1700  {
[12906]1701    $original_type = 'high';
[4348]1702  }
1703
[12906]1704  $file_path = $conf['upload_dir'].'/buffer/'.$image['md5sum'].'-original';
1705
1706  merge_chunks($file_path, $image['md5sum'], $original_type);
1707  chmod($file_path, 0644);
1708
1709  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1710
1711  // if we receive the "file", we only update the original if the "file" is
1712  // bigger than current original
[4348]1713  if ('file' == $params['type'])
1714  {
[12906]1715    $do_update = false;
[13074]1716
[12906]1717    $infos = pwg_image_infos($file_path);
[13074]1718
[12906]1719    foreach (array('width', 'height', 'filesize') as $image_info)
1720    {
1721      if ($infos[$image_info] > $image[$image_info])
1722      {
1723        $do_update = true;
1724      }
1725    }
1726
1727    if (!$do_update)
1728    {
1729      unlink($file_path);
1730      return true;
1731    }
[4348]1732  }
1733
[12906]1734  $image_id = add_uploaded_file(
1735    $file_path,
1736    $image['file'],
1737    null,
1738    null,
1739    $params['image_id'],
1740    $image['md5sum'] // we force the md5sum to remain the same
1741    );
[4348]1742}
1743
[2463]1744function ws_images_add($params, &$service)
1745{
[8464]1746  global $conf, $user;
[8126]1747  if (!is_admin())
[2496]1748  {
1749    return new PwgError(401, 'Access denied');
1750  }
1751
[3662]1752  foreach ($params as $param_key => $param_value) {
1753    ws_logfile(
1754      sprintf(
1755        '[pwg.images.add] input param "%s" : "%s"',
1756        $param_key,
1757        is_null($param_value) ? 'NULL' : $param_value
1758        )
1759      );
1760  }
[2496]1761
[13090]1762  $params['image_id'] = (int)$params['image_id'];
1763  if ($params['image_id'] > 0)
1764  {
1765    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1766
1767    $query='
1768SELECT *
1769  FROM '.IMAGES_TABLE.'
1770  WHERE id = '.$params['image_id'].'
1771;';
1772
1773    $image_row = pwg_db_fetch_assoc(pwg_query($query));
1774    if ($image_row == null)
1775    {
1776      return new PwgError(404, "image_id not found");
1777    }
1778  }
1779
[2592]1780  // does the image already exists ?
[12726]1781  if ($params['check_uniqueness'])
[4954]1782  {
[12726]1783    if ('md5sum' == $conf['uniqueness_mode'])
1784    {
1785      $where_clause = "md5sum = '".$params['original_sum']."'";
1786    }
1787    if ('filename' == $conf['uniqueness_mode'])
1788    {
1789      $where_clause = "file = '".$params['original_filename']."'";
1790    }
[11893]1791
[12726]1792    $query = '
[2592]1793SELECT
1794    COUNT(*) AS counter
1795  FROM '.IMAGES_TABLE.'
[4954]1796  WHERE '.$where_clause.'
[2592]1797;';
[12726]1798    list($counter) = pwg_db_fetch_row(pwg_query($query));
1799    if ($counter != 0) {
1800      return new PwgError(500, 'file already exists');
1801    }
[2592]1802  }
1803
[12906]1804  // due to the new feature "derivatives" (multiple sizes) introduced for
1805  // Piwigo 2.4, we only take the biggest photos sent on
1806  // pwg.images.addChunk. If "high" is available we use it as "original"
1807  // else we use "file".
1808  remove_chunks($params['original_sum'], 'thumb');
[13074]1809
[12906]1810  if (isset($params['high_sum']))
[12724]1811  {
[12906]1812    $original_type = 'high';
1813    remove_chunks($params['original_sum'], 'file');
[12724]1814  }
1815  else
1816  {
[12906]1817    $original_type = 'file';
1818  }
[2496]1819
[12906]1820  $file_path = $conf['upload_dir'].'/buffer/'.$params['original_sum'].'-original';
[2463]1821
[12906]1822  merge_chunks($file_path, $params['original_sum'], $original_type);
1823  chmod($file_path, 0644);
[12865]1824
[12906]1825  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[12865]1826
[12906]1827  $image_id = add_uploaded_file(
1828    $file_path,
1829    $params['original_filename'],
1830    null, // categories
1831    isset($params['level']) ? $params['level'] : null,
[13090]1832    $params['image_id'] > 0 ? $params['image_id'] : null,
[12906]1833    $params['original_sum']
1834    );
[12724]1835
[2569]1836  $info_columns = array(
1837    'name',
1838    'author',
1839    'comment',
1840    'date_creation',
1841    );
1842
[12906]1843  $update = array();
1844
[2569]1845  foreach ($info_columns as $key)
1846  {
1847    if (isset($params[$key]))
1848    {
[12724]1849      $update[$key] = $params[$key];
[2569]1850    }
1851  }
[12865]1852
[12724]1853  if (count(array_keys($update)) > 0)
[2670]1854  {
[12724]1855    single_update(
1856      IMAGES_TABLE,
1857      $update,
1858      array('id' => $image_id)
1859      );
[2670]1860  }
1861
[12728]1862  $url_params = array('image_id' => $image_id);
[12865]1863
[2569]1864  // let's add links between the image and the categories
1865  if (isset($params['categories']))
1866  {
[2919]1867    ws_add_image_category_relations($image_id, $params['categories']);
[12728]1868
1869    if (preg_match('/^\d+/', $params['categories'], $matches)) {
1870      $category_id = $matches[0];
[12865]1871
[12728]1872      $query = '
1873SELECT id, name, permalink
1874  FROM '.CATEGORIES_TABLE.'
1875  WHERE id = '.$category_id.'
1876;';
1877      $result = pwg_query($query);
1878      $category = pwg_db_fetch_assoc($result);
[12865]1879
[12728]1880      $url_params['section'] = 'categories';
1881      $url_params['category'] = $category;
1882    }
[2553]1883  }
[2569]1884
1885  // and now, let's create tag associations
[3660]1886  if (isset($params['tag_ids']) and !empty($params['tag_ids']))
[2553]1887  {
[2569]1888    set_tags(
1889      explode(',', $params['tag_ids']),
1890      $image_id
1891      );
[2553]1892  }
[2585]1893
[2501]1894  invalidate_user_cache();
[12728]1895
1896  return array(
1897    'image_id' => $image_id,
1898    'url' => make_picture_url($url_params),
1899    );
[2463]1900}
1901
[8249]1902function ws_images_addSimple($params, &$service)
1903{
1904  global $conf;
[8274]1905  if (!is_admin())
[8249]1906  {
1907    return new PwgError(401, 'Access denied');
1908  }
1909
1910  if (!$service->isPost())
1911  {
1912    return new PwgError(405, "This method requires HTTP POST");
1913  }
[11118]1914
1915  if (!isset($_FILES['image']))
1916  {
1917    return new PwgError(405, "The image (file) parameter is missing");
1918  }
[11893]1919
[9191]1920  $params['image_id'] = (int)$params['image_id'];
1921  if ($params['image_id'] > 0)
1922  {
1923    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
[8249]1924
[9191]1925    $query='
1926SELECT *
1927  FROM '.IMAGES_TABLE.'
1928  WHERE id = '.$params['image_id'].'
1929;';
1930
1931    $image_row = pwg_db_fetch_assoc(pwg_query($query));
1932    if ($image_row == null)
1933    {
1934      return new PwgError(404, "image_id not found");
1935    }
1936  }
1937
[8249]1938  // category
1939  $params['category'] = (int)$params['category'];
[9191]1940  if ($params['category'] <= 0 and $params['image_id'] <= 0)
[8249]1941  {
1942    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
1943  }
1944
1945  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1946
1947  $image_id = add_uploaded_file(
1948    $_FILES['image']['tmp_name'],
1949    $_FILES['image']['name'],
[9191]1950    $params['category'] > 0 ? array($params['category']) : null,
1951    8,
1952    $params['image_id'] > 0 ? $params['image_id'] : null
[8249]1953    );
1954
1955  $info_columns = array(
1956    'name',
1957    'author',
1958    'comment',
1959    'level',
1960    'date_creation',
1961    );
1962
1963  foreach ($info_columns as $key)
1964  {
1965    if (isset($params[$key]))
1966    {
1967      $update[$key] = $params[$key];
1968    }
1969  }
1970
1971  if (count(array_keys($update)) > 0)
1972  {
1973    $update['id'] = $image_id;
1974
1975    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1976    mass_updates(
1977      IMAGES_TABLE,
1978      array(
1979        'primary' => array('id'),
1980        'update'  => array_diff(array_keys($update), array('id'))
1981        ),
1982      array($update)
1983      );
1984  }
1985
1986
1987  if (isset($params['tags']) and !empty($params['tags']))
1988  {
1989    $tag_ids = array();
1990    $tag_names = explode(',', $params['tags']);
1991    foreach ($tag_names as $tag_name)
1992    {
1993      $tag_id = tag_id_from_tag_name($tag_name);
1994      array_push($tag_ids, $tag_id);
1995    }
1996
1997    add_tags($tag_ids, array($image_id));
1998  }
1999
[9191]2000  $url_params = array('image_id' => $image_id);
2001
2002  if ($params['category'] > 0)
2003  {
2004    $query = '
[8249]2005SELECT id, name, permalink
2006  FROM '.CATEGORIES_TABLE.'
2007  WHERE id = '.$params['category'].'
2008;';
[9191]2009    $result = pwg_query($query);
2010    $category = pwg_db_fetch_assoc($result);
[8249]2011
[9191]2012    $url_params['section'] = 'categories';
2013    $url_params['category'] = $category;
2014  }
2015
[9944]2016  // update metadata from the uploaded file (exif/iptc), even if the sync
2017  // was already performed by add_uploaded_file().
[11893]2018
[9944]2019  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
[12831]2020  sync_metadata(array($image_id));
[9944]2021
[8249]2022  return array(
2023    'image_id' => $image_id,
[9191]2024    'url' => make_picture_url($url_params),
[8249]2025    );
2026}
2027
[12624]2028function ws_rates_delete($params, &$service)
2029{
2030  global $conf;
2031
2032  if (!$service->isPost())
2033  {
2034    return new PwgError(405, 'This method requires HTTP POST');
2035  }
2036
2037  if (!is_admin())
2038  {
2039    return new PwgError(401, 'Access denied');
2040  }
2041
2042  $user_id = (int)$params['user_id'];
2043  if ($user_id<=0)
2044  {
2045    return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid user_id');
2046  }
[12865]2047
[12624]2048  $query = '
2049DELETE FROM '.RATE_TABLE.'
2050  WHERE user_id='.$user_id;
[12865]2051
[12624]2052  if (!empty($params['anonymous_id']))
2053  {
2054    $query .= ' AND anonymous_id=\''.$params['anonymous_id'].'\'';
2055  }
[12865]2056
[12624]2057  $changes = pwg_db_changes(pwg_query($query));
2058  if ($changes)
2059  {
2060    include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
2061    update_rating_score();
2062  }
2063  return $changes;
2064}
2065
2066
[1781]2067/**
2068 * perform a login (web service method)
2069 */
[1698]2070function ws_session_login($params, &$service)
2071{
2072  global $conf;
2073
2074  if (!$service->isPost())
2075  {
[1852]2076    return new PwgError(405, "This method requires HTTP POST");
[1698]2077  }
[1744]2078  if (try_log_user($params['username'], $params['password'],false))
[1698]2079  {
2080    return true;
2081  }
2082  return new PwgError(999, 'Invalid username/password');
2083}
2084
[1781]2085
2086/**
2087 * performs a logout (web service method)
2088 */
[1698]2089function ws_session_logout($params, &$service)
2090{
[2029]2091  if (!is_a_guest())
[1698]2092  {
[2757]2093    logout_user();
[1698]2094  }
2095  return true;
2096}
2097
2098function ws_session_getStatus($params, &$service)
2099{
[2356]2100  global $user;
[1698]2101  $res = array();
[4304]2102  $res['username'] = is_a_guest() ? 'guest' : stripslashes($user['username']);
[6437]2103  foreach ( array('status', 'theme', 'language') as $k )
[1849]2104  {
2105    $res[$k] = $user[$k];
2106  }
[7212]2107  $res['pwg_token'] = get_pwg_token();
[2126]2108  $res['charset'] = get_pwg_charset();
[11756]2109
2110  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2111  $res['current_datetime'] = $dbnow;
[11893]2112
[1698]2113  return $res;
2114}
2115
2116
[1781]2117/**
2118 * returns a list of tags (web service method)
2119 */
[1698]2120function ws_tags_getList($params, &$service)
2121{
[1711]2122  $tags = get_available_tags();
[1698]2123  if ($params['sort_by_counter'])
2124  {
2125    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
2126  }
2127  else
2128  {
[2409]2129    usort($tags, 'tag_alpha_compare');
[1698]2130  }
2131  for ($i=0; $i<count($tags); $i++)
2132  {
[1815]2133    $tags[$i]['id'] = (int)$tags[$i]['id'];
[1698]2134    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
2135    $tags[$i]['url'] = make_index_url(
2136        array(
2137          'section'=>'tags',
2138          'tags'=>array($tags[$i])
2139        )
2140      );
2141  }
[2585]2142  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
[1698]2143}
2144
[2584]2145/**
2146 * returns the list of tags as you can see them in administration (web
2147 * service method).
2148 *
2149 * Only admin can run this method and permissions are not taken into
2150 * account.
2151 */
2152function ws_tags_getAdminList($params, &$service)
2153{
2154  if (!is_admin())
2155  {
2156    return new PwgError(401, 'Access denied');
2157  }
[2585]2158
[2584]2159  $tags = get_all_tags();
2160  return array(
2161    'tags' => new PwgNamedArray(
2162      $tags,
2163      'tag',
2164      array(
2165        'name',
2166        'id',
2167        'url_name',
2168        )
2169      )
2170    );
2171}
[1781]2172
2173/**
2174 * returns a list of images for tags (web service method)
2175 */
[1698]2176function ws_tags_getImages($params, &$service)
2177{
[1816]2178  global $conf;
[2119]2179
[1698]2180  // first build all the tag_ids we are interested in
[1852]2181  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
2182  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
[1698]2183  $tags_by_id = array();
2184  foreach( $tags as $tag )
2185  {
[1852]2186    $tags['id'] = (int)$tag['id'];
[1815]2187    $tags_by_id[ $tag['id'] ] = $tag;
[1698]2188  }
2189  unset($tags);
[1852]2190  $tag_ids = array_keys($tags_by_id);
[1698]2191
2192
[8726]2193  $where_clauses = ws_std_image_sql_filter($params);
2194  if (!empty($where_clauses))
2195  {
2196    $where_clauses = implode( ' AND ', $where_clauses);
2197  }
2198  $image_ids = get_image_ids_for_tags(
2199    $tag_ids,
2200    $params['tag_mode_and'] ? 'AND' : 'OR',
2201    $where_clauses,
2202    ws_std_image_sql_order($params) );
2203
2204
2205  $image_ids = array_slice($image_ids, (int)($params['per_page']*$params['page']), (int)$params['per_page'] );
[11893]2206
[1698]2207  $image_tag_map = array();
[8726]2208  if ( !empty($image_ids) and !$params['tag_mode_and'] )
[1698]2209  { // build list of image ids with associated tags per image
[8726]2210    $query = '
[6652]2211SELECT image_id, GROUP_CONCAT(tag_id) AS tag_ids
[1698]2212  FROM '.IMAGE_TAG_TABLE.'
[8726]2213  WHERE tag_id IN ('.implode(',',$tag_ids).') AND image_id IN ('.implode(',',$image_ids).')
[1698]2214  GROUP BY image_id';
[8726]2215    $result = pwg_query($query);
2216    while ( $row=pwg_db_fetch_assoc($result) )
2217    {
2218      $row['image_id'] = (int)$row['image_id'];
2219      array_push( $image_ids, $row['image_id'] );
2220      $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
[1698]2221    }
2222  }
2223
2224  $images = array();
[8726]2225  if (!empty($image_ids))
[1698]2226  {
[8726]2227    $rank_of = array_flip($image_ids);
2228    $result = pwg_query('
2229SELECT * FROM '.IMAGES_TABLE.'
2230  WHERE id IN ('.implode(',',$image_ids).')');
[4325]2231    while ($row = pwg_db_fetch_assoc($result))
[1698]2232    {
[2119]2233      $image = array();
[8726]2234      $image['rank'] = $rank_of[ $row['id'] ];
[1698]2235      foreach ( array('id', 'width', 'height', 'hit') as $k )
2236      {
2237        if (isset($row[$k]))
2238        {
2239          $image[$k] = (int)$row[$k];
2240        }
2241      }
[11116]2242      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
[1698]2243      {
2244        $image[$k] = $row[$k];
2245      }
2246      $image = array_merge( $image, ws_std_get_urls($row) );
2247
2248      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
2249      $image_tags = array();
2250      foreach ($image_tag_ids as $tag_id)
2251      {
2252        $url = make_index_url(
2253                 array(
2254                  'section'=>'tags',
2255                  'tags'=> array($tags_by_id[$tag_id])
2256                )
2257              );
2258        $page_url = make_picture_url(
2259                 array(
2260                  'section'=>'tags',
2261                  'tags'=> array($tags_by_id[$tag_id]),
2262                  'image_id' => $row['id'],
2263                  'image_file' => $row['file'],
2264                )
2265              );
2266        array_push($image_tags, array(
2267                'id' => (int)$tag_id,
2268                'url' => $url,
2269                'page_url' => $page_url,
2270              )
2271            );
2272      }
[1711]2273      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
2274              array('id','url_name','url','page_url')
[1698]2275            );
2276      array_push($images, $image);
2277    }
[8726]2278    usort($images, 'rank_compare');
2279    unset($rank_of);
[1698]2280  }
2281
2282  return array( 'images' =>
2283    array (
2284      WS_XML_ATTRIBUTES =>
2285        array(
2286            'page' => $params['page'],
2287            'per_page' => $params['per_page'],
2288            'count' => count($images)
2289          ),
[1711]2290       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
[1845]2291          ws_std_get_image_xml_attributes() )
[1698]2292      )
2293    );
2294}
[2583]2295
2296function ws_categories_add($params, &$service)
2297{
[8126]2298  if (!is_admin())
[2583]2299  {
2300    return new PwgError(401, 'Access denied');
2301  }
2302
2303  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2304
2305  $creation_output = create_virtual_category(
2306    $params['name'],
2307    $params['parent']
2308    );
2309
2310  if (isset($creation_output['error']))
2311  {
2312    return new PwgError(500, $creation_output['error']);
2313  }
[15850]2314 
2315  $updates = array();
2316  if ( !empty($params['status']) and in_array($params['status'], array('private','public')) )
2317  {
2318    $updates['status'] = $params['status'];
2319  }
2320  if ( !empty($params['visible']) and in_array($params['visible'], array('true','false')) )
2321  {
2322    $updates['visible'] = $params['visible'];
2323  }
2324  if ( !empty($params['commentable']) and in_array($params['commentable'], array('true','false')) )
2325  {
2326    $updates['commentable'] = $params['commentable'];
2327  }
2328  if ( !empty($params['comment']) )
2329  {
2330    $updates['comment'] = strip_tags($params['comment']);
2331  }
[2585]2332
[15850]2333  if (!empty($updates))
2334  {
2335    single_update(
2336      CATEGORIES_TABLE,
2337      $updates,
2338      array('id'=>$creation_output['id'])
2339      );
2340  }
[15852]2341 
2342  if ( isset($updates['status']) and 'private' == $updates['status'] )
2343  {
2344    add_permission_on_category($creation_output['id'], get_admins());
2345  }
[15850]2346
[2644]2347  invalidate_user_cache();
[2757]2348
[2583]2349  return $creation_output;
2350}
[2634]2351
2352function ws_tags_add($params, &$service)
2353{
[8126]2354  if (!is_admin())
[2634]2355  {
2356    return new PwgError(401, 'Access denied');
2357  }
2358
2359  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2360
2361  $creation_output = create_tag($params['name']);
2362
2363  if (isset($creation_output['error']))
2364  {
2365    return new PwgError(500, $creation_output['error']);
2366  }
2367
2368  return $creation_output;
2369}
[2683]2370
2371function ws_images_exist($params, &$service)
2372{
[12906]2373  ws_logfile(__FUNCTION__.' '.var_export($params, true));
2374
[4954]2375  global $conf;
[11893]2376
[8126]2377  if (!is_admin())
[2683]2378  {
2379    return new PwgError(401, 'Access denied');
2380  }
2381
[4954]2382  $split_pattern = '/[\s,;\|]/';
2383
2384  if ('md5sum' == $conf['uniqueness_mode'])
2385  {
2386    // search among photos the list of photos already added, based on md5sum
2387    // list
2388    $md5sums = preg_split(
2389      $split_pattern,
2390      $params['md5sum_list'],
2391      -1,
2392      PREG_SPLIT_NO_EMPTY
[2683]2393    );
[2757]2394
[4954]2395    $query = '
[2683]2396SELECT
2397    id,
2398    md5sum
2399  FROM '.IMAGES_TABLE.'
[2757]2400  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
[2683]2401;';
[4954]2402    $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
[2683]2403
[4954]2404    $result = array();
[2757]2405
[4954]2406    foreach ($md5sums as $md5sum)
2407    {
2408      $result[$md5sum] = null;
2409      if (isset($id_of_md5[$md5sum]))
2410      {
2411        $result[$md5sum] = $id_of_md5[$md5sum];
2412      }
2413    }
2414  }
[11893]2415
[4954]2416  if ('filename' == $conf['uniqueness_mode'])
[2683]2417  {
[4954]2418    // search among photos the list of photos already added, based on
2419    // filename list
2420    $filenames = preg_split(
2421      $split_pattern,
2422      $params['filename_list'],
2423      -1,
2424      PREG_SPLIT_NO_EMPTY
2425    );
2426
2427    $query = '
2428SELECT
2429    id,
2430    file
2431  FROM '.IMAGES_TABLE.'
2432  WHERE file IN (\''.implode("','", $filenames).'\')
2433;';
2434    $id_of_filename = simple_hash_from_query($query, 'file', 'id');
2435
2436    $result = array();
2437
2438    foreach ($filenames as $filename)
[2683]2439    {
[4954]2440      $result[$filename] = null;
2441      if (isset($id_of_filename[$filename]))
2442      {
2443        $result[$filename] = $id_of_filename[$filename];
2444      }
[2683]2445    }
2446  }
2447
2448  return $result;
2449}
[2919]2450
[4347]2451function ws_images_checkFiles($params, &$service)
2452{
[12906]2453  ws_logfile(__FUNCTION__.', input :  '.var_export($params, true));
2454
[8126]2455  if (!is_admin())
[4347]2456  {
2457    return new PwgError(401, 'Access denied');
2458  }
2459
2460  // input parameters
2461  //
2462  // image_id
2463  // thumbnail_sum
2464  // file_sum
2465  // high_sum
2466
2467  $params['image_id'] = (int)$params['image_id'];
2468  if ($params['image_id'] <= 0)
2469  {
2470    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2471  }
2472
2473  $query = '
2474SELECT
2475    path
2476  FROM '.IMAGES_TABLE.'
2477  WHERE id = '.$params['image_id'].'
2478;';
2479  $result = pwg_query($query);
[12906]2480  if (pwg_db_num_rows($result) == 0)
2481  {
[4347]2482    return new PwgError(404, "image_id not found");
2483  }
[6500]2484  list($path) = pwg_db_fetch_row($result);
[4347]2485
2486  $ret = array();
2487
[12906]2488  if (isset($params['thumbnail_sum']))
2489  {
2490    // We always say the thumbnail is equal to create no reaction on the
2491    // other side. Since Piwigo 2.4 and derivatives, the thumbnails and web
2492    // sizes are always generated by Piwigo
2493    $ret['thumbnail'] = 'equals';
2494  }
[4347]2495
[12906]2496  if (isset($params['high_sum']))
2497  {
2498    $ret['file'] = 'equals';
2499    $compare_type = 'high';
2500  }
2501  elseif (isset($params['file_sum']))
2502  {
2503    $compare_type = 'file';
2504  }
2505
2506  if (isset($compare_type))
2507  {
2508    ws_logfile(__FUNCTION__.', md5_file($path) = '.md5_file($path));
2509    if (md5_file($path) != $params[$compare_type.'_sum'])
2510    {
2511      $ret[$compare_type] = 'differs';
[4347]2512    }
[12906]2513    else
2514    {
2515      $ret[$compare_type] = 'equals';
2516    }
[4347]2517  }
2518
[12906]2519  ws_logfile(__FUNCTION__.', output :  '.var_export($ret, true));
2520
[4347]2521  return $ret;
2522}
2523
[2919]2524function ws_images_setInfo($params, &$service)
2525{
2526  global $conf;
[8126]2527  if (!is_admin())
[2919]2528  {
2529    return new PwgError(401, 'Access denied');
2530  }
2531
[4511]2532  if (!$service->isPost())
2533  {
2534    return new PwgError(405, "This method requires HTTP POST");
2535  }
2536
[2919]2537  $params['image_id'] = (int)$params['image_id'];
2538  if ($params['image_id'] <= 0)
2539  {
2540    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2541  }
2542
[7613]2543  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2544
[2919]2545  $query='
2546SELECT *
2547  FROM '.IMAGES_TABLE.'
2548  WHERE id = '.$params['image_id'].'
2549;';
2550
[4325]2551  $image_row = pwg_db_fetch_assoc(pwg_query($query));
[2919]2552  if ($image_row == null)
2553  {
2554    return new PwgError(404, "image_id not found");
2555  }
2556
2557  // database registration
[4460]2558  $update = array();
[2919]2559
2560  $info_columns = array(
2561    'name',
2562    'author',
2563    'comment',
2564    'level',
2565    'date_creation',
2566    );
2567
2568  foreach ($info_columns as $key)
2569  {
2570    if (isset($params[$key]))
2571    {
[4460]2572      if ('fill_if_empty' == $params['single_value_mode'])
2573      {
2574        if (empty($image_row[$key]))
2575        {
2576          $update[$key] = $params[$key];
2577        }
2578      }
2579      elseif ('replace' == $params['single_value_mode'])
2580      {
2581        $update[$key] = $params[$key];
2582      }
2583      else
2584      {
[12796]2585        return new PwgError(
[4460]2586          500,
2587          '[ws_images_setInfo]'
2588          .' invalid parameter single_value_mode "'.$params['single_value_mode'].'"'
2589          .', possible values are {fill_if_empty, replace}.'
2590          );
2591      }
[2919]2592    }
2593  }
2594
[12739]2595  if (isset($params['file']))
2596  {
2597    if (!empty($image_row['storage_category_id']))
2598    {
[12796]2599      return new PwgError(500, '[ws_images_setInfo] updating "file" is forbidden on photos added by synchronization');
[12739]2600    }
2601
2602    $update['file'] = $params['file'];
2603  }
2604
[4460]2605  if (count(array_keys($update)) > 0)
[2919]2606  {
[4460]2607    $update['id'] = $params['image_id'];
2608
[2919]2609    mass_updates(
2610      IMAGES_TABLE,
2611      array(
2612        'primary' => array('id'),
2613        'update'  => array_diff(array_keys($update), array('id'))
2614        ),
2615      array($update)
2616      );
2617  }
[3145]2618
[2919]2619  if (isset($params['categories']))
2620  {
2621    ws_add_image_category_relations(
2622      $params['image_id'],
[4445]2623      $params['categories'],
[4460]2624      ('replace' == $params['multiple_value_mode'] ? true : false)
[2919]2625      );
2626  }
2627
2628  // and now, let's create tag associations
2629  if (isset($params['tag_ids']))
2630  {
[4445]2631    $tag_ids = explode(',', $params['tag_ids']);
2632
[4460]2633    if ('replace' == $params['multiple_value_mode'])
[4445]2634    {
2635      set_tags(
2636        $tag_ids,
2637        $params['image_id']
2638        );
2639    }
[4460]2640    elseif ('append' == $params['multiple_value_mode'])
[4445]2641    {
2642      add_tags(
2643        $tag_ids,
2644        array($params['image_id'])
2645        );
2646    }
[4460]2647    else
2648    {
[12796]2649      return new PwgError(
[4460]2650        500,
2651        '[ws_images_setInfo]'
2652        .' invalid parameter multiple_value_mode "'.$params['multiple_value_mode'].'"'
2653        .', possible values are {replace, append}.'
2654        );
2655    }
[2919]2656  }
2657
2658  invalidate_user_cache();
2659}
2660
[8266]2661function ws_images_delete($params, &$service)
2662{
2663  global $conf;
[8274]2664  if (!is_admin())
[8266]2665  {
2666    return new PwgError(401, 'Access denied');
2667  }
2668
2669  if (!$service->isPost())
2670  {
2671    return new PwgError(405, "This method requires HTTP POST");
2672  }
2673
2674  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2675  {
2676    return new PwgError(403, 'Invalid security token');
2677  }
2678
2679  $params['image_id'] = preg_split(
2680    '/[\s,;\|]/',
2681    $params['image_id'],
2682    -1,
2683    PREG_SPLIT_NO_EMPTY
2684    );
2685  $params['image_id'] = array_map('intval', $params['image_id']);
2686
2687  $image_ids = array();
2688  foreach ($params['image_id'] as $image_id)
2689  {
2690    if ($image_id > 0)
2691    {
2692      array_push($image_ids, $image_id);
2693    }
2694  }
2695
2696  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2697  delete_elements($image_ids, true);
2698}
2699
[4445]2700function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
[2919]2701{
2702  // let's add links between the image and the categories
2703  //
2704  // $params['categories'] should look like 123,12;456,auto;789 which means:
2705  //
2706  // 1. associate with category 123 on rank 12
2707  // 2. associate with category 456 on automatic rank
2708  // 3. associate with category 789 on automatic rank
2709  $cat_ids = array();
2710  $rank_on_category = array();
2711  $search_current_ranks = false;
2712
2713  $tokens = explode(';', $categories_string);
2714  foreach ($tokens as $token)
2715  {
[2920]2716    @list($cat_id, $rank) = explode(',', $token);
[2919]2717
[4445]2718    if (!preg_match('/^\d+$/', $cat_id))
2719    {
2720      continue;
2721    }
2722
[2919]2723    array_push($cat_ids, $cat_id);
2724
2725    if (!isset($rank))
2726    {
2727      $rank = 'auto';
2728    }
2729    $rank_on_category[$cat_id] = $rank;
2730
2731    if ($rank == 'auto')
2732    {
2733      $search_current_ranks = true;
2734    }
2735  }
2736
2737  $cat_ids = array_unique($cat_ids);
2738
[4445]2739  if (count($cat_ids) == 0)
[2919]2740  {
[12796]2741    return new PwgError(
[4445]2742      500,
2743      '[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
2744      );
2745  }
[4513]2746
[4445]2747  $query = '
2748SELECT
2749    id
2750  FROM '.CATEGORIES_TABLE.'
2751  WHERE id IN ('.implode(',', $cat_ids).')
2752;';
2753  $db_cat_ids = array_from_query($query, 'id');
2754
2755  $unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
2756  if (count($unknown_cat_ids) != 0)
2757  {
[12796]2758    return new PwgError(
[4445]2759      500,
2760      '[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
2761      );
2762  }
[4513]2763
[4445]2764  $to_update_cat_ids = array();
[4513]2765
[4445]2766  // in case of replace mode, we first check the existing associations
2767  $query = '
2768SELECT
2769    category_id
2770  FROM '.IMAGE_CATEGORY_TABLE.'
2771  WHERE image_id = '.$image_id.'
2772;';
2773  $existing_cat_ids = array_from_query($query, 'category_id');
2774
2775  if ($replace_mode)
2776  {
2777    $to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
2778    if (count($to_remove_cat_ids) > 0)
[2919]2779    {
2780      $query = '
[4445]2781DELETE
2782  FROM '.IMAGE_CATEGORY_TABLE.'
2783  WHERE image_id = '.$image_id.'
2784    AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
2785;';
2786      pwg_query($query);
2787      update_category($to_remove_cat_ids);
2788    }
2789  }
[4513]2790
[4445]2791  $new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
2792  if (count($new_cat_ids) == 0)
2793  {
2794    return true;
2795  }
[4513]2796
[4445]2797  if ($search_current_ranks)
2798  {
2799    $query = '
[2919]2800SELECT
2801    category_id,
2802    MAX(rank) AS max_rank
2803  FROM '.IMAGE_CATEGORY_TABLE.'
2804  WHERE rank IS NOT NULL
[4445]2805    AND category_id IN ('.implode(',', $new_cat_ids).')
[2919]2806  GROUP BY category_id
2807;';
[4445]2808    $current_rank_of = simple_hash_from_query(
2809      $query,
2810      'category_id',
2811      'max_rank'
2812      );
[2919]2813
[4445]2814    foreach ($new_cat_ids as $cat_id)
2815    {
2816      if (!isset($current_rank_of[$cat_id]))
[2919]2817      {
[4445]2818        $current_rank_of[$cat_id] = 0;
[2919]2819      }
[4513]2820
[4445]2821      if ('auto' == $rank_on_category[$cat_id])
2822      {
2823        $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
2824      }
[2919]2825    }
[4445]2826  }
[4513]2827
[4445]2828  $inserts = array();
[4513]2829
[4445]2830  foreach ($new_cat_ids as $cat_id)
2831  {
2832    array_push(
2833      $inserts,
2834      array(
2835        'image_id' => $image_id,
2836        'category_id' => $cat_id,
2837        'rank' => $rank_on_category[$cat_id],
2838        )
[2919]2839      );
2840  }
[4513]2841
[4445]2842  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2843  mass_inserts(
2844    IMAGE_CATEGORY_TABLE,
2845    array_keys($inserts[0]),
2846    $inserts
2847    );
[4513]2848
[4445]2849  update_category($new_cat_ids);
[2919]2850}
[3193]2851
[3454]2852function ws_categories_setInfo($params, &$service)
2853{
2854  global $conf;
[8126]2855  if (!is_admin())
[3454]2856  {
2857    return new PwgError(401, 'Access denied');
2858  }
2859
[4511]2860  if (!$service->isPost())
2861  {
2862    return new PwgError(405, "This method requires HTTP POST");
2863  }
2864
[3454]2865  // category_id
2866  // name
2867  // comment
2868
2869  $params['category_id'] = (int)$params['category_id'];
2870  if ($params['category_id'] <= 0)
2871  {
2872    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2873  }
2874
2875  // database registration
2876  $update = array(
2877    'id' => $params['category_id'],
2878    );
2879
2880  $info_columns = array(
2881    'name',
2882    'comment',
2883    );
2884
2885  $perform_update = false;
2886  foreach ($info_columns as $key)
2887  {
2888    if (isset($params[$key]))
2889    {
2890      $perform_update = true;
2891      $update[$key] = $params[$key];
2892    }
2893  }
2894
2895  if ($perform_update)
2896  {
2897    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2898    mass_updates(
2899      CATEGORIES_TABLE,
2900      array(
2901        'primary' => array('id'),
2902        'update'  => array_diff(array_keys($update), array('id'))
2903        ),
2904      array($update)
2905      );
2906  }
[3488]2907
[3454]2908}
2909
[11746]2910function ws_categories_setRepresentative($params, &$service)
2911{
2912  global $conf;
[11893]2913
[11746]2914  if (!is_admin())
2915  {
2916    return new PwgError(401, 'Access denied');
2917  }
2918
2919  if (!$service->isPost())
2920  {
2921    return new PwgError(405, "This method requires HTTP POST");
2922  }
2923
2924  // category_id
2925  // image_id
2926
2927  $params['category_id'] = (int)$params['category_id'];
2928  if ($params['category_id'] <= 0)
2929  {
2930    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2931  }
2932
2933  // does the category really exist?
2934  $query='
2935SELECT
2936    *
2937  FROM '.CATEGORIES_TABLE.'
2938  WHERE id = '.$params['category_id'].'
2939;';
2940  $row = pwg_db_fetch_assoc(pwg_query($query));
2941  if ($row == null)
2942  {
2943    return new PwgError(404, "category_id not found");
2944  }
2945
2946  $params['image_id'] = (int)$params['image_id'];
2947  if ($params['image_id'] <= 0)
2948  {
2949    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2950  }
[11893]2951
[11746]2952  // does the image really exist?
2953  $query='
2954SELECT
2955    *
2956  FROM '.IMAGES_TABLE.'
2957  WHERE id = '.$params['image_id'].'
2958;';
2959
2960  $row = pwg_db_fetch_assoc(pwg_query($query));
2961  if ($row == null)
2962  {
2963    return new PwgError(404, "image_id not found");
2964  }
2965
2966  // apply change
2967  $query = '
2968UPDATE '.CATEGORIES_TABLE.'
2969  SET representative_picture_id = '.$params['image_id'].'
2970  WHERE id = '.$params['category_id'].'
2971;';
2972  pwg_query($query);
2973
2974  $query = '
2975UPDATE '.USER_CACHE_CATEGORIES_TABLE.'
2976  SET user_representative_picture_id = NULL
2977  WHERE cat_id = '.$params['category_id'].'
2978;';
2979  pwg_query($query);
2980}
2981
[8266]2982function ws_categories_delete($params, &$service)
2983{
2984  global $conf;
[8274]2985  if (!is_admin())
[8266]2986  {
2987    return new PwgError(401, 'Access denied');
2988  }
2989
2990  if (!$service->isPost())
2991  {
2992    return new PwgError(405, "This method requires HTTP POST");
2993  }
2994
2995  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2996  {
2997    return new PwgError(403, 'Invalid security token');
2998  }
2999
3000  $modes = array('no_delete', 'delete_orphans', 'force_delete');
3001  if (!in_array($params['photo_deletion_mode'], $modes))
3002  {
3003    return new PwgError(
3004      500,
3005      '[ws_categories_delete]'
3006      .' invalid parameter photo_deletion_mode "'.$params['photo_deletion_mode'].'"'
3007      .', possible values are {'.implode(', ', $modes).'}.'
3008      );
3009  }
3010
3011  $params['category_id'] = preg_split(
3012    '/[\s,;\|]/',
3013    $params['category_id'],
3014    -1,
3015    PREG_SPLIT_NO_EMPTY
3016    );
3017  $params['category_id'] = array_map('intval', $params['category_id']);
3018
3019  $category_ids = array();
3020  foreach ($params['category_id'] as $category_id)
3021  {
3022    if ($category_id > 0)
3023    {
3024      array_push($category_ids, $category_id);
3025    }
3026  }
3027
3028  if (count($category_ids) == 0)
3029  {
3030    return;
3031  }
3032
3033  $query = '
3034SELECT id
3035  FROM '.CATEGORIES_TABLE.'
3036  WHERE id IN ('.implode(',', $category_ids).')
3037;';
3038  $category_ids = array_from_query($query, 'id');
3039
3040  if (count($category_ids) == 0)
3041  {
3042    return;
3043  }
[11893]3044
[8266]3045  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3046  delete_categories($category_ids, $params['photo_deletion_mode']);
3047  update_global_rank();
3048}
3049
[8272]3050function ws_categories_move($params, &$service)
3051{
3052  global $conf, $page;
[11893]3053
[8274]3054  if (!is_admin())
[8272]3055  {
3056    return new PwgError(401, 'Access denied');
3057  }
3058
3059  if (!$service->isPost())
3060  {
3061    return new PwgError(405, "This method requires HTTP POST");
3062  }
3063
3064  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3065  {
3066    return new PwgError(403, 'Invalid security token');
3067  }
3068
3069  $params['category_id'] = preg_split(
3070    '/[\s,;\|]/',
3071    $params['category_id'],
3072    -1,
3073    PREG_SPLIT_NO_EMPTY
3074    );
3075  $params['category_id'] = array_map('intval', $params['category_id']);
3076
3077  $category_ids = array();
3078  foreach ($params['category_id'] as $category_id)
3079  {
3080    if ($category_id > 0)
3081    {
3082      array_push($category_ids, $category_id);
3083    }
3084  }
3085
3086  if (count($category_ids) == 0)
3087  {
3088    return new PwgError(403, 'Invalid category_id input parameter, no category to move');
3089  }
3090
3091  // we can't move physical categories
3092  $categories_in_db = array();
[11893]3093
[8272]3094  $query = '
3095SELECT
3096    id,
3097    name,
3098    dir
3099  FROM '.CATEGORIES_TABLE.'
3100  WHERE id IN ('.implode(',', $category_ids).')
3101;';
3102  $result = pwg_query($query);
3103  while ($row = pwg_db_fetch_assoc($result))
3104  {
3105    $categories_in_db[$row['id']] = $row;
3106    // we break on error at first physical category detected
3107    if (!empty($row['dir']))
3108    {
3109      $row['name'] = strip_tags(
3110        trigger_event(
3111          'render_category_name',
3112          $row['name'],
3113          'ws_categories_move'
3114          )
3115        );
[11893]3116
[8272]3117      return new PwgError(
3118        403,
3119        sprintf(
3120          'Category %s (%u) is not a virtual category, you cannot move it',
3121          $row['name'],
3122          $row['id']
3123          )
3124        );
3125    }
3126  }
3127
3128  if (count($categories_in_db) != count($category_ids))
3129  {
3130    $unknown_category_ids = array_diff($category_ids, array_keys($categories_in_db));
[11893]3131
[8272]3132    return new PwgError(
3133      403,
3134      sprintf(
3135        'Category %u does not exist',
3136        $unknown_category_ids[0]
3137        )
3138      );
3139  }
3140
3141  // does this parent exists? This check should be made in the
3142  // move_categories function, not here
3143  //
3144  // 0 as parent means "move categories at gallery root"
3145  if (!is_numeric($params['parent']))
3146  {
3147    return new PwgError(403, 'Invalid parent input parameter');
3148  }
[11893]3149
[8272]3150  if (0 != $params['parent']) {
3151    $params['parent'] = intval($params['parent']);
3152    $subcat_ids = get_subcat_ids(array($params['parent']));
3153    if (count($subcat_ids) == 0)
3154    {
3155      return new PwgError(403, 'Unknown parent category id');
3156    }
3157  }
3158
3159  $page['infos'] = array();
3160  $page['errors'] = array();
3161  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3162  move_categories($category_ids, $params['parent']);
3163  invalidate_user_cache();
3164
3165  if (count($page['errors']) != 0)
3166  {
3167    return new PwgError(403, implode('; ', $page['errors']));
3168  }
3169}
3170
[3193]3171function ws_logfile($string)
3172{
[3662]3173  global $conf;
[3488]3174
[3662]3175  if (!$conf['ws_enable_log']) {
3176    return true;
3177  }
3178
[3193]3179  file_put_contents(
[3662]3180    $conf['ws_log_filepath'],
[3193]3181    '['.date('c').'] '.$string."\n",
3182    FILE_APPEND
3183    );
3184}
[6049]3185
3186function ws_images_checkUpload($params, &$service)
3187{
3188  global $conf;
3189
[8126]3190  if (!is_admin())
[6049]3191  {
3192    return new PwgError(401, 'Access denied');
3193  }
3194
[8249]3195  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[6051]3196  $ret['message'] = ready_for_upload_message();
3197  $ret['ready_for_upload'] = true;
[11893]3198
[6051]3199  if (!empty($ret['message']))
3200  {
3201    $ret['ready_for_upload'] = false;
3202  }
[11893]3203
[6051]3204  return $ret;
3205}
[8273]3206
3207function ws_plugins_getList($params, &$service)
3208{
3209  global $conf;
[11893]3210
[8273]3211  if (!is_admin())
3212  {
3213    return new PwgError(401, 'Access denied');
3214  }
3215
3216  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3217  $plugins = new plugins();
3218  $plugins->sort_fs_plugins('name');
3219  $plugin_list = array();
3220
3221  foreach($plugins->fs_plugins as $plugin_id => $fs_plugin)
3222  {
3223    if (isset($plugins->db_plugins_by_id[$plugin_id]))
3224    {
3225      $state = $plugins->db_plugins_by_id[$plugin_id]['state'];
3226    }
3227    else
3228    {
3229      $state = 'uninstalled';
3230    }
3231
3232    array_push(
3233      $plugin_list,
3234      array(
3235        'id' => $plugin_id,
3236        'name' => $fs_plugin['name'],
3237        'version' => $fs_plugin['version'],
3238        'state' => $state,
3239        'description' => $fs_plugin['description'],
3240        )
3241      );
3242  }
3243
3244  return $plugin_list;
3245}
3246
3247function ws_plugins_performAction($params, &$service)
3248{
3249  global $template;
[11893]3250
[8273]3251  if (!is_admin())
3252  {
3253    return new PwgError(401, 'Access denied');
3254  }
3255
3256  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3257  {
3258    return new PwgError(403, 'Invalid security token');
3259  }
3260
3261  define('IN_ADMIN', true);
3262  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3263  $plugins = new plugins();
3264  $errors = $plugins->perform_action($params['action'], $params['plugin']);
3265
[11893]3266
[8273]3267  if (!empty($errors))
3268  {
3269    return new PwgError(500, $errors);
3270  }
3271  else
3272  {
3273    if (in_array($params['action'], array('activate', 'deactivate')))
3274    {
3275      $template->delete_compiled_templates();
3276    }
3277    return true;
3278  }
3279}
3280
[8297]3281function ws_themes_performAction($params, &$service)
3282{
3283  global $template;
[11893]3284
[8726]3285  if (!is_admin())
[8297]3286  {
3287    return new PwgError(401, 'Access denied');
3288  }
3289
3290  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3291  {
3292    return new PwgError(403, 'Invalid security token');
3293  }
3294
3295  define('IN_ADMIN', true);
3296  include_once(PHPWG_ROOT_PATH.'admin/include/themes.class.php');
3297  $themes = new themes();
3298  $errors = $themes->perform_action($params['action'], $params['theme']);
[11893]3299
[8297]3300  if (!empty($errors))
3301  {
3302    return new PwgError(500, $errors);
3303  }
3304  else
3305  {
3306    if (in_array($params['action'], array('activate', 'deactivate')))
3307    {
3308      $template->delete_compiled_templates();
3309    }
3310    return true;
3311  }
3312}
[10235]3313
[10511]3314function ws_extensions_update($params, &$service)
3315{
3316  if (!is_webmaster())
3317  {
3318    return new PwgError(401, l10n('Webmaster status is required.'));
3319  }
3320
3321  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3322  {
3323    return new PwgError(403, 'Invalid security token');
3324  }
3325
3326  if (empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3327  {
3328    return new PwgError(403, "invalid extension type");
3329  }
3330
3331  if (empty($params['id']) or empty($params['revision']))
3332  {
3333    return new PwgError(null, 'Wrong parameters');
3334  }
3335
3336  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3337  include_once(PHPWG_ROOT_PATH.'admin/include/'.$params['type'].'.class.php');
3338
3339  $type = $params['type'];
3340  $extension_id = $params['id'];
3341  $revision = $params['revision'];
3342
3343  $extension = new $type();
3344
3345  if ($type == 'plugins')
3346  {
3347    if (isset($extension->db_plugins_by_id[$extension_id]) and $extension->db_plugins_by_id[$extension_id]['state'] == 'active')
3348    {
3349      $extension->perform_action('deactivate', $extension_id);
3350
3351      redirect(PHPWG_ROOT_PATH
3352        . 'ws.php'
3353        . '?method=pwg.extensions.update'
3354        . '&type=plugins'
3355        . '&id=' . $extension_id
3356        . '&revision=' . $revision
3357        . '&reactivate=true'
3358        . '&pwg_token=' . get_pwg_token()
3359        . '&format=json'
3360      );
3361    }
[11893]3362
[10511]3363    $upgrade_status = $extension->extract_plugin_files('upgrade', $revision, $extension_id);
3364    $extension_name = $extension->fs_plugins[$extension_id]['name'];
3365
3366    if (isset($params['reactivate']))
3367    {
3368      $extension->perform_action('activate', $extension_id);
3369    }
3370  }
3371  elseif ($type == 'themes')
3372  {
3373    $upgrade_status = $extension->extract_theme_files('upgrade', $revision, $extension_id);
3374    $extension_name = $extension->fs_themes[$extension_id]['name'];
3375  }
3376  elseif ($type == 'languages')
3377  {
3378    $upgrade_status = $extension->extract_language_files('upgrade', $revision, $extension_id);
3379    $extension_name = $extension->fs_languages[$extension_id]['name'];
3380  }
3381
3382  global $template;
3383  $template->delete_compiled_templates();
3384
3385  switch ($upgrade_status)
3386  {
3387    case 'ok':
3388      return sprintf(l10n('%s has been successfully updated.'), $extension_name);
3389
3390    case 'temp_path_error':
3391      return new PwgError(null, l10n('Can\'t create temporary file.'));
3392
3393    case 'dl_archive_error':
3394      return new PwgError(null, l10n('Can\'t download archive.'));
3395
3396    case 'archive_error':
3397      return new PwgError(null, l10n('Can\'t read or extract archive.'));
3398
3399    default:
3400      return new PwgError(null, sprintf(l10n('An error occured during extraction (%s).'), $upgrade_status));
3401  }
3402}
3403
3404function ws_extensions_ignoreupdate($params, &$service)
3405{
3406  global $conf;
3407
3408  define('IN_ADMIN', true);
3409  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3410
3411  if (!is_webmaster())
3412  {
3413    return new PwgError(401, 'Access denied');
3414  }
3415
3416  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3417  {
3418    return new PwgError(403, 'Invalid security token');
3419  }
3420
3421  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3422
[10538]3423  // Reset ignored extension
[10511]3424  if ($params['reset'])
3425  {
[10596]3426    if (!empty($params['type']) and isset($conf['updates_ignored'][$params['type']]))
3427    {
3428      $conf['updates_ignored'][$params['type']] = array();
3429    }
3430    else
3431    {
3432      $conf['updates_ignored'] = array(
3433        'plugins'=>array(),
3434        'themes'=>array(),
3435        'languages'=>array()
3436      );
3437    }
[10511]3438    conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3439    unset($_SESSION['extensions_need_update']);
3440    return true;
3441  }
3442
3443  if (empty($params['id']) or empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3444  {
3445    return new PwgError(403, 'Invalid parameters');
3446  }
3447
3448  // Add or remove extension from ignore list
3449  if (!in_array($params['id'], $conf['updates_ignored'][$params['type']]))
3450  {
3451    array_push($conf['updates_ignored'][$params['type']], $params['id']);
3452  }
3453  conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3454  unset($_SESSION['extensions_need_update']);
3455  return true;
3456}
[10538]3457
3458function ws_extensions_checkupdates($params, &$service)
3459{
3460  global $conf;
3461
3462  define('IN_ADMIN', true);
3463  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3464  include_once(PHPWG_ROOT_PATH.'admin/include/updates.class.php');
3465  $update = new updates();
3466
3467  if (!is_admin())
3468  {
3469    return new PwgError(401, 'Access denied');
3470  }
3471
3472  $result = array();
3473
3474  if (!isset($_SESSION['need_update']))
3475    $update->check_piwigo_upgrade();
3476
3477  $result['piwigo_need_update'] = $_SESSION['need_update'];
3478
3479  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3480
3481  if (!isset($_SESSION['extensions_need_update']))
3482    $update->check_extensions();
3483  else
3484    $update->check_updated_extensions();
3485
3486  if (!is_array($_SESSION['extensions_need_update']))
3487    $result['ext_need_update'] = null;
3488  else
3489    $result['ext_need_update'] = !empty($_SESSION['extensions_need_update']);
3490
3491  return $result;
3492}
[12728]3493?>
Note: See TracBrowser for help on using the repository browser.