source: branches/2.0/include/ws_functions.inc.php @ 4899

Last change on this file since 4899 was 4899, checked in by plg, 14 years ago

bug 1422 fixed: pwg.images.add (and sub methods) can create recursive
directories for windows.

add trace in ws_logfile for add_file + ws_images_add_chunk

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 49.4 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2009 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('1=1');
369  $join_type = 'INNER';
370  $join_user = $user['id'];
371
372  if (!$params['recursive'])
373  {
374    if ($params['cat_id']>0)
375      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
376    OR id='.(int)($params['cat_id']).')';
377    else
378      $where[] = 'id_uppercat IS NULL';
379  }
380  else if ($params['cat_id']>0)
381  {
382    $where[] = 'uppercats REGEXP \'(^|,)'.
383      (int)($params['cat_id'])
384      .'(,|$)\'';
385  }
386
387  if ($params['public'])
388  {
389    $where[] = 'status = "public"';
390    $where[] = 'visible = "true"';
391   
392    $join_user = $conf['guest_id'];
393  }
394  elseif (is_admin())
395  {
396    // in this very specific case, we don't want to hide empty
397    // categories. Function calculate_permissions will only return
398    // categories that are either locked or private and not permitted
399    //
400    // calculate_permissions does not consider empty categories as forbidden
401    $forbidden_categories = calculate_permissions($user['id'], $user['status']);
402    $where[]= 'id NOT IN ('.$forbidden_categories.')';
403    $join_type = 'LEFT';
404  }
405
406  $query = '
407SELECT id, name, permalink, uppercats, global_rank,
408    nb_images, count_images AS total_nb_images,
409    date_last, max_date_last, count_categories AS nb_categories
410  FROM '.CATEGORIES_TABLE.'
411   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
412  WHERE '. implode('
413    AND ', $where);
414
415  $result = pwg_query($query);
416
417  $cats = array();
418  while ($row = mysql_fetch_assoc($result))
419  {
420    $row['url'] = make_index_url(
421        array(
422          'category' => $row
423          )
424      );
425    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
426    {
427      $row[$key] = (int)$row[$key];
428    }
429
430    array_push($cats, $row);
431  }
432  usort($cats, 'global_rank_compare');
433  return array(
434    'categories' => new PwgNamedArray(
435      $cats,
436      'category',
437      array(
438        'id',
439        'url',
440        'nb_images',
441        'total_nb_images',
442        'nb_categories',
443        'date_last',
444        'max_date_last',
445        )
446      )
447    );
448}
449
450/**
451 * returns the list of categories as you can see them in administration (web
452 * service method).
453 *
454 * Only admin can run this method and permissions are not taken into
455 * account.
456 */
457function ws_categories_getAdminList($params, &$service)
458{
459  if (!is_admin())
460  {
461    return new PwgError(401, 'Access denied');
462  }
463
464  $query = '
465SELECT
466    category_id,
467    COUNT(*) AS counter
468  FROM '.IMAGE_CATEGORY_TABLE.'
469  GROUP BY category_id
470;';
471  $nb_images_of = simple_hash_from_query($query, 'category_id', 'counter');
472
473  $query = '
474SELECT
475    id,
476    name,
477    uppercats,
478    global_rank
479  FROM '.CATEGORIES_TABLE.'
480;';
481  $result = pwg_query($query);
482  $cats = array();
483
484  while ($row = mysql_fetch_assoc($result))
485  {
486    $id = $row['id'];
487    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
488    array_push($cats, $row);
489  }
490
491  usort($cats, 'global_rank_compare');
492  return array(
493    'categories' => new PwgNamedArray(
494      $cats,
495      'category',
496      array(
497        'id',
498        'nb_images',
499        'name',
500        'uppercats',
501        'global_rank',
502        )
503      )
504    );
505}
506
507/**
508 * returns detailed information for an element (web service method)
509 */
510function ws_images_addComment($params, &$service)
511{
512  if (!$service->isPost())
513  {
514    return new PwgError(405, "This method requires HTTP POST");
515  }
516  $params['image_id'] = (int)$params['image_id'];
517  $query = '
518SELECT DISTINCT image_id
519  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
520  WHERE commentable="true"
521    AND image_id='.$params['image_id'].
522    get_sql_condition_FandF(
523      array(
524        'forbidden_categories' => 'id',
525        'visible_categories' => 'id',
526        'visible_images' => 'image_id'
527      ),
528      ' AND'
529    );
530  if ( !mysql_num_rows( pwg_query( $query ) ) )
531  {
532    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
533  }
534
535  $comm = array(
536    'author' => trim( stripslashes($params['author']) ),
537    'content' => trim( stripslashes($params['content']) ),
538    'image_id' => $params['image_id'],
539   );
540
541  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
542
543  $comment_action = insert_user_comment(
544      $comm, $params['key'], $infos
545    );
546
547  switch ($comment_action)
548  {
549    case 'reject':
550      array_push($infos, l10n('comment_not_added') );
551      return new PwgError(403, implode("\n", $infos) );
552    case 'validate':
553    case 'moderate':
554      $ret = array(
555          'id' => $comm['id'],
556          'validation' => $comment_action=='validate',
557        );
558      return new PwgNamedStruct(
559          'comment',
560          $ret,
561          null, array()
562        );
563    default:
564      return new PwgError(500, "Unknown comment action ".$comment_action );
565  }
566}
567
568/**
569 * returns detailed information for an element (web service method)
570 */
571function ws_images_getInfo($params, &$service)
572{
573  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
574  global $user, $conf;
575  $params['image_id'] = (int)$params['image_id'];
576  if ( $params['image_id']<=0 )
577  {
578    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
579  }
580
581  $query='
582SELECT * FROM '.IMAGES_TABLE.'
583  WHERE id='.$params['image_id'].
584    get_sql_condition_FandF(
585      array('visible_images' => 'id'),
586      ' AND'
587    ).'
588LIMIT 1';
589
590  $image_row = mysql_fetch_assoc(pwg_query($query));
591  if ($image_row==null)
592  {
593    return new PwgError(404, "image_id not found");
594  }
595  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
596
597  //-------------------------------------------------------- related categories
598  $query = '
599SELECT id, name, permalink, uppercats, global_rank, commentable
600  FROM '.IMAGE_CATEGORY_TABLE.'
601    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
602  WHERE image_id = '.$image_row['id'].
603  get_sql_condition_FandF(
604      array( 'forbidden_categories' => 'category_id' ),
605      ' AND'
606    ).'
607;';
608  $result = pwg_query($query);
609  $is_commentable = false;
610  $related_categories = array();
611  while ($row = mysql_fetch_assoc($result))
612  {
613    if ($row['commentable']=='true')
614    {
615      $is_commentable = true;
616    }
617    unset($row['commentable']);
618    $row['url'] = make_index_url(
619        array(
620          'category' => $row
621          )
622      );
623
624    $row['page_url'] = make_picture_url(
625        array(
626          'image_id' => $image_row['id'],
627          'image_file' => $image_row['file'],
628          'category' => $row
629          )
630      );
631    $row['id']=(int)$row['id'];
632    array_push($related_categories, $row);
633  }
634  usort($related_categories, 'global_rank_compare');
635  if ( empty($related_categories) )
636  {
637    return new PwgError(401, 'Access denied');
638  }
639
640  //-------------------------------------------------------------- related tags
641  $related_tags = get_common_tags( array($image_row['id']), -1 );
642  foreach( $related_tags as $i=>$tag)
643  {
644    $tag['url'] = make_index_url(
645        array(
646          'tags' => array($tag)
647          )
648      );
649    $tag['page_url'] = make_picture_url(
650        array(
651          'image_id' => $image_row['id'],
652          'image_file' => $image_row['file'],
653          'tags' => array($tag),
654          )
655      );
656    unset($tag['counter']);
657    $tag['id']=(int)$tag['id'];
658    $related_tags[$i]=$tag;
659  }
660  //------------------------------------------------------------- related rates
661  $query = '
662SELECT COUNT(rate) AS count
663     , ROUND(AVG(rate),2) AS average
664     , ROUND(STD(rate),2) AS stdev
665  FROM '.RATE_TABLE.'
666  WHERE element_id = '.$image_row['id'].'
667;';
668  $rating = mysql_fetch_assoc(pwg_query($query));
669  $rating['count'] = (int)$rating['count'];
670
671  //---------------------------------------------------------- related comments
672  $related_comments = array();
673
674  $where_comments = 'image_id = '.$image_row['id'];
675  if ( !is_admin() )
676  {
677    $where_comments .= '
678    AND validated="true"';
679  }
680
681  $query = '
682SELECT COUNT(id) nb_comments
683  FROM '.COMMENTS_TABLE.'
684  WHERE '.$where_comments;
685  list($nb_comments) = array_from_query($query, 'nb_comments');
686  $nb_comments = (int)$nb_comments;
687
688  if ( $nb_comments>0 and $params['comments_per_page']>0 )
689  {
690    $query = '
691SELECT id, date, author, content
692  FROM '.COMMENTS_TABLE.'
693  WHERE '.$where_comments.'
694  ORDER BY date
695  LIMIT '.(int)($params['comments_per_page']*$params['comments_page']).
696    ','.(int)$params['comments_per_page'];
697
698    $result = pwg_query($query);
699    while ($row = mysql_fetch_assoc($result))
700    {
701      $row['id']=(int)$row['id'];
702      array_push($related_comments, $row);
703    }
704  }
705
706  $comment_post_data = null;
707  if ($is_commentable and
708      (!is_a_guest()
709        or (is_a_guest() and $conf['comments_forall'] )
710      )
711      )
712  {
713    $comment_post_data['author'] = $user['username'];
714    $comment_post_data['key'] = get_comment_post_key($params['image_id']);
715  }
716
717  $ret = $image_row;
718  foreach ( array('id','width','height','hit','filesize') as $k )
719  {
720    if (isset($ret[$k]))
721    {
722      $ret[$k] = (int)$ret[$k];
723    }
724  }
725  foreach ( array('path', 'storage_category_id') as $k )
726  {
727    unset($ret[$k]);
728  }
729
730  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
731  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
732  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
733  if ( isset($comment_post_data) )
734  {
735    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
736  }
737  $ret['comments'] = array(
738     WS_XML_ATTRIBUTES =>
739        array(
740          'page' => $params['comments_page'],
741          'per_page' => $params['comments_per_page'],
742          'count' => count($related_comments),
743          'nb_comments' => $nb_comments,
744        ),
745     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id','date') )
746      );
747
748  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
749}
750
751
752/**
753 * rates the image_id in the parameter
754 */
755function ws_images_Rate($params, &$service)
756{
757  $image_id = (int)$params['image_id'];
758  $query = '
759SELECT DISTINCT id FROM '.IMAGES_TABLE.'
760  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
761  WHERE id='.$image_id
762  .get_sql_condition_FandF(
763    array(
764        'forbidden_categories' => 'category_id',
765        'forbidden_images' => 'id',
766      ),
767    '    AND'
768    ).'
769    LIMIT 1';
770  if ( mysql_num_rows( pwg_query($query) )==0 )
771  {
772    return new PwgError(404, "Invalid image_id or access denied" );
773  }
774  $rate = (int)$params['rate'];
775  include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
776  $res = rate_picture( $image_id, $rate );
777  if ($res==false)
778  {
779    global $conf;
780    return new PwgError( 403, "Forbidden or rate not in ". implode(',',$conf['rate_items']));
781  }
782  return $res;
783}
784
785
786/**
787 * returns a list of elements corresponding to a query search
788 */
789function ws_images_search($params, &$service)
790{
791  global $page;
792  $images = array();
793  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
794  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
795
796  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
797  $order_by = ws_std_image_sql_order($params, 'i.');
798
799  $super_order_by = false;
800  if ( !empty($order_by) )
801  {
802    global $conf;
803    $conf['order_by'] = 'ORDER BY '.$order_by;
804    $super_order_by=true; // quick_search_result might be faster
805  }
806
807  $search_result = get_quick_search_results($params['query'],
808      $super_order_by,
809      implode(',', $where_clauses)
810    );
811
812  $image_ids = array_slice(
813      $search_result['items'],
814      $params['page']*$params['per_page'],
815      $params['per_page']
816    );
817
818  if ( count($image_ids) )
819  {
820    $query = '
821SELECT * FROM '.IMAGES_TABLE.'
822  WHERE id IN ('.implode(',', $image_ids).')';
823
824    $image_ids = array_flip($image_ids);
825    $result = pwg_query($query);
826    while ($row = mysql_fetch_assoc($result))
827    {
828      $image = array();
829      foreach ( array('id', 'width', 'height', 'hit') as $k )
830      {
831        if (isset($row[$k]))
832        {
833          $image[$k] = (int)$row[$k];
834        }
835      }
836      foreach ( array('file', 'name', 'comment') as $k )
837      {
838        $image[$k] = $row[$k];
839      }
840      $image = array_merge( $image, ws_std_get_urls($row) );
841      $images[$image_ids[$image['id']]] = $image;
842    }
843    ksort($images, SORT_NUMERIC);
844    $images = array_values($images);
845  }
846
847
848  return array( 'images' =>
849    array (
850      WS_XML_ATTRIBUTES =>
851        array(
852            'page' => $params['page'],
853            'per_page' => $params['per_page'],
854            'count' => count($images)
855          ),
856       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
857          ws_std_get_image_xml_attributes() )
858      )
859    );
860}
861
862function ws_images_setPrivacyLevel($params, &$service)
863{
864  if (!is_admin() || is_adviser() )
865  {
866    return new PwgError(401, 'Access denied');
867  }
868  if (!$service->isPost())
869  {
870    return new PwgError(405, "This method requires HTTP POST");
871  }
872  $params['image_id'] = array_map( 'intval',$params['image_id'] );
873  if ( empty($params['image_id']) )
874  {
875    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
876  }
877  global $conf;
878  if ( !in_array( (int)$params['level'], $conf['available_permission_levels']) )
879  {
880    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid level");
881  }
882
883  $query = '
884UPDATE '.IMAGES_TABLE.'
885  SET level='.(int)$params['level'].'
886  WHERE id IN ('.implode(',',$params['image_id']).')';
887  $result = pwg_query($query);
888  $affected_rows = mysql_affected_rows();
889  if ($affected_rows)
890  {
891    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
892    invalidate_user_cache();
893  }
894  return $affected_rows;
895}
896
897function ws_images_add_chunk($params, &$service)
898{
899  ws_logfile('[ws_images_add_chunk] welcome');
900  // data
901  // original_sum
902  // type {thumb, file, high}
903  // position
904
905  if (!is_admin() || is_adviser() )
906  {
907    return new PwgError(401, 'Access denied');
908  }
909
910  if (!$service->isPost())
911  {
912    return new PwgError(405, "This method requires HTTP POST");
913  }
914
915  foreach ($params as $param_key => $param_value) {
916    if ('data' == $param_key) {
917      continue;
918    }
919   
920    ws_logfile(
921      sprintf(
922        '[ws_images_add_chunk] input param "%s" : "%s"',
923        $param_key,
924        is_null($param_value) ? 'NULL' : $param_value
925        )
926      );
927  }
928
929  $upload_dir = PHPWG_ROOT_PATH.'upload/buffer';
930
931  // create the upload directory tree if not exists
932  if (!is_dir($upload_dir)) {
933    umask(0000);
934    $recursive = true;
935    if (!@mkdir($upload_dir, 0777, $recursive))
936    {
937      return new PwgError(500, 'error during buffer directory creation');
938    }
939  }
940
941  if (!is_writable($upload_dir))
942  {
943    // last chance to make the directory writable
944    @chmod($upload_dir, 0777);
945
946    if (!is_writable($upload_dir))
947    {
948      return new PwgError(500, 'buffer directory has no write access');
949    }
950  }
951
952  secure_directory($upload_dir);
953
954  $filename = sprintf(
955    '%s-%s-%05u.block',
956    $params['original_sum'],
957    $params['type'],
958    $params['position']
959    );
960
961  ws_logfile('[ws_images_add_chunk] data length : '.strlen($params['data']));
962
963  $bytes_written = file_put_contents(
964    $upload_dir.'/'.$filename,
965    base64_decode($params['data'])
966    );
967
968  if (false === $bytes_written) {
969    return new PwgError(
970      500,
971      'an error has occured while writting chunk '.$params['position'].' for '.$params['type']
972      );
973  }
974}
975
976function merge_chunks($output_filepath, $original_sum, $type)
977{
978  ws_logfile('[merge_chunks] input parameter $output_filepath : '.$output_filepath);
979
980  if (is_file($output_filepath))
981  {
982    unlink($output_filepath);
983
984    if (is_file($output_filepath))
985    {
986      new PwgError(500, '[merge_chunks] error while trying to remove existing '.$output_filepath);
987      exit();
988    }
989  }
990
991  $upload_dir = PHPWG_ROOT_PATH.'upload/buffer';
992  $pattern = '/'.$original_sum.'-'.$type.'/';
993  $chunks = array();
994
995  if ($handle = opendir($upload_dir))
996  {
997    while (false !== ($file = readdir($handle)))
998    {
999      if (preg_match($pattern, $file))
1000      {
1001        ws_logfile($file);
1002        array_push($chunks, $upload_dir.'/'.$file);
1003      }
1004    }
1005    closedir($handle);
1006  }
1007
1008  sort($chunks);
1009
1010  if (function_exists('memory_get_usage')) {
1011    ws_logfile('[merge_chunks] memory_get_usage before loading chunks: '.memory_get_usage());
1012  }
1013
1014  $i = 0;
1015
1016  foreach ($chunks as $chunk)
1017  {
1018    $string = file_get_contents($chunk);
1019
1020    if (function_exists('memory_get_usage')) {
1021      ws_logfile('[merge_chunks] memory_get_usage on chunk '.++$i.': '.memory_get_usage());
1022    }
1023
1024    if (!file_put_contents($output_filepath, $string, FILE_APPEND))
1025    {
1026      new PwgError(500, '[merge_chunks] error while writting chunks for '.$output_filepath);
1027      exit();
1028    }
1029
1030    unlink($chunk);
1031  }
1032
1033  if (function_exists('memory_get_usage')) {
1034    ws_logfile('[merge_chunks] memory_get_usage after loading chunks: '.memory_get_usage());
1035  }
1036}
1037
1038/*
1039 * The $file_path must be the path of the basic "web sized" photo
1040 * The $type value will automatically modify the $file_path to the corresponding file
1041 */
1042function add_file($file_path, $type, $original_sum, $file_sum)
1043{
1044  $file_path = file_path_for_type($file_path, $type);
1045
1046  $upload_dir = dirname($file_path);
1047  if (substr(PHP_OS, 0, 3) == 'WIN')
1048  {
1049    $upload_dir = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir);
1050  }
1051
1052  ws_logfile('[add_file] file_path  : '.$file_path);
1053  ws_logfile('[add_file] upload_dir : '.$upload_dir);
1054 
1055  if (!is_dir($upload_dir)) {
1056    umask(0000);
1057    $recursive = true;
1058    if (!@mkdir($upload_dir, 0777, $recursive))
1059    {
1060      new PwgError(500, '[add_file] error during '.$type.' directory creation');
1061      exit();
1062    }
1063  }
1064
1065  if (!is_writable($upload_dir))
1066  {
1067    // last chance to make the directory writable
1068    @chmod($upload_dir, 0777);
1069
1070    if (!is_writable($upload_dir))
1071    {
1072      new PwgError(500, '[add_file] '.$type.' directory has no write access');
1073      exit();
1074    }
1075  }
1076
1077  secure_directory($upload_dir);
1078
1079  // merge the thumbnail
1080  merge_chunks($file_path, $original_sum, $type);
1081  chmod($file_path, 0644);
1082
1083  // check dumped thumbnail md5
1084  $dumped_md5 = md5_file($file_path);
1085  if ($dumped_md5 != $file_sum) {
1086    new PwgError(500, '[add_file] '.$type.' transfer failed');
1087    exit();
1088  }
1089
1090  list($width, $height) = getimagesize($file_path);
1091  $filesize = floor(filesize($file_path)/1024);
1092
1093  return array(
1094    'width' => $width,
1095    'height' => $height,
1096    'filesize' => $filesize,
1097    );
1098}
1099
1100function ws_images_addFile($params, &$service)
1101{
1102  // image_id
1103  // type {thumb, file, high}
1104  // sum
1105
1106  global $conf;
1107  if (!is_admin() || is_adviser() )
1108  {
1109    return new PwgError(401, 'Access denied');
1110  }
1111
1112  $params['image_id'] = (int)$params['image_id'];
1113  if ($params['image_id'] <= 0)
1114  {
1115    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1116  }
1117
1118  //
1119  // what is the path?
1120  //
1121  $query = '
1122SELECT
1123    path,
1124    md5sum
1125  FROM '.IMAGES_TABLE.'
1126  WHERE id = '.$params['image_id'].'
1127;';
1128  list($file_path, $original_sum) = mysql_fetch_row(pwg_query($query));
1129
1130  // TODO only files added with web API can be updated with web API
1131
1132  //
1133  // makes sure directories are there and call the merge_chunks
1134  //
1135  $infos = add_file($file_path, $params['type'], $original_sum, $params['sum']);
1136
1137  //
1138  // update basic metadata from file
1139  //
1140  $update = array();
1141
1142  if ('high' == $params['type'])
1143  {
1144    $update['high_filesize'] = $infos['filesize'];
1145    $update['has_high'] = 'true';
1146  }
1147
1148  if ('file' == $params['type'])
1149  {
1150    $update['filesize'] = $infos['filesize'];
1151    $update['width'] = $infos['width'];
1152    $update['height'] = $infos['height'];
1153  }
1154
1155  // we may have nothing to update at database level, for example with a
1156  // thumbnail update
1157  if (count($update) > 0)
1158  {
1159    $update['id'] = $params['image_id'];
1160
1161    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1162    mass_updates(
1163      IMAGES_TABLE,
1164      array(
1165        'primary' => array('id'),
1166        'update'  => array_diff(array_keys($update), array('id'))
1167        ),
1168      array($update)
1169      );
1170  }
1171}
1172
1173function ws_images_add($params, &$service)
1174{
1175  global $conf;
1176  if (!is_admin() || is_adviser() )
1177  {
1178    return new PwgError(401, 'Access denied');
1179  }
1180
1181  foreach ($params as $param_key => $param_value) {
1182    ws_logfile(
1183      sprintf(
1184        '[pwg.images.add] input param "%s" : "%s"',
1185        $param_key,
1186        is_null($param_value) ? 'NULL' : $param_value
1187        )
1188      );
1189  }
1190
1191  // does the image already exists ?
1192  $query = '
1193SELECT
1194    COUNT(*) AS counter
1195  FROM '.IMAGES_TABLE.'
1196  WHERE md5sum = \''.$params['original_sum'].'\'
1197;';
1198  list($counter) = mysql_fetch_row(pwg_query($query));
1199  if ($counter != 0) {
1200    return new PwgError(500, 'file already exists');
1201  }
1202
1203  // current date
1204  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
1205  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
1206
1207  // upload directory hierarchy
1208  $upload_dir = sprintf(
1209    PHPWG_ROOT_PATH.'upload/%s/%s/%s',
1210    $year,
1211    $month,
1212    $day
1213    );
1214
1215  // compute file path
1216  $date_string = preg_replace('/[^\d]/', '', $dbnow);
1217  $random_string = substr($params['file_sum'], 0, 8);
1218  $filename_wo_ext = $date_string.'-'.$random_string;
1219  $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
1220
1221  // add files
1222  $file_infos  = add_file($file_path, 'file',  $params['original_sum'], $params['file_sum']);
1223  $thumb_infos = add_file($file_path, 'thumb', $params['original_sum'], $params['thumbnail_sum']);
1224
1225  if (isset($params['high_sum']))
1226  {
1227    $high_infos = add_file($file_path, 'high', $params['original_sum'], $params['high_sum']);
1228  }
1229
1230  // database registration
1231  $insert = array(
1232    'file' => $filename_wo_ext.'.jpg',
1233    'date_available' => $dbnow,
1234    'tn_ext' => 'jpg',
1235    'name' => $params['name'],
1236    'path' => $file_path,
1237    'filesize' => $file_infos['filesize'],
1238    'width' => $file_infos['width'],
1239    'height' => $file_infos['height'],
1240    'md5sum' => $params['original_sum'],
1241    );
1242
1243  $info_columns = array(
1244    'name',
1245    'author',
1246    'comment',
1247    'level',
1248    'date_creation',
1249    );
1250
1251  foreach ($info_columns as $key)
1252  {
1253    if (isset($params[$key]))
1254    {
1255      $insert[$key] = $params[$key];
1256    }
1257  }
1258
1259  if (isset($params['high_sum']))
1260  {
1261    $insert['has_high'] = 'true';
1262    $insert['high_filesize'] = $high_infos['filesize'];
1263  }
1264
1265  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1266  mass_inserts(
1267    IMAGES_TABLE,
1268    array_keys($insert),
1269    array($insert)
1270    );
1271
1272  $image_id = mysql_insert_id();
1273
1274  // let's add links between the image and the categories
1275  if (isset($params['categories']))
1276  {
1277    ws_add_image_category_relations($image_id, $params['categories']);
1278  }
1279
1280  // and now, let's create tag associations
1281  if (isset($params['tag_ids']) and !empty($params['tag_ids']))
1282  {
1283    set_tags(
1284      explode(',', $params['tag_ids']),
1285      $image_id
1286      );
1287  }
1288
1289  // update metadata from the uploaded file (exif/iptc)
1290  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1291  update_metadata(array($image_id=>$file_path));
1292 
1293  invalidate_user_cache();
1294}
1295
1296/**
1297 * perform a login (web service method)
1298 */
1299function ws_session_login($params, &$service)
1300{
1301  global $conf;
1302
1303  if (!$service->isPost())
1304  {
1305    return new PwgError(405, "This method requires HTTP POST");
1306  }
1307  if (try_log_user($params['username'], $params['password'],false))
1308  {
1309    return true;
1310  }
1311  return new PwgError(999, 'Invalid username/password');
1312}
1313
1314
1315/**
1316 * performs a logout (web service method)
1317 */
1318function ws_session_logout($params, &$service)
1319{
1320  if (!is_a_guest())
1321  {
1322    logout_user();
1323  }
1324  return true;
1325}
1326
1327function ws_session_getStatus($params, &$service)
1328{
1329  global $user;
1330  $res = array();
1331  $res['username'] = is_a_guest() ? 'guest' : $user['username'];
1332  foreach ( array('status', 'template', 'theme', 'language') as $k )
1333  {
1334    $res[$k] = $user[$k];
1335  }
1336  $res['charset'] = get_pwg_charset();
1337  return $res;
1338}
1339
1340
1341/**
1342 * returns a list of tags (web service method)
1343 */
1344function ws_tags_getList($params, &$service)
1345{
1346  $tags = get_available_tags();
1347  if ($params['sort_by_counter'])
1348  {
1349    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1350  }
1351  else
1352  {
1353    usort($tags, 'tag_alpha_compare');
1354  }
1355  for ($i=0; $i<count($tags); $i++)
1356  {
1357    $tags[$i]['id'] = (int)$tags[$i]['id'];
1358    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1359    $tags[$i]['url'] = make_index_url(
1360        array(
1361          'section'=>'tags',
1362          'tags'=>array($tags[$i])
1363        )
1364      );
1365  }
1366  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
1367}
1368
1369/**
1370 * returns the list of tags as you can see them in administration (web
1371 * service method).
1372 *
1373 * Only admin can run this method and permissions are not taken into
1374 * account.
1375 */
1376function ws_tags_getAdminList($params, &$service)
1377{
1378  if (!is_admin())
1379  {
1380    return new PwgError(401, 'Access denied');
1381  }
1382
1383  $tags = get_all_tags();
1384  return array(
1385    'tags' => new PwgNamedArray(
1386      $tags,
1387      'tag',
1388      array(
1389        'name',
1390        'id',
1391        'url_name',
1392        )
1393      )
1394    );
1395}
1396
1397/**
1398 * returns a list of images for tags (web service method)
1399 */
1400function ws_tags_getImages($params, &$service)
1401{
1402  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1403  global $conf;
1404
1405  // first build all the tag_ids we are interested in
1406  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1407  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1408  $tags_by_id = array();
1409  foreach( $tags as $tag )
1410  {
1411    $tags['id'] = (int)$tag['id'];
1412    $tags_by_id[ $tag['id'] ] = $tag;
1413  }
1414  unset($tags);
1415  $tag_ids = array_keys($tags_by_id);
1416
1417
1418  $image_ids = array();
1419  $image_tag_map = array();
1420
1421  if ( !empty($tag_ids) )
1422  { // build list of image ids with associated tags per image
1423    if ($params['tag_mode_and'])
1424    {
1425      $image_ids = get_image_ids_for_tags( $tag_ids );
1426    }
1427    else
1428    {
1429      $query = '
1430SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
1431  FROM '.IMAGE_TAG_TABLE.'
1432  WHERE tag_id IN ('.implode(',',$tag_ids).')
1433  GROUP BY image_id';
1434      $result = pwg_query($query);
1435      while ( $row=mysql_fetch_assoc($result) )
1436      {
1437        $row['image_id'] = (int)$row['image_id'];
1438        array_push( $image_ids, $row['image_id'] );
1439        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1440      }
1441    }
1442  }
1443
1444  $images = array();
1445  if ( !empty($image_ids))
1446  {
1447    $where_clauses = ws_std_image_sql_filter($params);
1448    $where_clauses[] = get_sql_condition_FandF(
1449        array
1450          (
1451            'forbidden_categories' => 'category_id',
1452            'visible_categories' => 'category_id',
1453            'visible_images' => 'i.id'
1454          ),
1455        '', true
1456      );
1457    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
1458
1459    $order_by = ws_std_image_sql_order($params);
1460    if (empty($order_by))
1461    {
1462      $order_by = $conf['order_by'];
1463    }
1464    else
1465    {
1466      $order_by = 'ORDER BY '.$order_by;
1467    }
1468
1469    $query = '
1470SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
1471  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
1472  WHERE '. implode('
1473    AND ', $where_clauses).'
1474'.$order_by.'
1475LIMIT '.(int)($params['per_page']*$params['page']).','.(int)$params['per_page'];
1476
1477    $result = pwg_query($query);
1478    while ($row = mysql_fetch_assoc($result))
1479    {
1480      $image = array();
1481      foreach ( array('id', 'width', 'height', 'hit') as $k )
1482      {
1483        if (isset($row[$k]))
1484        {
1485          $image[$k] = (int)$row[$k];
1486        }
1487      }
1488      foreach ( array('file', 'name', 'comment') as $k )
1489      {
1490        $image[$k] = $row[$k];
1491      }
1492      $image = array_merge( $image, ws_std_get_urls($row) );
1493
1494      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1495      $image_tags = array();
1496      foreach ($image_tag_ids as $tag_id)
1497      {
1498        $url = make_index_url(
1499                 array(
1500                  'section'=>'tags',
1501                  'tags'=> array($tags_by_id[$tag_id])
1502                )
1503              );
1504        $page_url = make_picture_url(
1505                 array(
1506                  'section'=>'tags',
1507                  'tags'=> array($tags_by_id[$tag_id]),
1508                  'image_id' => $row['id'],
1509                  'image_file' => $row['file'],
1510                )
1511              );
1512        array_push($image_tags, array(
1513                'id' => (int)$tag_id,
1514                'url' => $url,
1515                'page_url' => $page_url,
1516              )
1517            );
1518      }
1519      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1520              array('id','url_name','url','page_url')
1521            );
1522      array_push($images, $image);
1523    }
1524  }
1525
1526  return array( 'images' =>
1527    array (
1528      WS_XML_ATTRIBUTES =>
1529        array(
1530            'page' => $params['page'],
1531            'per_page' => $params['per_page'],
1532            'count' => count($images)
1533          ),
1534       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1535          ws_std_get_image_xml_attributes() )
1536      )
1537    );
1538}
1539
1540function ws_categories_add($params, &$service)
1541{
1542  if (!is_admin() or is_adviser())
1543  {
1544    return new PwgError(401, 'Access denied');
1545  }
1546
1547  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1548
1549  $creation_output = create_virtual_category(
1550    $params['name'],
1551    $params['parent']
1552    );
1553
1554  if (isset($creation_output['error']))
1555  {
1556    return new PwgError(500, $creation_output['error']);
1557  }
1558
1559  invalidate_user_cache();
1560
1561  return $creation_output;
1562}
1563
1564function ws_tags_add($params, &$service)
1565{
1566  if (!is_admin() or is_adviser())
1567  {
1568    return new PwgError(401, 'Access denied');
1569  }
1570
1571  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1572
1573  $creation_output = create_tag($params['name']);
1574
1575  if (isset($creation_output['error']))
1576  {
1577    return new PwgError(500, $creation_output['error']);
1578  }
1579
1580  return $creation_output;
1581}
1582
1583function ws_images_exist($params, &$service)
1584{
1585  if (!is_admin() or is_adviser())
1586  {
1587    return new PwgError(401, 'Access denied');
1588  }
1589
1590  // search among photos the list of photos already added, based on md5sum
1591  // list
1592  $md5sums = preg_split(
1593    '/[\s,;\|]/',
1594    $params['md5sum_list'],
1595    -1,
1596    PREG_SPLIT_NO_EMPTY
1597    );
1598
1599  $query = '
1600SELECT
1601    id,
1602    md5sum
1603  FROM '.IMAGES_TABLE.'
1604  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
1605;';
1606  $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
1607
1608  $result = array();
1609
1610  foreach ($md5sums as $md5sum)
1611  {
1612    $result[$md5sum] = null;
1613    if (isset($id_of_md5[$md5sum]))
1614    {
1615      $result[$md5sum] = $id_of_md5[$md5sum];
1616    }
1617  }
1618
1619  return $result;
1620}
1621
1622function ws_images_checkFiles($params, &$service)
1623{
1624  if (!is_admin() or is_adviser())
1625  {
1626    return new PwgError(401, 'Access denied');
1627  }
1628
1629  // input parameters
1630  //
1631  // image_id
1632  // thumbnail_sum
1633  // file_sum
1634  // high_sum
1635
1636  $params['image_id'] = (int)$params['image_id'];
1637  if ($params['image_id'] <= 0)
1638  {
1639    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1640  }
1641
1642  $query = '
1643SELECT
1644    path
1645  FROM '.IMAGES_TABLE.'
1646  WHERE id = '.$params['image_id'].'
1647;';
1648  $result = pwg_query($query);
1649  if (mysql_num_rows($result) == 0) {
1650    return new PwgError(404, "image_id not found");
1651  }
1652  list($path) = mysql_fetch_row($result);
1653
1654  $ret = array();
1655
1656  foreach (array('thumb', 'file', 'high') as $type) {
1657    $param_name = $type;
1658    if ('thumb' == $type) {
1659      $param_name = 'thumbnail';
1660    }
1661
1662    if (isset($params[$param_name.'_sum'])) {
1663      $type_path = file_path_for_type($path, $type);
1664      if (!is_file($type_path)) {
1665        $ret[$param_name] = 'missing';
1666      }
1667      else {
1668        if (md5_file($type_path) != $params[$param_name.'_sum']) {
1669          $ret[$param_name] = 'differs';
1670        }
1671        else {
1672          $ret[$param_name] = 'equals';
1673        }
1674      }
1675    }
1676  }
1677
1678  return $ret;
1679}
1680
1681function file_path_for_type($file_path, $type='thumb')
1682{
1683  // resolve the $file_path depending on the $type
1684  if ('thumb' == $type) {
1685    $file_path = get_thumbnail_location(
1686      array(
1687        'path' => $file_path,
1688        'tn_ext' => 'jpg',
1689        )
1690      );
1691  }
1692
1693  if ('high' == $type) {
1694    @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1695    $file_path = get_high_location(
1696      array(
1697        'path' => $file_path,
1698        'has_high' => 'true'
1699        )
1700      );
1701  }
1702
1703  return $file_path;
1704}
1705
1706function ws_images_setInfo($params, &$service)
1707{
1708  global $conf;
1709  if (!is_admin() || is_adviser() )
1710  {
1711    return new PwgError(401, 'Access denied');
1712  }
1713
1714  if (!$service->isPost())
1715  {
1716    return new PwgError(405, "This method requires HTTP POST");
1717  }
1718
1719  $params['image_id'] = (int)$params['image_id'];
1720  if ($params['image_id'] <= 0)
1721  {
1722    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1723  }
1724
1725  $query='
1726SELECT *
1727  FROM '.IMAGES_TABLE.'
1728  WHERE id = '.$params['image_id'].'
1729;';
1730
1731  $image_row = mysql_fetch_assoc(pwg_query($query));
1732  if ($image_row == null)
1733  {
1734    return new PwgError(404, "image_id not found");
1735  }
1736
1737  // database registration
1738  $update = array();
1739
1740  $info_columns = array(
1741    'name',
1742    'author',
1743    'comment',
1744    'level',
1745    'date_creation',
1746    );
1747
1748  foreach ($info_columns as $key)
1749  {
1750    if (isset($params[$key]))
1751    {
1752      if ('fill_if_empty' == $params['single_value_mode'])
1753      {
1754        if (empty($image_row[$key]))
1755        {
1756          $update[$key] = $params[$key];
1757        }
1758      }
1759      elseif ('replace' == $params['single_value_mode'])
1760      {
1761        $update[$key] = $params[$key];
1762      }
1763      else
1764      {
1765        new PwgError(
1766          500,
1767          '[ws_images_setInfo]'
1768          .' invalid parameter single_value_mode "'.$params['single_value_mode'].'"'
1769          .', possible values are {fill_if_empty, replace}.'
1770          );
1771        exit();
1772      }
1773    }
1774  }
1775
1776  if (count(array_keys($update)) > 0)
1777  {
1778    $update['id'] = $params['image_id'];
1779
1780    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1781    mass_updates(
1782      IMAGES_TABLE,
1783      array(
1784        'primary' => array('id'),
1785        'update'  => array_diff(array_keys($update), array('id'))
1786        ),
1787      array($update)
1788      );
1789  }
1790
1791  if (isset($params['categories']))
1792  {
1793    ws_add_image_category_relations(
1794      $params['image_id'],
1795      $params['categories'],
1796      ('replace' == $params['multiple_value_mode'] ? true : false)
1797      );
1798  }
1799
1800  // and now, let's create tag associations
1801  if (isset($params['tag_ids']))
1802  {
1803    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1804
1805    $tag_ids = explode(',', $params['tag_ids']);
1806
1807    if ('replace' == $params['multiple_value_mode'])
1808    {
1809      set_tags(
1810        $tag_ids,
1811        $params['image_id']
1812        );
1813    }
1814    elseif ('append' == $params['multiple_value_mode'])
1815    {
1816      add_tags(
1817        $tag_ids,
1818        array($params['image_id'])
1819        );
1820    }
1821    else
1822    {
1823      new PwgError(
1824        500,
1825        '[ws_images_setInfo]'
1826        .' invalid parameter multiple_value_mode "'.$params['multiple_value_mode'].'"'
1827        .', possible values are {replace, append}.'
1828        );
1829      exit();
1830    }
1831  }
1832
1833  invalidate_user_cache();
1834}
1835
1836function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
1837{
1838  // let's add links between the image and the categories
1839  //
1840  // $params['categories'] should look like 123,12;456,auto;789 which means:
1841  //
1842  // 1. associate with category 123 on rank 12
1843  // 2. associate with category 456 on automatic rank
1844  // 3. associate with category 789 on automatic rank
1845  $cat_ids = array();
1846  $rank_on_category = array();
1847  $search_current_ranks = false;
1848
1849  $tokens = explode(';', $categories_string);
1850  foreach ($tokens as $token)
1851  {
1852    @list($cat_id, $rank) = explode(',', $token);
1853
1854    if (!preg_match('/^\d+$/', $cat_id))
1855    {
1856      continue;
1857    }
1858
1859    array_push($cat_ids, $cat_id);
1860
1861    if (!isset($rank))
1862    {
1863      $rank = 'auto';
1864    }
1865    $rank_on_category[$cat_id] = $rank;
1866
1867    if ($rank == 'auto')
1868    {
1869      $search_current_ranks = true;
1870    }
1871  }
1872
1873  $cat_ids = array_unique($cat_ids);
1874
1875  if (count($cat_ids) == 0)
1876  {
1877    new PwgError(
1878      500,
1879      '[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
1880      );
1881    exit();
1882  }
1883
1884  $query = '
1885SELECT
1886    id
1887  FROM '.CATEGORIES_TABLE.'
1888  WHERE id IN ('.implode(',', $cat_ids).')
1889;';
1890  $db_cat_ids = array_from_query($query, 'id');
1891
1892  $unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
1893  if (count($unknown_cat_ids) != 0)
1894  {
1895    new PwgError(
1896      500,
1897      '[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
1898      );
1899    exit();
1900  }
1901
1902  $to_update_cat_ids = array();
1903
1904  // in case of replace mode, we first check the existing associations
1905  $query = '
1906SELECT
1907    category_id
1908  FROM '.IMAGE_CATEGORY_TABLE.'
1909  WHERE image_id = '.$image_id.'
1910;';
1911  $existing_cat_ids = array_from_query($query, 'category_id');
1912
1913  if ($replace_mode)
1914  {
1915    $to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
1916    if (count($to_remove_cat_ids) > 0)
1917    {
1918      $query = '
1919DELETE
1920  FROM '.IMAGE_CATEGORY_TABLE.'
1921  WHERE image_id = '.$image_id.'
1922    AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
1923;';
1924      pwg_query($query);
1925      update_category($to_remove_cat_ids);
1926    }
1927  }
1928
1929  $new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
1930  if (count($new_cat_ids) == 0)
1931  {
1932    return true;
1933  }
1934
1935  if ($search_current_ranks)
1936  {
1937    $query = '
1938SELECT
1939    category_id,
1940    MAX(rank) AS max_rank
1941  FROM '.IMAGE_CATEGORY_TABLE.'
1942  WHERE rank IS NOT NULL
1943    AND category_id IN ('.implode(',', $new_cat_ids).')
1944  GROUP BY category_id
1945;';
1946    $current_rank_of = simple_hash_from_query(
1947      $query,
1948      'category_id',
1949      'max_rank'
1950      );
1951
1952    foreach ($new_cat_ids as $cat_id)
1953    {
1954      if (!isset($current_rank_of[$cat_id]))
1955      {
1956        $current_rank_of[$cat_id] = 0;
1957      }
1958
1959      if ('auto' == $rank_on_category[$cat_id])
1960      {
1961        $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
1962      }
1963    }
1964  }
1965
1966  $inserts = array();
1967
1968  foreach ($new_cat_ids as $cat_id)
1969  {
1970    array_push(
1971      $inserts,
1972      array(
1973        'image_id' => $image_id,
1974        'category_id' => $cat_id,
1975        'rank' => $rank_on_category[$cat_id],
1976        )
1977      );
1978  }
1979
1980  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1981  mass_inserts(
1982    IMAGE_CATEGORY_TABLE,
1983    array_keys($inserts[0]),
1984    $inserts
1985    );
1986
1987  update_category($new_cat_ids);
1988}
1989
1990function ws_categories_setInfo($params, &$service)
1991{
1992  global $conf;
1993  if (!is_admin() || is_adviser() )
1994  {
1995    return new PwgError(401, 'Access denied');
1996  }
1997
1998  if (!$service->isPost())
1999  {
2000    return new PwgError(405, "This method requires HTTP POST");
2001  }
2002
2003  // category_id
2004  // name
2005  // comment
2006
2007  $params['category_id'] = (int)$params['category_id'];
2008  if ($params['category_id'] <= 0)
2009  {
2010    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2011  }
2012
2013  // database registration
2014  $update = array(
2015    'id' => $params['category_id'],
2016    );
2017
2018  $info_columns = array(
2019    'name',
2020    'comment',
2021    );
2022
2023  $perform_update = false;
2024  foreach ($info_columns as $key)
2025  {
2026    if (isset($params[$key]))
2027    {
2028      $perform_update = true;
2029      $update[$key] = $params[$key];
2030    }
2031  }
2032
2033  if ($perform_update)
2034  {
2035    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2036    mass_updates(
2037      CATEGORIES_TABLE,
2038      array(
2039        'primary' => array('id'),
2040        'update'  => array_diff(array_keys($update), array('id'))
2041        ),
2042      array($update)
2043      );
2044  }
2045
2046}
2047
2048function ws_logfile($string)
2049{
2050  global $conf;
2051
2052  if (!$conf['ws_enable_log']) {
2053    return true;
2054  }
2055
2056  file_put_contents(
2057    $conf['ws_log_filepath'],
2058    '['.date('c').'] '.$string."\n",
2059    FILE_APPEND
2060    );
2061}
2062?>
Note: See TracBrowser for help on using the repository browser.