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

Last change on this file since 12831 was 12831, checked in by rvelices, 12 years ago

feature 2548 multisize

  • rewrote local site sync + metadata sync
  • Property svn:eol-style set to LF
File size: 85.7 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
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// +-----------------------------------------------------------------------+
23
24/**** IMPLEMENTATION OF WEB SERVICE METHODS ***********************************/
25
26/**
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{
32  global $conf;
33
34  if ( strpos($methodName,'reflection.')===0 )
35  { // OK for reflection
36    return $res;
37  }
38
39  if ( !is_autorize_status(ACCESS_GUEST) and
40      strpos($methodName,'pwg.session.')!==0 )
41  {
42    return new PwgError(401, 'Access denied');
43  }
44
45  return $res;
46}
47
48/**
49 * returns a "standard" (for our web service) array of sql where clauses that
50 * filters the images (images table only)
51 */
52function ws_std_image_sql_filter( $params, $tbl_name='' )
53{
54  $clauses = array();
55  if ( is_numeric($params['f_min_rate']) )
56  {
57    $clauses[] = $tbl_name.'rating_score>'.$params['f_min_rate'];
58  }
59  if ( is_numeric($params['f_max_rate']) )
60  {
61    $clauses[] = $tbl_name.'rating_score<='.$params['f_max_rate'];
62  }
63  if ( is_numeric($params['f_min_hit']) )
64  {
65    $clauses[] = $tbl_name.'hit>'.$params['f_min_hit'];
66  }
67  if ( is_numeric($params['f_max_hit']) )
68  {
69    $clauses[] = $tbl_name.'hit<='.$params['f_max_hit'];
70  }
71  if ( isset($params['f_min_date_available']) )
72  {
73    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_available']."'";
74  }
75  if ( isset($params['f_max_date_available']) )
76  {
77    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_available']."'";
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
104 */
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':
124        $matches[1][$i] = DB_RANDOM_FUNCTION.'()'; break;
125    }
126    $sortable_fields = array('id', 'file', 'name', 'hit', 'rating_score',
127      'date_creation', 'date_available', DB_RANDOM_FUNCTION.'()' );
128    if ( in_array($matches[1][$i], $sortable_fields) )
129    {
130      if (!empty($ret))
131        $ret .= ', ';
132      if ($matches[1][$i] != DB_RANDOM_FUNCTION.'()' )
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
146 */
147function ws_std_get_urls($image_row)
148{
149  $ret = array();
150  global $user;
151  if ($user['enabled_high'])
152  {
153    $ret['element_url'] = get_element_url($image_row);
154  }
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;;
165  return $ret;
166}
167
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(
175    'id','element_url', 'file','width','height','hit','date_available','date_creation'
176    );
177}
178
179/**
180 * returns PWG version (web service method)
181 */
182function ws_getVersion($params, &$service)
183{
184  global $conf;
185  if ($conf['show_version'] or is_admin() )
186    return PHPWG_VERSION;
187  else
188    return new PwgError(403, 'Forbidden');
189}
190
191/**
192 * returns general informations (web service method)
193 */
194function ws_getInfos($params, &$service)
195{
196  if (!is_admin())
197  {
198    return new PwgError(403, 'Forbidden');
199  }
200
201  $infos['version'] = PHPWG_VERSION;
202
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
241  if ($infos['nb_comments'] > 0)
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
258function ws_caddie_add($params, &$service)
259{
260  if (!is_admin())
261  {
262    return new PwgError(401, 'Access denied');
263  }
264  $params['image_id'] = array_map( 'intval',$params['image_id'] );
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}
287
288/**
289 * returns images per category (web service method)
290 */
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    {
307      $where_clauses[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.$cat_id.'(,|$)\'';
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  }
321  $where_clauses[] = get_sql_condition_FandF(
322        array('forbidden_categories' => 'id'),
323        NULL, true
324      );
325
326  $query = '
327SELECT id, name, permalink, image_order
328  FROM '.CATEGORIES_TABLE.'
329  WHERE '. implode('
330    AND ', $where_clauses);
331  $result = pwg_query($query);
332  $cats = array();
333  while ($row = pwg_db_fetch_assoc($result))
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      .')';
346    $where_clauses[] = get_sql_condition_FandF( array(
347          'visible_images' => 'i.id'
348        ), null, true
349      );
350
351    $order_by = ws_std_image_sql_order($params, 'i.');
352    if ( empty($order_by)
353          and count($params['cat_id'])==1
354          and isset($cats[ $params['cat_id'][0] ]['image_order'])
355        )
356    {
357      $order_by = $cats[ $params['cat_id'][0] ]['image_order'];
358    }
359    $order_by = empty($order_by) ? $conf['order_by'] : 'ORDER BY '.$order_by;
360
361    $query = '
362SELECT i.*, GROUP_CONCAT(category_id) AS cat_ids
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.'
369LIMIT '.(int)$params['per_page'].' OFFSET '.(int)($params['per_page']*$params['page']);
370
371    $result = pwg_query($query);
372    while ($row = pwg_db_fetch_assoc($result))
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      }
382      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
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(
393                  'category' => $cats[$cat_id],
394                  )
395                );
396        $page_url = make_picture_url(
397                array(
398                  'category' => $cats[$cat_id],
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          ),
428       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
429          ws_std_get_image_xml_attributes() )
430      )
431    );
432}
433
434
435/**
436 * returns a list of categories (web service method)
437 */
438function ws_categories_getList($params, &$service)
439{
440  global $user,$conf;
441
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.
453
454      return new PwgError(405, "The tree_output option is only compatible with json/php output formats");
455    }
456  }
457
458  $where = array('1=1');
459  $join_type = 'INNER';
460  $join_user = $user['id'];
461
462  if (!$params['recursive'])
463  {
464    if ($params['cat_id']>0)
465      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
466    OR id='.(int)($params['cat_id']).')';
467    else
468      $where[] = 'id_uppercat IS NULL';
469  }
470  else if ($params['cat_id']>0)
471  {
472    $where[] = 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.
473      (int)($params['cat_id'])
474      .'(,|$)\'';
475  }
476
477  if ($params['public'])
478  {
479    $where[] = 'status = "public"';
480    $where[] = 'visible = "true"';
481
482    $join_user = $conf['guest_id'];
483  }
484  elseif (is_admin())
485  {
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
489    //
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';
494  }
495
496  $query = '
497SELECT id, name, permalink, uppercats, global_rank, id_uppercat,
498    comment,
499    nb_images, count_images AS total_nb_images,
500    representative_picture_id, user_representative_picture_id, count_images, count_categories,
501    date_last, max_date_last, count_categories AS nb_categories
502  FROM '.CATEGORIES_TABLE.'
503   '.$join_type.' JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id AND user_id='.$join_user.'
504  WHERE '. implode('
505    AND ', $where);
506
507  $result = pwg_query($query);
508
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 
515  $cats = array();
516  while ($row = pwg_db_fetch_assoc($result))
517  {
518    $row['url'] = make_index_url(
519        array(
520          'category' => $row
521          )
522      );
523    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
524    {
525      $row[$key] = (int)$row[$key];
526    }
527
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    }
542
543    $row['comment'] = strip_tags(
544      trigger_event(
545        'render_category_description',
546        $row['comment'],
547        'ws_categories_getList'
548        )
549      );
550
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
619    array_push($cats, $row);
620  }
621  usort($cats, 'global_rank_compare');
622
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 = '
630SELECT id, path, representative_ext, level
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      {
639        $thumbnail_src_of[$row['id']] = DerivativeImage::thumb_url($row);
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 = '
678SELECT id, path, representative_ext
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      {
685        $thumbnail_src_of[$row['id']] = DerivativeImage::thumb_url($row);
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']);
733    unset($cat['count_categories']);
734  }
735  unset($cat); 
736  // management of the album thumbnail -- stops here
737
738  if ($params['tree_output'])
739  {
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          )
757        )
758      );
759  }
760}
761
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  }
775
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,
789    comment,
790    uppercats,
791    global_rank
792  FROM '.CATEGORIES_TABLE.'
793;';
794  $result = pwg_query($query);
795  $cats = array();
796
797  while ($row = pwg_db_fetch_assoc($result))
798  {
799    $id = $row['id'];
800    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
801    $row['name'] = strip_tags(
802      trigger_event(
803        'render_category_name',
804        $row['name'],
805        'ws_categories_getAdminList'
806        )
807      );
808    $row['comment'] = strip_tags(
809      trigger_event(
810        'render_category_description',
811        $row['comment'],
812        'ws_categories_getAdminList'
813        )
814      );
815    array_push($cats, $row);
816  }
817
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
834/**
835 * returns detailed information for an element (web service method)
836 */
837function ws_images_addComment($params, &$service)
838{
839  if (!$service->isPost())
840  {
841    return new PwgError(405, "This method requires HTTP POST");
842  }
843  $params['image_id'] = (int)$params['image_id'];
844  $query = '
845SELECT DISTINCT image_id
846  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
847  WHERE commentable="true"
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    );
857  if ( !pwg_db_num_rows( pwg_query( $query ) ) )
858  {
859    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
860  }
861
862  $comm = array(
863    'author' => trim( $params['author'] ),
864    'content' => trim( $params['content'] ),
865    'image_id' => $params['image_id'],
866   );
867
868  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
869
870  $comment_action = insert_user_comment(
871      $comm, $params['key'], $infos
872    );
873
874  switch ($comment_action)
875  {
876    case 'reject':
877      array_push($infos, l10n('Your comment has NOT been registered because it did not pass the validation rules') );
878      return new PwgError(403, implode("; ", $infos) );
879    case 'validate':
880    case 'moderate':
881      $ret = array(
882          'id' => $comm['id'],
883          'validation' => $comment_action=='validate',
884        );
885      return new PwgNamedStruct(
886          'comment',
887          $ret,
888          null, array()
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 */
898function ws_images_getInfo($params, &$service)
899{
900  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
901  global $user, $conf;
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  }
907
908  $query='
909SELECT * FROM '.IMAGES_TABLE.'
910  WHERE id='.$params['image_id'].
911    get_sql_condition_FandF(
912      array('visible_images' => 'id'),
913      ' AND'
914    ).'
915LIMIT 1';
916
917  $image_row = pwg_db_fetch_assoc(pwg_query($query));
918  if ($image_row==null)
919  {
920    return new PwgError(404, "image_id not found");
921  }
922  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
923
924  //-------------------------------------------------------- related categories
925  $query = '
926SELECT id, name, permalink, uppercats, global_rank, commentable
927  FROM '.IMAGE_CATEGORY_TABLE.'
928    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
929  WHERE image_id = '.$image_row['id'].
930  get_sql_condition_FandF(
931      array( 'forbidden_categories' => 'category_id' ),
932      ' AND'
933    ).'
934;';
935  $result = pwg_query($query);
936  $is_commentable = false;
937  $related_categories = array();
938  while ($row = pwg_db_fetch_assoc($result))
939  {
940    if ($row['commentable']=='true')
941    {
942      $is_commentable = true;
943    }
944    unset($row['commentable']);
945    $row['url'] = make_index_url(
946        array(
947          'category' => $row
948          )
949      );
950
951    $row['page_url'] = make_picture_url(
952        array(
953          'image_id' => $image_row['id'],
954          'image_file' => $image_row['file'],
955          'category' => $row
956          )
957      );
958    $row['id']=(int)$row['id'];
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
968  $related_tags = get_common_tags( array($image_row['id']), -1 );
969  foreach( $related_tags as $i=>$tag)
970  {
971    $tag['url'] = make_index_url(
972        array(
973          'tags' => array($tag)
974          )
975      );
976    $tag['page_url'] = make_picture_url(
977        array(
978          'image_id' => $image_row['id'],
979          'image_file' => $image_row['file'],
980          'tags' => array($tag),
981          )
982      );
983    unset($tag['counter']);
984    $tag['id']=(int)$tag['id'];
985    $related_tags[$i]=$tag;
986  }
987  //------------------------------------------------------------- related rates
988        $rating = array('score'=>$image_row['rating_score'], 'count'=>0, 'average'=>null);
989        if (isset($rating['score']))
990        {
991                $query = '
992SELECT COUNT(rate) AS count
993     , ROUND(AVG(rate),2) AS average
994  FROM '.RATE_TABLE.'
995  WHERE element_id = '.$image_row['id'].'
996;';
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        }
1002
1003  //---------------------------------------------------------- related comments
1004  $related_comments = array();
1005
1006  $where_comments = 'image_id = '.$image_row['id'];
1007  if ( !is_admin() )
1008  {
1009    $where_comments .= '
1010    AND validated="true"';
1011  }
1012
1013  $query = '
1014SELECT COUNT(id) AS nb_comments
1015  FROM '.COMMENTS_TABLE.'
1016  WHERE '.$where_comments;
1017  list($nb_comments) = array_from_query($query, 'nb_comments');
1018  $nb_comments = (int)$nb_comments;
1019
1020  if ( $nb_comments>0 and $params['comments_per_page']>0 )
1021  {
1022    $query = '
1023SELECT id, date, author, content
1024  FROM '.COMMENTS_TABLE.'
1025  WHERE '.$where_comments.'
1026  ORDER BY date
1027  LIMIT '.(int)$params['comments_per_page'].
1028    ' OFFSET '.(int)($params['comments_per_page']*$params['comments_page']);
1029
1030    $result = pwg_query($query);
1031    while ($row = pwg_db_fetch_assoc($result))
1032    {
1033      $row['id']=(int)$row['id'];
1034      array_push($related_comments, $row);
1035    }
1036  }
1037
1038  $comment_post_data = null;
1039  if ($is_commentable and
1040      (!is_a_guest()
1041        or (is_a_guest() and $conf['comments_forall'] )
1042      )
1043      )
1044  {
1045    $comment_post_data['author'] = stripslashes($user['username']);
1046    $comment_post_data['key'] = get_ephemeral_key(2, $params['image_id']);
1047  }
1048
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  }
1061
1062  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
1063  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
1064  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
1065  if ( isset($comment_post_data) )
1066  {
1067    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
1068  }
1069  $ret['comments'] = array(
1070     WS_XML_ATTRIBUTES =>
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') )
1078      );
1079
1080  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
1081}
1082
1083
1084/**
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';
1102  if ( pwg_db_num_rows( pwg_query($query) )==0 )
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/**
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');
1127
1128  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
1129  $order_by = ws_std_image_sql_order($params, 'i.');
1130
1131  $super_order_by = false;
1132  if ( !empty($order_by) )
1133  {
1134    global $conf;
1135    $conf['order_by'] = 'ORDER BY '.$order_by;
1136    $super_order_by=true; // quick_search_result might be faster
1137  }
1138
1139  $search_result = get_quick_search_results($params['query'],
1140      $super_order_by,
1141      implode(',', $where_clauses)
1142    );
1143
1144  $image_ids = array_slice(
1145      $search_result['items'],
1146      $params['page']*$params['per_page'],
1147      $params['per_page']
1148    );
1149
1150  if ( count($image_ids) )
1151  {
1152    $query = '
1153SELECT * FROM '.IMAGES_TABLE.'
1154  WHERE id IN ('.implode(',', $image_ids).')';
1155
1156    $image_ids = array_flip($image_ids);
1157    $result = pwg_query($query);
1158    while ($row = pwg_db_fetch_assoc($result))
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      }
1168      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
1169      {
1170        $image[$k] = $row[$k];
1171      }
1172      $image = array_merge( $image, ws_std_get_urls($row) );
1173      $images[$image_ids[$image['id']]] = $image;
1174    }
1175    ksort($images, SORT_NUMERIC);
1176    $images = array_values($images);
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',
1189          ws_std_get_image_xml_attributes() )
1190      )
1191    );
1192}
1193
1194function ws_images_setPrivacyLevel($params, &$service)
1195{
1196  if (!is_admin())
1197  {
1198    return new PwgError(401, 'Access denied');
1199  }
1200  if (!$service->isPost())
1201  {
1202    return new PwgError(405, "This method requires HTTP POST");
1203  }
1204  $params['image_id'] = array_map( 'intval',$params['image_id'] );
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  }
1214
1215  $query = '
1216UPDATE '.IMAGES_TABLE.'
1217  SET level='.(int)$params['level'].'
1218  WHERE id IN ('.implode(',',$params['image_id']).')';
1219  $result = pwg_query($query);
1220  $affected_rows = pwg_db_changes($result);
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
1229function ws_images_setRank($params, &$service)
1230{
1231  if (!is_admin())
1232  {
1233    return new PwgError(401, 'Access denied');
1234  }
1235
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  }
1261
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  }
1275
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
1341function ws_images_add_chunk($params, &$service)
1342{
1343  global $conf;
1344
1345  ws_logfile('[ws_images_add_chunk] welcome');
1346  // data
1347  // original_sum
1348  // type {thumb, file, high}
1349  // position
1350
1351  if (!is_admin())
1352  {
1353    return new PwgError(401, 'Access denied');
1354  }
1355
1356  if (!$service->isPost())
1357  {
1358    return new PwgError(405, "This method requires HTTP POST");
1359  }
1360
1361  foreach ($params as $param_key => $param_value) {
1362    if ('data' == $param_key) {
1363      continue;
1364    }
1365
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
1375  $upload_dir = $conf['upload_dir'].'/buffer';
1376
1377  // create the upload directory tree if not exists
1378  if (!is_dir($upload_dir)) {
1379    umask(0000);
1380    if (!@mkdir($upload_dir, 0777, true))
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
1406  ws_logfile('[ws_images_add_chunk] data length : '.strlen($params['data']));
1407
1408  $bytes_written = file_put_contents(
1409    $upload_dir.'/'.$filename,
1410    base64_decode($params['data'])
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{
1423  global $conf;
1424
1425  ws_logfile('[merge_chunks] input parameter $output_filepath : '.$output_filepath);
1426
1427  if (is_file($output_filepath))
1428  {
1429    unlink($output_filepath);
1430
1431    if (is_file($output_filepath))
1432    {
1433      return new PwgError(500, '[merge_chunks] error while trying to remove existing '.$output_filepath);
1434    }
1435  }
1436
1437  $upload_dir = $conf['upload_dir'].'/buffer';
1438  $pattern = '/'.$original_sum.'-'.$type.'/';
1439  $chunks = array();
1440
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);
1455
1456  if (function_exists('memory_get_usage')) {
1457    ws_logfile('[merge_chunks] memory_get_usage before loading chunks: '.memory_get_usage());
1458  }
1459
1460  $i = 0;
1461
1462  foreach ($chunks as $chunk)
1463  {
1464    $string = file_get_contents($chunk);
1465
1466    if (function_exists('memory_get_usage')) {
1467      ws_logfile('[merge_chunks] memory_get_usage on chunk '.++$i.': '.memory_get_usage());
1468    }
1469
1470    if (!file_put_contents($output_filepath, $string, FILE_APPEND))
1471    {
1472      return new PwgError(500, '[merge_chunks] error while writting chunks for '.$output_filepath);
1473    }
1474
1475    unlink($chunk);
1476  }
1477
1478  if (function_exists('memory_get_usage')) {
1479    ws_logfile('[merge_chunks] memory_get_usage after loading chunks: '.memory_get_usage());
1480  }
1481}
1482
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{
1489  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
1490
1491  $file_path = file_path_for_type($file_path, $type);
1492
1493  $upload_dir = dirname($file_path);
1494  if (substr(PHP_OS, 0, 3) == 'WIN')
1495  {
1496    $upload_dir = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir);
1497  }
1498
1499  ws_logfile('[add_file] file_path  : '.$file_path);
1500  ws_logfile('[add_file] upload_dir : '.$upload_dir);
1501
1502  if (!is_dir($upload_dir)) {
1503    umask(0000);
1504    $recursive = true;
1505    if (!@mkdir($upload_dir, 0777, $recursive))
1506    {
1507      return new PwgError(500, '[add_file] error during '.$type.' directory creation');
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    {
1518      return new PwgError(500, '[add_file] '.$type.' directory has no write access');
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);
1530  if ($dumped_md5 != $file_sum) 
1531  {
1532    return new PwgError(500, '[add_file] '.$type.' transfer failed');
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
1545function ws_images_addFile($params, &$service)
1546{
1547  // image_id
1548  // type {thumb, file, high}
1549  // sum
1550
1551  global $conf;
1552  if (!is_admin())
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;';
1573  list($file_path, $original_sum) = pwg_db_fetch_row(pwg_query($query));
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();
1586
1587  if ('high' == $params['type'])
1588  {
1589    $update['high_filesize'] = $infos['filesize'];
1590    $update['high_width'] = $infos['width'];
1591    $update['high_height'] = $infos['height'];
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'];
1607
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
1620function ws_images_add($params, &$service)
1621{
1622  global $conf, $user;
1623  if (!is_admin())
1624  {
1625    return new PwgError(401, 'Access denied');
1626  }
1627
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  }
1637
1638  // does the image already exists ?
1639  if ($params['check_uniqueness'])
1640  {
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    }
1649
1650    $query = '
1651SELECT
1652    COUNT(*) AS counter
1653  FROM '.IMAGES_TABLE.'
1654  WHERE '.$where_clause.'
1655;';
1656    list($counter) = pwg_db_fetch_row(pwg_query($query));
1657    if ($counter != 0) {
1658      return new PwgError(500, 'file already exists');
1659    }
1660  }
1661
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);
1672
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      );
1679
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);
1689
1690    // upload directory hierarchy
1691    $upload_dir = sprintf(
1692      $conf['upload_dir'].'/%s/%s/%s',
1693      $year,
1694      $month,
1695      $day
1696      );
1697
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    sync_metadata(array($image_id));
1745  }
1746
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    {
1759      $update[$key] = $params[$key];
1760    }
1761  }
1762 
1763  if (count(array_keys($update)) > 0)
1764  {
1765    single_update(
1766      IMAGES_TABLE,
1767      $update,
1768      array('id' => $image_id)
1769      );
1770  }
1771
1772  $url_params = array('image_id' => $image_id);
1773 
1774  // let's add links between the image and the categories
1775  if (isset($params['categories']))
1776  {
1777    ws_add_image_category_relations($image_id, $params['categories']);
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    }
1793  }
1794
1795  // and now, let's create tag associations
1796  if (isset($params['tag_ids']) and !empty($params['tag_ids']))
1797  {
1798    set_tags(
1799      explode(',', $params['tag_ids']),
1800      $image_id
1801      );
1802  }
1803
1804  invalidate_user_cache();
1805
1806  return array(
1807    'image_id' => $image_id,
1808    'url' => make_picture_url($url_params),
1809    );
1810}
1811
1812function ws_images_addSimple($params, &$service)
1813{
1814  global $conf;
1815  if (!is_admin())
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  }
1824
1825  if (!isset($_FILES['image']))
1826  {
1827    return new PwgError(405, "The image (file) parameter is missing");
1828  }
1829
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');
1834
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
1848  // category
1849  $params['category'] = (int)$params['category'];
1850  if ($params['category'] <= 0 and $params['image_id'] <= 0)
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'],
1860    $params['category'] > 0 ? array($params['category']) : null,
1861    8,
1862    $params['image_id'] > 0 ? $params['image_id'] : null
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
1910  $url_params = array('image_id' => $image_id);
1911
1912  if ($params['category'] > 0)
1913  {
1914    $query = '
1915SELECT id, name, permalink
1916  FROM '.CATEGORIES_TABLE.'
1917  WHERE id = '.$params['category'].'
1918;';
1919    $result = pwg_query($query);
1920    $category = pwg_db_fetch_assoc($result);
1921
1922    $url_params['section'] = 'categories';
1923    $url_params['category'] = $category;
1924  }
1925
1926  // update metadata from the uploaded file (exif/iptc), even if the sync
1927  // was already performed by add_uploaded_file().
1928
1929  require_once(PHPWG_ROOT_PATH.'admin/include/functions_metadata.php');
1930  sync_metadata(array($image_id));
1931
1932  return array(
1933    'image_id' => $image_id,
1934    'url' => make_picture_url($url_params),
1935    );
1936}
1937
1938function ws_rates_delete($params, &$service)
1939{
1940  global $conf;
1941
1942  if (!$service->isPost())
1943  {
1944    return new PwgError(405, 'This method requires HTTP POST');
1945  }
1946
1947  if (!is_admin())
1948  {
1949    return new PwgError(401, 'Access denied');
1950  }
1951
1952  $user_id = (int)$params['user_id'];
1953  if ($user_id<=0)
1954  {
1955    return new PwgError(WS_ERR_INVALID_PARAM, 'Invalid user_id');
1956  }
1957 
1958  $query = '
1959DELETE FROM '.RATE_TABLE.'
1960  WHERE user_id='.$user_id;
1961 
1962  if (!empty($params['anonymous_id']))
1963  {
1964    $query .= ' AND anonymous_id=\''.$params['anonymous_id'].'\'';
1965  }
1966 
1967  $changes = pwg_db_changes(pwg_query($query));
1968  if ($changes)
1969  {
1970    include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
1971    update_rating_score();
1972  }
1973  return $changes;
1974}
1975
1976
1977/**
1978 * perform a login (web service method)
1979 */
1980function ws_session_login($params, &$service)
1981{
1982  global $conf;
1983
1984  if (!$service->isPost())
1985  {
1986    return new PwgError(405, "This method requires HTTP POST");
1987  }
1988  if (try_log_user($params['username'], $params['password'],false))
1989  {
1990    return true;
1991  }
1992  return new PwgError(999, 'Invalid username/password');
1993}
1994
1995
1996/**
1997 * performs a logout (web service method)
1998 */
1999function ws_session_logout($params, &$service)
2000{
2001  if (!is_a_guest())
2002  {
2003    logout_user();
2004  }
2005  return true;
2006}
2007
2008function ws_session_getStatus($params, &$service)
2009{
2010  global $user;
2011  $res = array();
2012  $res['username'] = is_a_guest() ? 'guest' : stripslashes($user['username']);
2013  foreach ( array('status', 'theme', 'language') as $k )
2014  {
2015    $res[$k] = $user[$k];
2016  }
2017  $res['pwg_token'] = get_pwg_token();
2018  $res['charset'] = get_pwg_charset();
2019
2020  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2021  $res['current_datetime'] = $dbnow;
2022
2023  return $res;
2024}
2025
2026
2027/**
2028 * returns a list of tags (web service method)
2029 */
2030function ws_tags_getList($params, &$service)
2031{
2032  $tags = get_available_tags();
2033  if ($params['sort_by_counter'])
2034  {
2035    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
2036  }
2037  else
2038  {
2039    usort($tags, 'tag_alpha_compare');
2040  }
2041  for ($i=0; $i<count($tags); $i++)
2042  {
2043    $tags[$i]['id'] = (int)$tags[$i]['id'];
2044    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
2045    $tags[$i]['url'] = make_index_url(
2046        array(
2047          'section'=>'tags',
2048          'tags'=>array($tags[$i])
2049        )
2050      );
2051  }
2052  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
2053}
2054
2055/**
2056 * returns the list of tags as you can see them in administration (web
2057 * service method).
2058 *
2059 * Only admin can run this method and permissions are not taken into
2060 * account.
2061 */
2062function ws_tags_getAdminList($params, &$service)
2063{
2064  if (!is_admin())
2065  {
2066    return new PwgError(401, 'Access denied');
2067  }
2068
2069  $tags = get_all_tags();
2070  return array(
2071    'tags' => new PwgNamedArray(
2072      $tags,
2073      'tag',
2074      array(
2075        'name',
2076        'id',
2077        'url_name',
2078        )
2079      )
2080    );
2081}
2082
2083/**
2084 * returns a list of images for tags (web service method)
2085 */
2086function ws_tags_getImages($params, &$service)
2087{
2088  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
2089  global $conf;
2090
2091  // first build all the tag_ids we are interested in
2092  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
2093  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
2094  $tags_by_id = array();
2095  foreach( $tags as $tag )
2096  {
2097    $tags['id'] = (int)$tag['id'];
2098    $tags_by_id[ $tag['id'] ] = $tag;
2099  }
2100  unset($tags);
2101  $tag_ids = array_keys($tags_by_id);
2102
2103
2104  $where_clauses = ws_std_image_sql_filter($params);
2105  if (!empty($where_clauses))
2106  {
2107    $where_clauses = implode( ' AND ', $where_clauses);
2108  }
2109  $image_ids = get_image_ids_for_tags(
2110    $tag_ids,
2111    $params['tag_mode_and'] ? 'AND' : 'OR',
2112    $where_clauses,
2113    ws_std_image_sql_order($params) );
2114
2115
2116  $image_ids = array_slice($image_ids, (int)($params['per_page']*$params['page']), (int)$params['per_page'] );
2117
2118  $image_tag_map = array();
2119  if ( !empty($image_ids) and !$params['tag_mode_and'] )
2120  { // build list of image ids with associated tags per image
2121    $query = '
2122SELECT image_id, GROUP_CONCAT(tag_id) AS tag_ids
2123  FROM '.IMAGE_TAG_TABLE.'
2124  WHERE tag_id IN ('.implode(',',$tag_ids).') AND image_id IN ('.implode(',',$image_ids).')
2125  GROUP BY image_id';
2126    $result = pwg_query($query);
2127    while ( $row=pwg_db_fetch_assoc($result) )
2128    {
2129      $row['image_id'] = (int)$row['image_id'];
2130      array_push( $image_ids, $row['image_id'] );
2131      $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
2132    }
2133  }
2134
2135  $images = array();
2136  if (!empty($image_ids))
2137  {
2138    $rank_of = array_flip($image_ids);
2139    $result = pwg_query('
2140SELECT * FROM '.IMAGES_TABLE.'
2141  WHERE id IN ('.implode(',',$image_ids).')');
2142    while ($row = pwg_db_fetch_assoc($result))
2143    {
2144      $image = array();
2145      $image['rank'] = $rank_of[ $row['id'] ];
2146      foreach ( array('id', 'width', 'height', 'hit') as $k )
2147      {
2148        if (isset($row[$k]))
2149        {
2150          $image[$k] = (int)$row[$k];
2151        }
2152      }
2153      foreach ( array('file', 'name', 'comment', 'date_creation', 'date_available') as $k )
2154      {
2155        $image[$k] = $row[$k];
2156      }
2157      $image = array_merge( $image, ws_std_get_urls($row) );
2158
2159      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
2160      $image_tags = array();
2161      foreach ($image_tag_ids as $tag_id)
2162      {
2163        $url = make_index_url(
2164                 array(
2165                  'section'=>'tags',
2166                  'tags'=> array($tags_by_id[$tag_id])
2167                )
2168              );
2169        $page_url = make_picture_url(
2170                 array(
2171                  'section'=>'tags',
2172                  'tags'=> array($tags_by_id[$tag_id]),
2173                  'image_id' => $row['id'],
2174                  'image_file' => $row['file'],
2175                )
2176              );
2177        array_push($image_tags, array(
2178                'id' => (int)$tag_id,
2179                'url' => $url,
2180                'page_url' => $page_url,
2181              )
2182            );
2183      }
2184      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
2185              array('id','url_name','url','page_url')
2186            );
2187      array_push($images, $image);
2188    }
2189    usort($images, 'rank_compare');
2190    unset($rank_of);
2191  }
2192
2193  return array( 'images' =>
2194    array (
2195      WS_XML_ATTRIBUTES =>
2196        array(
2197            'page' => $params['page'],
2198            'per_page' => $params['per_page'],
2199            'count' => count($images)
2200          ),
2201       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
2202          ws_std_get_image_xml_attributes() )
2203      )
2204    );
2205}
2206
2207function ws_categories_add($params, &$service)
2208{
2209  if (!is_admin())
2210  {
2211    return new PwgError(401, 'Access denied');
2212  }
2213
2214  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2215
2216  $creation_output = create_virtual_category(
2217    $params['name'],
2218    $params['parent']
2219    );
2220
2221  if (isset($creation_output['error']))
2222  {
2223    return new PwgError(500, $creation_output['error']);
2224  }
2225
2226  invalidate_user_cache();
2227
2228  return $creation_output;
2229}
2230
2231function ws_tags_add($params, &$service)
2232{
2233  if (!is_admin())
2234  {
2235    return new PwgError(401, 'Access denied');
2236  }
2237
2238  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2239
2240  $creation_output = create_tag($params['name']);
2241
2242  if (isset($creation_output['error']))
2243  {
2244    return new PwgError(500, $creation_output['error']);
2245  }
2246
2247  return $creation_output;
2248}
2249
2250function ws_images_exist($params, &$service)
2251{
2252  global $conf;
2253
2254  if (!is_admin())
2255  {
2256    return new PwgError(401, 'Access denied');
2257  }
2258
2259  $split_pattern = '/[\s,;\|]/';
2260
2261  if ('md5sum' == $conf['uniqueness_mode'])
2262  {
2263    // search among photos the list of photos already added, based on md5sum
2264    // list
2265    $md5sums = preg_split(
2266      $split_pattern,
2267      $params['md5sum_list'],
2268      -1,
2269      PREG_SPLIT_NO_EMPTY
2270    );
2271
2272    $query = '
2273SELECT
2274    id,
2275    md5sum
2276  FROM '.IMAGES_TABLE.'
2277  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
2278;';
2279    $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
2280
2281    $result = array();
2282
2283    foreach ($md5sums as $md5sum)
2284    {
2285      $result[$md5sum] = null;
2286      if (isset($id_of_md5[$md5sum]))
2287      {
2288        $result[$md5sum] = $id_of_md5[$md5sum];
2289      }
2290    }
2291  }
2292
2293  if ('filename' == $conf['uniqueness_mode'])
2294  {
2295    // search among photos the list of photos already added, based on
2296    // filename list
2297    $filenames = preg_split(
2298      $split_pattern,
2299      $params['filename_list'],
2300      -1,
2301      PREG_SPLIT_NO_EMPTY
2302    );
2303
2304    $query = '
2305SELECT
2306    id,
2307    file
2308  FROM '.IMAGES_TABLE.'
2309  WHERE file IN (\''.implode("','", $filenames).'\')
2310;';
2311    $id_of_filename = simple_hash_from_query($query, 'file', 'id');
2312
2313    $result = array();
2314
2315    foreach ($filenames as $filename)
2316    {
2317      $result[$filename] = null;
2318      if (isset($id_of_filename[$filename]))
2319      {
2320        $result[$filename] = $id_of_filename[$filename];
2321      }
2322    }
2323  }
2324
2325  return $result;
2326}
2327
2328function ws_images_checkFiles($params, &$service)
2329{
2330  if (!is_admin())
2331  {
2332    return new PwgError(401, 'Access denied');
2333  }
2334
2335  // input parameters
2336  //
2337  // image_id
2338  // thumbnail_sum
2339  // file_sum
2340  // high_sum
2341
2342  $params['image_id'] = (int)$params['image_id'];
2343  if ($params['image_id'] <= 0)
2344  {
2345    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2346  }
2347
2348  $query = '
2349SELECT
2350    path
2351  FROM '.IMAGES_TABLE.'
2352  WHERE id = '.$params['image_id'].'
2353;';
2354  $result = pwg_query($query);
2355  if (pwg_db_num_rows($result) == 0) {
2356    return new PwgError(404, "image_id not found");
2357  }
2358  list($path) = pwg_db_fetch_row($result);
2359
2360  $ret = array();
2361
2362  foreach (array('thumb', 'file', 'high') as $type) {
2363    $param_name = $type;
2364    if ('thumb' == $type) {
2365      $param_name = 'thumbnail';
2366    }
2367
2368    if (isset($params[$param_name.'_sum'])) {
2369      include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
2370      $type_path = file_path_for_type($path, $type);
2371      if (!is_file($type_path)) {
2372        $ret[$param_name] = 'missing';
2373      }
2374      else {
2375        if (md5_file($type_path) != $params[$param_name.'_sum']) {
2376          $ret[$param_name] = 'differs';
2377        }
2378        else {
2379          $ret[$param_name] = 'equals';
2380        }
2381      }
2382    }
2383  }
2384
2385  return $ret;
2386}
2387
2388function ws_images_setInfo($params, &$service)
2389{
2390  global $conf;
2391  if (!is_admin())
2392  {
2393    return new PwgError(401, 'Access denied');
2394  }
2395
2396  if (!$service->isPost())
2397  {
2398    return new PwgError(405, "This method requires HTTP POST");
2399  }
2400
2401  $params['image_id'] = (int)$params['image_id'];
2402  if ($params['image_id'] <= 0)
2403  {
2404    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2405  }
2406
2407  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2408
2409  $query='
2410SELECT *
2411  FROM '.IMAGES_TABLE.'
2412  WHERE id = '.$params['image_id'].'
2413;';
2414
2415  $image_row = pwg_db_fetch_assoc(pwg_query($query));
2416  if ($image_row == null)
2417  {
2418    return new PwgError(404, "image_id not found");
2419  }
2420
2421  // database registration
2422  $update = array();
2423
2424  $info_columns = array(
2425    'name',
2426    'author',
2427    'comment',
2428    'level',
2429    'date_creation',
2430    );
2431
2432  foreach ($info_columns as $key)
2433  {
2434    if (isset($params[$key]))
2435    {
2436      if ('fill_if_empty' == $params['single_value_mode'])
2437      {
2438        if (empty($image_row[$key]))
2439        {
2440          $update[$key] = $params[$key];
2441        }
2442      }
2443      elseif ('replace' == $params['single_value_mode'])
2444      {
2445        $update[$key] = $params[$key];
2446      }
2447      else
2448      {
2449        return new PwgError(
2450          500,
2451          '[ws_images_setInfo]'
2452          .' invalid parameter single_value_mode "'.$params['single_value_mode'].'"'
2453          .', possible values are {fill_if_empty, replace}.'
2454          );
2455      }
2456    }
2457  }
2458
2459  if (isset($params['file']))
2460  {
2461    if (!empty($image_row['storage_category_id']))
2462    {
2463      return new PwgError(500, '[ws_images_setInfo] updating "file" is forbidden on photos added by synchronization');
2464    }
2465
2466    $update['file'] = $params['file'];
2467  }
2468
2469  if (count(array_keys($update)) > 0)
2470  {
2471    $update['id'] = $params['image_id'];
2472
2473    mass_updates(
2474      IMAGES_TABLE,
2475      array(
2476        'primary' => array('id'),
2477        'update'  => array_diff(array_keys($update), array('id'))
2478        ),
2479      array($update)
2480      );
2481  }
2482
2483  if (isset($params['categories']))
2484  {
2485    ws_add_image_category_relations(
2486      $params['image_id'],
2487      $params['categories'],
2488      ('replace' == $params['multiple_value_mode'] ? true : false)
2489      );
2490  }
2491
2492  // and now, let's create tag associations
2493  if (isset($params['tag_ids']))
2494  {
2495    $tag_ids = explode(',', $params['tag_ids']);
2496
2497    if ('replace' == $params['multiple_value_mode'])
2498    {
2499      set_tags(
2500        $tag_ids,
2501        $params['image_id']
2502        );
2503    }
2504    elseif ('append' == $params['multiple_value_mode'])
2505    {
2506      add_tags(
2507        $tag_ids,
2508        array($params['image_id'])
2509        );
2510    }
2511    else
2512    {
2513      return new PwgError(
2514        500,
2515        '[ws_images_setInfo]'
2516        .' invalid parameter multiple_value_mode "'.$params['multiple_value_mode'].'"'
2517        .', possible values are {replace, append}.'
2518        );
2519    }
2520  }
2521
2522  invalidate_user_cache();
2523}
2524
2525function ws_images_delete($params, &$service)
2526{
2527  global $conf;
2528  if (!is_admin())
2529  {
2530    return new PwgError(401, 'Access denied');
2531  }
2532
2533  if (!$service->isPost())
2534  {
2535    return new PwgError(405, "This method requires HTTP POST");
2536  }
2537
2538  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2539  {
2540    return new PwgError(403, 'Invalid security token');
2541  }
2542
2543  $params['image_id'] = preg_split(
2544    '/[\s,;\|]/',
2545    $params['image_id'],
2546    -1,
2547    PREG_SPLIT_NO_EMPTY
2548    );
2549  $params['image_id'] = array_map('intval', $params['image_id']);
2550
2551  $image_ids = array();
2552  foreach ($params['image_id'] as $image_id)
2553  {
2554    if ($image_id > 0)
2555    {
2556      array_push($image_ids, $image_id);
2557    }
2558  }
2559
2560  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2561  delete_elements($image_ids, true);
2562}
2563
2564function ws_add_image_category_relations($image_id, $categories_string, $replace_mode=false)
2565{
2566  // let's add links between the image and the categories
2567  //
2568  // $params['categories'] should look like 123,12;456,auto;789 which means:
2569  //
2570  // 1. associate with category 123 on rank 12
2571  // 2. associate with category 456 on automatic rank
2572  // 3. associate with category 789 on automatic rank
2573  $cat_ids = array();
2574  $rank_on_category = array();
2575  $search_current_ranks = false;
2576
2577  $tokens = explode(';', $categories_string);
2578  foreach ($tokens as $token)
2579  {
2580    @list($cat_id, $rank) = explode(',', $token);
2581
2582    if (!preg_match('/^\d+$/', $cat_id))
2583    {
2584      continue;
2585    }
2586
2587    array_push($cat_ids, $cat_id);
2588
2589    if (!isset($rank))
2590    {
2591      $rank = 'auto';
2592    }
2593    $rank_on_category[$cat_id] = $rank;
2594
2595    if ($rank == 'auto')
2596    {
2597      $search_current_ranks = true;
2598    }
2599  }
2600
2601  $cat_ids = array_unique($cat_ids);
2602
2603  if (count($cat_ids) == 0)
2604  {
2605    return new PwgError(
2606      500,
2607      '[ws_add_image_category_relations] there is no category defined in "'.$categories_string.'"'
2608      );
2609  }
2610
2611  $query = '
2612SELECT
2613    id
2614  FROM '.CATEGORIES_TABLE.'
2615  WHERE id IN ('.implode(',', $cat_ids).')
2616;';
2617  $db_cat_ids = array_from_query($query, 'id');
2618
2619  $unknown_cat_ids = array_diff($cat_ids, $db_cat_ids);
2620  if (count($unknown_cat_ids) != 0)
2621  {
2622    return new PwgError(
2623      500,
2624      '[ws_add_image_category_relations] the following categories are unknown: '.implode(', ', $unknown_cat_ids)
2625      );
2626  }
2627
2628  $to_update_cat_ids = array();
2629
2630  // in case of replace mode, we first check the existing associations
2631  $query = '
2632SELECT
2633    category_id
2634  FROM '.IMAGE_CATEGORY_TABLE.'
2635  WHERE image_id = '.$image_id.'
2636;';
2637  $existing_cat_ids = array_from_query($query, 'category_id');
2638
2639  if ($replace_mode)
2640  {
2641    $to_remove_cat_ids = array_diff($existing_cat_ids, $cat_ids);
2642    if (count($to_remove_cat_ids) > 0)
2643    {
2644      $query = '
2645DELETE
2646  FROM '.IMAGE_CATEGORY_TABLE.'
2647  WHERE image_id = '.$image_id.'
2648    AND category_id IN ('.implode(', ', $to_remove_cat_ids).')
2649;';
2650      pwg_query($query);
2651      update_category($to_remove_cat_ids);
2652    }
2653  }
2654
2655  $new_cat_ids = array_diff($cat_ids, $existing_cat_ids);
2656  if (count($new_cat_ids) == 0)
2657  {
2658    return true;
2659  }
2660
2661  if ($search_current_ranks)
2662  {
2663    $query = '
2664SELECT
2665    category_id,
2666    MAX(rank) AS max_rank
2667  FROM '.IMAGE_CATEGORY_TABLE.'
2668  WHERE rank IS NOT NULL
2669    AND category_id IN ('.implode(',', $new_cat_ids).')
2670  GROUP BY category_id
2671;';
2672    $current_rank_of = simple_hash_from_query(
2673      $query,
2674      'category_id',
2675      'max_rank'
2676      );
2677
2678    foreach ($new_cat_ids as $cat_id)
2679    {
2680      if (!isset($current_rank_of[$cat_id]))
2681      {
2682        $current_rank_of[$cat_id] = 0;
2683      }
2684
2685      if ('auto' == $rank_on_category[$cat_id])
2686      {
2687        $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
2688      }
2689    }
2690  }
2691
2692  $inserts = array();
2693
2694  foreach ($new_cat_ids as $cat_id)
2695  {
2696    array_push(
2697      $inserts,
2698      array(
2699        'image_id' => $image_id,
2700        'category_id' => $cat_id,
2701        'rank' => $rank_on_category[$cat_id],
2702        )
2703      );
2704  }
2705
2706  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2707  mass_inserts(
2708    IMAGE_CATEGORY_TABLE,
2709    array_keys($inserts[0]),
2710    $inserts
2711    );
2712
2713  update_category($new_cat_ids);
2714}
2715
2716function ws_categories_setInfo($params, &$service)
2717{
2718  global $conf;
2719  if (!is_admin())
2720  {
2721    return new PwgError(401, 'Access denied');
2722  }
2723
2724  if (!$service->isPost())
2725  {
2726    return new PwgError(405, "This method requires HTTP POST");
2727  }
2728
2729  // category_id
2730  // name
2731  // comment
2732
2733  $params['category_id'] = (int)$params['category_id'];
2734  if ($params['category_id'] <= 0)
2735  {
2736    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2737  }
2738
2739  // database registration
2740  $update = array(
2741    'id' => $params['category_id'],
2742    );
2743
2744  $info_columns = array(
2745    'name',
2746    'comment',
2747    );
2748
2749  $perform_update = false;
2750  foreach ($info_columns as $key)
2751  {
2752    if (isset($params[$key]))
2753    {
2754      $perform_update = true;
2755      $update[$key] = $params[$key];
2756    }
2757  }
2758
2759  if ($perform_update)
2760  {
2761    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2762    mass_updates(
2763      CATEGORIES_TABLE,
2764      array(
2765        'primary' => array('id'),
2766        'update'  => array_diff(array_keys($update), array('id'))
2767        ),
2768      array($update)
2769      );
2770  }
2771
2772}
2773
2774function ws_categories_setRepresentative($params, &$service)
2775{
2776  global $conf;
2777
2778  if (!is_admin())
2779  {
2780    return new PwgError(401, 'Access denied');
2781  }
2782
2783  if (!$service->isPost())
2784  {
2785    return new PwgError(405, "This method requires HTTP POST");
2786  }
2787
2788  // category_id
2789  // image_id
2790
2791  $params['category_id'] = (int)$params['category_id'];
2792  if ($params['category_id'] <= 0)
2793  {
2794    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid category_id");
2795  }
2796
2797  // does the category really exist?
2798  $query='
2799SELECT
2800    *
2801  FROM '.CATEGORIES_TABLE.'
2802  WHERE id = '.$params['category_id'].'
2803;';
2804  $row = pwg_db_fetch_assoc(pwg_query($query));
2805  if ($row == null)
2806  {
2807    return new PwgError(404, "category_id not found");
2808  }
2809
2810  $params['image_id'] = (int)$params['image_id'];
2811  if ($params['image_id'] <= 0)
2812  {
2813    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
2814  }
2815
2816  // does the image really exist?
2817  $query='
2818SELECT
2819    *
2820  FROM '.IMAGES_TABLE.'
2821  WHERE id = '.$params['image_id'].'
2822;';
2823
2824  $row = pwg_db_fetch_assoc(pwg_query($query));
2825  if ($row == null)
2826  {
2827    return new PwgError(404, "image_id not found");
2828  }
2829
2830  // apply change
2831  $query = '
2832UPDATE '.CATEGORIES_TABLE.'
2833  SET representative_picture_id = '.$params['image_id'].'
2834  WHERE id = '.$params['category_id'].'
2835;';
2836  pwg_query($query);
2837
2838  $query = '
2839UPDATE '.USER_CACHE_CATEGORIES_TABLE.'
2840  SET user_representative_picture_id = NULL
2841  WHERE cat_id = '.$params['category_id'].'
2842;';
2843  pwg_query($query);
2844}
2845
2846function ws_categories_delete($params, &$service)
2847{
2848  global $conf;
2849  if (!is_admin())
2850  {
2851    return new PwgError(401, 'Access denied');
2852  }
2853
2854  if (!$service->isPost())
2855  {
2856    return new PwgError(405, "This method requires HTTP POST");
2857  }
2858
2859  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2860  {
2861    return new PwgError(403, 'Invalid security token');
2862  }
2863
2864  $modes = array('no_delete', 'delete_orphans', 'force_delete');
2865  if (!in_array($params['photo_deletion_mode'], $modes))
2866  {
2867    return new PwgError(
2868      500,
2869      '[ws_categories_delete]'
2870      .' invalid parameter photo_deletion_mode "'.$params['photo_deletion_mode'].'"'
2871      .', possible values are {'.implode(', ', $modes).'}.'
2872      );
2873  }
2874
2875  $params['category_id'] = preg_split(
2876    '/[\s,;\|]/',
2877    $params['category_id'],
2878    -1,
2879    PREG_SPLIT_NO_EMPTY
2880    );
2881  $params['category_id'] = array_map('intval', $params['category_id']);
2882
2883  $category_ids = array();
2884  foreach ($params['category_id'] as $category_id)
2885  {
2886    if ($category_id > 0)
2887    {
2888      array_push($category_ids, $category_id);
2889    }
2890  }
2891
2892  if (count($category_ids) == 0)
2893  {
2894    return;
2895  }
2896
2897  $query = '
2898SELECT id
2899  FROM '.CATEGORIES_TABLE.'
2900  WHERE id IN ('.implode(',', $category_ids).')
2901;';
2902  $category_ids = array_from_query($query, 'id');
2903
2904  if (count($category_ids) == 0)
2905  {
2906    return;
2907  }
2908
2909  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2910  delete_categories($category_ids, $params['photo_deletion_mode']);
2911  update_global_rank();
2912}
2913
2914function ws_categories_move($params, &$service)
2915{
2916  global $conf, $page;
2917
2918  if (!is_admin())
2919  {
2920    return new PwgError(401, 'Access denied');
2921  }
2922
2923  if (!$service->isPost())
2924  {
2925    return new PwgError(405, "This method requires HTTP POST");
2926  }
2927
2928  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
2929  {
2930    return new PwgError(403, 'Invalid security token');
2931  }
2932
2933  $params['category_id'] = preg_split(
2934    '/[\s,;\|]/',
2935    $params['category_id'],
2936    -1,
2937    PREG_SPLIT_NO_EMPTY
2938    );
2939  $params['category_id'] = array_map('intval', $params['category_id']);
2940
2941  $category_ids = array();
2942  foreach ($params['category_id'] as $category_id)
2943  {
2944    if ($category_id > 0)
2945    {
2946      array_push($category_ids, $category_id);
2947    }
2948  }
2949
2950  if (count($category_ids) == 0)
2951  {
2952    return new PwgError(403, 'Invalid category_id input parameter, no category to move');
2953  }
2954
2955  // we can't move physical categories
2956  $categories_in_db = array();
2957
2958  $query = '
2959SELECT
2960    id,
2961    name,
2962    dir
2963  FROM '.CATEGORIES_TABLE.'
2964  WHERE id IN ('.implode(',', $category_ids).')
2965;';
2966  $result = pwg_query($query);
2967  while ($row = pwg_db_fetch_assoc($result))
2968  {
2969    $categories_in_db[$row['id']] = $row;
2970    // we break on error at first physical category detected
2971    if (!empty($row['dir']))
2972    {
2973      $row['name'] = strip_tags(
2974        trigger_event(
2975          'render_category_name',
2976          $row['name'],
2977          'ws_categories_move'
2978          )
2979        );
2980
2981      return new PwgError(
2982        403,
2983        sprintf(
2984          'Category %s (%u) is not a virtual category, you cannot move it',
2985          $row['name'],
2986          $row['id']
2987          )
2988        );
2989    }
2990  }
2991
2992  if (count($categories_in_db) != count($category_ids))
2993  {
2994    $unknown_category_ids = array_diff($category_ids, array_keys($categories_in_db));
2995
2996    return new PwgError(
2997      403,
2998      sprintf(
2999        'Category %u does not exist',
3000        $unknown_category_ids[0]
3001        )
3002      );
3003  }
3004
3005  // does this parent exists? This check should be made in the
3006  // move_categories function, not here
3007  //
3008  // 0 as parent means "move categories at gallery root"
3009  if (!is_numeric($params['parent']))
3010  {
3011    return new PwgError(403, 'Invalid parent input parameter');
3012  }
3013
3014  if (0 != $params['parent']) {
3015    $params['parent'] = intval($params['parent']);
3016    $subcat_ids = get_subcat_ids(array($params['parent']));
3017    if (count($subcat_ids) == 0)
3018    {
3019      return new PwgError(403, 'Unknown parent category id');
3020    }
3021  }
3022
3023  $page['infos'] = array();
3024  $page['errors'] = array();
3025  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3026  move_categories($category_ids, $params['parent']);
3027  invalidate_user_cache();
3028
3029  if (count($page['errors']) != 0)
3030  {
3031    return new PwgError(403, implode('; ', $page['errors']));
3032  }
3033}
3034
3035function ws_logfile($string)
3036{
3037  global $conf;
3038
3039  if (!$conf['ws_enable_log']) {
3040    return true;
3041  }
3042
3043  file_put_contents(
3044    $conf['ws_log_filepath'],
3045    '['.date('c').'] '.$string."\n",
3046    FILE_APPEND
3047    );
3048}
3049
3050function ws_images_checkUpload($params, &$service)
3051{
3052  global $conf;
3053
3054  if (!is_admin())
3055  {
3056    return new PwgError(401, 'Access denied');
3057  }
3058
3059  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
3060  $ret['message'] = ready_for_upload_message();
3061  $ret['ready_for_upload'] = true;
3062
3063  if (!empty($ret['message']))
3064  {
3065    $ret['ready_for_upload'] = false;
3066  }
3067
3068  return $ret;
3069}
3070
3071function ws_plugins_getList($params, &$service)
3072{
3073  global $conf;
3074
3075  if (!is_admin())
3076  {
3077    return new PwgError(401, 'Access denied');
3078  }
3079
3080  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3081  $plugins = new plugins();
3082  $plugins->sort_fs_plugins('name');
3083  $plugin_list = array();
3084
3085  foreach($plugins->fs_plugins as $plugin_id => $fs_plugin)
3086  {
3087    if (isset($plugins->db_plugins_by_id[$plugin_id]))
3088    {
3089      $state = $plugins->db_plugins_by_id[$plugin_id]['state'];
3090    }
3091    else
3092    {
3093      $state = 'uninstalled';
3094    }
3095
3096    array_push(
3097      $plugin_list,
3098      array(
3099        'id' => $plugin_id,
3100        'name' => $fs_plugin['name'],
3101        'version' => $fs_plugin['version'],
3102        'state' => $state,
3103        'description' => $fs_plugin['description'],
3104        )
3105      );
3106  }
3107
3108  return $plugin_list;
3109}
3110
3111function ws_plugins_performAction($params, &$service)
3112{
3113  global $template;
3114
3115  if (!is_admin())
3116  {
3117    return new PwgError(401, 'Access denied');
3118  }
3119
3120  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3121  {
3122    return new PwgError(403, 'Invalid security token');
3123  }
3124
3125  define('IN_ADMIN', true);
3126  include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
3127  $plugins = new plugins();
3128  $errors = $plugins->perform_action($params['action'], $params['plugin']);
3129
3130
3131  if (!empty($errors))
3132  {
3133    return new PwgError(500, $errors);
3134  }
3135  else
3136  {
3137    if (in_array($params['action'], array('activate', 'deactivate')))
3138    {
3139      $template->delete_compiled_templates();
3140    }
3141    return true;
3142  }
3143}
3144
3145function ws_themes_performAction($params, &$service)
3146{
3147  global $template;
3148
3149  if (!is_admin())
3150  {
3151    return new PwgError(401, 'Access denied');
3152  }
3153
3154  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3155  {
3156    return new PwgError(403, 'Invalid security token');
3157  }
3158
3159  define('IN_ADMIN', true);
3160  include_once(PHPWG_ROOT_PATH.'admin/include/themes.class.php');
3161  $themes = new themes();
3162  $errors = $themes->perform_action($params['action'], $params['theme']);
3163
3164  if (!empty($errors))
3165  {
3166    return new PwgError(500, $errors);
3167  }
3168  else
3169  {
3170    if (in_array($params['action'], array('activate', 'deactivate')))
3171    {
3172      $template->delete_compiled_templates();
3173    }
3174    return true;
3175  }
3176}
3177
3178function ws_images_resizethumbnail($params, &$service)
3179{
3180  if (!is_admin())
3181  {
3182    return new PwgError(401, 'Access denied');
3183  }
3184
3185  if (empty($params['image_id']) and empty($params['image_path']))
3186  {
3187    return new PwgError(403, "image_id or image_path is missing");
3188  }
3189
3190  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
3191  include_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
3192
3193  if (!empty($params['image_id']))
3194  {
3195    $query='
3196SELECT id, path, tn_ext, has_high
3197  FROM '.IMAGES_TABLE.'
3198  WHERE id = '.(int)$params['image_id'].'
3199;';
3200    $image = pwg_db_fetch_assoc(pwg_query($query));
3201
3202    if ($image == null)
3203    {
3204      return new PwgError(403, "image_id not found");
3205    }
3206
3207    $image_path = $image['path'];
3208    $thumb_path = get_thumbnail_path($image);
3209  }
3210  else
3211  {
3212    $image_path = $params['image_path'];
3213    $thumb_path = file_path_for_type($image_path, 'thumb');
3214  }
3215
3216  if (!file_exists($image_path) or !is_valid_image_extension(get_extension($image_path)))
3217  {
3218    return new PwgError(403, "image can't be resized");
3219  }
3220
3221  $result = false;
3222  prepare_directory(dirname($thumb_path));
3223  $img = new pwg_image($image_path, $params['library']);
3224
3225  if (!is_bool($params['crop']))
3226    $params['crop'] = get_boolean($params['crop']);
3227  if (!is_bool($params['follow_orientation']))
3228    $params['follow_orientation'] = get_boolean($params['follow_orientation']);
3229
3230  $result =  $img->pwg_resize(
3231    $thumb_path,
3232    $params['maxwidth'],
3233    $params['maxheight'],
3234    $params['quality'],
3235    false, // automatic rotation is not needed for thumbnails.
3236    true, // strip metadata
3237    $params['crop'],
3238    $params['follow_orientation']
3239  );
3240
3241  $img->destroy();
3242  return $result;
3243}
3244
3245function ws_images_resizewebsize($params, &$service)
3246{
3247  if (!is_admin())
3248  {
3249    return new PwgError(401, 'Access denied');
3250  }
3251
3252  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
3253  include_once(PHPWG_ROOT_PATH.'admin/include/functions_upload.inc.php');
3254  include_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
3255
3256  $query='
3257SELECT id, path, tn_ext, has_high, width, height
3258  FROM '.IMAGES_TABLE.'
3259  WHERE id = '.(int)$params['image_id'].'
3260;';
3261  $image = pwg_db_fetch_assoc(pwg_query($query));
3262
3263  if ($image == null)
3264  {
3265    return new PwgError(403, "image_id not found");
3266  }
3267
3268  $image_path = $image['path'];
3269
3270  if (!is_valid_image_extension(get_extension($image_path)))
3271  {
3272    return new PwgError(403, "image can't be resized");
3273  }
3274 
3275  $hd_path = get_high_path($image);
3276
3277  if (empty($image['has_high']) or !file_exists($hd_path))
3278  {
3279    if ($image['width'] > $params['maxwidth'] or $image['height'] > $params['maxheight'])
3280    {
3281      $hd_path = file_path_for_type($image_path, 'high');
3282      $hd_dir = dirname($hd_path);
3283      prepare_directory($hd_dir);
3284     
3285      rename($image_path, $hd_path);
3286      $hd_infos = pwg_image_infos($hd_path);
3287
3288      single_update(
3289        IMAGES_TABLE,
3290        array(
3291          'has_high' => 'true',
3292          'high_filesize' => $hd_infos['filesize'],
3293          'high_width' => $hd_infos['width'],
3294          'high_height' => $hd_infos['height'],
3295          ),
3296        array(
3297          'id' => $image['id']
3298          )
3299        );
3300    }
3301    else
3302    {
3303      return new PwgError(403, "image can't be resized");
3304    }
3305  }
3306
3307  $result = false;
3308  $img = new pwg_image($hd_path, $params['library']);
3309
3310  $result = $img->pwg_resize(
3311    $image_path,
3312    $params['maxwidth'],
3313    $params['maxheight'],
3314    $params['quality'],
3315    $params['automatic_rotation'],
3316    false // strip metadata
3317    );
3318
3319  $img->destroy();
3320
3321  global $conf;
3322  $conf['use_exif'] = false;
3323  $conf['use_iptc'] = false;
3324  sync_metadata(array($image['id']));
3325
3326  return $result;
3327}
3328
3329function ws_extensions_update($params, &$service)
3330{
3331  if (!is_webmaster())
3332  {
3333    return new PwgError(401, l10n('Webmaster status is required.'));
3334  }
3335
3336  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3337  {
3338    return new PwgError(403, 'Invalid security token');
3339  }
3340
3341  if (empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3342  {
3343    return new PwgError(403, "invalid extension type");
3344  }
3345
3346  if (empty($params['id']) or empty($params['revision']))
3347  {
3348    return new PwgError(null, 'Wrong parameters');
3349  }
3350
3351  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3352  include_once(PHPWG_ROOT_PATH.'admin/include/'.$params['type'].'.class.php');
3353
3354  $type = $params['type'];
3355  $extension_id = $params['id'];
3356  $revision = $params['revision'];
3357
3358  $extension = new $type();
3359
3360  if ($type == 'plugins')
3361  {
3362    if (isset($extension->db_plugins_by_id[$extension_id]) and $extension->db_plugins_by_id[$extension_id]['state'] == 'active')
3363    {
3364      $extension->perform_action('deactivate', $extension_id);
3365
3366      redirect(PHPWG_ROOT_PATH
3367        . 'ws.php'
3368        . '?method=pwg.extensions.update'
3369        . '&type=plugins'
3370        . '&id=' . $extension_id
3371        . '&revision=' . $revision
3372        . '&reactivate=true'
3373        . '&pwg_token=' . get_pwg_token()
3374        . '&format=json'
3375      );
3376    }
3377
3378    $upgrade_status = $extension->extract_plugin_files('upgrade', $revision, $extension_id);
3379    $extension_name = $extension->fs_plugins[$extension_id]['name'];
3380
3381    if (isset($params['reactivate']))
3382    {
3383      $extension->perform_action('activate', $extension_id);
3384    }
3385  }
3386  elseif ($type == 'themes')
3387  {
3388    $upgrade_status = $extension->extract_theme_files('upgrade', $revision, $extension_id);
3389    $extension_name = $extension->fs_themes[$extension_id]['name'];
3390  }
3391  elseif ($type == 'languages')
3392  {
3393    $upgrade_status = $extension->extract_language_files('upgrade', $revision, $extension_id);
3394    $extension_name = $extension->fs_languages[$extension_id]['name'];
3395  }
3396
3397  global $template;
3398  $template->delete_compiled_templates();
3399
3400  switch ($upgrade_status)
3401  {
3402    case 'ok':
3403      return sprintf(l10n('%s has been successfully updated.'), $extension_name);
3404
3405    case 'temp_path_error':
3406      return new PwgError(null, l10n('Can\'t create temporary file.'));
3407
3408    case 'dl_archive_error':
3409      return new PwgError(null, l10n('Can\'t download archive.'));
3410
3411    case 'archive_error':
3412      return new PwgError(null, l10n('Can\'t read or extract archive.'));
3413
3414    default:
3415      return new PwgError(null, sprintf(l10n('An error occured during extraction (%s).'), $upgrade_status));
3416  }
3417}
3418
3419function ws_extensions_ignoreupdate($params, &$service)
3420{
3421  global $conf;
3422
3423  define('IN_ADMIN', true);
3424  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3425
3426  if (!is_webmaster())
3427  {
3428    return new PwgError(401, 'Access denied');
3429  }
3430
3431  if (empty($params['pwg_token']) or get_pwg_token() != $params['pwg_token'])
3432  {
3433    return new PwgError(403, 'Invalid security token');
3434  }
3435
3436  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3437
3438  // Reset ignored extension
3439  if ($params['reset'])
3440  {
3441    if (!empty($params['type']) and isset($conf['updates_ignored'][$params['type']]))
3442    {
3443      $conf['updates_ignored'][$params['type']] = array();
3444    }
3445    else
3446    {
3447      $conf['updates_ignored'] = array(
3448        'plugins'=>array(),
3449        'themes'=>array(),
3450        'languages'=>array()
3451      );
3452    }
3453    conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3454    unset($_SESSION['extensions_need_update']);
3455    return true;
3456  }
3457
3458  if (empty($params['id']) or empty($params['type']) or !in_array($params['type'], array('plugins', 'themes', 'languages')))
3459  {
3460    return new PwgError(403, 'Invalid parameters');
3461  }
3462
3463  // Add or remove extension from ignore list
3464  if (!in_array($params['id'], $conf['updates_ignored'][$params['type']]))
3465  {
3466    array_push($conf['updates_ignored'][$params['type']], $params['id']);
3467  }
3468  conf_update_param('updates_ignored', pwg_db_real_escape_string(serialize($conf['updates_ignored'])));
3469  unset($_SESSION['extensions_need_update']);
3470  return true;
3471}
3472
3473function ws_extensions_checkupdates($params, &$service)
3474{
3475  global $conf;
3476
3477  define('IN_ADMIN', true);
3478  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
3479  include_once(PHPWG_ROOT_PATH.'admin/include/updates.class.php');
3480  $update = new updates();
3481
3482  if (!is_admin())
3483  {
3484    return new PwgError(401, 'Access denied');
3485  }
3486
3487  $result = array();
3488
3489  if (!isset($_SESSION['need_update']))
3490    $update->check_piwigo_upgrade();
3491
3492  $result['piwigo_need_update'] = $_SESSION['need_update'];
3493
3494  $conf['updates_ignored'] = unserialize($conf['updates_ignored']);
3495
3496  if (!isset($_SESSION['extensions_need_update']))
3497    $update->check_extensions();
3498  else
3499    $update->check_updated_extensions();
3500
3501  if (!is_array($_SESSION['extensions_need_update']))
3502    $result['ext_need_update'] = null;
3503  else
3504    $result['ext_need_update'] = !empty($_SESSION['extensions_need_update']);
3505
3506  return $result;
3507}
3508?>
Note: See TracBrowser for help on using the repository browser.