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

Last change on this file since 12855 was 12855, checked in by rvelices, 12 years ago

feature 2548 multisize - improved picture.php display (original...) + code cleanup

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