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

Last change on this file since 12730 was 12730, checked in by plg, 12 years ago

merge r12729 from branch 2.3 to trunk

feature 2489 added: ability to update "file" info in pwg.images.setInfo

  • Property svn:eol-style set to LF
File size: 85.3 KB
RevLine 
[1698]1<?php
2// +-----------------------------------------------------------------------+
[8728]3// | Piwigo - a PHP based photo gallery                                    |
[2297]4// +-----------------------------------------------------------------------+
[8728]5// | Copyright(C) 2008-2011 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  {
[11893]57    $clauses[] = $tbl_name.'rating_score>'.$params['f_min_rate'];
[1698]58  }
59  if ( is_numeric($params['f_max_rate']) )
60  {
[11893]61    $clauses[] = $tbl_name.'rating_score<='.$params['f_max_rate'];
[1698]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  }
[9576]71  if ( isset($params['f_min_date_available']) )
[1698]72  {
[9576]73    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_available']."'";
[1698]74  }
[9576]75  if ( isset($params['f_max_date_available']) )
[1698]76  {
[9576]77    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_available']."'";
[1698]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    }
[11893]126    $sortable_fields = array('id', 'file', 'name', 'hit', 'rating_score',
[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(
[11116]168    'id','tn_url','element_url','high_url', 'file','width','height','hit','date_available','date_creation'
[1845]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;
[9742]178  if ($conf['show_version'] or is_admin() )
[1852]179    return PHPWG_VERSION;
180  else
181    return new PwgError(403, 'Forbidden');
[1698]182}
183
[10017]184/**
185 * returns general informations (web service method)
186 */
187function ws_getInfos($params, &$service)
188{
[10061]189  if (!is_admin())
[10017]190  {
[10061]191    return new PwgError(403, 'Forbidden');
[10017]192  }
[10061]193
194  $infos['version'] = PHPWG_VERSION;
[11893]195
[10017]196  $query = 'SELECT COUNT(*) FROM '.IMAGES_TABLE.';';
197  list($infos['nb_elements']) = pwg_db_fetch_row(pwg_query($query));
198
199  $query = 'SELECT COUNT(*) FROM '.CATEGORIES_TABLE.';';
200  list($infos['nb_categories']) = pwg_db_fetch_row(pwg_query($query));
201
202  $query = 'SELECT COUNT(*) FROM '.CATEGORIES_TABLE.' WHERE dir IS NULL;';
203  list($infos['nb_virtual']) = pwg_db_fetch_row(pwg_query($query));
204
205  $query = 'SELECT COUNT(*) FROM '.CATEGORIES_TABLE.' WHERE dir IS NOT NULL;';
206  list($infos['nb_physical']) = pwg_db_fetch_row(pwg_query($query));
207
208  $query = 'SELECT COUNT(*) FROM '.IMAGE_CATEGORY_TABLE.';';
209  list($infos['nb_image_category']) = pwg_db_fetch_row(pwg_query($query));
210
211  $query = 'SELECT COUNT(*) FROM '.TAGS_TABLE.';';
212  list($infos['nb_tags']) = pwg_db_fetch_row(pwg_query($query));
213
214  $query = 'SELECT COUNT(*) FROM '.IMAGE_TAG_TABLE.';';
215  list($infos['nb_image_tag']) = pwg_db_fetch_row(pwg_query($query));
216
217  $query = 'SELECT COUNT(*) FROM '.USERS_TABLE.';';
218  list($infos['nb_users']) = pwg_db_fetch_row(pwg_query($query));
219
220  $query = 'SELECT COUNT(*) FROM '.GROUPS_TABLE.';';
221  list($infos['nb_groups']) = pwg_db_fetch_row(pwg_query($query));
222
223  $query = 'SELECT COUNT(*) FROM '.COMMENTS_TABLE.';';
224  list($infos['nb_comments']) = pwg_db_fetch_row(pwg_query($query));
225
226  // first element
227  if ($infos['nb_elements'] > 0)
228  {
229    $query = 'SELECT MIN(date_available) FROM '.IMAGES_TABLE.';';
230    list($infos['first_date']) = pwg_db_fetch_row(pwg_query($query));
231  }
232
233  // unvalidated comments
[10061]234  if ($infos['nb_comments'] > 0)
[10017]235  {
236    $query = 'SELECT COUNT(*) FROM '.COMMENTS_TABLE.' WHERE validated=\'false\';';
237    list($infos['nb_unvalidated_comments']) = pwg_db_fetch_row(pwg_query($query));
238  }
239
240  foreach ($infos as $name => $value)
241  {
242    $output[] = array(
243      'name' => $name,
244      'value' => $value,
245    );
246  }
247
248  return array('infos' => new PwgNamedArray($output, 'item'));
249}
250
[2429]251function ws_caddie_add($params, &$service)
252{
253  if (!is_admin())
254  {
255    return new PwgError(401, 'Access denied');
256  }
[2770]257  $params['image_id'] = array_map( 'intval',$params['image_id'] );
[2429]258  if ( empty($params['image_id']) )
259  {
260    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
261  }
262  global $user;
263  $query = '
264SELECT id
265  FROM '.IMAGES_TABLE.' LEFT JOIN '.CADDIE_TABLE.' ON id=element_id AND user_id='.$user['id'].'
266  WHERE id IN ('.implode(',',$params['image_id']).')
267    AND element_id IS NULL';
268  $datas = array();
269  foreach ( array_from_query($query, 'id') as $id )
270  {
271    array_push($datas, array('element_id'=>$id, 'user_id'=>$user['id']) );
272  }
273  if (count($datas))
274  {
275    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
276    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
277  }
278  return count($datas);
279}
[1781]280
[1698]281/**
[1781]282 * returns images per category (web service method)
[1711]283 */
[1698]284function ws_categories_getImages($params, &$service)
285{
286  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
287  global $user, $conf;
288
289  $images = array();
290
291  //------------------------------------------------- get the related categories
292  $where_clauses = array();
293  foreach($params['cat_id'] as $cat_id)
294  {
295    $cat_id = (int)$cat_id;
296    if ($cat_id<=0)
297      continue;
298    if ($params['recursive'])
299    {
[4367]300      $where_clauses[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.$cat_id.'(,|$)\'';
[1698]301    }
302    else
303    {
304      $where_clauses[] = 'id='.$cat_id;
305    }
306  }
307  if (!empty($where_clauses))
308  {
309    $where_clauses = array( '('.
310    implode('
311    OR ', $where_clauses) . ')'
312      );
313  }
[2119]314  $where_clauses[] = get_sql_condition_FandF(
315        array('forbidden_categories' => 'id'),
316        NULL, true
317      );
[1698]318
319  $query = '
[1866]320SELECT id, name, permalink, image_order
[1698]321  FROM '.CATEGORIES_TABLE.'
322  WHERE '. implode('
323    AND ', $where_clauses);
324  $result = pwg_query($query);
325  $cats = array();
[4325]326  while ($row = pwg_db_fetch_assoc($result))
[1698]327  {
328    $row['id'] = (int)$row['id'];
329    $cats[ $row['id'] ] = $row;
330  }
331
332  //-------------------------------------------------------- get the images
333  if ( !empty($cats) )
334  {
335    $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
336    $where_clauses[] = 'category_id IN ('
337      .implode(',', array_keys($cats) )
338      .')';
[1781]339    $where_clauses[] = get_sql_condition_FandF( array(
340          'visible_images' => 'i.id'
341        ), null, true
342      );
[1756]343
[1698]344    $order_by = ws_std_image_sql_order($params, 'i.');
[1852]345    if ( empty($order_by)
346          and count($params['cat_id'])==1
347          and isset($cats[ $params['cat_id'][0] ]['image_order'])
348        )
[1698]349    {
[1852]350      $order_by = $cats[ $params['cat_id'][0] ]['image_order'];
[1698]351    }
[1852]352    $order_by = empty($order_by) ? $conf['order_by'] : 'ORDER BY '.$order_by;
353
[1698]354    $query = '
[6652]355SELECT i.*, GROUP_CONCAT(category_id) AS cat_ids
[1698]356  FROM '.IMAGES_TABLE.' i
357    INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
358  WHERE '. implode('
359    AND ', $where_clauses).'
360GROUP BY i.id
361'.$order_by.'
[4334]362LIMIT '.(int)$params['per_page'].' OFFSET '.(int)($params['per_page']*$params['page']);
[1698]363
364    $result = pwg_query($query);
[4325]365    while ($row = pwg_db_fetch_assoc($result))
[1698]366    {
367      $image = array();
368      foreach ( array('id', 'width', 'height', 'hit') as $k )
369      {
370        if (isset($row[$k]))
371        {
372          $image[$k] = (int)$row[$k];
373        }
374      }
[11116]375      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
[1698]376      {
377        $image[$k] = $row[$k];
378      }
379      $image = array_merge( $image, ws_std_get_urls($row) );
380
381      $image_cats = array();
382      foreach ( explode(',', $row['cat_ids']) as $cat_id )
383      {
384        $url = make_index_url(
385                array(
[1861]386                  'category' => $cats[$cat_id],
[1698]387                  )
388                );
389        $page_url = make_picture_url(
390                array(
[1861]391                  'category' => $cats[$cat_id],
[1698]392                  'image_id' => $row['id'],
393                  'image_file' => $row['file'],
394                  )
395                );
396        array_push( $image_cats,  array(
397              WS_XML_ATTRIBUTES => array (
398                  'id' => (int)$cat_id,
399                  'url' => $url,
400                  'page_url' => $page_url,
401                )
402            )
403          );
404      }
405
406      $image['categories'] = new PwgNamedArray(
407            $image_cats,'category', array('id','url','page_url')
408          );
409      array_push($images, $image);
410    }
411  }
412
413  return array( 'images' =>
414    array (
415      WS_XML_ATTRIBUTES =>
416        array(
417            'page' => $params['page'],
418            'per_page' => $params['per_page'],
419            'count' => count($images)
420          ),
[1711]421       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
[1845]422          ws_std_get_image_xml_attributes() )
[1698]423      )
424    );
425}
426
[1781]427
[1698]428/**
[1781]429 * returns a list of categories (web service method)
[1698]430 */
431function ws_categories_getList($params, &$service)
432{
[1820]433  global $user,$conf;
[1698]434
[11155]435  if ($params['tree_output'])
436  {
437    if (!isset($_GET['format']) or !in_array($_GET['format'], array('php', 'json')))
438    {
439      // the algorithm used to build a tree from a flat list of categories
440      // keeps original array keys, which is not compatible with
441      // PwgNamedArray.
442      //
443      // PwgNamedArray is useful to define which data is an attribute and
444      // which is an element in the XML output. The "hierarchy" output is
445      // only compatible with json/php output.
[11893]446
[11155]447      return new PwgError(405, "The tree_output option is only compatible with json/php output formats");
448    }
449  }
450
[4884]451  $where = array('1=1');
452  $join_type = 'INNER';
453  $join_user = $user['id'];
[1698]454
455  if (!$params['recursive'])
456  {
457    if ($params['cat_id']>0)
[1820]458      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
459    OR id='.(int)($params['cat_id']).')';
[1698]460    else
461      $where[] = 'id_uppercat IS NULL';
462  }
[1820]463  else if ($params['cat_id']>0)
464  {
[4367]465    $where[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.
[1820]466      (int)($params['cat_id'])
467      .'(,|$)\'';
468  }
[1698]469
470  if ($params['public'])
471  {
472    $where[] = 'status = "public"';
[1711]473    $where[] = 'visible = "true"';
[11893]474
[4884]475    $join_user = $conf['guest_id'];
[1698]476  }
[4884]477  elseif (is_admin())
[1698]478  {
[4884]479    // in this very specific case, we don't want to hide empty
480    // categories. Function calculate_permissions will only return
481    // categories that are either locked or private and not permitted
[11893]482    //
[4884]483    // calculate_permissions does not consider empty categories as forbidden
484    $forbidden_categories = calculate_permissions($user['id'], $user['status']);
485    $where[]= 'id NOT IN ('.$forbidden_categories.')';
486    $join_type = 'LEFT';
[1698]487  }
488
[1711]489  $query = '
[11155]490SELECT id, name, permalink, uppercats, global_rank, id_uppercat,
[7550]491    comment,
[1845]492    nb_images, count_images AS total_nb_images,
[12544]493    user_representative_picture_id, count_images, count_categories,
[1845]494    date_last, max_date_last, count_categories AS nb_categories
[1711]495  FROM '.CATEGORIES_TABLE.'
[4884]496   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
[1698]497  WHERE '. implode('
498    AND ', $where);
499
500  $result = pwg_query($query);
501
[12543]502  // management of the album thumbnail -- starts here
503  $image_ids = array();
504  $categories = array();
505  $user_representative_updates_for = array();
506  // management of the album thumbnail -- stops here
507 
[1698]508  $cats = array();
[4325]509  while ($row = pwg_db_fetch_assoc($result))
[1698]510  {
511    $row['url'] = make_index_url(
512        array(
[1861]513          'category' => $row
[1698]514          )
515      );
[1845]516    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
[1698]517    {
518      $row[$key] = (int)$row[$key];
519    }
[2572]520
[11962]521    if ($params['fullname'])
522    {
523      $row['name'] = strip_tags(get_cat_display_name_cache($row['uppercats'], null, false));
524    }
525    else
526    {
527      $row['name'] = strip_tags(
528        trigger_event(
529          'render_category_name',
530          $row['name'],
531          'ws_categories_getList'
532          )
533        );
534    }
[11893]535
[7550]536    $row['comment'] = strip_tags(
537      trigger_event(
538        'render_category_description',
539        $row['comment'],
540        'ws_categories_getList'
541        )
542      );
[11893]543
[12543]544    // management of the album thumbnail -- starts here
545    //
546    // on branch 2.3, the algorithm is duplicated from
547    // include/category_cats, but we should use a common code for Piwigo 2.4
548    //
549    // warning : if the API method is called with $params['public'], the
550    // album thumbnail may be not accurate. The thumbnail can be viewed by
551    // the connected user, but maybe not by the guest. Changing the
552    // filtering method would be too complicated for now. We will simply
553    // avoid to persist the user_representative_picture_id in the database
554    // if $params['public']
555    if (!empty($row['user_representative_picture_id']))
556    {
557      $image_id = $row['user_representative_picture_id'];
558    }
559    else if (!empty($row['representative_picture_id']))
560    { // if a representative picture is set, it has priority
561      $image_id = $row['representative_picture_id'];
562    }
563    else if ($conf['allow_random_representative'])
564    {
565      // searching a random representant among elements in sub-categories
566      $image_id = get_random_image_in_category($row);
567    }
568    else
569    { // searching a random representant among representant of sub-categories
570      if ($row['count_categories']>0 and $row['count_images']>0)
571      {
572        $query = '
573  SELECT representative_picture_id
574    FROM '.CATEGORIES_TABLE.' INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.'
575    ON id = cat_id and user_id = '.$user['id'].'
576    WHERE uppercats LIKE \''.$row['uppercats'].',%\'
577      AND representative_picture_id IS NOT NULL'
578          .get_sql_condition_FandF
579          (
580            array
581            (
582              'visible_categories' => 'id',
583              ),
584            "\n  AND"
585            ).'
586    ORDER BY '.DB_RANDOM_FUNCTION.'()
587    LIMIT 1
588  ;';
589        $subresult = pwg_query($query);
590        if (pwg_db_num_rows($subresult) > 0)
591        {
592          list($image_id) = pwg_db_fetch_row($subresult);
593        }
594      }
595    }
596   
597    if (isset($image_id))
598    {
599      if ($conf['representative_cache_on_subcats'] and $row['user_representative_picture_id'] != $image_id)
600      {
601        $user_representative_updates_for[ $user['id'].'#'.$row['id'] ] = $image_id;
602      }
603   
604      $row['representative_picture_id'] = $image_id;
605      array_push($image_ids, $image_id);
606      array_push($categories, $row);
607    }
608    unset($image_id);
609    // management of the album thumbnail -- stops here
610
611
[1698]612    array_push($cats, $row);
613  }
614  usort($cats, 'global_rank_compare');
[11155]615
[12543]616  // management of the album thumbnail -- starts here
617  if (count($categories) > 0)
618  {
619    $thumbnail_src_of = array();
620    $new_image_ids = array();
621
622    $query = '
623SELECT id, path, tn_ext, level
624  FROM '.IMAGES_TABLE.'
625  WHERE id IN ('.implode(',', $image_ids).')
626;';
627    $result = pwg_query($query);
628    while ($row = pwg_db_fetch_assoc($result))
629    {
630      if ($row['level'] <= $user['level'])
631      {
632        $thumbnail_src_of[$row['id']] = get_thumbnail_url($row);
633      }
634      else
635      {
636        // problem: we must not display the thumbnail of a photo which has a
637        // higher privacy level than user privacy level
638        //
639        // * what is the represented category?
640        // * find a random photo matching user permissions
641        // * register it at user_representative_picture_id
642        // * set it as the representative_picture_id for the category
643       
644        foreach ($categories as &$category)
645        {
646          if ($row['id'] == $category['representative_picture_id'])
647          {
648            // searching a random representant among elements in sub-categories
649            $image_id = get_random_image_in_category($category);
650           
651            if (isset($image_id) and !in_array($image_id, $image_ids))
652            {
653              array_push($new_image_ids, $image_id);
654            }
655           
656            if ($conf['representative_cache_on_level'])
657            {
658              $user_representative_updates_for[ $user['id'].'#'.$category['id'] ] = $image_id;
659            }
660           
661            $category['representative_picture_id'] = $image_id;
662          }
663        }
664        unset($category);
665      }
666    }
667   
668    if (count($new_image_ids) > 0)
669    {
670      $query = '
671SELECT id, path, tn_ext
672  FROM '.IMAGES_TABLE.'
673  WHERE id IN ('.implode(',', $new_image_ids).')
674;';
675      $result = pwg_query($query);
676      while ($row = pwg_db_fetch_assoc($result))
677      {
678        $thumbnail_src_of[$row['id']] = get_thumbnail_url($row);
679      }
680    }
681  }
682
683  // compared to code in include/category_cats, we only persist the new
684  // user_representative if we have used $user['id'] and not the guest id,
685  // or else the real guest may see thumbnail that he should not
686  if (!$params['public'] and count($user_representative_updates_for))
687  {
688    $updates = array();
689 
690    foreach ($user_representative_updates_for as $user_cat => $image_id)
691    {
692      list($user_id, $cat_id) = explode('#', $user_cat);
693   
694      array_push(
695        $updates,
696        array(
697          'user_id' => $user_id,
698          'cat_id' => $cat_id,
699          'user_representative_picture_id' => $image_id,
700          )
701        );
702    }
703
704    mass_updates(
705      USER_CACHE_CATEGORIES_TABLE,
706      array(
707        'primary' => array('user_id', 'cat_id'),
708        'update'  => array('user_representative_picture_id')
709        ),
710      $updates
711      );
712  }
713
714  foreach ($cats as &$cat)
715  {
716    foreach ($categories as $category)
717    {
718      if ($category['id'] == $cat['id'])
719      {
720        $cat['tn_url'] = $thumbnail_src_of[$category['representative_picture_id']];
721      }
722    }
723    // we don't want them in the output
724    unset($cat['user_representative_picture_id']);
725    unset($cat['count_images']);
[12544]726    unset($cat['count_categories']);
[12543]727  }
728  unset($cat); 
729  // management of the album thumbnail -- stops here
730
[11155]731  if ($params['tree_output'])
[11893]732  {
[11155]733    return categories_flatlist_to_tree($cats);
734  }
735  else
736  {
737    return array(
738      'categories' => new PwgNamedArray(
739        $cats,
740        'category',
741        array(
742          'id',
743          'url',
744          'nb_images',
745          'total_nb_images',
746          'nb_categories',
747          'date_last',
748          'max_date_last',
749          )
[2548]750        )
[11155]751      );
752  }
[1698]753}
754
[2563]755/**
756 * returns the list of categories as you can see them in administration (web
757 * service method).
758 *
759 * Only admin can run this method and permissions are not taken into
760 * account.
761 */
762function ws_categories_getAdminList($params, &$service)
763{
764  if (!is_admin())
765  {
766    return new PwgError(401, 'Access denied');
767  }
[1781]768
[2563]769  $query = '
770SELECT
771    category_id,
772    COUNT(*) AS counter
773  FROM '.IMAGE_CATEGORY_TABLE.'
774  GROUP BY category_id
775;';
776  $nb_images_of = simple_hash_from_query($query, 'category_id', 'counter');
777
778  $query = '
779SELECT
780    id,
781    name,
[7550]782    comment,
[2563]783    uppercats,
784    global_rank
785  FROM '.CATEGORIES_TABLE.'
786;';
787  $result = pwg_query($query);
788  $cats = array();
789
[4325]790  while ($row = pwg_db_fetch_assoc($result))
[2563]791  {
792    $id = $row['id'];
793    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
[4903]794    $row['name'] = strip_tags(
795      trigger_event(
796        'render_category_name',
797        $row['name'],
798        'ws_categories_getAdminList'
799        )
800      );
[7550]801    $row['comment'] = strip_tags(
802      trigger_event(
803        'render_category_description',
804        $row['comment'],
805        'ws_categories_getAdminList'
806        )
807      );
[2563]808    array_push($cats, $row);
[2585]809  }
810
[2563]811  usort($cats, 'global_rank_compare');
812  return array(
813    'categories' => new PwgNamedArray(
814      $cats,
815      'category',
816      array(
817        'id',
818        'nb_images',
819        'name',
820        'uppercats',
821        'global_rank',
822        )
823      )
824    );
825}
826
[1781]827/**
828 * returns detailed information for an element (web service method)
829 */
[1849]830function ws_images_addComment($params, &$service)
831{
[1852]832  if (!$service->isPost())
833  {
834    return new PwgError(405, "This method requires HTTP POST");
835  }
[1849]836  $params['image_id'] = (int)$params['image_id'];
837  $query = '
[2119]838SELECT DISTINCT image_id
[1849]839  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
[2119]840  WHERE commentable="true"
[1849]841    AND image_id='.$params['image_id'].
842    get_sql_condition_FandF(
843      array(
844        'forbidden_categories' => 'id',
845        'visible_categories' => 'id',
846        'visible_images' => 'image_id'
847      ),
848      ' AND'
849    );
[4325]850  if ( !pwg_db_num_rows( pwg_query( $query ) ) )
[1849]851  {
852    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
853  }
[2119]854
[1849]855  $comm = array(
[6437]856    'author' => trim( $params['author'] ),
857    'content' => trim( $params['content'] ),
[1849]858    'image_id' => $params['image_id'],
859   );
860
861  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
[2119]862
863  $comment_action = insert_user_comment(
[1849]864      $comm, $params['key'], $infos
865    );
866
867  switch ($comment_action)
868  {
869    case 'reject':
[5021]870      array_push($infos, l10n('Your comment has NOT been registered because it did not pass the validation rules') );
[7782]871      return new PwgError(403, implode("; ", $infos) );
[1849]872    case 'validate':
873    case 'moderate':
[2119]874      $ret = array(
[1849]875          'id' => $comm['id'],
876          'validation' => $comment_action=='validate',
877        );
878      return new PwgNamedStruct(
879          'comment',
[2119]880          $ret,
881          null, array()
[1849]882        );
883    default:
884      return new PwgError(500, "Unknown comment action ".$comment_action );
885  }
886}
887
888/**
889 * returns detailed information for an element (web service method)
890 */
[1698]891function ws_images_getInfo($params, &$service)
892{
893  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
[1849]894  global $user, $conf;
[1698]895  $params['image_id'] = (int)$params['image_id'];
896  if ( $params['image_id']<=0 )
897  {
898    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
899  }
[1781]900
[1698]901  $query='
902SELECT * FROM '.IMAGES_TABLE.'
[1711]903  WHERE id='.$params['image_id'].
904    get_sql_condition_FandF(
905      array('visible_images' => 'id'),
906      ' AND'
[2516]907    ).'
908LIMIT 1';
[1711]909
[4325]910  $image_row = pwg_db_fetch_assoc(pwg_query($query));
[1698]911  if ($image_row==null)
912  {
[1852]913    return new PwgError(404, "image_id not found");
[1698]914  }
[1845]915  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
[1698]916
917  //-------------------------------------------------------- related categories
918  $query = '
[1866]919SELECT id, name, permalink, uppercats, global_rank, commentable
[1698]920  FROM '.IMAGE_CATEGORY_TABLE.'
[1849]921    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
[2119]922  WHERE image_id = '.$image_row['id'].
923  get_sql_condition_FandF(
924      array( 'forbidden_categories' => 'category_id' ),
925      ' AND'
926    ).'
[1698]927;';
928  $result = pwg_query($query);
[1849]929  $is_commentable = false;
[1698]930  $related_categories = array();
[4325]931  while ($row = pwg_db_fetch_assoc($result))
[1698]932  {
[1849]933    if ($row['commentable']=='true')
934    {
935      $is_commentable = true;
936    }
937    unset($row['commentable']);
[1698]938    $row['url'] = make_index_url(
939        array(
[1861]940          'category' => $row
[1698]941          )
942      );
943
944    $row['page_url'] = make_picture_url(
945        array(
946          'image_id' => $image_row['id'],
947          'image_file' => $image_row['file'],
[1861]948          'category' => $row
[1698]949          )
950      );
[1849]951    $row['id']=(int)$row['id'];
[1698]952    array_push($related_categories, $row);
953  }
954  usort($related_categories, 'global_rank_compare');
955  if ( empty($related_categories) )
956  {
957    return new PwgError(401, 'Access denied');
958  }
959
960  //-------------------------------------------------------------- related tags
[1815]961  $related_tags = get_common_tags( array($image_row['id']), -1 );
962  foreach( $related_tags as $i=>$tag)
[1698]963  {
[1815]964    $tag['url'] = make_index_url(
[1698]965        array(
[1815]966          'tags' => array($tag)
[1698]967          )
968      );
[1815]969    $tag['page_url'] = make_picture_url(
[1698]970        array(
971          'image_id' => $image_row['id'],
972          'image_file' => $image_row['file'],
[1815]973          'tags' => array($tag),
[1698]974          )
975      );
[1815]976    unset($tag['counter']);
[1849]977    $tag['id']=(int)$tag['id'];
[1815]978    $related_tags[$i]=$tag;
[1698]979  }
[1849]980  //------------------------------------------------------------- related rates
[11893]981        $rating = array('score'=>$image_row['rating_score'], 'count'=>0, 'average'=>null);
[11827]982        if (isset($rating['score']))
983        {
984                $query = '
[1849]985SELECT COUNT(rate) AS count
986     , ROUND(AVG(rate),2) AS average
987  FROM '.RATE_TABLE.'
988  WHERE element_id = '.$image_row['id'].'
989;';
[11827]990                $row = pwg_db_fetch_assoc(pwg_query($query));
991                $rating['score'] = (float)$rating['score'];
992                $rating['average'] = (float)$row['average'];
993                $rating['count'] = (int)$row['count'];
994        }
[1849]995
[1698]996  //---------------------------------------------------------- related comments
[1849]997  $related_comments = array();
[2119]998
[1849]999  $where_comments = 'image_id = '.$image_row['id'];
1000  if ( !is_admin() )
1001  {
1002    $where_comments .= '
1003    AND validated="true"';
1004  }
1005
[1698]1006  $query = '
[6652]1007SELECT COUNT(id) AS nb_comments
[1698]1008  FROM '.COMMENTS_TABLE.'
[1849]1009  WHERE '.$where_comments;
[1698]1010  list($nb_comments) = array_from_query($query, 'nb_comments');
[1849]1011  $nb_comments = (int)$nb_comments;
[1698]1012
[1849]1013  if ( $nb_comments>0 and $params['comments_per_page']>0 )
1014  {
1015    $query = '
[1698]1016SELECT id, date, author, content
1017  FROM '.COMMENTS_TABLE.'
[1849]1018  WHERE '.$where_comments.'
1019  ORDER BY date
[4334]1020  LIMIT '.(int)$params['comments_per_page'].
1021    ' OFFSET '.(int)($params['comments_per_page']*$params['comments_page']);
[1698]1022
[1849]1023    $result = pwg_query($query);
[4325]1024    while ($row = pwg_db_fetch_assoc($result))
[1849]1025    {
1026      $row['id']=(int)$row['id'];
1027      array_push($related_comments, $row);
1028    }
1029  }
[2119]1030
[1849]1031  $comment_post_data = null;
[2119]1032  if ($is_commentable and
[2029]1033      (!is_a_guest()
1034        or (is_a_guest() and $conf['comments_forall'] )
[1849]1035      )
1036      )
[1698]1037  {
[4304]1038    $comment_post_data['author'] = stripslashes($user['username']);
[7495]1039    $comment_post_data['key'] = get_ephemeral_key(2, $params['image_id']);
[1698]1040  }
1041
[1849]1042  $ret = $image_row;
1043  foreach ( array('id','width','height','hit','filesize') as $k )
1044  {
1045    if (isset($ret[$k]))
1046    {
1047      $ret[$k] = (int)$ret[$k];
1048    }
1049  }
1050  foreach ( array('path', 'storage_category_id') as $k )
1051  {
1052    unset($ret[$k]);
1053  }
[1698]1054
[1849]1055  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
[1698]1056  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
[2585]1057  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
[1849]1058  if ( isset($comment_post_data) )
1059  {
1060    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
1061  }
[1698]1062  $ret['comments'] = array(
[2119]1063     WS_XML_ATTRIBUTES =>
[1849]1064        array(
1065          'page' => $params['comments_page'],
1066          'per_page' => $params['comments_per_page'],
1067          'count' => count($related_comments),
1068          'nb_comments' => $nb_comments,
1069        ),
1070     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id','date') )
[1698]1071      );
[1845]1072
[1698]1073  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
1074}
1075
[2435]1076
[1837]1077/**
[2435]1078 * rates the image_id in the parameter
1079 */
1080function ws_images_Rate($params, &$service)
1081{
1082  $image_id = (int)$params['image_id'];
1083  $query = '
1084SELECT DISTINCT id FROM '.IMAGES_TABLE.'
1085  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
1086  WHERE id='.$image_id
1087  .get_sql_condition_FandF(
1088    array(
1089        'forbidden_categories' => 'category_id',
1090        'forbidden_images' => 'id',
1091      ),
1092    '    AND'
1093    ).'
1094    LIMIT 1';
[4325]1095  if ( pwg_db_num_rows( pwg_query($query) )==0 )
[2435]1096  {
1097    return new PwgError(404, "Invalid image_id or access denied" );
1098  }
1099  $rate = (int)$params['rate'];
1100  include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
1101  $res = rate_picture( $image_id, $rate );
1102  if ($res==false)
1103  {
1104    global $conf;
1105    return new PwgError( 403, "Forbidden or rate not in ". implode(',',$conf['rate_items']));
1106  }
1107  return $res;
1108}
1109
1110
1111/**
[1837]1112 * returns a list of elements corresponding to a query search
1113 */
1114function ws_images_search($params, &$service)
1115{
1116  global $page;
1117  $images = array();
1118  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
1119  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
[1698]1120
[2135]1121  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
1122  $order_by = ws_std_image_sql_order($params, 'i.');
[1837]1123
[2451]1124  $super_order_by = false;
[2135]1125  if ( !empty($order_by) )
[1837]1126  {
[2135]1127    global $conf;
1128    $conf['order_by'] = 'ORDER BY '.$order_by;
[2451]1129    $super_order_by=true; // quick_search_result might be faster
[1837]1130  }
1131
[2135]1132  $search_result = get_quick_search_results($params['query'],
[2451]1133      $super_order_by,
1134      implode(',', $where_clauses)
1135    );
[2119]1136
[2451]1137  $image_ids = array_slice(
1138      $search_result['items'],
1139      $params['page']*$params['per_page'],
1140      $params['per_page']
1141    );
[1837]1142
1143  if ( count($image_ids) )
1144  {
1145    $query = '
1146SELECT * FROM '.IMAGES_TABLE.'
[2451]1147  WHERE id IN ('.implode(',', $image_ids).')';
[1837]1148
[2451]1149    $image_ids = array_flip($image_ids);
[1837]1150    $result = pwg_query($query);
[4325]1151    while ($row = pwg_db_fetch_assoc($result))
[1837]1152    {
1153      $image = array();
1154      foreach ( array('id', 'width', 'height', 'hit') as $k )
1155      {
1156        if (isset($row[$k]))
1157        {
1158          $image[$k] = (int)$row[$k];
1159        }
1160      }
[11116]1161      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
[1837]1162      {
1163        $image[$k] = $row[$k];
1164      }
1165      $image = array_merge( $image, ws_std_get_urls($row) );
[2451]1166      $images[$image_ids[$image['id']]] = $image;
[1837]1167    }
[2451]1168    ksort($images, SORT_NUMERIC);
1169    $images = array_values($images);
[1837]1170  }
1171
1172
1173  return array( 'images' =>
1174    array (
1175      WS_XML_ATTRIBUTES =>
1176        array(
1177            'page' => $params['page'],
1178            'per_page' => $params['per_page'],
1179            'count' => count($images)
1180          ),
1181       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
[1845]1182          ws_std_get_image_xml_attributes() )
[1837]1183      )
1184    );
1185}
1186
[2413]1187function ws_images_setPrivacyLevel($params, &$service)
1188{
[8126]1189  if (!is_admin())
[2413]1190  {
1191    return new PwgError(401, 'Access denied');
1192  }
[4513]1193  if (!$service->isPost())
1194  {
1195    return new PwgError(405, "This method requires HTTP POST");
1196  }
[2770]1197  $params['image_id'] = array_map( 'intval',$params['image_id'] );
[2413]1198  if ( empty($params['image_id']) )
1199  {
1200    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1201  }
1202  global $conf;
1203  if ( !in_array( (int)$params['level'], $conf['available_permission_levels']) )
1204  {
1205    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid level");
1206  }
[4513]1207
[2413]1208  $query = '
1209UPDATE '.IMAGES_TABLE.'
1210  SET level='.(int)$params['level'].'
1211  WHERE id IN ('.implode(',',$params['image_id']).')';
1212  $result = pwg_query($query);
[5930]1213  $affected_rows = pwg_db_changes($result);
[2413]1214  if ($affected_rows)
1215  {
1216    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1217    invalidate_user_cache();
1218  }
1219  return $affected_rows;
1220}
1221
[11372]1222function ws_images_setRank($params, &$service)
1223{
1224  if (!is_admin())
1225  {
1226    return new PwgError(401, 'Access denied');
1227  }
[11893]1228
[11372]1229  if (!$service->isPost())
1230  {
1231    return new PwgError(405, "This method requires HTTP POST");
1232  }
1233
1234  // is the image_id valid?
1235  $params['image_id'] = (int)$params['image_id'];
1236  if ($params['image_id'] <= 0)
1237  {
1238    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1239  }
1240
1241  // is the category valid?
1242  $params['category_id'] = (int)$params['category_id'];
1243  if ($params['category_id'] <= 0)
1244  {
1245    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
1246  }
1247
1248  // is the rank valid?
1249  $params['rank'] = (int)$params['rank'];
1250  if ($params['rank'] <= 0)
1251  {
1252    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid rank");
1253  }
[11893]1254
[11372]1255  // does the image really exist?
1256  $query='
1257SELECT
1258    *
1259  FROM '.IMAGES_TABLE.'
1260  WHERE id = '.$params['image_id'].'
1261;';
1262
1263  $image_row = pwg_db_fetch_assoc(pwg_query($query));
1264  if ($image_row == null)
1265  {
1266    return new PwgError(404, "image_id not found");
1267  }
[11893]1268
[11372]1269  // is the image associated to this category?
1270  $query = '
1271SELECT
1272    image_id,
1273    category_id,
1274    rank
1275  FROM '.IMAGE_CATEGORY_TABLE.'
1276  WHERE image_id = '.$params['image_id'].'
1277    AND category_id = '.$params['category_id'].'
1278;';
1279  $category_row = pwg_db_fetch_assoc(pwg_query($query));
1280  if ($category_row == null)
1281  {
1282    return new PwgError(404, "This image is not associated to this category");
1283  }
1284
1285  // what is the current higher rank for this category?
1286  $query = '
1287SELECT
1288    MAX(rank) AS max_rank
1289  FROM '.IMAGE_CATEGORY_TABLE.'
1290  WHERE category_id = '.$params['category_id'].'
1291;';
1292  $result = pwg_query($query);
1293  $row = pwg_db_fetch_assoc($result);
1294
1295  if (is_numeric($row['max_rank']))
1296  {
1297    if ($params['rank'] > $row['max_rank'])
1298    {
1299      $params['rank'] = $row['max_rank'] + 1;
1300    }
1301  }
1302  else
1303  {
1304    $params['rank'] = 1;
1305  }
1306
1307  // update rank for all other photos in the same category
1308  $query = '
1309UPDATE '.IMAGE_CATEGORY_TABLE.'
1310  SET rank = rank + 1
1311  WHERE category_id = '.$params['category_id'].'
1312    AND rank IS NOT NULL
1313    AND rank >= '.$params['rank'].'
1314;';
1315  pwg_query($query);
1316
1317  // set the new rank for the photo
1318  $query = '
1319UPDATE '.IMAGE_CATEGORY_TABLE.'
1320  SET rank = '.$params['rank'].'
1321  WHERE image_id = '.$params['image_id'].'
1322    AND category_id = '.$params['category_id'].'
1323;';
1324  pwg_query($query);
1325
1326  // return data for client
1327  return array(
1328    'image_id' => $params['image_id'],
1329    'category_id' => $params['category_id'],
1330    'rank' => $params['rank'],
1331    );
1332}
1333
[3193]1334function ws_images_add_chunk($params, &$service)
1335{
[5014]1336  global $conf;
[11893]1337
[4900]1338  ws_logfile('[ws_images_add_chunk] welcome');
[3193]1339  // data
1340  // original_sum
1341  // type {thumb, file, high}
1342  // position
[3488]1343
[8126]1344  if (!is_admin())
[3193]1345  {
1346    return new PwgError(401, 'Access denied');
1347  }
1348
[4511]1349  if (!$service->isPost())
1350  {
1351    return new PwgError(405, "This method requires HTTP POST");
1352  }
1353
[4900]1354  foreach ($params as $param_key => $param_value) {
1355    if ('data' == $param_key) {
1356      continue;
1357    }
[11893]1358
[4900]1359    ws_logfile(
1360      sprintf(
1361        '[ws_images_add_chunk] input param "%s" : "%s"',
1362        $param_key,
1363        is_null($param_value) ? 'NULL' : $param_value
1364        )
1365      );
1366  }
1367
[5014]1368  $upload_dir = $conf['upload_dir'].'/buffer';
[3193]1369
1370  // create the upload directory tree if not exists
1371  if (!is_dir($upload_dir)) {
1372    umask(0000);
1373    $recursive = true;
1374    if (!@mkdir($upload_dir, 0777, $recursive))
1375    {
1376      return new PwgError(500, 'error during buffer directory creation');
1377    }
1378  }
1379
1380  if (!is_writable($upload_dir))
1381  {
1382    // last chance to make the directory writable
1383    @chmod($upload_dir, 0777);
1384
1385    if (!is_writable($upload_dir))
1386    {
1387      return new PwgError(500, 'buffer directory has no write access');
1388    }
1389  }
1390
1391  secure_directory($upload_dir);
1392
1393  $filename = sprintf(
1394    '%s-%s-%05u.block',
1395    $params['original_sum'],
1396    $params['type'],
1397    $params['position']
1398    );
1399
[3240]1400  ws_logfile('[ws_images_add_chunk] data length : '.strlen($params['data']));
1401
[3193]1402  $bytes_written = file_put_contents(
1403    $upload_dir.'/'.$filename,
[3240]1404    base64_decode($params['data'])
[3193]1405    );
1406
1407  if (false === $bytes_written) {
1408    return new PwgError(
1409      500,
1410      'an error has occured while writting chunk '.$params['position'].' for '.$params['type']
1411      );
1412  }
1413}
1414
1415function merge_chunks($output_filepath, $original_sum, $type)
1416{
[5014]1417  global $conf;
[11893]1418
[3193]1419  ws_logfile('[merge_chunks] input parameter $output_filepath : '.$output_filepath);
1420
[4348]1421  if (is_file($output_filepath))
1422  {
1423    unlink($output_filepath);
[4513]1424
[4348]1425    if (is_file($output_filepath))
1426    {
1427      new PwgError(500, '[merge_chunks] error while trying to remove existing '.$output_filepath);
1428      exit();
1429    }
1430  }
[4513]1431
[5014]1432  $upload_dir = $conf['upload_dir'].'/buffer';
[3193]1433  $pattern = '/'.$original_sum.'-'.$type.'/';
1434  $chunks = array();
[3488]1435
[3193]1436  if ($handle = opendir($upload_dir))
1437  {
1438    while (false !== ($file = readdir($handle)))
1439    {
1440      if (preg_match($pattern, $file))
1441      {
1442        ws_logfile($file);
1443        array_push($chunks, $upload_dir.'/'.$file);
1444      }
1445    }
1446    closedir($handle);
1447  }
1448
1449  sort($chunks);
[3240]1450
[4425]1451  if (function_exists('memory_get_usage')) {
1452    ws_logfile('[merge_chunks] memory_get_usage before loading chunks: '.memory_get_usage());
1453  }
[3488]1454
[3514]1455  $i = 0;
[4513]1456
[3240]1457  foreach ($chunks as $chunk)
1458  {
1459    $string = file_get_contents($chunk);
[3488]1460
[4425]1461    if (function_exists('memory_get_usage')) {
1462      ws_logfile('[merge_chunks] memory_get_usage on chunk '.++$i.': '.memory_get_usage());
1463    }
[3488]1464
[3240]1465    if (!file_put_contents($output_filepath, $string, FILE_APPEND))
1466    {
[4346]1467      new PwgError(500, '[merge_chunks] error while writting chunks for '.$output_filepath);
1468      exit();
[3240]1469    }
[3488]1470
[3193]1471    unlink($chunk);
1472  }
[3240]1473
[4425]1474  if (function_exists('memory_get_usage')) {
1475    ws_logfile('[merge_chunks] memory_get_usage after loading chunks: '.memory_get_usage());
1476  }
[3193]1477}
1478
[4346]1479/*
1480 * The $file_path must be the path of the basic "web sized" photo
1481 * The $type value will automatically modify the $file_path to the corresponding file
1482 */
1483function add_file($file_path, $type, $original_sum, $file_sum)
1484{
[8249]1485  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[11893]1486
[4347]1487  $file_path = file_path_for_type($file_path, $type);
[4346]1488
1489  $upload_dir = dirname($file_path);
[4900]1490  if (substr(PHP_OS, 0, 3) == 'WIN')
1491  {
1492    $upload_dir = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir);
1493  }
[4513]1494
[4900]1495  ws_logfile('[add_file] file_path  : '.$file_path);
1496  ws_logfile('[add_file] upload_dir : '.$upload_dir);
[11893]1497
[4346]1498  if (!is_dir($upload_dir)) {
1499    umask(0000);
1500    $recursive = true;
1501    if (!@mkdir($upload_dir, 0777, $recursive))
1502    {
1503      new PwgError(500, '[add_file] error during '.$type.' directory creation');
1504      exit();
1505    }
1506  }
1507
1508  if (!is_writable($upload_dir))
1509  {
1510    // last chance to make the directory writable
1511    @chmod($upload_dir, 0777);
1512
1513    if (!is_writable($upload_dir))
1514    {
1515      new PwgError(500, '[add_file] '.$type.' directory has no write access');
1516      exit();
1517    }
1518  }
1519
1520  secure_directory($upload_dir);
1521
1522  // merge the thumbnail
1523  merge_chunks($file_path, $original_sum, $type);
1524  chmod($file_path, 0644);
1525
1526  // check dumped thumbnail md5
1527  $dumped_md5 = md5_file($file_path);
1528  if ($dumped_md5 != $file_sum) {
1529    new PwgError(500, '[add_file] '.$type.' transfer failed');
1530    exit();
1531  }
1532
1533  list($width, $height) = getimagesize($file_path);
1534  $filesize = floor(filesize($file_path)/1024);
1535
1536  return array(
1537    'width' => $width,
1538    'height' => $height,
1539    'filesize' => $filesize,
1540    );
1541}
1542
[4348]1543function ws_images_addFile($params, &$service)
1544{
1545  // image_id
1546  // type {thumb, file, high}
1547  // sum
1548
1549  global $conf;
[8126]1550  if (!is_admin())
[4348]1551  {
1552    return new PwgError(401, 'Access denied');
1553  }
1554
1555  $params['image_id'] = (int)$params['image_id'];
1556  if ($params['image_id'] <= 0)
1557  {
1558    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1559  }
1560
1561  //
1562  // what is the path?
1563  //
1564  $query = '
1565SELECT
1566    path,
1567    md5sum
1568  FROM '.IMAGES_TABLE.'
1569  WHERE id = '.$params['image_id'].'
1570;';
[6500]1571  list($file_path, $original_sum) = pwg_db_fetch_row(pwg_query($query));
[4348]1572
1573  // TODO only files added with web API can be updated with web API
1574
1575  //
1576  // makes sure directories are there and call the merge_chunks
1577  //
1578  $infos = add_file($file_path, $params['type'], $original_sum, $params['sum']);
1579
1580  //
1581  // update basic metadata from file
1582  //
1583  $update = array();
[4513]1584
[4348]1585  if ('high' == $params['type'])
1586  {
1587    $update['high_filesize'] = $infos['filesize'];
[10160]1588    $update['high_width'] = $infos['width'];
1589    $update['high_height'] = $infos['height'];
[4348]1590    $update['has_high'] = 'true';
1591  }
1592
1593  if ('file' == $params['type'])
1594  {
1595    $update['filesize'] = $infos['filesize'];
1596    $update['width'] = $infos['width'];
1597    $update['height'] = $infos['height'];
1598  }
1599
1600  // we may have nothing to update at database level, for example with a
1601  // thumbnail update
1602  if (count($update) > 0)
1603  {
1604    $update['id'] = $params['image_id'];
[4513]1605
[4348]1606    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1607    mass_updates(
1608      IMAGES_TABLE,
1609      array(
1610        'primary' => array('id'),
1611        'update'  => array_diff(array_keys($update), array('id'))
1612        ),
1613      array($update)
1614      );
1615  }
1616}
1617
[2463]1618function ws_images_add($params, &$service)
1619{
[8464]1620  global $conf, $user;
[8126]1621  if (!is_admin())
[2496]1622  {
1623    return new PwgError(401, 'Access denied');
1624  }
1625
[3662]1626  foreach ($params as $param_key => $param_value) {
1627    ws_logfile(
1628      sprintf(
1629        '[pwg.images.add] input param "%s" : "%s"',
1630        $param_key,
1631        is_null($param_value) ? 'NULL' : $param_value
1632        )
1633      );
1634  }
[2496]1635
[2592]1636  // does the image already exists ?
[12726]1637  if ($params['check_uniqueness'])
[4954]1638  {
[12726]1639    if ('md5sum' == $conf['uniqueness_mode'])
1640    {
1641      $where_clause = "md5sum = '".$params['original_sum']."'";
1642    }
1643    if ('filename' == $conf['uniqueness_mode'])
1644    {
1645      $where_clause = "file = '".$params['original_filename']."'";
1646    }
[11893]1647
[12726]1648    $query = '
[2592]1649SELECT
1650    COUNT(*) AS counter
1651  FROM '.IMAGES_TABLE.'
[4954]1652  WHERE '.$where_clause.'
[2592]1653;';
[12726]1654    list($counter) = pwg_db_fetch_row(pwg_query($query));
1655    if ($counter != 0) {
1656      return new PwgError(500, 'file already exists');
1657    }
[2592]1658  }
1659
[12724]1660  if ($params['resize'])
1661  {
1662    ws_logfile('[pwg.images.add] resize activated');
1663   
1664    // temporary file path
1665    $type = 'file';
1666    $file_path = $conf['upload_dir'].'/buffer/'.$params['original_sum'].'-'.$type;
1667   
1668    merge_chunks($file_path, $params['original_sum'], $type);
1669    chmod($file_path, 0644);
[2496]1670
[12724]1671    include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1672   
1673    $image_id = add_uploaded_file(
1674      $file_path,
1675      $params['original_filename']
1676      );
[2463]1677
[12724]1678    // add_uploaded_file doesn't remove the original file in the buffer
1679    // directory if it was not uploaded as $_FILES
1680    unlink($file_path);
1681  }
1682  else
1683  {
1684    // current date
1685    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1686    list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
[2496]1687
[12724]1688    // upload directory hierarchy
1689    $upload_dir = sprintf(
1690      $conf['upload_dir'].'/%s/%s/%s',
1691      $year,
1692      $month,
1693      $day
1694      );
[2463]1695
[12724]1696    // compute file path
1697    $date_string = preg_replace('/[^\d]/', '', $dbnow);
1698    $random_string = substr($params['file_sum'], 0, 8);
1699    $filename_wo_ext = $date_string.'-'.$random_string;
1700    $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
1701   
1702    // add files
1703    $file_infos  = add_file($file_path, 'file',  $params['original_sum'], $params['file_sum']);
1704    $thumb_infos = add_file($file_path, 'thumb', $params['original_sum'], $params['thumbnail_sum']);
1705   
1706    if (isset($params['high_sum']))
1707    {
1708      $high_infos = add_file($file_path, 'high', $params['original_sum'], $params['high_sum']);
1709    }
1710
1711    // database registration
1712    $insert = array(
1713      'file' => !empty($params['original_filename']) ? $params['original_filename'] : $filename_wo_ext.'.jpg',
1714      'date_available' => $dbnow,
1715      'tn_ext' => 'jpg',
1716      'name' => $params['name'],
1717      'path' => $file_path,
1718      'filesize' => $file_infos['filesize'],
1719      'width' => $file_infos['width'],
1720      'height' => $file_infos['height'],
1721      'md5sum' => $params['original_sum'],
1722      'added_by' => $user['id'],
1723      );
1724
1725    if (isset($params['high_sum']))
1726    {
1727      $insert['has_high'] = 'true';
1728      $insert['high_filesize'] = $high_infos['filesize'];
1729      $insert['high_width'] = $high_infos['width'];
1730      $insert['high_height'] = $high_infos['height'];
1731    }
1732
1733    single_insert(
1734      IMAGES_TABLE,
1735      $insert
1736      );
1737
1738    $image_id = pwg_db_insert_id(IMAGES_TABLE);
1739
1740    // update metadata from the uploaded file (exif/iptc)
1741    require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1742    update_metadata(array($image_id=>$file_path));
[2670]1743  }
1744
[2569]1745  $info_columns = array(
1746    'name',
1747    'author',
1748    'comment',
1749    'level',
1750    'date_creation',
1751    );
1752
1753  foreach ($info_columns as $key)
1754  {
1755    if (isset($params[$key]))
1756    {
[12724]1757      $update[$key] = $params[$key];
[2569]1758    }
1759  }
[12724]1760 
1761  if (count(array_keys($update)) > 0)
[2670]1762  {
[12724]1763    single_update(
1764      IMAGES_TABLE,
1765      $update,
1766      array('id' => $image_id)
1767      );
[2670]1768  }
1769
[12728]1770  $url_params = array('image_id' => $image_id);
1771 
[2569]1772  // let's add links between the image and the categories
1773  if (isset($params['categories']))
1774  {
[2919]1775    ws_add_image_category_relations($image_id, $params['categories']);
[12728]1776
1777    if (preg_match('/^\d+/', $params['categories'], $matches)) {
1778      $category_id = $matches[0];
1779   
1780      $query = '
1781SELECT id, name, permalink
1782  FROM '.CATEGORIES_TABLE.'
1783  WHERE id = '.$category_id.'
1784;';
1785      $result = pwg_query($query);
1786      $category = pwg_db_fetch_assoc($result);
1787     
1788      $url_params['section'] = 'categories';
1789      $url_params['category'] = $category;
1790    }
[2553]1791  }
[2569]1792
1793  // and now, let's create tag associations
[3660]1794  if (isset($params['tag_ids']) and !empty($params['tag_ids']))
[2553]1795  {
[2569]1796    set_tags(
1797      explode(',', $params['tag_ids']),
1798      $image_id
1799      );
[2553]1800  }
[2585]1801
[2501]1802  invalidate_user_cache();
[12728]1803
1804  return array(
1805    'image_id' => $image_id,
1806    'url' => make_picture_url($url_params),
1807    );
[2463]1808}
1809
[8249]1810function ws_images_addSimple($params, &$service)
1811{
1812  global $conf;
[8274]1813  if (!is_admin())
[8249]1814  {
1815    return new PwgError(401, 'Access denied');
1816  }
1817
1818  if (!$service->isPost())
1819  {
1820    return new PwgError(405, "This method requires HTTP POST");
1821  }
[11118]1822
1823  if (!isset($_FILES['image']))
1824  {
1825    return new PwgError(405, "The image (file) parameter is missing");
1826  }
[11893]1827
[9191]1828  $params['image_id'] = (int)$params['image_id'];
1829  if ($params['image_id'] > 0)
1830  {
1831    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
[8249]1832
[9191]1833    $query='
1834SELECT *
1835  FROM '.IMAGES_TABLE.'
1836  WHERE id = '.$params['image_id'].'
1837;';
1838
1839    $image_row = pwg_db_fetch_assoc(pwg_query($query));
1840    if ($image_row == null)
1841    {
1842      return new PwgError(404, "image_id not found");
1843    }
1844  }
1845
[8249]1846  // category
1847  $params['category'] = (int)$params['category'];
[9191]1848  if ($params['category'] <= 0 and $params['image_id'] <= 0)
[8249]1849  {
1850    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
1851  }
1852
1853  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1854
1855  $image_id = add_uploaded_file(
1856    $_FILES['image']['tmp_name'],
1857    $_FILES['image']['name'],
[9191]1858    $params['category'] > 0 ? array($params['category']) : null,
1859    8,
1860    $params['image_id'] > 0 ? $params['image_id'] : null
[8249]1861    );
1862
1863  $info_columns = array(
1864    'name',
1865    'author',
1866    'comment',
1867    'level',
1868    'date_creation',
1869    );
1870
1871  foreach ($info_columns as $key)
1872  {
1873    if (isset($params[$key]))
1874    {
1875      $update[$key] = $params[$key];
1876    }
1877  }
1878
1879  if (count(array_keys($update)) > 0)
1880  {
1881    $update['id'] = $image_id;
1882
1883    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1884    mass_updates(
1885      IMAGES_TABLE,
1886      array(
1887        'primary' => array('id'),
1888        'update'  => array_diff(array_keys($update), array('id'))
1889        ),
1890      array($update)
1891      );
1892  }
1893
1894
1895  if (isset($params['tags']) and !empty($params['tags']))
1896  {
1897    $tag_ids = array();
1898    $tag_names = explode(',', $params['tags']);
1899    foreach ($tag_names as $tag_name)
1900    {
1901      $tag_id = tag_id_from_tag_name($tag_name);
1902      array_push($tag_ids, $tag_id);
1903    }
1904
1905    add_tags($tag_ids, array($image_id));
1906  }
1907
[9191]1908  $url_params = array('image_id' => $image_id);
1909
1910  if ($params['category'] > 0)
1911  {
1912    $query = '
[8249]1913SELECT id, name, permalink
1914  FROM '.CATEGORIES_TABLE.'
1915  WHERE id = '.$params['category'].'
1916;';
[9191]1917    $result = pwg_query($query);
1918    $category = pwg_db_fetch_assoc($result);
[8249]1919
[9191]1920    $url_params['section'] = 'categories';
1921    $url_params['category'] = $category;
1922  }
1923
[9944]1924  // update metadata from the uploaded file (exif/iptc), even if the sync
1925  // was already performed by add_uploaded_file().
1926  $query = '
1927SELECT
1928    path
1929  FROM '.IMAGES_TABLE.'
1930  WHERE id = '.$image_id.'
1931;';
1932  list($file_path) = pwg_db_fetch_row(pwg_query($query));
[11893]1933
[9944]1934  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1935  update_metadata(array($image_id=>$file_path));
1936
[8249]1937  return array(
1938    'image_id' => $image_id,
[9191]1939    'url' => make_picture_url($url_params),
[8249]1940    );
1941}
1942
[12624]1943function ws_rates_delete($params, &$service)
1944{
1945  global $conf;
1946
1947  if (!$service->isPost())
1948  {
1949    return new PwgError(405, 'This method requires HTTP POST');
1950  }
1951
1952  if (!is_admin())
1953  {
1954    return new PwgError(401, 'Access denied');
1955  }
1956
1957  $user_id = (int)$params['user_id'];
1958  if ($user_id<=0)
1959  {
1960    return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid user_id');
1961  }
1962 
1963  $query = '
1964DELETE FROM '.RATE_TABLE.'
1965  WHERE user_id='.$user_id;
1966 
1967  if (!empty($params['anonymous_id']))
1968  {
1969    $query .= ' AND anonymous_id=\''.$params['anonymous_id'].'\'';
1970  }
1971 
1972  $changes = pwg_db_changes(pwg_query($query));
1973  if ($changes)
1974  {
1975    include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
1976    update_rating_score();
1977  }
1978  return $changes;
1979}
1980
1981
[1781]1982/**
1983 * perform a login (web service method)
1984 */
[1698]1985function ws_session_login($params, &$service)
1986{
1987  global $conf;
1988
1989  if (!$service->isPost())
1990  {
[1852]1991    return new PwgError(405, "This method requires HTTP POST");
[1698]1992  }
[1744]1993  if (try_log_user($params['username'], $params['password'],false))
[1698]1994  {
1995    return true;
1996  }
1997  return new PwgError(999, 'Invalid username/password');
1998}
1999
[1781]2000
2001/**
2002 * performs a logout (web service method)
2003 */
[1698]2004function ws_session_logout($params, &$service)
2005{
[2029]2006  if (!is_a_guest())
[1698]2007  {
[2757]2008    logout_user();
[1698]2009  }
2010  return true;
2011}
2012
2013function ws_session_getStatus($params, &$service)
2014{
[2356]2015  global $user;
[1698]2016  $res = array();
[4304]2017  $res['username'] = is_a_guest() ? 'guest' : stripslashes($user['username']);
[6437]2018  foreach ( array('status', 'theme', 'language') as $k )
[1849]2019  {
2020    $res[$k] = $user[$k];
2021  }
[7212]2022  $res['pwg_token'] = get_pwg_token();
[2126]2023  $res['charset'] = get_pwg_charset();
[11756]2024
2025  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2026  $res['current_datetime'] = $dbnow;
[11893]2027
[1698]2028  return $res;
2029}
2030
2031
[1781]2032/**
2033 * returns a list of tags (web service method)
2034 */
[1698]2035function ws_tags_getList($params, &$service)
2036{
[1711]2037  $tags = get_available_tags();
[1698]2038  if ($params['sort_by_counter'])
2039  {
2040    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
2041  }
2042  else
2043  {
[2409]2044    usort($tags, 'tag_alpha_compare');
[1698]2045  }
2046  for ($i=0; $i<count($tags); $i++)
2047  {
[1815]2048    $tags[$i]['id'] = (int)$tags[$i]['id'];
[1698]2049    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
2050    $tags[$i]['url'] = make_index_url(
2051        array(
2052          'section'=>'tags',
2053          'tags'=>array($tags[$i])
2054        )
2055      );
2056  }
[2585]2057  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
[1698]2058}
2059
[2584]2060/**
2061 * returns the list of tags as you can see them in administration (web
2062 * service method).
2063 *
2064 * Only admin can run this method and permissions are not taken into
2065 * account.
2066 */
2067function ws_tags_getAdminList($params, &$service)
2068{
2069  if (!is_admin())
2070  {
2071    return new PwgError(401, 'Access denied');
2072  }
[2585]2073
[2584]2074  $tags = get_all_tags();
2075  return array(
2076    'tags' => new PwgNamedArray(
2077      $tags,
2078      'tag',
2079      array(
2080        'name',
2081        'id',
2082        'url_name',
2083        )
2084      )
2085    );
2086}
[1781]2087
2088/**
2089 * returns a list of images for tags (web service method)
2090 */
[1698]2091function ws_tags_getImages($params, &$service)
2092{
2093  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
[1816]2094  global $conf;
[2119]2095
[1698]2096  // first build all the tag_ids we are interested in
[1852]2097  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
2098  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
[1698]2099  $tags_by_id = array();
2100  foreach( $tags as $tag )
2101  {
[1852]2102    $tags['id'] = (int)$tag['id'];
[1815]2103    $tags_by_id[ $tag['id'] ] = $tag;
[1698]2104  }
2105  unset($tags);
[1852]2106  $tag_ids = array_keys($tags_by_id);
[1698]2107
2108
[8726]2109  $where_clauses = ws_std_image_sql_filter($params);
2110  if (!empty($where_clauses))
2111  {
2112    $where_clauses = implode( ' AND ', $where_clauses);
2113  }
2114  $image_ids = get_image_ids_for_tags(
2115    $tag_ids,
2116    $params['tag_mode_and'] ? 'AND' : 'OR',
2117    $where_clauses,
2118    ws_std_image_sql_order($params) );
2119
2120
2121  $image_ids = array_slice($image_ids, (int)($params['per_page']*$params['page']), (int)$params['per_page'] );
[11893]2122
[1698]2123  $image_tag_map = array();
[8726]2124  if ( !empty($image_ids) and !$params['tag_mode_and'] )
[1698]2125  { // build list of image ids with associated tags per image
[8726]2126    $query = '
[6652]2127SELECT image_id, GROUP_CONCAT(tag_id) AS tag_ids
[1698]2128  FROM '.IMAGE_TAG_TABLE.'
[8726]2129  WHERE tag_id IN ('.implode(',',$tag_ids).') AND image_id IN ('.implode(',',$image_ids).')
[1698]2130  GROUP BY image_id';
[8726]2131    $result = pwg_query($query);
2132    while ( $row=pwg_db_fetch_assoc($result) )
2133    {
2134      $row['image_id'] = (int)$row['image_id'];
2135      array_push( $image_ids, $row['image_id'] );
2136      $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
[1698]2137    }
2138  }
2139
2140  $images = array();
[8726]2141  if (!empty($image_ids))
[1698]2142  {
[8726]2143    $rank_of = array_flip($image_ids);
2144    $result = pwg_query('
2145SELECT * FROM '.IMAGES_TABLE.'
2146  WHERE id IN ('.implode(',',$image_ids).')');
[4325]2147    while ($row = pwg_db_fetch_assoc($result))
[1698]2148    {
[2119]2149      $image = array();
[8726]2150      $image['rank'] = $rank_of[ $row['id'] ];
[1698]2151      foreach ( array('id', 'width', 'height', 'hit') as $k )
2152      {
2153        if (isset($row[$k]))
2154        {
2155          $image[$k] = (int)$row[$k];
2156        }
2157      }
[11116]2158      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
[1698]2159      {
2160        $image[$k] = $row[$k];
2161      }
2162      $image = array_merge( $image, ws_std_get_urls($row) );
2163
2164      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
2165      $image_tags = array();
2166      foreach ($image_tag_ids as $tag_id)
2167      {
2168        $url = make_index_url(
2169                 array(
2170                  'section'=>'tags',
2171                  'tags'=> array($tags_by_id[$tag_id])
2172                )
2173              );
2174        $page_url = make_picture_url(
2175                 array(
2176                  'section'=>'tags',
2177                  'tags'=> array($tags_by_id[$tag_id]),
2178                  'image_id' => $row['id'],
2179                  'image_file' => $row['file'],
2180                )
2181              );
2182        array_push($image_tags, array(
2183                'id' => (int)$tag_id,
2184                'url' => $url,
2185                'page_url' => $page_url,
2186              )
2187            );
2188      }
[1711]2189      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
2190              array('id','url_name','url','page_url')
[1698]2191            );
2192      array_push($images, $image);
2193    }
[8726]2194    usort($images, 'rank_compare');
2195    unset($rank_of);
[1698]2196  }
2197
2198  return array( 'images' =>
2199    array (
2200      WS_XML_ATTRIBUTES =>
2201        array(
2202            'page' => $params['page'],
2203            'per_page' => $params['per_page'],
2204            'count' => count($images)
2205          ),
[1711]2206       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
[1845]2207          ws_std_get_image_xml_attributes() )
[1698]2208      )
2209    );
2210}
[2583]2211
2212function ws_categories_add($params, &$service)
2213{
[8126]2214  if (!is_admin())
[2583]2215  {
2216    return new PwgError(401, 'Access denied');
2217  }
2218
2219  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2220
2221  $creation_output = create_virtual_category(
2222    $params['name'],
2223    $params['parent']
2224    );
2225
2226  if (isset($creation_output['error']))
2227  {
2228    return new PwgError(500, $creation_output['error']);
2229  }
[2585]2230
[2644]2231  invalidate_user_cache();
[2757]2232
[2583]2233  return $creation_output;
2234}
[2634]2235
2236function ws_tags_add($params, &$service)
2237{
[8126]2238  if (!is_admin())
[2634]2239  {
2240    return new PwgError(401, 'Access denied');
2241  }
2242
2243  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2244
2245  $creation_output = create_tag($params['name']);
2246
2247  if (isset($creation_output['error']))
2248  {
2249    return new PwgError(500, $creation_output['error']);
2250  }
2251
2252  return $creation_output;
2253}
[2683]2254
2255function ws_images_exist($params, &$service)
2256{
[4954]2257  global $conf;
[11893]2258
[8126]2259  if (!is_admin())
[2683]2260  {
2261    return new PwgError(401, 'Access denied');
2262  }
2263
[4954]2264  $split_pattern = '/[\s,;\|]/';
2265
2266  if ('md5sum' == $conf['uniqueness_mode'])
2267  {
2268    // search among photos the list of photos already added, based on md5sum
2269    // list
2270    $md5sums = preg_split(
2271      $split_pattern,
2272      $params['md5sum_list'],
2273      -1,
2274      PREG_SPLIT_NO_EMPTY
[2683]2275    );
[2757]2276
[4954]2277    $query = '
[2683]2278SELECT
2279    id,
2280    md5sum
2281  FROM '.IMAGES_TABLE.'
[2757]2282  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
[2683]2283;';
[4954]2284    $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
[2683]2285
[4954]2286    $result = array();
[2757]2287
[4954]2288    foreach ($md5sums as $md5sum)
2289    {
2290      $result[$md5sum] = null;
2291      if (isset($id_of_md5[$md5sum]))
2292      {
2293        $result[$md5sum] = $id_of_md5[$md5sum];
2294      }
2295    }
2296  }
[11893]2297
[4954]2298  if ('filename' == $conf['uniqueness_mode'])
[2683]2299  {
[4954]2300    // search among photos the list of photos already added, based on
2301    // filename list
2302    $filenames = preg_split(
2303      $split_pattern,
2304      $params['filename_list'],
2305      -1,
2306      PREG_SPLIT_NO_EMPTY
2307    );
2308
2309    $query = '
2310SELECT
2311    id,
2312    file
2313  FROM '.IMAGES_TABLE.'
2314  WHERE file IN (\''.implode("','", $filenames).'\')
2315;';
2316    $id_of_filename = simple_hash_from_query($query, 'file', 'id');
2317
2318    $result = array();
2319
2320    foreach ($filenames as $filename)
[2683]2321    {
[4954]2322      $result[$filename] = null;
2323      if (isset($id_of_filename[$filename]))
2324      {
2325        $result[$filename] = $id_of_filename[$filename];
2326      }
[2683]2327    }
2328  }
2329
2330  return $result;
2331}
[2919]2332
[4347]2333function ws_images_checkFiles($params, &$service)
2334{
[8126]2335  if (!is_admin())
[4347]2336  {
2337    return new PwgError(401, 'Access denied');
2338  }
2339
2340  // input parameters
2341  //
2342  // image_id
2343  // thumbnail_sum
2344  // file_sum
2345  // high_sum
2346
2347  $params['image_id'] = (int)$params['image_id'];
2348  if ($params['image_id'] <= 0)
2349  {
2350    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2351  }
2352
2353  $query = '
2354SELECT
2355    path
2356  FROM '.IMAGES_TABLE.'
2357  WHERE id = '.$params['image_id'].'
2358;';
2359  $result = pwg_query($query);
[6500]2360  if (pwg_db_num_rows($result) == 0) {
[4347]2361    return new PwgError(404, "image_id not found");
2362  }
[6500]2363  list($path) = pwg_db_fetch_row($result);
[4347]2364
2365  $ret = array();
2366
2367  foreach (array('thumb', 'file', 'high') as $type) {
2368    $param_name = $type;
2369    if ('thumb' == $type) {
2370      $param_name = 'thumbnail';
2371    }
2372
2373    if (isset($params[$param_name.'_sum'])) {
[8249]2374      include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[4347]2375      $type_path = file_path_for_type($path, $type);
2376      if (!is_file($type_path)) {
2377        $ret[$param_name] = 'missing';
2378      }
2379      else {
2380        if (md5_file($type_path) != $params[$param_name.'_sum']) {
2381          $ret[$param_name] = 'differs';
2382        }
2383        else {
2384          $ret[$param_name] = 'equals';
2385        }
2386      }
2387    }
2388  }
2389
2390  return $ret;
2391}
2392
[2919]2393function ws_images_setInfo($params, &$service)
2394{
2395  global $conf;
[8126]2396  if (!is_admin())
[2919]2397  {
2398    return new PwgError(401, 'Access denied');
2399  }
2400
[4511]2401  if (!$service->isPost())
2402  {
2403    return new PwgError(405, "This method requires HTTP POST");
2404  }
2405
[2919]2406  $params['image_id'] = (int)$params['image_id'];
2407  if ($params['image_id'] <= 0)
2408  {
2409    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2410  }
2411
[7613]2412  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2413
[2919]2414  $query='
2415SELECT *
2416  FROM '.IMAGES_TABLE.'
2417  WHERE id = '.$params['image_id'].'
2418;';
2419
[4325]2420  $image_row = pwg_db_fetch_assoc(pwg_query($query));
[2919]2421  if ($image_row == null)
2422  {
2423    return new PwgError(404, "image_id not found");
2424  }
2425
2426  // database registration
[4460]2427  $update = array();
[2919]2428
2429  $info_columns = array(
[12730]2430    'file',
[2919]2431    'name',
2432    'author',
2433    'comment',
2434    'level',
2435    'date_creation',
2436    );
2437
2438  foreach ($info_columns as $key)
2439  {
2440    if (isset($params[$key]))
2441    {
[4460]2442      if ('fill_if_empty' == $params['single_value_mode'])
2443      {
2444        if (empty($image_row[$key]))
2445        {
2446          $update[$key] = $params[$key];
2447        }
2448      }
2449      elseif ('replace' == $params['single_value_mode'])
2450      {
2451        $update[$key] = $params[$key];
2452      }
2453      else
2454      {
2455        new PwgError(
2456          500,
2457          '[ws_images_setInfo]'
2458          .' invalid parameter single_value_mode "'.$params['single_value_mode'].'"'
2459          .', possible values are {fill_if_empty, replace}.'
2460          );
2461        exit();
2462      }
[2919]2463    }
2464  }
2465
[4460]2466  if (count(array_keys($update)) > 0)
[2919]2467  {
[4460]2468    $update['id'] = $params['image_id'];
2469
[2919]2470    mass_updates(
2471      IMAGES_TABLE,
2472      array(
2473        'primary' => array('id'),
2474        'update'  => array_diff(array_keys($update), array('id'))
2475        ),
2476      array($update)
2477      );
2478  }
[3145]2479
[2919]2480  if (isset($params['categories']))
2481  {
2482    ws_add_image_category_relations(
2483      $params['image_id'],
[4445]2484      $params['categories'],
[4460]2485      ('replace' == $params['multiple_value_mode'] ? true : false)
[2919]2486      );
2487  }
2488
2489  // and now, let's create tag associations
2490  if (isset($params['tag_ids']))
2491  {
[4445]2492    $tag_ids = explode(',', $params['tag_ids']);
2493
[4460]2494    if ('replace' == $params['multiple_value_mode'])
[4445]2495    {
2496      set_tags(
2497        $tag_ids,
2498        $params['image_id']
2499        );
2500    }
[4460]2501    elseif ('append' == $params['multiple_value_mode'])
[4445]2502    {
2503      add_tags(
2504        $tag_ids,
2505        array($params['image_id'])
2506        );
2507    }
[4460]2508    else
2509    {
2510      new PwgError(
2511        500,
2512        '[ws_images_setInfo]'
2513        .' invalid parameter multiple_value_mode "'.$params['multiple_value_mode'].'"'
2514        .', possible values are {replace, append}.'
2515        );
2516      exit();
2517    }
[2919]2518  }
2519
2520  invalidate_user_cache();
2521}
2522
[8266]2523function ws_images_delete($params, &$service)
2524{
2525  global $conf;
[8274]2526  if (!is_admin())
[8266]2527  {
2528    return new PwgError(401, 'Access denied');
2529  }
2530
2531  if (!$service->isPost())
2532  {
2533    return new PwgError(405, "This method requires HTTP POST");
2534  }
2535
2536  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2537  {
2538    return new PwgError(403, 'Invalid security token');
2539  }
2540
2541  $params['image_id'] = preg_split(
2542    '/[\s,;\|]/',
2543    $params['image_id'],
2544    -1,
2545    PREG_SPLIT_NO_EMPTY
2546    );
2547  $params['image_id'] = array_map('intval', $params['image_id']);
2548
2549  $image_ids = array();
2550  foreach ($params['image_id'] as $image_id)
2551  {
2552    if ($image_id > 0)
2553    {
2554      array_push($image_ids, $image_id);
2555    }
2556  }
2557
2558  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2559  delete_elements($image_ids, true);
2560}
2561
[4445]2562function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
[2919]2563{
2564  // let's add links between the image and the categories
2565  //
2566  // $params['categories'] should look like 123,12;456,auto;789 which means:
2567  //
2568  // 1. associate with category 123 on rank 12
2569  // 2. associate with category 456 on automatic rank
2570  // 3. associate with category 789 on automatic rank
2571  $cat_ids = array();
2572  $rank_on_category = array();
2573  $search_current_ranks = false;
2574
2575  $tokens = explode(';', $categories_string);
2576  foreach ($tokens as $token)
2577  {
[2920]2578    @list($cat_id, $rank) = explode(',', $token);
[2919]2579
[4445]2580    if (!preg_match('/^\d+$/', $cat_id))
2581    {
2582      continue;
2583    }
2584
[2919]2585    array_push($cat_ids, $cat_id);
2586
2587    if (!isset($rank))
2588    {
2589      $rank = 'auto';
2590    }
2591    $rank_on_category[$cat_id] = $rank;
2592
2593    if ($rank == 'auto')
2594    {
2595      $search_current_ranks = true;
2596    }
2597  }
2598
2599  $cat_ids = array_unique($cat_ids);
2600
[4445]2601  if (count($cat_ids) == 0)
[2919]2602  {
[4445]2603    new PwgError(
2604      500,
2605      '[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
2606      );
2607    exit();
2608  }
[4513]2609
[4445]2610  $query = '
2611SELECT
2612    id
2613  FROM '.CATEGORIES_TABLE.'
2614  WHERE id IN ('.implode(',', $cat_ids).')
2615;';
2616  $db_cat_ids = array_from_query($query, 'id');
2617
2618  $unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
2619  if (count($unknown_cat_ids) != 0)
2620  {
2621    new PwgError(
2622      500,
2623      '[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
2624      );
2625    exit();
2626  }
[4513]2627
[4445]2628  $to_update_cat_ids = array();
[4513]2629
[4445]2630  // in case of replace mode, we first check the existing associations
2631  $query = '
2632SELECT
2633    category_id
2634  FROM '.IMAGE_CATEGORY_TABLE.'
2635  WHERE image_id = '.$image_id.'
2636;';
2637  $existing_cat_ids = array_from_query($query, 'category_id');
2638
2639  if ($replace_mode)
2640  {
2641    $to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
2642    if (count($to_remove_cat_ids) > 0)
[2919]2643    {
2644      $query = '
[4445]2645DELETE
2646  FROM '.IMAGE_CATEGORY_TABLE.'
2647  WHERE image_id = '.$image_id.'
2648    AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
2649;';
2650      pwg_query($query);
2651      update_category($to_remove_cat_ids);
2652    }
2653  }
[4513]2654
[4445]2655  $new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
2656  if (count($new_cat_ids) == 0)
2657  {
2658    return true;
2659  }
[4513]2660
[4445]2661  if ($search_current_ranks)
2662  {
2663    $query = '
[2919]2664SELECT
2665    category_id,
2666    MAX(rank) AS max_rank
2667  FROM '.IMAGE_CATEGORY_TABLE.'
2668  WHERE rank IS NOT NULL
[4445]2669    AND category_id IN ('.implode(',', $new_cat_ids).')
[2919]2670  GROUP BY category_id
2671;';
[4445]2672    $current_rank_of = simple_hash_from_query(
2673      $query,
2674      'category_id',
2675      'max_rank'
2676      );
[2919]2677
[4445]2678    foreach ($new_cat_ids as $cat_id)
2679    {
2680      if (!isset($current_rank_of[$cat_id]))
[2919]2681      {
[4445]2682        $current_rank_of[$cat_id] = 0;
[2919]2683      }
[4513]2684
[4445]2685      if ('auto' == $rank_on_category[$cat_id])
2686      {
2687        $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
2688      }
[2919]2689    }
[4445]2690  }
[4513]2691
[4445]2692  $inserts = array();
[4513]2693
[4445]2694  foreach ($new_cat_ids as $cat_id)
2695  {
2696    array_push(
2697      $inserts,
2698      array(
2699        'image_id' => $image_id,
2700        'category_id' => $cat_id,
2701        'rank' => $rank_on_category[$cat_id],
2702        )
[2919]2703      );
2704  }
[4513]2705
[4445]2706  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2707  mass_inserts(
2708    IMAGE_CATEGORY_TABLE,
2709    array_keys($inserts[0]),
2710    $inserts
2711    );
[4513]2712
[4445]2713  update_category($new_cat_ids);
[2919]2714}
[3193]2715
[3454]2716function ws_categories_setInfo($params, &$service)
2717{
2718  global $conf;
[8126]2719  if (!is_admin())
[3454]2720  {
2721    return new PwgError(401, 'Access denied');
2722  }
2723
[4511]2724  if (!$service->isPost())
2725  {
2726    return new PwgError(405, "This method requires HTTP POST");
2727  }
2728
[3454]2729  // category_id
2730  // name
2731  // comment
2732
2733  $params['category_id'] = (int)$params['category_id'];
2734  if ($params['category_id'] <= 0)
2735  {
2736    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2737  }
2738
2739  // database registration
2740  $update = array(
2741    'id' => $params['category_id'],
2742    );
2743
2744  $info_columns = array(
2745    'name',
2746    'comment',
2747    );
2748
2749  $perform_update = false;
2750  foreach ($info_columns as $key)
2751  {
2752    if (isset($params[$key]))
2753    {
2754      $perform_update = true;
2755      $update[$key] = $params[$key];
2756    }
2757  }
2758
2759  if ($perform_update)
2760  {
2761    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2762    mass_updates(
2763      CATEGORIES_TABLE,
2764      array(
2765        'primary' => array('id'),
2766        'update'  => array_diff(array_keys($update), array('id'))
2767        ),
2768      array($update)
2769      );
2770  }
[3488]2771
[3454]2772}
2773
[11746]2774function ws_categories_setRepresentative($params, &$service)
2775{
2776  global $conf;
[11893]2777
[11746]2778  if (!is_admin())
2779  {
2780    return new PwgError(401, 'Access denied');
2781  }
2782
2783  if (!$service->isPost())
2784  {
2785    return new PwgError(405, "This method requires HTTP POST");
2786  }
2787
2788  // category_id
2789  // image_id
2790
2791  $params['category_id'] = (int)$params['category_id'];
2792  if ($params['category_id'] <= 0)
2793  {
2794    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2795  }
2796
2797  // does the category really exist?
2798  $query='
2799SELECT
2800    *
2801  FROM '.CATEGORIES_TABLE.'
2802  WHERE id = '.$params['category_id'].'
2803;';
2804  $row = pwg_db_fetch_assoc(pwg_query($query));
2805  if ($row == null)
2806  {
2807    return new PwgError(404, "category_id not found");
2808  }
2809
2810  $params['image_id'] = (int)$params['image_id'];
2811  if ($params['image_id'] <= 0)
2812  {
2813    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2814  }
[11893]2815
[11746]2816  // does the image really exist?
2817  $query='
2818SELECT
2819    *
2820  FROM '.IMAGES_TABLE.'
2821  WHERE id = '.$params['image_id'].'
2822;';
2823
2824  $row = pwg_db_fetch_assoc(pwg_query($query));
2825  if ($row == null)
2826  {
2827    return new PwgError(404, "image_id not found");
2828  }
2829
2830  // apply change
2831  $query = '
2832UPDATE '.CATEGORIES_TABLE.'
2833  SET representative_picture_id = '.$params['image_id'].'
2834  WHERE id = '.$params['category_id'].'
2835;';
2836  pwg_query($query);
2837
2838  $query = '
2839UPDATE '.USER_CACHE_CATEGORIES_TABLE.'
2840  SET user_representative_picture_id = NULL
2841  WHERE cat_id = '.$params['category_id'].'
2842;';
2843  pwg_query($query);
2844}
2845
[8266]2846function ws_categories_delete($params, &$service)
2847{
2848  global $conf;
[8274]2849  if (!is_admin())
[8266]2850  {
2851    return new PwgError(401, 'Access denied');
2852  }
2853
2854  if (!$service->isPost())
2855  {
2856    return new PwgError(405, "This method requires HTTP POST");
2857  }
2858
2859  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2860  {
2861    return new PwgError(403, 'Invalid security token');
2862  }
2863
2864  $modes = array('no_delete', 'delete_orphans', 'force_delete');
2865  if (!in_array($params['photo_deletion_mode'], $modes))
2866  {
2867    return new PwgError(
2868      500,
2869      '[ws_categories_delete]'
2870      .' invalid parameter photo_deletion_mode "'.$params['photo_deletion_mode'].'"'
2871      .', possible values are {'.implode(', ', $modes).'}.'
2872      );
2873  }
2874
2875  $params['category_id'] = preg_split(
2876    '/[\s,;\|]/',
2877    $params['category_id'],
2878    -1,
2879    PREG_SPLIT_NO_EMPTY
2880    );
2881  $params['category_id'] = array_map('intval', $params['category_id']);
2882
2883  $category_ids = array();
2884  foreach ($params['category_id'] as $category_id)
2885  {
2886    if ($category_id > 0)
2887    {
2888      array_push($category_ids, $category_id);
2889    }
2890  }
2891
2892  if (count($category_ids) == 0)
2893  {
2894    return;
2895  }
2896
2897  $query = '
2898SELECT id
2899  FROM '.CATEGORIES_TABLE.'
2900  WHERE id IN ('.implode(',', $category_ids).')
2901;';
2902  $category_ids = array_from_query($query, 'id');
2903
2904  if (count($category_ids) == 0)
2905  {
2906    return;
2907  }
[11893]2908
[8266]2909  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2910  delete_categories($category_ids, $params['photo_deletion_mode']);
2911  update_global_rank();
2912}
2913
[8272]2914function ws_categories_move($params, &$service)
2915{
2916  global $conf, $page;
[11893]2917
[8274]2918  if (!is_admin())
[8272]2919  {
2920    return new PwgError(401, 'Access denied');
2921  }
2922
2923  if (!$service->isPost())
2924  {
2925    return new PwgError(405, "This method requires HTTP POST");
2926  }
2927
2928  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2929  {
2930    return new PwgError(403, 'Invalid security token');
2931  }
2932
2933  $params['category_id'] = preg_split(
2934    '/[\s,;\|]/',
2935    $params['category_id'],
2936    -1,
2937    PREG_SPLIT_NO_EMPTY
2938    );
2939  $params['category_id'] = array_map('intval', $params['category_id']);
2940
2941  $category_ids = array();
2942  foreach ($params['category_id'] as $category_id)
2943  {
2944    if ($category_id > 0)
2945    {
2946      array_push($category_ids, $category_id);
2947    }
2948  }
2949
2950  if (count($category_ids) == 0)
2951  {
2952    return new PwgError(403, 'Invalid category_id input parameter, no category to move');
2953  }
2954
2955  // we can't move physical categories
2956  $categories_in_db = array();
[11893]2957
[8272]2958  $query = '
2959SELECT
2960    id,
2961    name,
2962    dir
2963  FROM '.CATEGORIES_TABLE.'
2964  WHERE id IN ('.implode(',', $category_ids).')
2965;';
2966  $result = pwg_query($query);
2967  while ($row = pwg_db_fetch_assoc($result))
2968  {
2969    $categories_in_db[$row['id']] = $row;
2970    // we break on error at first physical category detected
2971    if (!empty($row['dir']))
2972    {
2973      $row['name'] = strip_tags(
2974        trigger_event(
2975          'render_category_name',
2976          $row['name'],
2977          'ws_categories_move'
2978          )
2979        );
[11893]2980
[8272]2981      return new PwgError(
2982        403,
2983        sprintf(
2984          'Category %s (%u) is not a virtual category, you cannot move it',
2985          $row['name'],
2986          $row['id']
2987          )
2988        );
2989    }
2990  }
2991
2992  if (count($categories_in_db) != count($category_ids))
2993  {
2994    $unknown_category_ids = array_diff($category_ids, array_keys($categories_in_db));
[11893]2995
[8272]2996    return new PwgError(
2997      403,
2998      sprintf(
2999        'Category %u does not exist',
3000        $unknown_category_ids[0]
3001        )
3002      );
3003  }
3004
3005  // does this parent exists? This check should be made in the
3006  // move_categories function, not here
3007  //
3008  // 0 as parent means "move categories at gallery root"
3009  if (!is_numeric($params['parent']))
3010  {
3011    return new PwgError(403, 'Invalid parent input parameter');
3012  }
[11893]3013
[8272]3014  if (0 != $params['parent']) {
3015    $params['parent'] = intval($params['parent']);
3016    $subcat_ids = get_subcat_ids(array($params['parent']));
3017    if (count($subcat_ids) == 0)
3018    {
3019      return new PwgError(403, 'Unknown parent category id');
3020    }
3021  }
3022
3023  $page['infos'] = array();
3024  $page['errors'] = array();
3025  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3026  move_categories($category_ids, $params['parent']);
3027  invalidate_user_cache();
3028
3029  if (count($page['errors']) != 0)
3030  {
3031    return new PwgError(403, implode('; ', $page['errors']));
3032  }
3033}
3034
[3193]3035function ws_logfile($string)
3036{
[3662]3037  global $conf;
[3488]3038
[3662]3039  if (!$conf['ws_enable_log']) {
3040    return true;
3041  }
3042
[3193]3043  file_put_contents(
[3662]3044    $conf['ws_log_filepath'],
[3193]3045    '['.date('c').'] '.$string."\n",
3046    FILE_APPEND
3047    );
3048}
[6049]3049
3050function ws_images_checkUpload($params, &$service)
3051{
3052  global $conf;
3053
[8126]3054  if (!is_admin())
[6049]3055  {
3056    return new PwgError(401, 'Access denied');
3057  }
3058
[8249]3059  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[6051]3060  $ret['message'] = ready_for_upload_message();
3061  $ret['ready_for_upload'] = true;
[11893]3062
[6051]3063  if (!empty($ret['message']))
3064  {
3065    $ret['ready_for_upload'] = false;
3066  }
[11893]3067
[6051]3068  return $ret;
3069}
[8273]3070
3071function ws_plugins_getList($params, &$service)
3072{
3073  global $conf;
[11893]3074
[8273]3075  if (!is_admin())
3076  {
3077    return new PwgError(401, 'Access denied');
3078  }
3079
3080  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3081  $plugins = new plugins();
3082  $plugins->sort_fs_plugins('name');
3083  $plugin_list = array();
3084
3085  foreach($plugins->fs_plugins as $plugin_id => $fs_plugin)
3086  {
3087    if (isset($plugins->db_plugins_by_id[$plugin_id]))
3088    {
3089      $state = $plugins->db_plugins_by_id[$plugin_id]['state'];
3090    }
3091    else
3092    {
3093      $state = 'uninstalled';
3094    }
3095
3096    array_push(
3097      $plugin_list,
3098      array(
3099        'id' => $plugin_id,
3100        'name' => $fs_plugin['name'],
3101        'version' => $fs_plugin['version'],
3102        'state' => $state,
3103        'description' => $fs_plugin['description'],
3104        )
3105      );
3106  }
3107
3108  return $plugin_list;
3109}
3110
3111function ws_plugins_performAction($params, &$service)
3112{
3113  global $template;
[11893]3114
[8273]3115  if (!is_admin())
3116  {
3117    return new PwgError(401, 'Access denied');
3118  }
3119
3120  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3121  {
3122    return new PwgError(403, 'Invalid security token');
3123  }
3124
3125  define('IN_ADMIN', true);
3126  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3127  $plugins = new plugins();
3128  $errors = $plugins->perform_action($params['action'], $params['plugin']);
3129
[11893]3130
[8273]3131  if (!empty($errors))
3132  {
3133    return new PwgError(500, $errors);
3134  }
3135  else
3136  {
3137    if (in_array($params['action'], array('activate', 'deactivate')))
3138    {
3139      $template->delete_compiled_templates();
3140    }
3141    return true;
3142  }
3143}
3144
[8297]3145function ws_themes_performAction($params, &$service)
3146{
3147  global $template;
[11893]3148
[8726]3149  if (!is_admin())
[8297]3150  {
3151    return new PwgError(401, 'Access denied');
3152  }
3153
3154  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3155  {
3156    return new PwgError(403, 'Invalid security token');
3157  }
3158
3159  define('IN_ADMIN', true);
3160  include_once(PHPWG_ROOT_PATH.'admin/include/themes.class.php');
3161  $themes = new themes();
3162  $errors = $themes->perform_action($params['action'], $params['theme']);
[11893]3163
[8297]3164  if (!empty($errors))
3165  {
3166    return new PwgError(500, $errors);
3167  }
3168  else
3169  {
3170    if (in_array($params['action'], array('activate', 'deactivate')))
3171    {
3172      $template->delete_compiled_templates();
3173    }
3174    return true;
3175  }
3176}
[10235]3177
[10686]3178function ws_images_resizethumbnail($params, &$service)
[10235]3179{
3180  if (!is_admin())
3181  {
3182    return new PwgError(401, 'Access denied');
3183  }
3184
[10563]3185  if (empty($params['image_id']) and empty($params['image_path']))
3186  {
3187    return new PwgError(403, "image_id or image_path is missing");
3188  }
3189
3190  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[10641]3191  include_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
[10563]3192
3193  if (!empty($params['image_id']))
3194  {
3195    $query='
[10235]3196SELECT id, path, tn_ext, has_high
[10563]3197  FROM '.IMAGES_TABLE.'
3198  WHERE id = '.(int)$params['image_id'].'
[10235]3199;';
[10563]3200    $image = pwg_db_fetch_assoc(pwg_query($query));
[10235]3201
[10563]3202    if ($image == null)
3203    {
3204      return new PwgError(403, "image_id not found");
3205    }
3206
3207    $image_path = $image['path'];
3208    $thumb_path = get_thumbnail_path($image);
3209  }
3210  else
[10235]3211  {
[10563]3212    $image_path = $params['image_path'];
3213    $thumb_path = file_path_for_type($image_path, 'thumb');
[10235]3214  }
3215
[10686]3216  if (!file_exists($image_path) or !is_valid_image_extension(get_extension($image_path)))
[10235]3217  {
3218    return new PwgError(403, "image can't be resized");
3219  }
3220
[10563]3221  $result = false;
[10686]3222  prepare_directory(dirname($thumb_path));
3223  $img = new pwg_image($image_path, $params['library']);
[10563]3224
[10686]3225  $result =  $img->pwg_resize(
3226    $thumb_path,
3227    $params['maxwidth'],
3228    $params['maxheight'],
3229    $params['quality'],
3230    false, // automatic rotation is not needed for thumbnails.
3231    true, // strip metadata
3232    get_boolean($params['crop']),
3233    get_boolean($params['follow_orientation'])
3234  );
3235
3236  $img->destroy();
3237  return $result;
3238}
3239
3240function ws_images_resizewebsize($params, &$service)
3241{
3242  if (!is_admin())
[10235]3243  {
[10686]3244    return new PwgError(401, 'Access denied');
3245  }
[10563]3246
[10686]3247  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
3248  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
3249  include_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
[10641]3250
[10686]3251  $query='
[12175]3252SELECT id, path, tn_ext, has_high, width, height
[10686]3253  FROM '.IMAGES_TABLE.'
3254  WHERE id = '.(int)$params['image_id'].'
3255;';
3256  $image = pwg_db_fetch_assoc(pwg_query($query));
[10641]3257
[10686]3258  if ($image == null)
3259  {
3260    return new PwgError(403, "image_id not found");
[10235]3261  }
[10686]3262
3263  $image_path = $image['path'];
3264
[12175]3265  if (!is_valid_image_extension(get_extension($image_path)))
[10235]3266  {
[10686]3267    return new PwgError(403, "image can't be resized");
3268  }
[12175]3269 
3270  $hd_path = get_high_path($image);
[10641]3271
[12175]3272  if (empty($image['has_high']) or !file_exists($hd_path))
3273  {
3274    if ($image['width'] > $params['maxwidth'] or $image['height'] > $params['maxheight'])
3275    {
3276      $hd_path = file_path_for_type($image_path, 'high');
3277      $hd_dir = dirname($hd_path);
3278      prepare_directory($hd_dir);
3279     
3280      rename($image_path, $hd_path);
3281      $hd_infos = pwg_image_infos($hd_path);
3282
3283      single_update(
3284        IMAGES_TABLE,
3285        array(
3286          'has_high' => 'true',
3287          'high_filesize' => $hd_infos['filesize'],
3288          'high_width' => $hd_infos['width'],
3289          'high_height' => $hd_infos['height'],
3290          ),
3291        array(
3292          'id' => $image['id']
3293          )
3294        );
3295    }
3296    else
3297    {
3298      return new PwgError(403, "image can't be resized");
3299    }
3300  }
3301
[10686]3302  $result = false;
[10747]3303  $img = new pwg_image($hd_path, $params['library']);
[10454]3304
[10686]3305  $result = $img->pwg_resize(
3306    $image_path,
3307    $params['maxwidth'],
3308    $params['maxheight'],
3309    $params['quality'],
3310    $params['automatic_rotation'],
3311    false // strip metadata
3312    );
[10641]3313
[10686]3314  $img->destroy();
3315
3316  global $conf;
3317  $conf['use_exif'] = false;
3318  $conf['use_iptc'] = false;
3319  update_metadata(array($image['id'] => $image['path']));
3320
[10563]3321  return $result;
[10235]3322}
[10511]3323
3324function ws_extensions_update($params, &$service)
3325{
3326  if (!is_webmaster())
3327  {
3328    return new PwgError(401, l10n('Webmaster status is required.'));
3329  }
3330
3331  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3332  {
3333    return new PwgError(403, 'Invalid security token');
3334  }
3335
3336  if (empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3337  {
3338    return new PwgError(403, "invalid extension type");
3339  }
3340
3341  if (empty($params['id']) or empty($params['revision']))
3342  {
3343    return new PwgError(null, 'Wrong parameters');
3344  }
3345
3346  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3347  include_once(PHPWG_ROOT_PATH.'admin/include/'.$params['type'].'.class.php');
3348
3349  $type = $params['type'];
3350  $extension_id = $params['id'];
3351  $revision = $params['revision'];
3352
3353  $extension = new $type();
3354
3355  if ($type == 'plugins')
3356  {
3357    if (isset($extension->db_plugins_by_id[$extension_id]) and $extension->db_plugins_by_id[$extension_id]['state'] == 'active')
3358    {
3359      $extension->perform_action('deactivate', $extension_id);
3360
3361      redirect(PHPWG_ROOT_PATH
3362        . 'ws.php'
3363        . '?method=pwg.extensions.update'
3364        . '&type=plugins'
3365        . '&id=' . $extension_id
3366        . '&revision=' . $revision
3367        . '&reactivate=true'
3368        . '&pwg_token=' . get_pwg_token()
3369        . '&format=json'
3370      );
3371    }
[11893]3372
[10511]3373    $upgrade_status = $extension->extract_plugin_files('upgrade', $revision, $extension_id);
3374    $extension_name = $extension->fs_plugins[$extension_id]['name'];
3375
3376    if (isset($params['reactivate']))
3377    {
3378      $extension->perform_action('activate', $extension_id);
3379    }
3380  }
3381  elseif ($type == 'themes')
3382  {
3383    $upgrade_status = $extension->extract_theme_files('upgrade', $revision, $extension_id);
3384    $extension_name = $extension->fs_themes[$extension_id]['name'];
3385  }
3386  elseif ($type == 'languages')
3387  {
3388    $upgrade_status = $extension->extract_language_files('upgrade', $revision, $extension_id);
3389    $extension_name = $extension->fs_languages[$extension_id]['name'];
3390  }
3391
3392  global $template;
3393  $template->delete_compiled_templates();
3394
3395  switch ($upgrade_status)
3396  {
3397    case 'ok':
3398      return sprintf(l10n('%s has been successfully updated.'), $extension_name);
3399
3400    case 'temp_path_error':
3401      return new PwgError(null, l10n('Can\'t create temporary file.'));
3402
3403    case 'dl_archive_error':
3404      return new PwgError(null, l10n('Can\'t download archive.'));
3405
3406    case 'archive_error':
3407      return new PwgError(null, l10n('Can\'t read or extract archive.'));
3408
3409    default:
3410      return new PwgError(null, sprintf(l10n('An error occured during extraction (%s).'), $upgrade_status));
3411  }
3412}
3413
3414function ws_extensions_ignoreupdate($params, &$service)
3415{
3416  global $conf;
3417
3418  define('IN_ADMIN', true);
3419  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3420
3421  if (!is_webmaster())
3422  {
3423    return new PwgError(401, 'Access denied');
3424  }
3425
3426  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3427  {
3428    return new PwgError(403, 'Invalid security token');
3429  }
3430
3431  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3432
[10538]3433  // Reset ignored extension
[10511]3434  if ($params['reset'])
3435  {
[10596]3436    if (!empty($params['type']) and isset($conf['updates_ignored'][$params['type']]))
3437    {
3438      $conf['updates_ignored'][$params['type']] = array();
3439    }
3440    else
3441    {
3442      $conf['updates_ignored'] = array(
3443        'plugins'=>array(),
3444        'themes'=>array(),
3445        'languages'=>array()
3446      );
3447    }
[10511]3448    conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3449    unset($_SESSION['extensions_need_update']);
3450    return true;
3451  }
3452
3453  if (empty($params['id']) or empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3454  {
3455    return new PwgError(403, 'Invalid parameters');
3456  }
3457
3458  // Add or remove extension from ignore list
3459  if (!in_array($params['id'], $conf['updates_ignored'][$params['type']]))
3460  {
3461    array_push($conf['updates_ignored'][$params['type']], $params['id']);
3462  }
3463  conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3464  unset($_SESSION['extensions_need_update']);
3465  return true;
3466}
[10538]3467
3468function ws_extensions_checkupdates($params, &$service)
3469{
3470  global $conf;
3471
3472  define('IN_ADMIN', true);
3473  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3474  include_once(PHPWG_ROOT_PATH.'admin/include/updates.class.php');
3475  $update = new updates();
3476
3477  if (!is_admin())
3478  {
3479    return new PwgError(401, 'Access denied');
3480  }
3481
3482  $result = array();
3483
3484  if (!isset($_SESSION['need_update']))
3485    $update->check_piwigo_upgrade();
3486
3487  $result['piwigo_need_update'] = $_SESSION['need_update'];
3488
3489  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3490
3491  if (!isset($_SESSION['extensions_need_update']))
3492    $update->check_extensions();
3493  else
3494    $update->check_updated_extensions();
3495
3496  if (!is_array($_SESSION['extensions_need_update']))
3497    $result['ext_need_update'] = null;
3498  else
3499    $result['ext_need_update'] = !empty($_SESSION['extensions_need_update']);
3500
3501  return $result;
3502}
[12728]3503?>
Note: See TracBrowser for help on using the repository browser.