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

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

improvement: WebService method pwg.images.add can set fill #images table
columns. rank is directly related to a category and several categories can
be linked at once. Basic technical metadata {filesize, width, height} are
automaticaly filled.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 34.2 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008      Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24/**** IMPLEMENTATION OF WEB SERVICE METHODS ***********************************/
25
26/**
27 * Event handler for method invocation security check. Should return a PwgError
28 * if the preconditions are not satifsied for method invocation.
29 */
30function ws_isInvokeAllowed($res, $methodName, $params)
31{
32  global $conf, $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  list($width, $height) = getimagesize($file_path);
978 
979  // database registration
980  $insert = array(
981    'file' => $filename_wo_ext.'.jpg',
982    'date_available' => $dbnow,
983    'tn_ext' => 'jpg',
984    'name' => $params['name'],
985    'path' => $file_path,
986    'filesize' => floor(filesize($file_path)/1024),
987    'width' => $width,
988    'height' => $height,
989    );
990
991  $info_columns = array(
992    'name',
993    'author',
994    'comment',
995    'level',
996    'date_creation',
997    );
998
999  foreach ($info_columns as $key)
1000  {
1001    if (isset($params[$key]))
1002    {
1003      $insert[$key] = $params[$key];
1004    }
1005  }
1006
1007  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1008  mass_inserts(
1009    IMAGES_TABLE,
1010    array_keys($insert),
1011    array($insert)
1012    );
1013
1014  $image_id = mysql_insert_id();
1015
1016  // let's add links between the image and the categories
1017  //
1018  // $params['categories'] should look like 123,12;456,auto;789 which means:
1019  //
1020  // 1. associate with category 123 on rank 12
1021  // 2. associate with category 456 on automatic rank
1022  // 3. associate with category 789 on automatic rank
1023  if (isset($params['categories']))
1024  {
1025    $cat_ids = array();
1026    $rank_on_category = array();
1027    $search_current_ranks = false;
1028   
1029    $tokens = explode(';', $params['categories']);
1030    foreach ($tokens as $token)
1031    {
1032      list($cat_id, $rank) = explode(',', $token);
1033
1034      array_push($cat_ids, $cat_id);
1035     
1036      if (!isset($rank))
1037      {
1038        $rank = 'auto';
1039      }
1040      $rank_on_category[$cat_id] = $rank;
1041
1042      if ($rank == 'auto')
1043      {
1044        $search_current_ranks = true;
1045      }
1046    }
1047
1048    $cat_ids = array_unique($cat_ids);
1049
1050    if (count($cat_ids) > 0)
1051    {
1052      if ($search_current_ranks)
1053      {
1054        $query = '
1055SELECT
1056    category_id,
1057    MAX(rank) AS max_rank
1058  FROM '.IMAGE_CATEGORY_TABLE.'
1059  WHERE rank IS NOT NULL
1060    AND category_id IN ('.implode(',', $cat_ids).')
1061  GROUP BY category_id
1062;';
1063        $current_rank_of = simple_hash_from_query(
1064          $query,
1065          'category_id',
1066          'max_rank'
1067          );
1068
1069        foreach ($cat_ids as $cat_id)
1070        {
1071          if ('auto' == $rank_on_category[$cat_id])
1072          {
1073          $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
1074          }
1075        }
1076      }
1077
1078      $inserts = array();
1079
1080      foreach ($cat_ids as $cat_id)
1081      {
1082        array_push(
1083          $inserts,
1084          array(
1085            'image_id' => $image_id,
1086            'category_id' => $cat_id,
1087            'rank' => $rank_on_category[$cat_id],
1088            )
1089          );
1090      }
1091
1092      mass_inserts(
1093        IMAGE_CATEGORY_TABLE,
1094        array_keys($inserts[0]),
1095        $inserts
1096        );
1097    }
1098  }
1099
1100  // and now, let's create tag associations
1101  if (isset($params['tag_ids']))
1102  {
1103    set_tags(
1104      explode(',', $params['tag_ids']),
1105      $image_id
1106      );
1107  }
1108 
1109  invalidate_user_cache();
1110
1111  // fclose($fh_log);
1112}
1113
1114/**
1115 * perform a login (web service method)
1116 */
1117function ws_session_login($params, &$service)
1118{
1119  global $conf;
1120
1121  if (!$service->isPost())
1122  {
1123    return new PwgError(405, "This method requires HTTP POST");
1124  }
1125  if (try_log_user($params['username'], $params['password'],false))
1126  {
1127    return true;
1128  }
1129  return new PwgError(999, 'Invalid username/password');
1130}
1131
1132
1133/**
1134 * performs a logout (web service method)
1135 */
1136function ws_session_logout($params, &$service)
1137{
1138  global $user, $conf;
1139  if (!is_a_guest())
1140  {
1141    $_SESSION = array();
1142    session_unset();
1143    session_destroy();
1144    setcookie(session_name(),'',0,
1145        ini_get('session.cookie_path'),
1146        ini_get('session.cookie_domain')
1147      );
1148    setcookie($conf['remember_me_name'], '', 0, cookie_path());
1149  }
1150  return true;
1151}
1152
1153function ws_session_getStatus($params, &$service)
1154{
1155  global $user;
1156  $res = array();
1157  $res['username'] = is_a_guest() ? 'guest' : $user['username'];
1158  foreach ( array('status', 'template', 'theme', 'language') as $k )
1159  {
1160    $res[$k] = $user[$k];
1161  }
1162  $res['charset'] = get_pwg_charset();
1163  return $res;
1164}
1165
1166
1167/**
1168 * returns a list of tags (web service method)
1169 */
1170function ws_tags_getList($params, &$service)
1171{
1172  $tags = get_available_tags();
1173  if ($params['sort_by_counter'])
1174  {
1175    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1176  }
1177  else
1178  {
1179    usort($tags, 'tag_alpha_compare');
1180  }
1181  for ($i=0; $i<count($tags); $i++)
1182  {
1183    $tags[$i]['id'] = (int)$tags[$i]['id'];
1184    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1185    $tags[$i]['url'] = make_index_url(
1186        array(
1187          'section'=>'tags',
1188          'tags'=>array($tags[$i])
1189        )
1190      );
1191  }
1192  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'counter' )) );
1193}
1194
1195
1196/**
1197 * returns a list of images for tags (web service method)
1198 */
1199function ws_tags_getImages($params, &$service)
1200{
1201  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1202  global $conf;
1203
1204  // first build all the tag_ids we are interested in
1205  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1206  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1207  $tags_by_id = array();
1208  foreach( $tags as $tag )
1209  {
1210    $tags['id'] = (int)$tag['id'];
1211    $tags_by_id[ $tag['id'] ] = $tag;
1212  }
1213  unset($tags);
1214  $tag_ids = array_keys($tags_by_id);
1215
1216
1217  $image_ids = array();
1218  $image_tag_map = array();
1219
1220  if ( !empty($tag_ids) )
1221  { // build list of image ids with associated tags per image
1222    if ($params['tag_mode_and'])
1223    {
1224      $image_ids = get_image_ids_for_tags( $tag_ids );
1225    }
1226    else
1227    {
1228      $query = '
1229SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
1230  FROM '.IMAGE_TAG_TABLE.'
1231  WHERE tag_id IN ('.implode(',',$tag_ids).')
1232  GROUP BY image_id';
1233      $result = pwg_query($query);
1234      while ( $row=mysql_fetch_assoc($result) )
1235      {
1236        $row['image_id'] = (int)$row['image_id'];
1237        array_push( $image_ids, $row['image_id'] );
1238        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1239      }
1240    }
1241  }
1242
1243  $images = array();
1244  if ( !empty($image_ids))
1245  {
1246    $where_clauses = ws_std_image_sql_filter($params);
1247    $where_clauses[] = get_sql_condition_FandF(
1248        array
1249          (
1250            'forbidden_categories' => 'category_id',
1251            'visible_categories' => 'category_id',
1252            'visible_images' => 'i.id'
1253          ),
1254        '', true
1255      );
1256    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
1257
1258    $order_by = ws_std_image_sql_order($params);
1259    if (empty($order_by))
1260    {
1261      $order_by = $conf['order_by'];
1262    }
1263    else
1264    {
1265      $order_by = 'ORDER BY '.$order_by;
1266    }
1267
1268    $query = '
1269SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
1270  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
1271  WHERE '. implode('
1272    AND ', $where_clauses).'
1273'.$order_by.'
1274LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
1275
1276    $result = pwg_query($query);
1277    while ($row = mysql_fetch_assoc($result))
1278    {
1279      $image = array();
1280      foreach ( array('id', 'width', 'height', 'hit') as $k )
1281      {
1282        if (isset($row[$k]))
1283        {
1284          $image[$k] = (int)$row[$k];
1285        }
1286      }
1287      foreach ( array('file', 'name', 'comment') as $k )
1288      {
1289        $image[$k] = $row[$k];
1290      }
1291      $image = array_merge( $image, ws_std_get_urls($row) );
1292
1293      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1294      $image_tags = array();
1295      foreach ($image_tag_ids as $tag_id)
1296      {
1297        $url = make_index_url(
1298                 array(
1299                  'section'=>'tags',
1300                  'tags'=> array($tags_by_id[$tag_id])
1301                )
1302              );
1303        $page_url = make_picture_url(
1304                 array(
1305                  'section'=>'tags',
1306                  'tags'=> array($tags_by_id[$tag_id]),
1307                  'image_id' => $row['id'],
1308                  'image_file' => $row['file'],
1309                )
1310              );
1311        array_push($image_tags, array(
1312                'id' => (int)$tag_id,
1313                'url' => $url,
1314                'page_url' => $page_url,
1315              )
1316            );
1317      }
1318      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1319              array('id','url_name','url','page_url')
1320            );
1321      array_push($images, $image);
1322    }
1323  }
1324
1325  return array( 'images' =>
1326    array (
1327      WS_XML_ATTRIBUTES =>
1328        array(
1329            'page' => $params['page'],
1330            'per_page' => $params['per_page'],
1331            'count' => count($images)
1332          ),
1333       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1334          ws_std_get_image_xml_attributes() )
1335      )
1336    );
1337}
1338?>
Note: See TracBrowser for help on using the repository browser.