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

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

Fix missing argument for pwg_db_changes()

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