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

Last change on this file since 1768 was 1768, checked in by rvelices, 17 years ago

web services: give vincent the calling partner id

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Rev URL
File size: 26.2 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 1768 2007-01-29 20:38:08Z rvelices $
8// | last update   : $Date: 2007-01-29 20:38:08 +0000 (Mon, 29 Jan 2007) $
9// | last modifier : $Author: rvelices $
10// | revision      : $Rev: 1768 $
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  {
38    return $res; // No controls are requested
39  }
40  $query = '
41SELECT * FROM '.WEB_SERVICES_ACCESS_TABLE."
42 WHERE `name` = '$calling_partner_id'
43   AND NOW() <= end; ";
44  $result = pwg_query($query);
45  $row = mysql_fetch_assoc($result);
46  if ( empty($row) )
47  {
48    return new PwgError(403, 'Partner id does not exist');
49  }
50  return $res;
51}
52
53/**
54 * ws_add_controls
55 * returns additionnal controls if requested
56 * usable for 99% of Web Service methods
57 *
58 * - Args 
59 * $method: is the requested method
60 * $partner: is the key
61 * $tbl_name: is the alias_name in the query (sometimes called correlation name)
62 *            null if !getting picture informations
63 * - Logic
64 * Access_control is not active: Return
65 * Key is incorrect: Return 0 = 1 (False condition for MySQL) 
66 * One of Params doesn't match with type of request: return 0 = 1 again
67 * Access list(id/cat/tag) is converted in expended image-id list
68 * image-id list: converted to an in-where-clause
69 *   
70 * The additionnal in-where-clause is return
71 */       
72function ws_add_controls( $method, $tbl_name )
73{
74  global $conf, $partner;
75  if ( !$conf['ws_access_control'] )
76  {
77    return ' 1 = 1 '; // No controls are requested
78  }
79 
80// Is it an active Partner?
81  $query = '
82SELECT * FROM '.WEB_SERVICES_ACCESS_TABLE."
83 WHERE `name` = '$partner'
84   AND NOW() <= end; ";
85$result = pwg_query($query);
86  if ( mysql_num_rows( $result ) == 0 )
87  {     
88    return ' 0 = 1 '; // Unknown partner or Obsolate agreement
89  }
90 
91  $row = mysql_fetch_array($result);
92
93// Method / Request matching
94// Generic is not ready
95// For generic you can say... tags. or categories. or images. maybe?
96  $filter = $row['request'];
97  $request_method = substr($method, 0, strlen($filter)) ;
98  if ( $filter !== $filter_method )
99  {
100    return ' 0 = 1'; // Unauthorized method request
101  }
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  $ids = explode( ',',$str_ids );
110// (array) 1,2,21,3,22,4,5,9-12,6,11,12,13,2,4,6,
111  $arr_ids = expand_id_list( $ids );
112  $addings = implode(',', $arr_ids); 
113// (string) 1,2,3,4,5,6,9,10,11,12,13,21,22,
114  if ( $type = 'list')
115  {
116    return $tbl_name . 'id IN ( ' . $addings . ' ) ';
117  }
118 
119  if ( $type = 'cat' )
120  {
121    $addings = implode(',', get_image_ids_for_cats($arr_ids));
122    return $tbl_name . 'id IN ( ' . $addings . ' ) ';
123  }
124 
125  if ( $type = 'tag' )
126  { 
127    $addings = implode(',', get_image_ids_for_tags($arr_ids, 'OR'));
128    return $tbl_name . 'id IN ( ' . $addings . ' ) ';
129  }
130  // Unmanaged new type?
131  return ' 0 = 1 '; // ???
132}
133
134/**
135 * returns a "standard" (for our web service) array of sql where clauses that
136 * filters the images (images table only)
137 */
138function ws_std_image_sql_filter( $params, $tbl_name='' )
139{
140  $clauses = array();
141  if ( is_numeric($params['f_min_rate']) )
142  {
143    $clauses[] = $tbl_name.'average_rate>'.$params['f_min_rate'];
144  }
145  if ( is_numeric($params['f_max_rate']) )
146  {
147    $clauses[] = $tbl_name.'average_rate<='.$params['f_max_rate'];
148  }
149  if ( is_numeric($params['f_min_hit']) )
150  {
151    $clauses[] = $tbl_name.'hit>'.$params['f_min_hit'];
152  }
153  if ( is_numeric($params['f_max_hit']) )
154  {
155    $clauses[] = $tbl_name.'hit<='.$params['f_max_hit'];
156  }
157  if ( isset($params['f_min_date_posted']) )
158  {
159    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_posted']."'";
160  }
161  if ( isset($params['f_max_date_posted']) )
162  {
163    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_posted']."'";
164  }
165  if ( isset($params['f_min_date_created']) )
166  {
167    $clauses[] = $tbl_name."date_creation>='".$params['f_min_date_created']."'";
168  }
169  if ( isset($params['f_max_date_created']) )
170  {
171    $clauses[] = $tbl_name."date_creation<'".$params['f_max_date_created']."'";
172  }
173  if ( is_numeric($params['f_min_ratio']) )
174  {
175    $clauses[] = $tbl_name.'width/'.$tbl_name.'height>'.$params['f_min_ratio'];
176  }
177  if ( is_numeric($params['f_max_ratio']) )
178  {
179    $clauses[] = $tbl_name.'width/'.$tbl_name.'height<='.$params['f_max_ratio'];
180  }
181  if ( $params['f_with_thumbnail'] )
182  {
183    $clauses[] = $tbl_name.'tn_ext IS NOT NULL';
184  }
185  return $clauses;
186}
187
188/**
189 * returns a "standard" (for our web service) ORDER BY sql clause for images
190 */
191function ws_std_image_sql_order( $params, $tbl_name='' )
192{
193  $ret = '';
194  if ( empty($params['order']) )
195  {
196    return $ret;
197  }
198  $matches = array();
199  preg_match_all('/([a-z_]+) *(?:(asc|desc)(?:ending)?)? *(?:, *|$)/i',
200    $params['order'], $matches);
201  for ($i=0; $i<count($matches[1]); $i++)
202  {
203    switch ($matches[1][$i])
204    {
205      case 'date_created':
206        $matches[1][$i] = 'date_creation'; break;
207      case 'date_posted':
208        $matches[1][$i] = 'date_available'; break;
209      case 'rand': case 'random':
210        $matches[1][$i] = 'RAND()'; break;
211    }
212    $sortable_fields = array('id', 'file', 'name', 'hit', 'average_rate',
213      'date_creation', 'date_available', 'RAND()' );
214    if ( in_array($matches[1][$i], $sortable_fields) )
215    {
216      if (!empty($ret))
217        $ret .= ', ';
218      if ($matches[1][$i] != 'RAND()' )
219      {
220        $ret .= $tbl_name;
221      }
222      $ret .= $matches[1][$i];
223      $ret .= ' '.$matches[2][$i];
224    }
225  }
226  return $ret;
227}
228
229/**
230 * returns an array map of urls (thumb/element) for image_row - to be returned
231 * in a standard way by different web service methods
232 */
233function ws_std_get_urls($image_row)
234{
235  $ret = array(
236    'tn_url' => get_thumbnail_url($image_row),
237    'element_url' => get_element_url($image_row)
238  );
239  global $user;
240  if ($user['enabled_high'] and $image_row['has_high'] )
241  {
242    $ret['high_url'] = get_high_url($image_row);
243  }
244  return $ret;
245}
246
247
248function ws_getVersion($params, &$service)
249{
250//  Needed for security reason... Maybe???
251//  $where_clause[] =
252//          ws_add_controls( 'getVersion', null );
253  return PHPWG_VERSION;
254}
255
256/**
257 * returns images per category (wb service method)
258 */
259function ws_categories_getImages($params, &$service)
260{
261  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
262  global $user, $conf;
263
264  $images = array();
265
266  //------------------------------------------------- get the related categories
267  $where_clauses = array();
268  foreach($params['cat_id'] as $cat_id)
269  {
270    $cat_id = (int)$cat_id;
271    if ($cat_id<=0)
272      continue;
273    if ($params['recursive'])
274    {
275      $where_clauses[] = 'uppercats REGEXP \'(^|,)'.$cat_id.'(,|$)\'';
276    }
277    else
278    {
279      $where_clauses[] = 'id='.$cat_id;
280    }
281  }
282  if (!empty($where_clauses))
283  {
284    $where_clauses = array( '('.
285    implode('
286    OR ', $where_clauses) . ')'
287      );
288  }
289  $where_clauses[] = 'id NOT IN ('.$user['forbidden_categories'].')';
290
291  $query = '
292SELECT id, name, image_order
293  FROM '.CATEGORIES_TABLE.'
294  WHERE '. implode('
295    AND ', $where_clauses);
296  $result = pwg_query($query);
297  $cats = array();
298  while ($row = mysql_fetch_assoc($result))
299  {
300    $row['id'] = (int)$row['id'];
301    $cats[ $row['id'] ] = $row;
302  }
303
304  //-------------------------------------------------------- get the images
305  if ( !empty($cats) )
306  {
307    $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
308    $where_clauses[] = 'category_id IN ('
309      .implode(',', array_keys($cats) )
310      .')';
311
312//  Mandatory
313//  $where_clause[] =
314//          ws_add_controls( 'categories.getImages', 'i.' );
315   
316    $order_by = ws_std_image_sql_order($params, 'i.');
317    if (empty($order_by))
318    {// TODO check for category order by (image_order)
319      $order_by = $conf['order_by'];
320    }
321    else
322    {
323      $order_by = 'ORDER BY '.$order_by;
324    }
325    $query = '
326SELECT i.*, GROUP_CONCAT(category_id) cat_ids
327  FROM '.IMAGES_TABLE.' i
328    INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
329  WHERE '. implode('
330    AND ', $where_clauses).'
331GROUP BY i.id
332'.$order_by.'
333LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
334
335    $result = pwg_query($query);
336    while ($row = mysql_fetch_assoc($result))
337    {
338      $image = array();
339      foreach ( array('id', 'width', 'height', 'hit') as $k )
340      {
341        if (isset($row[$k]))
342        {
343          $image[$k] = (int)$row[$k];
344        }
345      }
346      foreach ( array('name', 'file') as $k )
347      {
348        $image[$k] = $row[$k];
349      }
350      $image = array_merge( $image, ws_std_get_urls($row) );
351
352      $image_cats = array();
353      foreach ( explode(',', $row['cat_ids']) as $cat_id )
354      {
355        $url = make_index_url(
356                array(
357                  'category' => $cat_id,
358                  'cat_name' => $cats[$cat_id]['name'],
359                  )
360                );
361        $page_url = make_picture_url(
362                array(
363                  'category' => $cat_id,
364                  'cat_name' => $cats[$cat_id]['name'],
365                  'image_id' => $row['id'],
366                  'image_file' => $row['file'],
367                  )
368                );
369        array_push( $image_cats,  array(
370              WS_XML_ATTRIBUTES => array (
371                  'id' => (int)$cat_id,
372                  'url' => $url,
373                  'page_url' => $page_url,
374                )
375            )
376          );
377      }
378
379      $image['categories'] = new PwgNamedArray(
380            $image_cats,'category', array('id','url','page_url')
381          );
382      array_push($images, $image);
383    }
384  }
385
386  return array( 'images' =>
387    array (
388      WS_XML_ATTRIBUTES =>
389        array(
390            'page' => $params['page'],
391            'per_page' => $params['per_page'],
392            'count' => count($images)
393          ),
394       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
395          array('id', 'tn_url', 'element_url', 'file','width','height','hit') )
396      )
397    );
398}
399
400/**
401 * returns a list of categories
402 */
403function ws_categories_getList($params, &$service)
404{
405  global $user;
406
407  $where = array();
408  $where[]= 'user_id='.$user['id'];
409  if ($params['cat_id']>0)
410  {
411    $where[] = 'uppercats REGEXP \'(^|,)'.
412      (int)($params['cat_id'])
413      .'(,|$)\'';
414  }
415
416  if (!$params['recursive'])
417  {
418    if ($params['cat_id']>0)
419      $where[] = 'id_uppercat='.(int)($params['cat_id']);
420    else
421      $where[] = 'id_uppercat IS NULL';
422  }
423
424  if ($params['public'])
425  {
426    $where[] = 'status = "public"';
427    $where[] = 'visible = "true"';
428  }
429  else
430  {
431    $where[] = 'id NOT IN ('.$user['forbidden_categories'].')';
432  }
433
434// To ONLY build external links maybe ??? 
435//  $where_clause[] =
436//          ws_add_controls( 'categories.getList', null );
437// Making links in a Blog...
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
475function ws_images_getInfo($params, &$service)
476{
477  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
478  global $user;
479  $params['image_id'] = (int)$params['image_id'];
480  if ( $params['image_id']<=0 )
481  {
482    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
483  }
484// Mandatory (No comment) 
485//  $where_clause[] =
486//          ws_add_controls( 'images.getInfo', '' ); 
487  $query='
488SELECT * FROM '.IMAGES_TABLE.'
489  WHERE id='.$params['image_id'].
490    get_sql_condition_FandF(
491      array('visible_images' => 'id'),
492      ' AND'
493    ).'
494LIMIT 1';
495
496  $image_row = mysql_fetch_assoc(pwg_query($query));
497  if ($image_row==null)
498  {
499    return new PwgError(999, "image_id not found");
500  }
501  array_merge( $image_row, ws_std_get_urls($image_row) );
502
503  //-------------------------------------------------------- related categories
504  $query = '
505SELECT c.id,c.name,c.uppercats,c.global_rank
506  FROM '.IMAGE_CATEGORY_TABLE.'
507    INNER JOIN '.CATEGORIES_TABLE.' c ON category_id = id
508  WHERE image_id = '.$image_row['id'].'
509    AND category_id NOT IN ('.$user['forbidden_categories'].')
510;';
511  $result = pwg_query($query);
512  $related_categories = array();
513  while ($row = mysql_fetch_assoc($result))
514  {
515    $row['url'] = make_index_url(
516        array(
517          'category' => $row['id'],
518          'cat_name' => $row['name'],
519          )
520      );
521
522    $row['page_url'] = make_picture_url(
523        array(
524          'image_id' => $image_row['id'],
525          'image_file' => $image_row['file'],
526          'category' => $row['id'],
527          'cat_name' => $row['name'],
528          )
529      );
530    array_push($related_categories, $row);
531  }
532  usort($related_categories, 'global_rank_compare');
533  if ( empty($related_categories) )
534  {
535    return new PwgError(401, 'Access denied');
536  }
537
538  //-------------------------------------------------------------- related tags
539  $query = '
540SELECT id, name, url_name
541  FROM '.IMAGE_TAG_TABLE.'
542    INNER JOIN '.TAGS_TABLE.' ON tag_id = id
543  WHERE image_id = '.$image_row['id'].'
544;';
545  $result = pwg_query($query);
546  $related_tags = array();
547  while ($row = mysql_fetch_assoc($result))
548  {
549    $row['url'] = make_index_url(
550        array(
551          'tags' => array($row)
552          )
553      );
554    $row['page_url'] = make_picture_url(
555        array(
556          'image_id' => $image_row['id'],
557          'image_file' => $image_row['file'],
558          'tags' => array($row),
559          )
560      );
561    array_push($related_tags, $row);
562  }
563  //---------------------------------------------------------- related comments
564  $query = '
565SELECT COUNT(id) nb_comments
566  FROM '.COMMENTS_TABLE.'
567  WHERE image_id = '.$image_row['id'];
568  list($nb_comments) = array_from_query($query, 'nb_comments');
569
570  $query = '
571SELECT id, date, author, content
572  FROM '.COMMENTS_TABLE.'
573  WHERE image_id = '.$image_row['id'].'
574    AND validated="true"';
575  $query .= '
576  ORDER BY date DESC
577  LIMIT 0, 5';
578
579  $result = pwg_query($query);
580  $related_comments = array();
581  while ($row = mysql_fetch_assoc($result))
582  {
583    array_push($related_comments, $row);
584  }
585
586  //------------------------------------------------------------- related rates
587  $query = '
588SELECT COUNT(rate) AS count
589     , ROUND(AVG(rate),2) AS average
590     , ROUND(STD(rate),2) AS stdev
591  FROM '.RATE_TABLE.'
592  WHERE element_id = '.$image_row['id'].'
593;';
594  $row = mysql_fetch_assoc(pwg_query($query));
595
596  $ret = $image_row;
597  $ret['rates'] = array( WS_XML_ATTRIBUTES => $row );
598  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
599  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','page_url') );
600  $ret['comments'] = array(
601     WS_XML_ATTRIBUTES => array('nb_comments' => $nb_comments),
602     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id') )
603      );
604  unset($ret['path']);
605  unset($ret['storage_category_id']);
606  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
607}
608
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
625function ws_session_logout($params, &$service)
626{
627  global $user, $conf;
628  if (!$user['is_the_guest'])
629  {
630    $_SESSION = array();
631    session_unset();
632    session_destroy();
633    setcookie(session_name(),'',0,
634        ini_get('session.cookie_path'),
635        ini_get('session.cookie_domain')
636      );
637    setcookie($conf['remember_me_name'], '', 0, cookie_path());
638  }
639  return true;
640}
641
642function ws_session_getStatus($params, &$service)
643{
644  global $user;
645  $res = array();
646  $res['username'] = $user['is_the_guest'] ? 'guest' : $user['username'];
647  $res['status'] = $user['status'];
648  return $res;
649}
650
651
652function ws_tags_getList($params, &$service)
653{
654  global $user;
655  $tags = get_available_tags();
656  if ($params['sort_by_counter'])
657  {
658    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
659  }
660  else
661  {
662    usort($tags, 'name_compare');
663  }
664  for ($i=0; $i<count($tags); $i++)
665  {
666    $tags[$i]['id'] = (int)$tags[$i]['tag_id'];
667    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
668    unset($tags[$i]['tag_id']);
669    $tags[$i]['url'] = make_index_url(
670        array(
671          'section'=>'tags',
672          'tags'=>array($tags[$i])
673        )
674      );
675  }
676  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'counter' )) );
677}
678
679function ws_tags_getImages($params, &$service)
680{
681  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
682  global $user, $conf;
683
684  // first build all the tag_ids we are interested in
685  $tag_ids = array();
686  $tags = get_available_tags();
687  $tags_by_id = array();
688  for( $i=0; $i<count($tags); $i++ )
689  {
690    $tags[$i]['tag_id']=(int)$tags[$i]['tag_id'];
691    $tags[$i]['id']=(int)$tags[$i]['tag_id']; //required by make_xxx_url
692  }
693  foreach( $tags as $tag )
694  {
695    $tags_by_id[ $tag['tag_id'] ] = $tag;
696    if (
697        in_array($tag['name'], $params['tag_name'])
698      or
699        in_array($tag['url_name'], $params['tag_url_name'])
700       )
701    {
702      $tag_ids[] = $tag['tag_id'];
703    }
704  }
705  unset($tags);
706
707  foreach( $params['tag_id'] as $tag_id )
708  {
709    if ( (int)$tag_id > 0 )
710    {
711      $tag_ids[] = $tag_id;
712    }
713  }
714
715  $tag_ids = array_unique( $tag_ids );
716
717  $image_ids = array();
718  $image_tag_map = array();
719 
720  if ( !empty($tag_ids) )
721  { // build list of image ids with associated tags per image
722    if ($params['tag_mode_and'])
723    {
724      $image_ids = get_image_ids_for_tags( $tag_ids );
725    }
726    else
727    {
728      $query = '
729SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
730  FROM '.IMAGE_TAG_TABLE.'
731  WHERE tag_id IN ('.implode(',',$tag_ids).')
732  GROUP BY image_id';
733      $result = pwg_query($query);
734      while ( $row=mysql_fetch_assoc($result) )
735      {
736        $row['image_id'] = (int)$row['image_id'];
737        array_push( $image_ids, $row['image_id'] );
738        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
739      }
740    }
741  }
742
743  $images = array();
744  if ( !empty($image_ids))
745  {
746    $where_clauses = ws_std_image_sql_filter($params);
747    $where_clauses[] = get_sql_condition_FandF(
748        array
749          (
750            'forbidden_categories' => 'category_id',
751            'visible_categories' => 'category_id',
752            'visible_images' => 'i.id'
753          ),
754        '', true
755      );
756    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
757// Mandatory 
758//  $where_clause[] =
759//          ws_add_controls( 'tags.getImages', '' ); 
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 * official_req returns the managed requests list in array format
843 * FIXME A New list need to be build for ws_checker.php
844 * returns array of authrorized request/methods
845 * */   
846function official_req()
847{
848  $official = array(                  /* Requests are limited to             */
849      'categories.'                          /* all categories. methods */
850    , 'categories.getImages'                 /* <= see */
851    , 'categories.getList'                   /* <= see */
852    , 'images.'                              /* all images. methods */
853    , 'images.getInfo'                       /* <= see */
854    , 'tags.'                                /* all tags. methods */
855    , 'tags.getImages'                       /* <= see */
856    , 'tags.getList'                         /* <= see */
857  );
858  if (function_exists('local_req')) {
859     $local = local_req();
860     return array_merge( $official, $local );
861  }
862  return $official;
863}
864
865/**
866 * expand_id_list($ids) convert a human list expression to a full ordered list
867 * example : expand_id_list( array(5,2-3,2) ) returns array( 2, 3, 5)
868 * */ 
869function expand_id_list($ids)
870{
871    $tid = array();
872    foreach ( $ids as $id )
873    {
874      if ( is_numeric($id) )
875      {
876        $tid[] = (int) $id;
877      }
878      else
879      {
880        $range = explode( '-', $id );
881        if ( is_numeric($range[0]) and is_numeric($range[1]) )
882        {
883          $from = min($range[0],$range[1]);
884          $to = max($range[0],$range[1]);
885          for ($i = $from; $i <= $to; $i++) 
886          {
887            $tid[] = (int) $i;
888          }
889        }
890      }
891    }
892    $result = array_unique ($tid); // remove duplicates...
893    sort ($result);
894    return $result;
895}
896
897/**
898 * check_target($string) verifies and corrects syntax of target parameter
899 * example : check_target(cat/23,24,24,24,25,27) returns cat/23-25,27
900 * */ 
901function check_target($list)
902{
903  if ( $list !== '' )
904  {
905    $type = explode('/',$list); // Find type list
906    if ( !in_array($type[0],array('list','cat','tag') ) )
907    {
908      $type[0] = 'list'; // Assume an id list
909    } 
910    $ids = explode( ',',$type[1] );
911    $list = $type[0] . '/';
912
913    // 1,2,21,3,22,4,5,9-12,6,11,12,13,2,4,6,
914
915    $result = expand_id_list( $ids ); 
916
917    // 1,2,3,4,5,6,9,10,11,12,13,21,22,
918    // I would like
919    // 1-6,9-13,21-22
920    $serial[] = $result[0]; // To be shifted                     
921    foreach ($result as $k => $id)
922    {
923      $next_less_1 = (isset($result[$k + 1]))? $result[$k + 1] - 1:-1;
924      if ( $id == $next_less_1 and end($serial)=='-' )
925      { // nothing to do
926      }
927      elseif ( $id == $next_less_1 )
928      {
929        $serial[]=$id;
930        $serial[]='-';
931      }
932      else
933      {
934        $serial[]=$id;  // end serie or non serie
935      }
936    }
937    $null = array_shift($serial); // remove first value
938    $list .= array_shift($serial); // add the real first one
939    $separ = ',';
940    foreach ($serial as $id)
941    {
942      $list .= ($id=='-') ? '' : $separ . $id;
943      $separ = ($id=='-') ? '-':','; // add comma except if hyphen
944    }
945  }
946  return $list;
947}
948
949/**
950 * converts a cat-ids array in image-ids array
951 * FIXME Function which should already exist somewhere else
952 * */ 
953function get_image_ids_for_cats($cat_ids)
954{
955  $cat_list = implode(',', $cat_ids);
956  $ret_ids = array();
957  $query = '
958  SELECT DISTINCT image_id
959    FROM '.IMAGE_CATEGORY_TABLE.'
960  WHERE category_id in ('.$cat_list.')
961  ;';
962  return $array_from_query($query, 'image_id');
963}
964
965?>
Note: See TracBrowser for help on using the repository browser.