source: tags/release-1_7_0RC1/include/ws_functions.inc.php @ 22636

Last change on this file since 22636 was 1820, checked in by rvelices, 17 years ago
  • feature 642: display both subcategory thumbnails and element thumbnails (if a

category has both) in the index page

flat category view

  • web service fixes for categories.getList
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision URL
File size: 23.9 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2003-2007 PhpWebGallery Team - http://phpwebgallery.net |
5// +-----------------------------------------------------------------------+
6// | branch        : BSF (Best So Far)
7// | file          : $Id: ws_functions.inc.php 1820 2007-02-15 00:10:41Z rvelices $
8// | last update   : $Date: 2007-02-15 00:10:41 +0000 (Thu, 15 Feb 2007) $
9// | last modifier : $Author: rvelices $
10// | revision      : $Revision: 1820 $
11// +-----------------------------------------------------------------------+
12// | This program is free software; you can redistribute it and/or modify  |
13// | it under the terms of the GNU General Public License as published by  |
14// | the Free Software Foundation                                          |
15// |                                                                       |
16// | This program is distributed in the hope that it will be useful, but   |
17// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
18// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
19// | General Public License for more details.                              |
20// |                                                                       |
21// | You should have received a copy of the GNU General Public License     |
22// | along with this program; if not, write to the Free Software           |
23// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
24// | USA.                                                                  |
25// +-----------------------------------------------------------------------+
26
27/**** IMPLEMENTATION OF WEB SERVICE METHODS ***********************************/
28
29/**
30 * Event handler for method invocation security check. Should return a PwgError
31 * if the preconditions are not satifsied for method invocation.
32 */
33function ws_isInvokeAllowed($res, $methodName, $params)
34{
35  global $conf, $calling_partner_id;
36  if ( !$conf['ws_access_control']
37       or strpos($methodName,'reflection.')===0 )
38  {
39    return $res; // No controls are requested
40  }
41  $query = '
42SELECT * FROM '.WEB_SERVICES_ACCESS_TABLE."
43 WHERE `name` = '$calling_partner_id'
44   AND NOW() <= end; ";
45  $result = pwg_query($query);
46  $row = mysql_fetch_assoc($result);
47  if ( empty($row) )
48  {
49    return new PwgError(403, 'Partner id does not exist or is expired');
50  }
51  if ( !empty($row['request'])
52      and strpos($methodName, $row['request'])==false )
53  {
54    return new PwgError(403, 'Method not allowed');
55  }
56
57  return $res;
58}
59
60/**
61 * ws_addControls
62 * returns additionnal controls if requested
63 * usable for 99% of Web Service methods
64 *
65 * - Args
66 * $methodName: is the requested method
67 * $partner: is the key
68 * $tbl_name: is the alias_name in the query (sometimes called correlation name)
69 *            null if !getting picture informations
70 * - Logic
71 * Access_control is not active: Return
72 * Key is incorrect: Return 0 = 1 (False condition for MySQL)
73 * One of Params doesn't match with type of request: return 0 = 1 again
74 * Access list(id/cat/tag) is converted in expended image-id list
75 * image-id list: converted to an in-where-clause
76 *
77 * The additionnal in-where-clause is return
78 */
79function ws_addControls( $methodName, &$params, $tbl_name )
80{
81  global $conf, $calling_partner_id;
82  if ( !$conf['ws_access_control'] or !isset($calling_partner_id) )
83  {
84    return '1=1'; // No controls are requested
85  }
86
87// Is it an active Partner?
88  $query = '
89SELECT * FROM '.WEB_SERVICES_ACCESS_TABLE."
90 WHERE `name` = '$calling_partner_id'
91   AND NOW() <= end; ";
92$result = pwg_query($query);
93  if ( mysql_num_rows( $result ) == 0 )
94  {
95    return '0=1'; // Unknown partner or Obsolate agreement
96  }
97
98  $row = mysql_fetch_array($result);
99
100// Overide general object limit
101  $params['per_page'] = $row['limit'];
102
103// Target restrict
104// 3 cases: list, cat or tag
105// Behind / we could found img-ids, cat-ids or tag-ids
106  $target = $row['access'];
107  list($type, $str_ids) = explode('/',$target); // Find type list
108
109// (array) 1,2,21,3,22,4,5,9-12,6,11,12,13,2,4,6,
110  $arr_ids = expand_id_list( explode( ',',$str_ids ) );
111  $addings = implode(',', $arr_ids);
112// (string) 1,2,3,4,5,6,9,10,11,12,13,21,22,
113  if ( $type == 'list')
114  {
115    return $tbl_name . 'id IN ( ' . $addings . ' ) ';
116  }
117
118  if ( $type == 'cat' )
119  {
120    $addings = implode(',', get_image_ids_for_cats($arr_ids));
121    return $tbl_name . 'id IN ( ' . $addings . ' ) ';
122  }
123
124  if ( $type == 'tag' )
125  {
126    $addings = implode(',', get_image_ids_for_tags($arr_ids, 'OR'));
127    return $tbl_name . 'id IN ( ' . $addings . ' ) ';
128  }
129  // Unmanaged new type?
130  return ' 0 = 1 '; // ???
131}
132
133/**
134 * returns a "standard" (for our web service) array of sql where clauses that
135 * filters the images (images table only)
136 */
137function ws_std_image_sql_filter( $params, $tbl_name='' )
138{
139  $clauses = array();
140  if ( is_numeric($params['f_min_rate']) )
141  {
142    $clauses[] = $tbl_name.'average_rate>'.$params['f_min_rate'];
143  }
144  if ( is_numeric($params['f_max_rate']) )
145  {
146    $clauses[] = $tbl_name.'average_rate<='.$params['f_max_rate'];
147  }
148  if ( is_numeric($params['f_min_hit']) )
149  {
150    $clauses[] = $tbl_name.'hit>'.$params['f_min_hit'];
151  }
152  if ( is_numeric($params['f_max_hit']) )
153  {
154    $clauses[] = $tbl_name.'hit<='.$params['f_max_hit'];
155  }
156  if ( isset($params['f_min_date_posted']) )
157  {
158    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_posted']."'";
159  }
160  if ( isset($params['f_max_date_posted']) )
161  {
162    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_posted']."'";
163  }
164  if ( isset($params['f_min_date_created']) )
165  {
166    $clauses[] = $tbl_name."date_creation>='".$params['f_min_date_created']."'";
167  }
168  if ( isset($params['f_max_date_created']) )
169  {
170    $clauses[] = $tbl_name."date_creation<'".$params['f_max_date_created']."'";
171  }
172  if ( is_numeric($params['f_min_ratio']) )
173  {
174    $clauses[] = $tbl_name.'width/'.$tbl_name.'height>'.$params['f_min_ratio'];
175  }
176  if ( is_numeric($params['f_max_ratio']) )
177  {
178    $clauses[] = $tbl_name.'width/'.$tbl_name.'height<='.$params['f_max_ratio'];
179  }
180  if ( $params['f_with_thumbnail'] )
181  {
182    $clauses[] = $tbl_name.'tn_ext IS NOT NULL';
183  }
184  return $clauses;
185}
186
187/**
188 * returns a "standard" (for our web service) ORDER BY sql clause for images
189 */
190function ws_std_image_sql_order( $params, $tbl_name='' )
191{
192  $ret = '';
193  if ( empty($params['order']) )
194  {
195    return $ret;
196  }
197  $matches = array();
198  preg_match_all('/([a-z_]+) *(?:(asc|desc)(?:ending)?)? *(?:, *|$)/i',
199    $params['order'], $matches);
200  for ($i=0; $i<count($matches[1]); $i++)
201  {
202    switch ($matches[1][$i])
203    {
204      case 'date_created':
205        $matches[1][$i] = 'date_creation'; break;
206      case 'date_posted':
207        $matches[1][$i] = 'date_available'; break;
208      case 'rand': case 'random':
209        $matches[1][$i] = 'RAND()'; break;
210    }
211    $sortable_fields = array('id', 'file', 'name', 'hit', 'average_rate',
212      'date_creation', 'date_available', 'RAND()' );
213    if ( in_array($matches[1][$i], $sortable_fields) )
214    {
215      if (!empty($ret))
216        $ret .= ', ';
217      if ($matches[1][$i] != 'RAND()' )
218      {
219        $ret .= $tbl_name;
220      }
221      $ret .= $matches[1][$i];
222      $ret .= ' '.$matches[2][$i];
223    }
224  }
225  return $ret;
226}
227
228/**
229 * returns an array map of urls (thumb/element) for image_row - to be returned
230 * in a standard way by different web service methods
231 */
232function ws_std_get_urls($image_row)
233{
234  $ret = array(
235    'tn_url' => get_thumbnail_url($image_row),
236    'element_url' => get_element_url($image_row)
237  );
238  global $user;
239  if ($user['enabled_high'] and $image_row['has_high'] )
240  {
241    $ret['high_url'] = get_high_url($image_row);
242  }
243  return $ret;
244}
245
246
247/**
248 * returns PWG version (web service method)
249 */
250function ws_getVersion($params, &$service)
251{
252//  TODO = Version availability is under control of $conf['show_version']
253  return PHPWG_VERSION;
254}
255
256
257/**
258 * returns images per category (web service method)
259 */
260function ws_categories_getImages($params, &$service)
261{
262  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
263  global $user, $conf;
264
265  $images = array();
266
267  //------------------------------------------------- get the related categories
268  $where_clauses = array();
269  foreach($params['cat_id'] as $cat_id)
270  {
271    $cat_id = (int)$cat_id;
272    if ($cat_id<=0)
273      continue;
274    if ($params['recursive'])
275    {
276      $where_clauses[] = 'uppercats REGEXP \'(^|,)'.$cat_id.'(,|$)\'';
277    }
278    else
279    {
280      $where_clauses[] = 'id='.$cat_id;
281    }
282  }
283  if (!empty($where_clauses))
284  {
285    $where_clauses = array( '('.
286    implode('
287    OR ', $where_clauses) . ')'
288      );
289  }
290  $where_clauses[] = 'id NOT IN ('.$user['forbidden_categories'].')';
291
292  $query = '
293SELECT id, name, image_order
294  FROM '.CATEGORIES_TABLE.'
295  WHERE '. implode('
296    AND ', $where_clauses);
297  $result = pwg_query($query);
298  $cats = array();
299  while ($row = mysql_fetch_assoc($result))
300  {
301    $row['id'] = (int)$row['id'];
302    $cats[ $row['id'] ] = $row;
303  }
304
305  //-------------------------------------------------------- get the images
306  if ( !empty($cats) )
307  {
308    $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
309    $where_clauses[] = 'category_id IN ('
310      .implode(',', array_keys($cats) )
311      .')';
312    $where_clauses[] = get_sql_condition_FandF( array(
313          'visible_images' => 'i.id'
314        ), null, true
315      );
316    $where_clauses[] = ws_addControls( 'categories.getImages', $params, 'i.' );
317
318    $order_by = ws_std_image_sql_order($params, 'i.');
319    if (empty($order_by))
320    {// TODO check for category order by (image_order)
321      $order_by = $conf['order_by'];
322    }
323    else
324    {
325      $order_by = 'ORDER BY '.$order_by;
326    }
327    $query = '
328SELECT i.*, GROUP_CONCAT(category_id) cat_ids
329  FROM '.IMAGES_TABLE.' i
330    INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
331  WHERE '. implode('
332    AND ', $where_clauses).'
333GROUP BY i.id
334'.$order_by.'
335LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
336
337    $result = pwg_query($query);
338    while ($row = mysql_fetch_assoc($result))
339    {
340      $image = array();
341      foreach ( array('id', 'width', 'height', 'hit') as $k )
342      {
343        if (isset($row[$k]))
344        {
345          $image[$k] = (int)$row[$k];
346        }
347      }
348      foreach ( array('name', 'file') as $k )
349      {
350        $image[$k] = $row[$k];
351      }
352      $image = array_merge( $image, ws_std_get_urls($row) );
353
354      $image_cats = array();
355      foreach ( explode(',', $row['cat_ids']) as $cat_id )
356      {
357        $url = make_index_url(
358                array(
359                  'category' => $cat_id,
360                  'cat_name' => $cats[$cat_id]['name'],
361                  )
362                );
363        $page_url = make_picture_url(
364                array(
365                  'category' => $cat_id,
366                  'cat_name' => $cats[$cat_id]['name'],
367                  'image_id' => $row['id'],
368                  'image_file' => $row['file'],
369                  )
370                );
371        array_push( $image_cats,  array(
372              WS_XML_ATTRIBUTES => array (
373                  'id' => (int)$cat_id,
374                  'url' => $url,
375                  'page_url' => $page_url,
376                )
377            )
378          );
379      }
380
381      $image['categories'] = new PwgNamedArray(
382            $image_cats,'category', array('id','url','page_url')
383          );
384      array_push($images, $image);
385    }
386  }
387
388  return array( 'images' =>
389    array (
390      WS_XML_ATTRIBUTES =>
391        array(
392            'page' => $params['page'],
393            'per_page' => $params['per_page'],
394            'count' => count($images)
395          ),
396       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
397          array('id', 'tn_url', 'element_url', 'file','width','height','hit') )
398      )
399    );
400}
401
402
403/**
404 * returns a list of categories (web service method)
405 */
406function ws_categories_getList($params, &$service)
407{
408  global $user,$conf;
409
410  $where = array();
411
412  if (!$params['recursive'])
413  {
414    if ($params['cat_id']>0)
415      $where[] = '(id_uppercat='.(int)($params['cat_id']).'
416    OR id='.(int)($params['cat_id']).')';
417    else
418      $where[] = 'id_uppercat IS NULL';
419  }
420  else if ($params['cat_id']>0)
421  {
422    $where[] = 'uppercats REGEXP \'(^|,)'.
423      (int)($params['cat_id'])
424      .'(,|$)\'';
425  }
426
427  if ($params['public'])
428  {
429    $where[] = 'status = "public"';
430    $where[] = 'visible = "true"';
431    $where[]= 'user_id='.$conf['guest_id'];
432  }
433  else
434  {
435    $where[] = 'id NOT IN ('.$user['forbidden_categories'].')';
436    $where[]= 'user_id='.$user['id'];
437  }
438
439  $query = '
440SELECT id, name, uppercats, global_rank,
441    max_date_last, count_images AS nb_images, count_categories AS nb_categories
442  FROM '.CATEGORIES_TABLE.'
443   INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id
444  WHERE '. implode('
445    AND ', $where);
446  $query .= '
447ORDER BY global_rank';
448
449  $result = pwg_query($query);
450
451  $cats = array();
452  while ($row = mysql_fetch_assoc($result))
453  {
454    $row['url'] = make_index_url(
455        array(
456          'category' => $row['id'],
457          'cat_name' => $row['name'],
458          )
459      );
460    foreach( array('id','nb_images','nb_categories') as $key)
461    {
462      $row[$key] = (int)$row[$key];
463    }
464    array_push($cats, $row);
465  }
466  usort($cats, 'global_rank_compare');
467  return array(
468      'categories' =>
469          new PwgNamedArray($cats,'category',
470            array('id','url','nb_images','nb_categories','max_date_last')
471          )
472    );
473}
474
475
476/**
477 * returns detailed information for an element (web service method)
478 */
479function ws_images_getInfo($params, &$service)
480{
481  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
482  global $user;
483  $params['image_id'] = (int)$params['image_id'];
484  if ( $params['image_id']<=0 )
485  {
486    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
487  }
488
489  $query='
490SELECT * FROM '.IMAGES_TABLE.'
491  WHERE id='.$params['image_id'].
492    get_sql_condition_FandF(
493      array('visible_images' => 'id'),
494      ' AND'
495    ).' AND '.
496    ws_addControls( 'images.getInfo', $params, '' ).'
497LIMIT 1;';
498
499  $image_row = mysql_fetch_assoc(pwg_query($query));
500  if ($image_row==null)
501  {
502    return new PwgError(999, "image_id not found");
503  }
504  array_merge( $image_row, ws_std_get_urls($image_row) );
505
506  //-------------------------------------------------------- related categories
507  $query = '
508SELECT c.id,c.name,c.uppercats,c.global_rank
509  FROM '.IMAGE_CATEGORY_TABLE.'
510    INNER JOIN '.CATEGORIES_TABLE.' c ON category_id = id
511  WHERE image_id = '.$image_row['id'].'
512    AND category_id NOT IN ('.$user['forbidden_categories'].')
513;';
514  $result = pwg_query($query);
515  $related_categories = array();
516  while ($row = mysql_fetch_assoc($result))
517  {
518    $row['url'] = make_index_url(
519        array(
520          'category' => $row['id'],
521          'cat_name' => $row['name'],
522          )
523      );
524
525    $row['page_url'] = make_picture_url(
526        array(
527          'image_id' => $image_row['id'],
528          'image_file' => $image_row['file'],
529          'category' => $row['id'],
530          'cat_name' => $row['name'],
531          )
532      );
533    array_push($related_categories, $row);
534  }
535  usort($related_categories, 'global_rank_compare');
536  if ( empty($related_categories) )
537  {
538    return new PwgError(401, 'Access denied');
539  }
540
541  //-------------------------------------------------------------- related tags
542  $related_tags = get_common_tags( array($image_row['id']), -1 );
543  foreach( $related_tags as $i=>$tag)
544  {
545    $tag['url'] = make_index_url(
546        array(
547          'tags' => array($tag)
548          )
549      );
550    $tag['page_url'] = make_picture_url(
551        array(
552          'image_id' => $image_row['id'],
553          'image_file' => $image_row['file'],
554          'tags' => array($tag),
555          )
556      );
557    unset($tag['counter']);
558    $related_tags[$i]=$tag;
559  }
560  //---------------------------------------------------------- related comments
561  $query = '
562SELECT COUNT(id) nb_comments
563  FROM '.COMMENTS_TABLE.'
564  WHERE image_id = '.$image_row['id'];
565  list($nb_comments) = array_from_query($query, 'nb_comments');
566
567  $query = '
568SELECT id, date, author, content
569  FROM '.COMMENTS_TABLE.'
570  WHERE image_id = '.$image_row['id'].'
571    AND validated="true"';
572  $query .= '
573  ORDER BY date DESC
574  LIMIT 0, 5';
575
576  $result = pwg_query($query);
577  $related_comments = array();
578  while ($row = mysql_fetch_assoc($result))
579  {
580    array_push($related_comments, $row);
581  }
582
583  //------------------------------------------------------------- related rates
584  $query = '
585SELECT COUNT(rate) AS count
586     , ROUND(AVG(rate),2) AS average
587     , ROUND(STD(rate),2) AS stdev
588  FROM '.RATE_TABLE.'
589  WHERE element_id = '.$image_row['id'].'
590;';
591  $row = mysql_fetch_assoc(pwg_query($query));
592
593  $ret = $image_row;
594  $ret['rates'] = array( WS_XML_ATTRIBUTES => $row );
595  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
596  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','page_url') );
597  $ret['comments'] = array(
598     WS_XML_ATTRIBUTES => array('nb_comments' => $nb_comments),
599     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id') )
600      );
601  unset($ret['path']);
602  unset($ret['storage_category_id']);
603  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
604}
605
606
607/**
608 * perform a login (web service method)
609 */
610function ws_session_login($params, &$service)
611{
612  global $conf;
613
614  if (!$service->isPost())
615  {
616    return new PwgError(400, "This method requires POST");
617  }
618  if (try_log_user($params['username'], $params['password'],false))
619  {
620    return true;
621  }
622  return new PwgError(999, 'Invalid username/password');
623}
624
625
626/**
627 * performs a logout (web service method)
628 */
629function ws_session_logout($params, &$service)
630{
631  global $user, $conf;
632  if (!$user['is_the_guest'])
633  {
634    $_SESSION = array();
635    session_unset();
636    session_destroy();
637    setcookie(session_name(),'',0,
638        ini_get('session.cookie_path'),
639        ini_get('session.cookie_domain')
640      );
641    setcookie($conf['remember_me_name'], '', 0, cookie_path());
642  }
643  return true;
644}
645
646function ws_session_getStatus($params, &$service)
647{
648  global $user;
649  $res = array();
650  $res['username'] = $user['is_the_guest'] ? 'guest' : $user['username'];
651  $res['status'] = $user['status'];
652  return $res;
653}
654
655
656/**
657 * returns a list of tags (web service method)
658 */
659function ws_tags_getList($params, &$service)
660{
661  $tags = get_available_tags();
662  if ($params['sort_by_counter'])
663  {
664    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
665  }
666  else
667  {
668    usort($tags, 'name_compare');
669  }
670  for ($i=0; $i<count($tags); $i++)
671  {
672    $tags[$i]['id'] = (int)$tags[$i]['id'];
673    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
674    $tags[$i]['url'] = make_index_url(
675        array(
676          'section'=>'tags',
677          'tags'=>array($tags[$i])
678        )
679      );
680  }
681  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'counter' )) );
682}
683
684
685/**
686 * returns a list of images for tags (web service method)
687 */
688function ws_tags_getImages($params, &$service)
689{
690  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
691  global $conf;
692
693  // first build all the tag_ids we are interested in
694  $tag_ids = array();
695  $tags = get_available_tags();
696  $tags_by_id = array();
697  for( $i=0; $i<count($tags); $i++ )
698  {
699    $tags[$i]['id']=(int)$tags[$i]['id'];
700  }
701  foreach( $tags as $tag )
702  {
703    $tags_by_id[ $tag['id'] ] = $tag;
704    if (
705        in_array($tag['name'], $params['tag_name'])
706      or
707        in_array($tag['url_name'], $params['tag_url_name'])
708      or
709        in_array($tag['id'], $params['tag_id'])
710       )
711    {
712      $tag_ids[] = $tag['id'];
713    }
714  }
715  unset($tags);
716
717  $tag_ids = array_unique( $tag_ids );
718
719  $image_ids = array();
720  $image_tag_map = array();
721
722  if ( !empty($tag_ids) )
723  { // build list of image ids with associated tags per image
724    if ($params['tag_mode_and'])
725    {
726      $image_ids = get_image_ids_for_tags( $tag_ids );
727    }
728    else
729    {
730      $query = '
731SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
732  FROM '.IMAGE_TAG_TABLE.'
733  WHERE tag_id IN ('.implode(',',$tag_ids).')
734  GROUP BY image_id';
735      $result = pwg_query($query);
736      while ( $row=mysql_fetch_assoc($result) )
737      {
738        $row['image_id'] = (int)$row['image_id'];
739        array_push( $image_ids, $row['image_id'] );
740        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
741      }
742    }
743  }
744
745  $images = array();
746  if ( !empty($image_ids))
747  {
748    $where_clauses = ws_std_image_sql_filter($params);
749    $where_clauses[] = get_sql_condition_FandF(
750        array
751          (
752            'forbidden_categories' => 'category_id',
753            'visible_categories' => 'category_id',
754            'visible_images' => 'i.id'
755          ),
756        '', true
757      );
758    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
759    $where_clauses[] = ws_addControls( 'tags.getImages', $params, 'i.' );
760
761    $order_by = ws_std_image_sql_order($params);
762    if (empty($order_by))
763    {
764      $order_by = $conf['order_by'];
765    }
766    else
767    {
768      $order_by = 'ORDER BY '.$order_by;
769    }
770
771    $query = '
772SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
773  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
774  WHERE '. implode('
775    AND ', $where_clauses).'
776'.$order_by.'
777LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
778
779    $result = pwg_query($query);
780    while ($row = mysql_fetch_assoc($result))
781    {
782      foreach ( array('id', 'width', 'height', 'hit') as $k )
783      {
784        if (isset($row[$k]))
785        {
786          $image[$k] = (int)$row[$k];
787        }
788      }
789      foreach ( array('name', 'file') as $k )
790      {
791        $image[$k] = $row[$k];
792      }
793      $image = array_merge( $image, ws_std_get_urls($row) );
794
795      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
796      $image_tags = array();
797      foreach ($image_tag_ids as $tag_id)
798      {
799        $url = make_index_url(
800                 array(
801                  'section'=>'tags',
802                  'tags'=> array($tags_by_id[$tag_id])
803                )
804              );
805        $page_url = make_picture_url(
806                 array(
807                  'section'=>'tags',
808                  'tags'=> array($tags_by_id[$tag_id]),
809                  'image_id' => $row['id'],
810                  'image_file' => $row['file'],
811                )
812              );
813        array_push($image_tags, array(
814                'id' => (int)$tag_id,
815                'url' => $url,
816                'page_url' => $page_url,
817              )
818            );
819      }
820      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
821              array('id','url_name','url','page_url')
822            );
823      array_push($images, $image);
824    }
825  }
826
827  return array( 'images' =>
828    array (
829      WS_XML_ATTRIBUTES =>
830        array(
831            'page' => $params['page'],
832            'per_page' => $params['per_page'],
833            'count' => count($images)
834          ),
835       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
836          array('id', 'tn_url', 'element_url', 'file','width','height','hit') )
837      )
838    );
839}
840
841
842/**
843 * expand_id_list($ids) convert a human list expression to a full ordered list
844 * example : expand_id_list( array(5,2-3,2) ) returns array( 2, 3, 5)
845 * */
846function expand_id_list($ids)
847{
848  $tid = array();
849  foreach ( $ids as $id )
850  {
851    if ( is_numeric($id) )
852    {
853      $tid[] = (int) $id;
854    }
855    else
856    {
857      $range = explode( '-', $id );
858      if ( is_numeric($range[0]) and is_numeric($range[1]) )
859      {
860        $from = min($range[0],$range[1]);
861        $to = max($range[0],$range[1]);
862        for ($i = $from; $i <= $to; $i++)
863        {
864          $tid[] = (int) $i;
865        }
866      }
867    }
868  }
869  $result = array_unique ($tid); // remove duplicates...
870  sort ($result);
871  return $result;
872}
873
874
875/**
876 * converts a cat-ids array in image-ids array
877 * FIXME Function which should already exist somewhere else
878 * */
879function get_image_ids_for_cats($cat_ids)
880{
881  $cat_list = implode(',', $cat_ids);
882  $ret_ids = array();
883  $query = '
884  SELECT DISTINCT image_id
885    FROM '.IMAGE_CATEGORY_TABLE.'
886  WHERE category_id in ('.$cat_list.')
887  ;';
888  return array_from_query($query, 'image_id');
889}
890
891?>
Note: See TracBrowser for help on using the repository browser.