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

Last change on this file since 4781 was 4781, checked in by nikrou, 14 years ago

Feature 511 : add support for sqlite database engine

Using session_write_close function when session handler use database because write is called after object destruction.

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