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

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

new: webservice method pwg.categories.getAdminList was added so that pLoader
can see the list of categories as you can see in the administration
interface : not filtered by individual permissions.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 32.4 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, $calling_partner_id;
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','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  // current date
906  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
907  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
908
909  // upload directory hierarchy
910  $upload_dir = sprintf(
911    PHPWG_ROOT_PATH.'upload/%s/%s/%s',
912    $year,
913    $month,
914    $day
915    );
916
917  //fwrite($fh_log, $upload_dir."\n");
918
919  // create the upload directory tree if not exists
920  if (!is_dir($upload_dir)) {
921    umask(0000);
922    $recursive = true;
923    mkdir($upload_dir, 0777, $recursive);
924  }
925
926  // compute file path
927  $date_string = preg_replace('/[^\d]/', '', $dbnow);
928  $random_string = substr($params['file_sum'], 0, 8);
929  $filename_wo_ext = $date_string.'-'.$random_string;
930  $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
931
932  // dump the photo file
933  $fh_file = fopen($file_path, 'w');
934  fwrite($fh_file, base64_decode($params['file_content']));
935  fclose($fh_file);
936  chmod($file_path, 0644);
937
938  // check dumped file md5sum against expected md5sum
939  $dumped_md5 = md5_file($file_path);
940  if ($dumped_md5 != $params['file_sum']) {
941    return new PwgError(500, 'file transfert failed');
942  }
943
944  // thumbnail directory is a subdirectory of the photo file, hard coded
945  // "thumbnail"
946  $thumbnail_dir = $upload_dir.'/thumbnail';
947  if (!is_dir($thumbnail_dir)) {
948    umask(0000);
949    mkdir($thumbnail_dir, 0777);
950  }
951
952  // thumbnail path, the filename may use a prefix and the extension is
953  // always "jpg" (no matter what the real file format is)
954  $thumbnail_path = sprintf(
955    '%s/%s%s.%s',
956    $thumbnail_dir,
957    $conf['prefix_thumbnail'],
958    $filename_wo_ext,
959    'jpg'
960    );
961
962  // dump the thumbnail
963  $fh_thumbnail = fopen($thumbnail_path, 'w');
964  fwrite($fh_thumbnail, base64_decode($params['thumbnail_content']));
965  fclose($fh_thumbnail);
966  chmod($thumbnail_path, 0644);
967
968  // check dumped thumbnail md5
969  $dumped_md5 = md5_file($thumbnail_path);
970  if ($dumped_md5 != $params['thumbnail_sum']) {
971    return new PwgError(500, 'thumbnail transfert failed');
972  }
973
974  // fwrite($fh_log, 'output: '.md5_file($file_path)."\n");
975  // fwrite($fh_log, 'output: '.md5_file($thumbnail_path)."\n");
976
977  // database registration
978  $insert = array(
979    'file' => $filename_wo_ext.'.jpg',
980    'date_available' => $dbnow,
981    'tn_ext' => 'jpg',
982    'name' => $params['name'],
983    'path' => $file_path,
984    );
985
986  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
987  mass_inserts(
988    IMAGES_TABLE,
989    array_keys($insert),
990    array($insert)
991    );
992
993  $image_id = mysql_insert_id();
994
995  $insert = array(
996    'category_id' => $params['category_id'],
997    'image_id' => $image_id,
998    );
999
1000  if ('auto' == $params['rank'])
1001  {
1002    $query = '
1003SELECT
1004    MAX(rank) AS max_rank
1005  FROM '.IMAGE_CATEGORY_TABLE.'
1006  WHERE rank IS NOT NULL
1007    AND category_id = '.$params['category_id'].'
1008;';
1009    $row = mysql_fetch_assoc(pwg_query($query));
1010    $insert['rank'] = isset($row['max_rank']) ? $row['max_rank']+1 : 1;
1011  }
1012  else if (is_numeric($params['rank']))
1013  {
1014    $insert['rank'] = (int)$params['rank'];
1015  }
1016 
1017  mass_inserts(
1018    IMAGE_CATEGORY_TABLE,
1019    array_keys($insert),
1020    array($insert)
1021    );
1022
1023  invalidate_user_cache();
1024
1025  // fclose($fh_log);
1026}
1027
1028/**
1029 * perform a login (web service method)
1030 */
1031function ws_session_login($params, &$service)
1032{
1033  global $conf;
1034
1035  if (!$service->isPost())
1036  {
1037    return new PwgError(405, "This method requires HTTP POST");
1038  }
1039  if (try_log_user($params['username'], $params['password'],false))
1040  {
1041    return true;
1042  }
1043  return new PwgError(999, 'Invalid username/password');
1044}
1045
1046
1047/**
1048 * performs a logout (web service method)
1049 */
1050function ws_session_logout($params, &$service)
1051{
1052  global $user, $conf;
1053  if (!is_a_guest())
1054  {
1055    $_SESSION = array();
1056    session_unset();
1057    session_destroy();
1058    setcookie(session_name(),'',0,
1059        ini_get('session.cookie_path'),
1060        ini_get('session.cookie_domain')
1061      );
1062    setcookie($conf['remember_me_name'], '', 0, cookie_path());
1063  }
1064  return true;
1065}
1066
1067function ws_session_getStatus($params, &$service)
1068{
1069  global $user;
1070  $res = array();
1071  $res['username'] = is_a_guest() ? 'guest' : $user['username'];
1072  foreach ( array('status', 'template', 'theme', 'language') as $k )
1073  {
1074    $res[$k] = $user[$k];
1075  }
1076  $res['charset'] = get_pwg_charset();
1077  return $res;
1078}
1079
1080
1081/**
1082 * returns a list of tags (web service method)
1083 */
1084function ws_tags_getList($params, &$service)
1085{
1086  $tags = get_available_tags();
1087  if ($params['sort_by_counter'])
1088  {
1089    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1090  }
1091  else
1092  {
1093    usort($tags, 'tag_alpha_compare');
1094  }
1095  for ($i=0; $i<count($tags); $i++)
1096  {
1097    $tags[$i]['id'] = (int)$tags[$i]['id'];
1098    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1099    $tags[$i]['url'] = make_index_url(
1100        array(
1101          'section'=>'tags',
1102          'tags'=>array($tags[$i])
1103        )
1104      );
1105  }
1106  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'counter' )) );
1107}
1108
1109
1110/**
1111 * returns a list of images for tags (web service method)
1112 */
1113function ws_tags_getImages($params, &$service)
1114{
1115  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1116  global $conf;
1117
1118  // first build all the tag_ids we are interested in
1119  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1120  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1121  $tags_by_id = array();
1122  foreach( $tags as $tag )
1123  {
1124    $tags['id'] = (int)$tag['id'];
1125    $tags_by_id[ $tag['id'] ] = $tag;
1126  }
1127  unset($tags);
1128  $tag_ids = array_keys($tags_by_id);
1129
1130
1131  $image_ids = array();
1132  $image_tag_map = array();
1133
1134  if ( !empty($tag_ids) )
1135  { // build list of image ids with associated tags per image
1136    if ($params['tag_mode_and'])
1137    {
1138      $image_ids = get_image_ids_for_tags( $tag_ids );
1139    }
1140    else
1141    {
1142      $query = '
1143SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
1144  FROM '.IMAGE_TAG_TABLE.'
1145  WHERE tag_id IN ('.implode(',',$tag_ids).')
1146  GROUP BY image_id';
1147      $result = pwg_query($query);
1148      while ( $row=mysql_fetch_assoc($result) )
1149      {
1150        $row['image_id'] = (int)$row['image_id'];
1151        array_push( $image_ids, $row['image_id'] );
1152        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1153      }
1154    }
1155  }
1156
1157  $images = array();
1158  if ( !empty($image_ids))
1159  {
1160    $where_clauses = ws_std_image_sql_filter($params);
1161    $where_clauses[] = get_sql_condition_FandF(
1162        array
1163          (
1164            'forbidden_categories' => 'category_id',
1165            'visible_categories' => 'category_id',
1166            'visible_images' => 'i.id'
1167          ),
1168        '', true
1169      );
1170    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
1171
1172    $order_by = ws_std_image_sql_order($params);
1173    if (empty($order_by))
1174    {
1175      $order_by = $conf['order_by'];
1176    }
1177    else
1178    {
1179      $order_by = 'ORDER BY '.$order_by;
1180    }
1181
1182    $query = '
1183SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
1184  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
1185  WHERE '. implode('
1186    AND ', $where_clauses).'
1187'.$order_by.'
1188LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
1189
1190    $result = pwg_query($query);
1191    while ($row = mysql_fetch_assoc($result))
1192    {
1193      $image = array();
1194      foreach ( array('id', 'width', 'height', 'hit') as $k )
1195      {
1196        if (isset($row[$k]))
1197        {
1198          $image[$k] = (int)$row[$k];
1199        }
1200      }
1201      foreach ( array('file', 'name', 'comment') as $k )
1202      {
1203        $image[$k] = $row[$k];
1204      }
1205      $image = array_merge( $image, ws_std_get_urls($row) );
1206
1207      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1208      $image_tags = array();
1209      foreach ($image_tag_ids as $tag_id)
1210      {
1211        $url = make_index_url(
1212                 array(
1213                  'section'=>'tags',
1214                  'tags'=> array($tags_by_id[$tag_id])
1215                )
1216              );
1217        $page_url = make_picture_url(
1218                 array(
1219                  'section'=>'tags',
1220                  'tags'=> array($tags_by_id[$tag_id]),
1221                  'image_id' => $row['id'],
1222                  'image_file' => $row['file'],
1223                )
1224              );
1225        array_push($image_tags, array(
1226                'id' => (int)$tag_id,
1227                'url' => $url,
1228                'page_url' => $page_url,
1229              )
1230            );
1231      }
1232      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1233              array('id','url_name','url','page_url')
1234            );
1235      array_push($images, $image);
1236    }
1237  }
1238
1239  return array( 'images' =>
1240    array (
1241      WS_XML_ATTRIBUTES =>
1242        array(
1243            'page' => $params['page'],
1244            'per_page' => $params['per_page'],
1245            'count' => count($images)
1246          ),
1247       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1248          ws_std_get_image_xml_attributes() )
1249      )
1250    );
1251}
1252
1253?>
Note: See TracBrowser for help on using the repository browser.