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

Last change on this file since 10235 was 10235, checked in by patdenice, 13 years ago

feature:2259
Add web service method: pwg.images.resize

  • Property svn:eol-style set to LF
File size: 65.1 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  {
57    $clauses[] = $tbl_name.'average_rate>'.$params['f_min_rate'];
58  }
59  if ( is_numeric($params['f_max_rate']) )
60  {
61    $clauses[] = $tbl_name.'average_rate<='.$params['f_max_rate'];
62  }
63  if ( is_numeric($params['f_min_hit']) )
64  {
65    $clauses[] = $tbl_name.'hit>'.$params['f_min_hit'];
66  }
67  if ( is_numeric($params['f_max_hit']) )
68  {
69    $clauses[] = $tbl_name.'hit<='.$params['f_max_hit'];
70  }
[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    }
[1711]126    $sortable_fields = array('id', 'file', 'name', 'hit', 'average_rate',
[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(
168    'id','tn_url','element_url','high_url', 'file','width','height','hit'
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;
[10017]195       
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      }
[1880]375      foreach ( array('file', 'name', 'comment') 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
[4884]435  $where = array('1=1');
436  $join_type = 'INNER';
437  $join_user = $user['id'];
[1698]438
439  if (!$params['recursive'])
440  {
441    if ($params['cat_id']>0)
[1820]442      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
443    OR id='.(int)($params['cat_id']).')';
[1698]444    else
445      $where[] = 'id_uppercat IS NULL';
446  }
[1820]447  else if ($params['cat_id']>0)
448  {
[4367]449    $where[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.
[1820]450      (int)($params['cat_id'])
451      .'(,|$)\'';
452  }
[1698]453
454  if ($params['public'])
455  {
456    $where[] = 'status = "public"';
[1711]457    $where[] = 'visible = "true"';
[4884]458   
459    $join_user = $conf['guest_id'];
[1698]460  }
[4884]461  elseif (is_admin())
[1698]462  {
[4884]463    // in this very specific case, we don't want to hide empty
464    // categories. Function calculate_permissions will only return
465    // categories that are either locked or private and not permitted
466    //
467    // calculate_permissions does not consider empty categories as forbidden
468    $forbidden_categories = calculate_permissions($user['id'], $user['status']);
469    $where[]= 'id NOT IN ('.$forbidden_categories.')';
470    $join_type = 'LEFT';
[1698]471  }
472
[1711]473  $query = '
[1866]474SELECT id, name, permalink, uppercats, global_rank,
[7550]475    comment,
[1845]476    nb_images, count_images AS total_nb_images,
477    date_last, max_date_last, count_categories AS nb_categories
[1711]478  FROM '.CATEGORIES_TABLE.'
[4884]479   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
[1698]480  WHERE '. implode('
481    AND ', $where);
482
483  $result = pwg_query($query);
484
485  $cats = array();
[4325]486  while ($row = pwg_db_fetch_assoc($result))
[1698]487  {
488    $row['url'] = make_index_url(
489        array(
[1861]490          'category' => $row
[1698]491          )
492      );
[1845]493    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
[1698]494    {
495      $row[$key] = (int)$row[$key];
496    }
[2572]497
[4903]498    $row['name'] = strip_tags(
499      trigger_event(
500        'render_category_name',
501        $row['name'],
502        'ws_categories_getList'
503        )
504      );
505   
[7550]506    $row['comment'] = strip_tags(
507      trigger_event(
508        'render_category_description',
509        $row['comment'],
510        'ws_categories_getList'
511        )
512      );
513   
[1698]514    array_push($cats, $row);
515  }
516  usort($cats, 'global_rank_compare');
517  return array(
[2548]518    'categories' => new PwgNamedArray(
519      $cats,
520      'category',
521      array(
522        'id',
523        'url',
524        'nb_images',
525        'total_nb_images',
526        'nb_categories',
527        'date_last',
528        'max_date_last',
529        )
530      )
[1698]531    );
532}
533
[2563]534/**
535 * returns the list of categories as you can see them in administration (web
536 * service method).
537 *
538 * Only admin can run this method and permissions are not taken into
539 * account.
540 */
541function ws_categories_getAdminList($params, &$service)
542{
543  if (!is_admin())
544  {
545    return new PwgError(401, 'Access denied');
546  }
[1781]547
[2563]548  $query = '
549SELECT
550    category_id,
551    COUNT(*) AS counter
552  FROM '.IMAGE_CATEGORY_TABLE.'
553  GROUP BY category_id
554;';
555  $nb_images_of = simple_hash_from_query($query, 'category_id', 'counter');
556
557  $query = '
558SELECT
559    id,
560    name,
[7550]561    comment,
[2563]562    uppercats,
563    global_rank
564  FROM '.CATEGORIES_TABLE.'
565;';
566  $result = pwg_query($query);
567  $cats = array();
568
[4325]569  while ($row = pwg_db_fetch_assoc($result))
[2563]570  {
571    $id = $row['id'];
572    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
[4903]573    $row['name'] = strip_tags(
574      trigger_event(
575        'render_category_name',
576        $row['name'],
577        'ws_categories_getAdminList'
578        )
579      );
[7550]580    $row['comment'] = strip_tags(
581      trigger_event(
582        'render_category_description',
583        $row['comment'],
584        'ws_categories_getAdminList'
585        )
586      );
[2563]587    array_push($cats, $row);
[2585]588  }
589
[2563]590  usort($cats, 'global_rank_compare');
591  return array(
592    'categories' => new PwgNamedArray(
593      $cats,
594      'category',
595      array(
596        'id',
597        'nb_images',
598        'name',
599        'uppercats',
600        'global_rank',
601        )
602      )
603    );
604}
605
[1781]606/**
607 * returns detailed information for an element (web service method)
608 */
[1849]609function ws_images_addComment($params, &$service)
610{
[1852]611  if (!$service->isPost())
612  {
613    return new PwgError(405, "This method requires HTTP POST");
614  }
[1849]615  $params['image_id'] = (int)$params['image_id'];
616  $query = '
[2119]617SELECT DISTINCT image_id
[1849]618  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
[2119]619  WHERE commentable="true"
[1849]620    AND image_id='.$params['image_id'].
621    get_sql_condition_FandF(
622      array(
623        'forbidden_categories' => 'id',
624        'visible_categories' => 'id',
625        'visible_images' => 'image_id'
626      ),
627      ' AND'
628    );
[4325]629  if ( !pwg_db_num_rows( pwg_query( $query ) ) )
[1849]630  {
631    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
632  }
[2119]633
[1849]634  $comm = array(
[6437]635    'author' => trim( $params['author'] ),
636    'content' => trim( $params['content'] ),
[1849]637    'image_id' => $params['image_id'],
638   );
639
640  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
[2119]641
642  $comment_action = insert_user_comment(
[1849]643      $comm, $params['key'], $infos
644    );
645
646  switch ($comment_action)
647  {
648    case 'reject':
[5021]649      array_push($infos, l10n('Your comment has NOT been registered because it did not pass the validation rules') );
[7782]650      return new PwgError(403, implode("; ", $infos) );
[1849]651    case 'validate':
652    case 'moderate':
[2119]653      $ret = array(
[1849]654          'id' => $comm['id'],
655          'validation' => $comment_action=='validate',
656        );
657      return new PwgNamedStruct(
658          'comment',
[2119]659          $ret,
660          null, array()
[1849]661        );
662    default:
663      return new PwgError(500, "Unknown comment action ".$comment_action );
664  }
665}
666
667/**
668 * returns detailed information for an element (web service method)
669 */
[1698]670function ws_images_getInfo($params, &$service)
671{
672  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
[1849]673  global $user, $conf;
[1698]674  $params['image_id'] = (int)$params['image_id'];
675  if ( $params['image_id']<=0 )
676  {
677    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
678  }
[1781]679
[1698]680  $query='
681SELECT * FROM '.IMAGES_TABLE.'
[1711]682  WHERE id='.$params['image_id'].
683    get_sql_condition_FandF(
684      array('visible_images' => 'id'),
685      ' AND'
[2516]686    ).'
687LIMIT 1';
[1711]688
[4325]689  $image_row = pwg_db_fetch_assoc(pwg_query($query));
[1698]690  if ($image_row==null)
691  {
[1852]692    return new PwgError(404, "image_id not found");
[1698]693  }
[1845]694  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
[1698]695
696  //-------------------------------------------------------- related categories
697  $query = '
[1866]698SELECT id, name, permalink, uppercats, global_rank, commentable
[1698]699  FROM '.IMAGE_CATEGORY_TABLE.'
[1849]700    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
[2119]701  WHERE image_id = '.$image_row['id'].
702  get_sql_condition_FandF(
703      array( 'forbidden_categories' => 'category_id' ),
704      ' AND'
705    ).'
[1698]706;';
707  $result = pwg_query($query);
[1849]708  $is_commentable = false;
[1698]709  $related_categories = array();
[4325]710  while ($row = pwg_db_fetch_assoc($result))
[1698]711  {
[1849]712    if ($row['commentable']=='true')
713    {
714      $is_commentable = true;
715    }
716    unset($row['commentable']);
[1698]717    $row['url'] = make_index_url(
718        array(
[1861]719          'category' => $row
[1698]720          )
721      );
722
723    $row['page_url'] = make_picture_url(
724        array(
725          'image_id' => $image_row['id'],
726          'image_file' => $image_row['file'],
[1861]727          'category' => $row
[1698]728          )
729      );
[1849]730    $row['id']=(int)$row['id'];
[1698]731    array_push($related_categories, $row);
732  }
733  usort($related_categories, 'global_rank_compare');
734  if ( empty($related_categories) )
735  {
736    return new PwgError(401, 'Access denied');
737  }
738
739  //-------------------------------------------------------------- related tags
[1815]740  $related_tags = get_common_tags( array($image_row['id']), -1 );
741  foreach( $related_tags as $i=>$tag)
[1698]742  {
[1815]743    $tag['url'] = make_index_url(
[1698]744        array(
[1815]745          'tags' => array($tag)
[1698]746          )
747      );
[1815]748    $tag['page_url'] = make_picture_url(
[1698]749        array(
750          'image_id' => $image_row['id'],
751          'image_file' => $image_row['file'],
[1815]752          'tags' => array($tag),
[1698]753          )
754      );
[1815]755    unset($tag['counter']);
[1849]756    $tag['id']=(int)$tag['id'];
[1815]757    $related_tags[$i]=$tag;
[1698]758  }
[1849]759  //------------------------------------------------------------- related rates
760  $query = '
761SELECT COUNT(rate) AS count
762     , ROUND(AVG(rate),2) AS average
763  FROM '.RATE_TABLE.'
764  WHERE element_id = '.$image_row['id'].'
765;';
[4325]766  $rating = pwg_db_fetch_assoc(pwg_query($query));
[1849]767  $rating['count'] = (int)$rating['count'];
768
[1698]769  //---------------------------------------------------------- related comments
[1849]770  $related_comments = array();
[2119]771
[1849]772  $where_comments = 'image_id = '.$image_row['id'];
773  if ( !is_admin() )
774  {
775    $where_comments .= '
776    AND validated="true"';
777  }
778
[1698]779  $query = '
[6652]780SELECT COUNT(id) AS nb_comments
[1698]781  FROM '.COMMENTS_TABLE.'
[1849]782  WHERE '.$where_comments;
[1698]783  list($nb_comments) = array_from_query($query, 'nb_comments');
[1849]784  $nb_comments = (int)$nb_comments;
[1698]785
[1849]786  if ( $nb_comments>0 and $params['comments_per_page']>0 )
787  {
788    $query = '
[1698]789SELECT id, date, author, content
790  FROM '.COMMENTS_TABLE.'
[1849]791  WHERE '.$where_comments.'
792  ORDER BY date
[4334]793  LIMIT '.(int)$params['comments_per_page'].
794    ' OFFSET '.(int)($params['comments_per_page']*$params['comments_page']);
[1698]795
[1849]796    $result = pwg_query($query);
[4325]797    while ($row = pwg_db_fetch_assoc($result))
[1849]798    {
799      $row['id']=(int)$row['id'];
800      array_push($related_comments, $row);
801    }
802  }
[2119]803
[1849]804  $comment_post_data = null;
[2119]805  if ($is_commentable and
[2029]806      (!is_a_guest()
807        or (is_a_guest() and $conf['comments_forall'] )
[1849]808      )
809      )
[1698]810  {
[4304]811    $comment_post_data['author'] = stripslashes($user['username']);
[7495]812    $comment_post_data['key'] = get_ephemeral_key(2, $params['image_id']);
[1698]813  }
814
[1849]815  $ret = $image_row;
816  foreach ( array('id','width','height','hit','filesize') as $k )
817  {
818    if (isset($ret[$k]))
819    {
820      $ret[$k] = (int)$ret[$k];
821    }
822  }
823  foreach ( array('path', 'storage_category_id') as $k )
824  {
825    unset($ret[$k]);
826  }
[1698]827
[1849]828  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
[1698]829  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
[2585]830  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
[1849]831  if ( isset($comment_post_data) )
832  {
833    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
834  }
[1698]835  $ret['comments'] = array(
[2119]836     WS_XML_ATTRIBUTES =>
[1849]837        array(
838          'page' => $params['comments_page'],
839          'per_page' => $params['comments_per_page'],
840          'count' => count($related_comments),
841          'nb_comments' => $nb_comments,
842        ),
843     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id','date') )
[1698]844      );
[1845]845
[1698]846  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
847}
848
[2435]849
[1837]850/**
[2435]851 * rates the image_id in the parameter
852 */
853function ws_images_Rate($params, &$service)
854{
855  $image_id = (int)$params['image_id'];
856  $query = '
857SELECT DISTINCT id FROM '.IMAGES_TABLE.'
858  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
859  WHERE id='.$image_id
860  .get_sql_condition_FandF(
861    array(
862        'forbidden_categories' => 'category_id',
863        'forbidden_images' => 'id',
864      ),
865    '    AND'
866    ).'
867    LIMIT 1';
[4325]868  if ( pwg_db_num_rows( pwg_query($query) )==0 )
[2435]869  {
870    return new PwgError(404, "Invalid image_id or access denied" );
871  }
872  $rate = (int)$params['rate'];
873  include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
874  $res = rate_picture( $image_id, $rate );
875  if ($res==false)
876  {
877    global $conf;
878    return new PwgError( 403, "Forbidden or rate not in ". implode(',',$conf['rate_items']));
879  }
880  return $res;
881}
882
883
884/**
[1837]885 * returns a list of elements corresponding to a query search
886 */
887function ws_images_search($params, &$service)
888{
889  global $page;
890  $images = array();
891  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
892  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
[1698]893
[2135]894  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
895  $order_by = ws_std_image_sql_order($params, 'i.');
[1837]896
[2451]897  $super_order_by = false;
[2135]898  if ( !empty($order_by) )
[1837]899  {
[2135]900    global $conf;
901    $conf['order_by'] = 'ORDER BY '.$order_by;
[2451]902    $super_order_by=true; // quick_search_result might be faster
[1837]903  }
904
[2135]905  $search_result = get_quick_search_results($params['query'],
[2451]906      $super_order_by,
907      implode(',', $where_clauses)
908    );
[2119]909
[2451]910  $image_ids = array_slice(
911      $search_result['items'],
912      $params['page']*$params['per_page'],
913      $params['per_page']
914    );
[1837]915
916  if ( count($image_ids) )
917  {
918    $query = '
919SELECT * FROM '.IMAGES_TABLE.'
[2451]920  WHERE id IN ('.implode(',', $image_ids).')';
[1837]921
[2451]922    $image_ids = array_flip($image_ids);
[1837]923    $result = pwg_query($query);
[4325]924    while ($row = pwg_db_fetch_assoc($result))
[1837]925    {
926      $image = array();
927      foreach ( array('id', 'width', 'height', 'hit') as $k )
928      {
929        if (isset($row[$k]))
930        {
931          $image[$k] = (int)$row[$k];
932        }
933      }
[1880]934      foreach ( array('file', 'name', 'comment') as $k )
[1837]935      {
936        $image[$k] = $row[$k];
937      }
938      $image = array_merge( $image, ws_std_get_urls($row) );
[2451]939      $images[$image_ids[$image['id']]] = $image;
[1837]940    }
[2451]941    ksort($images, SORT_NUMERIC);
942    $images = array_values($images);
[1837]943  }
944
945
946  return array( 'images' =>
947    array (
948      WS_XML_ATTRIBUTES =>
949        array(
950            'page' => $params['page'],
951            'per_page' => $params['per_page'],
952            'count' => count($images)
953          ),
954       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
[1845]955          ws_std_get_image_xml_attributes() )
[1837]956      )
957    );
958}
959
[2413]960function ws_images_setPrivacyLevel($params, &$service)
961{
[8126]962  if (!is_admin())
[2413]963  {
964    return new PwgError(401, 'Access denied');
965  }
[4513]966  if (!$service->isPost())
967  {
968    return new PwgError(405, "This method requires HTTP POST");
969  }
[2770]970  $params['image_id'] = array_map( 'intval',$params['image_id'] );
[2413]971  if ( empty($params['image_id']) )
972  {
973    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
974  }
975  global $conf;
976  if ( !in_array( (int)$params['level'], $conf['available_permission_levels']) )
977  {
978    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid level");
979  }
[4513]980
[2413]981  $query = '
982UPDATE '.IMAGES_TABLE.'
983  SET level='.(int)$params['level'].'
984  WHERE id IN ('.implode(',',$params['image_id']).')';
985  $result = pwg_query($query);
[5930]986  $affected_rows = pwg_db_changes($result);
[2413]987  if ($affected_rows)
988  {
989    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
990    invalidate_user_cache();
991  }
992  return $affected_rows;
993}
994
[3193]995function ws_images_add_chunk($params, &$service)
996{
[5014]997  global $conf;
998 
[4900]999  ws_logfile('[ws_images_add_chunk] welcome');
[3193]1000  // data
1001  // original_sum
1002  // type {thumb, file, high}
1003  // position
[3488]1004
[8126]1005  if (!is_admin())
[3193]1006  {
1007    return new PwgError(401, 'Access denied');
1008  }
1009
[4511]1010  if (!$service->isPost())
1011  {
1012    return new PwgError(405, "This method requires HTTP POST");
1013  }
1014
[4900]1015  foreach ($params as $param_key => $param_value) {
1016    if ('data' == $param_key) {
1017      continue;
1018    }
1019   
1020    ws_logfile(
1021      sprintf(
1022        '[ws_images_add_chunk] input param "%s" : "%s"',
1023        $param_key,
1024        is_null($param_value) ? 'NULL' : $param_value
1025        )
1026      );
1027  }
1028
[5014]1029  $upload_dir = $conf['upload_dir'].'/buffer';
[3193]1030
1031  // create the upload directory tree if not exists
1032  if (!is_dir($upload_dir)) {
1033    umask(0000);
1034    $recursive = true;
1035    if (!@mkdir($upload_dir, 0777, $recursive))
1036    {
1037      return new PwgError(500, 'error during buffer directory creation');
1038    }
1039  }
1040
1041  if (!is_writable($upload_dir))
1042  {
1043    // last chance to make the directory writable
1044    @chmod($upload_dir, 0777);
1045
1046    if (!is_writable($upload_dir))
1047    {
1048      return new PwgError(500, 'buffer directory has no write access');
1049    }
1050  }
1051
1052  secure_directory($upload_dir);
1053
1054  $filename = sprintf(
1055    '%s-%s-%05u.block',
1056    $params['original_sum'],
1057    $params['type'],
1058    $params['position']
1059    );
1060
[3240]1061  ws_logfile('[ws_images_add_chunk] data length : '.strlen($params['data']));
1062
[3193]1063  $bytes_written = file_put_contents(
1064    $upload_dir.'/'.$filename,
[3240]1065    base64_decode($params['data'])
[3193]1066    );
1067
1068  if (false === $bytes_written) {
1069    return new PwgError(
1070      500,
1071      'an error has occured while writting chunk '.$params['position'].' for '.$params['type']
1072      );
1073  }
1074}
1075
1076function merge_chunks($output_filepath, $original_sum, $type)
1077{
[5014]1078  global $conf;
1079 
[3193]1080  ws_logfile('[merge_chunks] input parameter $output_filepath : '.$output_filepath);
1081
[4348]1082  if (is_file($output_filepath))
1083  {
1084    unlink($output_filepath);
[4513]1085
[4348]1086    if (is_file($output_filepath))
1087    {
1088      new PwgError(500, '[merge_chunks] error while trying to remove existing '.$output_filepath);
1089      exit();
1090    }
1091  }
[4513]1092
[5014]1093  $upload_dir = $conf['upload_dir'].'/buffer';
[3193]1094  $pattern = '/'.$original_sum.'-'.$type.'/';
1095  $chunks = array();
[3488]1096
[3193]1097  if ($handle = opendir($upload_dir))
1098  {
1099    while (false !== ($file = readdir($handle)))
1100    {
1101      if (preg_match($pattern, $file))
1102      {
1103        ws_logfile($file);
1104        array_push($chunks, $upload_dir.'/'.$file);
1105      }
1106    }
1107    closedir($handle);
1108  }
1109
1110  sort($chunks);
[3240]1111
[4425]1112  if (function_exists('memory_get_usage')) {
1113    ws_logfile('[merge_chunks] memory_get_usage before loading chunks: '.memory_get_usage());
1114  }
[3488]1115
[3514]1116  $i = 0;
[4513]1117
[3240]1118  foreach ($chunks as $chunk)
1119  {
1120    $string = file_get_contents($chunk);
[3488]1121
[4425]1122    if (function_exists('memory_get_usage')) {
1123      ws_logfile('[merge_chunks] memory_get_usage on chunk '.++$i.': '.memory_get_usage());
1124    }
[3488]1125
[3240]1126    if (!file_put_contents($output_filepath, $string, FILE_APPEND))
1127    {
[4346]1128      new PwgError(500, '[merge_chunks] error while writting chunks for '.$output_filepath);
1129      exit();
[3240]1130    }
[3488]1131
[3193]1132    unlink($chunk);
1133  }
[3240]1134
[4425]1135  if (function_exists('memory_get_usage')) {
1136    ws_logfile('[merge_chunks] memory_get_usage after loading chunks: '.memory_get_usage());
1137  }
[3193]1138}
1139
[4346]1140/*
1141 * The $file_path must be the path of the basic "web sized" photo
1142 * The $type value will automatically modify the $file_path to the corresponding file
1143 */
1144function add_file($file_path, $type, $original_sum, $file_sum)
1145{
[8249]1146  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1147 
[4347]1148  $file_path = file_path_for_type($file_path, $type);
[4346]1149
1150  $upload_dir = dirname($file_path);
[4900]1151  if (substr(PHP_OS, 0, 3) == 'WIN')
1152  {
1153    $upload_dir = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir);
1154  }
[4513]1155
[4900]1156  ws_logfile('[add_file] file_path  : '.$file_path);
1157  ws_logfile('[add_file] upload_dir : '.$upload_dir);
1158 
[4346]1159  if (!is_dir($upload_dir)) {
1160    umask(0000);
1161    $recursive = true;
1162    if (!@mkdir($upload_dir, 0777, $recursive))
1163    {
1164      new PwgError(500, '[add_file] error during '.$type.' directory creation');
1165      exit();
1166    }
1167  }
1168
1169  if (!is_writable($upload_dir))
1170  {
1171    // last chance to make the directory writable
1172    @chmod($upload_dir, 0777);
1173
1174    if (!is_writable($upload_dir))
1175    {
1176      new PwgError(500, '[add_file] '.$type.' directory has no write access');
1177      exit();
1178    }
1179  }
1180
1181  secure_directory($upload_dir);
1182
1183  // merge the thumbnail
1184  merge_chunks($file_path, $original_sum, $type);
1185  chmod($file_path, 0644);
1186
1187  // check dumped thumbnail md5
1188  $dumped_md5 = md5_file($file_path);
1189  if ($dumped_md5 != $file_sum) {
1190    new PwgError(500, '[add_file] '.$type.' transfer failed');
1191    exit();
1192  }
1193
1194  list($width, $height) = getimagesize($file_path);
1195  $filesize = floor(filesize($file_path)/1024);
1196
1197  return array(
1198    'width' => $width,
1199    'height' => $height,
1200    'filesize' => $filesize,
1201    );
1202}
1203
[4348]1204function ws_images_addFile($params, &$service)
1205{
1206  // image_id
1207  // type {thumb, file, high}
1208  // sum
1209
1210  global $conf;
[8126]1211  if (!is_admin())
[4348]1212  {
1213    return new PwgError(401, 'Access denied');
1214  }
1215
1216  $params['image_id'] = (int)$params['image_id'];
1217  if ($params['image_id'] <= 0)
1218  {
1219    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1220  }
1221
1222  //
1223  // what is the path?
1224  //
1225  $query = '
1226SELECT
1227    path,
1228    md5sum
1229  FROM '.IMAGES_TABLE.'
1230  WHERE id = '.$params['image_id'].'
1231;';
[6500]1232  list($file_path, $original_sum) = pwg_db_fetch_row(pwg_query($query));
[4348]1233
1234  // TODO only files added with web API can be updated with web API
1235
1236  //
1237  // makes sure directories are there and call the merge_chunks
1238  //
1239  $infos = add_file($file_path, $params['type'], $original_sum, $params['sum']);
1240
1241  //
1242  // update basic metadata from file
1243  //
1244  $update = array();
[4513]1245
[4348]1246  if ('high' == $params['type'])
1247  {
1248    $update['high_filesize'] = $infos['filesize'];
[10160]1249    $update['high_width'] = $infos['width'];
1250    $update['high_height'] = $infos['height'];
[4348]1251    $update['has_high'] = 'true';
1252  }
1253
1254  if ('file' == $params['type'])
1255  {
1256    $update['filesize'] = $infos['filesize'];
1257    $update['width'] = $infos['width'];
1258    $update['height'] = $infos['height'];
1259  }
1260
1261  // we may have nothing to update at database level, for example with a
1262  // thumbnail update
1263  if (count($update) > 0)
1264  {
1265    $update['id'] = $params['image_id'];
[4513]1266
[4348]1267    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1268    mass_updates(
1269      IMAGES_TABLE,
1270      array(
1271        'primary' => array('id'),
1272        'update'  => array_diff(array_keys($update), array('id'))
1273        ),
1274      array($update)
1275      );
1276  }
1277}
1278
[2463]1279function ws_images_add($params, &$service)
1280{
[8464]1281  global $conf, $user;
[8126]1282  if (!is_admin())
[2496]1283  {
1284    return new PwgError(401, 'Access denied');
1285  }
1286
[3662]1287  foreach ($params as $param_key => $param_value) {
1288    ws_logfile(
1289      sprintf(
1290        '[pwg.images.add] input param "%s" : "%s"',
1291        $param_key,
1292        is_null($param_value) ? 'NULL' : $param_value
1293        )
1294      );
1295  }
[2496]1296
[2592]1297  // does the image already exists ?
[4954]1298  if ('md5sum' == $conf['uniqueness_mode'])
1299  {
1300    $where_clause = "md5sum = '".$params['original_sum']."'";
1301  }
1302  if ('filename' == $conf['uniqueness_mode'])
1303  {
1304    $where_clause = "file = '".$params['original_filename']."'";
1305  }
1306 
[2592]1307  $query = '
1308SELECT
1309    COUNT(*) AS counter
1310  FROM '.IMAGES_TABLE.'
[4954]1311  WHERE '.$where_clause.'
[2592]1312;';
[4325]1313  list($counter) = pwg_db_fetch_row(pwg_query($query));
[2592]1314  if ($counter != 0) {
1315    return new PwgError(500, 'file already exists');
1316  }
1317
[2463]1318  // current date
[4325]1319  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
[2463]1320  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
[2496]1321
[2501]1322  // upload directory hierarchy
[2463]1323  $upload_dir = sprintf(
[5014]1324    $conf['upload_dir'].'/%s/%s/%s',
[2463]1325    $year,
1326    $month,
1327    $day
1328    );
1329
[2501]1330  // compute file path
[2463]1331  $date_string = preg_replace('/[^\d]/', '', $dbnow);
1332  $random_string = substr($params['file_sum'], 0, 8);
1333  $filename_wo_ext = $date_string.'-'.$random_string;
[2501]1334  $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
[2496]1335
[4346]1336  // add files
1337  $file_infos  = add_file($file_path, 'file',  $params['original_sum'], $params['file_sum']);
1338  $thumb_infos = add_file($file_path, 'thumb', $params['original_sum'], $params['thumbnail_sum']);
[2463]1339
[3193]1340  if (isset($params['high_sum']))
[2670]1341  {
[4346]1342    $high_infos = add_file($file_path, 'high', $params['original_sum'], $params['high_sum']);
[2670]1343  }
1344
[2463]1345  // database registration
1346  $insert = array(
[4911]1347    'file' => !empty($params['original_filename']) ? $params['original_filename'] : $filename_wo_ext.'.jpg',
[2463]1348    'date_available' => $dbnow,
1349    'tn_ext' => 'jpg',
1350    'name' => $params['name'],
1351    'path' => $file_path,
[4346]1352    'filesize' => $file_infos['filesize'],
1353    'width' => $file_infos['width'],
1354    'height' => $file_infos['height'],
[3065]1355    'md5sum' => $params['original_sum'],
[8464]1356    'added_by' => $user['id'],
[2463]1357    );
1358
[2569]1359  $info_columns = array(
1360    'name',
1361    'author',
1362    'comment',
1363    'level',
1364    'date_creation',
1365    );
1366
1367  foreach ($info_columns as $key)
1368  {
1369    if (isset($params[$key]))
1370    {
1371      $insert[$key] = $params[$key];
1372    }
1373  }
1374
[3193]1375  if (isset($params['high_sum']))
[2670]1376  {
1377    $insert['has_high'] = 'true';
[4346]1378    $insert['high_filesize'] = $high_infos['filesize'];
[10160]1379    $insert['high_width'] = $high_infos['width'];
1380    $insert['high_height'] = $high_infos['height'];
[2670]1381  }
1382
[2463]1383  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1384  mass_inserts(
1385    IMAGES_TABLE,
1386    array_keys($insert),
1387    array($insert)
1388    );
1389
[4892]1390  $image_id = pwg_db_insert_id(IMAGES_TABLE);
[2463]1391
[2569]1392  // let's add links between the image and the categories
1393  if (isset($params['categories']))
1394  {
[2919]1395    ws_add_image_category_relations($image_id, $params['categories']);
[2553]1396  }
[2569]1397
1398  // and now, let's create tag associations
[3660]1399  if (isset($params['tag_ids']) and !empty($params['tag_ids']))
[2553]1400  {
[2569]1401    set_tags(
1402      explode(',', $params['tag_ids']),
1403      $image_id
1404      );
[2553]1405  }
[2585]1406
[4685]1407  // update metadata from the uploaded file (exif/iptc)
1408  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1409  update_metadata(array($image_id=>$file_path));
1410 
[2501]1411  invalidate_user_cache();
[2463]1412}
1413
[8249]1414function ws_images_addSimple($params, &$service)
1415{
1416  global $conf;
[8274]1417  if (!is_admin())
[8249]1418  {
1419    return new PwgError(401, 'Access denied');
1420  }
1421
1422  if (!$service->isPost())
1423  {
1424    return new PwgError(405, "This method requires HTTP POST");
1425  }
[9191]1426 
1427  $params['image_id'] = (int)$params['image_id'];
1428  if ($params['image_id'] > 0)
1429  {
1430    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
[8249]1431
[9191]1432    $query='
1433SELECT *
1434  FROM '.IMAGES_TABLE.'
1435  WHERE id = '.$params['image_id'].'
1436;';
1437
1438    $image_row = pwg_db_fetch_assoc(pwg_query($query));
1439    if ($image_row == null)
1440    {
1441      return new PwgError(404, "image_id not found");
1442    }
1443  }
1444
[8249]1445  // category
1446  $params['category'] = (int)$params['category'];
[9191]1447  if ($params['category'] <= 0 and $params['image_id'] <= 0)
[8249]1448  {
1449    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
1450  }
1451
1452  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1453  prepare_upload_configuration();
1454
1455  $image_id = add_uploaded_file(
1456    $_FILES['image']['tmp_name'],
1457    $_FILES['image']['name'],
[9191]1458    $params['category'] > 0 ? array($params['category']) : null,
1459    8,
1460    $params['image_id'] > 0 ? $params['image_id'] : null
[8249]1461    );
1462
1463  $info_columns = array(
1464    'name',
1465    'author',
1466    'comment',
1467    'level',
1468    'date_creation',
1469    );
1470
1471  foreach ($info_columns as $key)
1472  {
1473    if (isset($params[$key]))
1474    {
1475      $update[$key] = $params[$key];
1476    }
1477  }
1478
1479  if (count(array_keys($update)) > 0)
1480  {
1481    $update['id'] = $image_id;
1482
1483    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1484    mass_updates(
1485      IMAGES_TABLE,
1486      array(
1487        'primary' => array('id'),
1488        'update'  => array_diff(array_keys($update), array('id'))
1489        ),
1490      array($update)
1491      );
1492  }
1493
1494
1495  if (isset($params['tags']) and !empty($params['tags']))
1496  {
1497    $tag_ids = array();
1498    $tag_names = explode(',', $params['tags']);
1499    foreach ($tag_names as $tag_name)
1500    {
1501      $tag_id = tag_id_from_tag_name($tag_name);
1502      array_push($tag_ids, $tag_id);
1503    }
1504
1505    add_tags($tag_ids, array($image_id));
1506  }
1507
[9191]1508  $url_params = array('image_id' => $image_id);
1509
1510  if ($params['category'] > 0)
1511  {
1512    $query = '
[8249]1513SELECT id, name, permalink
1514  FROM '.CATEGORIES_TABLE.'
1515  WHERE id = '.$params['category'].'
1516;';
[9191]1517    $result = pwg_query($query);
1518    $category = pwg_db_fetch_assoc($result);
[8249]1519
[9191]1520    $url_params['section'] = 'categories';
1521    $url_params['category'] = $category;
1522  }
1523
[9944]1524  // update metadata from the uploaded file (exif/iptc), even if the sync
1525  // was already performed by add_uploaded_file().
1526  $query = '
1527SELECT
1528    path
1529  FROM '.IMAGES_TABLE.'
1530  WHERE id = '.$image_id.'
1531;';
1532  list($file_path) = pwg_db_fetch_row(pwg_query($query));
1533 
1534  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1535  update_metadata(array($image_id=>$file_path));
1536
[8249]1537  return array(
1538    'image_id' => $image_id,
[9191]1539    'url' => make_picture_url($url_params),
[8249]1540    );
1541}
1542
[1781]1543/**
1544 * perform a login (web service method)
1545 */
[1698]1546function ws_session_login($params, &$service)
1547{
1548  global $conf;
1549
1550  if (!$service->isPost())
1551  {
[1852]1552    return new PwgError(405, "This method requires HTTP POST");
[1698]1553  }
[1744]1554  if (try_log_user($params['username'], $params['password'],false))
[1698]1555  {
1556    return true;
1557  }
1558  return new PwgError(999, 'Invalid username/password');
1559}
1560
[1781]1561
1562/**
1563 * performs a logout (web service method)
1564 */
[1698]1565function ws_session_logout($params, &$service)
1566{
[2029]1567  if (!is_a_guest())
[1698]1568  {
[2757]1569    logout_user();
[1698]1570  }
1571  return true;
1572}
1573
1574function ws_session_getStatus($params, &$service)
1575{
[2356]1576  global $user;
[1698]1577  $res = array();
[4304]1578  $res['username'] = is_a_guest() ? 'guest' : stripslashes($user['username']);
[6437]1579  foreach ( array('status', 'theme', 'language') as $k )
[1849]1580  {
1581    $res[$k] = $user[$k];
1582  }
[7212]1583  $res['pwg_token'] = get_pwg_token();
[2126]1584  $res['charset'] = get_pwg_charset();
[1698]1585  return $res;
1586}
1587
1588
[1781]1589/**
1590 * returns a list of tags (web service method)
1591 */
[1698]1592function ws_tags_getList($params, &$service)
1593{
[1711]1594  $tags = get_available_tags();
[1698]1595  if ($params['sort_by_counter'])
1596  {
1597    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1598  }
1599  else
1600  {
[2409]1601    usort($tags, 'tag_alpha_compare');
[1698]1602  }
1603  for ($i=0; $i<count($tags); $i++)
1604  {
[1815]1605    $tags[$i]['id'] = (int)$tags[$i]['id'];
[1698]1606    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1607    $tags[$i]['url'] = make_index_url(
1608        array(
1609          'section'=>'tags',
1610          'tags'=>array($tags[$i])
1611        )
1612      );
1613  }
[2585]1614  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
[1698]1615}
1616
[2584]1617/**
1618 * returns the list of tags as you can see them in administration (web
1619 * service method).
1620 *
1621 * Only admin can run this method and permissions are not taken into
1622 * account.
1623 */
1624function ws_tags_getAdminList($params, &$service)
1625{
1626  if (!is_admin())
1627  {
1628    return new PwgError(401, 'Access denied');
1629  }
[2585]1630
[2584]1631  $tags = get_all_tags();
1632  return array(
1633    'tags' => new PwgNamedArray(
1634      $tags,
1635      'tag',
1636      array(
1637        'name',
1638        'id',
1639        'url_name',
1640        )
1641      )
1642    );
1643}
[1781]1644
1645/**
1646 * returns a list of images for tags (web service method)
1647 */
[1698]1648function ws_tags_getImages($params, &$service)
1649{
1650  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
[1816]1651  global $conf;
[2119]1652
[1698]1653  // first build all the tag_ids we are interested in
[1852]1654  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1655  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
[1698]1656  $tags_by_id = array();
1657  foreach( $tags as $tag )
1658  {
[1852]1659    $tags['id'] = (int)$tag['id'];
[1815]1660    $tags_by_id[ $tag['id'] ] = $tag;
[1698]1661  }
1662  unset($tags);
[1852]1663  $tag_ids = array_keys($tags_by_id);
[1698]1664
1665
[8726]1666  $where_clauses = ws_std_image_sql_filter($params);
1667  if (!empty($where_clauses))
1668  {
1669    $where_clauses = implode( ' AND ', $where_clauses);
1670  }
1671  $image_ids = get_image_ids_for_tags(
1672    $tag_ids,
1673    $params['tag_mode_and'] ? 'AND' : 'OR',
1674    $where_clauses,
1675    ws_std_image_sql_order($params) );
1676
1677
1678  $image_ids = array_slice($image_ids, (int)($params['per_page']*$params['page']), (int)$params['per_page'] );
1679 
[1698]1680  $image_tag_map = array();
[8726]1681  if ( !empty($image_ids) and !$params['tag_mode_and'] )
[1698]1682  { // build list of image ids with associated tags per image
[8726]1683    $query = '
[6652]1684SELECT image_id, GROUP_CONCAT(tag_id) AS tag_ids
[1698]1685  FROM '.IMAGE_TAG_TABLE.'
[8726]1686  WHERE tag_id IN ('.implode(',',$tag_ids).') AND image_id IN ('.implode(',',$image_ids).')
[1698]1687  GROUP BY image_id';
[8726]1688    $result = pwg_query($query);
1689    while ( $row=pwg_db_fetch_assoc($result) )
1690    {
1691      $row['image_id'] = (int)$row['image_id'];
1692      array_push( $image_ids, $row['image_id'] );
1693      $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
[1698]1694    }
1695  }
1696
1697  $images = array();
[8726]1698  if (!empty($image_ids))
[1698]1699  {
[8726]1700    $rank_of = array_flip($image_ids);
1701    $result = pwg_query('
1702SELECT * FROM '.IMAGES_TABLE.'
1703  WHERE id IN ('.implode(',',$image_ids).')');
[4325]1704    while ($row = pwg_db_fetch_assoc($result))
[1698]1705    {
[2119]1706      $image = array();
[8726]1707      $image['rank'] = $rank_of[ $row['id'] ];
[1698]1708      foreach ( array('id', 'width', 'height', 'hit') as $k )
1709      {
1710        if (isset($row[$k]))
1711        {
1712          $image[$k] = (int)$row[$k];
1713        }
1714      }
[1880]1715      foreach ( array('file', 'name', 'comment') as $k )
[1698]1716      {
1717        $image[$k] = $row[$k];
1718      }
1719      $image = array_merge( $image, ws_std_get_urls($row) );
1720
1721      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1722      $image_tags = array();
1723      foreach ($image_tag_ids as $tag_id)
1724      {
1725        $url = make_index_url(
1726                 array(
1727                  'section'=>'tags',
1728                  'tags'=> array($tags_by_id[$tag_id])
1729                )
1730              );
1731        $page_url = make_picture_url(
1732                 array(
1733                  'section'=>'tags',
1734                  'tags'=> array($tags_by_id[$tag_id]),
1735                  'image_id' => $row['id'],
1736                  'image_file' => $row['file'],
1737                )
1738              );
1739        array_push($image_tags, array(
1740                'id' => (int)$tag_id,
1741                'url' => $url,
1742                'page_url' => $page_url,
1743              )
1744            );
1745      }
[1711]1746      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1747              array('id','url_name','url','page_url')
[1698]1748            );
1749      array_push($images, $image);
1750    }
[8726]1751    usort($images, 'rank_compare');
1752    unset($rank_of);
[1698]1753  }
1754
1755  return array( 'images' =>
1756    array (
1757      WS_XML_ATTRIBUTES =>
1758        array(
1759            'page' => $params['page'],
1760            'per_page' => $params['per_page'],
1761            'count' => count($images)
1762          ),
[1711]1763       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
[1845]1764          ws_std_get_image_xml_attributes() )
[1698]1765      )
1766    );
1767}
[2583]1768
1769function ws_categories_add($params, &$service)
1770{
[8126]1771  if (!is_admin())
[2583]1772  {
1773    return new PwgError(401, 'Access denied');
1774  }
1775
1776  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1777
1778  $creation_output = create_virtual_category(
1779    $params['name'],
1780    $params['parent']
1781    );
1782
1783  if (isset($creation_output['error']))
1784  {
1785    return new PwgError(500, $creation_output['error']);
1786  }
[2585]1787
[2644]1788  invalidate_user_cache();
[2757]1789
[2583]1790  return $creation_output;
1791}
[2634]1792
1793function ws_tags_add($params, &$service)
1794{
[8126]1795  if (!is_admin())
[2634]1796  {
1797    return new PwgError(401, 'Access denied');
1798  }
1799
1800  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1801
1802  $creation_output = create_tag($params['name']);
1803
1804  if (isset($creation_output['error']))
1805  {
1806    return new PwgError(500, $creation_output['error']);
1807  }
1808
1809  return $creation_output;
1810}
[2683]1811
1812function ws_images_exist($params, &$service)
1813{
[4954]1814  global $conf;
1815 
[8126]1816  if (!is_admin())
[2683]1817  {
1818    return new PwgError(401, 'Access denied');
1819  }
1820
[4954]1821  $split_pattern = '/[\s,;\|]/';
1822
1823  if ('md5sum' == $conf['uniqueness_mode'])
1824  {
1825    // search among photos the list of photos already added, based on md5sum
1826    // list
1827    $md5sums = preg_split(
1828      $split_pattern,
1829      $params['md5sum_list'],
1830      -1,
1831      PREG_SPLIT_NO_EMPTY
[2683]1832    );
[2757]1833
[4954]1834    $query = '
[2683]1835SELECT
1836    id,
1837    md5sum
1838  FROM '.IMAGES_TABLE.'
[2757]1839  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
[2683]1840;';
[4954]1841    $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
[2683]1842
[4954]1843    $result = array();
[2757]1844
[4954]1845    foreach ($md5sums as $md5sum)
1846    {
1847      $result[$md5sum] = null;
1848      if (isset($id_of_md5[$md5sum]))
1849      {
1850        $result[$md5sum] = $id_of_md5[$md5sum];
1851      }
1852    }
1853  }
1854 
1855  if ('filename' == $conf['uniqueness_mode'])
[2683]1856  {
[4954]1857    // search among photos the list of photos already added, based on
1858    // filename list
1859    $filenames = preg_split(
1860      $split_pattern,
1861      $params['filename_list'],
1862      -1,
1863      PREG_SPLIT_NO_EMPTY
1864    );
1865
1866    $query = '
1867SELECT
1868    id,
1869    file
1870  FROM '.IMAGES_TABLE.'
1871  WHERE file IN (\''.implode("','", $filenames).'\')
1872;';
1873    $id_of_filename = simple_hash_from_query($query, 'file', 'id');
1874
1875    $result = array();
1876
1877    foreach ($filenames as $filename)
[2683]1878    {
[4954]1879      $result[$filename] = null;
1880      if (isset($id_of_filename[$filename]))
1881      {
1882        $result[$filename] = $id_of_filename[$filename];
1883      }
[2683]1884    }
1885  }
1886
1887  return $result;
1888}
[2919]1889
[4347]1890function ws_images_checkFiles($params, &$service)
1891{
[8126]1892  if (!is_admin())
[4347]1893  {
1894    return new PwgError(401, 'Access denied');
1895  }
1896
1897  // input parameters
1898  //
1899  // image_id
1900  // thumbnail_sum
1901  // file_sum
1902  // high_sum
1903
1904  $params['image_id'] = (int)$params['image_id'];
1905  if ($params['image_id'] <= 0)
1906  {
1907    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1908  }
1909
1910  $query = '
1911SELECT
1912    path
1913  FROM '.IMAGES_TABLE.'
1914  WHERE id = '.$params['image_id'].'
1915;';
1916  $result = pwg_query($query);
[6500]1917  if (pwg_db_num_rows($result) == 0) {
[4347]1918    return new PwgError(404, "image_id not found");
1919  }
[6500]1920  list($path) = pwg_db_fetch_row($result);
[4347]1921
1922  $ret = array();
1923
1924  foreach (array('thumb', 'file', 'high') as $type) {
1925    $param_name = $type;
1926    if ('thumb' == $type) {
1927      $param_name = 'thumbnail';
1928    }
1929
1930    if (isset($params[$param_name.'_sum'])) {
[8249]1931      include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[4347]1932      $type_path = file_path_for_type($path, $type);
1933      if (!is_file($type_path)) {
1934        $ret[$param_name] = 'missing';
1935      }
1936      else {
1937        if (md5_file($type_path) != $params[$param_name.'_sum']) {
1938          $ret[$param_name] = 'differs';
1939        }
1940        else {
1941          $ret[$param_name] = 'equals';
1942        }
1943      }
1944    }
1945  }
1946
1947  return $ret;
1948}
1949
[2919]1950function ws_images_setInfo($params, &$service)
1951{
1952  global $conf;
[8126]1953  if (!is_admin())
[2919]1954  {
1955    return new PwgError(401, 'Access denied');
1956  }
1957
[4511]1958  if (!$service->isPost())
1959  {
1960    return new PwgError(405, "This method requires HTTP POST");
1961  }
1962
[2919]1963  $params['image_id'] = (int)$params['image_id'];
1964  if ($params['image_id'] <= 0)
1965  {
1966    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1967  }
1968
[7613]1969  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1970
[2919]1971  $query='
1972SELECT *
1973  FROM '.IMAGES_TABLE.'
1974  WHERE id = '.$params['image_id'].'
1975;';
1976
[4325]1977  $image_row = pwg_db_fetch_assoc(pwg_query($query));
[2919]1978  if ($image_row == null)
1979  {
1980    return new PwgError(404, "image_id not found");
1981  }
1982
1983  // database registration
[4460]1984  $update = array();
[2919]1985
1986  $info_columns = array(
1987    'name',
1988    'author',
1989    'comment',
1990    'level',
1991    'date_creation',
1992    );
1993
1994  foreach ($info_columns as $key)
1995  {
1996    if (isset($params[$key]))
1997    {
[4460]1998      if ('fill_if_empty' == $params['single_value_mode'])
1999      {
2000        if (empty($image_row[$key]))
2001        {
2002          $update[$key] = $params[$key];
2003        }
2004      }
2005      elseif ('replace' == $params['single_value_mode'])
2006      {
2007        $update[$key] = $params[$key];
2008      }
2009      else
2010      {
2011        new PwgError(
2012          500,
2013          '[ws_images_setInfo]'
2014          .' invalid parameter single_value_mode "'.$params['single_value_mode'].'"'
2015          .', possible values are {fill_if_empty, replace}.'
2016          );
2017        exit();
2018      }
[2919]2019    }
2020  }
2021
[4460]2022  if (count(array_keys($update)) > 0)
[2919]2023  {
[4460]2024    $update['id'] = $params['image_id'];
2025
[2919]2026    mass_updates(
2027      IMAGES_TABLE,
2028      array(
2029        'primary' => array('id'),
2030        'update'  => array_diff(array_keys($update), array('id'))
2031        ),
2032      array($update)
2033      );
2034  }
[3145]2035
[2919]2036  if (isset($params['categories']))
2037  {
2038    ws_add_image_category_relations(
2039      $params['image_id'],
[4445]2040      $params['categories'],
[4460]2041      ('replace' == $params['multiple_value_mode'] ? true : false)
[2919]2042      );
2043  }
2044
2045  // and now, let's create tag associations
2046  if (isset($params['tag_ids']))
2047  {
[4445]2048    $tag_ids = explode(',', $params['tag_ids']);
2049
[4460]2050    if ('replace' == $params['multiple_value_mode'])
[4445]2051    {
2052      set_tags(
2053        $tag_ids,
2054        $params['image_id']
2055        );
2056    }
[4460]2057    elseif ('append' == $params['multiple_value_mode'])
[4445]2058    {
2059      add_tags(
2060        $tag_ids,
2061        array($params['image_id'])
2062        );
2063    }
[4460]2064    else
2065    {
2066      new PwgError(
2067        500,
2068        '[ws_images_setInfo]'
2069        .' invalid parameter multiple_value_mode "'.$params['multiple_value_mode'].'"'
2070        .', possible values are {replace, append}.'
2071        );
2072      exit();
2073    }
[2919]2074  }
2075
2076  invalidate_user_cache();
2077}
2078
[8266]2079function ws_images_delete($params, &$service)
2080{
2081  global $conf;
[8274]2082  if (!is_admin())
[8266]2083  {
2084    return new PwgError(401, 'Access denied');
2085  }
2086
2087  if (!$service->isPost())
2088  {
2089    return new PwgError(405, "This method requires HTTP POST");
2090  }
2091
2092  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2093  {
2094    return new PwgError(403, 'Invalid security token');
2095  }
2096
2097  $params['image_id'] = preg_split(
2098    '/[\s,;\|]/',
2099    $params['image_id'],
2100    -1,
2101    PREG_SPLIT_NO_EMPTY
2102    );
2103  $params['image_id'] = array_map('intval', $params['image_id']);
2104
2105  $image_ids = array();
2106  foreach ($params['image_id'] as $image_id)
2107  {
2108    if ($image_id > 0)
2109    {
2110      array_push($image_ids, $image_id);
2111    }
2112  }
2113
2114  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2115  delete_elements($image_ids, true);
2116}
2117
[4445]2118function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
[2919]2119{
2120  // let's add links between the image and the categories
2121  //
2122  // $params['categories'] should look like 123,12;456,auto;789 which means:
2123  //
2124  // 1. associate with category 123 on rank 12
2125  // 2. associate with category 456 on automatic rank
2126  // 3. associate with category 789 on automatic rank
2127  $cat_ids = array();
2128  $rank_on_category = array();
2129  $search_current_ranks = false;
2130
2131  $tokens = explode(';', $categories_string);
2132  foreach ($tokens as $token)
2133  {
[2920]2134    @list($cat_id, $rank) = explode(',', $token);
[2919]2135
[4445]2136    if (!preg_match('/^\d+$/', $cat_id))
2137    {
2138      continue;
2139    }
2140
[2919]2141    array_push($cat_ids, $cat_id);
2142
2143    if (!isset($rank))
2144    {
2145      $rank = 'auto';
2146    }
2147    $rank_on_category[$cat_id] = $rank;
2148
2149    if ($rank == 'auto')
2150    {
2151      $search_current_ranks = true;
2152    }
2153  }
2154
2155  $cat_ids = array_unique($cat_ids);
2156
[4445]2157  if (count($cat_ids) == 0)
[2919]2158  {
[4445]2159    new PwgError(
2160      500,
2161      '[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
2162      );
2163    exit();
2164  }
[4513]2165
[4445]2166  $query = '
2167SELECT
2168    id
2169  FROM '.CATEGORIES_TABLE.'
2170  WHERE id IN ('.implode(',', $cat_ids).')
2171;';
2172  $db_cat_ids = array_from_query($query, 'id');
2173
2174  $unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
2175  if (count($unknown_cat_ids) != 0)
2176  {
2177    new PwgError(
2178      500,
2179      '[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
2180      );
2181    exit();
2182  }
[4513]2183
[4445]2184  $to_update_cat_ids = array();
[4513]2185
[4445]2186  // in case of replace mode, we first check the existing associations
2187  $query = '
2188SELECT
2189    category_id
2190  FROM '.IMAGE_CATEGORY_TABLE.'
2191  WHERE image_id = '.$image_id.'
2192;';
2193  $existing_cat_ids = array_from_query($query, 'category_id');
2194
2195  if ($replace_mode)
2196  {
2197    $to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
2198    if (count($to_remove_cat_ids) > 0)
[2919]2199    {
2200      $query = '
[4445]2201DELETE
2202  FROM '.IMAGE_CATEGORY_TABLE.'
2203  WHERE image_id = '.$image_id.'
2204    AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
2205;';
2206      pwg_query($query);
2207      update_category($to_remove_cat_ids);
2208    }
2209  }
[4513]2210
[4445]2211  $new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
2212  if (count($new_cat_ids) == 0)
2213  {
2214    return true;
2215  }
[4513]2216
[4445]2217  if ($search_current_ranks)
2218  {
2219    $query = '
[2919]2220SELECT
2221    category_id,
2222    MAX(rank) AS max_rank
2223  FROM '.IMAGE_CATEGORY_TABLE.'
2224  WHERE rank IS NOT NULL
[4445]2225    AND category_id IN ('.implode(',', $new_cat_ids).')
[2919]2226  GROUP BY category_id
2227;';
[4445]2228    $current_rank_of = simple_hash_from_query(
2229      $query,
2230      'category_id',
2231      'max_rank'
2232      );
[2919]2233
[4445]2234    foreach ($new_cat_ids as $cat_id)
2235    {
2236      if (!isset($current_rank_of[$cat_id]))
[2919]2237      {
[4445]2238        $current_rank_of[$cat_id] = 0;
[2919]2239      }
[4513]2240
[4445]2241      if ('auto' == $rank_on_category[$cat_id])
2242      {
2243        $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
2244      }
[2919]2245    }
[4445]2246  }
[4513]2247
[4445]2248  $inserts = array();
[4513]2249
[4445]2250  foreach ($new_cat_ids as $cat_id)
2251  {
2252    array_push(
2253      $inserts,
2254      array(
2255        'image_id' => $image_id,
2256        'category_id' => $cat_id,
2257        'rank' => $rank_on_category[$cat_id],
2258        )
[2919]2259      );
2260  }
[4513]2261
[4445]2262  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2263  mass_inserts(
2264    IMAGE_CATEGORY_TABLE,
2265    array_keys($inserts[0]),
2266    $inserts
2267    );
[4513]2268
[4445]2269  update_category($new_cat_ids);
[2919]2270}
[3193]2271
[3454]2272function ws_categories_setInfo($params, &$service)
2273{
2274  global $conf;
[8126]2275  if (!is_admin())
[3454]2276  {
2277    return new PwgError(401, 'Access denied');
2278  }
2279
[4511]2280  if (!$service->isPost())
2281  {
2282    return new PwgError(405, "This method requires HTTP POST");
2283  }
2284
[3454]2285  // category_id
2286  // name
2287  // comment
2288
2289  $params['category_id'] = (int)$params['category_id'];
2290  if ($params['category_id'] <= 0)
2291  {
2292    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2293  }
2294
2295  // database registration
2296  $update = array(
2297    'id' => $params['category_id'],
2298    );
2299
2300  $info_columns = array(
2301    'name',
2302    'comment',
2303    );
2304
2305  $perform_update = false;
2306  foreach ($info_columns as $key)
2307  {
2308    if (isset($params[$key]))
2309    {
2310      $perform_update = true;
2311      $update[$key] = $params[$key];
2312    }
2313  }
2314
2315  if ($perform_update)
2316  {
2317    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2318    mass_updates(
2319      CATEGORIES_TABLE,
2320      array(
2321        'primary' => array('id'),
2322        'update'  => array_diff(array_keys($update), array('id'))
2323        ),
2324      array($update)
2325      );
2326  }
[3488]2327
[3454]2328}
2329
[8266]2330function ws_categories_delete($params, &$service)
2331{
2332  global $conf;
[8274]2333  if (!is_admin())
[8266]2334  {
2335    return new PwgError(401, 'Access denied');
2336  }
2337
2338  if (!$service->isPost())
2339  {
2340    return new PwgError(405, "This method requires HTTP POST");
2341  }
2342
2343  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2344  {
2345    return new PwgError(403, 'Invalid security token');
2346  }
2347
2348  $modes = array('no_delete', 'delete_orphans', 'force_delete');
2349  if (!in_array($params['photo_deletion_mode'], $modes))
2350  {
2351    return new PwgError(
2352      500,
2353      '[ws_categories_delete]'
2354      .' invalid parameter photo_deletion_mode "'.$params['photo_deletion_mode'].'"'
2355      .', possible values are {'.implode(', ', $modes).'}.'
2356      );
2357  }
2358
2359  $params['category_id'] = preg_split(
2360    '/[\s,;\|]/',
2361    $params['category_id'],
2362    -1,
2363    PREG_SPLIT_NO_EMPTY
2364    );
2365  $params['category_id'] = array_map('intval', $params['category_id']);
2366
2367  $category_ids = array();
2368  foreach ($params['category_id'] as $category_id)
2369  {
2370    if ($category_id > 0)
2371    {
2372      array_push($category_ids, $category_id);
2373    }
2374  }
2375
2376  if (count($category_ids) == 0)
2377  {
2378    return;
2379  }
2380
2381  $query = '
2382SELECT id
2383  FROM '.CATEGORIES_TABLE.'
2384  WHERE id IN ('.implode(',', $category_ids).')
2385;';
2386  $category_ids = array_from_query($query, 'id');
2387
2388  if (count($category_ids) == 0)
2389  {
2390    return;
2391  }
2392 
2393  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2394  delete_categories($category_ids, $params['photo_deletion_mode']);
2395  update_global_rank();
2396}
2397
[8272]2398function ws_categories_move($params, &$service)
2399{
2400  global $conf, $page;
2401 
[8274]2402  if (!is_admin())
[8272]2403  {
2404    return new PwgError(401, 'Access denied');
2405  }
2406
2407  if (!$service->isPost())
2408  {
2409    return new PwgError(405, "This method requires HTTP POST");
2410  }
2411
2412  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2413  {
2414    return new PwgError(403, 'Invalid security token');
2415  }
2416
2417  $params['category_id'] = preg_split(
2418    '/[\s,;\|]/',
2419    $params['category_id'],
2420    -1,
2421    PREG_SPLIT_NO_EMPTY
2422    );
2423  $params['category_id'] = array_map('intval', $params['category_id']);
2424
2425  $category_ids = array();
2426  foreach ($params['category_id'] as $category_id)
2427  {
2428    if ($category_id > 0)
2429    {
2430      array_push($category_ids, $category_id);
2431    }
2432  }
2433
2434  if (count($category_ids) == 0)
2435  {
2436    return new PwgError(403, 'Invalid category_id input parameter, no category to move');
2437  }
2438
2439  // we can't move physical categories
2440  $categories_in_db = array();
2441 
2442  $query = '
2443SELECT
2444    id,
2445    name,
2446    dir
2447  FROM '.CATEGORIES_TABLE.'
2448  WHERE id IN ('.implode(',', $category_ids).')
2449;';
2450  $result = pwg_query($query);
2451  while ($row = pwg_db_fetch_assoc($result))
2452  {
2453    $categories_in_db[$row['id']] = $row;
2454    // we break on error at first physical category detected
2455    if (!empty($row['dir']))
2456    {
2457      $row['name'] = strip_tags(
2458        trigger_event(
2459          'render_category_name',
2460          $row['name'],
2461          'ws_categories_move'
2462          )
2463        );
2464     
2465      return new PwgError(
2466        403,
2467        sprintf(
2468          'Category %s (%u) is not a virtual category, you cannot move it',
2469          $row['name'],
2470          $row['id']
2471          )
2472        );
2473    }
2474  }
2475
2476  if (count($categories_in_db) != count($category_ids))
2477  {
2478    $unknown_category_ids = array_diff($category_ids, array_keys($categories_in_db));
2479   
2480    return new PwgError(
2481      403,
2482      sprintf(
2483        'Category %u does not exist',
2484        $unknown_category_ids[0]
2485        )
2486      );
2487  }
2488
2489  // does this parent exists? This check should be made in the
2490  // move_categories function, not here
2491  //
2492  // 0 as parent means "move categories at gallery root"
2493  if (!is_numeric($params['parent']))
2494  {
2495    return new PwgError(403, 'Invalid parent input parameter');
2496  }
2497 
2498  if (0 != $params['parent']) {
2499    $params['parent'] = intval($params['parent']);
2500    $subcat_ids = get_subcat_ids(array($params['parent']));
2501    if (count($subcat_ids) == 0)
2502    {
2503      return new PwgError(403, 'Unknown parent category id');
2504    }
2505  }
2506
2507  $page['infos'] = array();
2508  $page['errors'] = array();
2509  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2510  move_categories($category_ids, $params['parent']);
2511  invalidate_user_cache();
2512
2513  if (count($page['errors']) != 0)
2514  {
2515    return new PwgError(403, implode('; ', $page['errors']));
2516  }
2517}
2518
[3193]2519function ws_logfile($string)
2520{
[3662]2521  global $conf;
[3488]2522
[3662]2523  if (!$conf['ws_enable_log']) {
2524    return true;
2525  }
2526
[3193]2527  file_put_contents(
[3662]2528    $conf['ws_log_filepath'],
[3193]2529    '['.date('c').'] '.$string."\n",
2530    FILE_APPEND
2531    );
2532}
[6049]2533
2534function ws_images_checkUpload($params, &$service)
2535{
2536  global $conf;
2537
[8126]2538  if (!is_admin())
[6049]2539  {
2540    return new PwgError(401, 'Access denied');
2541  }
2542
[8249]2543  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[6051]2544  $ret['message'] = ready_for_upload_message();
2545  $ret['ready_for_upload'] = true;
2546 
2547  if (!empty($ret['message']))
2548  {
2549    $ret['ready_for_upload'] = false;
2550  }
2551 
2552  return $ret;
2553}
[8273]2554
2555function ws_plugins_getList($params, &$service)
2556{
2557  global $conf;
2558 
2559  if (!is_admin())
2560  {
2561    return new PwgError(401, 'Access denied');
2562  }
2563
2564  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
2565  $plugins = new plugins();
2566  $plugins->sort_fs_plugins('name');
2567  $plugin_list = array();
2568
2569  foreach($plugins->fs_plugins as $plugin_id => $fs_plugin)
2570  {
2571    if (isset($plugins->db_plugins_by_id[$plugin_id]))
2572    {
2573      $state = $plugins->db_plugins_by_id[$plugin_id]['state'];
2574    }
2575    else
2576    {
2577      $state = 'uninstalled';
2578    }
2579
2580    array_push(
2581      $plugin_list,
2582      array(
2583        'id' => $plugin_id,
2584        'name' => $fs_plugin['name'],
2585        'version' => $fs_plugin['version'],
2586        'state' => $state,
2587        'description' => $fs_plugin['description'],
2588        )
2589      );
2590  }
2591
2592  return $plugin_list;
2593}
2594
2595function ws_plugins_performAction($params, &$service)
2596{
2597  global $template;
2598 
2599  if (!is_admin())
2600  {
2601    return new PwgError(401, 'Access denied');
2602  }
2603
2604  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2605  {
2606    return new PwgError(403, 'Invalid security token');
2607  }
2608
2609  define('IN_ADMIN', true);
2610  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
2611  $plugins = new plugins();
2612  $errors = $plugins->perform_action($params['action'], $params['plugin']);
2613
2614 
2615  if (!empty($errors))
2616  {
2617    return new PwgError(500, $errors);
2618  }
2619  else
2620  {
2621    if (in_array($params['action'], array('activate', 'deactivate')))
2622    {
2623      $template->delete_compiled_templates();
2624    }
2625    return true;
2626  }
2627}
2628
[8297]2629function ws_themes_performAction($params, &$service)
2630{
2631  global $template;
2632 
[8726]2633  if (!is_admin())
[8297]2634  {
2635    return new PwgError(401, 'Access denied');
2636  }
2637
2638  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2639  {
2640    return new PwgError(403, 'Invalid security token');
2641  }
2642
2643  define('IN_ADMIN', true);
2644  include_once(PHPWG_ROOT_PATH.'admin/include/themes.class.php');
2645  $themes = new themes();
2646  $errors = $themes->perform_action($params['action'], $params['theme']);
2647 
2648  if (!empty($errors))
2649  {
2650    return new PwgError(500, $errors);
2651  }
2652  else
2653  {
2654    if (in_array($params['action'], array('activate', 'deactivate')))
2655    {
2656      $template->delete_compiled_templates();
2657    }
2658    return true;
2659  }
2660}
[10235]2661
2662function ws_images_resize($params, &$service)
2663{
2664  global $conf;
2665
2666  if (!is_admin())
2667  {
2668    return new PwgError(401, 'Access denied');
2669  }
2670
2671  if (!in_array($params['type'], array('thumbnail', 'websize')))
2672  {
2673    return new PwgError(403, 'Unknown type (only "thumbnail" or "websize" are accepted');
2674  }
2675
2676  $resize_params = array('maxwidth', 'maxheight', 'quality');
2677  $type = $params['type'] == 'thumbnail' ? 'thumb' : 'websize';
2678  foreach ($resize_params as $param)
2679  {
2680    if (empty($params[$param]))
2681      $params[$param] = $conf['upload_form_'.$type.'_'.$param];
2682  }
2683
2684  $query='
2685SELECT id, path, tn_ext, has_high
2686FROM '.IMAGES_TABLE.'
2687WHERE id = '.(int)$params['image_id'].'
2688;';
2689  $image = pwg_db_fetch_assoc(pwg_query($query));
2690
2691  if ($image == null)
2692  {
2693    return new PwgError(403, "image_id not found");
2694  }
2695
2696  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
2697
2698  if (!is_valid_image_extension(get_extension($image['path'])))
2699  {
2700    return new PwgError(403, "image can't be resized");
2701  }
2702
2703  if ($params['type'] == 'thumbnail' and !empty($image['tn_ext']))
2704  {
2705    trigger_event(
2706      'upload_thumbnail_resize',
2707      false,
2708      $image['path'],
2709      get_thumbnail_path($image),
2710      $params['maxwidth'],
2711      $params['maxheight'],
2712      $params['quality'],
2713      true
2714    );
2715    return true;
2716  }
2717  elseif (!empty($image['has_high']))
2718  {
2719    trigger_event(
2720      'upload_image_resize',
2721      false,
2722      file_path_for_type($image['path'], 'high'),
2723      $image['path'],
2724      $params['maxwidth'],
2725      $params['maxheight'],
2726      $params['quality'],
2727      false
2728      );
2729    return true;
2730  }
2731  return false;
2732}
[1698]2733?>
Note: See TracBrowser for help on using the repository browser.