source: tags/release-2_0_0RC3/include/ws_functions.inc.php @ 20987

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

feature 892 added: pwg.images.setInfo added so that once we have discovered
the photo was already in the database (thanks to pwg.images.exist), we can
only set the photo metadata.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 39.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;
33
34  if ( strpos($methodName,'reflection.')===0 )
35  { // OK for reflection
36    return $res;
37  }
38
39  if ( !is_autorize_status(ACCESS_GUEST) and
40      strpos($methodName,'pwg.session.')!==0 )
41  {
42    return new PwgError(401, 'Access denied');
43  }
44
45  return $res;
46}
47
48/**
49 * returns a "standard" (for our web service) array of sql where clauses that
50 * filters the images (images table only)
51 */
52function ws_std_image_sql_filter( $params, $tbl_name='' )
53{
54  $clauses = array();
55  if ( is_numeric($params['f_min_rate']) )
56  {
57    $clauses[] = $tbl_name.'average_rate>'.$params['f_min_rate'];
58  }
59  if ( is_numeric($params['f_max_rate']) )
60  {
61    $clauses[] = $tbl_name.'average_rate<='.$params['f_max_rate'];
62  }
63  if ( is_numeric($params['f_min_hit']) )
64  {
65    $clauses[] = $tbl_name.'hit>'.$params['f_min_hit'];
66  }
67  if ( is_numeric($params['f_max_hit']) )
68  {
69    $clauses[] = $tbl_name.'hit<='.$params['f_max_hit'];
70  }
71  if ( isset($params['f_min_date_posted']) )
72  {
73    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_posted']."'";
74  }
75  if ( isset($params['f_max_date_posted']) )
76  {
77    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_posted']."'";
78  }
79  if ( isset($params['f_min_date_created']) )
80  {
81    $clauses[] = $tbl_name."date_creation>='".$params['f_min_date_created']."'";
82  }
83  if ( isset($params['f_max_date_created']) )
84  {
85    $clauses[] = $tbl_name."date_creation<'".$params['f_max_date_created']."'";
86  }
87  if ( is_numeric($params['f_min_ratio']) )
88  {
89    $clauses[] = $tbl_name.'width/'.$tbl_name.'height>'.$params['f_min_ratio'];
90  }
91  if ( is_numeric($params['f_max_ratio']) )
92  {
93    $clauses[] = $tbl_name.'width/'.$tbl_name.'height<='.$params['f_max_ratio'];
94  }
95  if ( $params['f_with_thumbnail'] )
96  {
97    $clauses[] = $tbl_name.'tn_ext IS NOT NULL';
98  }
99  return $clauses;
100}
101
102/**
103 * returns a "standard" (for our web service) ORDER BY sql clause for images
104 */
105function ws_std_image_sql_order( $params, $tbl_name='' )
106{
107  $ret = '';
108  if ( empty($params['order']) )
109  {
110    return $ret;
111  }
112  $matches = array();
113  preg_match_all('/([a-z_]+) *(?:(asc|desc)(?:ending)?)? *(?:, *|$)/i',
114    $params['order'], $matches);
115  for ($i=0; $i<count($matches[1]); $i++)
116  {
117    switch ($matches[1][$i])
118    {
119      case 'date_created':
120        $matches[1][$i] = 'date_creation'; break;
121      case 'date_posted':
122        $matches[1][$i] = 'date_available'; break;
123      case 'rand': case 'random':
124        $matches[1][$i] = 'RAND()'; break;
125    }
126    $sortable_fields = array('id', 'file', 'name', 'hit', 'average_rate',
127      'date_creation', 'date_available', 'RAND()' );
128    if ( in_array($matches[1][$i], $sortable_fields) )
129    {
130      if (!empty($ret))
131        $ret .= ', ';
132      if ($matches[1][$i] != 'RAND()' )
133      {
134        $ret .= $tbl_name;
135      }
136      $ret .= $matches[1][$i];
137      $ret .= ' '.$matches[2][$i];
138    }
139  }
140  return $ret;
141}
142
143/**
144 * returns an array map of urls (thumb/element) for image_row - to be returned
145 * in a standard way by different web service methods
146 */
147function ws_std_get_urls($image_row)
148{
149  $ret = array(
150    'tn_url' => get_thumbnail_url($image_row),
151    'element_url' => get_element_url($image_row)
152  );
153  global $user;
154  if ($user['enabled_high'] and $image_row['has_high'] )
155  {
156    $ret['high_url'] = get_high_url($image_row);
157  }
158  return $ret;
159}
160
161/**
162 * returns an array of image attributes that are to be encoded as xml attributes
163 * instead of xml elements
164 */
165function ws_std_get_image_xml_attributes()
166{
167  return array(
168    'id','tn_url','element_url','high_url', 'file','width','height','hit'
169    );
170}
171
172/**
173 * returns PWG version (web service method)
174 */
175function ws_getVersion($params, &$service)
176{
177  global $conf;
178  if ($conf['show_version'])
179    return PHPWG_VERSION;
180  else
181    return new PwgError(403, 'Forbidden');
182}
183
184function ws_caddie_add($params, &$service)
185{
186  if (!is_admin())
187  {
188    return new PwgError(401, 'Access denied');
189  }
190  if ( empty($params['image_id']) )
191  {
192    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
193  }
194  global $user;
195  $query = '
196SELECT id
197  FROM '.IMAGES_TABLE.' LEFT JOIN '.CADDIE_TABLE.' ON id=element_id AND user_id='.$user['id'].'
198  WHERE id IN ('.implode(',',$params['image_id']).')
199    AND element_id IS NULL';
200  $datas = array();
201  foreach ( array_from_query($query, 'id') as $id )
202  {
203    array_push($datas, array('element_id'=>$id, 'user_id'=>$user['id']) );
204  }
205  if (count($datas))
206  {
207    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
208    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
209  }
210  return count($datas);
211}
212
213/**
214 * returns images per category (web service method)
215 */
216function ws_categories_getImages($params, &$service)
217{
218  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
219  global $user, $conf;
220
221  $images = array();
222
223  //------------------------------------------------- get the related categories
224  $where_clauses = array();
225  foreach($params['cat_id'] as $cat_id)
226  {
227    $cat_id = (int)$cat_id;
228    if ($cat_id<=0)
229      continue;
230    if ($params['recursive'])
231    {
232      $where_clauses[] = 'uppercats REGEXP \'(^|,)'.$cat_id.'(,|$)\'';
233    }
234    else
235    {
236      $where_clauses[] = 'id='.$cat_id;
237    }
238  }
239  if (!empty($where_clauses))
240  {
241    $where_clauses = array( '('.
242    implode('
243    OR ', $where_clauses) . ')'
244      );
245  }
246  $where_clauses[] = get_sql_condition_FandF(
247        array('forbidden_categories' => 'id'),
248        NULL, true
249      );
250
251  $query = '
252SELECT id, name, permalink, image_order
253  FROM '.CATEGORIES_TABLE.'
254  WHERE '. implode('
255    AND ', $where_clauses);
256  $result = pwg_query($query);
257  $cats = array();
258  while ($row = mysql_fetch_assoc($result))
259  {
260    $row['id'] = (int)$row['id'];
261    $cats[ $row['id'] ] = $row;
262  }
263
264  //-------------------------------------------------------- get the images
265  if ( !empty($cats) )
266  {
267    $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
268    $where_clauses[] = 'category_id IN ('
269      .implode(',', array_keys($cats) )
270      .')';
271    $where_clauses[] = get_sql_condition_FandF( array(
272          'visible_images' => 'i.id'
273        ), null, true
274      );
275
276    $order_by = ws_std_image_sql_order($params, 'i.');
277    if ( empty($order_by)
278          and count($params['cat_id'])==1
279          and isset($cats[ $params['cat_id'][0] ]['image_order'])
280        )
281    {
282      $order_by = $cats[ $params['cat_id'][0] ]['image_order'];
283    }
284    $order_by = empty($order_by) ? $conf['order_by'] : 'ORDER BY '.$order_by;
285
286    $query = '
287SELECT i.*, GROUP_CONCAT(category_id) cat_ids
288  FROM '.IMAGES_TABLE.' i
289    INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
290  WHERE '. implode('
291    AND ', $where_clauses).'
292GROUP BY i.id
293'.$order_by.'
294LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
295
296    $result = pwg_query($query);
297    while ($row = mysql_fetch_assoc($result))
298    {
299      $image = array();
300      foreach ( array('id', 'width', 'height', 'hit') as $k )
301      {
302        if (isset($row[$k]))
303        {
304          $image[$k] = (int)$row[$k];
305        }
306      }
307      foreach ( array('file', 'name', 'comment') as $k )
308      {
309        $image[$k] = $row[$k];
310      }
311      $image = array_merge( $image, ws_std_get_urls($row) );
312
313      $image_cats = array();
314      foreach ( explode(',', $row['cat_ids']) as $cat_id )
315      {
316        $url = make_index_url(
317                array(
318                  'category' => $cats[$cat_id],
319                  )
320                );
321        $page_url = make_picture_url(
322                array(
323                  'category' => $cats[$cat_id],
324                  'image_id' => $row['id'],
325                  'image_file' => $row['file'],
326                  )
327                );
328        array_push( $image_cats,  array(
329              WS_XML_ATTRIBUTES => array (
330                  'id' => (int)$cat_id,
331                  'url' => $url,
332                  'page_url' => $page_url,
333                )
334            )
335          );
336      }
337
338      $image['categories'] = new PwgNamedArray(
339            $image_cats,'category', array('id','url','page_url')
340          );
341      array_push($images, $image);
342    }
343  }
344
345  return array( 'images' =>
346    array (
347      WS_XML_ATTRIBUTES =>
348        array(
349            'page' => $params['page'],
350            'per_page' => $params['per_page'],
351            'count' => count($images)
352          ),
353       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
354          ws_std_get_image_xml_attributes() )
355      )
356    );
357}
358
359
360/**
361 * returns a list of categories (web service method)
362 */
363function ws_categories_getList($params, &$service)
364{
365  global $user,$conf;
366
367  $where = array();
368
369  if (!$params['recursive'])
370  {
371    if ($params['cat_id']>0)
372      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
373    OR id='.(int)($params['cat_id']).')';
374    else
375      $where[] = 'id_uppercat IS NULL';
376  }
377  else if ($params['cat_id']>0)
378  {
379    $where[] = 'uppercats REGEXP \'(^|,)'.
380      (int)($params['cat_id'])
381      .'(,|$)\'';
382  }
383
384  if ($params['public'])
385  {
386    $where[] = 'status = "public"';
387    $where[] = 'visible = "true"';
388    $where[]= 'user_id='.$conf['guest_id'];
389  }
390  else
391  {
392    $where[]= 'user_id='.$user['id'];
393  }
394
395  $query = '
396SELECT id, name, permalink, uppercats, global_rank,
397    nb_images, count_images AS total_nb_images,
398    date_last, max_date_last, count_categories AS nb_categories
399  FROM '.CATEGORIES_TABLE.'
400   INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id
401  WHERE '. implode('
402    AND ', $where);
403
404  $result = pwg_query($query);
405
406  $cats = array();
407  while ($row = mysql_fetch_assoc($result))
408  {
409    $row['url'] = make_index_url(
410        array(
411          'category' => $row
412          )
413      );
414    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
415    {
416      $row[$key] = (int)$row[$key];
417    }
418
419    array_push($cats, $row);
420  }
421  usort($cats, 'global_rank_compare');
422  return array(
423    'categories' => new PwgNamedArray(
424      $cats,
425      'category',
426      array(
427        'id',
428        'url',
429        'nb_images',
430        'total_nb_images',
431        'nb_categories',
432        'date_last',
433        'max_date_last',
434        )
435      )
436    );
437}
438
439/**
440 * returns the list of categories as you can see them in administration (web
441 * service method).
442 *
443 * Only admin can run this method and permissions are not taken into
444 * account.
445 */
446function ws_categories_getAdminList($params, &$service)
447{
448  if (!is_admin())
449  {
450    return new PwgError(401, 'Access denied');
451  }
452
453  $query = '
454SELECT
455    category_id,
456    COUNT(*) AS counter
457  FROM '.IMAGE_CATEGORY_TABLE.'
458  GROUP BY category_id
459;';
460  $nb_images_of = simple_hash_from_query($query, 'category_id', 'counter');
461
462  $query = '
463SELECT
464    id,
465    name,
466    uppercats,
467    global_rank
468  FROM '.CATEGORIES_TABLE.'
469;';
470  $result = pwg_query($query);
471  $cats = array();
472
473  while ($row = mysql_fetch_assoc($result))
474  {
475    $id = $row['id'];
476    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
477    array_push($cats, $row);
478  }
479
480  usort($cats, 'global_rank_compare');
481  return array(
482    'categories' => new PwgNamedArray(
483      $cats,
484      'category',
485      array(
486        'id',
487        'nb_images',
488        'name',
489        'uppercats',
490        'global_rank',
491        )
492      )
493    );
494}
495
496/**
497 * returns detailed information for an element (web service method)
498 */
499function ws_images_addComment($params, &$service)
500{
501  if (!$service->isPost())
502  {
503    return new PwgError(405, "This method requires HTTP POST");
504  }
505  $params['image_id'] = (int)$params['image_id'];
506  $query = '
507SELECT DISTINCT image_id
508  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
509  WHERE commentable="true"
510    AND image_id='.$params['image_id'].
511    get_sql_condition_FandF(
512      array(
513        'forbidden_categories' => 'id',
514        'visible_categories' => 'id',
515        'visible_images' => 'image_id'
516      ),
517      ' AND'
518    );
519  if ( !mysql_num_rows( pwg_query( $query ) ) )
520  {
521    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
522  }
523
524  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
525
526  $comm = array(
527    'author' => trim( stripslashes($params['author']) ),
528    'content' => trim( stripslashes($params['content']) ),
529    'image_id' => $params['image_id'],
530   );
531
532  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
533
534  $comment_action = insert_user_comment(
535      $comm, $params['key'], $infos
536    );
537
538  switch ($comment_action)
539  {
540    case 'reject':
541      array_push($infos, l10n('comment_not_added') );
542      return new PwgError(403, implode("\n", $infos) );
543    case 'validate':
544    case 'moderate':
545      $ret = array(
546          'id' => $comm['id'],
547          'validation' => $comment_action=='validate',
548        );
549      return new PwgNamedStruct(
550          'comment',
551          $ret,
552          null, array()
553        );
554    default:
555      return new PwgError(500, "Unknown comment action ".$comment_action );
556  }
557}
558
559/**
560 * returns detailed information for an element (web service method)
561 */
562function ws_images_getInfo($params, &$service)
563{
564  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
565  global $user, $conf;
566  $params['image_id'] = (int)$params['image_id'];
567  if ( $params['image_id']<=0 )
568  {
569    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
570  }
571
572  $query='
573SELECT * FROM '.IMAGES_TABLE.'
574  WHERE id='.$params['image_id'].
575    get_sql_condition_FandF(
576      array('visible_images' => 'id'),
577      ' AND'
578    ).'
579LIMIT 1';
580
581  $image_row = mysql_fetch_assoc(pwg_query($query));
582  if ($image_row==null)
583  {
584    return new PwgError(404, "image_id not found");
585  }
586  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
587
588  //-------------------------------------------------------- related categories
589  $query = '
590SELECT id, name, permalink, uppercats, global_rank, commentable
591  FROM '.IMAGE_CATEGORY_TABLE.'
592    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
593  WHERE image_id = '.$image_row['id'].
594  get_sql_condition_FandF(
595      array( 'forbidden_categories' => 'category_id' ),
596      ' AND'
597    ).'
598;';
599  $result = pwg_query($query);
600  $is_commentable = false;
601  $related_categories = array();
602  while ($row = mysql_fetch_assoc($result))
603  {
604    if ($row['commentable']=='true')
605    {
606      $is_commentable = true;
607    }
608    unset($row['commentable']);
609    $row['url'] = make_index_url(
610        array(
611          'category' => $row
612          )
613      );
614
615    $row['page_url'] = make_picture_url(
616        array(
617          'image_id' => $image_row['id'],
618          'image_file' => $image_row['file'],
619          'category' => $row
620          )
621      );
622    $row['id']=(int)$row['id'];
623    array_push($related_categories, $row);
624  }
625  usort($related_categories, 'global_rank_compare');
626  if ( empty($related_categories) )
627  {
628    return new PwgError(401, 'Access denied');
629  }
630
631  //-------------------------------------------------------------- related tags
632  $related_tags = get_common_tags( array($image_row['id']), -1 );
633  foreach( $related_tags as $i=>$tag)
634  {
635    $tag['url'] = make_index_url(
636        array(
637          'tags' => array($tag)
638          )
639      );
640    $tag['page_url'] = make_picture_url(
641        array(
642          'image_id' => $image_row['id'],
643          'image_file' => $image_row['file'],
644          'tags' => array($tag),
645          )
646      );
647    unset($tag['counter']);
648    $tag['id']=(int)$tag['id'];
649    $related_tags[$i]=$tag;
650  }
651  //------------------------------------------------------------- related rates
652  $query = '
653SELECT COUNT(rate) AS count
654     , ROUND(AVG(rate),2) AS average
655     , ROUND(STD(rate),2) AS stdev
656  FROM '.RATE_TABLE.'
657  WHERE element_id = '.$image_row['id'].'
658;';
659  $rating = mysql_fetch_assoc(pwg_query($query));
660  $rating['count'] = (int)$rating['count'];
661
662  //---------------------------------------------------------- related comments
663  $related_comments = array();
664
665  $where_comments = 'image_id = '.$image_row['id'];
666  if ( !is_admin() )
667  {
668    $where_comments .= '
669    AND validated="true"';
670  }
671
672  $query = '
673SELECT COUNT(id) nb_comments
674  FROM '.COMMENTS_TABLE.'
675  WHERE '.$where_comments;
676  list($nb_comments) = array_from_query($query, 'nb_comments');
677  $nb_comments = (int)$nb_comments;
678
679  if ( $nb_comments>0 and $params['comments_per_page']>0 )
680  {
681    $query = '
682SELECT id, date, author, content
683  FROM '.COMMENTS_TABLE.'
684  WHERE '.$where_comments.'
685  ORDER BY date
686  LIMIT '.$params['comments_per_page']*(int)$params['comments_page'].
687    ','.$params['comments_per_page'];
688
689    $result = pwg_query($query);
690    while ($row = mysql_fetch_assoc($result))
691    {
692      $row['id']=(int)$row['id'];
693      array_push($related_comments, $row);
694    }
695  }
696
697  $comment_post_data = null;
698  if ($is_commentable and
699      (!is_a_guest()
700        or (is_a_guest() and $conf['comments_forall'] )
701      )
702      )
703  {
704    include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
705    $comment_post_data['author'] = $user['username'];
706    $comment_post_data['key'] = get_comment_post_key($params['image_id']);
707  }
708
709  $ret = $image_row;
710  foreach ( array('id','width','height','hit','filesize') as $k )
711  {
712    if (isset($ret[$k]))
713    {
714      $ret[$k] = (int)$ret[$k];
715    }
716  }
717  foreach ( array('path', 'storage_category_id') as $k )
718  {
719    unset($ret[$k]);
720  }
721
722  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
723  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
724  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
725  if ( isset($comment_post_data) )
726  {
727    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
728  }
729  $ret['comments'] = array(
730     WS_XML_ATTRIBUTES =>
731        array(
732          'page' => $params['comments_page'],
733          'per_page' => $params['comments_per_page'],
734          'count' => count($related_comments),
735          'nb_comments' => $nb_comments,
736        ),
737     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id','date') )
738      );
739
740  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
741}
742
743
744/**
745 * rates the image_id in the parameter
746 */
747function ws_images_Rate($params, &$service)
748{
749  $image_id = (int)$params['image_id'];
750  $query = '
751SELECT DISTINCT id FROM '.IMAGES_TABLE.'
752  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
753  WHERE id='.$image_id
754  .get_sql_condition_FandF(
755    array(
756        'forbidden_categories' => 'category_id',
757        'forbidden_images' => 'id',
758      ),
759    '    AND'
760    ).'
761    LIMIT 1';
762  if ( mysql_num_rows( pwg_query($query) )==0 )
763  {
764    return new PwgError(404, "Invalid image_id or access denied" );
765  }
766  $rate = (int)$params['rate'];
767  include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
768  $res = rate_picture( $image_id, $rate );
769  if ($res==false)
770  {
771    global $conf;
772    return new PwgError( 403, "Forbidden or rate not in ". implode(',',$conf['rate_items']));
773  }
774  return $res;
775}
776
777
778/**
779 * returns a list of elements corresponding to a query search
780 */
781function ws_images_search($params, &$service)
782{
783  global $page;
784  $images = array();
785  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
786  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
787
788  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
789  $order_by = ws_std_image_sql_order($params, 'i.');
790
791  $super_order_by = false;
792  if ( !empty($order_by) )
793  {
794    global $conf;
795    $conf['order_by'] = 'ORDER BY '.$order_by;
796    $super_order_by=true; // quick_search_result might be faster
797  }
798
799  $search_result = get_quick_search_results($params['query'],
800      $super_order_by,
801      implode(',', $where_clauses)
802    );
803
804  $image_ids = array_slice(
805      $search_result['items'],
806      $params['page']*$params['per_page'],
807      $params['per_page']
808    );
809
810  if ( count($image_ids) )
811  {
812    $query = '
813SELECT * FROM '.IMAGES_TABLE.'
814  WHERE id IN ('.implode(',', $image_ids).')';
815
816    $image_ids = array_flip($image_ids);
817    $result = pwg_query($query);
818    while ($row = mysql_fetch_assoc($result))
819    {
820      $image = array();
821      foreach ( array('id', 'width', 'height', 'hit') as $k )
822      {
823        if (isset($row[$k]))
824        {
825          $image[$k] = (int)$row[$k];
826        }
827      }
828      foreach ( array('file', 'name', 'comment') as $k )
829      {
830        $image[$k] = $row[$k];
831      }
832      $image = array_merge( $image, ws_std_get_urls($row) );
833      $images[$image_ids[$image['id']]] = $image;
834    }
835    ksort($images, SORT_NUMERIC);
836    $images = array_values($images);
837  }
838
839
840  return array( 'images' =>
841    array (
842      WS_XML_ATTRIBUTES =>
843        array(
844            'page' => $params['page'],
845            'per_page' => $params['per_page'],
846            'count' => count($images)
847          ),
848       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
849          ws_std_get_image_xml_attributes() )
850      )
851    );
852}
853
854function ws_images_setPrivacyLevel($params, &$service)
855{
856  if (!is_admin() || is_adviser() )
857  {
858    return new PwgError(401, 'Access denied');
859  }
860  if ( empty($params['image_id']) )
861  {
862    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
863  }
864  global $conf;
865  if ( !in_array( (int)$params['level'], $conf['available_permission_levels']) )
866  {
867    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid level");
868  }
869  $query = '
870UPDATE '.IMAGES_TABLE.'
871  SET level='.(int)$params['level'].'
872  WHERE id IN ('.implode(',',$params['image_id']).')';
873  $result = pwg_query($query);
874  $affected_rows = mysql_affected_rows();
875  if ($affected_rows)
876  {
877    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
878    invalidate_user_cache();
879  }
880  return $affected_rows;
881}
882
883function ws_images_add($params, &$service)
884{
885  global $conf;
886  if (!is_admin() || is_adviser() )
887  {
888    return new PwgError(401, 'Access denied');
889  }
890
891  // name
892  // category_id
893  // file_content
894  // file_sum
895  // thumbnail_content
896  // thumbnail_sum
897  // rank
898
899  // $fh_log = fopen('/tmp/php.log', 'w');
900  // fwrite($fh_log, time()."\n");
901  // fwrite($fh_log, 'input rank :'.$params['rank']."\n");
902  // fwrite($fh_log, 'input:  '.$params['file_sum']."\n");
903  // fwrite($fh_log, 'input:  '.$params['thumbnail_sum']."\n");
904
905  // does the image already exists ?
906  $query = '
907SELECT
908    COUNT(*) AS counter
909  FROM '.IMAGES_TABLE.'
910  WHERE md5sum = \''.$params['file_sum'].'\'
911;';
912  list($counter) = mysql_fetch_row(pwg_query($query));
913  if ($counter != 0) {
914    return new PwgError(500, 'file already exists');
915  }
916
917  // current date
918  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
919  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
920
921  // upload directory hierarchy
922  $upload_dir = sprintf(
923    PHPWG_ROOT_PATH.'upload/%s/%s/%s',
924    $year,
925    $month,
926    $day
927    );
928
929  //fwrite($fh_log, $upload_dir."\n");
930
931  // create the upload directory tree if not exists
932  if (!is_dir($upload_dir)) {
933    umask(0000);
934    $recursive = true;
935    mkdir($upload_dir, 0777, $recursive);
936  }
937
938  // compute file path
939  $date_string = preg_replace('/[^\d]/', '', $dbnow);
940  $random_string = substr($params['file_sum'], 0, 8);
941  $filename_wo_ext = $date_string.'-'.$random_string;
942  $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
943
944  // dump the photo file
945  $fh_file = fopen($file_path, 'w');
946  fwrite($fh_file, base64_decode($params['file_content']));
947  fclose($fh_file);
948  chmod($file_path, 0644);
949
950  // check dumped file md5sum against expected md5sum
951  $dumped_md5 = md5_file($file_path);
952  if ($dumped_md5 != $params['file_sum']) {
953    return new PwgError(500, 'file transfer failed');
954  }
955
956  // thumbnail directory is a subdirectory of the photo file, hard coded
957  // "thumbnail"
958  $thumbnail_dir = $upload_dir.'/thumbnail';
959  if (!is_dir($thumbnail_dir)) {
960    umask(0000);
961    mkdir($thumbnail_dir, 0777);
962  }
963
964  // thumbnail path, the filename may use a prefix and the extension is
965  // always "jpg" (no matter what the real file format is)
966  $thumbnail_path = sprintf(
967    '%s/%s%s.%s',
968    $thumbnail_dir,
969    $conf['prefix_thumbnail'],
970    $filename_wo_ext,
971    'jpg'
972    );
973
974  // dump the thumbnail
975  $fh_thumbnail = fopen($thumbnail_path, 'w');
976  fwrite($fh_thumbnail, base64_decode($params['thumbnail_content']));
977  fclose($fh_thumbnail);
978  chmod($thumbnail_path, 0644);
979
980  // check dumped thumbnail md5
981  $dumped_md5 = md5_file($thumbnail_path);
982  if ($dumped_md5 != $params['thumbnail_sum']) {
983    return new PwgError(500, 'thumbnail transfer failed');
984  }
985
986  // high resolution
987  if (isset($params['high_content']))
988  {
989    // high resolution directory is a subdirectory of the photo file, hard
990    // coded "pwg_high"
991    $high_dir = $upload_dir.'/pwg_high';
992    if (!is_dir($high_dir)) {
993      umask(0000);
994      mkdir($high_dir, 0777);
995    }
996
997    // high resolution path, same name as web size file
998    $high_path = sprintf(
999      '%s/%s.%s',
1000      $high_dir,
1001      $filename_wo_ext,
1002      'jpg'
1003      );
1004
1005    // dump the high resolution file
1006    $fh_high = fopen($high_path, 'w');
1007    fwrite($fh_high, base64_decode($params['high_content']));
1008    fclose($fh_high);
1009    chmod($high_path, 0644);
1010
1011    // check dumped thumbnail md5
1012    $dumped_md5 = md5_file($high_path);
1013    if ($dumped_md5 != $params['high_sum']) {
1014      return new PwgError(500, 'high resolution transfer failed');
1015    }
1016
1017    $high_filesize = floor(filesize($high_path)/1024);
1018  }
1019
1020  list($width, $height) = getimagesize($file_path);
1021
1022  // database registration
1023  $insert = array(
1024    'file' => $filename_wo_ext.'.jpg',
1025    'date_available' => $dbnow,
1026    'tn_ext' => 'jpg',
1027    'name' => $params['name'],
1028    'path' => $file_path,
1029    'filesize' => floor(filesize($file_path)/1024),
1030    'width' => $width,
1031    'height' => $height,
1032    'md5sum' => $params['file_sum'],
1033    );
1034
1035  $info_columns = array(
1036    'name',
1037    'author',
1038    'comment',
1039    'level',
1040    'date_creation',
1041    );
1042
1043  foreach ($info_columns as $key)
1044  {
1045    if (isset($params[$key]))
1046    {
1047      $insert[$key] = $params[$key];
1048    }
1049  }
1050
1051  if (isset($params['high_content']))
1052  {
1053    $insert['has_high'] = 'true';
1054    $insert['high_filesize'] = $high_filesize;
1055  }
1056
1057  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1058  mass_inserts(
1059    IMAGES_TABLE,
1060    array_keys($insert),
1061    array($insert)
1062    );
1063
1064  $image_id = mysql_insert_id();
1065
1066  // let's add links between the image and the categories
1067  if (isset($params['categories']))
1068  {
1069    ws_add_image_category_relations($image_id, $params['categories']);
1070  }
1071
1072  // and now, let's create tag associations
1073  if (isset($params['tag_ids']))
1074  {
1075    set_tags(
1076      explode(',', $params['tag_ids']),
1077      $image_id
1078      );
1079  }
1080
1081  invalidate_user_cache();
1082
1083  // fclose($fh_log);
1084}
1085
1086/**
1087 * perform a login (web service method)
1088 */
1089function ws_session_login($params, &$service)
1090{
1091  global $conf;
1092
1093  if (!$service->isPost())
1094  {
1095    return new PwgError(405, "This method requires HTTP POST");
1096  }
1097  if (try_log_user($params['username'], $params['password'],false))
1098  {
1099    return true;
1100  }
1101  return new PwgError(999, 'Invalid username/password');
1102}
1103
1104
1105/**
1106 * performs a logout (web service method)
1107 */
1108function ws_session_logout($params, &$service)
1109{
1110  global $user, $conf;
1111  if (!is_a_guest())
1112  {
1113    $_SESSION = array();
1114    session_unset();
1115    session_destroy();
1116    setcookie(session_name(),'',0,
1117        ini_get('session.cookie_path'),
1118        ini_get('session.cookie_domain')
1119      );
1120    setcookie($conf['remember_me_name'], '', 0, cookie_path());
1121  }
1122  return true;
1123}
1124
1125function ws_session_getStatus($params, &$service)
1126{
1127  global $user;
1128  $res = array();
1129  $res['username'] = is_a_guest() ? 'guest' : $user['username'];
1130  foreach ( array('status', 'template', 'theme', 'language') as $k )
1131  {
1132    $res[$k] = $user[$k];
1133  }
1134  $res['charset'] = get_pwg_charset();
1135  return $res;
1136}
1137
1138
1139/**
1140 * returns a list of tags (web service method)
1141 */
1142function ws_tags_getList($params, &$service)
1143{
1144  $tags = get_available_tags();
1145  if ($params['sort_by_counter'])
1146  {
1147    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1148  }
1149  else
1150  {
1151    usort($tags, 'tag_alpha_compare');
1152  }
1153  for ($i=0; $i<count($tags); $i++)
1154  {
1155    $tags[$i]['id'] = (int)$tags[$i]['id'];
1156    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1157    $tags[$i]['url'] = make_index_url(
1158        array(
1159          'section'=>'tags',
1160          'tags'=>array($tags[$i])
1161        )
1162      );
1163  }
1164  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
1165}
1166
1167/**
1168 * returns the list of tags as you can see them in administration (web
1169 * service method).
1170 *
1171 * Only admin can run this method and permissions are not taken into
1172 * account.
1173 */
1174function ws_tags_getAdminList($params, &$service)
1175{
1176  if (!is_admin())
1177  {
1178    return new PwgError(401, 'Access denied');
1179  }
1180
1181  $tags = get_all_tags();
1182  return array(
1183    'tags' => new PwgNamedArray(
1184      $tags,
1185      'tag',
1186      array(
1187        'name',
1188        'id',
1189        'url_name',
1190        )
1191      )
1192    );
1193}
1194
1195/**
1196 * returns a list of images for tags (web service method)
1197 */
1198function ws_tags_getImages($params, &$service)
1199{
1200  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1201  global $conf;
1202
1203  // first build all the tag_ids we are interested in
1204  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1205  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1206  $tags_by_id = array();
1207  foreach( $tags as $tag )
1208  {
1209    $tags['id'] = (int)$tag['id'];
1210    $tags_by_id[ $tag['id'] ] = $tag;
1211  }
1212  unset($tags);
1213  $tag_ids = array_keys($tags_by_id);
1214
1215
1216  $image_ids = array();
1217  $image_tag_map = array();
1218
1219  if ( !empty($tag_ids) )
1220  { // build list of image ids with associated tags per image
1221    if ($params['tag_mode_and'])
1222    {
1223      $image_ids = get_image_ids_for_tags( $tag_ids );
1224    }
1225    else
1226    {
1227      $query = '
1228SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
1229  FROM '.IMAGE_TAG_TABLE.'
1230  WHERE tag_id IN ('.implode(',',$tag_ids).')
1231  GROUP BY image_id';
1232      $result = pwg_query($query);
1233      while ( $row=mysql_fetch_assoc($result) )
1234      {
1235        $row['image_id'] = (int)$row['image_id'];
1236        array_push( $image_ids, $row['image_id'] );
1237        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1238      }
1239    }
1240  }
1241
1242  $images = array();
1243  if ( !empty($image_ids))
1244  {
1245    $where_clauses = ws_std_image_sql_filter($params);
1246    $where_clauses[] = get_sql_condition_FandF(
1247        array
1248          (
1249            'forbidden_categories' => 'category_id',
1250            'visible_categories' => 'category_id',
1251            'visible_images' => 'i.id'
1252          ),
1253        '', true
1254      );
1255    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
1256
1257    $order_by = ws_std_image_sql_order($params);
1258    if (empty($order_by))
1259    {
1260      $order_by = $conf['order_by'];
1261    }
1262    else
1263    {
1264      $order_by = 'ORDER BY '.$order_by;
1265    }
1266
1267    $query = '
1268SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
1269  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
1270  WHERE '. implode('
1271    AND ', $where_clauses).'
1272'.$order_by.'
1273LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
1274
1275    $result = pwg_query($query);
1276    while ($row = mysql_fetch_assoc($result))
1277    {
1278      $image = array();
1279      foreach ( array('id', 'width', 'height', 'hit') as $k )
1280      {
1281        if (isset($row[$k]))
1282        {
1283          $image[$k] = (int)$row[$k];
1284        }
1285      }
1286      foreach ( array('file', 'name', 'comment') as $k )
1287      {
1288        $image[$k] = $row[$k];
1289      }
1290      $image = array_merge( $image, ws_std_get_urls($row) );
1291
1292      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1293      $image_tags = array();
1294      foreach ($image_tag_ids as $tag_id)
1295      {
1296        $url = make_index_url(
1297                 array(
1298                  'section'=>'tags',
1299                  'tags'=> array($tags_by_id[$tag_id])
1300                )
1301              );
1302        $page_url = make_picture_url(
1303                 array(
1304                  'section'=>'tags',
1305                  'tags'=> array($tags_by_id[$tag_id]),
1306                  'image_id' => $row['id'],
1307                  'image_file' => $row['file'],
1308                )
1309              );
1310        array_push($image_tags, array(
1311                'id' => (int)$tag_id,
1312                'url' => $url,
1313                'page_url' => $page_url,
1314              )
1315            );
1316      }
1317      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1318              array('id','url_name','url','page_url')
1319            );
1320      array_push($images, $image);
1321    }
1322  }
1323
1324  return array( 'images' =>
1325    array (
1326      WS_XML_ATTRIBUTES =>
1327        array(
1328            'page' => $params['page'],
1329            'per_page' => $params['per_page'],
1330            'count' => count($images)
1331          ),
1332       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1333          ws_std_get_image_xml_attributes() )
1334      )
1335    );
1336}
1337
1338function ws_categories_add($params, &$service)
1339{
1340  if (!is_admin() or is_adviser())
1341  {
1342    return new PwgError(401, 'Access denied');
1343  }
1344
1345  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1346
1347  $creation_output = create_virtual_category(
1348    $params['name'],
1349    $params['parent']
1350    );
1351
1352  if (isset($creation_output['error']))
1353  {
1354    return new PwgError(500, $creation_output['error']);
1355  }
1356
1357  invalidate_user_cache();
1358 
1359  return $creation_output;
1360}
1361
1362function ws_tags_add($params, &$service)
1363{
1364  if (!is_admin() or is_adviser())
1365  {
1366    return new PwgError(401, 'Access denied');
1367  }
1368
1369  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1370
1371  $creation_output = create_tag($params['name']);
1372
1373  if (isset($creation_output['error']))
1374  {
1375    return new PwgError(500, $creation_output['error']);
1376  }
1377
1378  return $creation_output;
1379}
1380
1381function ws_images_exist($params, &$service)
1382{
1383  if (!is_admin() or is_adviser())
1384  {
1385    return new PwgError(401, 'Access denied');
1386  }
1387
1388  // search among photos the list of photos already added, based on md5sum
1389  // list
1390  $md5sums = preg_split(
1391    '/[\s,;\|]/',
1392    $params['md5sum_list'],
1393    -1,
1394    PREG_SPLIT_NO_EMPTY
1395    );
1396 
1397  $query = '
1398SELECT
1399    id,
1400    md5sum
1401  FROM '.IMAGES_TABLE.'
1402  WHERE md5sum IN (\''.implode("','", $md5sums).'\') 
1403;';
1404  $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
1405
1406  $result = array();
1407 
1408  foreach ($md5sums as $md5sum)
1409  {
1410    $result[$md5sum] = null;
1411    if (isset($id_of_md5[$md5sum]))
1412    {
1413      $result[$md5sum] = $id_of_md5[$md5sum];
1414    }
1415  }
1416
1417  return $result;
1418}
1419
1420function ws_images_setInfo($params, &$service)
1421{
1422  global $conf;
1423  if (!is_admin() || is_adviser() )
1424  {
1425    return new PwgError(401, 'Access denied');
1426  }
1427
1428  // name
1429  // category_id
1430  // file_content
1431  // file_sum
1432  // thumbnail_content
1433  // thumbnail_sum
1434 
1435  $params['image_id'] = (int)$params['image_id'];
1436  if ($params['image_id'] <= 0)
1437  {
1438    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1439  }
1440
1441  $query='
1442SELECT *
1443  FROM '.IMAGES_TABLE.'
1444  WHERE id = '.$params['image_id'].'
1445;';
1446
1447  $image_row = mysql_fetch_assoc(pwg_query($query));
1448  if ($image_row == null)
1449  {
1450    return new PwgError(404, "image_id not found");
1451  }
1452
1453  // database registration
1454  $update = array(
1455    'id' => $params['image_id'],
1456    );
1457
1458  $info_columns = array(
1459    'name',
1460    'author',
1461    'comment',
1462    'level',
1463    'date_creation',
1464    );
1465
1466  $perform_update = false;
1467  foreach ($info_columns as $key)
1468  {
1469    if (isset($params[$key]))
1470    {
1471      $perform_update = true;
1472      $update[$key] = $params[$key];
1473    }
1474  }
1475
1476  if ($perform_update)
1477  {
1478    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1479    mass_updates(
1480      IMAGES_TABLE,
1481      array(
1482        'primary' => array('id'),
1483        'update'  => array_diff(array_keys($update), array('id'))
1484        ),
1485      array($update)
1486      );
1487  }
1488 
1489  if (isset($params['categories']))
1490  {
1491    ws_add_image_category_relations(
1492      $params['image_id'],
1493      $params['categories']
1494      );
1495  }
1496
1497  // and now, let's create tag associations
1498  if (isset($params['tag_ids']))
1499  {
1500    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1501    add_tags(
1502      explode(',', $params['tag_ids']),
1503      array($params['image_id'])
1504      );
1505  }
1506
1507  invalidate_user_cache();
1508}
1509
1510function ws_add_image_category_relations($image_id, $categories_string)
1511{
1512  // let's add links between the image and the categories
1513  //
1514  // $params['categories'] should look like 123,12;456,auto;789 which means:
1515  //
1516  // 1. associate with category 123 on rank 12
1517  // 2. associate with category 456 on automatic rank
1518  // 3. associate with category 789 on automatic rank
1519  $cat_ids = array();
1520  $rank_on_category = array();
1521  $search_current_ranks = false;
1522
1523  $tokens = explode(';', $categories_string);
1524  foreach ($tokens as $token)
1525  {
1526    list($cat_id, $rank) = explode(',', $token);
1527
1528    array_push($cat_ids, $cat_id);
1529
1530    if (!isset($rank))
1531    {
1532      $rank = 'auto';
1533    }
1534    $rank_on_category[$cat_id] = $rank;
1535
1536    if ($rank == 'auto')
1537    {
1538      $search_current_ranks = true;
1539    }
1540  }
1541
1542  $cat_ids = array_unique($cat_ids);
1543
1544  if (count($cat_ids) > 0)
1545  {
1546    if ($search_current_ranks)
1547    {
1548      $query = '
1549SELECT
1550    category_id,
1551    MAX(rank) AS max_rank
1552  FROM '.IMAGE_CATEGORY_TABLE.'
1553  WHERE rank IS NOT NULL
1554    AND category_id IN ('.implode(',', $cat_ids).')
1555  GROUP BY category_id
1556;';
1557      $current_rank_of = simple_hash_from_query(
1558        $query,
1559        'category_id',
1560        'max_rank'
1561        );
1562
1563      foreach ($cat_ids as $cat_id)
1564      {
1565        if ('auto' == $rank_on_category[$cat_id])
1566        {
1567          $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
1568        }
1569      }
1570    }
1571
1572    $inserts = array();
1573
1574    foreach ($cat_ids as $cat_id)
1575    {
1576      array_push(
1577        $inserts,
1578        array(
1579          'image_id' => $image_id,
1580          'category_id' => $cat_id,
1581          'rank' => $rank_on_category[$cat_id],
1582          )
1583        );
1584    }
1585
1586    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1587    mass_inserts(
1588      IMAGE_CATEGORY_TABLE,
1589      array_keys($inserts[0]),
1590      $inserts
1591      );
1592
1593    update_category($cat_ids);
1594  }
1595}
1596?>
Note: See TracBrowser for help on using the repository browser.