source: branches/2.0/include/ws_functions.inc.php @ 3147

Last change on this file since 3147 was 3147, checked in by rvelices, 15 years ago

merge 3145-3146 from trunk
Last (I hope) paranoic optims ...

  • move get_uysername and get_groupname from public to admin/functions.inc.php
  • optim in index.php
  • tags.tpl does not need smarty modifier included
  • move func get_comment_post_key from functions_comment to functions (avoid extra inclusion every time on picture page)
  • 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-2009 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  $comm = array(
526    'author' => trim( stripslashes($params['author']) ),
527    'content' => trim( stripslashes($params['content']) ),
528    'image_id' => $params['image_id'],
529   );
530
531  include_once(PHPWG_ROOT_PATH.'include/functions_comment.inc.php');
532
533  $comment_action = insert_user_comment(
534      $comm, $params['key'], $infos
535    );
536
537  switch ($comment_action)
538  {
539    case 'reject':
540      array_push($infos, l10n('comment_not_added') );
541      return new PwgError(403, implode("\n", $infos) );
542    case 'validate':
543    case 'moderate':
544      $ret = array(
545          'id' => $comm['id'],
546          'validation' => $comment_action=='validate',
547        );
548      return new PwgNamedStruct(
549          'comment',
550          $ret,
551          null, array()
552        );
553    default:
554      return new PwgError(500, "Unknown comment action ".$comment_action );
555  }
556}
557
558/**
559 * returns detailed information for an element (web service method)
560 */
561function ws_images_getInfo($params, &$service)
562{
563  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
564  global $user, $conf;
565  $params['image_id'] = (int)$params['image_id'];
566  if ( $params['image_id']<=0 )
567  {
568    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
569  }
570
571  $query='
572SELECT * FROM '.IMAGES_TABLE.'
573  WHERE id='.$params['image_id'].
574    get_sql_condition_FandF(
575      array('visible_images' => 'id'),
576      ' AND'
577    ).'
578LIMIT 1';
579
580  $image_row = mysql_fetch_assoc(pwg_query($query));
581  if ($image_row==null)
582  {
583    return new PwgError(404, "image_id not found");
584  }
585  $image_row = array_merge( $image_row, ws_std_get_urls($image_row) );
586
587  //-------------------------------------------------------- related categories
588  $query = '
589SELECT id, name, permalink, uppercats, global_rank, commentable
590  FROM '.IMAGE_CATEGORY_TABLE.'
591    INNER JOIN '.CATEGORIES_TABLE.' ON category_id = id
592  WHERE image_id = '.$image_row['id'].
593  get_sql_condition_FandF(
594      array( 'forbidden_categories' => 'category_id' ),
595      ' AND'
596    ).'
597;';
598  $result = pwg_query($query);
599  $is_commentable = false;
600  $related_categories = array();
601  while ($row = mysql_fetch_assoc($result))
602  {
603    if ($row['commentable']=='true')
604    {
605      $is_commentable = true;
606    }
607    unset($row['commentable']);
608    $row['url'] = make_index_url(
609        array(
610          'category' => $row
611          )
612      );
613
614    $row['page_url'] = make_picture_url(
615        array(
616          'image_id' => $image_row['id'],
617          'image_file' => $image_row['file'],
618          'category' => $row
619          )
620      );
621    $row['id']=(int)$row['id'];
622    array_push($related_categories, $row);
623  }
624  usort($related_categories, 'global_rank_compare');
625  if ( empty($related_categories) )
626  {
627    return new PwgError(401, 'Access denied');
628  }
629
630  //-------------------------------------------------------------- related tags
631  $related_tags = get_common_tags( array($image_row['id']), -1 );
632  foreach( $related_tags as $i=>$tag)
633  {
634    $tag['url'] = make_index_url(
635        array(
636          'tags' => array($tag)
637          )
638      );
639    $tag['page_url'] = make_picture_url(
640        array(
641          'image_id' => $image_row['id'],
642          'image_file' => $image_row['file'],
643          'tags' => array($tag),
644          )
645      );
646    unset($tag['counter']);
647    $tag['id']=(int)$tag['id'];
648    $related_tags[$i]=$tag;
649  }
650  //------------------------------------------------------------- related rates
651  $query = '
652SELECT COUNT(rate) AS count
653     , ROUND(AVG(rate),2) AS average
654     , ROUND(STD(rate),2) AS stdev
655  FROM '.RATE_TABLE.'
656  WHERE element_id = '.$image_row['id'].'
657;';
658  $rating = mysql_fetch_assoc(pwg_query($query));
659  $rating['count'] = (int)$rating['count'];
660
661  //---------------------------------------------------------- related comments
662  $related_comments = array();
663
664  $where_comments = 'image_id = '.$image_row['id'];
665  if ( !is_admin() )
666  {
667    $where_comments .= '
668    AND validated="true"';
669  }
670
671  $query = '
672SELECT COUNT(id) nb_comments
673  FROM '.COMMENTS_TABLE.'
674  WHERE '.$where_comments;
675  list($nb_comments) = array_from_query($query, 'nb_comments');
676  $nb_comments = (int)$nb_comments;
677
678  if ( $nb_comments>0 and $params['comments_per_page']>0 )
679  {
680    $query = '
681SELECT id, date, author, content
682  FROM '.COMMENTS_TABLE.'
683  WHERE '.$where_comments.'
684  ORDER BY date
685  LIMIT '.(int)($params['comments_per_page']*$params['comments_page']).
686    ','.(int)$params['comments_per_page'];
687
688    $result = pwg_query($query);
689    while ($row = mysql_fetch_assoc($result))
690    {
691      $row['id']=(int)$row['id'];
692      array_push($related_comments, $row);
693    }
694  }
695
696  $comment_post_data = null;
697  if ($is_commentable and
698      (!is_a_guest()
699        or (is_a_guest() and $conf['comments_forall'] )
700      )
701      )
702  {
703    $comment_post_data['author'] = $user['username'];
704    $comment_post_data['key'] = get_comment_post_key($params['image_id']);
705  }
706
707  $ret = $image_row;
708  foreach ( array('id','width','height','hit','filesize') as $k )
709  {
710    if (isset($ret[$k]))
711    {
712      $ret[$k] = (int)$ret[$k];
713    }
714  }
715  foreach ( array('path', 'storage_category_id') as $k )
716  {
717    unset($ret[$k]);
718  }
719
720  $ret['rates'] = array( WS_XML_ATTRIBUTES => $rating );
721  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
722  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','name','page_url') );
723  if ( isset($comment_post_data) )
724  {
725    $ret['comment_post'] = array( WS_XML_ATTRIBUTES => $comment_post_data );
726  }
727  $ret['comments'] = array(
728     WS_XML_ATTRIBUTES =>
729        array(
730          'page' => $params['comments_page'],
731          'per_page' => $params['comments_per_page'],
732          'count' => count($related_comments),
733          'nb_comments' => $nb_comments,
734        ),
735     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id','date') )
736      );
737
738  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
739}
740
741
742/**
743 * rates the image_id in the parameter
744 */
745function ws_images_Rate($params, &$service)
746{
747  $image_id = (int)$params['image_id'];
748  $query = '
749SELECT DISTINCT id FROM '.IMAGES_TABLE.'
750  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
751  WHERE id='.$image_id
752  .get_sql_condition_FandF(
753    array(
754        'forbidden_categories' => 'category_id',
755        'forbidden_images' => 'id',
756      ),
757    '    AND'
758    ).'
759    LIMIT 1';
760  if ( mysql_num_rows( pwg_query($query) )==0 )
761  {
762    return new PwgError(404, "Invalid image_id or access denied" );
763  }
764  $rate = (int)$params['rate'];
765  include_once(PHPWG_ROOT_PATH.'include/functions_rate.inc.php');
766  $res = rate_picture( $image_id, $rate );
767  if ($res==false)
768  {
769    global $conf;
770    return new PwgError( 403, "Forbidden or rate not in ". implode(',',$conf['rate_items']));
771  }
772  return $res;
773}
774
775
776/**
777 * returns a list of elements corresponding to a query search
778 */
779function ws_images_search($params, &$service)
780{
781  global $page;
782  $images = array();
783  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
784  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
785
786  $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
787  $order_by = ws_std_image_sql_order($params, 'i.');
788
789  $super_order_by = false;
790  if ( !empty($order_by) )
791  {
792    global $conf;
793    $conf['order_by'] = 'ORDER BY '.$order_by;
794    $super_order_by=true; // quick_search_result might be faster
795  }
796
797  $search_result = get_quick_search_results($params['query'],
798      $super_order_by,
799      implode(',', $where_clauses)
800    );
801
802  $image_ids = array_slice(
803      $search_result['items'],
804      $params['page']*$params['per_page'],
805      $params['per_page']
806    );
807
808  if ( count($image_ids) )
809  {
810    $query = '
811SELECT * FROM '.IMAGES_TABLE.'
812  WHERE id IN ('.implode(',', $image_ids).')';
813
814    $image_ids = array_flip($image_ids);
815    $result = pwg_query($query);
816    while ($row = mysql_fetch_assoc($result))
817    {
818      $image = array();
819      foreach ( array('id', 'width', 'height', 'hit') as $k )
820      {
821        if (isset($row[$k]))
822        {
823          $image[$k] = (int)$row[$k];
824        }
825      }
826      foreach ( array('file', 'name', 'comment') as $k )
827      {
828        $image[$k] = $row[$k];
829      }
830      $image = array_merge( $image, ws_std_get_urls($row) );
831      $images[$image_ids[$image['id']]] = $image;
832    }
833    ksort($images, SORT_NUMERIC);
834    $images = array_values($images);
835  }
836
837
838  return array( 'images' =>
839    array (
840      WS_XML_ATTRIBUTES =>
841        array(
842            'page' => $params['page'],
843            'per_page' => $params['per_page'],
844            'count' => count($images)
845          ),
846       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
847          ws_std_get_image_xml_attributes() )
848      )
849    );
850}
851
852function ws_images_setPrivacyLevel($params, &$service)
853{
854  if (!is_admin() || is_adviser() )
855  {
856    return new PwgError(401, 'Access denied');
857  }
858  $params['image_id'] = array_map( 'intval',$params['image_id'] );
859  if ( empty($params['image_id']) )
860  {
861    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
862  }
863  global $conf;
864  if ( !in_array( (int)$params['level'], $conf['available_permission_levels']) )
865  {
866    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid level");
867  }
868  $query = '
869UPDATE '.IMAGES_TABLE.'
870  SET level='.(int)$params['level'].'
871  WHERE id IN ('.implode(',',$params['image_id']).')';
872  $result = pwg_query($query);
873  $affected_rows = mysql_affected_rows();
874  if ($affected_rows)
875  {
876    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
877    invalidate_user_cache();
878  }
879  return $affected_rows;
880}
881
882function ws_images_add($params, &$service)
883{
884  global $conf;
885  if (!is_admin() || is_adviser() )
886  {
887    return new PwgError(401, 'Access denied');
888  }
889
890  // name
891  // category_id
892  // file_content
893  // file_sum
894  // thumbnail_content
895  // thumbnail_sum
896  // rank
897
898  // $fh_log = fopen('/tmp/php.log', 'w');
899  // fwrite($fh_log, time()."\n");
900  // fwrite($fh_log, 'input rank :'.$params['rank']."\n");
901  // fwrite($fh_log, 'input:  '.$params['file_sum']."\n");
902  // fwrite($fh_log, 'input:  '.$params['thumbnail_sum']."\n");
903
904  // does the image already exists ?
905  $query = '
906SELECT
907    COUNT(*) AS counter
908  FROM '.IMAGES_TABLE.'
909  WHERE md5sum = \''.$params['original_sum'].'\'
910;';
911  list($counter) = mysql_fetch_row(pwg_query($query));
912  if ($counter != 0) {
913    return new PwgError(500, 'file already exists');
914  }
915
916  // current date
917  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
918  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
919
920  // upload directory hierarchy
921  $upload_dir = sprintf(
922    PHPWG_ROOT_PATH.'upload/%s/%s/%s',
923    $year,
924    $month,
925    $day
926    );
927
928  //fwrite($fh_log, $upload_dir."\n");
929
930  // create the upload directory tree if not exists
931  if (!is_dir($upload_dir)) {
932    umask(0000);
933    $recursive = true;
934    if (!@mkdir($upload_dir, 0777, $recursive))
935    {
936      return new PwgError(500, 'error during directory creation');
937    }
938  }
939
940  if (!is_writable($upload_dir))
941  {
942    // last chance to make the directory writable
943    @chmod($upload_dir, 0777);
944
945    if (!is_writable($upload_dir))
946    {
947      return new PwgError(500, 'directory has no write access');
948    }
949  }
950
951  secure_directory($upload_dir);
952
953  // compute file path
954  $date_string = preg_replace('/[^\d]/', '', $dbnow);
955  $random_string = substr($params['file_sum'], 0, 8);
956  $filename_wo_ext = $date_string.'-'.$random_string;
957  $file_path = $upload_dir.'/'.$filename_wo_ext.'.jpg';
958
959  // dump the photo file
960  $fh_file = fopen($file_path, 'w');
961  if (!fwrite($fh_file, base64_decode($params['file_content'])))
962  {
963    return new PwgError(500, 'error while writing file');
964  }
965  fclose($fh_file);
966  chmod($file_path, 0644);
967
968  // check dumped file md5sum against expected md5sum
969  $dumped_md5 = md5_file($file_path);
970  if ($dumped_md5 != $params['file_sum']) {
971    return new PwgError(500, 'file transfer failed');
972  }
973
974  // thumbnail directory is a subdirectory of the photo file, hard coded
975  // "thumbnail"
976  $thumbnail_dir = $upload_dir.'/thumbnail';
977  if (!is_dir($thumbnail_dir)) {
978    umask(0000);
979    if (!@mkdir($thumbnail_dir, 0777))
980    {
981      return new PwgError(500, 'error during thumbnail directory creation');
982    }
983  }
984
985  if (!is_writable($thumbnail_dir))
986  {
987    // last chance to make the directory writable
988    @chmod($thumbnail_dir, 0777);
989
990    if (!is_writable($thumbnail_dir))
991    {
992      return new PwgError(500, 'thumbnail directory has no write access');
993    }
994  }
995
996  secure_directory($thumbnail_dir);
997
998  // thumbnail path, the filename may use a prefix and the extension is
999  // always "jpg" (no matter what the real file format is)
1000  $thumbnail_path = sprintf(
1001    '%s/%s%s.%s',
1002    $thumbnail_dir,
1003    $conf['prefix_thumbnail'],
1004    $filename_wo_ext,
1005    'jpg'
1006    );
1007
1008  // dump the thumbnail
1009  $fh_thumbnail = fopen($thumbnail_path, 'w');
1010  if (!fwrite($fh_thumbnail, base64_decode($params['thumbnail_content'])))
1011  {
1012    return new PwgError(500, 'error while writing thumbnail');
1013  }
1014  fclose($fh_thumbnail);
1015  chmod($thumbnail_path, 0644);
1016
1017  // check dumped thumbnail md5
1018  $dumped_md5 = md5_file($thumbnail_path);
1019  if ($dumped_md5 != $params['thumbnail_sum']) {
1020    return new PwgError(500, 'thumbnail transfer failed');
1021  }
1022
1023  // high resolution
1024  if (isset($params['high_content']))
1025  {
1026    // high resolution directory is a subdirectory of the photo file, hard
1027    // coded "pwg_high"
1028    $high_dir = $upload_dir.'/pwg_high';
1029    if (!is_dir($high_dir)) {
1030      umask(0000);
1031      if (!@mkdir($high_dir, 0777))
1032      {
1033        return new PwgError(500, 'error during high directory creation');
1034      }
1035    }
1036
1037    if (!is_writable($high_dir))
1038    {
1039      // last chance to make the directory writable
1040      @chmod($high_dir, 0777);
1041
1042      if (!is_writable($high_dir))
1043      {
1044        return new PwgError(500, 'high directory has no write access');
1045      }
1046    }
1047
1048    secure_directory($high_dir);
1049
1050    // high resolution path, same name as web size file
1051    $high_path = sprintf(
1052      '%s/%s.%s',
1053      $high_dir,
1054      $filename_wo_ext,
1055      'jpg'
1056      );
1057
1058    // dump the high resolution file
1059    $fh_high = fopen($high_path, 'w');
1060    if (!fwrite($fh_high, base64_decode($params['high_content'])))
1061    {
1062      return new PwgError(500, 'error while writing high');
1063    }
1064    fclose($fh_high);
1065    chmod($high_path, 0644);
1066
1067    // check dumped thumbnail md5
1068    $dumped_md5 = md5_file($high_path);
1069    if ($dumped_md5 != $params['high_sum']) {
1070      return new PwgError(500, 'high resolution transfer failed');
1071    }
1072
1073    $high_filesize = floor(filesize($high_path)/1024);
1074  }
1075
1076  list($width, $height) = getimagesize($file_path);
1077
1078  // database registration
1079  $insert = array(
1080    'file' => $filename_wo_ext.'.jpg',
1081    'date_available' => $dbnow,
1082    'tn_ext' => 'jpg',
1083    'name' => $params['name'],
1084    'path' => $file_path,
1085    'filesize' => floor(filesize($file_path)/1024),
1086    'width' => $width,
1087    'height' => $height,
1088    'md5sum' => $params['original_sum'],
1089    );
1090
1091  $info_columns = array(
1092    'name',
1093    'author',
1094    'comment',
1095    'level',
1096    'date_creation',
1097    );
1098
1099  foreach ($info_columns as $key)
1100  {
1101    if (isset($params[$key]))
1102    {
1103      $insert[$key] = $params[$key];
1104    }
1105  }
1106
1107  if (isset($params['high_content']))
1108  {
1109    $insert['has_high'] = 'true';
1110    $insert['high_filesize'] = $high_filesize;
1111  }
1112
1113  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1114  mass_inserts(
1115    IMAGES_TABLE,
1116    array_keys($insert),
1117    array($insert)
1118    );
1119
1120  $image_id = mysql_insert_id();
1121
1122  // let's add links between the image and the categories
1123  if (isset($params['categories']))
1124  {
1125    ws_add_image_category_relations($image_id, $params['categories']);
1126  }
1127
1128  // and now, let's create tag associations
1129  if (isset($params['tag_ids']))
1130  {
1131    set_tags(
1132      explode(',', $params['tag_ids']),
1133      $image_id
1134      );
1135  }
1136
1137  invalidate_user_cache();
1138
1139  // fclose($fh_log);
1140}
1141
1142/**
1143 * perform a login (web service method)
1144 */
1145function ws_session_login($params, &$service)
1146{
1147  global $conf;
1148
1149  if (!$service->isPost())
1150  {
1151    return new PwgError(405, "This method requires HTTP POST");
1152  }
1153  if (try_log_user($params['username'], $params['password'],false))
1154  {
1155    return true;
1156  }
1157  return new PwgError(999, 'Invalid username/password');
1158}
1159
1160
1161/**
1162 * performs a logout (web service method)
1163 */
1164function ws_session_logout($params, &$service)
1165{
1166  if (!is_a_guest())
1167  {
1168    logout_user();
1169  }
1170  return true;
1171}
1172
1173function ws_session_getStatus($params, &$service)
1174{
1175  global $user;
1176  $res = array();
1177  $res['username'] = is_a_guest() ? 'guest' : $user['username'];
1178  foreach ( array('status', 'template', 'theme', 'language') as $k )
1179  {
1180    $res[$k] = $user[$k];
1181  }
1182  $res['charset'] = get_pwg_charset();
1183  return $res;
1184}
1185
1186
1187/**
1188 * returns a list of tags (web service method)
1189 */
1190function ws_tags_getList($params, &$service)
1191{
1192  $tags = get_available_tags();
1193  if ($params['sort_by_counter'])
1194  {
1195    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
1196  }
1197  else
1198  {
1199    usort($tags, 'tag_alpha_compare');
1200  }
1201  for ($i=0; $i<count($tags); $i++)
1202  {
1203    $tags[$i]['id'] = (int)$tags[$i]['id'];
1204    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
1205    $tags[$i]['url'] = make_index_url(
1206        array(
1207          'section'=>'tags',
1208          'tags'=>array($tags[$i])
1209        )
1210      );
1211  }
1212  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'name', 'counter' )) );
1213}
1214
1215/**
1216 * returns the list of tags as you can see them in administration (web
1217 * service method).
1218 *
1219 * Only admin can run this method and permissions are not taken into
1220 * account.
1221 */
1222function ws_tags_getAdminList($params, &$service)
1223{
1224  if (!is_admin())
1225  {
1226    return new PwgError(401, 'Access denied');
1227  }
1228
1229  $tags = get_all_tags();
1230  return array(
1231    'tags' => new PwgNamedArray(
1232      $tags,
1233      'tag',
1234      array(
1235        'name',
1236        'id',
1237        'url_name',
1238        )
1239      )
1240    );
1241}
1242
1243/**
1244 * returns a list of images for tags (web service method)
1245 */
1246function ws_tags_getImages($params, &$service)
1247{
1248  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
1249  global $conf;
1250
1251  // first build all the tag_ids we are interested in
1252  $params['tag_id'] = array_map( 'intval',$params['tag_id'] );
1253  $tags = find_tags($params['tag_id'], $params['tag_url_name'], $params['tag_name']);
1254  $tags_by_id = array();
1255  foreach( $tags as $tag )
1256  {
1257    $tags['id'] = (int)$tag['id'];
1258    $tags_by_id[ $tag['id'] ] = $tag;
1259  }
1260  unset($tags);
1261  $tag_ids = array_keys($tags_by_id);
1262
1263
1264  $image_ids = array();
1265  $image_tag_map = array();
1266
1267  if ( !empty($tag_ids) )
1268  { // build list of image ids with associated tags per image
1269    if ($params['tag_mode_and'])
1270    {
1271      $image_ids = get_image_ids_for_tags( $tag_ids );
1272    }
1273    else
1274    {
1275      $query = '
1276SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
1277  FROM '.IMAGE_TAG_TABLE.'
1278  WHERE tag_id IN ('.implode(',',$tag_ids).')
1279  GROUP BY image_id';
1280      $result = pwg_query($query);
1281      while ( $row=mysql_fetch_assoc($result) )
1282      {
1283        $row['image_id'] = (int)$row['image_id'];
1284        array_push( $image_ids, $row['image_id'] );
1285        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
1286      }
1287    }
1288  }
1289
1290  $images = array();
1291  if ( !empty($image_ids))
1292  {
1293    $where_clauses = ws_std_image_sql_filter($params);
1294    $where_clauses[] = get_sql_condition_FandF(
1295        array
1296          (
1297            'forbidden_categories' => 'category_id',
1298            'visible_categories' => 'category_id',
1299            'visible_images' => 'i.id'
1300          ),
1301        '', true
1302      );
1303    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
1304
1305    $order_by = ws_std_image_sql_order($params);
1306    if (empty($order_by))
1307    {
1308      $order_by = $conf['order_by'];
1309    }
1310    else
1311    {
1312      $order_by = 'ORDER BY '.$order_by;
1313    }
1314
1315    $query = '
1316SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
1317  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
1318  WHERE '. implode('
1319    AND ', $where_clauses).'
1320'.$order_by.'
1321LIMIT '.(int)($params['per_page']*$params['page']).','.(int)$params['per_page'];
1322
1323    $result = pwg_query($query);
1324    while ($row = mysql_fetch_assoc($result))
1325    {
1326      $image = array();
1327      foreach ( array('id', 'width', 'height', 'hit') as $k )
1328      {
1329        if (isset($row[$k]))
1330        {
1331          $image[$k] = (int)$row[$k];
1332        }
1333      }
1334      foreach ( array('file', 'name', 'comment') as $k )
1335      {
1336        $image[$k] = $row[$k];
1337      }
1338      $image = array_merge( $image, ws_std_get_urls($row) );
1339
1340      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
1341      $image_tags = array();
1342      foreach ($image_tag_ids as $tag_id)
1343      {
1344        $url = make_index_url(
1345                 array(
1346                  'section'=>'tags',
1347                  'tags'=> array($tags_by_id[$tag_id])
1348                )
1349              );
1350        $page_url = make_picture_url(
1351                 array(
1352                  'section'=>'tags',
1353                  'tags'=> array($tags_by_id[$tag_id]),
1354                  'image_id' => $row['id'],
1355                  'image_file' => $row['file'],
1356                )
1357              );
1358        array_push($image_tags, array(
1359                'id' => (int)$tag_id,
1360                'url' => $url,
1361                'page_url' => $page_url,
1362              )
1363            );
1364      }
1365      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
1366              array('id','url_name','url','page_url')
1367            );
1368      array_push($images, $image);
1369    }
1370  }
1371
1372  return array( 'images' =>
1373    array (
1374      WS_XML_ATTRIBUTES =>
1375        array(
1376            'page' => $params['page'],
1377            'per_page' => $params['per_page'],
1378            'count' => count($images)
1379          ),
1380       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
1381          ws_std_get_image_xml_attributes() )
1382      )
1383    );
1384}
1385
1386function ws_categories_add($params, &$service)
1387{
1388  if (!is_admin() or is_adviser())
1389  {
1390    return new PwgError(401, 'Access denied');
1391  }
1392
1393  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1394
1395  $creation_output = create_virtual_category(
1396    $params['name'],
1397    $params['parent']
1398    );
1399
1400  if (isset($creation_output['error']))
1401  {
1402    return new PwgError(500, $creation_output['error']);
1403  }
1404
1405  invalidate_user_cache();
1406
1407  return $creation_output;
1408}
1409
1410function ws_tags_add($params, &$service)
1411{
1412  if (!is_admin() or is_adviser())
1413  {
1414    return new PwgError(401, 'Access denied');
1415  }
1416
1417  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1418
1419  $creation_output = create_tag($params['name']);
1420
1421  if (isset($creation_output['error']))
1422  {
1423    return new PwgError(500, $creation_output['error']);
1424  }
1425
1426  return $creation_output;
1427}
1428
1429function ws_images_exist($params, &$service)
1430{
1431  if (!is_admin() or is_adviser())
1432  {
1433    return new PwgError(401, 'Access denied');
1434  }
1435
1436  // search among photos the list of photos already added, based on md5sum
1437  // list
1438  $md5sums = preg_split(
1439    '/[\s,;\|]/',
1440    $params['md5sum_list'],
1441    -1,
1442    PREG_SPLIT_NO_EMPTY
1443    );
1444
1445  $query = '
1446SELECT
1447    id,
1448    md5sum
1449  FROM '.IMAGES_TABLE.'
1450  WHERE md5sum IN (\''.implode("','", $md5sums).'\')
1451;';
1452  $id_of_md5 = simple_hash_from_query($query, 'md5sum', 'id');
1453
1454  $result = array();
1455
1456  foreach ($md5sums as $md5sum)
1457  {
1458    $result[$md5sum] = null;
1459    if (isset($id_of_md5[$md5sum]))
1460    {
1461      $result[$md5sum] = $id_of_md5[$md5sum];
1462    }
1463  }
1464
1465  return $result;
1466}
1467
1468function ws_images_setInfo($params, &$service)
1469{
1470  global $conf;
1471  if (!is_admin() || is_adviser() )
1472  {
1473    return new PwgError(401, 'Access denied');
1474  }
1475
1476  // name
1477  // category_id
1478  // file_content
1479  // file_sum
1480  // thumbnail_content
1481  // thumbnail_sum
1482
1483  $params['image_id'] = (int)$params['image_id'];
1484  if ($params['image_id'] <= 0)
1485  {
1486    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
1487  }
1488
1489  $query='
1490SELECT *
1491  FROM '.IMAGES_TABLE.'
1492  WHERE id = '.$params['image_id'].'
1493;';
1494
1495  $image_row = mysql_fetch_assoc(pwg_query($query));
1496  if ($image_row == null)
1497  {
1498    return new PwgError(404, "image_id not found");
1499  }
1500
1501  // database registration
1502  $update = array(
1503    'id' => $params['image_id'],
1504    );
1505
1506  $info_columns = array(
1507    'name',
1508    'author',
1509    'comment',
1510    'level',
1511    'date_creation',
1512    );
1513
1514  $perform_update = false;
1515  foreach ($info_columns as $key)
1516  {
1517    if (isset($params[$key]))
1518    {
1519      $perform_update = true;
1520      $update[$key] = $params[$key];
1521    }
1522  }
1523
1524  if ($perform_update)
1525  {
1526    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1527    mass_updates(
1528      IMAGES_TABLE,
1529      array(
1530        'primary' => array('id'),
1531        'update'  => array_diff(array_keys($update), array('id'))
1532        ),
1533      array($update)
1534      );
1535  }
1536
1537  if (isset($params['categories']))
1538  {
1539    ws_add_image_category_relations(
1540      $params['image_id'],
1541      $params['categories']
1542      );
1543  }
1544
1545  // and now, let's create tag associations
1546  if (isset($params['tag_ids']))
1547  {
1548    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1549    add_tags(
1550      explode(',', $params['tag_ids']),
1551      array($params['image_id'])
1552      );
1553  }
1554
1555  invalidate_user_cache();
1556}
1557
1558function ws_add_image_category_relations($image_id, $categories_string)
1559{
1560  // let's add links between the image and the categories
1561  //
1562  // $params['categories'] should look like 123,12;456,auto;789 which means:
1563  //
1564  // 1. associate with category 123 on rank 12
1565  // 2. associate with category 456 on automatic rank
1566  // 3. associate with category 789 on automatic rank
1567  $cat_ids = array();
1568  $rank_on_category = array();
1569  $search_current_ranks = false;
1570
1571  $tokens = explode(';', $categories_string);
1572  foreach ($tokens as $token)
1573  {
1574    @list($cat_id, $rank) = explode(',', $token);
1575
1576    array_push($cat_ids, $cat_id);
1577
1578    if (!isset($rank))
1579    {
1580      $rank = 'auto';
1581    }
1582    $rank_on_category[$cat_id] = $rank;
1583
1584    if ($rank == 'auto')
1585    {
1586      $search_current_ranks = true;
1587    }
1588  }
1589
1590  $cat_ids = array_unique($cat_ids);
1591
1592  if (count($cat_ids) > 0)
1593  {
1594    if ($search_current_ranks)
1595    {
1596      $query = '
1597SELECT
1598    category_id,
1599    MAX(rank) AS max_rank
1600  FROM '.IMAGE_CATEGORY_TABLE.'
1601  WHERE rank IS NOT NULL
1602    AND category_id IN ('.implode(',', $cat_ids).')
1603  GROUP BY category_id
1604;';
1605      $current_rank_of = simple_hash_from_query(
1606        $query,
1607        'category_id',
1608        'max_rank'
1609        );
1610
1611      foreach ($cat_ids as $cat_id)
1612      {
1613        if (!isset($current_rank_of[$cat_id]))
1614        {
1615          $current_rank_of[$cat_id] = 0;
1616        }
1617
1618        if ('auto' == $rank_on_category[$cat_id])
1619        {
1620          $rank_on_category[$cat_id] = $current_rank_of[$cat_id] + 1;
1621        }
1622      }
1623    }
1624
1625    $inserts = array();
1626
1627    foreach ($cat_ids as $cat_id)
1628    {
1629      array_push(
1630        $inserts,
1631        array(
1632          'image_id' => $image_id,
1633          'category_id' => $cat_id,
1634          'rank' => $rank_on_category[$cat_id],
1635          )
1636        );
1637    }
1638
1639    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1640    mass_inserts(
1641      IMAGE_CATEGORY_TABLE,
1642      array_keys($inserts[0]),
1643      $inserts
1644      );
1645
1646    update_category($cat_ids);
1647  }
1648}
1649?>
Note: See TracBrowser for help on using the repository browser.