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

Last change on this file since 2757 was 2757, checked in by rvelices, 16 years ago

merge 2755 and 2756 from branch 2.0 to trunk

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 37.2 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008      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  if ( empty($params['image_id']) )
191  {
192    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
193  }
194  global $user;
195  $query = '
196SELECT id
197  FROM '.IMAGES_TABLE.' LEFT JOIN '.CADDIE_TABLE.' ON id=element_id AND user_id='.$user['id'].'
198  WHERE id IN ('.implode(',',$params['image_id']).')
199    AND element_id IS NULL';
200  $datas = array();
201  foreach ( array_from_query($query, 'id') as $id )
202  {
203    array_push($datas, array('element_id'=>$id, 'user_id'=>$user['id']) );
204  }
205  if (count($datas))
206  {
207    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
208    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
209  }
210  return count($datas);
211}
212
213/**
214 * returns images per category (web service method)
215 */
216function ws_categories_getImages($params, &$service)
217{
218  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
219  global $user, $conf;
220
221  $images = array();
222
223  //------------------------------------------------- get the related categories
224  $where_clauses = array();
225  foreach($params['cat_id'] as $cat_id)
226  {
227    $cat_id = (int)$cat_id;
228    if ($cat_id<=0)
229      continue;
230    if ($params['recursive'])
231    {
232      $where_clauses[] = 'uppercats REGEXP \'(^|,)'.$cat_id.'(,|$)\'';
233    }
234    else
235    {
236      $where_clauses[] = 'id='.$cat_id;
237    }
238  }
239  if (!empty($where_clauses))
240  {
241    $where_clauses = array( '('.
242    implode('
243    OR ', $where_clauses) . ')'
244      );
245  }
246  $where_clauses[] = get_sql_condition_FandF(
247        array('forbidden_categories' => 'id'),
248        NULL, true
249      );
250
251  $query = '
252SELECT id, name, permalink, image_order
253  FROM '.CATEGORIES_TABLE.'
254  WHERE '. implode('
255    AND ', $where_clauses);
256  $result = pwg_query($query);
257  $cats = array();
258  while ($row = mysql_fetch_assoc($result))
259  {
260    $row['id'] = (int)$row['id'];
261    $cats[ $row['id'] ] = $row;
262  }
263
264  //-------------------------------------------------------- get the images
265  if ( !empty($cats) )
266  {
267    $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
268    $where_clauses[] = 'category_id IN ('
269      .implode(',', array_keys($cats) )
270      .')';
271    $where_clauses[] = get_sql_condition_FandF( array(
272          'visible_images' => 'i.id'
273        ), null, true
274      );
275
276    $order_by = ws_std_image_sql_order($params, 'i.');
277    if ( empty($order_by)
278          and count($params['cat_id'])==1
279          and isset($cats[ $params['cat_id'][0] ]['image_order'])
280        )
281    {
282      $order_by = $cats[ $params['cat_id'][0] ]['image_order'];
283    }
284    $order_by = empty($order_by) ? $conf['order_by'] : 'ORDER BY '.$order_by;
285
286    $query = '
287SELECT i.*, GROUP_CONCAT(category_id) cat_ids
288  FROM '.IMAGES_TABLE.' i
289    INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
290  WHERE '. implode('
291    AND ', $where_clauses).'
292GROUP BY i.id
293'.$order_by.'
294LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
295
296    $result = pwg_query($query);
297    while ($row = mysql_fetch_assoc($result))
298    {
299      $image = array();
300      foreach ( array('id', 'width', 'height', 'hit') as $k )
301      {
302        if (isset($row[$k]))
303        {
304          $image[$k] = (int)$row[$k];
305        }
306      }
307      foreach ( array('file', 'name', 'comment') as $k )
308      {
309        $image[$k] = $row[$k];
310      }
311      $image = array_merge( $image, ws_std_get_urls($row) );
312
313      $image_cats = array();
314      foreach ( explode(',', $row['cat_ids']) as $cat_id )
315      {
316        $url = make_index_url(
317                array(
318                  'category' => $cats[$cat_id],
319                  )
320                );
321        $page_url = make_picture_url(
322                array(
323                  'category' => $cats[$cat_id],
324                  'image_id' => $row['id'],
325                  'image_file' => $row['file'],
326                  )
327                );
328        array_push( $image_cats,  array(
329              WS_XML_ATTRIBUTES => array (
330                  'id' => (int)$cat_id,
331                  'url' => $url,
332                  'page_url' => $page_url,
333                )
334            )
335          );
336      }
337
338      $image['categories'] = new PwgNamedArray(
339            $image_cats,'category', array('id','url','page_url')
340          );
341      array_push($images, $image);
342    }
343  }
344
345  return array( 'images' =>
346    array (
347      WS_XML_ATTRIBUTES =>
348        array(
349            'page' => $params['page'],
350            'per_page' => $params['per_page'],
351            'count' => count($images)
352          ),
353       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
354          ws_std_get_image_xml_attributes() )
355      )
356    );
357}
358
359
360/**
361 * returns a list of categories (web service method)
362 */
363function ws_categories_getList($params, &$service)
364{
365  global $user,$conf;
366
367  $where = array();
368
369  if (!$params['recursive'])
370  {
371    if ($params['cat_id']>0)
372      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
373    OR id='.(int)($params['cat_id']).')';
374    else
375      $where[] = 'id_uppercat IS NULL';
376  }
377  else if ($params['cat_id']>0)
378  {
379    $where[] = 'uppercats REGEXP \'(^|,)'.
380      (int)($params['cat_id'])
381      .'(,|$)\'';
382  }
383
384  if ($params['public'])
385  {
386    $where[] = 'status = "public"';
387    $where[] = 'visible = "true"';
388    $where[]= 'user_id='.$conf['guest_id'];
389  }
390  else
391  {
392    $where[]= 'user_id='.$user['id'];
393  }
394
395  $query = '
396SELECT id, name, permalink, uppercats, global_rank,
397    nb_images, count_images AS total_nb_images,
398    date_last, max_date_last, count_categories AS nb_categories
399  FROM '.CATEGORIES_TABLE.'
400   INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id
401  WHERE '. implode('
402    AND ', $where);
403
404  $result = pwg_query($query);
405
406  $cats = array();
407  while ($row = mysql_fetch_assoc($result))
408  {
409    $row['url'] = make_index_url(
410        array(
411          'category' => $row
412          )
413      );
414    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
415    {
416      $row[$key] = (int)$row[$key];
417    }
418
419    array_push($cats, $row);
420  }
421  usort($cats, 'global_rank_compare');
422  return array(
423    'categories' => new PwgNamedArray(
424      $cats,
425      'category',
426      array(
427        'id',
428        'url',
429        'nb_images',
430        'total_nb_images',
431        'nb_categories',
432        'date_last',
433        'max_date_last',
434        )
435      )
436    );
437}
438
439/**
440 * returns the list of categories as you can see them in administration (web
441 * service method).
442 *
443 * Only admin can run this method and permissions are not taken into
444 * account.
445 */
446function ws_categories_getAdminList($params, &$service)
447{
448  if (!is_admin())
449  {
450    return new PwgError(401, 'Access denied');
451  }
452
453  $query = '
454SELECT
455    category_id,
456    COUNT(*) AS counter
457  FROM '.IMAGE_CATEGORY_TABLE.'
458  GROUP BY category_id
459;';
460  $nb_images_of = simple_hash_from_query($query, 'category_id', 'counter');
461
462  $query = '
463SELECT
464    id,
465    name,
466    uppercats,
467    global_rank
468  FROM '.CATEGORIES_TABLE.'
469;';
470  $result = pwg_query($query);
471  $cats = array();
472
473  while ($row = mysql_fetch_assoc($result))
474  {
475    $id = $row['id'];
476    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
477    array_push($cats, $row);
478  }
479
480  usort($cats, 'global_rank_compare');
481  return array(
482    'categories' => new PwgNamedArray(
483      $cats,
484      'category',
485      array(
486        'id',
487        'nb_images',
488        'name',
489        'uppercats',
490        'global_rank',
491        )
492      )
493    );
494}
495
496/**
497 * returns detailed information for an element (web service method)
498 */
499function ws_images_addComment($params, &$service)
500{
501  if (!$service->isPost())
502  {
503    return new PwgError(405, "This method requires HTTP POST");
504  }
505  $params['image_id'] = (int)$params['image_id'];
506  $query = '
507SELECT DISTINCT image_id
508  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
509  WHERE commentable="true"
510    AND image_id='.$params['image_id'].
511    get_sql_condition_FandF(
512      array(
513        'forbidden_categories' => 'id',
514        'visible_categories' => 'id',
515        'visible_images' => 'image_id'
516      ),
517      ' AND'
518    );
519  if ( !mysql_num_rows( pwg_query( $query ) ) )
520  {
521    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
522  }
523
524  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
525
526  $comm = array(
527    'author' => trim( stripslashes($params['author']) ),
528    'content' => trim( stripslashes($params['content']) ),
529    'image_id' => $params['image_id'],
530   );
531
532  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
533
534  $comment_action = insert_user_comment(
535      $comm, $params['key'], $infos
536    );
537
538  switch ($comment_action)
539  {
540    case 'reject':
541      array_push($infos, l10n('comment_not_added') );
542      return new PwgError(403, implode("\n", $infos) );
543    case 'validate':
544    case 'moderate':
545      $ret = array(
546          'id' => $comm['id'],
547          'validation' => $comment_action=='validate',
548        );
549      return new PwgNamedStruct(
550          'comment',
551          $ret,
552          null, array()
553        );
554    default:
555      return new PwgError(500, "Unknown comment action ".$comment_action );
556  }
557}
558
559/**
560 * returns detailed information for an element (web service method)
561 */
562function ws_images_getInfo($params, &$service)
563{
564  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
565  global $user, $conf;
566  $params['image_id'] = (int)$params['image_id'];
567  if ( $params['image_id']<=0 )
568  {
569    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
570  }
571
572  $query='
573SELECT * FROM '.IMAGES_TABLE.'
574  WHERE id='.$params['image_id'].
575    get_sql_condition_FandF(
576      array('visible_images' => 'id'),
577      ' AND'
578    ).'
579LIMIT 1';
580
581  $image_row = mysql_fetch_assoc(pwg_query($query));
582  if ($image_row==null)
583  {
584    return new PwgError(404, "image_id not found");
585  }
586  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
587
588  //-------------------------------------------------------- related categories
589  $query = '
590SELECT id, name, permalink, uppercats, global_rank, commentable
591  FROM '.IMAGE_CATEGORY_TABLE.'
592    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
593  WHERE image_id = '.$image_row['id'].
594  get_sql_condition_FandF(
595      array( 'forbidden_categories' => 'category_id' ),
596      ' AND'
597    ).'
598;';
599  $result = pwg_query($query);
600  $is_commentable = false;
601  $related_categories = array();
602  while ($row = mysql_fetch_assoc($result))
603  {
604    if ($row['commentable']=='true')
605    {
606      $is_commentable = true;
607    }
608    unset($row['commentable']);
609    $row['url'] = make_index_url(
610        array(
611          'category' => $row
612          )
613      );
614
615    $row['page_url'] = make_picture_url(
616        array(
617          'image_id' => $image_row['id'],
618          'image_file' => $image_row['file'],
619          'category' => $row
620          )
621      );
622    $row['id']=(int)$row['id'];
623    array_push($related_categories, $row);
624  }
625  usort($related_categories, 'global_rank_compare');
626  if ( empty($related_categories) )
627  {
628    return new PwgError(401, 'Access denied');
629  }
630
631  //-------------------------------------------------------------- related tags
632  $related_tags = get_common_tags( array($image_row['id']), -1 );
633  foreach( $related_tags as $i=>$tag)
634  {
635    $tag['url'] = make_index_url(
636        array(
637          'tags' => array($tag)
638          )
639      );
640    $tag['page_url'] = make_picture_url(
641        array(
642          'image_id' => $image_row['id'],
643          'image_file' => $image_row['file'],
644          'tags' => array($tag),
645          )
646      );
647    unset($tag['counter']);
648    $tag['id']=(int)$tag['id'];
649    $related_tags[$i]=$tag;
650  }
651  //------------------------------------------------------------- related rates
652  $query = '
653SELECT COUNT(rate) AS count
654     , ROUND(AVG(rate),2) AS average
655     , ROUND(STD(rate),2) AS stdev
656  FROM '.RATE_TABLE.'
657  WHERE element_id = '.$image_row['id'].'
658;';
659  $rating = mysql_fetch_assoc(pwg_query($query));
660  $rating['count'] = (int)$rating['count'];
661
662  //---------------------------------------------------------- related comments
663  $related_comments = array();
664
665  $where_comments = 'image_id = '.$image_row['id'];
666  if ( !is_admin() )
667  {
668    $where_comments .= '
669    AND validated="true"';
670  }
671
672  $query = '
673SELECT COUNT(id) nb_comments
674  FROM '.COMMENTS_TABLE.'
675  WHERE '.$where_comments;
676  list($nb_comments) = array_from_query($query, 'nb_comments');
677  $nb_comments = (int)$nb_comments;
678
679  if ( $nb_comments>0 and $params['comments_per_page']>0 )
680  {
681    $query = '
682SELECT id, date, author, content
683  FROM '.COMMENTS_TABLE.'
684  WHERE '.$where_comments.'
685  ORDER BY date
686  LIMIT '.$params['comments_per_page']*(int)$params['comments_page'].
687    ','.$params['comments_per_page'];
688
689    $result = pwg_query($query);
690    while ($row = mysql_fetch_assoc($result))
691    {
692      $row['id']=(int)$row['id'];
693      array_push($related_comments, $row);
694    }
695  }
696
697  $comment_post_data = null;
698  if ($is_commentable and
699      (!is_a_guest()
700        or (is_a_guest() and $conf['comments_forall'] )
701      )
702      )
703  {
704    include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
705    $comment_post_data['author'] = $user['username'];
706    $comment_post_data['key'] = get_comment_post_key($params['image_id']);
707  }
708
709  $ret = $image_row;
710  foreach ( array('id','width','height','hit','filesize') as $k )
711  {
712    if (isset($ret[$k]))
713    {
714      $ret[$k] = (int)$ret[$k];
715    }
716  }
717  foreach ( array('path', 'storage_category_id') as $k )
718  {
719    unset($ret[$k]);
720  }
721
722  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
723  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
724  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
725  if ( isset($comment_post_data) )
726  {
727    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
728  }
729  $ret['comments'] = array(
730     WS_XML_ATTRIBUTES =>
731        array(
732          'page' => $params['comments_page'],
733          'per_page' => $params['comments_per_page'],
734          'count' => count($related_comments),
735          'nb_comments' => $nb_comments,
736        ),
737     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id','date') )
738      );
739
740  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
741}
742
743
744/**
745 * rates the image_id in the parameter
746 */
747function ws_images_Rate($params, &$service)
748{
749  $image_id = (int)$params['image_id'];
750  $query = '
751SELECT DISTINCT id FROM '.IMAGES_TABLE.'
752  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
753  WHERE id='.$image_id
754  .get_sql_condition_FandF(
755    array(
756        'forbidden_categories' => 'category_id',
757        'forbidden_images' => 'id',
758      ),
759    '    AND'
760    ).'
761    LIMIT 1';
762  if ( mysql_num_rows( pwg_query($query) )==0 )
763  {
764    return new PwgError(404, "Invalid image_id or access denied" );
765  }
766  $rate = (int)$params['rate'];
767  include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
768  $res = rate_picture( $image_id, $rate );
769  if ($res==false)
770  {
771    global $conf;
772    return new PwgError( 403, "Forbidden or rate not in ". implode(',',$conf['rate_items']));
773  }
774  return $res;
775}
776
777
778/**
779 * returns a list of elements corresponding to a query search
780 */
781function ws_images_search($params, &$service)
782{
783  global $page;
784  $images = array();
785  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
786  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
787
788  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
789  $order_by = ws_std_image_sql_order($params, 'i.');
790
791  $super_order_by = false;
792  if ( !empty($order_by) )
793  {
794    global $conf;
795    $conf['order_by'] = 'ORDER BY '.$order_by;
796    $super_order_by=true; // quick_search_result might be faster
797  }
798
799  $search_result = get_quick_search_results($params['query'],
800      $super_order_by,
801      implode(',', $where_clauses)
802    );
803
804  $image_ids = array_slice(
805      $search_result['items'],
806      $params['page']*$params['per_page'],
807      $params['per_page']
808    );
809
810  if ( count($image_ids) )
811  {
812    $query = '
813SELECT * FROM '.IMAGES_TABLE.'
814  WHERE id IN ('.implode(',', $image_ids).')';
815
816    $image_ids = array_flip($image_ids);
817    $result = pwg_query($query);
818    while ($row = mysql_fetch_assoc($result))
819    {
820      $image = array();
821      foreach ( array('id', 'width', 'height', 'hit') as $k )
822      {
823        if (isset($row[$k]))
824        {
825          $image[$k] = (int)$row[$k];
826        }
827      }
828      foreach ( array('file', 'name', 'comment') as $k )
829      {
830        $image[$k] = $row[$k];
831      }
832      $image = array_merge( $image, ws_std_get_urls($row) );
833      $images[$image_ids[$image['id']]] = $image;
834    }
835    ksort($images, SORT_NUMERIC);
836    $images = array_values($images);
837  }
838
839
840  return array( 'images' =>
841    array (
842      WS_XML_ATTRIBUTES =>
843        array(
844            'page' => $params['page'],
845            'per_page' => $params['per_page'],
846            'count' => count($images)
847          ),
848       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
849          ws_std_get_image_xml_attributes() )
850      )
851    );
852}
853
854function ws_images_setPrivacyLevel($params, &$service)
855{
856  if (!is_admin() || is_adviser() )
857  {
858    return new PwgError(401, 'Access denied');
859  }
860  if ( empty($params['image_id']) )
861  {
862    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
863  }
864  global $conf;
865  if ( !in_array( (int)$params['level'], $conf['available_permission_levels']) )
866  {
867    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid level");
868  }
869  $query = '
870UPDATE '.IMAGES_TABLE.'
871  SET level='.(int)$params['level'].'
872  WHERE id IN ('.implode(',',$params['image_id']).')';
873  $result = pwg_query($query);
874  $affected_rows = mysql_affected_rows();
875  if ($affected_rows)
876  {
877    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
878    invalidate_user_cache();
879  }
880  return $affected_rows;
881}
882
883function ws_images_add($params, &$service)
884{
885  global $conf;
886  if (!is_admin() || is_adviser() )
887  {
888    return new PwgError(401, 'Access denied');
889  }
890
891  // name
892  // category_id
893  // file_content
894  // file_sum
895  // thumbnail_content
896  // thumbnail_sum
897  // rank
898
899  // $fh_log = fopen('/tmp/php.log', 'w');
900  // fwrite($fh_log, time()."\n");
901  // fwrite($fh_log, 'input rank :'.$params['rank']."\n");
902  // fwrite($fh_log, 'input:  '.$params['file_sum']."\n");
903  // fwrite($fh_log, 'input:  '.$params['thumbnail_sum']."\n");
904
905  // does the image already exists ?
906  $query = '
907SELECT
908    COUNT(*) AS counter
909  FROM '.IMAGES_TABLE.'
910  WHERE md5sum = \''.$params['file_sum'].'\'
911;';
912  list($counter) = mysql_fetch_row(pwg_query($query));
913  if ($counter != 0) {
914    return new PwgError(500, 'file already exists');
915  }
916
917  // current date
918  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
919  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
920
921  // upload directory hierarchy
922  $upload_dir = sprintf(
923    PHPWG_ROOT_PATH.'upload/%s/%s/%s',
924    $year,
925    $month,
926    $day
927    );
928
929  //fwrite($fh_log, $upload_dir."\n");
930
931  // create the upload directory tree if not exists
932  if (!is_dir($upload_dir)) {
933    umask(0000);
934    $recursive = true;
935    mkdir($upload_dir, 0777, $recursive);
936  }
937
938  // compute file path
939  $date_string = preg_replace('/[^\d]/', '', $dbnow);
940  $random_string = substr($params['file_sum'], 0, 8);
941  $filename_wo_ext = $date_string.'-'.$random_string;
942  $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
943
944  // dump the photo file
945  $fh_file = fopen($file_path, 'w');
946  fwrite($fh_file, base64_decode($params['file_content']));
947  fclose($fh_file);
948  chmod($file_path, 0644);
949
950  // check dumped file md5sum against expected md5sum
951  $dumped_md5 = md5_file($file_path);
952  if ($dumped_md5 != $params['file_sum']) {
953    return new PwgError(500, 'file transfer failed');
954  }
955
956  // thumbnail directory is a subdirectory of the photo file, hard coded
957  // "thumbnail"
958  $thumbnail_dir = $upload_dir.'/thumbnail';
959  if (!is_dir($thumbnail_dir)) {
960    umask(0000);
961    mkdir($thumbnail_dir, 0777);
962  }
963
964  // thumbnail path, the filename may use a prefix and the extension is
965  // always "jpg" (no matter what the real file format is)
966  $thumbnail_path = sprintf(
967    '%s/%s%s.%s',
968    $thumbnail_dir,
969    $conf['prefix_thumbnail'],
970    $filename_wo_ext,
971    'jpg'
972    );
973
974  // dump the thumbnail
975  $fh_thumbnail = fopen($thumbnail_path, 'w');
976  fwrite($fh_thumbnail, base64_decode($params['thumbnail_content']));
977  fclose($fh_thumbnail);
978  chmod($thumbnail_path, 0644);
979
980  // check dumped thumbnail md5
981  $dumped_md5 = md5_file($thumbnail_path);
982  if ($dumped_md5 != $params['thumbnail_sum']) {
983    return new PwgError(500, 'thumbnail transfer failed');
984  }
985
986  // high resolution
987  if (isset($params['high_content']))
988  {
989    // high resolution directory is a subdirectory of the photo file, hard
990    // coded "pwg_high"
991    $high_dir = $upload_dir.'/pwg_high';
992    if (!is_dir($high_dir)) {
993      umask(0000);
994      mkdir($high_dir, 0777);
995    }
996
997    // high resolution path, same name as web size file
998    $high_path = sprintf(
999      '%s/%s.%s',
1000      $high_dir,
1001      $filename_wo_ext,
1002      'jpg'
1003      );
1004
1005    // dump the high resolution file
1006    $fh_high = fopen($high_path, 'w');
1007    fwrite($fh_high, base64_decode($params['high_content']));
1008    fclose($fh_high);
1009    chmod($high_path, 0644);
1010
1011    // check dumped thumbnail md5
1012    $dumped_md5 = md5_file($high_path);
1013    if ($dumped_md5 != $params['high_sum']) {
1014      return new PwgError(500, 'high resolution transfer failed');
1015    }
1016
1017    $high_filesize = floor(filesize($high_path)/1024);
1018  }
1019
1020  list($width, $height) = getimagesize($file_path);
1021
1022  // database registration
1023  $insert = array(
1024    'file' => $filename_wo_ext.'.jpg',
1025    'date_available' => $dbnow,
1026    'tn_ext' => 'jpg',
1027    'name' => $params['name'],
1028    'path' => $file_path,
1029    'filesize' => floor(filesize($file_path)/1024),
1030    'width' => $width,
1031    'height' => $height,
1032    'md5sum' => $params['file_sum'],
1033    );
1034
1035  $info_columns = array(
1036    'name',
1037    'author',
1038    'comment',
1039    'level',
1040    'date_creation',
1041    );
1042
1043  foreach ($info_columns as $key)
1044  {
1045    if (isset($params[$key]))
1046    {
1047      $insert[$key] = $params[$key];
1048    }
1049  }
1050
1051  if (isset($params['high_content']))
1052  {
1053    $insert['has_high'] = 'true';
1054    $insert['high_filesize'] = $high_filesize;
1055  }
1056
1057  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1058  mass_inserts(
1059    IMAGES_TABLE,
1060    array_keys($insert),
1061    array($insert)
1062    );
1063
1064  $image_id = mysql_insert_id();
1065
1066  // let's add links between the image and the categories
1067  //
1068  // $params['categories'] should look like 123,12;456,auto;789 which means:
1069  //
1070  // 1. associate with category 123 on rank 12
1071  // 2. associate with category 456 on automatic rank
1072  // 3. associate with category 789 on automatic rank
1073  if (isset($params['categories']))
1074  {
1075    $cat_ids = array();
1076    $rank_on_category = array();
1077    $search_current_ranks = false;
1078
1079    $tokens = explode(';', $params['categories']);
1080    foreach ($tokens as $token)
1081    {
1082      list($cat_id, $rank) = explode(',', $token);
1083
1084      array_push($cat_ids, $cat_id);
1085
1086      if (!isset($rank))
1087      {
1088        $rank = 'auto';
1089      }
1090      $rank_on_category[$cat_id] = $rank;
1091
1092      if ($rank == 'auto')
1093      {
1094        $search_current_ranks = true;
1095      }
1096    }
1097
1098    $cat_ids = array_unique($cat_ids);
1099
1100    if (count($cat_ids) > 0)
1101    {
1102      if ($search_current_ranks)
1103      {
1104        $query = '
1105SELECT
1106    category_id,
1107    MAX(rank) AS max_rank
1108  FROM '.IMAGE_CATEGORY_TABLE.'
1109  WHERE rank IS NOT NULL
1110    AND category_id IN ('.implode(',', $cat_ids).')
1111  GROUP BY category_id
1112;';
1113        $current_rank_of = simple_hash_from_query(
1114          $query,
1115          'category_id',
1116          'max_rank'
1117          );
1118
1119        foreach ($cat_ids as $cat_id)
1120        {
1121          if ('auto' == $rank_on_category[$cat_id])
1122          {
1123            $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
1124          }
1125        }
1126      }
1127
1128      $inserts = array();
1129
1130      foreach ($cat_ids as $cat_id)
1131      {
1132        array_push(
1133          $inserts,
1134          array(
1135            'image_id' => $image_id,
1136            'category_id' => $cat_id,
1137            'rank' => $rank_on_category[$cat_id],
1138            )
1139          );
1140      }
1141
1142      mass_inserts(
1143        IMAGE_CATEGORY_TABLE,
1144        array_keys($inserts[0]),
1145        $inserts
1146        );
1147
1148      update_category($cat_ids);
1149    }
1150  }
1151
1152  // and now, let's create tag associations
1153  if (isset($params['tag_ids']))
1154  {
1155    set_tags(
1156      explode(',', $params['tag_ids']),
1157      $image_id
1158      );
1159  }
1160
1161  invalidate_user_cache();
1162
1163  // fclose($fh_log);
1164}
1165
1166/**
1167 * perform a login (web service method)
1168 */
1169function ws_session_login($params, &$service)
1170{
1171  global $conf;
1172
1173  if (!$service->isPost())
1174  {
1175    return new PwgError(405, "This method requires HTTP POST");
1176  }
1177  if (try_log_user($params['username'], $params['password'],false))
1178  {
1179    return true;
1180  }
1181  return new PwgError(999, 'Invalid username/password');
1182}
1183
1184
1185/**
1186 * performs a logout (web service method)
1187 */
1188function ws_session_logout($params, &$service)
1189{
1190  if (!is_a_guest())
1191  {
1192    logout_user();
1193  }
1194  return true;
1195}
1196
1197function ws_session_getStatus($params, &$service)
1198{
1199  global $user;
1200  $res = array();
1201  $res['username'] = is_a_guest() ? 'guest' : $user['username'];
1202  foreach ( array('status', 'template', 'theme', 'language') as $k )
1203  {
1204    $res[$k] = $user[$k];
1205  }
1206  $res['charset'] = get_pwg_charset();
1207  return $res;
1208}
1209
1210
1211/**
1212 * returns a list of tags (web service method)
1213 */
1214function ws_tags_getList($params, &$service)
1215{
1216  $tags = get_available_tags();
1217  if ($params['sort_by_counter'])
1218  {
1219    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1220  }
1221  else
1222  {
1223    usort($tags, 'tag_alpha_compare');
1224  }
1225  for ($i=0; $i<count($tags); $i++)
1226  {
1227    $tags[$i]['id'] = (int)$tags[$i]['id'];
1228    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1229    $tags[$i]['url'] = make_index_url(
1230        array(
1231          'section'=>'tags',
1232          'tags'=>array($tags[$i])
1233        )
1234      );
1235  }
1236  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
1237}
1238
1239/**
1240 * returns the list of tags as you can see them in administration (web
1241 * service method).
1242 *
1243 * Only admin can run this method and permissions are not taken into
1244 * account.
1245 */
1246function ws_tags_getAdminList($params, &$service)
1247{
1248  if (!is_admin())
1249  {
1250    return new PwgError(401, 'Access denied');
1251  }
1252
1253  $tags = get_all_tags();
1254  return array(
1255    'tags' => new PwgNamedArray(
1256      $tags,
1257      'tag',
1258      array(
1259        'name',
1260        'id',
1261        'url_name',
1262        )
1263      )
1264    );
1265}
1266
1267/**
1268 * returns a list of images for tags (web service method)
1269 */
1270function ws_tags_getImages($params, &$service)
1271{
1272  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1273  global $conf;
1274
1275  // first build all the tag_ids we are interested in
1276  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1277  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1278  $tags_by_id = array();
1279  foreach( $tags as $tag )
1280  {
1281    $tags['id'] = (int)$tag['id'];
1282    $tags_by_id[ $tag['id'] ] = $tag;
1283  }
1284  unset($tags);
1285  $tag_ids = array_keys($tags_by_id);
1286
1287
1288  $image_ids = array();
1289  $image_tag_map = array();
1290
1291  if ( !empty($tag_ids) )
1292  { // build list of image ids with associated tags per image
1293    if ($params['tag_mode_and'])
1294    {
1295      $image_ids = get_image_ids_for_tags( $tag_ids );
1296    }
1297    else
1298    {
1299      $query = '
1300SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
1301  FROM '.IMAGE_TAG_TABLE.'
1302  WHERE tag_id IN ('.implode(',',$tag_ids).')
1303  GROUP BY image_id';
1304      $result = pwg_query($query);
1305      while ( $row=mysql_fetch_assoc($result) )
1306      {
1307        $row['image_id'] = (int)$row['image_id'];
1308        array_push( $image_ids, $row['image_id'] );
1309        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1310      }
1311    }
1312  }
1313
1314  $images = array();
1315  if ( !empty($image_ids))
1316  {
1317    $where_clauses = ws_std_image_sql_filter($params);
1318    $where_clauses[] = get_sql_condition_FandF(
1319        array
1320          (
1321            'forbidden_categories' => 'category_id',
1322            'visible_categories' => 'category_id',
1323            'visible_images' => 'i.id'
1324          ),
1325        '', true
1326      );
1327    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
1328
1329    $order_by = ws_std_image_sql_order($params);
1330    if (empty($order_by))
1331    {
1332      $order_by = $conf['order_by'];
1333    }
1334    else
1335    {
1336      $order_by = 'ORDER BY '.$order_by;
1337    }
1338
1339    $query = '
1340SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
1341  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
1342  WHERE '. implode('
1343    AND ', $where_clauses).'
1344'.$order_by.'
1345LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
1346
1347    $result = pwg_query($query);
1348    while ($row = mysql_fetch_assoc($result))
1349    {
1350      $image = array();
1351      foreach ( array('id', 'width', 'height', 'hit') as $k )
1352      {
1353        if (isset($row[$k]))
1354        {
1355          $image[$k] = (int)$row[$k];
1356        }
1357      }
1358      foreach ( array('file', 'name', 'comment') as $k )
1359      {
1360        $image[$k] = $row[$k];
1361      }
1362      $image = array_merge( $image, ws_std_get_urls($row) );
1363
1364      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1365      $image_tags = array();
1366      foreach ($image_tag_ids as $tag_id)
1367      {
1368        $url = make_index_url(
1369                 array(
1370                  'section'=>'tags',
1371                  'tags'=> array($tags_by_id[$tag_id])
1372                )
1373              );
1374        $page_url = make_picture_url(
1375                 array(
1376                  'section'=>'tags',
1377                  'tags'=> array($tags_by_id[$tag_id]),
1378                  'image_id' => $row['id'],
1379                  'image_file' => $row['file'],
1380                )
1381              );
1382        array_push($image_tags, array(
1383                'id' => (int)$tag_id,
1384                'url' => $url,
1385                'page_url' => $page_url,
1386              )
1387            );
1388      }
1389      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1390              array('id','url_name','url','page_url')
1391            );
1392      array_push($images, $image);
1393    }
1394  }
1395
1396  return array( 'images' =>
1397    array (
1398      WS_XML_ATTRIBUTES =>
1399        array(
1400            'page' => $params['page'],
1401            'per_page' => $params['per_page'],
1402            'count' => count($images)
1403          ),
1404       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1405          ws_std_get_image_xml_attributes() )
1406      )
1407    );
1408}
1409
1410function ws_categories_add($params, &$service)
1411{
1412  if (!is_admin() or is_adviser())
1413  {
1414    return new PwgError(401, 'Access denied');
1415  }
1416
1417  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1418
1419  $creation_output = create_virtual_category(
1420    $params['name'],
1421    $params['parent']
1422    );
1423
1424  if (isset($creation_output['error']))
1425  {
1426    return new PwgError(500, $creation_output['error']);
1427  }
1428
1429  invalidate_user_cache();
1430
1431  return $creation_output;
1432}
1433
1434function ws_tags_add($params, &$service)
1435{
1436  if (!is_admin() or is_adviser())
1437  {
1438    return new PwgError(401, 'Access denied');
1439  }
1440
1441  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1442
1443  $creation_output = create_tag($params['name']);
1444
1445  if (isset($creation_output['error']))
1446  {
1447    return new PwgError(500, $creation_output['error']);
1448  }
1449
1450  return $creation_output;
1451}
1452
1453function ws_images_exist($params, &$service)
1454{
1455  if (!is_admin() or is_adviser())
1456  {
1457    return new PwgError(401, 'Access denied');
1458  }
1459
1460  // search among photos the list of photos already added, based on md5sum
1461  // list
1462  $md5sums = preg_split(
1463    '/[\s,;\|]/',
1464    $params['md5sum_list'],
1465    -1,
1466    PREG_SPLIT_NO_EMPTY
1467    );
1468
1469  $query = '
1470SELECT
1471    id,
1472    md5sum
1473  FROM '.IMAGES_TABLE.'
1474  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
1475;';
1476  $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
1477
1478  $result = array();
1479
1480  foreach ($md5sums as $md5sum)
1481  {
1482    $result[$md5sum] = null;
1483    if (isset($id_of_md5[$md5sum]))
1484    {
1485      $result[$md5sum] = $id_of_md5[$md5sum];
1486    }
1487  }
1488
1489  return $result;
1490}
1491?>
Note: See TracBrowser for help on using the repository browser.