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

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

merge r4883 from branch 2.0 to trunk

bug 1431: Community users now can see empty categories just like any admin.

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