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

Last change on this file since 11116 was 11116, checked in by plg, 13 years ago

merge r11115 from branch 2.2 to trunk

feature 2244 added: web API methods pwg.categories.getImages,
pwg.tags.getImages and pwg.images.search now give the date_creation
and date_available for each returned photo.

  • Property svn:eol-style set to LF
File size: 71.3 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24/**** IMPLEMENTATION OF WEB SERVICE METHODS ***********************************/
25
26/**
27 * Event handler for method invocation security check. Should return a PwgError
28 * if the preconditions are not satifsied for method invocation.
29 */
30function ws_isInvokeAllowed($res, $methodName, $params)
31{
32  global $conf;
33
34  if ( strpos($methodName,'reflection.')===0 )
35  { // OK for reflection
36    return $res;
37  }
38
39  if ( !is_autorize_status(ACCESS_GUEST) and
40      strpos($methodName,'pwg.session.')!==0 )
41  {
42    return new PwgError(401, 'Access denied');
43  }
44
45  return $res;
46}
47
48/**
49 * returns a "standard" (for our web service) array of sql where clauses that
50 * filters the images (images table only)
51 */
52function ws_std_image_sql_filter( $params, $tbl_name='' )
53{
54  $clauses = array();
55  if ( is_numeric($params['f_min_rate']) )
56  {
57    $clauses[] = $tbl_name.'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  }
71  if ( isset($params['f_min_date_available']) )
72  {
73    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_available']."'";
74  }
75  if ( isset($params['f_max_date_available']) )
76  {
77    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_available']."'";
78  }
79  if ( isset($params['f_min_date_created']) )
80  {
81    $clauses[] = $tbl_name."date_creation>='".$params['f_min_date_created']."'";
82  }
83  if ( isset($params['f_max_date_created']) )
84  {
85    $clauses[] = $tbl_name."date_creation<'".$params['f_max_date_created']."'";
86  }
87  if ( is_numeric($params['f_min_ratio']) )
88  {
89    $clauses[] = $tbl_name.'width/'.$tbl_name.'height>'.$params['f_min_ratio'];
90  }
91  if ( is_numeric($params['f_max_ratio']) )
92  {
93    $clauses[] = $tbl_name.'width/'.$tbl_name.'height<='.$params['f_max_ratio'];
94  }
95  if ( $params['f_with_thumbnail'] )
96  {
97    $clauses[] = $tbl_name.'tn_ext IS NOT NULL';
98  }
99  return $clauses;
100}
101
102/**
103 * returns a "standard" (for our web service) ORDER BY sql clause for images
104 */
105function ws_std_image_sql_order( $params, $tbl_name='' )
106{
107  $ret = '';
108  if ( empty($params['order']) )
109  {
110    return $ret;
111  }
112  $matches = array();
113  preg_match_all('/([a-z_]+) *(?:(asc|desc)(?:ending)?)? *(?:, *|$)/i',
114    $params['order'], $matches);
115  for ($i=0; $i<count($matches[1]); $i++)
116  {
117    switch ($matches[1][$i])
118    {
119      case 'date_created':
120        $matches[1][$i] = 'date_creation'; break;
121      case 'date_posted':
122        $matches[1][$i] = 'date_available'; break;
123      case 'rand': case 'random':
124        $matches[1][$i] = DB_RANDOM_FUNCTION.'()'; break;
125    }
126    $sortable_fields = array('id', 'file', 'name', 'hit', 'average_rate',
127      'date_creation', 'date_available', DB_RANDOM_FUNCTION.'()' );
128    if ( in_array($matches[1][$i], $sortable_fields) )
129    {
130      if (!empty($ret))
131        $ret .= ', ';
132      if ($matches[1][$i] != DB_RANDOM_FUNCTION.'()' )
133      {
134        $ret .= $tbl_name;
135      }
136      $ret .= $matches[1][$i];
137      $ret .= ' '.$matches[2][$i];
138    }
139  }
140  return $ret;
141}
142
143/**
144 * returns an array map of urls (thumb/element) for image_row - to be returned
145 * in a standard way by different web service methods
146 */
147function ws_std_get_urls($image_row)
148{
149  $ret = array(
150    'tn_url' => get_thumbnail_url($image_row),
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
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','date_available','date_creation'
169    );
170}
171
172/**
173 * returns PWG version (web service method)
174 */
175function ws_getVersion($params, &$service)
176{
177  global $conf;
178  if ($conf['show_version'] or is_admin() )
179    return PHPWG_VERSION;
180  else
181    return new PwgError(403, 'Forbidden');
182}
183
184/**
185 * returns general informations (web service method)
186 */
187function ws_getInfos($params, &$service)
188{
189  if (!is_admin())
190  {
191    return new PwgError(403, 'Forbidden');
192  }
193
194  $infos['version'] = PHPWG_VERSION;
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
234  if ($infos['nb_comments'] > 0)
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
251function ws_caddie_add($params, &$service)
252{
253  if (!is_admin())
254  {
255    return new PwgError(401, 'Access denied');
256  }
257  $params['image_id'] = array_map( 'intval',$params['image_id'] );
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}
280
281/**
282 * returns images per category (web service method)
283 */
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    {
300      $where_clauses[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.$cat_id.'(,|$)\'';
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  }
314  $where_clauses[] = get_sql_condition_FandF(
315        array('forbidden_categories' => 'id'),
316        NULL, true
317      );
318
319  $query = '
320SELECT id, name, permalink, image_order
321  FROM '.CATEGORIES_TABLE.'
322  WHERE '. implode('
323    AND ', $where_clauses);
324  $result = pwg_query($query);
325  $cats = array();
326  while ($row = pwg_db_fetch_assoc($result))
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      .')';
339    $where_clauses[] = get_sql_condition_FandF( array(
340          'visible_images' => 'i.id'
341        ), null, true
342      );
343
344    $order_by = ws_std_image_sql_order($params, 'i.');
345    if ( empty($order_by)
346          and count($params['cat_id'])==1
347          and isset($cats[ $params['cat_id'][0] ]['image_order'])
348        )
349    {
350      $order_by = $cats[ $params['cat_id'][0] ]['image_order'];
351    }
352    $order_by = empty($order_by) ? $conf['order_by'] : 'ORDER BY '.$order_by;
353
354    $query = '
355SELECT i.*, GROUP_CONCAT(category_id) AS cat_ids
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.'
362LIMIT '.(int)$params['per_page'].' OFFSET '.(int)($params['per_page']*$params['page']);
363
364    $result = pwg_query($query);
365    while ($row = pwg_db_fetch_assoc($result))
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      }
375      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
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(
386                  'category' => $cats[$cat_id],
387                  )
388                );
389        $page_url = make_picture_url(
390                array(
391                  'category' => $cats[$cat_id],
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          ),
421       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
422          ws_std_get_image_xml_attributes() )
423      )
424    );
425}
426
427
428/**
429 * returns a list of categories (web service method)
430 */
431function ws_categories_getList($params, &$service)
432{
433  global $user,$conf;
434
435  $where = array('1=1');
436  $join_type = 'INNER';
437  $join_user = $user['id'];
438
439  if (!$params['recursive'])
440  {
441    if ($params['cat_id']>0)
442      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
443    OR id='.(int)($params['cat_id']).')';
444    else
445      $where[] = 'id_uppercat IS NULL';
446  }
447  else if ($params['cat_id']>0)
448  {
449    $where[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.
450      (int)($params['cat_id'])
451      .'(,|$)\'';
452  }
453
454  if ($params['public'])
455  {
456    $where[] = 'status = "public"';
457    $where[] = 'visible = "true"';
458   
459    $join_user = $conf['guest_id'];
460  }
461  elseif (is_admin())
462  {
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';
471  }
472
473  $query = '
474SELECT id, name, permalink, uppercats, global_rank,
475    comment,
476    nb_images, count_images AS total_nb_images,
477    date_last, max_date_last, count_categories AS nb_categories
478  FROM '.CATEGORIES_TABLE.'
479   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
480  WHERE '. implode('
481    AND ', $where);
482
483  $result = pwg_query($query);
484
485  $cats = array();
486  while ($row = pwg_db_fetch_assoc($result))
487  {
488    $row['url'] = make_index_url(
489        array(
490          'category' => $row
491          )
492      );
493    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
494    {
495      $row[$key] = (int)$row[$key];
496    }
497
498    $row['name'] = strip_tags(
499      trigger_event(
500        'render_category_name',
501        $row['name'],
502        'ws_categories_getList'
503        )
504      );
505   
506    $row['comment'] = strip_tags(
507      trigger_event(
508        'render_category_description',
509        $row['comment'],
510        'ws_categories_getList'
511        )
512      );
513   
514    array_push($cats, $row);
515  }
516  usort($cats, 'global_rank_compare');
517  return array(
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      )
531    );
532}
533
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  }
547
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,
561    comment,
562    uppercats,
563    global_rank
564  FROM '.CATEGORIES_TABLE.'
565;';
566  $result = pwg_query($query);
567  $cats = array();
568
569  while ($row = pwg_db_fetch_assoc($result))
570  {
571    $id = $row['id'];
572    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
573    $row['name'] = strip_tags(
574      trigger_event(
575        'render_category_name',
576        $row['name'],
577        'ws_categories_getAdminList'
578        )
579      );
580    $row['comment'] = strip_tags(
581      trigger_event(
582        'render_category_description',
583        $row['comment'],
584        'ws_categories_getAdminList'
585        )
586      );
587    array_push($cats, $row);
588  }
589
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
606/**
607 * returns detailed information for an element (web service method)
608 */
609function ws_images_addComment($params, &$service)
610{
611  if (!$service->isPost())
612  {
613    return new PwgError(405, "This method requires HTTP POST");
614  }
615  $params['image_id'] = (int)$params['image_id'];
616  $query = '
617SELECT DISTINCT image_id
618  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
619  WHERE commentable="true"
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    );
629  if ( !pwg_db_num_rows( pwg_query( $query ) ) )
630  {
631    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
632  }
633
634  $comm = array(
635    'author' => trim( $params['author'] ),
636    'content' => trim( $params['content'] ),
637    'image_id' => $params['image_id'],
638   );
639
640  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
641
642  $comment_action = insert_user_comment(
643      $comm, $params['key'], $infos
644    );
645
646  switch ($comment_action)
647  {
648    case 'reject':
649      array_push($infos, l10n('Your comment has NOT been registered because it did not pass the validation rules') );
650      return new PwgError(403, implode("; ", $infos) );
651    case 'validate':
652    case 'moderate':
653      $ret = array(
654          'id' => $comm['id'],
655          'validation' => $comment_action=='validate',
656        );
657      return new PwgNamedStruct(
658          'comment',
659          $ret,
660          null, array()
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 */
670function ws_images_getInfo($params, &$service)
671{
672  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
673  global $user, $conf;
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  }
679
680  $query='
681SELECT * FROM '.IMAGES_TABLE.'
682  WHERE id='.$params['image_id'].
683    get_sql_condition_FandF(
684      array('visible_images' => 'id'),
685      ' AND'
686    ).'
687LIMIT 1';
688
689  $image_row = pwg_db_fetch_assoc(pwg_query($query));
690  if ($image_row==null)
691  {
692    return new PwgError(404, "image_id not found");
693  }
694  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
695
696  //-------------------------------------------------------- related categories
697  $query = '
698SELECT id, name, permalink, uppercats, global_rank, commentable
699  FROM '.IMAGE_CATEGORY_TABLE.'
700    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
701  WHERE image_id = '.$image_row['id'].
702  get_sql_condition_FandF(
703      array( 'forbidden_categories' => 'category_id' ),
704      ' AND'
705    ).'
706;';
707  $result = pwg_query($query);
708  $is_commentable = false;
709  $related_categories = array();
710  while ($row = pwg_db_fetch_assoc($result))
711  {
712    if ($row['commentable']=='true')
713    {
714      $is_commentable = true;
715    }
716    unset($row['commentable']);
717    $row['url'] = make_index_url(
718        array(
719          'category' => $row
720          )
721      );
722
723    $row['page_url'] = make_picture_url(
724        array(
725          'image_id' => $image_row['id'],
726          'image_file' => $image_row['file'],
727          'category' => $row
728          )
729      );
730    $row['id']=(int)$row['id'];
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
740  $related_tags = get_common_tags( array($image_row['id']), -1 );
741  foreach( $related_tags as $i=>$tag)
742  {
743    $tag['url'] = make_index_url(
744        array(
745          'tags' => array($tag)
746          )
747      );
748    $tag['page_url'] = make_picture_url(
749        array(
750          'image_id' => $image_row['id'],
751          'image_file' => $image_row['file'],
752          'tags' => array($tag),
753          )
754      );
755    unset($tag['counter']);
756    $tag['id']=(int)$tag['id'];
757    $related_tags[$i]=$tag;
758  }
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;';
766  $rating = pwg_db_fetch_assoc(pwg_query($query));
767  $rating['count'] = (int)$rating['count'];
768
769  //---------------------------------------------------------- related comments
770  $related_comments = array();
771
772  $where_comments = 'image_id = '.$image_row['id'];
773  if ( !is_admin() )
774  {
775    $where_comments .= '
776    AND validated="true"';
777  }
778
779  $query = '
780SELECT COUNT(id) AS nb_comments
781  FROM '.COMMENTS_TABLE.'
782  WHERE '.$where_comments;
783  list($nb_comments) = array_from_query($query, 'nb_comments');
784  $nb_comments = (int)$nb_comments;
785
786  if ( $nb_comments>0 and $params['comments_per_page']>0 )
787  {
788    $query = '
789SELECT id, date, author, content
790  FROM '.COMMENTS_TABLE.'
791  WHERE '.$where_comments.'
792  ORDER BY date
793  LIMIT '.(int)$params['comments_per_page'].
794    ' OFFSET '.(int)($params['comments_per_page']*$params['comments_page']);
795
796    $result = pwg_query($query);
797    while ($row = pwg_db_fetch_assoc($result))
798    {
799      $row['id']=(int)$row['id'];
800      array_push($related_comments, $row);
801    }
802  }
803
804  $comment_post_data = null;
805  if ($is_commentable and
806      (!is_a_guest()
807        or (is_a_guest() and $conf['comments_forall'] )
808      )
809      )
810  {
811    $comment_post_data['author'] = stripslashes($user['username']);
812    $comment_post_data['key'] = get_ephemeral_key(2, $params['image_id']);
813  }
814
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  }
827
828  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
829  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
830  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
831  if ( isset($comment_post_data) )
832  {
833    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
834  }
835  $ret['comments'] = array(
836     WS_XML_ATTRIBUTES =>
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') )
844      );
845
846  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
847}
848
849
850/**
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';
868  if ( pwg_db_num_rows( pwg_query($query) )==0 )
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/**
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');
893
894  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
895  $order_by = ws_std_image_sql_order($params, 'i.');
896
897  $super_order_by = false;
898  if ( !empty($order_by) )
899  {
900    global $conf;
901    $conf['order_by'] = 'ORDER BY '.$order_by;
902    $super_order_by=true; // quick_search_result might be faster
903  }
904
905  $search_result = get_quick_search_results($params['query'],
906      $super_order_by,
907      implode(',', $where_clauses)
908    );
909
910  $image_ids = array_slice(
911      $search_result['items'],
912      $params['page']*$params['per_page'],
913      $params['per_page']
914    );
915
916  if ( count($image_ids) )
917  {
918    $query = '
919SELECT * FROM '.IMAGES_TABLE.'
920  WHERE id IN ('.implode(',', $image_ids).')';
921
922    $image_ids = array_flip($image_ids);
923    $result = pwg_query($query);
924    while ($row = pwg_db_fetch_assoc($result))
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      }
934      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
935      {
936        $image[$k] = $row[$k];
937      }
938      $image = array_merge( $image, ws_std_get_urls($row) );
939      $images[$image_ids[$image['id']]] = $image;
940    }
941    ksort($images, SORT_NUMERIC);
942    $images = array_values($images);
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',
955          ws_std_get_image_xml_attributes() )
956      )
957    );
958}
959
960function ws_images_setPrivacyLevel($params, &$service)
961{
962  if (!is_admin())
963  {
964    return new PwgError(401, 'Access denied');
965  }
966  if (!$service->isPost())
967  {
968    return new PwgError(405, "This method requires HTTP POST");
969  }
970  $params['image_id'] = array_map( 'intval',$params['image_id'] );
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  }
980
981  $query = '
982UPDATE '.IMAGES_TABLE.'
983  SET level='.(int)$params['level'].'
984  WHERE id IN ('.implode(',',$params['image_id']).')';
985  $result = pwg_query($query);
986  $affected_rows = pwg_db_changes($result);
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
995function ws_images_add_chunk($params, &$service)
996{
997  global $conf;
998 
999  ws_logfile('[ws_images_add_chunk] welcome');
1000  // data
1001  // original_sum
1002  // type {thumb, file, high}
1003  // position
1004
1005  if (!is_admin())
1006  {
1007    return new PwgError(401, 'Access denied');
1008  }
1009
1010  if (!$service->isPost())
1011  {
1012    return new PwgError(405, "This method requires HTTP POST");
1013  }
1014
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
1029  $upload_dir = $conf['upload_dir'].'/buffer';
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
1061  ws_logfile('[ws_images_add_chunk] data length : '.strlen($params['data']));
1062
1063  $bytes_written = file_put_contents(
1064    $upload_dir.'/'.$filename,
1065    base64_decode($params['data'])
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{
1078  global $conf;
1079 
1080  ws_logfile('[merge_chunks] input parameter $output_filepath : '.$output_filepath);
1081
1082  if (is_file($output_filepath))
1083  {
1084    unlink($output_filepath);
1085
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  }
1092
1093  $upload_dir = $conf['upload_dir'].'/buffer';
1094  $pattern = '/'.$original_sum.'-'.$type.'/';
1095  $chunks = array();
1096
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);
1111
1112  if (function_exists('memory_get_usage')) {
1113    ws_logfile('[merge_chunks] memory_get_usage before loading chunks: '.memory_get_usage());
1114  }
1115
1116  $i = 0;
1117
1118  foreach ($chunks as $chunk)
1119  {
1120    $string = file_get_contents($chunk);
1121
1122    if (function_exists('memory_get_usage')) {
1123      ws_logfile('[merge_chunks] memory_get_usage on chunk '.++$i.': '.memory_get_usage());
1124    }
1125
1126    if (!file_put_contents($output_filepath, $string, FILE_APPEND))
1127    {
1128      new PwgError(500, '[merge_chunks] error while writting chunks for '.$output_filepath);
1129      exit();
1130    }
1131
1132    unlink($chunk);
1133  }
1134
1135  if (function_exists('memory_get_usage')) {
1136    ws_logfile('[merge_chunks] memory_get_usage after loading chunks: '.memory_get_usage());
1137  }
1138}
1139
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{
1146  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1147 
1148  $file_path = file_path_for_type($file_path, $type);
1149
1150  $upload_dir = dirname($file_path);
1151  if (substr(PHP_OS, 0, 3) == 'WIN')
1152  {
1153    $upload_dir = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir);
1154  }
1155
1156  ws_logfile('[add_file] file_path  : '.$file_path);
1157  ws_logfile('[add_file] upload_dir : '.$upload_dir);
1158 
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
1204function ws_images_addFile($params, &$service)
1205{
1206  // image_id
1207  // type {thumb, file, high}
1208  // sum
1209
1210  global $conf;
1211  if (!is_admin())
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;';
1232  list($file_path, $original_sum) = pwg_db_fetch_row(pwg_query($query));
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();
1245
1246  if ('high' == $params['type'])
1247  {
1248    $update['high_filesize'] = $infos['filesize'];
1249    $update['high_width'] = $infos['width'];
1250    $update['high_height'] = $infos['height'];
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'];
1266
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
1279function ws_images_add($params, &$service)
1280{
1281  global $conf, $user;
1282  if (!is_admin())
1283  {
1284    return new PwgError(401, 'Access denied');
1285  }
1286
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  }
1296
1297  // does the image already exists ?
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 
1307  $query = '
1308SELECT
1309    COUNT(*) AS counter
1310  FROM '.IMAGES_TABLE.'
1311  WHERE '.$where_clause.'
1312;';
1313  list($counter) = pwg_db_fetch_row(pwg_query($query));
1314  if ($counter != 0) {
1315    return new PwgError(500, 'file already exists');
1316  }
1317
1318  // current date
1319  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1320  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
1321
1322  // upload directory hierarchy
1323  $upload_dir = sprintf(
1324    $conf['upload_dir'].'/%s/%s/%s',
1325    $year,
1326    $month,
1327    $day
1328    );
1329
1330  // compute file path
1331  $date_string = preg_replace('/[^\d]/', '', $dbnow);
1332  $random_string = substr($params['file_sum'], 0, 8);
1333  $filename_wo_ext = $date_string.'-'.$random_string;
1334  $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
1335
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']);
1339
1340  if (isset($params['high_sum']))
1341  {
1342    $high_infos = add_file($file_path, 'high', $params['original_sum'], $params['high_sum']);
1343  }
1344
1345  // database registration
1346  $insert = array(
1347    'file' => !empty($params['original_filename']) ? $params['original_filename'] : $filename_wo_ext.'.jpg',
1348    'date_available' => $dbnow,
1349    'tn_ext' => 'jpg',
1350    'name' => $params['name'],
1351    'path' => $file_path,
1352    'filesize' => $file_infos['filesize'],
1353    'width' => $file_infos['width'],
1354    'height' => $file_infos['height'],
1355    'md5sum' => $params['original_sum'],
1356    'added_by' => $user['id'],
1357    );
1358
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
1375  if (isset($params['high_sum']))
1376  {
1377    $insert['has_high'] = 'true';
1378    $insert['high_filesize'] = $high_infos['filesize'];
1379    $insert['high_width'] = $high_infos['width'];
1380    $insert['high_height'] = $high_infos['height'];
1381  }
1382
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
1390  $image_id = pwg_db_insert_id(IMAGES_TABLE);
1391
1392  // let's add links between the image and the categories
1393  if (isset($params['categories']))
1394  {
1395    ws_add_image_category_relations($image_id, $params['categories']);
1396  }
1397
1398  // and now, let's create tag associations
1399  if (isset($params['tag_ids']) and !empty($params['tag_ids']))
1400  {
1401    set_tags(
1402      explode(',', $params['tag_ids']),
1403      $image_id
1404      );
1405  }
1406
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 
1411  invalidate_user_cache();
1412}
1413
1414function ws_images_addSimple($params, &$service)
1415{
1416  global $conf;
1417  if (!is_admin())
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  }
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');
1431
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
1445  // category
1446  $params['category'] = (int)$params['category'];
1447  if ($params['category'] <= 0 and $params['image_id'] <= 0)
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
1454  $image_id = add_uploaded_file(
1455    $_FILES['image']['tmp_name'],
1456    $_FILES['image']['name'],
1457    $params['category'] > 0 ? array($params['category']) : null,
1458    8,
1459    $params['image_id'] > 0 ? $params['image_id'] : null
1460    );
1461
1462  $info_columns = array(
1463    'name',
1464    'author',
1465    'comment',
1466    'level',
1467    'date_creation',
1468    );
1469
1470  foreach ($info_columns as $key)
1471  {
1472    if (isset($params[$key]))
1473    {
1474      $update[$key] = $params[$key];
1475    }
1476  }
1477
1478  if (count(array_keys($update)) > 0)
1479  {
1480    $update['id'] = $image_id;
1481
1482    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1483    mass_updates(
1484      IMAGES_TABLE,
1485      array(
1486        'primary' => array('id'),
1487        'update'  => array_diff(array_keys($update), array('id'))
1488        ),
1489      array($update)
1490      );
1491  }
1492
1493
1494  if (isset($params['tags']) and !empty($params['tags']))
1495  {
1496    $tag_ids = array();
1497    $tag_names = explode(',', $params['tags']);
1498    foreach ($tag_names as $tag_name)
1499    {
1500      $tag_id = tag_id_from_tag_name($tag_name);
1501      array_push($tag_ids, $tag_id);
1502    }
1503
1504    add_tags($tag_ids, array($image_id));
1505  }
1506
1507  $url_params = array('image_id' => $image_id);
1508
1509  if ($params['category'] > 0)
1510  {
1511    $query = '
1512SELECT id, name, permalink
1513  FROM '.CATEGORIES_TABLE.'
1514  WHERE id = '.$params['category'].'
1515;';
1516    $result = pwg_query($query);
1517    $category = pwg_db_fetch_assoc($result);
1518
1519    $url_params['section'] = 'categories';
1520    $url_params['category'] = $category;
1521  }
1522
1523  // update metadata from the uploaded file (exif/iptc), even if the sync
1524  // was already performed by add_uploaded_file().
1525  $query = '
1526SELECT
1527    path
1528  FROM '.IMAGES_TABLE.'
1529  WHERE id = '.$image_id.'
1530;';
1531  list($file_path) = pwg_db_fetch_row(pwg_query($query));
1532 
1533  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1534  update_metadata(array($image_id=>$file_path));
1535
1536  return array(
1537    'image_id' => $image_id,
1538    'url' => make_picture_url($url_params),
1539    );
1540}
1541
1542/**
1543 * perform a login (web service method)
1544 */
1545function ws_session_login($params, &$service)
1546{
1547  global $conf;
1548
1549  if (!$service->isPost())
1550  {
1551    return new PwgError(405, "This method requires HTTP POST");
1552  }
1553  if (try_log_user($params['username'], $params['password'],false))
1554  {
1555    return true;
1556  }
1557  return new PwgError(999, 'Invalid username/password');
1558}
1559
1560
1561/**
1562 * performs a logout (web service method)
1563 */
1564function ws_session_logout($params, &$service)
1565{
1566  if (!is_a_guest())
1567  {
1568    logout_user();
1569  }
1570  return true;
1571}
1572
1573function ws_session_getStatus($params, &$service)
1574{
1575  global $user;
1576  $res = array();
1577  $res['username'] = is_a_guest() ? 'guest' : stripslashes($user['username']);
1578  foreach ( array('status', 'theme', 'language') as $k )
1579  {
1580    $res[$k] = $user[$k];
1581  }
1582  $res['pwg_token'] = get_pwg_token();
1583  $res['charset'] = get_pwg_charset();
1584  return $res;
1585}
1586
1587
1588/**
1589 * returns a list of tags (web service method)
1590 */
1591function ws_tags_getList($params, &$service)
1592{
1593  $tags = get_available_tags();
1594  if ($params['sort_by_counter'])
1595  {
1596    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1597  }
1598  else
1599  {
1600    usort($tags, 'tag_alpha_compare');
1601  }
1602  for ($i=0; $i<count($tags); $i++)
1603  {
1604    $tags[$i]['id'] = (int)$tags[$i]['id'];
1605    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1606    $tags[$i]['url'] = make_index_url(
1607        array(
1608          'section'=>'tags',
1609          'tags'=>array($tags[$i])
1610        )
1611      );
1612  }
1613  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
1614}
1615
1616/**
1617 * returns the list of tags as you can see them in administration (web
1618 * service method).
1619 *
1620 * Only admin can run this method and permissions are not taken into
1621 * account.
1622 */
1623function ws_tags_getAdminList($params, &$service)
1624{
1625  if (!is_admin())
1626  {
1627    return new PwgError(401, 'Access denied');
1628  }
1629
1630  $tags = get_all_tags();
1631  return array(
1632    'tags' => new PwgNamedArray(
1633      $tags,
1634      'tag',
1635      array(
1636        'name',
1637        'id',
1638        'url_name',
1639        )
1640      )
1641    );
1642}
1643
1644/**
1645 * returns a list of images for tags (web service method)
1646 */
1647function ws_tags_getImages($params, &$service)
1648{
1649  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1650  global $conf;
1651
1652  // first build all the tag_ids we are interested in
1653  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1654  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1655  $tags_by_id = array();
1656  foreach( $tags as $tag )
1657  {
1658    $tags['id'] = (int)$tag['id'];
1659    $tags_by_id[ $tag['id'] ] = $tag;
1660  }
1661  unset($tags);
1662  $tag_ids = array_keys($tags_by_id);
1663
1664
1665  $where_clauses = ws_std_image_sql_filter($params);
1666  if (!empty($where_clauses))
1667  {
1668    $where_clauses = implode( ' AND ', $where_clauses);
1669  }
1670  $image_ids = get_image_ids_for_tags(
1671    $tag_ids,
1672    $params['tag_mode_and'] ? 'AND' : 'OR',
1673    $where_clauses,
1674    ws_std_image_sql_order($params) );
1675
1676
1677  $image_ids = array_slice($image_ids, (int)($params['per_page']*$params['page']), (int)$params['per_page'] );
1678 
1679  $image_tag_map = array();
1680  if ( !empty($image_ids) and !$params['tag_mode_and'] )
1681  { // build list of image ids with associated tags per image
1682    $query = '
1683SELECT image_id, GROUP_CONCAT(tag_id) AS tag_ids
1684  FROM '.IMAGE_TAG_TABLE.'
1685  WHERE tag_id IN ('.implode(',',$tag_ids).') AND image_id IN ('.implode(',',$image_ids).')
1686  GROUP BY image_id';
1687    $result = pwg_query($query);
1688    while ( $row=pwg_db_fetch_assoc($result) )
1689    {
1690      $row['image_id'] = (int)$row['image_id'];
1691      array_push( $image_ids, $row['image_id'] );
1692      $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1693    }
1694  }
1695
1696  $images = array();
1697  if (!empty($image_ids))
1698  {
1699    $rank_of = array_flip($image_ids);
1700    $result = pwg_query('
1701SELECT * FROM '.IMAGES_TABLE.'
1702  WHERE id IN ('.implode(',',$image_ids).')');
1703    while ($row = pwg_db_fetch_assoc($result))
1704    {
1705      $image = array();
1706      $image['rank'] = $rank_of[ $row['id'] ];
1707      foreach ( array('id', 'width', 'height', 'hit') as $k )
1708      {
1709        if (isset($row[$k]))
1710        {
1711          $image[$k] = (int)$row[$k];
1712        }
1713      }
1714      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
1715      {
1716        $image[$k] = $row[$k];
1717      }
1718      $image = array_merge( $image, ws_std_get_urls($row) );
1719
1720      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1721      $image_tags = array();
1722      foreach ($image_tag_ids as $tag_id)
1723      {
1724        $url = make_index_url(
1725                 array(
1726                  'section'=>'tags',
1727                  'tags'=> array($tags_by_id[$tag_id])
1728                )
1729              );
1730        $page_url = make_picture_url(
1731                 array(
1732                  'section'=>'tags',
1733                  'tags'=> array($tags_by_id[$tag_id]),
1734                  'image_id' => $row['id'],
1735                  'image_file' => $row['file'],
1736                )
1737              );
1738        array_push($image_tags, array(
1739                'id' => (int)$tag_id,
1740                'url' => $url,
1741                'page_url' => $page_url,
1742              )
1743            );
1744      }
1745      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1746              array('id','url_name','url','page_url')
1747            );
1748      array_push($images, $image);
1749    }
1750    usort($images, 'rank_compare');
1751    unset($rank_of);
1752  }
1753
1754  return array( 'images' =>
1755    array (
1756      WS_XML_ATTRIBUTES =>
1757        array(
1758            'page' => $params['page'],
1759            'per_page' => $params['per_page'],
1760            'count' => count($images)
1761          ),
1762       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1763          ws_std_get_image_xml_attributes() )
1764      )
1765    );
1766}
1767
1768function ws_categories_add($params, &$service)
1769{
1770  if (!is_admin())
1771  {
1772    return new PwgError(401, 'Access denied');
1773  }
1774
1775  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1776
1777  $creation_output = create_virtual_category(
1778    $params['name'],
1779    $params['parent']
1780    );
1781
1782  if (isset($creation_output['error']))
1783  {
1784    return new PwgError(500, $creation_output['error']);
1785  }
1786
1787  invalidate_user_cache();
1788
1789  return $creation_output;
1790}
1791
1792function ws_tags_add($params, &$service)
1793{
1794  if (!is_admin())
1795  {
1796    return new PwgError(401, 'Access denied');
1797  }
1798
1799  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1800
1801  $creation_output = create_tag($params['name']);
1802
1803  if (isset($creation_output['error']))
1804  {
1805    return new PwgError(500, $creation_output['error']);
1806  }
1807
1808  return $creation_output;
1809}
1810
1811function ws_images_exist($params, &$service)
1812{
1813  global $conf;
1814 
1815  if (!is_admin())
1816  {
1817    return new PwgError(401, 'Access denied');
1818  }
1819
1820  $split_pattern = '/[\s,;\|]/';
1821
1822  if ('md5sum' == $conf['uniqueness_mode'])
1823  {
1824    // search among photos the list of photos already added, based on md5sum
1825    // list
1826    $md5sums = preg_split(
1827      $split_pattern,
1828      $params['md5sum_list'],
1829      -1,
1830      PREG_SPLIT_NO_EMPTY
1831    );
1832
1833    $query = '
1834SELECT
1835    id,
1836    md5sum
1837  FROM '.IMAGES_TABLE.'
1838  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
1839;';
1840    $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
1841
1842    $result = array();
1843
1844    foreach ($md5sums as $md5sum)
1845    {
1846      $result[$md5sum] = null;
1847      if (isset($id_of_md5[$md5sum]))
1848      {
1849        $result[$md5sum] = $id_of_md5[$md5sum];
1850      }
1851    }
1852  }
1853 
1854  if ('filename' == $conf['uniqueness_mode'])
1855  {
1856    // search among photos the list of photos already added, based on
1857    // filename list
1858    $filenames = preg_split(
1859      $split_pattern,
1860      $params['filename_list'],
1861      -1,
1862      PREG_SPLIT_NO_EMPTY
1863    );
1864
1865    $query = '
1866SELECT
1867    id,
1868    file
1869  FROM '.IMAGES_TABLE.'
1870  WHERE file IN (\''.implode("','", $filenames).'\')
1871;';
1872    $id_of_filename = simple_hash_from_query($query, 'file', 'id');
1873
1874    $result = array();
1875
1876    foreach ($filenames as $filename)
1877    {
1878      $result[$filename] = null;
1879      if (isset($id_of_filename[$filename]))
1880      {
1881        $result[$filename] = $id_of_filename[$filename];
1882      }
1883    }
1884  }
1885
1886  return $result;
1887}
1888
1889function ws_images_checkFiles($params, &$service)
1890{
1891  if (!is_admin())
1892  {
1893    return new PwgError(401, 'Access denied');
1894  }
1895
1896  // input parameters
1897  //
1898  // image_id
1899  // thumbnail_sum
1900  // file_sum
1901  // high_sum
1902
1903  $params['image_id'] = (int)$params['image_id'];
1904  if ($params['image_id'] <= 0)
1905  {
1906    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1907  }
1908
1909  $query = '
1910SELECT
1911    path
1912  FROM '.IMAGES_TABLE.'
1913  WHERE id = '.$params['image_id'].'
1914;';
1915  $result = pwg_query($query);
1916  if (pwg_db_num_rows($result) == 0) {
1917    return new PwgError(404, "image_id not found");
1918  }
1919  list($path) = pwg_db_fetch_row($result);
1920
1921  $ret = array();
1922
1923  foreach (array('thumb', 'file', 'high') as $type) {
1924    $param_name = $type;
1925    if ('thumb' == $type) {
1926      $param_name = 'thumbnail';
1927    }
1928
1929    if (isset($params[$param_name.'_sum'])) {
1930      include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1931      $type_path = file_path_for_type($path, $type);
1932      if (!is_file($type_path)) {
1933        $ret[$param_name] = 'missing';
1934      }
1935      else {
1936        if (md5_file($type_path) != $params[$param_name.'_sum']) {
1937          $ret[$param_name] = 'differs';
1938        }
1939        else {
1940          $ret[$param_name] = 'equals';
1941        }
1942      }
1943    }
1944  }
1945
1946  return $ret;
1947}
1948
1949function ws_images_setInfo($params, &$service)
1950{
1951  global $conf;
1952  if (!is_admin())
1953  {
1954    return new PwgError(401, 'Access denied');
1955  }
1956
1957  if (!$service->isPost())
1958  {
1959    return new PwgError(405, "This method requires HTTP POST");
1960  }
1961
1962  $params['image_id'] = (int)$params['image_id'];
1963  if ($params['image_id'] <= 0)
1964  {
1965    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1966  }
1967
1968  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1969
1970  $query='
1971SELECT *
1972  FROM '.IMAGES_TABLE.'
1973  WHERE id = '.$params['image_id'].'
1974;';
1975
1976  $image_row = pwg_db_fetch_assoc(pwg_query($query));
1977  if ($image_row == null)
1978  {
1979    return new PwgError(404, "image_id not found");
1980  }
1981
1982  // database registration
1983  $update = array();
1984
1985  $info_columns = array(
1986    'name',
1987    'author',
1988    'comment',
1989    'level',
1990    'date_creation',
1991    );
1992
1993  foreach ($info_columns as $key)
1994  {
1995    if (isset($params[$key]))
1996    {
1997      if ('fill_if_empty' == $params['single_value_mode'])
1998      {
1999        if (empty($image_row[$key]))
2000        {
2001          $update[$key] = $params[$key];
2002        }
2003      }
2004      elseif ('replace' == $params['single_value_mode'])
2005      {
2006        $update[$key] = $params[$key];
2007      }
2008      else
2009      {
2010        new PwgError(
2011          500,
2012          '[ws_images_setInfo]'
2013          .' invalid parameter single_value_mode "'.$params['single_value_mode'].'"'
2014          .', possible values are {fill_if_empty, replace}.'
2015          );
2016        exit();
2017      }
2018    }
2019  }
2020
2021  if (count(array_keys($update)) > 0)
2022  {
2023    $update['id'] = $params['image_id'];
2024
2025    mass_updates(
2026      IMAGES_TABLE,
2027      array(
2028        'primary' => array('id'),
2029        'update'  => array_diff(array_keys($update), array('id'))
2030        ),
2031      array($update)
2032      );
2033  }
2034
2035  if (isset($params['categories']))
2036  {
2037    ws_add_image_category_relations(
2038      $params['image_id'],
2039      $params['categories'],
2040      ('replace' == $params['multiple_value_mode'] ? true : false)
2041      );
2042  }
2043
2044  // and now, let's create tag associations
2045  if (isset($params['tag_ids']))
2046  {
2047    $tag_ids = explode(',', $params['tag_ids']);
2048
2049    if ('replace' == $params['multiple_value_mode'])
2050    {
2051      set_tags(
2052        $tag_ids,
2053        $params['image_id']
2054        );
2055    }
2056    elseif ('append' == $params['multiple_value_mode'])
2057    {
2058      add_tags(
2059        $tag_ids,
2060        array($params['image_id'])
2061        );
2062    }
2063    else
2064    {
2065      new PwgError(
2066        500,
2067        '[ws_images_setInfo]'
2068        .' invalid parameter multiple_value_mode "'.$params['multiple_value_mode'].'"'
2069        .', possible values are {replace, append}.'
2070        );
2071      exit();
2072    }
2073  }
2074
2075  invalidate_user_cache();
2076}
2077
2078function ws_images_delete($params, &$service)
2079{
2080  global $conf;
2081  if (!is_admin())
2082  {
2083    return new PwgError(401, 'Access denied');
2084  }
2085
2086  if (!$service->isPost())
2087  {
2088    return new PwgError(405, "This method requires HTTP POST");
2089  }
2090
2091  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2092  {
2093    return new PwgError(403, 'Invalid security token');
2094  }
2095
2096  $params['image_id'] = preg_split(
2097    '/[\s,;\|]/',
2098    $params['image_id'],
2099    -1,
2100    PREG_SPLIT_NO_EMPTY
2101    );
2102  $params['image_id'] = array_map('intval', $params['image_id']);
2103
2104  $image_ids = array();
2105  foreach ($params['image_id'] as $image_id)
2106  {
2107    if ($image_id > 0)
2108    {
2109      array_push($image_ids, $image_id);
2110    }
2111  }
2112
2113  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2114  delete_elements($image_ids, true);
2115}
2116
2117function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
2118{
2119  // let's add links between the image and the categories
2120  //
2121  // $params['categories'] should look like 123,12;456,auto;789 which means:
2122  //
2123  // 1. associate with category 123 on rank 12
2124  // 2. associate with category 456 on automatic rank
2125  // 3. associate with category 789 on automatic rank
2126  $cat_ids = array();
2127  $rank_on_category = array();
2128  $search_current_ranks = false;
2129
2130  $tokens = explode(';', $categories_string);
2131  foreach ($tokens as $token)
2132  {
2133    @list($cat_id, $rank) = explode(',', $token);
2134
2135    if (!preg_match('/^\d+$/', $cat_id))
2136    {
2137      continue;
2138    }
2139
2140    array_push($cat_ids, $cat_id);
2141
2142    if (!isset($rank))
2143    {
2144      $rank = 'auto';
2145    }
2146    $rank_on_category[$cat_id] = $rank;
2147
2148    if ($rank == 'auto')
2149    {
2150      $search_current_ranks = true;
2151    }
2152  }
2153
2154  $cat_ids = array_unique($cat_ids);
2155
2156  if (count($cat_ids) == 0)
2157  {
2158    new PwgError(
2159      500,
2160      '[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
2161      );
2162    exit();
2163  }
2164
2165  $query = '
2166SELECT
2167    id
2168  FROM '.CATEGORIES_TABLE.'
2169  WHERE id IN ('.implode(',', $cat_ids).')
2170;';
2171  $db_cat_ids = array_from_query($query, 'id');
2172
2173  $unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
2174  if (count($unknown_cat_ids) != 0)
2175  {
2176    new PwgError(
2177      500,
2178      '[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
2179      );
2180    exit();
2181  }
2182
2183  $to_update_cat_ids = array();
2184
2185  // in case of replace mode, we first check the existing associations
2186  $query = '
2187SELECT
2188    category_id
2189  FROM '.IMAGE_CATEGORY_TABLE.'
2190  WHERE image_id = '.$image_id.'
2191;';
2192  $existing_cat_ids = array_from_query($query, 'category_id');
2193
2194  if ($replace_mode)
2195  {
2196    $to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
2197    if (count($to_remove_cat_ids) > 0)
2198    {
2199      $query = '
2200DELETE
2201  FROM '.IMAGE_CATEGORY_TABLE.'
2202  WHERE image_id = '.$image_id.'
2203    AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
2204;';
2205      pwg_query($query);
2206      update_category($to_remove_cat_ids);
2207    }
2208  }
2209
2210  $new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
2211  if (count($new_cat_ids) == 0)
2212  {
2213    return true;
2214  }
2215
2216  if ($search_current_ranks)
2217  {
2218    $query = '
2219SELECT
2220    category_id,
2221    MAX(rank) AS max_rank
2222  FROM '.IMAGE_CATEGORY_TABLE.'
2223  WHERE rank IS NOT NULL
2224    AND category_id IN ('.implode(',', $new_cat_ids).')
2225  GROUP BY category_id
2226;';
2227    $current_rank_of = simple_hash_from_query(
2228      $query,
2229      'category_id',
2230      'max_rank'
2231      );
2232
2233    foreach ($new_cat_ids as $cat_id)
2234    {
2235      if (!isset($current_rank_of[$cat_id]))
2236      {
2237        $current_rank_of[$cat_id] = 0;
2238      }
2239
2240      if ('auto' == $rank_on_category[$cat_id])
2241      {
2242        $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
2243      }
2244    }
2245  }
2246
2247  $inserts = array();
2248
2249  foreach ($new_cat_ids as $cat_id)
2250  {
2251    array_push(
2252      $inserts,
2253      array(
2254        'image_id' => $image_id,
2255        'category_id' => $cat_id,
2256        'rank' => $rank_on_category[$cat_id],
2257        )
2258      );
2259  }
2260
2261  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2262  mass_inserts(
2263    IMAGE_CATEGORY_TABLE,
2264    array_keys($inserts[0]),
2265    $inserts
2266    );
2267
2268  update_category($new_cat_ids);
2269}
2270
2271function ws_categories_setInfo($params, &$service)
2272{
2273  global $conf;
2274  if (!is_admin())
2275  {
2276    return new PwgError(401, 'Access denied');
2277  }
2278
2279  if (!$service->isPost())
2280  {
2281    return new PwgError(405, "This method requires HTTP POST");
2282  }
2283
2284  // category_id
2285  // name
2286  // comment
2287
2288  $params['category_id'] = (int)$params['category_id'];
2289  if ($params['category_id'] <= 0)
2290  {
2291    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2292  }
2293
2294  // database registration
2295  $update = array(
2296    'id' => $params['category_id'],
2297    );
2298
2299  $info_columns = array(
2300    'name',
2301    'comment',
2302    );
2303
2304  $perform_update = false;
2305  foreach ($info_columns as $key)
2306  {
2307    if (isset($params[$key]))
2308    {
2309      $perform_update = true;
2310      $update[$key] = $params[$key];
2311    }
2312  }
2313
2314  if ($perform_update)
2315  {
2316    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2317    mass_updates(
2318      CATEGORIES_TABLE,
2319      array(
2320        'primary' => array('id'),
2321        'update'  => array_diff(array_keys($update), array('id'))
2322        ),
2323      array($update)
2324      );
2325  }
2326
2327}
2328
2329function ws_categories_delete($params, &$service)
2330{
2331  global $conf;
2332  if (!is_admin())
2333  {
2334    return new PwgError(401, 'Access denied');
2335  }
2336
2337  if (!$service->isPost())
2338  {
2339    return new PwgError(405, "This method requires HTTP POST");
2340  }
2341
2342  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2343  {
2344    return new PwgError(403, 'Invalid security token');
2345  }
2346
2347  $modes = array('no_delete', 'delete_orphans', 'force_delete');
2348  if (!in_array($params['photo_deletion_mode'], $modes))
2349  {
2350    return new PwgError(
2351      500,
2352      '[ws_categories_delete]'
2353      .' invalid parameter photo_deletion_mode "'.$params['photo_deletion_mode'].'"'
2354      .', possible values are {'.implode(', ', $modes).'}.'
2355      );
2356  }
2357
2358  $params['category_id'] = preg_split(
2359    '/[\s,;\|]/',
2360    $params['category_id'],
2361    -1,
2362    PREG_SPLIT_NO_EMPTY
2363    );
2364  $params['category_id'] = array_map('intval', $params['category_id']);
2365
2366  $category_ids = array();
2367  foreach ($params['category_id'] as $category_id)
2368  {
2369    if ($category_id > 0)
2370    {
2371      array_push($category_ids, $category_id);
2372    }
2373  }
2374
2375  if (count($category_ids) == 0)
2376  {
2377    return;
2378  }
2379
2380  $query = '
2381SELECT id
2382  FROM '.CATEGORIES_TABLE.'
2383  WHERE id IN ('.implode(',', $category_ids).')
2384;';
2385  $category_ids = array_from_query($query, 'id');
2386
2387  if (count($category_ids) == 0)
2388  {
2389    return;
2390  }
2391 
2392  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2393  delete_categories($category_ids, $params['photo_deletion_mode']);
2394  update_global_rank();
2395}
2396
2397function ws_categories_move($params, &$service)
2398{
2399  global $conf, $page;
2400 
2401  if (!is_admin())
2402  {
2403    return new PwgError(401, 'Access denied');
2404  }
2405
2406  if (!$service->isPost())
2407  {
2408    return new PwgError(405, "This method requires HTTP POST");
2409  }
2410
2411  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2412  {
2413    return new PwgError(403, 'Invalid security token');
2414  }
2415
2416  $params['category_id'] = preg_split(
2417    '/[\s,;\|]/',
2418    $params['category_id'],
2419    -1,
2420    PREG_SPLIT_NO_EMPTY
2421    );
2422  $params['category_id'] = array_map('intval', $params['category_id']);
2423
2424  $category_ids = array();
2425  foreach ($params['category_id'] as $category_id)
2426  {
2427    if ($category_id > 0)
2428    {
2429      array_push($category_ids, $category_id);
2430    }
2431  }
2432
2433  if (count($category_ids) == 0)
2434  {
2435    return new PwgError(403, 'Invalid category_id input parameter, no category to move');
2436  }
2437
2438  // we can't move physical categories
2439  $categories_in_db = array();
2440 
2441  $query = '
2442SELECT
2443    id,
2444    name,
2445    dir
2446  FROM '.CATEGORIES_TABLE.'
2447  WHERE id IN ('.implode(',', $category_ids).')
2448;';
2449  $result = pwg_query($query);
2450  while ($row = pwg_db_fetch_assoc($result))
2451  {
2452    $categories_in_db[$row['id']] = $row;
2453    // we break on error at first physical category detected
2454    if (!empty($row['dir']))
2455    {
2456      $row['name'] = strip_tags(
2457        trigger_event(
2458          'render_category_name',
2459          $row['name'],
2460          'ws_categories_move'
2461          )
2462        );
2463     
2464      return new PwgError(
2465        403,
2466        sprintf(
2467          'Category %s (%u) is not a virtual category, you cannot move it',
2468          $row['name'],
2469          $row['id']
2470          )
2471        );
2472    }
2473  }
2474
2475  if (count($categories_in_db) != count($category_ids))
2476  {
2477    $unknown_category_ids = array_diff($category_ids, array_keys($categories_in_db));
2478   
2479    return new PwgError(
2480      403,
2481      sprintf(
2482        'Category %u does not exist',
2483        $unknown_category_ids[0]
2484        )
2485      );
2486  }
2487
2488  // does this parent exists? This check should be made in the
2489  // move_categories function, not here
2490  //
2491  // 0 as parent means "move categories at gallery root"
2492  if (!is_numeric($params['parent']))
2493  {
2494    return new PwgError(403, 'Invalid parent input parameter');
2495  }
2496 
2497  if (0 != $params['parent']) {
2498    $params['parent'] = intval($params['parent']);
2499    $subcat_ids = get_subcat_ids(array($params['parent']));
2500    if (count($subcat_ids) == 0)
2501    {
2502      return new PwgError(403, 'Unknown parent category id');
2503    }
2504  }
2505
2506  $page['infos'] = array();
2507  $page['errors'] = array();
2508  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2509  move_categories($category_ids, $params['parent']);
2510  invalidate_user_cache();
2511
2512  if (count($page['errors']) != 0)
2513  {
2514    return new PwgError(403, implode('; ', $page['errors']));
2515  }
2516}
2517
2518function ws_logfile($string)
2519{
2520  global $conf;
2521
2522  if (!$conf['ws_enable_log']) {
2523    return true;
2524  }
2525
2526  file_put_contents(
2527    $conf['ws_log_filepath'],
2528    '['.date('c').'] '.$string."\n",
2529    FILE_APPEND
2530    );
2531}
2532
2533function ws_images_checkUpload($params, &$service)
2534{
2535  global $conf;
2536
2537  if (!is_admin())
2538  {
2539    return new PwgError(401, 'Access denied');
2540  }
2541
2542  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
2543  $ret['message'] = ready_for_upload_message();
2544  $ret['ready_for_upload'] = true;
2545 
2546  if (!empty($ret['message']))
2547  {
2548    $ret['ready_for_upload'] = false;
2549  }
2550 
2551  return $ret;
2552}
2553
2554function ws_plugins_getList($params, &$service)
2555{
2556  global $conf;
2557 
2558  if (!is_admin())
2559  {
2560    return new PwgError(401, 'Access denied');
2561  }
2562
2563  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
2564  $plugins = new plugins();
2565  $plugins->sort_fs_plugins('name');
2566  $plugin_list = array();
2567
2568  foreach($plugins->fs_plugins as $plugin_id => $fs_plugin)
2569  {
2570    if (isset($plugins->db_plugins_by_id[$plugin_id]))
2571    {
2572      $state = $plugins->db_plugins_by_id[$plugin_id]['state'];
2573    }
2574    else
2575    {
2576      $state = 'uninstalled';
2577    }
2578
2579    array_push(
2580      $plugin_list,
2581      array(
2582        'id' => $plugin_id,
2583        'name' => $fs_plugin['name'],
2584        'version' => $fs_plugin['version'],
2585        'state' => $state,
2586        'description' => $fs_plugin['description'],
2587        )
2588      );
2589  }
2590
2591  return $plugin_list;
2592}
2593
2594function ws_plugins_performAction($params, &$service)
2595{
2596  global $template;
2597 
2598  if (!is_admin())
2599  {
2600    return new PwgError(401, 'Access denied');
2601  }
2602
2603  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2604  {
2605    return new PwgError(403, 'Invalid security token');
2606  }
2607
2608  define('IN_ADMIN', true);
2609  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
2610  $plugins = new plugins();
2611  $errors = $plugins->perform_action($params['action'], $params['plugin']);
2612
2613 
2614  if (!empty($errors))
2615  {
2616    return new PwgError(500, $errors);
2617  }
2618  else
2619  {
2620    if (in_array($params['action'], array('activate', 'deactivate')))
2621    {
2622      $template->delete_compiled_templates();
2623    }
2624    return true;
2625  }
2626}
2627
2628function ws_themes_performAction($params, &$service)
2629{
2630  global $template;
2631 
2632  if (!is_admin())
2633  {
2634    return new PwgError(401, 'Access denied');
2635  }
2636
2637  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2638  {
2639    return new PwgError(403, 'Invalid security token');
2640  }
2641
2642  define('IN_ADMIN', true);
2643  include_once(PHPWG_ROOT_PATH.'admin/include/themes.class.php');
2644  $themes = new themes();
2645  $errors = $themes->perform_action($params['action'], $params['theme']);
2646 
2647  if (!empty($errors))
2648  {
2649    return new PwgError(500, $errors);
2650  }
2651  else
2652  {
2653    if (in_array($params['action'], array('activate', 'deactivate')))
2654    {
2655      $template->delete_compiled_templates();
2656    }
2657    return true;
2658  }
2659}
2660
2661function ws_images_resizethumbnail($params, &$service)
2662{
2663  if (!is_admin())
2664  {
2665    return new PwgError(401, 'Access denied');
2666  }
2667
2668  if (empty($params['image_id']) and empty($params['image_path']))
2669  {
2670    return new PwgError(403, "image_id or image_path is missing");
2671  }
2672
2673  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
2674  include_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
2675
2676  if (!empty($params['image_id']))
2677  {
2678    $query='
2679SELECT id, path, tn_ext, has_high
2680  FROM '.IMAGES_TABLE.'
2681  WHERE id = '.(int)$params['image_id'].'
2682;';
2683    $image = pwg_db_fetch_assoc(pwg_query($query));
2684
2685    if ($image == null)
2686    {
2687      return new PwgError(403, "image_id not found");
2688    }
2689
2690    $image_path = $image['path'];
2691    $thumb_path = get_thumbnail_path($image);
2692  }
2693  else
2694  {
2695    $image_path = $params['image_path'];
2696    $thumb_path = file_path_for_type($image_path, 'thumb');
2697  }
2698
2699  if (!file_exists($image_path) or !is_valid_image_extension(get_extension($image_path)))
2700  {
2701    return new PwgError(403, "image can't be resized");
2702  }
2703
2704  $result = false;
2705  prepare_directory(dirname($thumb_path));
2706  $img = new pwg_image($image_path, $params['library']);
2707
2708  $result =  $img->pwg_resize(
2709    $thumb_path,
2710    $params['maxwidth'],
2711    $params['maxheight'],
2712    $params['quality'],
2713    false, // automatic rotation is not needed for thumbnails.
2714    true, // strip metadata
2715    get_boolean($params['crop']),
2716    get_boolean($params['follow_orientation'])
2717  );
2718
2719  $img->destroy();
2720  return $result;
2721}
2722
2723function ws_images_resizewebsize($params, &$service)
2724{
2725  if (!is_admin())
2726  {
2727    return new PwgError(401, 'Access denied');
2728  }
2729
2730  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
2731  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
2732  include_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
2733
2734  $query='
2735SELECT id, path, tn_ext, has_high
2736  FROM '.IMAGES_TABLE.'
2737  WHERE id = '.(int)$params['image_id'].'
2738;';
2739  $image = pwg_db_fetch_assoc(pwg_query($query));
2740
2741  if ($image == null)
2742  {
2743    return new PwgError(403, "image_id not found");
2744  }
2745
2746  $image_path = $image['path'];
2747  $hd_path = get_high_path($image);
2748
2749  if (empty($image['has_high']) or !file_exists($hd_path) or !is_valid_image_extension(get_extension($image_path)))
2750  {
2751    return new PwgError(403, "image can't be resized");
2752  }
2753
2754  $result = false;
2755  $img = new pwg_image($hd_path, $params['library']);
2756
2757  $result = $img->pwg_resize(
2758    $image_path,
2759    $params['maxwidth'],
2760    $params['maxheight'],
2761    $params['quality'],
2762    $params['automatic_rotation'],
2763    false // strip metadata
2764    );
2765
2766  $img->destroy();
2767
2768  global $conf;
2769  $conf['use_exif'] = false;
2770  $conf['use_iptc'] = false;
2771  update_metadata(array($image['id'] => $image['path']));
2772
2773  return $result;
2774}
2775
2776function ws_extensions_update($params, &$service)
2777{
2778  if (!is_webmaster())
2779  {
2780    return new PwgError(401, l10n('Webmaster status is required.'));
2781  }
2782
2783  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2784  {
2785    return new PwgError(403, 'Invalid security token');
2786  }
2787
2788  if (empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
2789  {
2790    return new PwgError(403, "invalid extension type");
2791  }
2792
2793  if (empty($params['id']) or empty($params['revision']))
2794  {
2795    return new PwgError(null, 'Wrong parameters');
2796  }
2797
2798  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2799  include_once(PHPWG_ROOT_PATH.'admin/include/'.$params['type'].'.class.php');
2800
2801  $type = $params['type'];
2802  $extension_id = $params['id'];
2803  $revision = $params['revision'];
2804
2805  $extension = new $type();
2806
2807  if ($type == 'plugins')
2808  {
2809    if (isset($extension->db_plugins_by_id[$extension_id]) and $extension->db_plugins_by_id[$extension_id]['state'] == 'active')
2810    {
2811      $extension->perform_action('deactivate', $extension_id);
2812
2813      redirect(PHPWG_ROOT_PATH
2814        . 'ws.php'
2815        . '?method=pwg.extensions.update'
2816        . '&type=plugins'
2817        . '&id=' . $extension_id
2818        . '&revision=' . $revision
2819        . '&reactivate=true'
2820        . '&pwg_token=' . get_pwg_token()
2821        . '&format=json'
2822      );
2823    }
2824   
2825    $upgrade_status = $extension->extract_plugin_files('upgrade', $revision, $extension_id);
2826    $extension_name = $extension->fs_plugins[$extension_id]['name'];
2827
2828    if (isset($params['reactivate']))
2829    {
2830      $extension->perform_action('activate', $extension_id);
2831    }
2832  }
2833  elseif ($type == 'themes')
2834  {
2835    $upgrade_status = $extension->extract_theme_files('upgrade', $revision, $extension_id);
2836    $extension_name = $extension->fs_themes[$extension_id]['name'];
2837  }
2838  elseif ($type == 'languages')
2839  {
2840    $upgrade_status = $extension->extract_language_files('upgrade', $revision, $extension_id);
2841    $extension_name = $extension->fs_languages[$extension_id]['name'];
2842  }
2843
2844  global $template;
2845  $template->delete_compiled_templates();
2846
2847  switch ($upgrade_status)
2848  {
2849    case 'ok':
2850      return sprintf(l10n('%s has been successfully updated.'), $extension_name);
2851
2852    case 'temp_path_error':
2853      return new PwgError(null, l10n('Can\'t create temporary file.'));
2854
2855    case 'dl_archive_error':
2856      return new PwgError(null, l10n('Can\'t download archive.'));
2857
2858    case 'archive_error':
2859      return new PwgError(null, l10n('Can\'t read or extract archive.'));
2860
2861    default:
2862      return new PwgError(null, sprintf(l10n('An error occured during extraction (%s).'), $upgrade_status));
2863  }
2864}
2865
2866function ws_extensions_ignoreupdate($params, &$service)
2867{
2868  global $conf;
2869
2870  define('IN_ADMIN', true);
2871  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2872
2873  if (!is_webmaster())
2874  {
2875    return new PwgError(401, 'Access denied');
2876  }
2877
2878  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2879  {
2880    return new PwgError(403, 'Invalid security token');
2881  }
2882
2883  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
2884
2885  // Reset ignored extension
2886  if ($params['reset'])
2887  {
2888    if (!empty($params['type']) and isset($conf['updates_ignored'][$params['type']]))
2889    {
2890      $conf['updates_ignored'][$params['type']] = array();
2891    }
2892    else
2893    {
2894      $conf['updates_ignored'] = array(
2895        'plugins'=>array(),
2896        'themes'=>array(),
2897        'languages'=>array()
2898      );
2899    }
2900    conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
2901    unset($_SESSION['extensions_need_update']);
2902    return true;
2903  }
2904
2905  if (empty($params['id']) or empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
2906  {
2907    return new PwgError(403, 'Invalid parameters');
2908  }
2909
2910  // Add or remove extension from ignore list
2911  if (!in_array($params['id'], $conf['updates_ignored'][$params['type']]))
2912  {
2913    array_push($conf['updates_ignored'][$params['type']], $params['id']);
2914  }
2915  conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
2916  unset($_SESSION['extensions_need_update']);
2917  return true;
2918}
2919
2920function ws_extensions_checkupdates($params, &$service)
2921{
2922  global $conf;
2923
2924  define('IN_ADMIN', true);
2925  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2926  include_once(PHPWG_ROOT_PATH.'admin/include/updates.class.php');
2927  $update = new updates();
2928
2929  if (!is_admin())
2930  {
2931    return new PwgError(401, 'Access denied');
2932  }
2933
2934  $result = array();
2935
2936  if (!isset($_SESSION['need_update']))
2937    $update->check_piwigo_upgrade();
2938
2939  $result['piwigo_need_update'] = $_SESSION['need_update'];
2940
2941  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
2942
2943  if (!isset($_SESSION['extensions_need_update']))
2944    $update->check_extensions();
2945  else
2946    $update->check_updated_extensions();
2947
2948  if (!is_array($_SESSION['extensions_need_update']))
2949    $result['ext_need_update'] = null;
2950  else
2951    $result['ext_need_update'] = !empty($_SESSION['extensions_need_update']);
2952
2953  return $result;
2954}
2955?>
Note: See TracBrowser for help on using the repository browser.