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

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

improvement: instead of sending the images_max_rank of each category in
pwg.categories.getList so that you can correctly set the rank in
pwg.images.add, the rank is calculated automatically in pwg.images.add so
that the image is added at the end of the category.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 31.3 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/**
441 * returns detailed information for an element (web service method)
442 */
443function ws_images_addComment($params, &$service)
444{
445  if (!$service->isPost())
446  {
447    return new PwgError(405, "This method requires HTTP POST");
448  }
449  $params['image_id'] = (int)$params['image_id'];
450  $query = '
451SELECT DISTINCT image_id
452  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
453  WHERE commentable="true"
454    AND image_id='.$params['image_id'].
455    get_sql_condition_FandF(
456      array(
457        'forbidden_categories' => 'id',
458        'visible_categories' => 'id',
459        'visible_images' => 'image_id'
460      ),
461      ' AND'
462    );
463  if ( !mysql_num_rows( pwg_query( $query ) ) )
464  {
465    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
466  }
467
468  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
469
470  $comm = array(
471    'author' => trim( stripslashes($params['author']) ),
472    'content' => trim( stripslashes($params['content']) ),
473    'image_id' => $params['image_id'],
474   );
475
476  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
477
478  $comment_action = insert_user_comment(
479      $comm, $params['key'], $infos
480    );
481
482  switch ($comment_action)
483  {
484    case 'reject':
485      array_push($infos, l10n('comment_not_added') );
486      return new PwgError(403, implode("\n", $infos) );
487    case 'validate':
488    case 'moderate':
489      $ret = array(
490          'id' => $comm['id'],
491          'validation' => $comment_action=='validate',
492        );
493      return new PwgNamedStruct(
494          'comment',
495          $ret,
496          null, array()
497        );
498    default:
499      return new PwgError(500, "Unknown comment action ".$comment_action );
500  }
501}
502
503/**
504 * returns detailed information for an element (web service method)
505 */
506function ws_images_getInfo($params, &$service)
507{
508  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
509  global $user, $conf;
510  $params['image_id'] = (int)$params['image_id'];
511  if ( $params['image_id']<=0 )
512  {
513    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
514  }
515
516  $query='
517SELECT * FROM '.IMAGES_TABLE.'
518  WHERE id='.$params['image_id'].
519    get_sql_condition_FandF(
520      array('visible_images' => 'id'),
521      ' AND'
522    ).'
523LIMIT 1';
524
525  $image_row = mysql_fetch_assoc(pwg_query($query));
526  if ($image_row==null)
527  {
528    return new PwgError(404, "image_id not found");
529  }
530  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
531
532  //-------------------------------------------------------- related categories
533  $query = '
534SELECT id, name, permalink, uppercats, global_rank, commentable
535  FROM '.IMAGE_CATEGORY_TABLE.'
536    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
537  WHERE image_id = '.$image_row['id'].
538  get_sql_condition_FandF(
539      array( 'forbidden_categories' => 'category_id' ),
540      ' AND'
541    ).'
542;';
543  $result = pwg_query($query);
544  $is_commentable = false;
545  $related_categories = array();
546  while ($row = mysql_fetch_assoc($result))
547  {
548    if ($row['commentable']=='true')
549    {
550      $is_commentable = true;
551    }
552    unset($row['commentable']);
553    $row['url'] = make_index_url(
554        array(
555          'category' => $row
556          )
557      );
558
559    $row['page_url'] = make_picture_url(
560        array(
561          'image_id' => $image_row['id'],
562          'image_file' => $image_row['file'],
563          'category' => $row
564          )
565      );
566    $row['id']=(int)$row['id'];
567    array_push($related_categories, $row);
568  }
569  usort($related_categories, 'global_rank_compare');
570  if ( empty($related_categories) )
571  {
572    return new PwgError(401, 'Access denied');
573  }
574
575  //-------------------------------------------------------------- related tags
576  $related_tags = get_common_tags( array($image_row['id']), -1 );
577  foreach( $related_tags as $i=>$tag)
578  {
579    $tag['url'] = make_index_url(
580        array(
581          'tags' => array($tag)
582          )
583      );
584    $tag['page_url'] = make_picture_url(
585        array(
586          'image_id' => $image_row['id'],
587          'image_file' => $image_row['file'],
588          'tags' => array($tag),
589          )
590      );
591    unset($tag['counter']);
592    $tag['id']=(int)$tag['id'];
593    $related_tags[$i]=$tag;
594  }
595  //------------------------------------------------------------- related rates
596  $query = '
597SELECT COUNT(rate) AS count
598     , ROUND(AVG(rate),2) AS average
599     , ROUND(STD(rate),2) AS stdev
600  FROM '.RATE_TABLE.'
601  WHERE element_id = '.$image_row['id'].'
602;';
603  $rating = mysql_fetch_assoc(pwg_query($query));
604  $rating['count'] = (int)$rating['count'];
605
606  //---------------------------------------------------------- related comments
607  $related_comments = array();
608
609  $where_comments = 'image_id = '.$image_row['id'];
610  if ( !is_admin() )
611  {
612    $where_comments .= '
613    AND validated="true"';
614  }
615
616  $query = '
617SELECT COUNT(id) nb_comments
618  FROM '.COMMENTS_TABLE.'
619  WHERE '.$where_comments;
620  list($nb_comments) = array_from_query($query, 'nb_comments');
621  $nb_comments = (int)$nb_comments;
622
623  if ( $nb_comments>0 and $params['comments_per_page']>0 )
624  {
625    $query = '
626SELECT id, date, author, content
627  FROM '.COMMENTS_TABLE.'
628  WHERE '.$where_comments.'
629  ORDER BY date
630  LIMIT '.$params['comments_per_page']*(int)$params['comments_page'].
631    ','.$params['comments_per_page'];
632
633    $result = pwg_query($query);
634    while ($row = mysql_fetch_assoc($result))
635    {
636      $row['id']=(int)$row['id'];
637      array_push($related_comments, $row);
638    }
639  }
640
641  $comment_post_data = null;
642  if ($is_commentable and
643      (!is_a_guest()
644        or (is_a_guest() and $conf['comments_forall'] )
645      )
646      )
647  {
648    include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
649    $comment_post_data['author'] = $user['username'];
650    $comment_post_data['key'] = get_comment_post_key($params['image_id']);
651  }
652
653  $ret = $image_row;
654  foreach ( array('id','width','height','hit','filesize') as $k )
655  {
656    if (isset($ret[$k]))
657    {
658      $ret[$k] = (int)$ret[$k];
659    }
660  }
661  foreach ( array('path', 'storage_category_id') as $k )
662  {
663    unset($ret[$k]);
664  }
665
666  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
667  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
668  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','page_url') );
669  if ( isset($comment_post_data) )
670  {
671    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
672  }
673  $ret['comments'] = array(
674     WS_XML_ATTRIBUTES =>
675        array(
676          'page' => $params['comments_page'],
677          'per_page' => $params['comments_per_page'],
678          'count' => count($related_comments),
679          'nb_comments' => $nb_comments,
680        ),
681     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id','date') )
682      );
683
684  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
685}
686
687
688/**
689 * rates the image_id in the parameter
690 */
691function ws_images_Rate($params, &$service)
692{
693  $image_id = (int)$params['image_id'];
694  $query = '
695SELECT DISTINCT id FROM '.IMAGES_TABLE.'
696  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
697  WHERE id='.$image_id
698  .get_sql_condition_FandF(
699    array(
700        'forbidden_categories' => 'category_id',
701        'forbidden_images' => 'id',
702      ),
703    '    AND'
704    ).'
705    LIMIT 1';
706  if ( mysql_num_rows( pwg_query($query) )==0 )
707  {
708    return new PwgError(404, "Invalid image_id or access denied" );
709  }
710  $rate = (int)$params['rate'];
711  include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
712  $res = rate_picture( $image_id, $rate );
713  if ($res==false)
714  {
715    global $conf;
716    return new PwgError( 403, "Forbidden or rate not in ". implode(',',$conf['rate_items']));
717  }
718  return $res;
719}
720
721
722/**
723 * returns a list of elements corresponding to a query search
724 */
725function ws_images_search($params, &$service)
726{
727  global $page;
728  $images = array();
729  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
730  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
731
732  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
733  $order_by = ws_std_image_sql_order($params, 'i.');
734
735  $super_order_by = false;
736  if ( !empty($order_by) )
737  {
738    global $conf;
739    $conf['order_by'] = 'ORDER BY '.$order_by;
740    $super_order_by=true; // quick_search_result might be faster
741  }
742
743  $search_result = get_quick_search_results($params['query'],
744      $super_order_by,
745      implode(',', $where_clauses)
746    );
747
748  $image_ids = array_slice(
749      $search_result['items'],
750      $params['page']*$params['per_page'],
751      $params['per_page']
752    );
753
754  if ( count($image_ids) )
755  {
756    $query = '
757SELECT * FROM '.IMAGES_TABLE.'
758  WHERE id IN ('.implode(',', $image_ids).')';
759
760    $image_ids = array_flip($image_ids);
761    $result = pwg_query($query);
762    while ($row = mysql_fetch_assoc($result))
763    {
764      $image = array();
765      foreach ( array('id', 'width', 'height', 'hit') as $k )
766      {
767        if (isset($row[$k]))
768        {
769          $image[$k] = (int)$row[$k];
770        }
771      }
772      foreach ( array('file', 'name', 'comment') as $k )
773      {
774        $image[$k] = $row[$k];
775      }
776      $image = array_merge( $image, ws_std_get_urls($row) );
777      $images[$image_ids[$image['id']]] = $image;
778    }
779    ksort($images, SORT_NUMERIC);
780    $images = array_values($images);
781  }
782
783
784  return array( 'images' =>
785    array (
786      WS_XML_ATTRIBUTES =>
787        array(
788            'page' => $params['page'],
789            'per_page' => $params['per_page'],
790            'count' => count($images)
791          ),
792       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
793          ws_std_get_image_xml_attributes() )
794      )
795    );
796}
797
798function ws_images_setPrivacyLevel($params, &$service)
799{
800  if (!is_admin() || is_adviser() )
801  {
802    return new PwgError(401, 'Access denied');
803  }
804  if ( empty($params['image_id']) )
805  {
806    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
807  }
808  global $conf;
809  if ( !in_array( (int)$params['level'], $conf['available_permission_levels']) )
810  {
811    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid level");
812  }
813  $query = '
814UPDATE '.IMAGES_TABLE.'
815  SET level='.(int)$params['level'].'
816  WHERE id IN ('.implode(',',$params['image_id']).')';
817  $result = pwg_query($query);
818  $affected_rows = mysql_affected_rows();
819  if ($affected_rows)
820  {
821    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
822    invalidate_user_cache();
823  }
824  return $affected_rows;
825}
826
827function ws_images_add($params, &$service)
828{
829  global $conf;
830  if (!is_admin() || is_adviser() )
831  {
832    return new PwgError(401, 'Access denied');
833  }
834
835  // name
836  // category_id
837  // file_content
838  // file_sum
839  // thumbnail_content
840  // thumbnail_sum
841  // rank
842
843  // $fh_log = fopen('/tmp/php.log', 'w');
844  // fwrite($fh_log, time()."\n");
845  // fwrite($fh_log, 'input rank :'.$params['rank']."\n");
846  // fwrite($fh_log, 'input:  '.$params['file_sum']."\n");
847  // fwrite($fh_log, 'input:  '.$params['thumbnail_sum']."\n");
848
849  // current date
850  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
851  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
852
853  // upload directory hierarchy
854  $upload_dir = sprintf(
855    PHPWG_ROOT_PATH.'upload/%s/%s/%s',
856    $year,
857    $month,
858    $day
859    );
860
861  //fwrite($fh_log, $upload_dir."\n");
862
863  // create the upload directory tree if not exists
864  if (!is_dir($upload_dir)) {
865    umask(0000);
866    $recursive = true;
867    mkdir($upload_dir, 0777, $recursive);
868  }
869
870  // compute file path
871  $date_string = preg_replace('/[^\d]/', '', $dbnow);
872  $random_string = substr($params['file_sum'], 0, 8);
873  $filename_wo_ext = $date_string.'-'.$random_string;
874  $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
875
876  // dump the photo file
877  $fh_file = fopen($file_path, 'w');
878  fwrite($fh_file, base64_decode($params['file_content']));
879  fclose($fh_file);
880  chmod($file_path, 0644);
881
882  // check dumped file md5sum against expected md5sum
883  $dumped_md5 = md5_file($file_path);
884  if ($dumped_md5 != $params['file_sum']) {
885    return new PwgError(500, 'file transfert failed');
886  }
887
888  // thumbnail directory is a subdirectory of the photo file, hard coded
889  // "thumbnail"
890  $thumbnail_dir = $upload_dir.'/thumbnail';
891  if (!is_dir($thumbnail_dir)) {
892    umask(0000);
893    mkdir($thumbnail_dir, 0777);
894  }
895
896  // thumbnail path, the filename may use a prefix and the extension is
897  // always "jpg" (no matter what the real file format is)
898  $thumbnail_path = sprintf(
899    '%s/%s%s.%s',
900    $thumbnail_dir,
901    $conf['prefix_thumbnail'],
902    $filename_wo_ext,
903    'jpg'
904    );
905
906  // dump the thumbnail
907  $fh_thumbnail = fopen($thumbnail_path, 'w');
908  fwrite($fh_thumbnail, base64_decode($params['thumbnail_content']));
909  fclose($fh_thumbnail);
910  chmod($thumbnail_path, 0644);
911
912  // check dumped thumbnail md5
913  $dumped_md5 = md5_file($thumbnail_path);
914  if ($dumped_md5 != $params['thumbnail_sum']) {
915    return new PwgError(500, 'thumbnail transfert failed');
916  }
917
918  // fwrite($fh_log, 'output: '.md5_file($file_path)."\n");
919  // fwrite($fh_log, 'output: '.md5_file($thumbnail_path)."\n");
920
921  // database registration
922  $insert = array(
923    'file' => $filename_wo_ext.'.jpg',
924    'date_available' => $dbnow,
925    'tn_ext' => 'jpg',
926    'name' => $params['name'],
927    'path' => $file_path,
928    );
929
930  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
931  mass_inserts(
932    IMAGES_TABLE,
933    array_keys($insert),
934    array($insert)
935    );
936
937  $image_id = mysql_insert_id();
938
939  $insert = array(
940    'category_id' => $params['category_id'],
941    'image_id' => $image_id,
942    );
943
944  if ('auto' == $params['rank'])
945  {
946    $query = '
947SELECT
948    MAX(rank) AS max_rank
949  FROM '.IMAGE_CATEGORY_TABLE.'
950  WHERE rank IS NOT NULL
951    AND category_id = '.$params['category_id'].'
952;';
953    $row = mysql_fetch_assoc(pwg_query($query));
954    $insert['rank'] = isset($row['max_rank']) ? $row['max_rank']+1 : 1;
955  }
956  else if (is_numeric($params['rank']))
957  {
958    $insert['rank'] = (int)$params['rank'];
959  }
960 
961  mass_inserts(
962    IMAGE_CATEGORY_TABLE,
963    array_keys($insert),
964    array($insert)
965    );
966
967  invalidate_user_cache();
968
969  // fclose($fh_log);
970}
971
972/**
973 * perform a login (web service method)
974 */
975function ws_session_login($params, &$service)
976{
977  global $conf;
978
979  if (!$service->isPost())
980  {
981    return new PwgError(405, "This method requires HTTP POST");
982  }
983  if (try_log_user($params['username'], $params['password'],false))
984  {
985    return true;
986  }
987  return new PwgError(999, 'Invalid username/password');
988}
989
990
991/**
992 * performs a logout (web service method)
993 */
994function ws_session_logout($params, &$service)
995{
996  global $user, $conf;
997  if (!is_a_guest())
998  {
999    $_SESSION = array();
1000    session_unset();
1001    session_destroy();
1002    setcookie(session_name(),'',0,
1003        ini_get('session.cookie_path'),
1004        ini_get('session.cookie_domain')
1005      );
1006    setcookie($conf['remember_me_name'], '', 0, cookie_path());
1007  }
1008  return true;
1009}
1010
1011function ws_session_getStatus($params, &$service)
1012{
1013  global $user;
1014  $res = array();
1015  $res['username'] = is_a_guest() ? 'guest' : $user['username'];
1016  foreach ( array('status', 'template', 'theme', 'language') as $k )
1017  {
1018    $res[$k] = $user[$k];
1019  }
1020  $res['charset'] = get_pwg_charset();
1021  return $res;
1022}
1023
1024
1025/**
1026 * returns a list of tags (web service method)
1027 */
1028function ws_tags_getList($params, &$service)
1029{
1030  $tags = get_available_tags();
1031  if ($params['sort_by_counter'])
1032  {
1033    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1034  }
1035  else
1036  {
1037    usort($tags, 'tag_alpha_compare');
1038  }
1039  for ($i=0; $i<count($tags); $i++)
1040  {
1041    $tags[$i]['id'] = (int)$tags[$i]['id'];
1042    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1043    $tags[$i]['url'] = make_index_url(
1044        array(
1045          'section'=>'tags',
1046          'tags'=>array($tags[$i])
1047        )
1048      );
1049  }
1050  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'counter' )) );
1051}
1052
1053
1054/**
1055 * returns a list of images for tags (web service method)
1056 */
1057function ws_tags_getImages($params, &$service)
1058{
1059  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1060  global $conf;
1061
1062  // first build all the tag_ids we are interested in
1063  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1064  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1065  $tags_by_id = array();
1066  foreach( $tags as $tag )
1067  {
1068    $tags['id'] = (int)$tag['id'];
1069    $tags_by_id[ $tag['id'] ] = $tag;
1070  }
1071  unset($tags);
1072  $tag_ids = array_keys($tags_by_id);
1073
1074
1075  $image_ids = array();
1076  $image_tag_map = array();
1077
1078  if ( !empty($tag_ids) )
1079  { // build list of image ids with associated tags per image
1080    if ($params['tag_mode_and'])
1081    {
1082      $image_ids = get_image_ids_for_tags( $tag_ids );
1083    }
1084    else
1085    {
1086      $query = '
1087SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
1088  FROM '.IMAGE_TAG_TABLE.'
1089  WHERE tag_id IN ('.implode(',',$tag_ids).')
1090  GROUP BY image_id';
1091      $result = pwg_query($query);
1092      while ( $row=mysql_fetch_assoc($result) )
1093      {
1094        $row['image_id'] = (int)$row['image_id'];
1095        array_push( $image_ids, $row['image_id'] );
1096        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1097      }
1098    }
1099  }
1100
1101  $images = array();
1102  if ( !empty($image_ids))
1103  {
1104    $where_clauses = ws_std_image_sql_filter($params);
1105    $where_clauses[] = get_sql_condition_FandF(
1106        array
1107          (
1108            'forbidden_categories' => 'category_id',
1109            'visible_categories' => 'category_id',
1110            'visible_images' => 'i.id'
1111          ),
1112        '', true
1113      );
1114    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
1115
1116    $order_by = ws_std_image_sql_order($params);
1117    if (empty($order_by))
1118    {
1119      $order_by = $conf['order_by'];
1120    }
1121    else
1122    {
1123      $order_by = 'ORDER BY '.$order_by;
1124    }
1125
1126    $query = '
1127SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
1128  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
1129  WHERE '. implode('
1130    AND ', $where_clauses).'
1131'.$order_by.'
1132LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
1133
1134    $result = pwg_query($query);
1135    while ($row = mysql_fetch_assoc($result))
1136    {
1137      $image = array();
1138      foreach ( array('id', 'width', 'height', 'hit') as $k )
1139      {
1140        if (isset($row[$k]))
1141        {
1142          $image[$k] = (int)$row[$k];
1143        }
1144      }
1145      foreach ( array('file', 'name', 'comment') as $k )
1146      {
1147        $image[$k] = $row[$k];
1148      }
1149      $image = array_merge( $image, ws_std_get_urls($row) );
1150
1151      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1152      $image_tags = array();
1153      foreach ($image_tag_ids as $tag_id)
1154      {
1155        $url = make_index_url(
1156                 array(
1157                  'section'=>'tags',
1158                  'tags'=> array($tags_by_id[$tag_id])
1159                )
1160              );
1161        $page_url = make_picture_url(
1162                 array(
1163                  'section'=>'tags',
1164                  'tags'=> array($tags_by_id[$tag_id]),
1165                  'image_id' => $row['id'],
1166                  'image_file' => $row['file'],
1167                )
1168              );
1169        array_push($image_tags, array(
1170                'id' => (int)$tag_id,
1171                'url' => $url,
1172                'page_url' => $page_url,
1173              )
1174            );
1175      }
1176      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1177              array('id','url_name','url','page_url')
1178            );
1179      array_push($images, $image);
1180    }
1181  }
1182
1183  return array( 'images' =>
1184    array (
1185      WS_XML_ATTRIBUTES =>
1186        array(
1187            'page' => $params['page'],
1188            'per_page' => $params['per_page'],
1189            'count' => count($images)
1190          ),
1191       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1192          ws_std_get_image_xml_attributes() )
1193      )
1194    );
1195}
1196
1197?>
Note: See TracBrowser for help on using the repository browser.