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

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

merge r12809 from branch 2.3 to trunk

bug 2543 fixed: the representative_picture_id was missing in the SQL query for pwg.categories.getList

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