source: branches/2.0/include/ws_functions.inc.php @ 4966

Last change on this file since 4966 was 4953, checked in by plg, 14 years ago

feature 1453 added: ability to check for uniqueness on filename. No change on
the default behavior: uniqueness is set on md5sum.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 50.8 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2009 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_posted']) )
72  {
73    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_posted']."'";
74  }
75  if ( isset($params['f_max_date_posted']) )
76  {
77    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_posted']."'";
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] = 'RAND()'; break;
125    }
126    $sortable_fields = array('id', 'file', 'name', 'hit', 'average_rate',
127      'date_creation', 'date_available', 'RAND()' );
128    if ( in_array($matches[1][$i], $sortable_fields) )
129    {
130      if (!empty($ret))
131        $ret .= ', ';
132      if ($matches[1][$i] != 'RAND()' )
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 REGEXP \'(^|,)'.$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 = mysql_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) 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']*$params['page']).','.(int)$params['per_page'];
296
297    $result = pwg_query($query);
298    while ($row = mysql_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 REGEXP \'(^|,)'.
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    nb_images, count_images AS total_nb_images,
409    date_last, max_date_last, count_categories AS nb_categories
410  FROM '.CATEGORIES_TABLE.'
411   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
412  WHERE '. implode('
413    AND ', $where);
414
415  $result = pwg_query($query);
416
417  $cats = array();
418  while ($row = mysql_fetch_assoc($result))
419  {
420    $row['url'] = make_index_url(
421        array(
422          'category' => $row
423          )
424      );
425    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
426    {
427      $row[$key] = (int)$row[$key];
428    }
429
430    $row['name'] = strip_tags(
431      trigger_event(
432        'render_category_name',
433        $row['name'],
434        'ws_categories_getList'
435        )
436      );
437   
438    array_push($cats, $row);
439  }
440  usort($cats, 'global_rank_compare');
441  return array(
442    'categories' => new PwgNamedArray(
443      $cats,
444      'category',
445      array(
446        'id',
447        'url',
448        'nb_images',
449        'total_nb_images',
450        'nb_categories',
451        'date_last',
452        'max_date_last',
453        )
454      )
455    );
456}
457
458/**
459 * returns the list of categories as you can see them in administration (web
460 * service method).
461 *
462 * Only admin can run this method and permissions are not taken into
463 * account.
464 */
465function ws_categories_getAdminList($params, &$service)
466{
467  if (!is_admin())
468  {
469    return new PwgError(401, 'Access denied');
470  }
471
472  $query = '
473SELECT
474    category_id,
475    COUNT(*) AS counter
476  FROM '.IMAGE_CATEGORY_TABLE.'
477  GROUP BY category_id
478;';
479  $nb_images_of = simple_hash_from_query($query, 'category_id', 'counter');
480
481  $query = '
482SELECT
483    id,
484    name,
485    uppercats,
486    global_rank
487  FROM '.CATEGORIES_TABLE.'
488;';
489  $result = pwg_query($query);
490  $cats = array();
491
492  while ($row = mysql_fetch_assoc($result))
493  {
494    $id = $row['id'];
495    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
496    $row['name'] = strip_tags(
497      trigger_event(
498        'render_category_name',
499        $row['name'],
500        'ws_categories_getAdminList'
501        )
502      );
503    array_push($cats, $row);
504  }
505
506  usort($cats, 'global_rank_compare');
507  return array(
508    'categories' => new PwgNamedArray(
509      $cats,
510      'category',
511      array(
512        'id',
513        'nb_images',
514        'name',
515        'uppercats',
516        'global_rank',
517        )
518      )
519    );
520}
521
522/**
523 * returns detailed information for an element (web service method)
524 */
525function ws_images_addComment($params, &$service)
526{
527  if (!$service->isPost())
528  {
529    return new PwgError(405, "This method requires HTTP POST");
530  }
531  $params['image_id'] = (int)$params['image_id'];
532  $query = '
533SELECT DISTINCT image_id
534  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
535  WHERE commentable="true"
536    AND image_id='.$params['image_id'].
537    get_sql_condition_FandF(
538      array(
539        'forbidden_categories' => 'id',
540        'visible_categories' => 'id',
541        'visible_images' => 'image_id'
542      ),
543      ' AND'
544    );
545  if ( !mysql_num_rows( pwg_query( $query ) ) )
546  {
547    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
548  }
549
550  $comm = array(
551    'author' => trim( stripslashes($params['author']) ),
552    'content' => trim( stripslashes($params['content']) ),
553    'image_id' => $params['image_id'],
554   );
555
556  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
557
558  $comment_action = insert_user_comment(
559      $comm, $params['key'], $infos
560    );
561
562  switch ($comment_action)
563  {
564    case 'reject':
565      array_push($infos, l10n('comment_not_added') );
566      return new PwgError(403, implode("\n", $infos) );
567    case 'validate':
568    case 'moderate':
569      $ret = array(
570          'id' => $comm['id'],
571          'validation' => $comment_action=='validate',
572        );
573      return new PwgNamedStruct(
574          'comment',
575          $ret,
576          null, array()
577        );
578    default:
579      return new PwgError(500, "Unknown comment action ".$comment_action );
580  }
581}
582
583/**
584 * returns detailed information for an element (web service method)
585 */
586function ws_images_getInfo($params, &$service)
587{
588  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
589  global $user, $conf;
590  $params['image_id'] = (int)$params['image_id'];
591  if ( $params['image_id']<=0 )
592  {
593    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
594  }
595
596  $query='
597SELECT * FROM '.IMAGES_TABLE.'
598  WHERE id='.$params['image_id'].
599    get_sql_condition_FandF(
600      array('visible_images' => 'id'),
601      ' AND'
602    ).'
603LIMIT 1';
604
605  $image_row = mysql_fetch_assoc(pwg_query($query));
606  if ($image_row==null)
607  {
608    return new PwgError(404, "image_id not found");
609  }
610  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
611
612  //-------------------------------------------------------- related categories
613  $query = '
614SELECT id, name, permalink, uppercats, global_rank, commentable
615  FROM '.IMAGE_CATEGORY_TABLE.'
616    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
617  WHERE image_id = '.$image_row['id'].
618  get_sql_condition_FandF(
619      array( 'forbidden_categories' => 'category_id' ),
620      ' AND'
621    ).'
622;';
623  $result = pwg_query($query);
624  $is_commentable = false;
625  $related_categories = array();
626  while ($row = mysql_fetch_assoc($result))
627  {
628    if ($row['commentable']=='true')
629    {
630      $is_commentable = true;
631    }
632    unset($row['commentable']);
633    $row['url'] = make_index_url(
634        array(
635          'category' => $row
636          )
637      );
638
639    $row['page_url'] = make_picture_url(
640        array(
641          'image_id' => $image_row['id'],
642          'image_file' => $image_row['file'],
643          'category' => $row
644          )
645      );
646    $row['id']=(int)$row['id'];
647    array_push($related_categories, $row);
648  }
649  usort($related_categories, 'global_rank_compare');
650  if ( empty($related_categories) )
651  {
652    return new PwgError(401, 'Access denied');
653  }
654
655  //-------------------------------------------------------------- related tags
656  $related_tags = get_common_tags( array($image_row['id']), -1 );
657  foreach( $related_tags as $i=>$tag)
658  {
659    $tag['url'] = make_index_url(
660        array(
661          'tags' => array($tag)
662          )
663      );
664    $tag['page_url'] = make_picture_url(
665        array(
666          'image_id' => $image_row['id'],
667          'image_file' => $image_row['file'],
668          'tags' => array($tag),
669          )
670      );
671    unset($tag['counter']);
672    $tag['id']=(int)$tag['id'];
673    $related_tags[$i]=$tag;
674  }
675  //------------------------------------------------------------- related rates
676  $query = '
677SELECT COUNT(rate) AS count
678     , ROUND(AVG(rate),2) AS average
679     , ROUND(STD(rate),2) AS stdev
680  FROM '.RATE_TABLE.'
681  WHERE element_id = '.$image_row['id'].'
682;';
683  $rating = mysql_fetch_assoc(pwg_query($query));
684  $rating['count'] = (int)$rating['count'];
685
686  //---------------------------------------------------------- related comments
687  $related_comments = array();
688
689  $where_comments = 'image_id = '.$image_row['id'];
690  if ( !is_admin() )
691  {
692    $where_comments .= '
693    AND validated="true"';
694  }
695
696  $query = '
697SELECT COUNT(id) nb_comments
698  FROM '.COMMENTS_TABLE.'
699  WHERE '.$where_comments;
700  list($nb_comments) = array_from_query($query, 'nb_comments');
701  $nb_comments = (int)$nb_comments;
702
703  if ( $nb_comments>0 and $params['comments_per_page']>0 )
704  {
705    $query = '
706SELECT id, date, author, content
707  FROM '.COMMENTS_TABLE.'
708  WHERE '.$where_comments.'
709  ORDER BY date
710  LIMIT '.(int)($params['comments_per_page']*$params['comments_page']).
711    ','.(int)$params['comments_per_page'];
712
713    $result = pwg_query($query);
714    while ($row = mysql_fetch_assoc($result))
715    {
716      $row['id']=(int)$row['id'];
717      array_push($related_comments, $row);
718    }
719  }
720
721  $comment_post_data = null;
722  if ($is_commentable and
723      (!is_a_guest()
724        or (is_a_guest() and $conf['comments_forall'] )
725      )
726      )
727  {
728    $comment_post_data['author'] = $user['username'];
729    $comment_post_data['key'] = get_comment_post_key($params['image_id']);
730  }
731
732  $ret = $image_row;
733  foreach ( array('id','width','height','hit','filesize') as $k )
734  {
735    if (isset($ret[$k]))
736    {
737      $ret[$k] = (int)$ret[$k];
738    }
739  }
740  foreach ( array('path', 'storage_category_id') as $k )
741  {
742    unset($ret[$k]);
743  }
744
745  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
746  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
747  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
748  if ( isset($comment_post_data) )
749  {
750    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
751  }
752  $ret['comments'] = array(
753     WS_XML_ATTRIBUTES =>
754        array(
755          'page' => $params['comments_page'],
756          'per_page' => $params['comments_per_page'],
757          'count' => count($related_comments),
758          'nb_comments' => $nb_comments,
759        ),
760     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id','date') )
761      );
762
763  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
764}
765
766
767/**
768 * rates the image_id in the parameter
769 */
770function ws_images_Rate($params, &$service)
771{
772  $image_id = (int)$params['image_id'];
773  $query = '
774SELECT DISTINCT id FROM '.IMAGES_TABLE.'
775  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
776  WHERE id='.$image_id
777  .get_sql_condition_FandF(
778    array(
779        'forbidden_categories' => 'category_id',
780        'forbidden_images' => 'id',
781      ),
782    '    AND'
783    ).'
784    LIMIT 1';
785  if ( mysql_num_rows( pwg_query($query) )==0 )
786  {
787    return new PwgError(404, "Invalid image_id or access denied" );
788  }
789  $rate = (int)$params['rate'];
790  include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
791  $res = rate_picture( $image_id, $rate );
792  if ($res==false)
793  {
794    global $conf;
795    return new PwgError( 403, "Forbidden or rate not in ". implode(',',$conf['rate_items']));
796  }
797  return $res;
798}
799
800
801/**
802 * returns a list of elements corresponding to a query search
803 */
804function ws_images_search($params, &$service)
805{
806  global $page;
807  $images = array();
808  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
809  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
810
811  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
812  $order_by = ws_std_image_sql_order($params, 'i.');
813
814  $super_order_by = false;
815  if ( !empty($order_by) )
816  {
817    global $conf;
818    $conf['order_by'] = 'ORDER BY '.$order_by;
819    $super_order_by=true; // quick_search_result might be faster
820  }
821
822  $search_result = get_quick_search_results($params['query'],
823      $super_order_by,
824      implode(',', $where_clauses)
825    );
826
827  $image_ids = array_slice(
828      $search_result['items'],
829      $params['page']*$params['per_page'],
830      $params['per_page']
831    );
832
833  if ( count($image_ids) )
834  {
835    $query = '
836SELECT * FROM '.IMAGES_TABLE.'
837  WHERE id IN ('.implode(',', $image_ids).')';
838
839    $image_ids = array_flip($image_ids);
840    $result = pwg_query($query);
841    while ($row = mysql_fetch_assoc($result))
842    {
843      $image = array();
844      foreach ( array('id', 'width', 'height', 'hit') as $k )
845      {
846        if (isset($row[$k]))
847        {
848          $image[$k] = (int)$row[$k];
849        }
850      }
851      foreach ( array('file', 'name', 'comment') as $k )
852      {
853        $image[$k] = $row[$k];
854      }
855      $image = array_merge( $image, ws_std_get_urls($row) );
856      $images[$image_ids[$image['id']]] = $image;
857    }
858    ksort($images, SORT_NUMERIC);
859    $images = array_values($images);
860  }
861
862
863  return array( 'images' =>
864    array (
865      WS_XML_ATTRIBUTES =>
866        array(
867            'page' => $params['page'],
868            'per_page' => $params['per_page'],
869            'count' => count($images)
870          ),
871       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
872          ws_std_get_image_xml_attributes() )
873      )
874    );
875}
876
877function ws_images_setPrivacyLevel($params, &$service)
878{
879  if (!is_admin() || is_adviser() )
880  {
881    return new PwgError(401, 'Access denied');
882  }
883  if (!$service->isPost())
884  {
885    return new PwgError(405, "This method requires HTTP POST");
886  }
887  $params['image_id'] = array_map( 'intval',$params['image_id'] );
888  if ( empty($params['image_id']) )
889  {
890    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
891  }
892  global $conf;
893  if ( !in_array( (int)$params['level'], $conf['available_permission_levels']) )
894  {
895    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid level");
896  }
897
898  $query = '
899UPDATE '.IMAGES_TABLE.'
900  SET level='.(int)$params['level'].'
901  WHERE id IN ('.implode(',',$params['image_id']).')';
902  $result = pwg_query($query);
903  $affected_rows = mysql_affected_rows();
904  if ($affected_rows)
905  {
906    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
907    invalidate_user_cache();
908  }
909  return $affected_rows;
910}
911
912function ws_images_add_chunk($params, &$service)
913{
914  ws_logfile('[ws_images_add_chunk] welcome');
915  // data
916  // original_sum
917  // type {thumb, file, high}
918  // position
919
920  if (!is_admin() || is_adviser() )
921  {
922    return new PwgError(401, 'Access denied');
923  }
924
925  if (!$service->isPost())
926  {
927    return new PwgError(405, "This method requires HTTP POST");
928  }
929
930  foreach ($params as $param_key => $param_value) {
931    if ('data' == $param_key) {
932      continue;
933    }
934   
935    ws_logfile(
936      sprintf(
937        '[ws_images_add_chunk] input param "%s" : "%s"',
938        $param_key,
939        is_null($param_value) ? 'NULL' : $param_value
940        )
941      );
942  }
943
944  $upload_dir = PHPWG_ROOT_PATH.'upload/buffer';
945
946  // create the upload directory tree if not exists
947  if (!is_dir($upload_dir)) {
948    umask(0000);
949    $recursive = true;
950    if (!@mkdir($upload_dir, 0777, $recursive))
951    {
952      return new PwgError(500, 'error during buffer directory creation');
953    }
954  }
955
956  if (!is_writable($upload_dir))
957  {
958    // last chance to make the directory writable
959    @chmod($upload_dir, 0777);
960
961    if (!is_writable($upload_dir))
962    {
963      return new PwgError(500, 'buffer directory has no write access');
964    }
965  }
966
967  secure_directory($upload_dir);
968
969  $filename = sprintf(
970    '%s-%s-%05u.block',
971    $params['original_sum'],
972    $params['type'],
973    $params['position']
974    );
975
976  ws_logfile('[ws_images_add_chunk] data length : '.strlen($params['data']));
977
978  $bytes_written = file_put_contents(
979    $upload_dir.'/'.$filename,
980    base64_decode($params['data'])
981    );
982
983  if (false === $bytes_written) {
984    return new PwgError(
985      500,
986      'an error has occured while writting chunk '.$params['position'].' for '.$params['type']
987      );
988  }
989}
990
991function merge_chunks($output_filepath, $original_sum, $type)
992{
993  ws_logfile('[merge_chunks] input parameter $output_filepath : '.$output_filepath);
994
995  if (is_file($output_filepath))
996  {
997    unlink($output_filepath);
998
999    if (is_file($output_filepath))
1000    {
1001      new PwgError(500, '[merge_chunks] error while trying to remove existing '.$output_filepath);
1002      exit();
1003    }
1004  }
1005
1006  $upload_dir = PHPWG_ROOT_PATH.'upload/buffer';
1007  $pattern = '/'.$original_sum.'-'.$type.'/';
1008  $chunks = array();
1009
1010  if ($handle = opendir($upload_dir))
1011  {
1012    while (false !== ($file = readdir($handle)))
1013    {
1014      if (preg_match($pattern, $file))
1015      {
1016        ws_logfile($file);
1017        array_push($chunks, $upload_dir.'/'.$file);
1018      }
1019    }
1020    closedir($handle);
1021  }
1022
1023  sort($chunks);
1024
1025  if (function_exists('memory_get_usage')) {
1026    ws_logfile('[merge_chunks] memory_get_usage before loading chunks: '.memory_get_usage());
1027  }
1028
1029  $i = 0;
1030
1031  foreach ($chunks as $chunk)
1032  {
1033    $string = file_get_contents($chunk);
1034
1035    if (function_exists('memory_get_usage')) {
1036      ws_logfile('[merge_chunks] memory_get_usage on chunk '.++$i.': '.memory_get_usage());
1037    }
1038
1039    if (!file_put_contents($output_filepath, $string, FILE_APPEND))
1040    {
1041      new PwgError(500, '[merge_chunks] error while writting chunks for '.$output_filepath);
1042      exit();
1043    }
1044
1045    unlink($chunk);
1046  }
1047
1048  if (function_exists('memory_get_usage')) {
1049    ws_logfile('[merge_chunks] memory_get_usage after loading chunks: '.memory_get_usage());
1050  }
1051}
1052
1053/*
1054 * The $file_path must be the path of the basic "web sized" photo
1055 * The $type value will automatically modify the $file_path to the corresponding file
1056 */
1057function add_file($file_path, $type, $original_sum, $file_sum)
1058{
1059  $file_path = file_path_for_type($file_path, $type);
1060
1061  $upload_dir = dirname($file_path);
1062  if (substr(PHP_OS, 0, 3) == 'WIN')
1063  {
1064    $upload_dir = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir);
1065  }
1066
1067  ws_logfile('[add_file] file_path  : '.$file_path);
1068  ws_logfile('[add_file] upload_dir : '.$upload_dir);
1069 
1070  if (!is_dir($upload_dir)) {
1071    umask(0000);
1072    $recursive = true;
1073    if (!@mkdir($upload_dir, 0777, $recursive))
1074    {
1075      new PwgError(500, '[add_file] error during '.$type.' directory creation');
1076      exit();
1077    }
1078  }
1079
1080  if (!is_writable($upload_dir))
1081  {
1082    // last chance to make the directory writable
1083    @chmod($upload_dir, 0777);
1084
1085    if (!is_writable($upload_dir))
1086    {
1087      new PwgError(500, '[add_file] '.$type.' directory has no write access');
1088      exit();
1089    }
1090  }
1091
1092  secure_directory($upload_dir);
1093
1094  // merge the thumbnail
1095  merge_chunks($file_path, $original_sum, $type);
1096  chmod($file_path, 0644);
1097
1098  // check dumped thumbnail md5
1099  $dumped_md5 = md5_file($file_path);
1100  if ($dumped_md5 != $file_sum) {
1101    new PwgError(500, '[add_file] '.$type.' transfer failed');
1102    exit();
1103  }
1104
1105  list($width, $height) = getimagesize($file_path);
1106  $filesize = floor(filesize($file_path)/1024);
1107
1108  return array(
1109    'width' => $width,
1110    'height' => $height,
1111    'filesize' => $filesize,
1112    );
1113}
1114
1115function ws_images_addFile($params, &$service)
1116{
1117  // image_id
1118  // type {thumb, file, high}
1119  // sum
1120
1121  global $conf;
1122  if (!is_admin() || is_adviser() )
1123  {
1124    return new PwgError(401, 'Access denied');
1125  }
1126
1127  $params['image_id'] = (int)$params['image_id'];
1128  if ($params['image_id'] <= 0)
1129  {
1130    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1131  }
1132
1133  //
1134  // what is the path?
1135  //
1136  $query = '
1137SELECT
1138    path,
1139    md5sum
1140  FROM '.IMAGES_TABLE.'
1141  WHERE id = '.$params['image_id'].'
1142;';
1143  list($file_path, $original_sum) = mysql_fetch_row(pwg_query($query));
1144
1145  // TODO only files added with web API can be updated with web API
1146
1147  //
1148  // makes sure directories are there and call the merge_chunks
1149  //
1150  $infos = add_file($file_path, $params['type'], $original_sum, $params['sum']);
1151
1152  //
1153  // update basic metadata from file
1154  //
1155  $update = array();
1156
1157  if ('high' == $params['type'])
1158  {
1159    $update['high_filesize'] = $infos['filesize'];
1160    $update['has_high'] = 'true';
1161  }
1162
1163  if ('file' == $params['type'])
1164  {
1165    $update['filesize'] = $infos['filesize'];
1166    $update['width'] = $infos['width'];
1167    $update['height'] = $infos['height'];
1168  }
1169
1170  // we may have nothing to update at database level, for example with a
1171  // thumbnail update
1172  if (count($update) > 0)
1173  {
1174    $update['id'] = $params['image_id'];
1175
1176    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1177    mass_updates(
1178      IMAGES_TABLE,
1179      array(
1180        'primary' => array('id'),
1181        'update'  => array_diff(array_keys($update), array('id'))
1182        ),
1183      array($update)
1184      );
1185  }
1186}
1187
1188function ws_images_add($params, &$service)
1189{
1190  global $conf;
1191  if (!is_admin() || is_adviser() )
1192  {
1193    return new PwgError(401, 'Access denied');
1194  }
1195
1196  foreach ($params as $param_key => $param_value) {
1197    ws_logfile(
1198      sprintf(
1199        '[pwg.images.add] input param "%s" : "%s"',
1200        $param_key,
1201        is_null($param_value) ? 'NULL' : $param_value
1202        )
1203      );
1204  }
1205
1206  // does the image already exists ?
1207  if ('md5sum' == $conf['uniqueness_mode'])
1208  {
1209    $where_clause = "md5sum = '".$params['original_sum']."'";
1210  }
1211  if ('filename' == $conf['uniqueness_mode'])
1212  {
1213    $where_clause = "file = '".$params['original_filename']."'";
1214  }
1215 
1216  $query = '
1217SELECT
1218    COUNT(*) AS counter
1219  FROM '.IMAGES_TABLE.'
1220  WHERE '.$where_clause.'
1221;';
1222  list($counter) = mysql_fetch_row(pwg_query($query));
1223  if ($counter != 0) {
1224    return new PwgError(500, 'file already exists');
1225  }
1226
1227  // current date
1228  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
1229  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
1230
1231  // upload directory hierarchy
1232  $upload_dir = sprintf(
1233    PHPWG_ROOT_PATH.'upload/%s/%s/%s',
1234    $year,
1235    $month,
1236    $day
1237    );
1238
1239  // compute file path
1240  $date_string = preg_replace('/[^\d]/', '', $dbnow);
1241  $random_string = substr($params['file_sum'], 0, 8);
1242  $filename_wo_ext = $date_string.'-'.$random_string;
1243  $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
1244
1245  // add files
1246  $file_infos  = add_file($file_path, 'file',  $params['original_sum'], $params['file_sum']);
1247  $thumb_infos = add_file($file_path, 'thumb', $params['original_sum'], $params['thumbnail_sum']);
1248
1249  if (isset($params['high_sum']))
1250  {
1251    $high_infos = add_file($file_path, 'high', $params['original_sum'], $params['high_sum']);
1252  }
1253
1254  // database registration
1255  $insert = array(
1256    'file' => !empty($params['original_filename']) ? $params['original_filename'] : $filename_wo_ext.'.jpg',
1257    'date_available' => $dbnow,
1258    'tn_ext' => 'jpg',
1259    'name' => $params['name'],
1260    'path' => $file_path,
1261    'filesize' => $file_infos['filesize'],
1262    'width' => $file_infos['width'],
1263    'height' => $file_infos['height'],
1264    'md5sum' => $params['original_sum'],
1265    );
1266
1267  $info_columns = array(
1268    'name',
1269    'author',
1270    'comment',
1271    'level',
1272    'date_creation',
1273    );
1274
1275  foreach ($info_columns as $key)
1276  {
1277    if (isset($params[$key]))
1278    {
1279      $insert[$key] = $params[$key];
1280    }
1281  }
1282
1283  if (isset($params['high_sum']))
1284  {
1285    $insert['has_high'] = 'true';
1286    $insert['high_filesize'] = $high_infos['filesize'];
1287  }
1288
1289  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1290  mass_inserts(
1291    IMAGES_TABLE,
1292    array_keys($insert),
1293    array($insert)
1294    );
1295
1296  $image_id = mysql_insert_id();
1297
1298  // let's add links between the image and the categories
1299  if (isset($params['categories']))
1300  {
1301    ws_add_image_category_relations($image_id, $params['categories']);
1302  }
1303
1304  // and now, let's create tag associations
1305  if (isset($params['tag_ids']) and !empty($params['tag_ids']))
1306  {
1307    set_tags(
1308      explode(',', $params['tag_ids']),
1309      $image_id
1310      );
1311  }
1312
1313  // update metadata from the uploaded file (exif/iptc)
1314  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1315  update_metadata(array($image_id=>$file_path));
1316 
1317  invalidate_user_cache();
1318}
1319
1320/**
1321 * perform a login (web service method)
1322 */
1323function ws_session_login($params, &$service)
1324{
1325  global $conf;
1326
1327  if (!$service->isPost())
1328  {
1329    return new PwgError(405, "This method requires HTTP POST");
1330  }
1331  if (try_log_user($params['username'], $params['password'],false))
1332  {
1333    return true;
1334  }
1335  return new PwgError(999, 'Invalid username/password');
1336}
1337
1338
1339/**
1340 * performs a logout (web service method)
1341 */
1342function ws_session_logout($params, &$service)
1343{
1344  if (!is_a_guest())
1345  {
1346    logout_user();
1347  }
1348  return true;
1349}
1350
1351function ws_session_getStatus($params, &$service)
1352{
1353  global $user;
1354  $res = array();
1355  $res['username'] = is_a_guest() ? 'guest' : $user['username'];
1356  foreach ( array('status', 'template', 'theme', 'language') as $k )
1357  {
1358    $res[$k] = $user[$k];
1359  }
1360  $res['charset'] = get_pwg_charset();
1361  return $res;
1362}
1363
1364
1365/**
1366 * returns a list of tags (web service method)
1367 */
1368function ws_tags_getList($params, &$service)
1369{
1370  $tags = get_available_tags();
1371  if ($params['sort_by_counter'])
1372  {
1373    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1374  }
1375  else
1376  {
1377    usort($tags, 'tag_alpha_compare');
1378  }
1379  for ($i=0; $i<count($tags); $i++)
1380  {
1381    $tags[$i]['id'] = (int)$tags[$i]['id'];
1382    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1383    $tags[$i]['url'] = make_index_url(
1384        array(
1385          'section'=>'tags',
1386          'tags'=>array($tags[$i])
1387        )
1388      );
1389  }
1390  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
1391}
1392
1393/**
1394 * returns the list of tags as you can see them in administration (web
1395 * service method).
1396 *
1397 * Only admin can run this method and permissions are not taken into
1398 * account.
1399 */
1400function ws_tags_getAdminList($params, &$service)
1401{
1402  if (!is_admin())
1403  {
1404    return new PwgError(401, 'Access denied');
1405  }
1406
1407  $tags = get_all_tags();
1408  return array(
1409    'tags' => new PwgNamedArray(
1410      $tags,
1411      'tag',
1412      array(
1413        'name',
1414        'id',
1415        'url_name',
1416        )
1417      )
1418    );
1419}
1420
1421/**
1422 * returns a list of images for tags (web service method)
1423 */
1424function ws_tags_getImages($params, &$service)
1425{
1426  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1427  global $conf;
1428
1429  // first build all the tag_ids we are interested in
1430  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1431  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1432  $tags_by_id = array();
1433  foreach( $tags as $tag )
1434  {
1435    $tags['id'] = (int)$tag['id'];
1436    $tags_by_id[ $tag['id'] ] = $tag;
1437  }
1438  unset($tags);
1439  $tag_ids = array_keys($tags_by_id);
1440
1441
1442  $image_ids = array();
1443  $image_tag_map = array();
1444
1445  if ( !empty($tag_ids) )
1446  { // build list of image ids with associated tags per image
1447    if ($params['tag_mode_and'])
1448    {
1449      $image_ids = get_image_ids_for_tags( $tag_ids );
1450    }
1451    else
1452    {
1453      $query = '
1454SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
1455  FROM '.IMAGE_TAG_TABLE.'
1456  WHERE tag_id IN ('.implode(',',$tag_ids).')
1457  GROUP BY image_id';
1458      $result = pwg_query($query);
1459      while ( $row=mysql_fetch_assoc($result) )
1460      {
1461        $row['image_id'] = (int)$row['image_id'];
1462        array_push( $image_ids, $row['image_id'] );
1463        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1464      }
1465    }
1466  }
1467
1468  $images = array();
1469  if ( !empty($image_ids))
1470  {
1471    $where_clauses = ws_std_image_sql_filter($params);
1472    $where_clauses[] = get_sql_condition_FandF(
1473        array
1474          (
1475            'forbidden_categories' => 'category_id',
1476            'visible_categories' => 'category_id',
1477            'visible_images' => 'i.id'
1478          ),
1479        '', true
1480      );
1481    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
1482
1483    $order_by = ws_std_image_sql_order($params);
1484    if (empty($order_by))
1485    {
1486      $order_by = $conf['order_by'];
1487    }
1488    else
1489    {
1490      $order_by = 'ORDER BY '.$order_by;
1491    }
1492
1493    $query = '
1494SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
1495  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
1496  WHERE '. implode('
1497    AND ', $where_clauses).'
1498'.$order_by.'
1499LIMIT '.(int)($params['per_page']*$params['page']).','.(int)$params['per_page'];
1500
1501    $result = pwg_query($query);
1502    while ($row = mysql_fetch_assoc($result))
1503    {
1504      $image = array();
1505      foreach ( array('id', 'width', 'height', 'hit') as $k )
1506      {
1507        if (isset($row[$k]))
1508        {
1509          $image[$k] = (int)$row[$k];
1510        }
1511      }
1512      foreach ( array('file', 'name', 'comment') as $k )
1513      {
1514        $image[$k] = $row[$k];
1515      }
1516      $image = array_merge( $image, ws_std_get_urls($row) );
1517
1518      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1519      $image_tags = array();
1520      foreach ($image_tag_ids as $tag_id)
1521      {
1522        $url = make_index_url(
1523                 array(
1524                  'section'=>'tags',
1525                  'tags'=> array($tags_by_id[$tag_id])
1526                )
1527              );
1528        $page_url = make_picture_url(
1529                 array(
1530                  'section'=>'tags',
1531                  'tags'=> array($tags_by_id[$tag_id]),
1532                  'image_id' => $row['id'],
1533                  'image_file' => $row['file'],
1534                )
1535              );
1536        array_push($image_tags, array(
1537                'id' => (int)$tag_id,
1538                'url' => $url,
1539                'page_url' => $page_url,
1540              )
1541            );
1542      }
1543      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1544              array('id','url_name','url','page_url')
1545            );
1546      array_push($images, $image);
1547    }
1548  }
1549
1550  return array( 'images' =>
1551    array (
1552      WS_XML_ATTRIBUTES =>
1553        array(
1554            'page' => $params['page'],
1555            'per_page' => $params['per_page'],
1556            'count' => count($images)
1557          ),
1558       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1559          ws_std_get_image_xml_attributes() )
1560      )
1561    );
1562}
1563
1564function ws_categories_add($params, &$service)
1565{
1566  if (!is_admin() or is_adviser())
1567  {
1568    return new PwgError(401, 'Access denied');
1569  }
1570
1571  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1572
1573  $creation_output = create_virtual_category(
1574    $params['name'],
1575    $params['parent']
1576    );
1577
1578  if (isset($creation_output['error']))
1579  {
1580    return new PwgError(500, $creation_output['error']);
1581  }
1582
1583  invalidate_user_cache();
1584
1585  return $creation_output;
1586}
1587
1588function ws_tags_add($params, &$service)
1589{
1590  if (!is_admin() or is_adviser())
1591  {
1592    return new PwgError(401, 'Access denied');
1593  }
1594
1595  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1596
1597  $creation_output = create_tag($params['name']);
1598
1599  if (isset($creation_output['error']))
1600  {
1601    return new PwgError(500, $creation_output['error']);
1602  }
1603
1604  return $creation_output;
1605}
1606
1607function ws_images_exist($params, &$service)
1608{
1609  global $conf;
1610 
1611  if (!is_admin() or is_adviser())
1612  {
1613    return new PwgError(401, 'Access denied');
1614  }
1615
1616  $split_pattern = '/[\s,;\|]/';
1617
1618  if ('md5sum' == $conf['uniqueness_mode'])
1619  {
1620    // search among photos the list of photos already added, based on md5sum
1621    // list
1622    $md5sums = preg_split(
1623      $split_pattern,
1624      $params['md5sum_list'],
1625      -1,
1626      PREG_SPLIT_NO_EMPTY
1627    );
1628
1629    $query = '
1630SELECT
1631    id,
1632    md5sum
1633  FROM '.IMAGES_TABLE.'
1634  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
1635;';
1636    $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
1637
1638    $result = array();
1639
1640    foreach ($md5sums as $md5sum)
1641    {
1642      $result[$md5sum] = null;
1643      if (isset($id_of_md5[$md5sum]))
1644      {
1645        $result[$md5sum] = $id_of_md5[$md5sum];
1646      }
1647    }
1648  }
1649 
1650  if ('filename' == $conf['uniqueness_mode'])
1651  {
1652    // search among photos the list of photos already added, based on
1653    // filename list
1654    $filenames = preg_split(
1655      $split_pattern,
1656      $params['filename_list'],
1657      -1,
1658      PREG_SPLIT_NO_EMPTY
1659    );
1660
1661    $query = '
1662SELECT
1663    id,
1664    file
1665  FROM '.IMAGES_TABLE.'
1666  WHERE file IN (\''.implode("','", $filenames).'\')
1667;';
1668    $id_of_filename = simple_hash_from_query($query, 'file', 'id');
1669
1670    $result = array();
1671
1672    foreach ($filenames as $filename)
1673    {
1674      $result[$filename] = null;
1675      if (isset($id_of_filename[$filename]))
1676      {
1677        $result[$filename] = $id_of_filename[$filename];
1678      }
1679    }
1680  }
1681
1682  return $result;
1683}
1684
1685function ws_images_checkFiles($params, &$service)
1686{
1687  if (!is_admin() or is_adviser())
1688  {
1689    return new PwgError(401, 'Access denied');
1690  }
1691
1692  // input parameters
1693  //
1694  // image_id
1695  // thumbnail_sum
1696  // file_sum
1697  // high_sum
1698
1699  $params['image_id'] = (int)$params['image_id'];
1700  if ($params['image_id'] <= 0)
1701  {
1702    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1703  }
1704
1705  $query = '
1706SELECT
1707    path
1708  FROM '.IMAGES_TABLE.'
1709  WHERE id = '.$params['image_id'].'
1710;';
1711  $result = pwg_query($query);
1712  if (mysql_num_rows($result) == 0) {
1713    return new PwgError(404, "image_id not found");
1714  }
1715  list($path) = mysql_fetch_row($result);
1716
1717  $ret = array();
1718
1719  foreach (array('thumb', 'file', 'high') as $type) {
1720    $param_name = $type;
1721    if ('thumb' == $type) {
1722      $param_name = 'thumbnail';
1723    }
1724
1725    if (isset($params[$param_name.'_sum'])) {
1726      $type_path = file_path_for_type($path, $type);
1727      if (!is_file($type_path)) {
1728        $ret[$param_name] = 'missing';
1729      }
1730      else {
1731        if (md5_file($type_path) != $params[$param_name.'_sum']) {
1732          $ret[$param_name] = 'differs';
1733        }
1734        else {
1735          $ret[$param_name] = 'equals';
1736        }
1737      }
1738    }
1739  }
1740
1741  return $ret;
1742}
1743
1744function file_path_for_type($file_path, $type='thumb')
1745{
1746  // resolve the $file_path depending on the $type
1747  if ('thumb' == $type) {
1748    $file_path = get_thumbnail_location(
1749      array(
1750        'path' => $file_path,
1751        'tn_ext' => 'jpg',
1752        )
1753      );
1754  }
1755
1756  if ('high' == $type) {
1757    @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1758    $file_path = get_high_location(
1759      array(
1760        'path' => $file_path,
1761        'has_high' => 'true'
1762        )
1763      );
1764  }
1765
1766  return $file_path;
1767}
1768
1769function ws_images_setInfo($params, &$service)
1770{
1771  global $conf;
1772  if (!is_admin() || is_adviser() )
1773  {
1774    return new PwgError(401, 'Access denied');
1775  }
1776
1777  if (!$service->isPost())
1778  {
1779    return new PwgError(405, "This method requires HTTP POST");
1780  }
1781
1782  $params['image_id'] = (int)$params['image_id'];
1783  if ($params['image_id'] <= 0)
1784  {
1785    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1786  }
1787
1788  $query='
1789SELECT *
1790  FROM '.IMAGES_TABLE.'
1791  WHERE id = '.$params['image_id'].'
1792;';
1793
1794  $image_row = mysql_fetch_assoc(pwg_query($query));
1795  if ($image_row == null)
1796  {
1797    return new PwgError(404, "image_id not found");
1798  }
1799
1800  // database registration
1801  $update = array();
1802
1803  $info_columns = array(
1804    'name',
1805    'author',
1806    'comment',
1807    'level',
1808    'date_creation',
1809    );
1810
1811  foreach ($info_columns as $key)
1812  {
1813    if (isset($params[$key]))
1814    {
1815      if ('fill_if_empty' == $params['single_value_mode'])
1816      {
1817        if (empty($image_row[$key]))
1818        {
1819          $update[$key] = $params[$key];
1820        }
1821      }
1822      elseif ('replace' == $params['single_value_mode'])
1823      {
1824        $update[$key] = $params[$key];
1825      }
1826      else
1827      {
1828        new PwgError(
1829          500,
1830          '[ws_images_setInfo]'
1831          .' invalid parameter single_value_mode "'.$params['single_value_mode'].'"'
1832          .', possible values are {fill_if_empty, replace}.'
1833          );
1834        exit();
1835      }
1836    }
1837  }
1838
1839  if (count(array_keys($update)) > 0)
1840  {
1841    $update['id'] = $params['image_id'];
1842
1843    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1844    mass_updates(
1845      IMAGES_TABLE,
1846      array(
1847        'primary' => array('id'),
1848        'update'  => array_diff(array_keys($update), array('id'))
1849        ),
1850      array($update)
1851      );
1852  }
1853
1854  if (isset($params['categories']))
1855  {
1856    ws_add_image_category_relations(
1857      $params['image_id'],
1858      $params['categories'],
1859      ('replace' == $params['multiple_value_mode'] ? true : false)
1860      );
1861  }
1862
1863  // and now, let's create tag associations
1864  if (isset($params['tag_ids']))
1865  {
1866    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1867
1868    $tag_ids = explode(',', $params['tag_ids']);
1869
1870    if ('replace' == $params['multiple_value_mode'])
1871    {
1872      set_tags(
1873        $tag_ids,
1874        $params['image_id']
1875        );
1876    }
1877    elseif ('append' == $params['multiple_value_mode'])
1878    {
1879      add_tags(
1880        $tag_ids,
1881        array($params['image_id'])
1882        );
1883    }
1884    else
1885    {
1886      new PwgError(
1887        500,
1888        '[ws_images_setInfo]'
1889        .' invalid parameter multiple_value_mode "'.$params['multiple_value_mode'].'"'
1890        .', possible values are {replace, append}.'
1891        );
1892      exit();
1893    }
1894  }
1895
1896  invalidate_user_cache();
1897}
1898
1899function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
1900{
1901  // let's add links between the image and the categories
1902  //
1903  // $params['categories'] should look like 123,12;456,auto;789 which means:
1904  //
1905  // 1. associate with category 123 on rank 12
1906  // 2. associate with category 456 on automatic rank
1907  // 3. associate with category 789 on automatic rank
1908  $cat_ids = array();
1909  $rank_on_category = array();
1910  $search_current_ranks = false;
1911
1912  $tokens = explode(';', $categories_string);
1913  foreach ($tokens as $token)
1914  {
1915    @list($cat_id, $rank) = explode(',', $token);
1916
1917    if (!preg_match('/^\d+$/', $cat_id))
1918    {
1919      continue;
1920    }
1921
1922    array_push($cat_ids, $cat_id);
1923
1924    if (!isset($rank))
1925    {
1926      $rank = 'auto';
1927    }
1928    $rank_on_category[$cat_id] = $rank;
1929
1930    if ($rank == 'auto')
1931    {
1932      $search_current_ranks = true;
1933    }
1934  }
1935
1936  $cat_ids = array_unique($cat_ids);
1937
1938  if (count($cat_ids) == 0)
1939  {
1940    new PwgError(
1941      500,
1942      '[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
1943      );
1944    exit();
1945  }
1946
1947  $query = '
1948SELECT
1949    id
1950  FROM '.CATEGORIES_TABLE.'
1951  WHERE id IN ('.implode(',', $cat_ids).')
1952;';
1953  $db_cat_ids = array_from_query($query, 'id');
1954
1955  $unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
1956  if (count($unknown_cat_ids) != 0)
1957  {
1958    new PwgError(
1959      500,
1960      '[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
1961      );
1962    exit();
1963  }
1964
1965  $to_update_cat_ids = array();
1966
1967  // in case of replace mode, we first check the existing associations
1968  $query = '
1969SELECT
1970    category_id
1971  FROM '.IMAGE_CATEGORY_TABLE.'
1972  WHERE image_id = '.$image_id.'
1973;';
1974  $existing_cat_ids = array_from_query($query, 'category_id');
1975
1976  if ($replace_mode)
1977  {
1978    $to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
1979    if (count($to_remove_cat_ids) > 0)
1980    {
1981      $query = '
1982DELETE
1983  FROM '.IMAGE_CATEGORY_TABLE.'
1984  WHERE image_id = '.$image_id.'
1985    AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
1986;';
1987      pwg_query($query);
1988      update_category($to_remove_cat_ids);
1989    }
1990  }
1991
1992  $new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
1993  if (count($new_cat_ids) == 0)
1994  {
1995    return true;
1996  }
1997
1998  if ($search_current_ranks)
1999  {
2000    $query = '
2001SELECT
2002    category_id,
2003    MAX(rank) AS max_rank
2004  FROM '.IMAGE_CATEGORY_TABLE.'
2005  WHERE rank IS NOT NULL
2006    AND category_id IN ('.implode(',', $new_cat_ids).')
2007  GROUP BY category_id
2008;';
2009    $current_rank_of = simple_hash_from_query(
2010      $query,
2011      'category_id',
2012      'max_rank'
2013      );
2014
2015    foreach ($new_cat_ids as $cat_id)
2016    {
2017      if (!isset($current_rank_of[$cat_id]))
2018      {
2019        $current_rank_of[$cat_id] = 0;
2020      }
2021
2022      if ('auto' == $rank_on_category[$cat_id])
2023      {
2024        $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
2025      }
2026    }
2027  }
2028
2029  $inserts = array();
2030
2031  foreach ($new_cat_ids as $cat_id)
2032  {
2033    array_push(
2034      $inserts,
2035      array(
2036        'image_id' => $image_id,
2037        'category_id' => $cat_id,
2038        'rank' => $rank_on_category[$cat_id],
2039        )
2040      );
2041  }
2042
2043  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2044  mass_inserts(
2045    IMAGE_CATEGORY_TABLE,
2046    array_keys($inserts[0]),
2047    $inserts
2048    );
2049
2050  update_category($new_cat_ids);
2051}
2052
2053function ws_categories_setInfo($params, &$service)
2054{
2055  global $conf;
2056  if (!is_admin() || is_adviser() )
2057  {
2058    return new PwgError(401, 'Access denied');
2059  }
2060
2061  if (!$service->isPost())
2062  {
2063    return new PwgError(405, "This method requires HTTP POST");
2064  }
2065
2066  // category_id
2067  // name
2068  // comment
2069
2070  $params['category_id'] = (int)$params['category_id'];
2071  if ($params['category_id'] <= 0)
2072  {
2073    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2074  }
2075
2076  // database registration
2077  $update = array(
2078    'id' => $params['category_id'],
2079    );
2080
2081  $info_columns = array(
2082    'name',
2083    'comment',
2084    );
2085
2086  $perform_update = false;
2087  foreach ($info_columns as $key)
2088  {
2089    if (isset($params[$key]))
2090    {
2091      $perform_update = true;
2092      $update[$key] = $params[$key];
2093    }
2094  }
2095
2096  if ($perform_update)
2097  {
2098    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2099    mass_updates(
2100      CATEGORIES_TABLE,
2101      array(
2102        'primary' => array('id'),
2103        'update'  => array_diff(array_keys($update), array('id'))
2104        ),
2105      array($update)
2106      );
2107  }
2108
2109}
2110
2111function ws_logfile($string)
2112{
2113  global $conf;
2114
2115  if (!$conf['ws_enable_log']) {
2116    return true;
2117  }
2118
2119  file_put_contents(
2120    $conf['ws_log_filepath'],
2121    '['.date('c').'] '.$string."\n",
2122    FILE_APPEND
2123    );
2124}
2125?>
Note: See TracBrowser for help on using the repository browser.