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

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

remove obsolete function add_file

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