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

Last change on this file since 25026 was 25019, checked in by mistic100, 11 years ago

replace some mass_updates/inserts by single_update/insert

  • Property svn:eol-style set to LF
File size: 83.3 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    $datas[] = array('element_id'=>$id, 'user_id'=>$user['id']);
405  }
406  if (count($datas))
407  {
408    mass_inserts(
409      CADDIE_TABLE,
410      array('element_id','user_id'),
411      $datas
412      );
413  }
414  return count($datas);
415}
416
417/**
418 * returns images per category (web service method)
419 */
420function ws_categories_getImages($params, $service)
421{
422  global $user, $conf;
423
424  $images = array();
425
426  //------------------------------------------------- get the related categories
427  $where_clauses = array();
428  foreach($params['cat_id'] as $cat_id)
429  {
430    $cat_id = (int)$cat_id;
431    if ($cat_id<=0)
432      continue;
433    if ($params['recursive'])
434    {
435      $where_clauses[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.$cat_id.'(,|$)\'';
436    }
437    else
438    {
439      $where_clauses[] = 'id='.$cat_id;
440    }
441  }
442  if (!empty($where_clauses))
443  {
444    $where_clauses = array( '('.
445    implode('
446    OR ', $where_clauses) . ')'
447      );
448  }
449  $where_clauses[] = get_sql_condition_FandF(
450        array('forbidden_categories' => 'id'),
451        NULL, true
452      );
453
454  $query = '
455SELECT id, name, permalink, image_order
456  FROM '.CATEGORIES_TABLE.'
457  WHERE '. implode('
458    AND ', $where_clauses);
459  $result = pwg_query($query);
460  $cats = array();
461  while ($row = pwg_db_fetch_assoc($result))
462  {
463    $row['id'] = (int)$row['id'];
464    $cats[ $row['id'] ] = $row;
465  }
466
467  //-------------------------------------------------------- get the images
468  if ( !empty($cats) )
469  {
470    $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
471    $where_clauses[] = 'category_id IN ('
472      .implode(',', array_keys($cats) )
473      .')';
474    $where_clauses[] = get_sql_condition_FandF( array(
475          'visible_images' => 'i.id'
476        ), null, true
477      );
478
479    $order_by = ws_std_image_sql_order($params, 'i.');
480    if ( empty($order_by)
481          and count($params['cat_id'])==1
482          and isset($cats[ $params['cat_id'][0] ]['image_order'])
483        )
484    {
485      $order_by = $cats[ $params['cat_id'][0] ]['image_order'];
486    }
487    $order_by = empty($order_by) ? $conf['order_by'] : 'ORDER BY '.$order_by;
488
489    $params['per_page'] = (int)$params['per_page'];
490    $params['page'] = (int)$params['page'];
491
492    $query = '
493SELECT i.*, GROUP_CONCAT(category_id) AS cat_ids
494  FROM '.IMAGES_TABLE.' i
495    INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
496  WHERE '. implode('
497    AND ', $where_clauses).'
498GROUP BY i.id
499'.$order_by.'
500LIMIT '.$params['per_page'].' OFFSET '.($params['per_page']*$params['page']);
501
502    $result = pwg_query($query);
503    while ($row = pwg_db_fetch_assoc($result))
504    {
505      $image = array();
506      foreach ( array('id', 'width', 'height', 'hit') as $k )
507      {
508        if (isset($row[$k]))
509        {
510          $image[$k] = (int)$row[$k];
511        }
512      }
513      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
514      {
515        $image[$k] = $row[$k];
516      }
517      $image = array_merge( $image, ws_std_get_urls($row) );
518
519      $image_cats = array();
520      foreach ( explode(',', $row['cat_ids']) as $cat_id )
521      {
522        $url = make_index_url(
523                array(
524                  'category' => $cats[$cat_id],
525                  )
526                );
527        $page_url = make_picture_url(
528                array(
529                  'category' => $cats[$cat_id],
530                  'image_id' => $row['id'],
531                  'image_file' => $row['file'],
532                  )
533                );
534        $image_cats[] = array (
535                'id' => (int)$cat_id,
536                'url' => $url,
537                'page_url' => $page_url,
538            );
539      }
540
541      $image['categories'] = new PwgNamedArray(
542            $image_cats,'category', array('id','url','page_url')
543          );
544      $images[] = $image;
545    }
546  }
547
548  return array (
549      'paging' => new PwgNamedStruct(
550        array(
551            'page' => $params['page'],
552            'per_page' => $params['per_page'],
553            'count' => count($images)
554          ) ),
555       'images' => new PwgNamedArray($images, 'image', ws_std_get_image_xml_attributes() )
556    );
557}
558
559
560/**
561 * create a tree from a flat list of categories, no recursivity for high speed
562 */
563function categories_flatlist_to_tree($categories)
564{
565  $tree = array();
566  $key_of_cat = array();
567
568  foreach ($categories as $key => &$node)
569  {
570    $key_of_cat[$node['id']] = $key;
571
572    if (!isset($node['id_uppercat']))
573    {
574      $tree[] = &$node;
575    }
576    else
577    {
578      if (!isset($categories[ $key_of_cat[ $node['id_uppercat'] ] ]['sub_categories']))
579      {
580        $categories[ $key_of_cat[ $node['id_uppercat'] ] ]['sub_categories'] = new PwgNamedArray(array(), 'category', ws_std_get_category_xml_attributes());
581      }
582
583      $categories[ $key_of_cat[ $node['id_uppercat'] ] ]['sub_categories']->_content[] = &$node;
584    }
585  }
586
587  return $tree;
588}
589
590/**
591 * returns a list of categories (web service method)
592 */
593function ws_categories_getList($params, $service)
594{
595  global $user,$conf;
596
597  $where = array('1=1');
598  $join_type = 'INNER';
599  $join_user = $user['id'];
600
601  if (!$params['recursive'])
602  {
603    if ($params['cat_id']>0)
604      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
605    OR id='.(int)($params['cat_id']).')';
606    else
607      $where[] = 'id_uppercat IS NULL';
608  }
609  elseif ($params['cat_id']>0)
610  {
611    $where[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.
612      (int)($params['cat_id'])
613      .'(,|$)\'';
614  }
615
616  if ($params['public'])
617  {
618    $where[] = 'status = "public"';
619    $where[] = 'visible = "true"';
620
621    $join_user = $conf['guest_id'];
622  }
623  elseif (is_admin())
624  {
625    // in this very specific case, we don't want to hide empty
626    // categories. Function calculate_permissions will only return
627    // categories that are either locked or private and not permitted
628    //
629    // calculate_permissions does not consider empty categories as forbidden
630    $forbidden_categories = calculate_permissions($user['id'], $user['status']);
631    $where[]= 'id NOT IN ('.$forbidden_categories.')';
632    $join_type = 'LEFT';
633  }
634
635  $query = '
636SELECT id, name, permalink, uppercats, global_rank, id_uppercat,
637    comment,
638    nb_images, count_images AS total_nb_images,
639    representative_picture_id, user_representative_picture_id, count_images, count_categories,
640    date_last, max_date_last, count_categories AS nb_categories
641  FROM '.CATEGORIES_TABLE.'
642   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
643  WHERE '. implode('
644    AND ', $where);
645
646  $result = pwg_query($query);
647
648  // management of the album thumbnail -- starts here
649  $image_ids = array();
650  $categories = array();
651  $user_representative_updates_for = array();
652  // management of the album thumbnail -- stops here
653
654  $cats = array();
655  while ($row = pwg_db_fetch_assoc($result))
656  {
657    $row['url'] = make_index_url(
658        array(
659          'category' => $row
660          )
661      );
662    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
663    {
664      $row[$key] = (int)$row[$key];
665    }
666
667    if ($params['fullname'])
668    {
669      $row['name'] = strip_tags(get_cat_display_name_cache($row['uppercats'], null, false));
670    }
671    else
672    {
673      $row['name'] = strip_tags(
674        trigger_event(
675          'render_category_name',
676          $row['name'],
677          'ws_categories_getList'
678          )
679        );
680    }
681
682    $row['comment'] = strip_tags(
683      trigger_event(
684        'render_category_description',
685        $row['comment'],
686        'ws_categories_getList'
687        )
688      );
689
690    // management of the album thumbnail -- starts here
691    //
692    // on branch 2.3, the algorithm is duplicated from
693    // include/category_cats, but we should use a common code for Piwigo 2.4
694    //
695    // warning : if the API method is called with $params['public'], the
696    // album thumbnail may be not accurate. The thumbnail can be viewed by
697    // the connected user, but maybe not by the guest. Changing the
698    // filtering method would be too complicated for now. We will simply
699    // avoid to persist the user_representative_picture_id in the database
700    // if $params['public']
701    if (!empty($row['user_representative_picture_id']))
702    {
703      $image_id = $row['user_representative_picture_id'];
704    }
705    elseif (!empty($row['representative_picture_id']))
706    { // if a representative picture is set, it has priority
707      $image_id = $row['representative_picture_id'];
708    }
709    elseif ($conf['allow_random_representative'])
710    {
711      // searching a random representant among elements in sub-categories
712      $image_id = get_random_image_in_category($row);
713    }
714    else
715    { // searching a random representant among representant of sub-categories
716      if ($row['count_categories']>0 and $row['count_images']>0)
717      {
718        $query = '
719  SELECT representative_picture_id
720    FROM '.CATEGORIES_TABLE.' INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.'
721    ON id = cat_id and user_id = '.$user['id'].'
722    WHERE uppercats LIKE \''.$row['uppercats'].',%\'
723      AND representative_picture_id IS NOT NULL'
724          .get_sql_condition_FandF
725          (
726            array
727            (
728              'visible_categories' => 'id',
729              ),
730            "\n  AND"
731            ).'
732    ORDER BY '.DB_RANDOM_FUNCTION.'()
733    LIMIT 1
734  ;';
735        $subresult = pwg_query($query);
736        if (pwg_db_num_rows($subresult) > 0)
737        {
738          list($image_id) = pwg_db_fetch_row($subresult);
739        }
740      }
741    }
742
743    if (isset($image_id))
744    {
745      if ($conf['representative_cache_on_subcats'] and $row['user_representative_picture_id'] != $image_id)
746      {
747        $user_representative_updates_for[ $row['id'] ] = $image_id;
748      }
749
750      $row['representative_picture_id'] = $image_id;
751      $image_ids[] = $image_id;
752      $categories[] = $row;
753    }
754    unset($image_id);
755    // management of the album thumbnail -- stops here
756
757
758    $cats[] = $row;
759  }
760  usort($cats, 'global_rank_compare');
761
762  // management of the album thumbnail -- starts here
763  if (count($categories) > 0)
764  {
765    $thumbnail_src_of = array();
766    $new_image_ids = array();
767
768    $query = '
769SELECT id, path, representative_ext, level
770  FROM '.IMAGES_TABLE.'
771  WHERE id IN ('.implode(',', $image_ids).')
772;';
773    $result = pwg_query($query);
774    while ($row = pwg_db_fetch_assoc($result))
775    {
776      if ($row['level'] <= $user['level'])
777      {
778        $thumbnail_src_of[$row['id']] = DerivativeImage::thumb_url($row);
779      }
780      else
781      {
782        // problem: we must not display the thumbnail of a photo which has a
783        // higher privacy level than user privacy level
784        //
785        // * what is the represented category?
786        // * find a random photo matching user permissions
787        // * register it at user_representative_picture_id
788        // * set it as the representative_picture_id for the category
789
790        foreach ($categories as &$category)
791        {
792          if ($row['id'] == $category['representative_picture_id'])
793          {
794            // searching a random representant among elements in sub-categories
795            $image_id = get_random_image_in_category($category);
796
797            if (isset($image_id) and !in_array($image_id, $image_ids))
798            {
799              $new_image_ids[] = $image_id;
800            }
801
802            if ($conf['representative_cache_on_level'])
803            {
804              $user_representative_updates_for[ $category['id'] ] = $image_id;
805            }
806
807            $category['representative_picture_id'] = $image_id;
808          }
809        }
810        unset($category);
811      }
812    }
813
814    if (count($new_image_ids) > 0)
815    {
816      $query = '
817SELECT id, path, representative_ext
818  FROM '.IMAGES_TABLE.'
819  WHERE id IN ('.implode(',', $new_image_ids).')
820;';
821      $result = pwg_query($query);
822      while ($row = pwg_db_fetch_assoc($result))
823      {
824        $thumbnail_src_of[$row['id']] = DerivativeImage::thumb_url($row);
825      }
826    }
827  }
828
829  // compared to code in include/category_cats, we only persist the new
830  // user_representative if we have used $user['id'] and not the guest id,
831  // or else the real guest may see thumbnail that he should not
832  if (!$params['public'] and count($user_representative_updates_for))
833  {
834    $updates = array();
835
836    foreach ($user_representative_updates_for as $cat_id => $image_id)
837    {
838      $updates[] = array(
839        'user_id' => $user['id'],
840        'cat_id' => $cat_id,
841        'user_representative_picture_id' => $image_id,
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      $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    $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        $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        $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    $query='
1733SELECT *
1734  FROM '.IMAGES_TABLE.'
1735  WHERE id = '.$params['image_id'].'
1736;';
1737
1738    $image_row = pwg_db_fetch_assoc(pwg_query($query));
1739    if ($image_row == null)
1740    {
1741      return new PwgError(404, "image_id not found");
1742    }
1743  }
1744
1745  // does the image already exists ?
1746  if ($params['check_uniqueness'])
1747  {
1748    if ('md5sum' == $conf['uniqueness_mode'])
1749    {
1750      $where_clause = "md5sum = '".$params['original_sum']."'";
1751    }
1752    if ('filename' == $conf['uniqueness_mode'])
1753    {
1754      $where_clause = "file = '".$params['original_filename']."'";
1755    }
1756
1757    $query = '
1758SELECT
1759    COUNT(*) AS counter
1760  FROM '.IMAGES_TABLE.'
1761  WHERE '.$where_clause.'
1762;';
1763    list($counter) = pwg_db_fetch_row(pwg_query($query));
1764    if ($counter != 0) {
1765      return new PwgError(500, 'file already exists');
1766    }
1767  }
1768
1769  // due to the new feature "derivatives" (multiple sizes) introduced for
1770  // Piwigo 2.4, we only take the biggest photos sent on
1771  // pwg.images.addChunk. If "high" is available we use it as "original"
1772  // else we use "file".
1773  remove_chunks($params['original_sum'], 'thumb');
1774
1775  if (isset($params['high_sum']))
1776  {
1777    $original_type = 'high';
1778    remove_chunks($params['original_sum'], 'file');
1779  }
1780  else
1781  {
1782    $original_type = 'file';
1783  }
1784
1785  $file_path = $conf['upload_dir'].'/buffer/'.$params['original_sum'].'-original';
1786
1787  merge_chunks($file_path, $params['original_sum'], $original_type);
1788  chmod($file_path, 0644);
1789
1790  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1791
1792  $image_id = add_uploaded_file(
1793    $file_path,
1794    $params['original_filename'],
1795    null, // categories
1796    isset($params['level']) ? $params['level'] : null,
1797    $params['image_id'] > 0 ? $params['image_id'] : null,
1798    $params['original_sum']
1799    );
1800
1801  $info_columns = array(
1802    'name',
1803    'author',
1804    'comment',
1805    'date_creation',
1806    );
1807
1808  $update = array();
1809
1810  foreach ($info_columns as $key)
1811  {
1812    if (isset($params[$key]))
1813    {
1814      $update[$key] = $params[$key];
1815    }
1816  }
1817
1818  if (count(array_keys($update)) > 0)
1819  {
1820    single_update(
1821      IMAGES_TABLE,
1822      $update,
1823      array('id' => $image_id)
1824      );
1825  }
1826
1827  $url_params = array('image_id' => $image_id);
1828
1829  // let's add links between the image and the categories
1830  if (isset($params['categories']))
1831  {
1832    ws_add_image_category_relations($image_id, $params['categories']);
1833
1834    if (preg_match('/^\d+/', $params['categories'], $matches)) {
1835      $category_id = $matches[0];
1836
1837      $query = '
1838SELECT id, name, permalink
1839  FROM '.CATEGORIES_TABLE.'
1840  WHERE id = '.$category_id.'
1841;';
1842      $result = pwg_query($query);
1843      $category = pwg_db_fetch_assoc($result);
1844
1845      $url_params['section'] = 'categories';
1846      $url_params['category'] = $category;
1847    }
1848  }
1849
1850  // and now, let's create tag associations
1851  if (isset($params['tag_ids']) and !empty($params['tag_ids']))
1852  {
1853    set_tags(
1854      explode(',', $params['tag_ids']),
1855      $image_id
1856      );
1857  }
1858
1859  invalidate_user_cache();
1860
1861  return array(
1862    'image_id' => $image_id,
1863    'url' => make_picture_url($url_params),
1864    );
1865}
1866
1867function ws_images_addSimple($params, $service)
1868{
1869  global $conf;
1870  if (!is_admin())
1871  {
1872    return new PwgError(401, 'Access denied');
1873  }
1874
1875  if (!$service->isPost())
1876  {
1877    return new PwgError(405, "This method requires HTTP POST");
1878  }
1879
1880  if (!isset($_FILES['image']))
1881  {
1882    return new PwgError(405, "The image (file) parameter is missing");
1883  }
1884
1885  $params['image_id'] = (int)$params['image_id'];
1886  if ($params['image_id'] > 0)
1887  {
1888    $query='
1889SELECT *
1890  FROM '.IMAGES_TABLE.'
1891  WHERE id = '.$params['image_id'].'
1892;';
1893
1894    $image_row = pwg_db_fetch_assoc(pwg_query($query));
1895    if ($image_row == null)
1896    {
1897      return new PwgError(404, "image_id not found");
1898    }
1899  }
1900
1901  // category
1902  $params['category'] = (int)$params['category'];
1903  if ($params['category'] <= 0 and $params['image_id'] <= 0)
1904  {
1905    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
1906  }
1907
1908  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1909
1910  $image_id = add_uploaded_file(
1911    $_FILES['image']['tmp_name'],
1912    $_FILES['image']['name'],
1913    $params['category'] > 0 ? array($params['category']) : null,
1914    8,
1915    $params['image_id'] > 0 ? $params['image_id'] : null
1916    );
1917
1918  $info_columns = array(
1919    'name',
1920    'author',
1921    'comment',
1922    'level',
1923    'date_creation',
1924    );
1925
1926  foreach ($info_columns as $key)
1927  {
1928    if (isset($params[$key]))
1929    {
1930      $update[$key] = $params[$key];
1931    }
1932  }
1933
1934  if (count(array_keys($update)) > 0)
1935  {
1936    $update['id'] = $image_id;
1937   
1938    single_update(
1939      IMAGES_TABLE,
1940      $update,
1941      array('id', $update['id'])
1942      );
1943  }
1944
1945
1946  if (isset($params['tags']) and !empty($params['tags']))
1947  {
1948    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1949   
1950    $tag_ids = array();
1951    if (is_array($params['tags']))
1952    {
1953      foreach ($params['tags'] as $tag_name)
1954      {
1955        $tag_ids[] = tag_id_from_tag_name($tag_name);
1956      }
1957    }
1958    else
1959    {
1960      $tag_names = preg_split('~(?<!\\\),~', $params['tags']);
1961      foreach ($tag_names as $tag_name)
1962      {
1963        $tag_ids[] = tag_id_from_tag_name(preg_replace('#\\\\*,#', ',', $tag_name));
1964      }
1965    }
1966
1967    add_tags($tag_ids, array($image_id));
1968  }
1969
1970  $url_params = array('image_id' => $image_id);
1971
1972  if ($params['category'] > 0)
1973  {
1974    $query = '
1975SELECT id, name, permalink
1976  FROM '.CATEGORIES_TABLE.'
1977  WHERE id = '.$params['category'].'
1978;';
1979    $result = pwg_query($query);
1980    $category = pwg_db_fetch_assoc($result);
1981
1982    $url_params['section'] = 'categories';
1983    $url_params['category'] = $category;
1984  }
1985
1986  // update metadata from the uploaded file (exif/iptc), even if the sync
1987  // was already performed by add_uploaded_file().
1988
1989  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1990  sync_metadata(array($image_id));
1991
1992  return array(
1993    'image_id' => $image_id,
1994    'url' => make_picture_url($url_params),
1995    );
1996}
1997
1998function ws_rates_delete($params, $service)
1999{
2000  global $conf;
2001
2002  if (!$service->isPost())
2003  {
2004    return new PwgError(405, 'This method requires HTTP POST');
2005  }
2006
2007  if (!is_admin())
2008  {
2009    return new PwgError(401, 'Access denied');
2010  }
2011
2012  $user_id = (int)$params['user_id'];
2013  if ($user_id<=0)
2014  {
2015    return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid user_id');
2016  }
2017
2018  $query = '
2019DELETE FROM '.RATE_TABLE.'
2020  WHERE user_id='.$user_id;
2021
2022  if (!empty($params['anonymous_id']))
2023  {
2024    $query .= ' AND anonymous_id=\''.$params['anonymous_id'].'\'';
2025  }
2026
2027  $changes = pwg_db_changes(pwg_query($query));
2028  if ($changes)
2029  {
2030    include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
2031    update_rating_score();
2032  }
2033  return $changes;
2034}
2035
2036
2037/**
2038 * perform a login (web service method)
2039 */
2040function ws_session_login($params, $service)
2041{
2042  global $conf;
2043
2044  if (!$service->isPost())
2045  {
2046    return new PwgError(405, "This method requires HTTP POST");
2047  }
2048  if (try_log_user($params['username'], $params['password'],false))
2049  {
2050    return true;
2051  }
2052  return new PwgError(999, 'Invalid username/password');
2053}
2054
2055
2056/**
2057 * performs a logout (web service method)
2058 */
2059function ws_session_logout($params, $service)
2060{
2061  if (!is_a_guest())
2062  {
2063    logout_user();
2064  }
2065  return true;
2066}
2067
2068function ws_session_getStatus($params, $service)
2069{
2070  global $user;
2071  $res = array();
2072  $res['username'] = is_a_guest() ? 'guest' : stripslashes($user['username']);
2073  foreach ( array('status', 'theme', 'language') as $k )
2074  {
2075    $res[$k] = $user[$k];
2076  }
2077  $res['pwg_token'] = get_pwg_token();
2078  $res['charset'] = get_pwg_charset();
2079
2080  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2081  $res['current_datetime'] = $dbnow;
2082
2083  return $res;
2084}
2085
2086
2087/**
2088 * returns a list of tags (web service method)
2089 */
2090function ws_tags_getList($params, $service)
2091{
2092  $tags = get_available_tags();
2093  if ($params['sort_by_counter'])
2094  {
2095    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
2096  }
2097  else
2098  {
2099    usort($tags, 'tag_alpha_compare');
2100  }
2101  for ($i=0; $i<count($tags); $i++)
2102  {
2103    $tags[$i]['id'] = (int)$tags[$i]['id'];
2104    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
2105    $tags[$i]['url'] = make_index_url(
2106        array(
2107          'section'=>'tags',
2108          'tags'=>array($tags[$i])
2109        )
2110      );
2111  }
2112  return array('tags' => new PwgNamedArray($tags, 'tag', ws_std_get_tag_xml_attributes()) );
2113}
2114
2115/**
2116 * returns the list of tags as you can see them in administration (web
2117 * service method).
2118 *
2119 * Only admin can run this method and permissions are not taken into
2120 * account.
2121 */
2122function ws_tags_getAdminList($params, $service)
2123{
2124  if (!is_admin())
2125  {
2126    return new PwgError(401, 'Access denied');
2127  }
2128
2129  $tags = get_all_tags();
2130  return array(
2131    'tags' => new PwgNamedArray(
2132      $tags,
2133      'tag',
2134      ws_std_get_tag_xml_attributes()
2135      )
2136    );
2137}
2138
2139/**
2140 * returns a list of images for tags (web service method)
2141 */
2142function ws_tags_getImages($params, $service)
2143{
2144  global $conf;
2145
2146  // first build all the tag_ids we are interested in
2147  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
2148  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
2149  $tags_by_id = array();
2150  foreach( $tags as $tag )
2151  {
2152    $tags['id'] = (int)$tag['id'];
2153    $tags_by_id[ $tag['id'] ] = $tag;
2154  }
2155  unset($tags);
2156  $tag_ids = array_keys($tags_by_id);
2157
2158
2159  $where_clauses = ws_std_image_sql_filter($params);
2160  if (!empty($where_clauses))
2161  {
2162    $where_clauses = implode( ' AND ', $where_clauses);
2163  }
2164  $image_ids = get_image_ids_for_tags(
2165    $tag_ids,
2166    $params['tag_mode_and'] ? 'AND' : 'OR',
2167    $where_clauses,
2168    ws_std_image_sql_order($params) );
2169
2170  $count_set = count($image_ids);
2171  $params['per_page'] = (int)$params['per_page'];
2172  $params['page'] = (int)$params['page'];
2173  $image_ids = array_slice($image_ids, $params['per_page']*$params['page'], $params['per_page'] );
2174
2175  $image_tag_map = array();
2176  if ( !empty($image_ids) and !$params['tag_mode_and'] )
2177  { // build list of image ids with associated tags per image
2178    $query = '
2179SELECT image_id, GROUP_CONCAT(tag_id) AS tag_ids
2180  FROM '.IMAGE_TAG_TABLE.'
2181  WHERE tag_id IN ('.implode(',',$tag_ids).') AND image_id IN ('.implode(',',$image_ids).')
2182  GROUP BY image_id';
2183    $result = pwg_query($query);
2184    while ( $row=pwg_db_fetch_assoc($result) )
2185    {
2186      $row['image_id'] = (int)$row['image_id'];
2187      $image_ids[] = $row['image_id'];
2188      $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
2189    }
2190  }
2191
2192  $images = array();
2193  if (!empty($image_ids))
2194  {
2195    $rank_of = array_flip($image_ids);
2196    $result = pwg_query('
2197SELECT * FROM '.IMAGES_TABLE.'
2198  WHERE id IN ('.implode(',',$image_ids).')');
2199    while ($row = pwg_db_fetch_assoc($result))
2200    {
2201      $image = array();
2202      $image['rank'] = $rank_of[ $row['id'] ];
2203      foreach ( array('id', 'width', 'height', 'hit') as $k )
2204      {
2205        if (isset($row[$k]))
2206        {
2207          $image[$k] = (int)$row[$k];
2208        }
2209      }
2210      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
2211      {
2212        $image[$k] = $row[$k];
2213      }
2214      $image = array_merge( $image, ws_std_get_urls($row) );
2215
2216      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
2217      $image_tags = array();
2218      foreach ($image_tag_ids as $tag_id)
2219      {
2220        $url = make_index_url(
2221                 array(
2222                  'section'=>'tags',
2223                  'tags'=> array($tags_by_id[$tag_id])
2224                )
2225              );
2226        $page_url = make_picture_url(
2227                 array(
2228                  'section'=>'tags',
2229                  'tags'=> array($tags_by_id[$tag_id]),
2230                  'image_id' => $row['id'],
2231                  'image_file' => $row['file'],
2232                )
2233              );
2234        $image_tags[] = array(
2235                'id' => (int)$tag_id,
2236                'url' => $url,
2237                'page_url' => $page_url,
2238              );
2239      }
2240      $image['tags'] = new PwgNamedArray($image_tags, 'tag', ws_std_get_tag_xml_attributes() );
2241      $images[] = $image;
2242    }
2243    usort($images, 'rank_compare');
2244    unset($rank_of);
2245  }
2246
2247  return array( 
2248      'paging' => new PwgNamedStruct(
2249        array(
2250          'page' => $params['page'],
2251          'per_page' => $params['per_page'],
2252          'count' => count($images),
2253          'total_count' => $count_set,
2254          ) ),
2255       'images' => new PwgNamedArray($images, 'image',
2256          ws_std_get_image_xml_attributes() )
2257    );
2258}
2259
2260function ws_categories_add($params, $service)
2261{
2262  if (!is_admin())
2263  {
2264    return new PwgError(401, 'Access denied');
2265  }
2266
2267  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2268
2269  $options = array();
2270  if (!empty($params['status']) and in_array($params['status'], array('private','public')))
2271  {
2272    $options['status'] = $params['status'];
2273  }
2274 
2275  if (!empty($params['visible']) and in_array($params['visible'], array('true','false')))
2276  {
2277    $options['visible'] = get_boolean($params['visible']);
2278  }
2279 
2280  if (!empty($params['commentable']) and in_array($params['commentable'], array('true','false')) )
2281  {
2282    $options['commentable'] = get_boolean($params['commentable']);
2283  }
2284 
2285  if (!empty($params['comment']))
2286  {
2287    $options['comment'] = $params['comment'];
2288  }
2289 
2290
2291  $creation_output = create_virtual_category(
2292    $params['name'],
2293    $params['parent'],
2294    $options
2295    );
2296
2297  if (isset($creation_output['error']))
2298  {
2299    return new PwgError(500, $creation_output['error']);
2300  }
2301
2302  invalidate_user_cache();
2303
2304  return $creation_output;
2305}
2306
2307function ws_tags_add($params, $service)
2308{
2309  if (!is_admin())
2310  {
2311    return new PwgError(401, 'Access denied');
2312  }
2313
2314  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2315
2316  $creation_output = create_tag($params['name']);
2317
2318  if (isset($creation_output['error']))
2319  {
2320    return new PwgError(500, $creation_output['error']);
2321  }
2322
2323  return $creation_output;
2324}
2325
2326function ws_images_exist($params, $service)
2327{
2328  ws_logfile(__FUNCTION__.' '.var_export($params, true));
2329
2330  global $conf;
2331
2332  if (!is_admin())
2333  {
2334    return new PwgError(401, 'Access denied');
2335  }
2336
2337  $split_pattern = '/[\s,;\|]/';
2338
2339  if ('md5sum' == $conf['uniqueness_mode'])
2340  {
2341    // search among photos the list of photos already added, based on md5sum
2342    // list
2343    $md5sums = preg_split(
2344      $split_pattern,
2345      $params['md5sum_list'],
2346      -1,
2347      PREG_SPLIT_NO_EMPTY
2348    );
2349
2350    $query = '
2351SELECT
2352    id,
2353    md5sum
2354  FROM '.IMAGES_TABLE.'
2355  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
2356;';
2357    $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
2358
2359    $result = array();
2360
2361    foreach ($md5sums as $md5sum)
2362    {
2363      $result[$md5sum] = null;
2364      if (isset($id_of_md5[$md5sum]))
2365      {
2366        $result[$md5sum] = $id_of_md5[$md5sum];
2367      }
2368    }
2369  }
2370
2371  if ('filename' == $conf['uniqueness_mode'])
2372  {
2373    // search among photos the list of photos already added, based on
2374    // filename list
2375    $filenames = preg_split(
2376      $split_pattern,
2377      $params['filename_list'],
2378      -1,
2379      PREG_SPLIT_NO_EMPTY
2380    );
2381
2382    $query = '
2383SELECT
2384    id,
2385    file
2386  FROM '.IMAGES_TABLE.'
2387  WHERE file IN (\''.implode("','", $filenames).'\')
2388;';
2389    $id_of_filename = simple_hash_from_query($query, 'file', 'id');
2390
2391    $result = array();
2392
2393    foreach ($filenames as $filename)
2394    {
2395      $result[$filename] = null;
2396      if (isset($id_of_filename[$filename]))
2397      {
2398        $result[$filename] = $id_of_filename[$filename];
2399      }
2400    }
2401  }
2402
2403  return $result;
2404}
2405
2406function ws_images_checkFiles($params, $service)
2407{
2408  ws_logfile(__FUNCTION__.', input :  '.var_export($params, true));
2409
2410  if (!is_admin())
2411  {
2412    return new PwgError(401, 'Access denied');
2413  }
2414
2415  // input parameters
2416  //
2417  // image_id
2418  // thumbnail_sum
2419  // file_sum
2420  // high_sum
2421
2422  $params['image_id'] = (int)$params['image_id'];
2423  if ($params['image_id'] <= 0)
2424  {
2425    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2426  }
2427
2428  $query = '
2429SELECT
2430    path
2431  FROM '.IMAGES_TABLE.'
2432  WHERE id = '.$params['image_id'].'
2433;';
2434  $result = pwg_query($query);
2435  if (pwg_db_num_rows($result) == 0)
2436  {
2437    return new PwgError(404, "image_id not found");
2438  }
2439  list($path) = pwg_db_fetch_row($result);
2440
2441  $ret = array();
2442
2443  if (isset($params['thumbnail_sum']))
2444  {
2445    // We always say the thumbnail is equal to create no reaction on the
2446    // other side. Since Piwigo 2.4 and derivatives, the thumbnails and web
2447    // sizes are always generated by Piwigo
2448    $ret['thumbnail'] = 'equals';
2449  }
2450
2451  if (isset($params['high_sum']))
2452  {
2453    $ret['file'] = 'equals';
2454    $compare_type = 'high';
2455  }
2456  elseif (isset($params['file_sum']))
2457  {
2458    $compare_type = 'file';
2459  }
2460
2461  if (isset($compare_type))
2462  {
2463    ws_logfile(__FUNCTION__.', md5_file($path) = '.md5_file($path));
2464    if (md5_file($path) != $params[$compare_type.'_sum'])
2465    {
2466      $ret[$compare_type] = 'differs';
2467    }
2468    else
2469    {
2470      $ret[$compare_type] = 'equals';
2471    }
2472  }
2473
2474  ws_logfile(__FUNCTION__.', output :  '.var_export($ret, true));
2475
2476  return $ret;
2477}
2478
2479function ws_images_setInfo($params, $service)
2480{
2481  global $conf;
2482  if (!is_admin())
2483  {
2484    return new PwgError(401, 'Access denied');
2485  }
2486
2487  if (!$service->isPost())
2488  {
2489    return new PwgError(405, "This method requires HTTP POST");
2490  }
2491
2492  $params['image_id'] = (int)$params['image_id'];
2493  if ($params['image_id'] <= 0)
2494  {
2495    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2496  }
2497
2498  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2499
2500  $query='
2501SELECT *
2502  FROM '.IMAGES_TABLE.'
2503  WHERE id = '.$params['image_id'].'
2504;';
2505
2506  $image_row = pwg_db_fetch_assoc(pwg_query($query));
2507  if ($image_row == null)
2508  {
2509    return new PwgError(404, "image_id not found");
2510  }
2511
2512  // database registration
2513  $update = array();
2514
2515  $info_columns = array(
2516    'name',
2517    'author',
2518    'comment',
2519    'level',
2520    'date_creation',
2521    );
2522
2523  foreach ($info_columns as $key)
2524  {
2525    if (isset($params[$key]))
2526    {
2527      if ('fill_if_empty' == $params['single_value_mode'])
2528      {
2529        if (empty($image_row[$key]))
2530        {
2531          $update[$key] = $params[$key];
2532        }
2533      }
2534      elseif ('replace' == $params['single_value_mode'])
2535      {
2536        $update[$key] = $params[$key];
2537      }
2538      else
2539      {
2540        return new PwgError(
2541          500,
2542          '[ws_images_setInfo]'
2543          .' invalid parameter single_value_mode "'.$params['single_value_mode'].'"'
2544          .', possible values are {fill_if_empty, replace}.'
2545          );
2546      }
2547    }
2548  }
2549
2550  if (isset($params['file']))
2551  {
2552    if (!empty($image_row['storage_category_id']))
2553    {
2554      return new PwgError(500, '[ws_images_setInfo] updating "file" is forbidden on photos added by synchronization');
2555    }
2556
2557    $update['file'] = $params['file'];
2558  }
2559
2560  if (count(array_keys($update)) > 0)
2561  {
2562    $update['id'] = $params['image_id'];
2563
2564    single_update(
2565      IMAGES_TABLE,
2566      $update,
2567      array('id', $update['id'])
2568      );
2569  }
2570
2571  if (isset($params['categories']))
2572  {
2573    ws_add_image_category_relations(
2574      $params['image_id'],
2575      $params['categories'],
2576      ('replace' == $params['multiple_value_mode'] ? true : false)
2577      );
2578  }
2579
2580  // and now, let's create tag associations
2581  if (isset($params['tag_ids']))
2582  {
2583    $tag_ids = array();
2584
2585    foreach (explode(',', $params['tag_ids']) as $candidate)
2586    {
2587      $candidate = trim($candidate);
2588
2589      if (preg_match(PATTERN_ID, $candidate))
2590      {
2591        $tag_ids[] = $candidate;
2592      }
2593    }
2594
2595    if ('replace' == $params['multiple_value_mode'])
2596    {
2597      set_tags(
2598        $tag_ids,
2599        $params['image_id']
2600        );
2601    }
2602    elseif ('append' == $params['multiple_value_mode'])
2603    {
2604      add_tags(
2605        $tag_ids,
2606        array($params['image_id'])
2607        );
2608    }
2609    else
2610    {
2611      return new PwgError(
2612        500,
2613        '[ws_images_setInfo]'
2614        .' invalid parameter multiple_value_mode "'.$params['multiple_value_mode'].'"'
2615        .', possible values are {replace, append}.'
2616        );
2617    }
2618  }
2619
2620  invalidate_user_cache();
2621}
2622
2623function ws_images_delete($params, $service)
2624{
2625  global $conf;
2626  if (!is_admin())
2627  {
2628    return new PwgError(401, 'Access denied');
2629  }
2630
2631  if (!$service->isPost())
2632  {
2633    return new PwgError(405, "This method requires HTTP POST");
2634  }
2635
2636  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2637  {
2638    return new PwgError(403, 'Invalid security token');
2639  }
2640
2641  $params['image_id'] = preg_split(
2642    '/[\s,;\|]/',
2643    $params['image_id'],
2644    -1,
2645    PREG_SPLIT_NO_EMPTY
2646    );
2647  $params['image_id'] = array_map('intval', $params['image_id']);
2648
2649  $image_ids = array();
2650  foreach ($params['image_id'] as $image_id)
2651  {
2652    if ($image_id > 0)
2653    {
2654      $image_ids[] = $image_id;
2655    }
2656  }
2657
2658  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2659  delete_elements($image_ids, true);
2660  invalidate_user_cache();
2661}
2662
2663function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
2664{
2665  // let's add links between the image and the categories
2666  //
2667  // $params['categories'] should look like 123,12;456,auto;789 which means:
2668  //
2669  // 1. associate with category 123 on rank 12
2670  // 2. associate with category 456 on automatic rank
2671  // 3. associate with category 789 on automatic rank
2672  $cat_ids = array();
2673  $rank_on_category = array();
2674  $search_current_ranks = false;
2675
2676  $tokens = explode(';', $categories_string);
2677  foreach ($tokens as $token)
2678  {
2679    @list($cat_id, $rank) = explode(',', $token);
2680
2681    if (!preg_match('/^\d+$/', $cat_id))
2682    {
2683      continue;
2684    }
2685
2686    $cat_ids[] = $cat_id;
2687
2688    if (!isset($rank))
2689    {
2690      $rank = 'auto';
2691    }
2692    $rank_on_category[$cat_id] = $rank;
2693
2694    if ($rank == 'auto')
2695    {
2696      $search_current_ranks = true;
2697    }
2698  }
2699
2700  $cat_ids = array_unique($cat_ids);
2701
2702  if (count($cat_ids) == 0)
2703  {
2704    return new PwgError(
2705      500,
2706      '[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
2707      );
2708  }
2709
2710  $query = '
2711SELECT
2712    id
2713  FROM '.CATEGORIES_TABLE.'
2714  WHERE id IN ('.implode(',', $cat_ids).')
2715;';
2716  $db_cat_ids = array_from_query($query, 'id');
2717
2718  $unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
2719  if (count($unknown_cat_ids) != 0)
2720  {
2721    return new PwgError(
2722      500,
2723      '[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
2724      );
2725  }
2726
2727  $to_update_cat_ids = array();
2728
2729  // in case of replace mode, we first check the existing associations
2730  $query = '
2731SELECT
2732    category_id
2733  FROM '.IMAGE_CATEGORY_TABLE.'
2734  WHERE image_id = '.$image_id.'
2735;';
2736  $existing_cat_ids = array_from_query($query, 'category_id');
2737
2738  if ($replace_mode)
2739  {
2740    $to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
2741    if (count($to_remove_cat_ids) > 0)
2742    {
2743      $query = '
2744DELETE
2745  FROM '.IMAGE_CATEGORY_TABLE.'
2746  WHERE image_id = '.$image_id.'
2747    AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
2748;';
2749      pwg_query($query);
2750      update_category($to_remove_cat_ids);
2751    }
2752  }
2753
2754  $new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
2755  if (count($new_cat_ids) == 0)
2756  {
2757    return true;
2758  }
2759
2760  if ($search_current_ranks)
2761  {
2762    $query = '
2763SELECT
2764    category_id,
2765    MAX(rank) AS max_rank
2766  FROM '.IMAGE_CATEGORY_TABLE.'
2767  WHERE rank IS NOT NULL
2768    AND category_id IN ('.implode(',', $new_cat_ids).')
2769  GROUP BY category_id
2770;';
2771    $current_rank_of = simple_hash_from_query(
2772      $query,
2773      'category_id',
2774      'max_rank'
2775      );
2776
2777    foreach ($new_cat_ids as $cat_id)
2778    {
2779      if (!isset($current_rank_of[$cat_id]))
2780      {
2781        $current_rank_of[$cat_id] = 0;
2782      }
2783
2784      if ('auto' == $rank_on_category[$cat_id])
2785      {
2786        $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
2787      }
2788    }
2789  }
2790
2791  $inserts = array();
2792
2793  foreach ($new_cat_ids as $cat_id)
2794  {
2795    $inserts[] = array(
2796      'image_id' => $image_id,
2797      'category_id' => $cat_id,
2798      'rank' => $rank_on_category[$cat_id],
2799      );
2800  }
2801
2802  mass_inserts(
2803    IMAGE_CATEGORY_TABLE,
2804    array_keys($inserts[0]),
2805    $inserts
2806    );
2807
2808  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2809  update_category($new_cat_ids);
2810}
2811
2812function ws_categories_setInfo($params, $service)
2813{
2814  global $conf;
2815  if (!is_admin())
2816  {
2817    return new PwgError(401, 'Access denied');
2818  }
2819
2820  if (!$service->isPost())
2821  {
2822    return new PwgError(405, "This method requires HTTP POST");
2823  }
2824
2825  // category_id
2826  // name
2827  // comment
2828
2829  $params['category_id'] = (int)$params['category_id'];
2830  if ($params['category_id'] <= 0)
2831  {
2832    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2833  }
2834
2835  // database registration
2836  $update = array(
2837    'id' => $params['category_id'],
2838    );
2839
2840  $info_columns = array(
2841    'name',
2842    'comment',
2843    );
2844
2845  $perform_update = false;
2846  foreach ($info_columns as $key)
2847  {
2848    if (isset($params[$key]))
2849    {
2850      $perform_update = true;
2851      $update[$key] = $params[$key];
2852    }
2853  }
2854
2855  if ($perform_update)
2856  {
2857    single_update(
2858      CATEGORIES_TABLE,
2859      $update,
2860      array('id', $update['id'])
2861      );
2862  }
2863}
2864
2865function ws_categories_setRepresentative($params, $service)
2866{
2867  global $conf;
2868
2869  if (!is_admin())
2870  {
2871    return new PwgError(401, 'Access denied');
2872  }
2873
2874  if (!$service->isPost())
2875  {
2876    return new PwgError(405, "This method requires HTTP POST");
2877  }
2878
2879  // category_id
2880  // image_id
2881
2882  $params['category_id'] = (int)$params['category_id'];
2883  if ($params['category_id'] <= 0)
2884  {
2885    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2886  }
2887
2888  // does the category really exist?
2889  $query='
2890SELECT
2891    *
2892  FROM '.CATEGORIES_TABLE.'
2893  WHERE id = '.$params['category_id'].'
2894;';
2895  $row = pwg_db_fetch_assoc(pwg_query($query));
2896  if ($row == null)
2897  {
2898    return new PwgError(404, "category_id not found");
2899  }
2900
2901  $params['image_id'] = (int)$params['image_id'];
2902  if ($params['image_id'] <= 0)
2903  {
2904    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2905  }
2906
2907  // does the image really exist?
2908  $query='
2909SELECT
2910    *
2911  FROM '.IMAGES_TABLE.'
2912  WHERE id = '.$params['image_id'].'
2913;';
2914
2915  $row = pwg_db_fetch_assoc(pwg_query($query));
2916  if ($row == null)
2917  {
2918    return new PwgError(404, "image_id not found");
2919  }
2920
2921  // apply change
2922  $query = '
2923UPDATE '.CATEGORIES_TABLE.'
2924  SET representative_picture_id = '.$params['image_id'].'
2925  WHERE id = '.$params['category_id'].'
2926;';
2927  pwg_query($query);
2928
2929  $query = '
2930UPDATE '.USER_CACHE_CATEGORIES_TABLE.'
2931  SET user_representative_picture_id = NULL
2932  WHERE cat_id = '.$params['category_id'].'
2933;';
2934  pwg_query($query);
2935}
2936
2937function ws_categories_delete($params, $service)
2938{
2939  global $conf;
2940  if (!is_admin())
2941  {
2942    return new PwgError(401, 'Access denied');
2943  }
2944
2945  if (!$service->isPost())
2946  {
2947    return new PwgError(405, "This method requires HTTP POST");
2948  }
2949
2950  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2951  {
2952    return new PwgError(403, 'Invalid security token');
2953  }
2954
2955  $modes = array('no_delete', 'delete_orphans', 'force_delete');
2956  if (!in_array($params['photo_deletion_mode'], $modes))
2957  {
2958    return new PwgError(
2959      500,
2960      '[ws_categories_delete]'
2961      .' invalid parameter photo_deletion_mode "'.$params['photo_deletion_mode'].'"'
2962      .', possible values are {'.implode(', ', $modes).'}.'
2963      );
2964  }
2965
2966  $params['category_id'] = preg_split(
2967    '/[\s,;\|]/',
2968    $params['category_id'],
2969    -1,
2970    PREG_SPLIT_NO_EMPTY
2971    );
2972  $params['category_id'] = array_map('intval', $params['category_id']);
2973
2974  $category_ids = array();
2975  foreach ($params['category_id'] as $category_id)
2976  {
2977    if ($category_id > 0)
2978    {
2979      $category_ids[] = $category_id;
2980    }
2981  }
2982
2983  if (count($category_ids) == 0)
2984  {
2985    return;
2986  }
2987
2988  $query = '
2989SELECT id
2990  FROM '.CATEGORIES_TABLE.'
2991  WHERE id IN ('.implode(',', $category_ids).')
2992;';
2993  $category_ids = array_from_query($query, 'id');
2994
2995  if (count($category_ids) == 0)
2996  {
2997    return;
2998  }
2999
3000  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3001  delete_categories($category_ids, $params['photo_deletion_mode']);
3002  update_global_rank();
3003}
3004
3005function ws_categories_move($params, $service)
3006{
3007  global $conf, $page;
3008
3009  if (!is_admin())
3010  {
3011    return new PwgError(401, 'Access denied');
3012  }
3013
3014  if (!$service->isPost())
3015  {
3016    return new PwgError(405, "This method requires HTTP POST");
3017  }
3018
3019  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3020  {
3021    return new PwgError(403, 'Invalid security token');
3022  }
3023
3024  $params['category_id'] = preg_split(
3025    '/[\s,;\|]/',
3026    $params['category_id'],
3027    -1,
3028    PREG_SPLIT_NO_EMPTY
3029    );
3030  $params['category_id'] = array_map('intval', $params['category_id']);
3031
3032  $category_ids = array();
3033  foreach ($params['category_id'] as $category_id)
3034  {
3035    if ($category_id > 0)
3036    {
3037      $category_ids[] = $category_id;
3038    }
3039  }
3040
3041  if (count($category_ids) == 0)
3042  {
3043    return new PwgError(403, 'Invalid category_id input parameter, no category to move');
3044  }
3045
3046  // we can't move physical categories
3047  $categories_in_db = array();
3048
3049  $query = '
3050SELECT
3051    id,
3052    name,
3053    dir
3054  FROM '.CATEGORIES_TABLE.'
3055  WHERE id IN ('.implode(',', $category_ids).')
3056;';
3057  $result = pwg_query($query);
3058  while ($row = pwg_db_fetch_assoc($result))
3059  {
3060    $categories_in_db[$row['id']] = $row;
3061    // we break on error at first physical category detected
3062    if (!empty($row['dir']))
3063    {
3064      $row['name'] = strip_tags(
3065        trigger_event(
3066          'render_category_name',
3067          $row['name'],
3068          'ws_categories_move'
3069          )
3070        );
3071
3072      return new PwgError(
3073        403,
3074        sprintf(
3075          'Category %s (%u) is not a virtual category, you cannot move it',
3076          $row['name'],
3077          $row['id']
3078          )
3079        );
3080    }
3081  }
3082
3083  if (count($categories_in_db) != count($category_ids))
3084  {
3085    $unknown_category_ids = array_diff($category_ids, array_keys($categories_in_db));
3086
3087    return new PwgError(
3088      403,
3089      sprintf(
3090        'Category %u does not exist',
3091        $unknown_category_ids[0]
3092        )
3093      );
3094  }
3095
3096  // does this parent exists? This check should be made in the
3097  // move_categories function, not here
3098  //
3099  // 0 as parent means "move categories at gallery root"
3100  if (!is_numeric($params['parent']))
3101  {
3102    return new PwgError(403, 'Invalid parent input parameter');
3103  }
3104
3105  if (0 != $params['parent']) {
3106    $params['parent'] = intval($params['parent']);
3107    $subcat_ids = get_subcat_ids(array($params['parent']));
3108    if (count($subcat_ids) == 0)
3109    {
3110      return new PwgError(403, 'Unknown parent category id');
3111    }
3112  }
3113
3114  $page['infos'] = array();
3115  $page['errors'] = array();
3116  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3117  move_categories($category_ids, $params['parent']);
3118  invalidate_user_cache();
3119
3120  if (count($page['errors']) != 0)
3121  {
3122    return new PwgError(403, implode('; ', $page['errors']));
3123  }
3124}
3125
3126function ws_logfile($string)
3127{
3128  global $conf;
3129
3130  if (!$conf['ws_enable_log']) {
3131    return true;
3132  }
3133
3134  file_put_contents(
3135    $conf['ws_log_filepath'],
3136    '['.date('c').'] '.$string."\n",
3137    FILE_APPEND
3138    );
3139}
3140
3141function ws_images_checkUpload($params, $service)
3142{
3143  global $conf;
3144
3145  if (!is_admin())
3146  {
3147    return new PwgError(401, 'Access denied');
3148  }
3149
3150  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
3151  $ret['message'] = ready_for_upload_message();
3152  $ret['ready_for_upload'] = true;
3153
3154  if (!empty($ret['message']))
3155  {
3156    $ret['ready_for_upload'] = false;
3157  }
3158
3159  return $ret;
3160}
3161
3162function ws_plugins_getList($params, $service)
3163{
3164  global $conf;
3165
3166  if (!is_admin())
3167  {
3168    return new PwgError(401, 'Access denied');
3169  }
3170
3171  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3172  $plugins = new plugins();
3173  $plugins->sort_fs_plugins('name');
3174  $plugin_list = array();
3175
3176  foreach($plugins->fs_plugins as $plugin_id => $fs_plugin)
3177  {
3178    if (isset($plugins->db_plugins_by_id[$plugin_id]))
3179    {
3180      $state = $plugins->db_plugins_by_id[$plugin_id]['state'];
3181    }
3182    else
3183    {
3184      $state = 'uninstalled';
3185    }
3186
3187    $plugin_list[] =
3188      array(
3189        'id' => $plugin_id,
3190        'name' => $fs_plugin['name'],
3191        'version' => $fs_plugin['version'],
3192        'state' => $state,
3193        'description' => $fs_plugin['description'],
3194        );
3195  }
3196
3197  return $plugin_list;
3198}
3199
3200function ws_plugins_performAction($params, &$service)
3201{
3202  global $template;
3203
3204  if (!is_admin())
3205  {
3206    return new PwgError(401, 'Access denied');
3207  }
3208
3209  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3210  {
3211    return new PwgError(403, 'Invalid security token');
3212  }
3213
3214  define('IN_ADMIN', true);
3215  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3216  $plugins = new plugins();
3217  $errors = $plugins->perform_action($params['action'], $params['plugin']);
3218
3219
3220  if (!empty($errors))
3221  {
3222    return new PwgError(500, $errors);
3223  }
3224  else
3225  {
3226    if (in_array($params['action'], array('activate', 'deactivate')))
3227    {
3228      $template->delete_compiled_templates();
3229    }
3230    return true;
3231  }
3232}
3233
3234function ws_themes_performAction($params, $service)
3235{
3236  global $template;
3237
3238  if (!is_admin())
3239  {
3240    return new PwgError(401, 'Access denied');
3241  }
3242
3243  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3244  {
3245    return new PwgError(403, 'Invalid security token');
3246  }
3247
3248  define('IN_ADMIN', true);
3249  include_once(PHPWG_ROOT_PATH.'admin/include/themes.class.php');
3250  $themes = new themes();
3251  $errors = $themes->perform_action($params['action'], $params['theme']);
3252
3253  if (!empty($errors))
3254  {
3255    return new PwgError(500, $errors);
3256  }
3257  else
3258  {
3259    if (in_array($params['action'], array('activate', 'deactivate')))
3260    {
3261      $template->delete_compiled_templates();
3262    }
3263    return true;
3264  }
3265}
3266
3267function ws_extensions_update($params, $service)
3268{
3269  if (!is_webmaster())
3270  {
3271    return new PwgError(401, l10n('Webmaster status is required.'));
3272  }
3273
3274  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3275  {
3276    return new PwgError(403, 'Invalid security token');
3277  }
3278
3279  if (empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3280  {
3281    return new PwgError(403, "invalid extension type");
3282  }
3283
3284  if (empty($params['id']) or empty($params['revision']))
3285  {
3286    return new PwgError(null, 'Wrong parameters');
3287  }
3288
3289  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3290  include_once(PHPWG_ROOT_PATH.'admin/include/'.$params['type'].'.class.php');
3291
3292  $type = $params['type'];
3293  $extension_id = $params['id'];
3294  $revision = $params['revision'];
3295
3296  $extension = new $type();
3297
3298  if ($type == 'plugins')
3299  {
3300    if (isset($extension->db_plugins_by_id[$extension_id]) and $extension->db_plugins_by_id[$extension_id]['state'] == 'active')
3301    {
3302      $extension->perform_action('deactivate', $extension_id);
3303
3304      redirect(PHPWG_ROOT_PATH
3305        . 'ws.php'
3306        . '?method=pwg.extensions.update'
3307        . '&type=plugins'
3308        . '&id=' . $extension_id
3309        . '&revision=' . $revision
3310        . '&reactivate=true'
3311        . '&pwg_token=' . get_pwg_token()
3312        . '&format=json'
3313      );
3314    }
3315
3316    $upgrade_status = $extension->extract_plugin_files('upgrade', $revision, $extension_id);
3317    $extension_name = $extension->fs_plugins[$extension_id]['name'];
3318
3319    if (isset($params['reactivate']))
3320    {
3321      $extension->perform_action('activate', $extension_id);
3322    }
3323  }
3324  elseif ($type == 'themes')
3325  {
3326    $upgrade_status = $extension->extract_theme_files('upgrade', $revision, $extension_id);
3327    $extension_name = $extension->fs_themes[$extension_id]['name'];
3328  }
3329  elseif ($type == 'languages')
3330  {
3331    $upgrade_status = $extension->extract_language_files('upgrade', $revision, $extension_id);
3332    $extension_name = $extension->fs_languages[$extension_id]['name'];
3333  }
3334
3335  global $template;
3336  $template->delete_compiled_templates();
3337
3338  switch ($upgrade_status)
3339  {
3340    case 'ok':
3341      return l10n('%s has been successfully updated.', $extension_name);
3342
3343    case 'temp_path_error':
3344      return new PwgError(null, l10n('Can\'t create temporary file.'));
3345
3346    case 'dl_archive_error':
3347      return new PwgError(null, l10n('Can\'t download archive.'));
3348
3349    case 'archive_error':
3350      return new PwgError(null, l10n('Can\'t read or extract archive.'));
3351
3352    default:
3353      return new PwgError(null, l10n('An error occured during extraction (%s).', $upgrade_status));
3354  }
3355}
3356
3357function ws_extensions_ignoreupdate($params, $service)
3358{
3359  global $conf;
3360
3361  define('IN_ADMIN', true);
3362  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3363
3364  if (!is_webmaster())
3365  {
3366    return new PwgError(401, 'Access denied');
3367  }
3368
3369  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3370  {
3371    return new PwgError(403, 'Invalid security token');
3372  }
3373
3374  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3375
3376  // Reset ignored extension
3377  if ($params['reset'])
3378  {
3379    if (!empty($params['type']) and isset($conf['updates_ignored'][$params['type']]))
3380    {
3381      $conf['updates_ignored'][$params['type']] = array();
3382    }
3383    else
3384    {
3385      $conf['updates_ignored'] = array(
3386        'plugins'=>array(),
3387        'themes'=>array(),
3388        'languages'=>array()
3389      );
3390    }
3391    conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3392    unset($_SESSION['extensions_need_update']);
3393    return true;
3394  }
3395
3396  if (empty($params['id']) or empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3397  {
3398    return new PwgError(403, 'Invalid parameters');
3399  }
3400
3401  // Add or remove extension from ignore list
3402  if (!in_array($params['id'], $conf['updates_ignored'][$params['type']]))
3403  {
3404    $conf['updates_ignored'][ $params['type'] ][] = $params['id'];
3405  }
3406  conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3407  unset($_SESSION['extensions_need_update']);
3408  return true;
3409}
3410
3411function ws_extensions_checkupdates($params, $service)
3412{
3413  global $conf;
3414
3415  define('IN_ADMIN', true);
3416  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3417  include_once(PHPWG_ROOT_PATH.'admin/include/updates.class.php');
3418  $update = new updates();
3419
3420  if (!is_admin())
3421  {
3422    return new PwgError(401, 'Access denied');
3423  }
3424
3425  $result = array();
3426
3427  if (!isset($_SESSION['need_update']))
3428    $update->check_piwigo_upgrade();
3429
3430  $result['piwigo_need_update'] = $_SESSION['need_update'];
3431
3432  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3433
3434  if (!isset($_SESSION['extensions_need_update']))
3435    $update->check_extensions();
3436  else
3437    $update->check_updated_extensions();
3438
3439  if (!is_array($_SESSION['extensions_need_update']))
3440    $result['ext_need_update'] = null;
3441  else
3442    $result['ext_need_update'] = !empty($_SESSION['extensions_need_update']);
3443
3444  return $result;
3445}
3446?>
Note: See TracBrowser for help on using the repository browser.