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

Last change on this file since 11893 was 11893, checked in by rvelices, 13 years ago

rename #images.average_rate to rating_score

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