root/trunk/include/ws_functions.inc.php @ 12865

Revision 12865, 87.8 KB (checked in by rvelices, 17 months ago)

feature 2548 multisize - added a page to build missing derivatives

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