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

Last change on this file since 13090 was 13090, checked in by plg, 12 years ago

feature added: pwg.images.add can perform an update on an existing photo.

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