source: tags/build-Butterfly02/include/ws_functions.inc.php @ 13096

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

feature added: ability to set rank from webservice upload.

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