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

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

merge -c2785 from branch 2.0 to trunk

bug 897 fixed: controls added in pwg.images.add to have clear error messages
if permission is denied or any error occur during file write.

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