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

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

merge r11152 from branch 2.2 to trunk

feature 1622 added: pwg.categories.getList is now able to return a tree with
the new "tree_output" option. Only compatible with json/php output formats.

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