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

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