source: branches/2.3/include/ws_functions.inc.php @ 12722

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

feature 2531 added: pwg.images.add is able to generate web size + thumbnail
(remote client needs to set "resize" option to something else than 0). When
the "resize" is On, only the "file" must be send with pwg.images.addChunk.

  • Property svn:eol-style set to LF
File size: 85.0 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,
[12539]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
[12537]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
[12537]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
[12537]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']);
[12539]726    unset($cat['count_categories']);
[12537]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 ?
[4954]1637  if ('md5sum' == $conf['uniqueness_mode'])
1638  {
1639    $where_clause = "md5sum = '".$params['original_sum']."'";
1640  }
1641  if ('filename' == $conf['uniqueness_mode'])
1642  {
1643    $where_clause = "file = '".$params['original_filename']."'";
1644  }
[11893]1645
[2592]1646  $query = '
1647SELECT
1648    COUNT(*) AS counter
1649  FROM '.IMAGES_TABLE.'
[4954]1650  WHERE '.$where_clause.'
[2592]1651;';
[4325]1652  list($counter) = pwg_db_fetch_row(pwg_query($query));
[2592]1653  if ($counter != 0) {
1654    return new PwgError(500, 'file already exists');
1655  }
1656
[12722]1657  if ($params['resize'])
1658  {
1659    ws_logfile('[pwg.images.add] resize activated');
1660   
1661    // temporary file path
1662    $type = 'file';
1663    $file_path = $conf['upload_dir'].'/buffer/'.$params['original_sum'].'-'.$type;
1664   
1665    merge_chunks($file_path, $params['original_sum'], $type);
1666    chmod($file_path, 0644);
1667   
1668    $image_id = add_uploaded_file(
1669      $file_path,
1670      $params['original_filename']
1671      );
[2496]1672
[12722]1673    // add_uploaded_file doesn't remove the original file in the buffer
1674    // directory if it was not uploaded as $_FILES
1675    unlink($file_path);
1676
1677    $info_columns = array(
1678      'name',
1679      'author',
1680      'comment',
1681      'level',
1682      'date_creation',
[2463]1683    );
1684
[12722]1685    foreach ($info_columns as $key)
1686    {
1687      if (isset($params[$key]))
1688      {
1689        $update[$key] = $params[$key];
1690      }
1691    }
[2496]1692
[12722]1693    if (count(array_keys($update)) > 0)
1694    {
1695      single_update(
1696        IMAGES_TABLE,
1697        $update,
1698        array('id' => $image_id)
1699        );
1700    }
1701  }
1702  else
[2670]1703  {
[12722]1704    // current date
1705    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1706    list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
[2670]1707
[12722]1708    // upload directory hierarchy
1709    $upload_dir = sprintf(
1710      $conf['upload_dir'].'/%s/%s/%s',
1711      $year,
1712      $month,
1713      $day
1714      );
[2463]1715
[12722]1716    // compute file path
1717    $date_string = preg_replace('/[^\d]/', '', $dbnow);
1718    $random_string = substr($params['file_sum'], 0, 8);
1719    $filename_wo_ext = $date_string.'-'.$random_string;
1720    $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
1721   
1722    // add files
1723    $file_infos  = add_file($file_path, 'file',  $params['original_sum'], $params['file_sum']);
1724    $thumb_infos = add_file($file_path, 'thumb', $params['original_sum'], $params['thumbnail_sum']);
1725   
1726    if (isset($params['high_sum']))
1727    {
1728      $high_infos = add_file($file_path, 'high', $params['original_sum'], $params['high_sum']);
1729    }
[2569]1730
[12722]1731    // database registration
1732    $insert = array(
1733      'file' => !empty($params['original_filename']) ? $params['original_filename'] : $filename_wo_ext.'.jpg',
1734      'date_available' => $dbnow,
1735      'tn_ext' => 'jpg',
1736      'name' => $params['name'],
1737      'path' => $file_path,
1738      'filesize' => $file_infos['filesize'],
1739      'width' => $file_infos['width'],
1740      'height' => $file_infos['height'],
1741      'md5sum' => $params['original_sum'],
1742      'added_by' => $user['id'],
1743      );
1744
1745    $info_columns = array(
1746      'name',
1747      'author',
1748      'comment',
1749      'level',
1750      'date_creation',
1751      );
1752
1753    foreach ($info_columns as $key)
[2569]1754    {
[12722]1755      if (isset($params[$key]))
1756      {
1757        $insert[$key] = $params[$key];
1758      }
[2569]1759    }
1760
[12722]1761    if (isset($params['high_sum']))
1762    {
1763      $insert['has_high'] = 'true';
1764      $insert['high_filesize'] = $high_infos['filesize'];
1765      $insert['high_width'] = $high_infos['width'];
1766      $insert['high_height'] = $high_infos['height'];
1767    }
[2670]1768
[12722]1769    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1770    mass_inserts(
1771      IMAGES_TABLE,
1772      array_keys($insert),
1773      array($insert)
1774      );
[2463]1775
[12722]1776    $image_id = pwg_db_insert_id(IMAGES_TABLE);
[2463]1777
[12722]1778    // update metadata from the uploaded file (exif/iptc)
1779    require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1780    update_metadata(array($image_id=>$file_path));
1781  }
1782
[2569]1783  // let's add links between the image and the categories
1784  if (isset($params['categories']))
1785  {
[2919]1786    ws_add_image_category_relations($image_id, $params['categories']);
[2553]1787  }
[2569]1788
1789  // and now, let's create tag associations
[3660]1790  if (isset($params['tag_ids']) and !empty($params['tag_ids']))
[2553]1791  {
[2569]1792    set_tags(
1793      explode(',', $params['tag_ids']),
1794      $image_id
1795      );
[2553]1796  }
[2585]1797
[2501]1798  invalidate_user_cache();
[2463]1799}
1800
[8249]1801function ws_images_addSimple($params, &$service)
1802{
1803  global $conf;
[8274]1804  if (!is_admin())
[8249]1805  {
1806    return new PwgError(401, 'Access denied');
1807  }
1808
1809  if (!$service->isPost())
1810  {
1811    return new PwgError(405, "This method requires HTTP POST");
1812  }
[11118]1813
1814  if (!isset($_FILES['image']))
1815  {
1816    return new PwgError(405, "The image (file) parameter is missing");
1817  }
[11893]1818
[9191]1819  $params['image_id'] = (int)$params['image_id'];
1820  if ($params['image_id'] > 0)
1821  {
1822    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
[8249]1823
[9191]1824    $query='
1825SELECT *
1826  FROM '.IMAGES_TABLE.'
1827  WHERE id = '.$params['image_id'].'
1828;';
1829
1830    $image_row = pwg_db_fetch_assoc(pwg_query($query));
1831    if ($image_row == null)
1832    {
1833      return new PwgError(404, "image_id not found");
1834    }
1835  }
1836
[8249]1837  // category
1838  $params['category'] = (int)$params['category'];
[9191]1839  if ($params['category'] <= 0 and $params['image_id'] <= 0)
[8249]1840  {
1841    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
1842  }
1843
1844  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1845
1846  $image_id = add_uploaded_file(
1847    $_FILES['image']['tmp_name'],
1848    $_FILES['image']['name'],
[9191]1849    $params['category'] > 0 ? array($params['category']) : null,
1850    8,
1851    $params['image_id'] > 0 ? $params['image_id'] : null
[8249]1852    );
1853
1854  $info_columns = array(
1855    'name',
1856    'author',
1857    'comment',
1858    'level',
1859    'date_creation',
1860    );
1861
1862  foreach ($info_columns as $key)
1863  {
1864    if (isset($params[$key]))
1865    {
1866      $update[$key] = $params[$key];
1867    }
1868  }
1869
1870  if (count(array_keys($update)) > 0)
1871  {
1872    $update['id'] = $image_id;
1873
1874    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1875    mass_updates(
1876      IMAGES_TABLE,
1877      array(
1878        'primary' => array('id'),
1879        'update'  => array_diff(array_keys($update), array('id'))
1880        ),
1881      array($update)
1882      );
1883  }
1884
1885
1886  if (isset($params['tags']) and !empty($params['tags']))
1887  {
1888    $tag_ids = array();
1889    $tag_names = explode(',', $params['tags']);
1890    foreach ($tag_names as $tag_name)
1891    {
1892      $tag_id = tag_id_from_tag_name($tag_name);
1893      array_push($tag_ids, $tag_id);
1894    }
1895
1896    add_tags($tag_ids, array($image_id));
1897  }
1898
[9191]1899  $url_params = array('image_id' => $image_id);
1900
1901  if ($params['category'] > 0)
1902  {
1903    $query = '
[8249]1904SELECT id, name, permalink
1905  FROM '.CATEGORIES_TABLE.'
1906  WHERE id = '.$params['category'].'
1907;';
[9191]1908    $result = pwg_query($query);
1909    $category = pwg_db_fetch_assoc($result);
[8249]1910
[9191]1911    $url_params['section'] = 'categories';
1912    $url_params['category'] = $category;
1913  }
1914
[9944]1915  // update metadata from the uploaded file (exif/iptc), even if the sync
1916  // was already performed by add_uploaded_file().
1917  $query = '
1918SELECT
1919    path
1920  FROM '.IMAGES_TABLE.'
1921  WHERE id = '.$image_id.'
1922;';
1923  list($file_path) = pwg_db_fetch_row(pwg_query($query));
[11893]1924
[9944]1925  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1926  update_metadata(array($image_id=>$file_path));
1927
[8249]1928  return array(
1929    'image_id' => $image_id,
[9191]1930    'url' => make_picture_url($url_params),
[8249]1931    );
1932}
1933
[12651]1934function ws_rates_delete($params, &$service)
1935{
1936  global $conf;
1937
1938  if (!$service->isPost())
1939  {
1940    return new PwgError(405, 'This method requires HTTP POST');
1941  }
1942
1943  if (!is_admin())
1944  {
1945    return new PwgError(401, 'Access denied');
1946  }
1947
1948  $user_id = (int)$params['user_id'];
1949  if ($user_id<=0)
1950  {
1951    return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid user_id');
1952  }
1953 
1954  $query = '
1955DELETE FROM '.RATE_TABLE.'
1956  WHERE user_id='.$user_id;
1957 
1958  if (!empty($params['anonymous_id']))
1959  {
1960    $query .= ' AND anonymous_id=\''.$params['anonymous_id'].'\'';
1961  }
1962 
1963  $changes = pwg_db_changes(pwg_query($query));
1964  if ($changes)
1965  {
1966    include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
1967    update_rating_score();
1968  }
1969  return $changes;
1970}
1971
1972
[1781]1973/**
1974 * perform a login (web service method)
1975 */
[1698]1976function ws_session_login($params, &$service)
1977{
1978  global $conf;
1979
1980  if (!$service->isPost())
1981  {
[1852]1982    return new PwgError(405, "This method requires HTTP POST");
[1698]1983  }
[1744]1984  if (try_log_user($params['username'], $params['password'],false))
[1698]1985  {
1986    return true;
1987  }
1988  return new PwgError(999, 'Invalid username/password');
1989}
1990
[1781]1991
1992/**
1993 * performs a logout (web service method)
1994 */
[1698]1995function ws_session_logout($params, &$service)
1996{
[2029]1997  if (!is_a_guest())
[1698]1998  {
[2757]1999    logout_user();
[1698]2000  }
2001  return true;
2002}
2003
2004function ws_session_getStatus($params, &$service)
2005{
[2356]2006  global $user;
[1698]2007  $res = array();
[4304]2008  $res['username'] = is_a_guest() ? 'guest' : stripslashes($user['username']);
[6437]2009  foreach ( array('status', 'theme', 'language') as $k )
[1849]2010  {
2011    $res[$k] = $user[$k];
2012  }
[7212]2013  $res['pwg_token'] = get_pwg_token();
[2126]2014  $res['charset'] = get_pwg_charset();
[11756]2015
2016  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2017  $res['current_datetime'] = $dbnow;
[11893]2018
[1698]2019  return $res;
2020}
2021
2022
[1781]2023/**
2024 * returns a list of tags (web service method)
2025 */
[1698]2026function ws_tags_getList($params, &$service)
2027{
[1711]2028  $tags = get_available_tags();
[1698]2029  if ($params['sort_by_counter'])
2030  {
2031    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
2032  }
2033  else
2034  {
[2409]2035    usort($tags, 'tag_alpha_compare');
[1698]2036  }
2037  for ($i=0; $i<count($tags); $i++)
2038  {
[1815]2039    $tags[$i]['id'] = (int)$tags[$i]['id'];
[1698]2040    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
2041    $tags[$i]['url'] = make_index_url(
2042        array(
2043          'section'=>'tags',
2044          'tags'=>array($tags[$i])
2045        )
2046      );
2047  }
[2585]2048  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
[1698]2049}
2050
[2584]2051/**
2052 * returns the list of tags as you can see them in administration (web
2053 * service method).
2054 *
2055 * Only admin can run this method and permissions are not taken into
2056 * account.
2057 */
2058function ws_tags_getAdminList($params, &$service)
2059{
2060  if (!is_admin())
2061  {
2062    return new PwgError(401, 'Access denied');
2063  }
[2585]2064
[2584]2065  $tags = get_all_tags();
2066  return array(
2067    'tags' => new PwgNamedArray(
2068      $tags,
2069      'tag',
2070      array(
2071        'name',
2072        'id',
2073        'url_name',
2074        )
2075      )
2076    );
2077}
[1781]2078
2079/**
2080 * returns a list of images for tags (web service method)
2081 */
[1698]2082function ws_tags_getImages($params, &$service)
2083{
2084  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
[1816]2085  global $conf;
[2119]2086
[1698]2087  // first build all the tag_ids we are interested in
[1852]2088  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
2089  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
[1698]2090  $tags_by_id = array();
2091  foreach( $tags as $tag )
2092  {
[1852]2093    $tags['id'] = (int)$tag['id'];
[1815]2094    $tags_by_id[ $tag['id'] ] = $tag;
[1698]2095  }
2096  unset($tags);
[1852]2097  $tag_ids = array_keys($tags_by_id);
[1698]2098
2099
[8726]2100  $where_clauses = ws_std_image_sql_filter($params);
2101  if (!empty($where_clauses))
2102  {
2103    $where_clauses = implode( ' AND ', $where_clauses);
2104  }
2105  $image_ids = get_image_ids_for_tags(
2106    $tag_ids,
2107    $params['tag_mode_and'] ? 'AND' : 'OR',
2108    $where_clauses,
2109    ws_std_image_sql_order($params) );
2110
2111
2112  $image_ids = array_slice($image_ids, (int)($params['per_page']*$params['page']), (int)$params['per_page'] );
[11893]2113
[1698]2114  $image_tag_map = array();
[8726]2115  if ( !empty($image_ids) and !$params['tag_mode_and'] )
[1698]2116  { // build list of image ids with associated tags per image
[8726]2117    $query = '
[6652]2118SELECT image_id, GROUP_CONCAT(tag_id) AS tag_ids
[1698]2119  FROM '.IMAGE_TAG_TABLE.'
[8726]2120  WHERE tag_id IN ('.implode(',',$tag_ids).') AND image_id IN ('.implode(',',$image_ids).')
[1698]2121  GROUP BY image_id';
[8726]2122    $result = pwg_query($query);
2123    while ( $row=pwg_db_fetch_assoc($result) )
2124    {
2125      $row['image_id'] = (int)$row['image_id'];
2126      array_push( $image_ids, $row['image_id'] );
2127      $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
[1698]2128    }
2129  }
2130
2131  $images = array();
[8726]2132  if (!empty($image_ids))
[1698]2133  {
[8726]2134    $rank_of = array_flip($image_ids);
2135    $result = pwg_query('
2136SELECT * FROM '.IMAGES_TABLE.'
2137  WHERE id IN ('.implode(',',$image_ids).')');
[4325]2138    while ($row = pwg_db_fetch_assoc($result))
[1698]2139    {
[2119]2140      $image = array();
[8726]2141      $image['rank'] = $rank_of[ $row['id'] ];
[1698]2142      foreach ( array('id', 'width', 'height', 'hit') as $k )
2143      {
2144        if (isset($row[$k]))
2145        {
2146          $image[$k] = (int)$row[$k];
2147        }
2148      }
[11116]2149      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
[1698]2150      {
2151        $image[$k] = $row[$k];
2152      }
2153      $image = array_merge( $image, ws_std_get_urls($row) );
2154
2155      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
2156      $image_tags = array();
2157      foreach ($image_tag_ids as $tag_id)
2158      {
2159        $url = make_index_url(
2160                 array(
2161                  'section'=>'tags',
2162                  'tags'=> array($tags_by_id[$tag_id])
2163                )
2164              );
2165        $page_url = make_picture_url(
2166                 array(
2167                  'section'=>'tags',
2168                  'tags'=> array($tags_by_id[$tag_id]),
2169                  'image_id' => $row['id'],
2170                  'image_file' => $row['file'],
2171                )
2172              );
2173        array_push($image_tags, array(
2174                'id' => (int)$tag_id,
2175                'url' => $url,
2176                'page_url' => $page_url,
2177              )
2178            );
2179      }
[1711]2180      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
2181              array('id','url_name','url','page_url')
[1698]2182            );
2183      array_push($images, $image);
2184    }
[8726]2185    usort($images, 'rank_compare');
2186    unset($rank_of);
[1698]2187  }
2188
2189  return array( 'images' =>
2190    array (
2191      WS_XML_ATTRIBUTES =>
2192        array(
2193            'page' => $params['page'],
2194            'per_page' => $params['per_page'],
2195            'count' => count($images)
2196          ),
[1711]2197       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
[1845]2198          ws_std_get_image_xml_attributes() )
[1698]2199      )
2200    );
2201}
[2583]2202
2203function ws_categories_add($params, &$service)
2204{
[8126]2205  if (!is_admin())
[2583]2206  {
2207    return new PwgError(401, 'Access denied');
2208  }
2209
2210  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2211
2212  $creation_output = create_virtual_category(
2213    $params['name'],
2214    $params['parent']
2215    );
2216
2217  if (isset($creation_output['error']))
2218  {
2219    return new PwgError(500, $creation_output['error']);
2220  }
[2585]2221
[2644]2222  invalidate_user_cache();
[2757]2223
[2583]2224  return $creation_output;
2225}
[2634]2226
2227function ws_tags_add($params, &$service)
2228{
[8126]2229  if (!is_admin())
[2634]2230  {
2231    return new PwgError(401, 'Access denied');
2232  }
2233
2234  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2235
2236  $creation_output = create_tag($params['name']);
2237
2238  if (isset($creation_output['error']))
2239  {
2240    return new PwgError(500, $creation_output['error']);
2241  }
2242
2243  return $creation_output;
2244}
[2683]2245
2246function ws_images_exist($params, &$service)
2247{
[4954]2248  global $conf;
[11893]2249
[8126]2250  if (!is_admin())
[2683]2251  {
2252    return new PwgError(401, 'Access denied');
2253  }
2254
[4954]2255  $split_pattern = '/[\s,;\|]/';
2256
2257  if ('md5sum' == $conf['uniqueness_mode'])
2258  {
2259    // search among photos the list of photos already added, based on md5sum
2260    // list
2261    $md5sums = preg_split(
2262      $split_pattern,
2263      $params['md5sum_list'],
2264      -1,
2265      PREG_SPLIT_NO_EMPTY
[2683]2266    );
[2757]2267
[4954]2268    $query = '
[2683]2269SELECT
2270    id,
2271    md5sum
2272  FROM '.IMAGES_TABLE.'
[2757]2273  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
[2683]2274;';
[4954]2275    $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
[2683]2276
[4954]2277    $result = array();
[2757]2278
[4954]2279    foreach ($md5sums as $md5sum)
2280    {
2281      $result[$md5sum] = null;
2282      if (isset($id_of_md5[$md5sum]))
2283      {
2284        $result[$md5sum] = $id_of_md5[$md5sum];
2285      }
2286    }
2287  }
[11893]2288
[4954]2289  if ('filename' == $conf['uniqueness_mode'])
[2683]2290  {
[4954]2291    // search among photos the list of photos already added, based on
2292    // filename list
2293    $filenames = preg_split(
2294      $split_pattern,
2295      $params['filename_list'],
2296      -1,
2297      PREG_SPLIT_NO_EMPTY
2298    );
2299
2300    $query = '
2301SELECT
2302    id,
2303    file
2304  FROM '.IMAGES_TABLE.'
2305  WHERE file IN (\''.implode("','", $filenames).'\')
2306;';
2307    $id_of_filename = simple_hash_from_query($query, 'file', 'id');
2308
2309    $result = array();
2310
2311    foreach ($filenames as $filename)
[2683]2312    {
[4954]2313      $result[$filename] = null;
2314      if (isset($id_of_filename[$filename]))
2315      {
2316        $result[$filename] = $id_of_filename[$filename];
2317      }
[2683]2318    }
2319  }
2320
2321  return $result;
2322}
[2919]2323
[4347]2324function ws_images_checkFiles($params, &$service)
2325{
[8126]2326  if (!is_admin())
[4347]2327  {
2328    return new PwgError(401, 'Access denied');
2329  }
2330
2331  // input parameters
2332  //
2333  // image_id
2334  // thumbnail_sum
2335  // file_sum
2336  // high_sum
2337
2338  $params['image_id'] = (int)$params['image_id'];
2339  if ($params['image_id'] <= 0)
2340  {
2341    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2342  }
2343
2344  $query = '
2345SELECT
2346    path
2347  FROM '.IMAGES_TABLE.'
2348  WHERE id = '.$params['image_id'].'
2349;';
2350  $result = pwg_query($query);
[6500]2351  if (pwg_db_num_rows($result) == 0) {
[4347]2352    return new PwgError(404, "image_id not found");
2353  }
[6500]2354  list($path) = pwg_db_fetch_row($result);
[4347]2355
2356  $ret = array();
2357
2358  foreach (array('thumb', 'file', 'high') as $type) {
2359    $param_name = $type;
2360    if ('thumb' == $type) {
2361      $param_name = 'thumbnail';
2362    }
2363
2364    if (isset($params[$param_name.'_sum'])) {
[8249]2365      include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[4347]2366      $type_path = file_path_for_type($path, $type);
2367      if (!is_file($type_path)) {
2368        $ret[$param_name] = 'missing';
2369      }
2370      else {
2371        if (md5_file($type_path) != $params[$param_name.'_sum']) {
2372          $ret[$param_name] = 'differs';
2373        }
2374        else {
2375          $ret[$param_name] = 'equals';
2376        }
2377      }
2378    }
2379  }
2380
2381  return $ret;
2382}
2383
[2919]2384function ws_images_setInfo($params, &$service)
2385{
2386  global $conf;
[8126]2387  if (!is_admin())
[2919]2388  {
2389    return new PwgError(401, 'Access denied');
2390  }
2391
[4511]2392  if (!$service->isPost())
2393  {
2394    return new PwgError(405, "This method requires HTTP POST");
2395  }
2396
[2919]2397  $params['image_id'] = (int)$params['image_id'];
2398  if ($params['image_id'] <= 0)
2399  {
2400    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2401  }
2402
[7613]2403  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2404
[2919]2405  $query='
2406SELECT *
2407  FROM '.IMAGES_TABLE.'
2408  WHERE id = '.$params['image_id'].'
2409;';
2410
[4325]2411  $image_row = pwg_db_fetch_assoc(pwg_query($query));
[2919]2412  if ($image_row == null)
2413  {
2414    return new PwgError(404, "image_id not found");
2415  }
2416
2417  // database registration
[4460]2418  $update = array();
[2919]2419
2420  $info_columns = array(
2421    'name',
2422    'author',
2423    'comment',
2424    'level',
2425    'date_creation',
2426    );
2427
2428  foreach ($info_columns as $key)
2429  {
2430    if (isset($params[$key]))
2431    {
[4460]2432      if ('fill_if_empty' == $params['single_value_mode'])
2433      {
2434        if (empty($image_row[$key]))
2435        {
2436          $update[$key] = $params[$key];
2437        }
2438      }
2439      elseif ('replace' == $params['single_value_mode'])
2440      {
2441        $update[$key] = $params[$key];
2442      }
2443      else
2444      {
2445        new PwgError(
2446          500,
2447          '[ws_images_setInfo]'
2448          .' invalid parameter single_value_mode "'.$params['single_value_mode'].'"'
2449          .', possible values are {fill_if_empty, replace}.'
2450          );
2451        exit();
2452      }
[2919]2453    }
2454  }
2455
[4460]2456  if (count(array_keys($update)) > 0)
[2919]2457  {
[4460]2458    $update['id'] = $params['image_id'];
2459
[2919]2460    mass_updates(
2461      IMAGES_TABLE,
2462      array(
2463        'primary' => array('id'),
2464        'update'  => array_diff(array_keys($update), array('id'))
2465        ),
2466      array($update)
2467      );
2468  }
[3145]2469
[2919]2470  if (isset($params['categories']))
2471  {
2472    ws_add_image_category_relations(
2473      $params['image_id'],
[4445]2474      $params['categories'],
[4460]2475      ('replace' == $params['multiple_value_mode'] ? true : false)
[2919]2476      );
2477  }
2478
2479  // and now, let's create tag associations
2480  if (isset($params['tag_ids']))
2481  {
[4445]2482    $tag_ids = explode(',', $params['tag_ids']);
2483
[4460]2484    if ('replace' == $params['multiple_value_mode'])
[4445]2485    {
2486      set_tags(
2487        $tag_ids,
2488        $params['image_id']
2489        );
2490    }
[4460]2491    elseif ('append' == $params['multiple_value_mode'])
[4445]2492    {
2493      add_tags(
2494        $tag_ids,
2495        array($params['image_id'])
2496        );
2497    }
[4460]2498    else
2499    {
2500      new PwgError(
2501        500,
2502        '[ws_images_setInfo]'
2503        .' invalid parameter multiple_value_mode "'.$params['multiple_value_mode'].'"'
2504        .', possible values are {replace, append}.'
2505        );
2506      exit();
2507    }
[2919]2508  }
2509
2510  invalidate_user_cache();
2511}
2512
[8266]2513function ws_images_delete($params, &$service)
2514{
2515  global $conf;
[8274]2516  if (!is_admin())
[8266]2517  {
2518    return new PwgError(401, 'Access denied');
2519  }
2520
2521  if (!$service->isPost())
2522  {
2523    return new PwgError(405, "This method requires HTTP POST");
2524  }
2525
2526  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2527  {
2528    return new PwgError(403, 'Invalid security token');
2529  }
2530
2531  $params['image_id'] = preg_split(
2532    '/[\s,;\|]/',
2533    $params['image_id'],
2534    -1,
2535    PREG_SPLIT_NO_EMPTY
2536    );
2537  $params['image_id'] = array_map('intval', $params['image_id']);
2538
2539  $image_ids = array();
2540  foreach ($params['image_id'] as $image_id)
2541  {
2542    if ($image_id > 0)
2543    {
2544      array_push($image_ids, $image_id);
2545    }
2546  }
2547
2548  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2549  delete_elements($image_ids, true);
2550}
2551
[4445]2552function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
[2919]2553{
2554  // let's add links between the image and the categories
2555  //
2556  // $params['categories'] should look like 123,12;456,auto;789 which means:
2557  //
2558  // 1. associate with category 123 on rank 12
2559  // 2. associate with category 456 on automatic rank
2560  // 3. associate with category 789 on automatic rank
2561  $cat_ids = array();
2562  $rank_on_category = array();
2563  $search_current_ranks = false;
2564
2565  $tokens = explode(';', $categories_string);
2566  foreach ($tokens as $token)
2567  {
[2920]2568    @list($cat_id, $rank) = explode(',', $token);
[2919]2569
[4445]2570    if (!preg_match('/^\d+$/', $cat_id))
2571    {
2572      continue;
2573    }
2574
[2919]2575    array_push($cat_ids, $cat_id);
2576
2577    if (!isset($rank))
2578    {
2579      $rank = 'auto';
2580    }
2581    $rank_on_category[$cat_id] = $rank;
2582
2583    if ($rank == 'auto')
2584    {
2585      $search_current_ranks = true;
2586    }
2587  }
2588
2589  $cat_ids = array_unique($cat_ids);
2590
[4445]2591  if (count($cat_ids) == 0)
[2919]2592  {
[4445]2593    new PwgError(
2594      500,
2595      '[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
2596      );
2597    exit();
2598  }
[4513]2599
[4445]2600  $query = '
2601SELECT
2602    id
2603  FROM '.CATEGORIES_TABLE.'
2604  WHERE id IN ('.implode(',', $cat_ids).')
2605;';
2606  $db_cat_ids = array_from_query($query, 'id');
2607
2608  $unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
2609  if (count($unknown_cat_ids) != 0)
2610  {
2611    new PwgError(
2612      500,
2613      '[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
2614      );
2615    exit();
2616  }
[4513]2617
[4445]2618  $to_update_cat_ids = array();
[4513]2619
[4445]2620  // in case of replace mode, we first check the existing associations
2621  $query = '
2622SELECT
2623    category_id
2624  FROM '.IMAGE_CATEGORY_TABLE.'
2625  WHERE image_id = '.$image_id.'
2626;';
2627  $existing_cat_ids = array_from_query($query, 'category_id');
2628
2629  if ($replace_mode)
2630  {
2631    $to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
2632    if (count($to_remove_cat_ids) > 0)
[2919]2633    {
2634      $query = '
[4445]2635DELETE
2636  FROM '.IMAGE_CATEGORY_TABLE.'
2637  WHERE image_id = '.$image_id.'
2638    AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
2639;';
2640      pwg_query($query);
2641      update_category($to_remove_cat_ids);
2642    }
2643  }
[4513]2644
[4445]2645  $new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
2646  if (count($new_cat_ids) == 0)
2647  {
2648    return true;
2649  }
[4513]2650
[4445]2651  if ($search_current_ranks)
2652  {
2653    $query = '
[2919]2654SELECT
2655    category_id,
2656    MAX(rank) AS max_rank
2657  FROM '.IMAGE_CATEGORY_TABLE.'
2658  WHERE rank IS NOT NULL
[4445]2659    AND category_id IN ('.implode(',', $new_cat_ids).')
[2919]2660  GROUP BY category_id
2661;';
[4445]2662    $current_rank_of = simple_hash_from_query(
2663      $query,
2664      'category_id',
2665      'max_rank'
2666      );
[2919]2667
[4445]2668    foreach ($new_cat_ids as $cat_id)
2669    {
2670      if (!isset($current_rank_of[$cat_id]))
[2919]2671      {
[4445]2672        $current_rank_of[$cat_id] = 0;
[2919]2673      }
[4513]2674
[4445]2675      if ('auto' == $rank_on_category[$cat_id])
2676      {
2677        $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
2678      }
[2919]2679    }
[4445]2680  }
[4513]2681
[4445]2682  $inserts = array();
[4513]2683
[4445]2684  foreach ($new_cat_ids as $cat_id)
2685  {
2686    array_push(
2687      $inserts,
2688      array(
2689        'image_id' => $image_id,
2690        'category_id' => $cat_id,
2691        'rank' => $rank_on_category[$cat_id],
2692        )
[2919]2693      );
2694  }
[4513]2695
[4445]2696  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2697  mass_inserts(
2698    IMAGE_CATEGORY_TABLE,
2699    array_keys($inserts[0]),
2700    $inserts
2701    );
[4513]2702
[4445]2703  update_category($new_cat_ids);
[2919]2704}
[3193]2705
[3454]2706function ws_categories_setInfo($params, &$service)
2707{
2708  global $conf;
[8126]2709  if (!is_admin())
[3454]2710  {
2711    return new PwgError(401, 'Access denied');
2712  }
2713
[4511]2714  if (!$service->isPost())
2715  {
2716    return new PwgError(405, "This method requires HTTP POST");
2717  }
2718
[3454]2719  // category_id
2720  // name
2721  // comment
2722
2723  $params['category_id'] = (int)$params['category_id'];
2724  if ($params['category_id'] <= 0)
2725  {
2726    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2727  }
2728
2729  // database registration
2730  $update = array(
2731    'id' => $params['category_id'],
2732    );
2733
2734  $info_columns = array(
2735    'name',
2736    'comment',
2737    );
2738
2739  $perform_update = false;
2740  foreach ($info_columns as $key)
2741  {
2742    if (isset($params[$key]))
2743    {
2744      $perform_update = true;
2745      $update[$key] = $params[$key];
2746    }
2747  }
2748
2749  if ($perform_update)
2750  {
2751    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2752    mass_updates(
2753      CATEGORIES_TABLE,
2754      array(
2755        'primary' => array('id'),
2756        'update'  => array_diff(array_keys($update), array('id'))
2757        ),
2758      array($update)
2759      );
2760  }
[3488]2761
[3454]2762}
2763
[11746]2764function ws_categories_setRepresentative($params, &$service)
2765{
2766  global $conf;
[11893]2767
[11746]2768  if (!is_admin())
2769  {
2770    return new PwgError(401, 'Access denied');
2771  }
2772
2773  if (!$service->isPost())
2774  {
2775    return new PwgError(405, "This method requires HTTP POST");
2776  }
2777
2778  // category_id
2779  // image_id
2780
2781  $params['category_id'] = (int)$params['category_id'];
2782  if ($params['category_id'] <= 0)
2783  {
2784    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2785  }
2786
2787  // does the category really exist?
2788  $query='
2789SELECT
2790    *
2791  FROM '.CATEGORIES_TABLE.'
2792  WHERE id = '.$params['category_id'].'
2793;';
2794  $row = pwg_db_fetch_assoc(pwg_query($query));
2795  if ($row == null)
2796  {
2797    return new PwgError(404, "category_id not found");
2798  }
2799
2800  $params['image_id'] = (int)$params['image_id'];
2801  if ($params['image_id'] <= 0)
2802  {
2803    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2804  }
[11893]2805
[11746]2806  // does the image really exist?
2807  $query='
2808SELECT
2809    *
2810  FROM '.IMAGES_TABLE.'
2811  WHERE id = '.$params['image_id'].'
2812;';
2813
2814  $row = pwg_db_fetch_assoc(pwg_query($query));
2815  if ($row == null)
2816  {
2817    return new PwgError(404, "image_id not found");
2818  }
2819
2820  // apply change
2821  $query = '
2822UPDATE '.CATEGORIES_TABLE.'
2823  SET representative_picture_id = '.$params['image_id'].'
2824  WHERE id = '.$params['category_id'].'
2825;';
2826  pwg_query($query);
2827
2828  $query = '
2829UPDATE '.USER_CACHE_CATEGORIES_TABLE.'
2830  SET user_representative_picture_id = NULL
2831  WHERE cat_id = '.$params['category_id'].'
2832;';
2833  pwg_query($query);
2834}
2835
[8266]2836function ws_categories_delete($params, &$service)
2837{
2838  global $conf;
[8274]2839  if (!is_admin())
[8266]2840  {
2841    return new PwgError(401, 'Access denied');
2842  }
2843
2844  if (!$service->isPost())
2845  {
2846    return new PwgError(405, "This method requires HTTP POST");
2847  }
2848
2849  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2850  {
2851    return new PwgError(403, 'Invalid security token');
2852  }
2853
2854  $modes = array('no_delete', 'delete_orphans', 'force_delete');
2855  if (!in_array($params['photo_deletion_mode'], $modes))
2856  {
2857    return new PwgError(
2858      500,
2859      '[ws_categories_delete]'
2860      .' invalid parameter photo_deletion_mode "'.$params['photo_deletion_mode'].'"'
2861      .', possible values are {'.implode(', ', $modes).'}.'
2862      );
2863  }
2864
2865  $params['category_id'] = preg_split(
2866    '/[\s,;\|]/',
2867    $params['category_id'],
2868    -1,
2869    PREG_SPLIT_NO_EMPTY
2870    );
2871  $params['category_id'] = array_map('intval', $params['category_id']);
2872
2873  $category_ids = array();
2874  foreach ($params['category_id'] as $category_id)
2875  {
2876    if ($category_id > 0)
2877    {
2878      array_push($category_ids, $category_id);
2879    }
2880  }
2881
2882  if (count($category_ids) == 0)
2883  {
2884    return;
2885  }
2886
2887  $query = '
2888SELECT id
2889  FROM '.CATEGORIES_TABLE.'
2890  WHERE id IN ('.implode(',', $category_ids).')
2891;';
2892  $category_ids = array_from_query($query, 'id');
2893
2894  if (count($category_ids) == 0)
2895  {
2896    return;
2897  }
[11893]2898
[8266]2899  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2900  delete_categories($category_ids, $params['photo_deletion_mode']);
2901  update_global_rank();
2902}
2903
[8272]2904function ws_categories_move($params, &$service)
2905{
2906  global $conf, $page;
[11893]2907
[8274]2908  if (!is_admin())
[8272]2909  {
2910    return new PwgError(401, 'Access denied');
2911  }
2912
2913  if (!$service->isPost())
2914  {
2915    return new PwgError(405, "This method requires HTTP POST");
2916  }
2917
2918  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2919  {
2920    return new PwgError(403, 'Invalid security token');
2921  }
2922
2923  $params['category_id'] = preg_split(
2924    '/[\s,;\|]/',
2925    $params['category_id'],
2926    -1,
2927    PREG_SPLIT_NO_EMPTY
2928    );
2929  $params['category_id'] = array_map('intval', $params['category_id']);
2930
2931  $category_ids = array();
2932  foreach ($params['category_id'] as $category_id)
2933  {
2934    if ($category_id > 0)
2935    {
2936      array_push($category_ids, $category_id);
2937    }
2938  }
2939
2940  if (count($category_ids) == 0)
2941  {
2942    return new PwgError(403, 'Invalid category_id input parameter, no category to move');
2943  }
2944
2945  // we can't move physical categories
2946  $categories_in_db = array();
[11893]2947
[8272]2948  $query = '
2949SELECT
2950    id,
2951    name,
2952    dir
2953  FROM '.CATEGORIES_TABLE.'
2954  WHERE id IN ('.implode(',', $category_ids).')
2955;';
2956  $result = pwg_query($query);
2957  while ($row = pwg_db_fetch_assoc($result))
2958  {
2959    $categories_in_db[$row['id']] = $row;
2960    // we break on error at first physical category detected
2961    if (!empty($row['dir']))
2962    {
2963      $row['name'] = strip_tags(
2964        trigger_event(
2965          'render_category_name',
2966          $row['name'],
2967          'ws_categories_move'
2968          )
2969        );
[11893]2970
[8272]2971      return new PwgError(
2972        403,
2973        sprintf(
2974          'Category %s (%u) is not a virtual category, you cannot move it',
2975          $row['name'],
2976          $row['id']
2977          )
2978        );
2979    }
2980  }
2981
2982  if (count($categories_in_db) != count($category_ids))
2983  {
2984    $unknown_category_ids = array_diff($category_ids, array_keys($categories_in_db));
[11893]2985
[8272]2986    return new PwgError(
2987      403,
2988      sprintf(
2989        'Category %u does not exist',
2990        $unknown_category_ids[0]
2991        )
2992      );
2993  }
2994
2995  // does this parent exists? This check should be made in the
2996  // move_categories function, not here
2997  //
2998  // 0 as parent means "move categories at gallery root"
2999  if (!is_numeric($params['parent']))
3000  {
3001    return new PwgError(403, 'Invalid parent input parameter');
3002  }
[11893]3003
[8272]3004  if (0 != $params['parent']) {
3005    $params['parent'] = intval($params['parent']);
3006    $subcat_ids = get_subcat_ids(array($params['parent']));
3007    if (count($subcat_ids) == 0)
3008    {
3009      return new PwgError(403, 'Unknown parent category id');
3010    }
3011  }
3012
3013  $page['infos'] = array();
3014  $page['errors'] = array();
3015  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3016  move_categories($category_ids, $params['parent']);
3017  invalidate_user_cache();
3018
3019  if (count($page['errors']) != 0)
3020  {
3021    return new PwgError(403, implode('; ', $page['errors']));
3022  }
3023}
3024
[3193]3025function ws_logfile($string)
3026{
[3662]3027  global $conf;
[3488]3028
[3662]3029  if (!$conf['ws_enable_log']) {
3030    return true;
3031  }
3032
[3193]3033  file_put_contents(
[3662]3034    $conf['ws_log_filepath'],
[3193]3035    '['.date('c').'] '.$string."\n",
3036    FILE_APPEND
3037    );
3038}
[6049]3039
3040function ws_images_checkUpload($params, &$service)
3041{
3042  global $conf;
3043
[8126]3044  if (!is_admin())
[6049]3045  {
3046    return new PwgError(401, 'Access denied');
3047  }
3048
[8249]3049  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[6051]3050  $ret['message'] = ready_for_upload_message();
3051  $ret['ready_for_upload'] = true;
[11893]3052
[6051]3053  if (!empty($ret['message']))
3054  {
3055    $ret['ready_for_upload'] = false;
3056  }
[11893]3057
[6051]3058  return $ret;
3059}
[8273]3060
3061function ws_plugins_getList($params, &$service)
3062{
3063  global $conf;
[11893]3064
[8273]3065  if (!is_admin())
3066  {
3067    return new PwgError(401, 'Access denied');
3068  }
3069
3070  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3071  $plugins = new plugins();
3072  $plugins->sort_fs_plugins('name');
3073  $plugin_list = array();
3074
3075  foreach($plugins->fs_plugins as $plugin_id => $fs_plugin)
3076  {
3077    if (isset($plugins->db_plugins_by_id[$plugin_id]))
3078    {
3079      $state = $plugins->db_plugins_by_id[$plugin_id]['state'];
3080    }
3081    else
3082    {
3083      $state = 'uninstalled';
3084    }
3085
3086    array_push(
3087      $plugin_list,
3088      array(
3089        'id' => $plugin_id,
3090        'name' => $fs_plugin['name'],
3091        'version' => $fs_plugin['version'],
3092        'state' => $state,
3093        'description' => $fs_plugin['description'],
3094        )
3095      );
3096  }
3097
3098  return $plugin_list;
3099}
3100
3101function ws_plugins_performAction($params, &$service)
3102{
3103  global $template;
[11893]3104
[8273]3105  if (!is_admin())
3106  {
3107    return new PwgError(401, 'Access denied');
3108  }
3109
3110  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3111  {
3112    return new PwgError(403, 'Invalid security token');
3113  }
3114
3115  define('IN_ADMIN', true);
3116  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3117  $plugins = new plugins();
3118  $errors = $plugins->perform_action($params['action'], $params['plugin']);
3119
[11893]3120
[8273]3121  if (!empty($errors))
3122  {
3123    return new PwgError(500, $errors);
3124  }
3125  else
3126  {
3127    if (in_array($params['action'], array('activate', 'deactivate')))
3128    {
3129      $template->delete_compiled_templates();
3130    }
3131    return true;
3132  }
3133}
3134
[8297]3135function ws_themes_performAction($params, &$service)
3136{
3137  global $template;
[11893]3138
[8726]3139  if (!is_admin())
[8297]3140  {
3141    return new PwgError(401, 'Access denied');
3142  }
3143
3144  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3145  {
3146    return new PwgError(403, 'Invalid security token');
3147  }
3148
3149  define('IN_ADMIN', true);
3150  include_once(PHPWG_ROOT_PATH.'admin/include/themes.class.php');
3151  $themes = new themes();
3152  $errors = $themes->perform_action($params['action'], $params['theme']);
[11893]3153
[8297]3154  if (!empty($errors))
3155  {
3156    return new PwgError(500, $errors);
3157  }
3158  else
3159  {
3160    if (in_array($params['action'], array('activate', 'deactivate')))
3161    {
3162      $template->delete_compiled_templates();
3163    }
3164    return true;
3165  }
3166}
[10235]3167
[10686]3168function ws_images_resizethumbnail($params, &$service)
[10235]3169{
3170  if (!is_admin())
3171  {
3172    return new PwgError(401, 'Access denied');
3173  }
3174
[10563]3175  if (empty($params['image_id']) and empty($params['image_path']))
3176  {
3177    return new PwgError(403, "image_id or image_path is missing");
3178  }
3179
3180  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
[10641]3181  include_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
[10563]3182
3183  if (!empty($params['image_id']))
3184  {
3185    $query='
[10235]3186SELECT id, path, tn_ext, has_high
[10563]3187  FROM '.IMAGES_TABLE.'
3188  WHERE id = '.(int)$params['image_id'].'
[10235]3189;';
[10563]3190    $image = pwg_db_fetch_assoc(pwg_query($query));
[10235]3191
[10563]3192    if ($image == null)
3193    {
3194      return new PwgError(403, "image_id not found");
3195    }
3196
3197    $image_path = $image['path'];
3198    $thumb_path = get_thumbnail_path($image);
3199  }
3200  else
[10235]3201  {
[10563]3202    $image_path = $params['image_path'];
3203    $thumb_path = file_path_for_type($image_path, 'thumb');
[10235]3204  }
3205
[10686]3206  if (!file_exists($image_path) or !is_valid_image_extension(get_extension($image_path)))
[10235]3207  {
3208    return new PwgError(403, "image can't be resized");
3209  }
3210
[10563]3211  $result = false;
[10686]3212  prepare_directory(dirname($thumb_path));
3213  $img = new pwg_image($image_path, $params['library']);
[10563]3214
[10686]3215  $result =  $img->pwg_resize(
3216    $thumb_path,
3217    $params['maxwidth'],
3218    $params['maxheight'],
3219    $params['quality'],
3220    false, // automatic rotation is not needed for thumbnails.
3221    true, // strip metadata
3222    get_boolean($params['crop']),
3223    get_boolean($params['follow_orientation'])
3224  );
3225
3226  $img->destroy();
3227  return $result;
3228}
3229
3230function ws_images_resizewebsize($params, &$service)
3231{
3232  if (!is_admin())
[10235]3233  {
[10686]3234    return new PwgError(401, 'Access denied');
3235  }
[10563]3236
[10686]3237  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
3238  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
3239  include_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
[10641]3240
[10686]3241  $query='
[12175]3242SELECT id, path, tn_ext, has_high, width, height
[10686]3243  FROM '.IMAGES_TABLE.'
3244  WHERE id = '.(int)$params['image_id'].'
3245;';
3246  $image = pwg_db_fetch_assoc(pwg_query($query));
[10641]3247
[10686]3248  if ($image == null)
3249  {
3250    return new PwgError(403, "image_id not found");
[10235]3251  }
[10686]3252
3253  $image_path = $image['path'];
3254
[12175]3255  if (!is_valid_image_extension(get_extension($image_path)))
[10235]3256  {
[10686]3257    return new PwgError(403, "image can't be resized");
3258  }
[12175]3259 
3260  $hd_path = get_high_path($image);
[10641]3261
[12175]3262  if (empty($image['has_high']) or !file_exists($hd_path))
3263  {
3264    if ($image['width'] > $params['maxwidth'] or $image['height'] > $params['maxheight'])
3265    {
3266      $hd_path = file_path_for_type($image_path, 'high');
3267      $hd_dir = dirname($hd_path);
3268      prepare_directory($hd_dir);
3269     
3270      rename($image_path, $hd_path);
3271      $hd_infos = pwg_image_infos($hd_path);
3272
3273      single_update(
3274        IMAGES_TABLE,
3275        array(
3276          'has_high' => 'true',
3277          'high_filesize' => $hd_infos['filesize'],
3278          'high_width' => $hd_infos['width'],
3279          'high_height' => $hd_infos['height'],
3280          ),
3281        array(
3282          'id' => $image['id']
3283          )
3284        );
3285    }
3286    else
3287    {
3288      return new PwgError(403, "image can't be resized");
3289    }
3290  }
3291
[10686]3292  $result = false;
[10747]3293  $img = new pwg_image($hd_path, $params['library']);
[10454]3294
[10686]3295  $result = $img->pwg_resize(
3296    $image_path,
3297    $params['maxwidth'],
3298    $params['maxheight'],
3299    $params['quality'],
3300    $params['automatic_rotation'],
3301    false // strip metadata
3302    );
[10641]3303
[10686]3304  $img->destroy();
3305
3306  global $conf;
3307  $conf['use_exif'] = false;
3308  $conf['use_iptc'] = false;
3309  update_metadata(array($image['id'] => $image['path']));
3310
[10563]3311  return $result;
[10235]3312}
[10511]3313
3314function ws_extensions_update($params, &$service)
3315{
3316  if (!is_webmaster())
3317  {
3318    return new PwgError(401, l10n('Webmaster status is required.'));
3319  }
3320
3321  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3322  {
3323    return new PwgError(403, 'Invalid security token');
3324  }
3325
3326  if (empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3327  {
3328    return new PwgError(403, "invalid extension type");
3329  }
3330
3331  if (empty($params['id']) or empty($params['revision']))
3332  {
3333    return new PwgError(null, 'Wrong parameters');
3334  }
3335
3336  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3337  include_once(PHPWG_ROOT_PATH.'admin/include/'.$params['type'].'.class.php');
3338
3339  $type = $params['type'];
3340  $extension_id = $params['id'];
3341  $revision = $params['revision'];
3342
3343  $extension = new $type();
3344
3345  if ($type == 'plugins')
3346  {
3347    if (isset($extension->db_plugins_by_id[$extension_id]) and $extension->db_plugins_by_id[$extension_id]['state'] == 'active')
3348    {
3349      $extension->perform_action('deactivate', $extension_id);
3350
3351      redirect(PHPWG_ROOT_PATH
3352        . 'ws.php'
3353        . '?method=pwg.extensions.update'
3354        . '&type=plugins'
3355        . '&id=' . $extension_id
3356        . '&revision=' . $revision
3357        . '&reactivate=true'
3358        . '&pwg_token=' . get_pwg_token()
3359        . '&format=json'
3360      );
3361    }
[11893]3362
[10511]3363    $upgrade_status = $extension->extract_plugin_files('upgrade', $revision, $extension_id);
3364    $extension_name = $extension->fs_plugins[$extension_id]['name'];
3365
3366    if (isset($params['reactivate']))
3367    {
3368      $extension->perform_action('activate', $extension_id);
3369    }
3370  }
3371  elseif ($type == 'themes')
3372  {
3373    $upgrade_status = $extension->extract_theme_files('upgrade', $revision, $extension_id);
3374    $extension_name = $extension->fs_themes[$extension_id]['name'];
3375  }
3376  elseif ($type == 'languages')
3377  {
3378    $upgrade_status = $extension->extract_language_files('upgrade', $revision, $extension_id);
3379    $extension_name = $extension->fs_languages[$extension_id]['name'];
3380  }
3381
3382  global $template;
3383  $template->delete_compiled_templates();
3384
3385  switch ($upgrade_status)
3386  {
3387    case 'ok':
3388      return sprintf(l10n('%s has been successfully updated.'), $extension_name);
3389
3390    case 'temp_path_error':
3391      return new PwgError(null, l10n('Can\'t create temporary file.'));
3392
3393    case 'dl_archive_error':
3394      return new PwgError(null, l10n('Can\'t download archive.'));
3395
3396    case 'archive_error':
3397      return new PwgError(null, l10n('Can\'t read or extract archive.'));
3398
3399    default:
3400      return new PwgError(null, sprintf(l10n('An error occured during extraction (%s).'), $upgrade_status));
3401  }
3402}
3403
3404function ws_extensions_ignoreupdate($params, &$service)
3405{
3406  global $conf;
3407
3408  define('IN_ADMIN', true);
3409  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3410
3411  if (!is_webmaster())
3412  {
3413    return new PwgError(401, 'Access denied');
3414  }
3415
3416  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3417  {
3418    return new PwgError(403, 'Invalid security token');
3419  }
3420
3421  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3422
[10538]3423  // Reset ignored extension
[10511]3424  if ($params['reset'])
3425  {
[10596]3426    if (!empty($params['type']) and isset($conf['updates_ignored'][$params['type']]))
3427    {
3428      $conf['updates_ignored'][$params['type']] = array();
3429    }
3430    else
3431    {
3432      $conf['updates_ignored'] = array(
3433        'plugins'=>array(),
3434        'themes'=>array(),
3435        'languages'=>array()
3436      );
3437    }
[10511]3438    conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3439    unset($_SESSION['extensions_need_update']);
3440    return true;
3441  }
3442
3443  if (empty($params['id']) or empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3444  {
3445    return new PwgError(403, 'Invalid parameters');
3446  }
3447
3448  // Add or remove extension from ignore list
3449  if (!in_array($params['id'], $conf['updates_ignored'][$params['type']]))
3450  {
3451    array_push($conf['updates_ignored'][$params['type']], $params['id']);
3452  }
3453  conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3454  unset($_SESSION['extensions_need_update']);
3455  return true;
3456}
[10538]3457
3458function ws_extensions_checkupdates($params, &$service)
3459{
3460  global $conf;
3461
3462  define('IN_ADMIN', true);
3463  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3464  include_once(PHPWG_ROOT_PATH.'admin/include/updates.class.php');
3465  $update = new updates();
3466
3467  if (!is_admin())
3468  {
3469    return new PwgError(401, 'Access denied');
3470  }
3471
3472  $result = array();
3473
3474  if (!isset($_SESSION['need_update']))
3475    $update->check_piwigo_upgrade();
3476
3477  $result['piwigo_need_update'] = $_SESSION['need_update'];
3478
3479  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3480
3481  if (!isset($_SESSION['extensions_need_update']))
3482    $update->check_extensions();
3483  else
3484    $update->check_updated_extensions();
3485
3486  if (!is_array($_SESSION['extensions_need_update']))
3487    $result['ext_need_update'] = null;
3488  else
3489    $result['ext_need_update'] = !empty($_SESSION['extensions_need_update']);
3490
3491  return $result;
3492}
[11893]3493?>
Note: See TracBrowser for help on using the repository browser.