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

Last change on this file since 2644 was 2644, checked in by plg, 16 years ago

bug 880 fixed: pwg.categories.add invalidate the user cache so that the new
category is added to the user category tree.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 35.8 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 transfert 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 transfert failed');
984  }
985
986  // fwrite($fh_log, 'output: '.md5_file($file_path)."\n");
987  // fwrite($fh_log, 'output: '.md5_file($thumbnail_path)."\n");
988
989  list($width, $height) = getimagesize($file_path);
990
991  // database registration
992  $insert = array(
993    'file' => $filename_wo_ext.'.jpg',
994    'date_available' => $dbnow,
995    'tn_ext' => 'jpg',
996    'name' => $params['name'],
997    'path' => $file_path,
998    'filesize' => floor(filesize($file_path)/1024),
999    'width' => $width,
1000    'height' => $height,
1001    'md5sum' => $params['file_sum'],
1002    );
1003
1004  $info_columns = array(
1005    'name',
1006    'author',
1007    'comment',
1008    'level',
1009    'date_creation',
1010    );
1011
1012  foreach ($info_columns as $key)
1013  {
1014    if (isset($params[$key]))
1015    {
1016      $insert[$key] = $params[$key];
1017    }
1018  }
1019
1020  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1021  mass_inserts(
1022    IMAGES_TABLE,
1023    array_keys($insert),
1024    array($insert)
1025    );
1026
1027  $image_id = mysql_insert_id();
1028
1029  // let's add links between the image and the categories
1030  //
1031  // $params['categories'] should look like 123,12;456,auto;789 which means:
1032  //
1033  // 1. associate with category 123 on rank 12
1034  // 2. associate with category 456 on automatic rank
1035  // 3. associate with category 789 on automatic rank
1036  if (isset($params['categories']))
1037  {
1038    $cat_ids = array();
1039    $rank_on_category = array();
1040    $search_current_ranks = false;
1041
1042    $tokens = explode(';', $params['categories']);
1043    foreach ($tokens as $token)
1044    {
1045      list($cat_id, $rank) = explode(',', $token);
1046
1047      array_push($cat_ids, $cat_id);
1048
1049      if (!isset($rank))
1050      {
1051        $rank = 'auto';
1052      }
1053      $rank_on_category[$cat_id] = $rank;
1054
1055      if ($rank == 'auto')
1056      {
1057        $search_current_ranks = true;
1058      }
1059    }
1060
1061    $cat_ids = array_unique($cat_ids);
1062
1063    if (count($cat_ids) > 0)
1064    {
1065      if ($search_current_ranks)
1066      {
1067        $query = '
1068SELECT
1069    category_id,
1070    MAX(rank) AS max_rank
1071  FROM '.IMAGE_CATEGORY_TABLE.'
1072  WHERE rank IS NOT NULL
1073    AND category_id IN ('.implode(',', $cat_ids).')
1074  GROUP BY category_id
1075;';
1076        $current_rank_of = simple_hash_from_query(
1077          $query,
1078          'category_id',
1079          'max_rank'
1080          );
1081
1082        foreach ($cat_ids as $cat_id)
1083        {
1084          if ('auto' == $rank_on_category[$cat_id])
1085          {
1086          $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
1087          }
1088        }
1089      }
1090
1091      $inserts = array();
1092
1093      foreach ($cat_ids as $cat_id)
1094      {
1095        array_push(
1096          $inserts,
1097          array(
1098            'image_id' => $image_id,
1099            'category_id' => $cat_id,
1100            'rank' => $rank_on_category[$cat_id],
1101            )
1102          );
1103      }
1104
1105      mass_inserts(
1106        IMAGE_CATEGORY_TABLE,
1107        array_keys($inserts[0]),
1108        $inserts
1109        );
1110    }
1111  }
1112
1113  // and now, let's create tag associations
1114  if (isset($params['tag_ids']))
1115  {
1116    set_tags(
1117      explode(',', $params['tag_ids']),
1118      $image_id
1119      );
1120  }
1121
1122  invalidate_user_cache();
1123
1124  // fclose($fh_log);
1125}
1126
1127/**
1128 * perform a login (web service method)
1129 */
1130function ws_session_login($params, &$service)
1131{
1132  global $conf;
1133
1134  if (!$service->isPost())
1135  {
1136    return new PwgError(405, "This method requires HTTP POST");
1137  }
1138  if (try_log_user($params['username'], $params['password'],false))
1139  {
1140    return true;
1141  }
1142  return new PwgError(999, 'Invalid username/password');
1143}
1144
1145
1146/**
1147 * performs a logout (web service method)
1148 */
1149function ws_session_logout($params, &$service)
1150{
1151  global $user, $conf;
1152  if (!is_a_guest())
1153  {
1154    $_SESSION = array();
1155    session_unset();
1156    session_destroy();
1157    setcookie(session_name(),'',0,
1158        ini_get('session.cookie_path'),
1159        ini_get('session.cookie_domain')
1160      );
1161    setcookie($conf['remember_me_name'], '', 0, cookie_path());
1162  }
1163  return true;
1164}
1165
1166function ws_session_getStatus($params, &$service)
1167{
1168  global $user;
1169  $res = array();
1170  $res['username'] = is_a_guest() ? 'guest' : $user['username'];
1171  foreach ( array('status', 'template', 'theme', 'language') as $k )
1172  {
1173    $res[$k] = $user[$k];
1174  }
1175  $res['charset'] = get_pwg_charset();
1176  return $res;
1177}
1178
1179
1180/**
1181 * returns a list of tags (web service method)
1182 */
1183function ws_tags_getList($params, &$service)
1184{
1185  $tags = get_available_tags();
1186  if ($params['sort_by_counter'])
1187  {
1188    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1189  }
1190  else
1191  {
1192    usort($tags, 'tag_alpha_compare');
1193  }
1194  for ($i=0; $i<count($tags); $i++)
1195  {
1196    $tags[$i]['id'] = (int)$tags[$i]['id'];
1197    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1198    $tags[$i]['url'] = make_index_url(
1199        array(
1200          'section'=>'tags',
1201          'tags'=>array($tags[$i])
1202        )
1203      );
1204  }
1205  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
1206}
1207
1208/**
1209 * returns the list of tags as you can see them in administration (web
1210 * service method).
1211 *
1212 * Only admin can run this method and permissions are not taken into
1213 * account.
1214 */
1215function ws_tags_getAdminList($params, &$service)
1216{
1217  if (!is_admin())
1218  {
1219    return new PwgError(401, 'Access denied');
1220  }
1221
1222  $tags = get_all_tags();
1223  return array(
1224    'tags' => new PwgNamedArray(
1225      $tags,
1226      'tag',
1227      array(
1228        'name',
1229        'id',
1230        'url_name',
1231        )
1232      )
1233    );
1234}
1235
1236/**
1237 * returns a list of images for tags (web service method)
1238 */
1239function ws_tags_getImages($params, &$service)
1240{
1241  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1242  global $conf;
1243
1244  // first build all the tag_ids we are interested in
1245  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1246  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1247  $tags_by_id = array();
1248  foreach( $tags as $tag )
1249  {
1250    $tags['id'] = (int)$tag['id'];
1251    $tags_by_id[ $tag['id'] ] = $tag;
1252  }
1253  unset($tags);
1254  $tag_ids = array_keys($tags_by_id);
1255
1256
1257  $image_ids = array();
1258  $image_tag_map = array();
1259
1260  if ( !empty($tag_ids) )
1261  { // build list of image ids with associated tags per image
1262    if ($params['tag_mode_and'])
1263    {
1264      $image_ids = get_image_ids_for_tags( $tag_ids );
1265    }
1266    else
1267    {
1268      $query = '
1269SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
1270  FROM '.IMAGE_TAG_TABLE.'
1271  WHERE tag_id IN ('.implode(',',$tag_ids).')
1272  GROUP BY image_id';
1273      $result = pwg_query($query);
1274      while ( $row=mysql_fetch_assoc($result) )
1275      {
1276        $row['image_id'] = (int)$row['image_id'];
1277        array_push( $image_ids, $row['image_id'] );
1278        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1279      }
1280    }
1281  }
1282
1283  $images = array();
1284  if ( !empty($image_ids))
1285  {
1286    $where_clauses = ws_std_image_sql_filter($params);
1287    $where_clauses[] = get_sql_condition_FandF(
1288        array
1289          (
1290            'forbidden_categories' => 'category_id',
1291            'visible_categories' => 'category_id',
1292            'visible_images' => 'i.id'
1293          ),
1294        '', true
1295      );
1296    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
1297
1298    $order_by = ws_std_image_sql_order($params);
1299    if (empty($order_by))
1300    {
1301      $order_by = $conf['order_by'];
1302    }
1303    else
1304    {
1305      $order_by = 'ORDER BY '.$order_by;
1306    }
1307
1308    $query = '
1309SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
1310  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
1311  WHERE '. implode('
1312    AND ', $where_clauses).'
1313'.$order_by.'
1314LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
1315
1316    $result = pwg_query($query);
1317    while ($row = mysql_fetch_assoc($result))
1318    {
1319      $image = array();
1320      foreach ( array('id', 'width', 'height', 'hit') as $k )
1321      {
1322        if (isset($row[$k]))
1323        {
1324          $image[$k] = (int)$row[$k];
1325        }
1326      }
1327      foreach ( array('file', 'name', 'comment') as $k )
1328      {
1329        $image[$k] = $row[$k];
1330      }
1331      $image = array_merge( $image, ws_std_get_urls($row) );
1332
1333      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1334      $image_tags = array();
1335      foreach ($image_tag_ids as $tag_id)
1336      {
1337        $url = make_index_url(
1338                 array(
1339                  'section'=>'tags',
1340                  'tags'=> array($tags_by_id[$tag_id])
1341                )
1342              );
1343        $page_url = make_picture_url(
1344                 array(
1345                  'section'=>'tags',
1346                  'tags'=> array($tags_by_id[$tag_id]),
1347                  'image_id' => $row['id'],
1348                  'image_file' => $row['file'],
1349                )
1350              );
1351        array_push($image_tags, array(
1352                'id' => (int)$tag_id,
1353                'url' => $url,
1354                'page_url' => $page_url,
1355              )
1356            );
1357      }
1358      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1359              array('id','url_name','url','page_url')
1360            );
1361      array_push($images, $image);
1362    }
1363  }
1364
1365  return array( 'images' =>
1366    array (
1367      WS_XML_ATTRIBUTES =>
1368        array(
1369            'page' => $params['page'],
1370            'per_page' => $params['per_page'],
1371            'count' => count($images)
1372          ),
1373       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1374          ws_std_get_image_xml_attributes() )
1375      )
1376    );
1377}
1378
1379function ws_categories_add($params, &$service)
1380{
1381  if (!is_admin() or is_adviser())
1382  {
1383    return new PwgError(401, 'Access denied');
1384  }
1385
1386  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1387
1388  $creation_output = create_virtual_category(
1389    $params['name'],
1390    $params['parent']
1391    );
1392
1393  if (isset($creation_output['error']))
1394  {
1395    return new PwgError(500, $creation_output['error']);
1396  }
1397
1398  invalidate_user_cache();
1399 
1400  return $creation_output;
1401}
1402
1403function ws_tags_add($params, &$service)
1404{
1405  if (!is_admin() or is_adviser())
1406  {
1407    return new PwgError(401, 'Access denied');
1408  }
1409
1410  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1411
1412  $creation_output = create_tag($params['name']);
1413
1414  if (isset($creation_output['error']))
1415  {
1416    return new PwgError(500, $creation_output['error']);
1417  }
1418
1419  return $creation_output;
1420}
1421?>
Note: See TracBrowser for help on using the repository browser.