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

Last change on this file since 2919 was 2919, checked in by plg, 15 years ago

merge r2722 from branch 2.0 to trunk

feature 892 added: pwg.images.setInfo added so that once we have discovered
the photo was already in the database (thanks to pwg.images.exist), we can
only set the photo metadata.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 40.5 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008      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.'average_rate>'.$params['f_min_rate'];
58  }
59  if ( is_numeric($params['f_max_rate']) )
60  {
61    $clauses[] = $tbl_name.'average_rate<='.$params['f_max_rate'];
62  }
63  if ( is_numeric($params['f_min_hit']) )
64  {
65    $clauses[] = $tbl_name.'hit>'.$params['f_min_hit'];
66  }
67  if ( is_numeric($params['f_max_hit']) )
68  {
69    $clauses[] = $tbl_name.'hit<='.$params['f_max_hit'];
70  }
71  if ( isset($params['f_min_date_posted']) )
72  {
73    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_posted']."'";
74  }
75  if ( isset($params['f_max_date_posted']) )
76  {
77    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_posted']."'";
78  }
79  if ( isset($params['f_min_date_created']) )
80  {
81    $clauses[] = $tbl_name."date_creation>='".$params['f_min_date_created']."'";
82  }
83  if ( isset($params['f_max_date_created']) )
84  {
85    $clauses[] = $tbl_name."date_creation<'".$params['f_max_date_created']."'";
86  }
87  if ( is_numeric($params['f_min_ratio']) )
88  {
89    $clauses[] = $tbl_name.'width/'.$tbl_name.'height>'.$params['f_min_ratio'];
90  }
91  if ( is_numeric($params['f_max_ratio']) )
92  {
93    $clauses[] = $tbl_name.'width/'.$tbl_name.'height<='.$params['f_max_ratio'];
94  }
95  if ( $params['f_with_thumbnail'] )
96  {
97    $clauses[] = $tbl_name.'tn_ext IS NOT NULL';
98  }
99  return $clauses;
100}
101
102/**
103 * returns a "standard" (for our web service) ORDER BY sql clause for images
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] = 'RAND()'; break;
125    }
126    $sortable_fields = array('id', 'file', 'name', 'hit', 'average_rate',
127      'date_creation', 'date_available', 'RAND()' );
128    if ( in_array($matches[1][$i], $sortable_fields) )
129    {
130      if (!empty($ret))
131        $ret .= ', ';
132      if ($matches[1][$i] != 'RAND()' )
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    'tn_url' => get_thumbnail_url($image_row),
151    'element_url' => get_element_url($image_row)
152  );
153  global $user;
154  if ($user['enabled_high'] and $image_row['has_high'] )
155  {
156    $ret['high_url'] = get_high_url($image_row);
157  }
158  return $ret;
159}
160
161/**
162 * returns an array of image attributes that are to be encoded as xml attributes
163 * instead of xml elements
164 */
165function ws_std_get_image_xml_attributes()
166{
167  return array(
168    'id','tn_url','element_url','high_url', 'file','width','height','hit'
169    );
170}
171
172/**
173 * returns PWG version (web service method)
174 */
175function ws_getVersion($params, &$service)
176{
177  global $conf;
178  if ($conf['show_version'])
179    return PHPWG_VERSION;
180  else
181    return new PwgError(403, 'Forbidden');
182}
183
184function ws_caddie_add($params, &$service)
185{
186  if (!is_admin())
187  {
188    return new PwgError(401, 'Access denied');
189  }
190  $params['image_id'] = array_map( 'intval',$params['image_id'] );
191  if ( empty($params['image_id']) )
192  {
193    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
194  }
195  global $user;
196  $query = '
197SELECT id
198  FROM '.IMAGES_TABLE.' LEFT JOIN '.CADDIE_TABLE.' ON id=element_id AND user_id='.$user['id'].'
199  WHERE id IN ('.implode(',',$params['image_id']).')
200    AND element_id IS NULL';
201  $datas = array();
202  foreach ( array_from_query($query, 'id') as $id )
203  {
204    array_push($datas, array('element_id'=>$id, 'user_id'=>$user['id']) );
205  }
206  if (count($datas))
207  {
208    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
209    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
210  }
211  return count($datas);
212}
213
214/**
215 * returns images per category (web service method)
216 */
217function ws_categories_getImages($params, &$service)
218{
219  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
220  global $user, $conf;
221
222  $images = array();
223
224  //------------------------------------------------- get the related categories
225  $where_clauses = array();
226  foreach($params['cat_id'] as $cat_id)
227  {
228    $cat_id = (int)$cat_id;
229    if ($cat_id<=0)
230      continue;
231    if ($params['recursive'])
232    {
233      $where_clauses[] = 'uppercats REGEXP \'(^|,)'.$cat_id.'(,|$)\'';
234    }
235    else
236    {
237      $where_clauses[] = 'id='.$cat_id;
238    }
239  }
240  if (!empty($where_clauses))
241  {
242    $where_clauses = array( '('.
243    implode('
244    OR ', $where_clauses) . ')'
245      );
246  }
247  $where_clauses[] = get_sql_condition_FandF(
248        array('forbidden_categories' => 'id'),
249        NULL, true
250      );
251
252  $query = '
253SELECT id, name, permalink, image_order
254  FROM '.CATEGORIES_TABLE.'
255  WHERE '. implode('
256    AND ', $where_clauses);
257  $result = pwg_query($query);
258  $cats = array();
259  while ($row = mysql_fetch_assoc($result))
260  {
261    $row['id'] = (int)$row['id'];
262    $cats[ $row['id'] ] = $row;
263  }
264
265  //-------------------------------------------------------- get the images
266  if ( !empty($cats) )
267  {
268    $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
269    $where_clauses[] = 'category_id IN ('
270      .implode(',', array_keys($cats) )
271      .')';
272    $where_clauses[] = get_sql_condition_FandF( array(
273          'visible_images' => 'i.id'
274        ), null, true
275      );
276
277    $order_by = ws_std_image_sql_order($params, 'i.');
278    if ( empty($order_by)
279          and count($params['cat_id'])==1
280          and isset($cats[ $params['cat_id'][0] ]['image_order'])
281        )
282    {
283      $order_by = $cats[ $params['cat_id'][0] ]['image_order'];
284    }
285    $order_by = empty($order_by) ? $conf['order_by'] : 'ORDER BY '.$order_by;
286
287    $query = '
288SELECT i.*, GROUP_CONCAT(category_id) cat_ids
289  FROM '.IMAGES_TABLE.' i
290    INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
291  WHERE '. implode('
292    AND ', $where_clauses).'
293GROUP BY i.id
294'.$order_by.'
295LIMIT '.(int)($params['per_page']*$params['page']).','.(int)$params['per_page'];
296
297    $result = pwg_query($query);
298    while ($row = mysql_fetch_assoc($result))
299    {
300      $image = array();
301      foreach ( array('id', 'width', 'height', 'hit') as $k )
302      {
303        if (isset($row[$k]))
304        {
305          $image[$k] = (int)$row[$k];
306        }
307      }
308      foreach ( array('file', 'name', 'comment') as $k )
309      {
310        $image[$k] = $row[$k];
311      }
312      $image = array_merge( $image, ws_std_get_urls($row) );
313
314      $image_cats = array();
315      foreach ( explode(',', $row['cat_ids']) as $cat_id )
316      {
317        $url = make_index_url(
318                array(
319                  'category' => $cats[$cat_id],
320                  )
321                );
322        $page_url = make_picture_url(
323                array(
324                  'category' => $cats[$cat_id],
325                  'image_id' => $row['id'],
326                  'image_file' => $row['file'],
327                  )
328                );
329        array_push( $image_cats,  array(
330              WS_XML_ATTRIBUTES => array (
331                  'id' => (int)$cat_id,
332                  'url' => $url,
333                  'page_url' => $page_url,
334                )
335            )
336          );
337      }
338
339      $image['categories'] = new PwgNamedArray(
340            $image_cats,'category', array('id','url','page_url')
341          );
342      array_push($images, $image);
343    }
344  }
345
346  return array( 'images' =>
347    array (
348      WS_XML_ATTRIBUTES =>
349        array(
350            'page' => $params['page'],
351            'per_page' => $params['per_page'],
352            'count' => count($images)
353          ),
354       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
355          ws_std_get_image_xml_attributes() )
356      )
357    );
358}
359
360
361/**
362 * returns a list of categories (web service method)
363 */
364function ws_categories_getList($params, &$service)
365{
366  global $user,$conf;
367
368  $where = array();
369
370  if (!$params['recursive'])
371  {
372    if ($params['cat_id']>0)
373      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
374    OR id='.(int)($params['cat_id']).')';
375    else
376      $where[] = 'id_uppercat IS NULL';
377  }
378  else if ($params['cat_id']>0)
379  {
380    $where[] = 'uppercats REGEXP \'(^|,)'.
381      (int)($params['cat_id'])
382      .'(,|$)\'';
383  }
384
385  if ($params['public'])
386  {
387    $where[] = 'status = "public"';
388    $where[] = 'visible = "true"';
389    $where[]= 'user_id='.$conf['guest_id'];
390  }
391  else
392  {
393    $where[]= 'user_id='.$user['id'];
394  }
395
396  $query = '
397SELECT id, name, permalink, uppercats, global_rank,
398    nb_images, count_images AS total_nb_images,
399    date_last, max_date_last, count_categories AS nb_categories
400  FROM '.CATEGORIES_TABLE.'
401   INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id
402  WHERE '. implode('
403    AND ', $where);
404
405  $result = pwg_query($query);
406
407  $cats = array();
408  while ($row = mysql_fetch_assoc($result))
409  {
410    $row['url'] = make_index_url(
411        array(
412          'category' => $row
413          )
414      );
415    foreach( array('id','nb_images','total_nb_images','nb_categories') as $key)
416    {
417      $row[$key] = (int)$row[$key];
418    }
419
420    array_push($cats, $row);
421  }
422  usort($cats, 'global_rank_compare');
423  return array(
424    'categories' => new PwgNamedArray(
425      $cats,
426      'category',
427      array(
428        'id',
429        'url',
430        'nb_images',
431        'total_nb_images',
432        'nb_categories',
433        'date_last',
434        'max_date_last',
435        )
436      )
437    );
438}
439
440/**
441 * returns the list of categories as you can see them in administration (web
442 * service method).
443 *
444 * Only admin can run this method and permissions are not taken into
445 * account.
446 */
447function ws_categories_getAdminList($params, &$service)
448{
449  if (!is_admin())
450  {
451    return new PwgError(401, 'Access denied');
452  }
453
454  $query = '
455SELECT
456    category_id,
457    COUNT(*) AS counter
458  FROM '.IMAGE_CATEGORY_TABLE.'
459  GROUP BY category_id
460;';
461  $nb_images_of = simple_hash_from_query($query, 'category_id', 'counter');
462
463  $query = '
464SELECT
465    id,
466    name,
467    uppercats,
468    global_rank
469  FROM '.CATEGORIES_TABLE.'
470;';
471  $result = pwg_query($query);
472  $cats = array();
473
474  while ($row = mysql_fetch_assoc($result))
475  {
476    $id = $row['id'];
477    $row['nb_images'] = isset($nb_images_of[$id]) ? $nb_images_of[$id] : 0;
478    array_push($cats, $row);
479  }
480
481  usort($cats, 'global_rank_compare');
482  return array(
483    'categories' => new PwgNamedArray(
484      $cats,
485      'category',
486      array(
487        'id',
488        'nb_images',
489        'name',
490        'uppercats',
491        'global_rank',
492        )
493      )
494    );
495}
496
497/**
498 * returns detailed information for an element (web service method)
499 */
500function ws_images_addComment($params, &$service)
501{
502  if (!$service->isPost())
503  {
504    return new PwgError(405, "This method requires HTTP POST");
505  }
506  $params['image_id'] = (int)$params['image_id'];
507  $query = '
508SELECT DISTINCT image_id
509  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.CATEGORIES_TABLE.' ON category_id=id
510  WHERE commentable="true"
511    AND image_id='.$params['image_id'].
512    get_sql_condition_FandF(
513      array(
514        'forbidden_categories' => 'id',
515        'visible_categories' => 'id',
516        'visible_images' => 'image_id'
517      ),
518      ' AND'
519    );
520  if ( !mysql_num_rows( pwg_query( $query ) ) )
521  {
522    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
523  }
524
525  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
526
527  $comm = array(
528    'author' => trim( stripslashes($params['author']) ),
529    'content' => trim( stripslashes($params['content']) ),
530    'image_id' => $params['image_id'],
531   );
532
533  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
534
535  $comment_action = insert_user_comment(
536      $comm, $params['key'], $infos
537    );
538
539  switch ($comment_action)
540  {
541    case 'reject':
542      array_push($infos, l10n('comment_not_added') );
543      return new PwgError(403, implode("\n", $infos) );
544    case 'validate':
545    case 'moderate':
546      $ret = array(
547          'id' => $comm['id'],
548          'validation' => $comment_action=='validate',
549        );
550      return new PwgNamedStruct(
551          'comment',
552          $ret,
553          null, array()
554        );
555    default:
556      return new PwgError(500, "Unknown comment action ".$comment_action );
557  }
558}
559
560/**
561 * returns detailed information for an element (web service method)
562 */
563function ws_images_getInfo($params, &$service)
564{
565  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
566  global $user, $conf;
567  $params['image_id'] = (int)$params['image_id'];
568  if ( $params['image_id']<=0 )
569  {
570    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
571  }
572
573  $query='
574SELECT * FROM '.IMAGES_TABLE.'
575  WHERE id='.$params['image_id'].
576    get_sql_condition_FandF(
577      array('visible_images' => 'id'),
578      ' AND'
579    ).'
580LIMIT 1';
581
582  $image_row = mysql_fetch_assoc(pwg_query($query));
583  if ($image_row==null)
584  {
585    return new PwgError(404, "image_id not found");
586  }
587  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
588
589  //-------------------------------------------------------- related categories
590  $query = '
591SELECT id, name, permalink, uppercats, global_rank, commentable
592  FROM '.IMAGE_CATEGORY_TABLE.'
593    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
594  WHERE image_id = '.$image_row['id'].
595  get_sql_condition_FandF(
596      array( 'forbidden_categories' => 'category_id' ),
597      ' AND'
598    ).'
599;';
600  $result = pwg_query($query);
601  $is_commentable = false;
602  $related_categories = array();
603  while ($row = mysql_fetch_assoc($result))
604  {
605    if ($row['commentable']=='true')
606    {
607      $is_commentable = true;
608    }
609    unset($row['commentable']);
610    $row['url'] = make_index_url(
611        array(
612          'category' => $row
613          )
614      );
615
616    $row['page_url'] = make_picture_url(
617        array(
618          'image_id' => $image_row['id'],
619          'image_file' => $image_row['file'],
620          'category' => $row
621          )
622      );
623    $row['id']=(int)$row['id'];
624    array_push($related_categories, $row);
625  }
626  usort($related_categories, 'global_rank_compare');
627  if ( empty($related_categories) )
628  {
629    return new PwgError(401, 'Access denied');
630  }
631
632  //-------------------------------------------------------------- related tags
633  $related_tags = get_common_tags( array($image_row['id']), -1 );
634  foreach( $related_tags as $i=>$tag)
635  {
636    $tag['url'] = make_index_url(
637        array(
638          'tags' => array($tag)
639          )
640      );
641    $tag['page_url'] = make_picture_url(
642        array(
643          'image_id' => $image_row['id'],
644          'image_file' => $image_row['file'],
645          'tags' => array($tag),
646          )
647      );
648    unset($tag['counter']);
649    $tag['id']=(int)$tag['id'];
650    $related_tags[$i]=$tag;
651  }
652  //------------------------------------------------------------- related rates
653  $query = '
654SELECT COUNT(rate) AS count
655     , ROUND(AVG(rate),2) AS average
656     , ROUND(STD(rate),2) AS stdev
657  FROM '.RATE_TABLE.'
658  WHERE element_id = '.$image_row['id'].'
659;';
660  $rating = mysql_fetch_assoc(pwg_query($query));
661  $rating['count'] = (int)$rating['count'];
662
663  //---------------------------------------------------------- related comments
664  $related_comments = array();
665
666  $where_comments = 'image_id = '.$image_row['id'];
667  if ( !is_admin() )
668  {
669    $where_comments .= '
670    AND validated="true"';
671  }
672
673  $query = '
674SELECT COUNT(id) nb_comments
675  FROM '.COMMENTS_TABLE.'
676  WHERE '.$where_comments;
677  list($nb_comments) = array_from_query($query, 'nb_comments');
678  $nb_comments = (int)$nb_comments;
679
680  if ( $nb_comments>0 and $params['comments_per_page']>0 )
681  {
682    $query = '
683SELECT id, date, author, content
684  FROM '.COMMENTS_TABLE.'
685  WHERE '.$where_comments.'
686  ORDER BY date
687  LIMIT '.(int)($params['comments_per_page']*$params['comments_page']).
688    ','.(int)$params['comments_per_page'];
689
690    $result = pwg_query($query);
691    while ($row = mysql_fetch_assoc($result))
692    {
693      $row['id']=(int)$row['id'];
694      array_push($related_comments, $row);
695    }
696  }
697
698  $comment_post_data = null;
699  if ($is_commentable and
700      (!is_a_guest()
701        or (is_a_guest() and $conf['comments_forall'] )
702      )
703      )
704  {
705    include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
706    $comment_post_data['author'] = $user['username'];
707    $comment_post_data['key'] = get_comment_post_key($params['image_id']);
708  }
709
710  $ret = $image_row;
711  foreach ( array('id','width','height','hit','filesize') as $k )
712  {
713    if (isset($ret[$k]))
714    {
715      $ret[$k] = (int)$ret[$k];
716    }
717  }
718  foreach ( array('path', 'storage_category_id') as $k )
719  {
720    unset($ret[$k]);
721  }
722
723  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
724  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
725  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
726  if ( isset($comment_post_data) )
727  {
728    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
729  }
730  $ret['comments'] = array(
731     WS_XML_ATTRIBUTES =>
732        array(
733          'page' => $params['comments_page'],
734          'per_page' => $params['comments_per_page'],
735          'count' => count($related_comments),
736          'nb_comments' => $nb_comments,
737        ),
738     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id','date') )
739      );
740
741  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
742}
743
744
745/**
746 * rates the image_id in the parameter
747 */
748function ws_images_Rate($params, &$service)
749{
750  $image_id = (int)$params['image_id'];
751  $query = '
752SELECT DISTINCT id FROM '.IMAGES_TABLE.'
753  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
754  WHERE id='.$image_id
755  .get_sql_condition_FandF(
756    array(
757        'forbidden_categories' => 'category_id',
758        'forbidden_images' => 'id',
759      ),
760    '    AND'
761    ).'
762    LIMIT 1';
763  if ( mysql_num_rows( pwg_query($query) )==0 )
764  {
765    return new PwgError(404, "Invalid image_id or access denied" );
766  }
767  $rate = (int)$params['rate'];
768  include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
769  $res = rate_picture( $image_id, $rate );
770  if ($res==false)
771  {
772    global $conf;
773    return new PwgError( 403, "Forbidden or rate not in ". implode(',',$conf['rate_items']));
774  }
775  return $res;
776}
777
778
779/**
780 * returns a list of elements corresponding to a query search
781 */
782function ws_images_search($params, &$service)
783{
784  global $page;
785  $images = array();
786  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
787  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
788
789  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
790  $order_by = ws_std_image_sql_order($params, 'i.');
791
792  $super_order_by = false;
793  if ( !empty($order_by) )
794  {
795    global $conf;
796    $conf['order_by'] = 'ORDER BY '.$order_by;
797    $super_order_by=true; // quick_search_result might be faster
798  }
799
800  $search_result = get_quick_search_results($params['query'],
801      $super_order_by,
802      implode(',', $where_clauses)
803    );
804
805  $image_ids = array_slice(
806      $search_result['items'],
807      $params['page']*$params['per_page'],
808      $params['per_page']
809    );
810
811  if ( count($image_ids) )
812  {
813    $query = '
814SELECT * FROM '.IMAGES_TABLE.'
815  WHERE id IN ('.implode(',', $image_ids).')';
816
817    $image_ids = array_flip($image_ids);
818    $result = pwg_query($query);
819    while ($row = mysql_fetch_assoc($result))
820    {
821      $image = array();
822      foreach ( array('id', 'width', 'height', 'hit') as $k )
823      {
824        if (isset($row[$k]))
825        {
826          $image[$k] = (int)$row[$k];
827        }
828      }
829      foreach ( array('file', 'name', 'comment') as $k )
830      {
831        $image[$k] = $row[$k];
832      }
833      $image = array_merge( $image, ws_std_get_urls($row) );
834      $images[$image_ids[$image['id']]] = $image;
835    }
836    ksort($images, SORT_NUMERIC);
837    $images = array_values($images);
838  }
839
840
841  return array( 'images' =>
842    array (
843      WS_XML_ATTRIBUTES =>
844        array(
845            'page' => $params['page'],
846            'per_page' => $params['per_page'],
847            'count' => count($images)
848          ),
849       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
850          ws_std_get_image_xml_attributes() )
851      )
852    );
853}
854
855function ws_images_setPrivacyLevel($params, &$service)
856{
857  if (!is_admin() || is_adviser() )
858  {
859    return new PwgError(401, 'Access denied');
860  }
861  $params['image_id'] = array_map( 'intval',$params['image_id'] );
862  if ( empty($params['image_id']) )
863  {
864    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
865  }
866  global $conf;
867  if ( !in_array( (int)$params['level'], $conf['available_permission_levels']) )
868  {
869    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid level");
870  }
871  $query = '
872UPDATE '.IMAGES_TABLE.'
873  SET level='.(int)$params['level'].'
874  WHERE id IN ('.implode(',',$params['image_id']).')';
875  $result = pwg_query($query);
876  $affected_rows = mysql_affected_rows();
877  if ($affected_rows)
878  {
879    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
880    invalidate_user_cache();
881  }
882  return $affected_rows;
883}
884
885function ws_images_add($params, &$service)
886{
887  global $conf;
888  if (!is_admin() || is_adviser() )
889  {
890    return new PwgError(401, 'Access denied');
891  }
892
893  // name
894  // category_id
895  // file_content
896  // file_sum
897  // thumbnail_content
898  // thumbnail_sum
899  // rank
900
901  // $fh_log = fopen('/tmp/php.log', 'w');
902  // fwrite($fh_log, time()."\n");
903  // fwrite($fh_log, 'input rank :'.$params['rank']."\n");
904  // fwrite($fh_log, 'input:  '.$params['file_sum']."\n");
905  // fwrite($fh_log, 'input:  '.$params['thumbnail_sum']."\n");
906
907  // does the image already exists ?
908  $query = '
909SELECT
910    COUNT(*) AS counter
911  FROM '.IMAGES_TABLE.'
912  WHERE md5sum = \''.$params['file_sum'].'\'
913;';
914  list($counter) = mysql_fetch_row(pwg_query($query));
915  if ($counter != 0) {
916    return new PwgError(500, 'file already exists');
917  }
918
919  // current date
920  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
921  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
922
923  // upload directory hierarchy
924  $upload_dir = sprintf(
925    PHPWG_ROOT_PATH.'upload/%s/%s/%s',
926    $year,
927    $month,
928    $day
929    );
930
931  //fwrite($fh_log, $upload_dir."\n");
932
933  // create the upload directory tree if not exists
934  if (!is_dir($upload_dir)) {
935    umask(0000);
936    $recursive = true;
937    if (!@mkdir($upload_dir, 0777, $recursive))
938    {
939      return new PwgError(500, 'error during directory creation');
940    }
941  }
942
943  if (!is_writable($upload_dir))
944  {
945    // last chance to make the directory writable
946    @chmod($upload_dir, 0777);
947
948    if (!is_writable($upload_dir))
949    {
950      return new PwgError(500, 'directory has no write access');
951    }
952  }
953
954  secure_directory($upload_dir);
955
956  // compute file path
957  $date_string = preg_replace('/[^\d]/', '', $dbnow);
958  $random_string = substr($params['file_sum'], 0, 8);
959  $filename_wo_ext = $date_string.'-'.$random_string;
960  $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
961
962  // dump the photo file
963  $fh_file = fopen($file_path, 'w');
964  if (!fwrite($fh_file, base64_decode($params['file_content'])))
965  {
966    return new PwgError(500, 'error while writing file');
967  }
968  fclose($fh_file);
969  chmod($file_path, 0644);
970
971  // check dumped file md5sum against expected md5sum
972  $dumped_md5 = md5_file($file_path);
973  if ($dumped_md5 != $params['file_sum']) {
974    return new PwgError(500, 'file transfer failed');
975  }
976
977  // thumbnail directory is a subdirectory of the photo file, hard coded
978  // "thumbnail"
979  $thumbnail_dir = $upload_dir.'/thumbnail';
980  if (!is_dir($thumbnail_dir)) {
981    umask(0000);
982    if (!@mkdir($thumbnail_dir, 0777))
983    {
984      return new PwgError(500, 'error during thumbnail directory creation');
985    }
986  }
987
988  if (!is_writable($thumbnail_dir))
989  {
990    // last chance to make the directory writable
991    @chmod($thumbnail_dir, 0777);
992
993    if (!is_writable($thumbnail_dir))
994    {
995      return new PwgError(500, 'thumbnail directory has no write access');
996    }
997  }
998
999  secure_directory($thumbnail_dir);
1000
1001  // thumbnail path, the filename may use a prefix and the extension is
1002  // always "jpg" (no matter what the real file format is)
1003  $thumbnail_path = sprintf(
1004    '%s/%s%s.%s',
1005    $thumbnail_dir,
1006    $conf['prefix_thumbnail'],
1007    $filename_wo_ext,
1008    'jpg'
1009    );
1010
1011  // dump the thumbnail
1012  $fh_thumbnail = fopen($thumbnail_path, 'w');
1013  if (!fwrite($fh_thumbnail, base64_decode($params['thumbnail_content'])))
1014  {
1015    return new PwgError(500, 'error while writing thumbnail');
1016  }
1017  fclose($fh_thumbnail);
1018  chmod($thumbnail_path, 0644);
1019
1020  // check dumped thumbnail md5
1021  $dumped_md5 = md5_file($thumbnail_path);
1022  if ($dumped_md5 != $params['thumbnail_sum']) {
1023    return new PwgError(500, 'thumbnail transfer failed');
1024  }
1025
1026  // high resolution
1027  if (isset($params['high_content']))
1028  {
1029    // high resolution directory is a subdirectory of the photo file, hard
1030    // coded "pwg_high"
1031    $high_dir = $upload_dir.'/pwg_high';
1032    if (!is_dir($high_dir)) {
1033      umask(0000);
1034      if (!@mkdir($high_dir, 0777))
1035      {
1036        return new PwgError(500, 'error during high directory creation');
1037      }
1038    }
1039
1040    if (!is_writable($high_dir))
1041    {
1042      // last chance to make the directory writable
1043      @chmod($high_dir, 0777);
1044     
1045      if (!is_writable($high_dir))
1046      {
1047        return new PwgError(500, 'high directory has no write access');
1048      }
1049    }
1050   
1051    secure_directory($high_dir);
1052   
1053    // high resolution path, same name as web size file
1054    $high_path = sprintf(
1055      '%s/%s.%s',
1056      $high_dir,
1057      $filename_wo_ext,
1058      'jpg'
1059      );
1060
1061    // dump the high resolution file
1062    $fh_high = fopen($high_path, 'w');
1063    if (!fwrite($fh_high, base64_decode($params['high_content'])))
1064    {
1065      return new PwgError(500, 'error while writing high');
1066    }
1067    fclose($fh_high);
1068    chmod($high_path, 0644);
1069
1070    // check dumped thumbnail md5
1071    $dumped_md5 = md5_file($high_path);
1072    if ($dumped_md5 != $params['high_sum']) {
1073      return new PwgError(500, 'high resolution transfer failed');
1074    }
1075
1076    $high_filesize = floor(filesize($high_path)/1024);
1077  }
1078
1079  list($width, $height) = getimagesize($file_path);
1080
1081  // database registration
1082  $insert = array(
1083    'file' => $filename_wo_ext.'.jpg',
1084    'date_available' => $dbnow,
1085    'tn_ext' => 'jpg',
1086    'name' => $params['name'],
1087    'path' => $file_path,
1088    'filesize' => floor(filesize($file_path)/1024),
1089    'width' => $width,
1090    'height' => $height,
1091    'md5sum' => $params['file_sum'],
1092    );
1093
1094  $info_columns = array(
1095    'name',
1096    'author',
1097    'comment',
1098    'level',
1099    'date_creation',
1100    );
1101
1102  foreach ($info_columns as $key)
1103  {
1104    if (isset($params[$key]))
1105    {
1106      $insert[$key] = $params[$key];
1107    }
1108  }
1109
1110  if (isset($params['high_content']))
1111  {
1112    $insert['has_high'] = 'true';
1113    $insert['high_filesize'] = $high_filesize;
1114  }
1115
1116  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1117  mass_inserts(
1118    IMAGES_TABLE,
1119    array_keys($insert),
1120    array($insert)
1121    );
1122
1123  $image_id = mysql_insert_id();
1124
1125  // let's add links between the image and the categories
1126  if (isset($params['categories']))
1127  {
1128    ws_add_image_category_relations($image_id, $params['categories']);
1129  }
1130
1131  // and now, let's create tag associations
1132  if (isset($params['tag_ids']))
1133  {
1134    set_tags(
1135      explode(',', $params['tag_ids']),
1136      $image_id
1137      );
1138  }
1139
1140  invalidate_user_cache();
1141
1142  // fclose($fh_log);
1143}
1144
1145/**
1146 * perform a login (web service method)
1147 */
1148function ws_session_login($params, &$service)
1149{
1150  global $conf;
1151
1152  if (!$service->isPost())
1153  {
1154    return new PwgError(405, "This method requires HTTP POST");
1155  }
1156  if (try_log_user($params['username'], $params['password'],false))
1157  {
1158    return true;
1159  }
1160  return new PwgError(999, 'Invalid username/password');
1161}
1162
1163
1164/**
1165 * performs a logout (web service method)
1166 */
1167function ws_session_logout($params, &$service)
1168{
1169  if (!is_a_guest())
1170  {
1171    logout_user();
1172  }
1173  return true;
1174}
1175
1176function ws_session_getStatus($params, &$service)
1177{
1178  global $user;
1179  $res = array();
1180  $res['username'] = is_a_guest() ? 'guest' : $user['username'];
1181  foreach ( array('status', 'template', 'theme', 'language') as $k )
1182  {
1183    $res[$k] = $user[$k];
1184  }
1185  $res['charset'] = get_pwg_charset();
1186  return $res;
1187}
1188
1189
1190/**
1191 * returns a list of tags (web service method)
1192 */
1193function ws_tags_getList($params, &$service)
1194{
1195  $tags = get_available_tags();
1196  if ($params['sort_by_counter'])
1197  {
1198    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1199  }
1200  else
1201  {
1202    usort($tags, 'tag_alpha_compare');
1203  }
1204  for ($i=0; $i<count($tags); $i++)
1205  {
1206    $tags[$i]['id'] = (int)$tags[$i]['id'];
1207    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1208    $tags[$i]['url'] = make_index_url(
1209        array(
1210          'section'=>'tags',
1211          'tags'=>array($tags[$i])
1212        )
1213      );
1214  }
1215  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
1216}
1217
1218/**
1219 * returns the list of tags as you can see them in administration (web
1220 * service method).
1221 *
1222 * Only admin can run this method and permissions are not taken into
1223 * account.
1224 */
1225function ws_tags_getAdminList($params, &$service)
1226{
1227  if (!is_admin())
1228  {
1229    return new PwgError(401, 'Access denied');
1230  }
1231
1232  $tags = get_all_tags();
1233  return array(
1234    'tags' => new PwgNamedArray(
1235      $tags,
1236      'tag',
1237      array(
1238        'name',
1239        'id',
1240        'url_name',
1241        )
1242      )
1243    );
1244}
1245
1246/**
1247 * returns a list of images for tags (web service method)
1248 */
1249function ws_tags_getImages($params, &$service)
1250{
1251  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1252  global $conf;
1253
1254  // first build all the tag_ids we are interested in
1255  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1256  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1257  $tags_by_id = array();
1258  foreach( $tags as $tag )
1259  {
1260    $tags['id'] = (int)$tag['id'];
1261    $tags_by_id[ $tag['id'] ] = $tag;
1262  }
1263  unset($tags);
1264  $tag_ids = array_keys($tags_by_id);
1265
1266
1267  $image_ids = array();
1268  $image_tag_map = array();
1269
1270  if ( !empty($tag_ids) )
1271  { // build list of image ids with associated tags per image
1272    if ($params['tag_mode_and'])
1273    {
1274      $image_ids = get_image_ids_for_tags( $tag_ids );
1275    }
1276    else
1277    {
1278      $query = '
1279SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
1280  FROM '.IMAGE_TAG_TABLE.'
1281  WHERE tag_id IN ('.implode(',',$tag_ids).')
1282  GROUP BY image_id';
1283      $result = pwg_query($query);
1284      while ( $row=mysql_fetch_assoc($result) )
1285      {
1286        $row['image_id'] = (int)$row['image_id'];
1287        array_push( $image_ids, $row['image_id'] );
1288        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1289      }
1290    }
1291  }
1292
1293  $images = array();
1294  if ( !empty($image_ids))
1295  {
1296    $where_clauses = ws_std_image_sql_filter($params);
1297    $where_clauses[] = get_sql_condition_FandF(
1298        array
1299          (
1300            'forbidden_categories' => 'category_id',
1301            'visible_categories' => 'category_id',
1302            'visible_images' => 'i.id'
1303          ),
1304        '', true
1305      );
1306    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
1307
1308    $order_by = ws_std_image_sql_order($params);
1309    if (empty($order_by))
1310    {
1311      $order_by = $conf['order_by'];
1312    }
1313    else
1314    {
1315      $order_by = 'ORDER BY '.$order_by;
1316    }
1317
1318    $query = '
1319SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
1320  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
1321  WHERE '. implode('
1322    AND ', $where_clauses).'
1323'.$order_by.'
1324LIMIT '.(int)($params['per_page']*$params['page']).','.(int)$params['per_page'];
1325
1326    $result = pwg_query($query);
1327    while ($row = mysql_fetch_assoc($result))
1328    {
1329      $image = array();
1330      foreach ( array('id', 'width', 'height', 'hit') as $k )
1331      {
1332        if (isset($row[$k]))
1333        {
1334          $image[$k] = (int)$row[$k];
1335        }
1336      }
1337      foreach ( array('file', 'name', 'comment') as $k )
1338      {
1339        $image[$k] = $row[$k];
1340      }
1341      $image = array_merge( $image, ws_std_get_urls($row) );
1342
1343      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1344      $image_tags = array();
1345      foreach ($image_tag_ids as $tag_id)
1346      {
1347        $url = make_index_url(
1348                 array(
1349                  'section'=>'tags',
1350                  'tags'=> array($tags_by_id[$tag_id])
1351                )
1352              );
1353        $page_url = make_picture_url(
1354                 array(
1355                  'section'=>'tags',
1356                  'tags'=> array($tags_by_id[$tag_id]),
1357                  'image_id' => $row['id'],
1358                  'image_file' => $row['file'],
1359                )
1360              );
1361        array_push($image_tags, array(
1362                'id' => (int)$tag_id,
1363                'url' => $url,
1364                'page_url' => $page_url,
1365              )
1366            );
1367      }
1368      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1369              array('id','url_name','url','page_url')
1370            );
1371      array_push($images, $image);
1372    }
1373  }
1374
1375  return array( 'images' =>
1376    array (
1377      WS_XML_ATTRIBUTES =>
1378        array(
1379            'page' => $params['page'],
1380            'per_page' => $params['per_page'],
1381            'count' => count($images)
1382          ),
1383       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1384          ws_std_get_image_xml_attributes() )
1385      )
1386    );
1387}
1388
1389function ws_categories_add($params, &$service)
1390{
1391  if (!is_admin() or is_adviser())
1392  {
1393    return new PwgError(401, 'Access denied');
1394  }
1395
1396  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1397
1398  $creation_output = create_virtual_category(
1399    $params['name'],
1400    $params['parent']
1401    );
1402
1403  if (isset($creation_output['error']))
1404  {
1405    return new PwgError(500, $creation_output['error']);
1406  }
1407
1408  invalidate_user_cache();
1409
1410  return $creation_output;
1411}
1412
1413function ws_tags_add($params, &$service)
1414{
1415  if (!is_admin() or is_adviser())
1416  {
1417    return new PwgError(401, 'Access denied');
1418  }
1419
1420  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1421
1422  $creation_output = create_tag($params['name']);
1423
1424  if (isset($creation_output['error']))
1425  {
1426    return new PwgError(500, $creation_output['error']);
1427  }
1428
1429  return $creation_output;
1430}
1431
1432function ws_images_exist($params, &$service)
1433{
1434  if (!is_admin() or is_adviser())
1435  {
1436    return new PwgError(401, 'Access denied');
1437  }
1438
1439  // search among photos the list of photos already added, based on md5sum
1440  // list
1441  $md5sums = preg_split(
1442    '/[\s,;\|]/',
1443    $params['md5sum_list'],
1444    -1,
1445    PREG_SPLIT_NO_EMPTY
1446    );
1447
1448  $query = '
1449SELECT
1450    id,
1451    md5sum
1452  FROM '.IMAGES_TABLE.'
1453  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
1454;';
1455  $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
1456
1457  $result = array();
1458
1459  foreach ($md5sums as $md5sum)
1460  {
1461    $result[$md5sum] = null;
1462    if (isset($id_of_md5[$md5sum]))
1463    {
1464      $result[$md5sum] = $id_of_md5[$md5sum];
1465    }
1466  }
1467
1468  return $result;
1469}
1470
1471function ws_images_setInfo($params, &$service)
1472{
1473  global $conf;
1474  if (!is_admin() || is_adviser() )
1475  {
1476    return new PwgError(401, 'Access denied');
1477  }
1478
1479  // name
1480  // category_id
1481  // file_content
1482  // file_sum
1483  // thumbnail_content
1484  // thumbnail_sum
1485 
1486  $params['image_id'] = (int)$params['image_id'];
1487  if ($params['image_id'] <= 0)
1488  {
1489    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1490  }
1491
1492  $query='
1493SELECT *
1494  FROM '.IMAGES_TABLE.'
1495  WHERE id = '.$params['image_id'].'
1496;';
1497
1498  $image_row = mysql_fetch_assoc(pwg_query($query));
1499  if ($image_row == null)
1500  {
1501    return new PwgError(404, "image_id not found");
1502  }
1503
1504  // database registration
1505  $update = array(
1506    'id' => $params['image_id'],
1507    );
1508
1509  $info_columns = array(
1510    'name',
1511    'author',
1512    'comment',
1513    'level',
1514    'date_creation',
1515    );
1516
1517  $perform_update = false;
1518  foreach ($info_columns as $key)
1519  {
1520    if (isset($params[$key]))
1521    {
1522      $perform_update = true;
1523      $update[$key] = $params[$key];
1524    }
1525  }
1526
1527  if ($perform_update)
1528  {
1529    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1530    mass_updates(
1531      IMAGES_TABLE,
1532      array(
1533        'primary' => array('id'),
1534        'update'  => array_diff(array_keys($update), array('id'))
1535        ),
1536      array($update)
1537      );
1538  }
1539 
1540  if (isset($params['categories']))
1541  {
1542    ws_add_image_category_relations(
1543      $params['image_id'],
1544      $params['categories']
1545      );
1546  }
1547
1548  // and now, let's create tag associations
1549  if (isset($params['tag_ids']))
1550  {
1551    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1552    add_tags(
1553      explode(',', $params['tag_ids']),
1554      array($params['image_id'])
1555      );
1556  }
1557
1558  invalidate_user_cache();
1559}
1560
1561function ws_add_image_category_relations($image_id, $categories_string)
1562{
1563  // let's add links between the image and the categories
1564  //
1565  // $params['categories'] should look like 123,12;456,auto;789 which means:
1566  //
1567  // 1. associate with category 123 on rank 12
1568  // 2. associate with category 456 on automatic rank
1569  // 3. associate with category 789 on automatic rank
1570  $cat_ids = array();
1571  $rank_on_category = array();
1572  $search_current_ranks = false;
1573
1574  $tokens = explode(';', $categories_string);
1575  foreach ($tokens as $token)
1576  {
1577    list($cat_id, $rank) = explode(',', $token);
1578
1579    array_push($cat_ids, $cat_id);
1580
1581    if (!isset($rank))
1582    {
1583      $rank = 'auto';
1584    }
1585    $rank_on_category[$cat_id] = $rank;
1586
1587    if ($rank == 'auto')
1588    {
1589      $search_current_ranks = true;
1590    }
1591  }
1592
1593  $cat_ids = array_unique($cat_ids);
1594
1595  if (count($cat_ids) > 0)
1596  {
1597    if ($search_current_ranks)
1598    {
1599      $query = '
1600SELECT
1601    category_id,
1602    MAX(rank) AS max_rank
1603  FROM '.IMAGE_CATEGORY_TABLE.'
1604  WHERE rank IS NOT NULL
1605    AND category_id IN ('.implode(',', $cat_ids).')
1606  GROUP BY category_id
1607;';
1608      $current_rank_of = simple_hash_from_query(
1609        $query,
1610        'category_id',
1611        'max_rank'
1612        );
1613
1614      foreach ($cat_ids as $cat_id)
1615      {
1616        if ('auto' == $rank_on_category[$cat_id])
1617        {
1618          $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
1619        }
1620      }
1621    }
1622
1623    $inserts = array();
1624
1625    foreach ($cat_ids as $cat_id)
1626    {
1627      array_push(
1628        $inserts,
1629        array(
1630          'image_id' => $image_id,
1631          'category_id' => $cat_id,
1632          'rank' => $rank_on_category[$cat_id],
1633          )
1634        );
1635    }
1636
1637    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1638    mass_inserts(
1639      IMAGE_CATEGORY_TABLE,
1640      array_keys($inserts[0]),
1641      $inserts
1642      );
1643
1644    update_category($cat_ids);
1645  }
1646}
1647?>
Note: See TracBrowser for help on using the repository browser.