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

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

bug 2195: webservices f_min_date_available not working

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