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

Last change on this file since 23060 was 23060, checked in by plg, 11 years ago

merge r23059 from branch 2.5 to trunk

bug 2917 fixed: invalidate user cache each time pwg.images.delete is called,
to avoid blocking errors on gallery side if deleted photo is set as album
thumbnail.

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