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

Last change on this file since 1760 was 1760, checked in by vdigital, 17 years ago

Web Service Revise ws_checker and ws_functions.inc.php

(Next steps:

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