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

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

web service: added method to query search elements
picture: small correction on my last commit
monthly calendar nice view: always use getimagesize instead of guessing the size
query search: improved results (filename is searched separately) and sometimes less sql queries than before

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision URL
File size: 26.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 1837 2007-02-19 16:25:47Z rvelices $
8// | last update   : $Date: 2007-02-19 16:25:47 +0000 (Mon, 19 Feb 2007) $
9// | last modifier : $Author: rvelices $
10// | revision      : $Revision: 1837 $
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 * returns a list of elements corresponding to a query search
608 */
609function ws_images_search($params, &$service)
610{
611  global $page;
612  $images = array();
613  include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
614  include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
615
616  $where_clauses = ws_std_image_sql_filter( $params );
617  $order_by = ws_std_image_sql_order($params);
618
619  if ( !empty($where_clauses) and !empty($order_by) )
620  {
621    $page['super_order_by']=1; // quick_search_result might be faster
622  }
623  $search_result = get_quick_search_results($params['query']);
624
625  global $image_ids; //needed for sorting by rank (usort)
626  if ( ( !isset($search_result['as_is'])
627      or !empty($where_clauses)
628      or !empty($order_by) )
629      and !empty($search_result['items']) )
630  {
631    $where_clauses[] = 'id IN ('
632        .wordwrap(implode(', ', $search_result['items']), 80, "\n")
633        .')';
634    $where_clauses[] = get_sql_condition_FandF(
635        array
636          (
637            'forbidden_categories' => 'category_id',
638            'visible_categories' => 'category_id',
639            'visible_images' => 'id'
640          ),
641        '', true
642      );
643    $query = '
644SELECT DISTINCT id FROM '.IMAGES_TABLE.' INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
645  WHERE '.implode('
646    AND ', $where_clauses);
647    if (!empty($order_by))
648    {
649      $query .= '
650  ORDER BY '.$order_by;
651    }
652    $image_ids = array_from_query($query, 'id');
653    global $ranks;
654    $ranks = array_flip( $search_result['items'] );
655    usort(
656      $image_ids,
657      create_function('$i1,$i2', 'global $ranks; return $ranks[$i1]-$ranks[$i2];')
658    );
659    unset ($ranks);
660  }
661  else
662  {
663    $image_ids = $search_result['items'];
664  }
665 
666  $image_ids = array_slice($image_ids,
667    $params['page']*$params['per_page'],
668    $params['per_page'] );
669
670  if ( count($image_ids) )
671  {
672    $query = '
673SELECT * FROM '.IMAGES_TABLE.'
674  WHERE id IN ('
675        .wordwrap(implode(', ', $image_ids), 80, "\n")
676        .')';
677
678    $result = pwg_query($query);
679    while ($row = mysql_fetch_assoc($result))
680    {
681      $image = array();
682      foreach ( array('id', 'width', 'height', 'hit') as $k )
683      {
684        if (isset($row[$k]))
685        {
686          $image[$k] = (int)$row[$k];
687        }
688      }
689      foreach ( array('name', 'file') as $k )
690      {
691        $image[$k] = $row[$k];
692      }
693      $image = array_merge( $image, ws_std_get_urls($row) );
694      array_push($images, $image);
695    }
696
697    $image_ids = array_flip($image_ids);
698    usort(
699        $images,
700        create_function('$i1,$i2', 'global $image_ids; return $image_ids[$i1["id"]]-$image_ids[$i2["id"]];')
701      );
702  }
703
704
705  return array( 'images' =>
706    array (
707      WS_XML_ATTRIBUTES =>
708        array(
709            'page' => $params['page'],
710            'per_page' => $params['per_page'],
711            'count' => count($images)
712          ),
713       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
714          array('id', 'tn_url', 'element_url', 'file','width','height','hit') )
715      )
716    );
717}
718
719/**
720 * perform a login (web service method)
721 */
722function ws_session_login($params, &$service)
723{
724  global $conf;
725
726  if (!$service->isPost())
727  {
728    return new PwgError(400, "This method requires POST");
729  }
730  if (try_log_user($params['username'], $params['password'],false))
731  {
732    return true;
733  }
734  return new PwgError(999, 'Invalid username/password');
735}
736
737
738/**
739 * performs a logout (web service method)
740 */
741function ws_session_logout($params, &$service)
742{
743  global $user, $conf;
744  if (!$user['is_the_guest'])
745  {
746    $_SESSION = array();
747    session_unset();
748    session_destroy();
749    setcookie(session_name(),'',0,
750        ini_get('session.cookie_path'),
751        ini_get('session.cookie_domain')
752      );
753    setcookie($conf['remember_me_name'], '', 0, cookie_path());
754  }
755  return true;
756}
757
758function ws_session_getStatus($params, &$service)
759{
760  global $user;
761  $res = array();
762  $res['username'] = $user['is_the_guest'] ? 'guest' : $user['username'];
763  $res['status'] = $user['status'];
764  return $res;
765}
766
767
768/**
769 * returns a list of tags (web service method)
770 */
771function ws_tags_getList($params, &$service)
772{
773  $tags = get_available_tags();
774  if ($params['sort_by_counter'])
775  {
776    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
777  }
778  else
779  {
780    usort($tags, 'name_compare');
781  }
782  for ($i=0; $i<count($tags); $i++)
783  {
784    $tags[$i]['id'] = (int)$tags[$i]['id'];
785    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
786    $tags[$i]['url'] = make_index_url(
787        array(
788          'section'=>'tags',
789          'tags'=>array($tags[$i])
790        )
791      );
792  }
793  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'counter' )) );
794}
795
796
797/**
798 * returns a list of images for tags (web service method)
799 */
800function ws_tags_getImages($params, &$service)
801{
802  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
803  global $conf;
804
805  // first build all the tag_ids we are interested in
806  $tag_ids = array();
807  $tags = get_available_tags();
808  $tags_by_id = array();
809  for( $i=0; $i<count($tags); $i++ )
810  {
811    $tags[$i]['id']=(int)$tags[$i]['id'];
812  }
813  foreach( $tags as $tag )
814  {
815    $tags_by_id[ $tag['id'] ] = $tag;
816    if (
817        in_array($tag['name'], $params['tag_name'])
818      or
819        in_array($tag['url_name'], $params['tag_url_name'])
820      or
821        in_array($tag['id'], $params['tag_id'])
822       )
823    {
824      $tag_ids[] = $tag['id'];
825    }
826  }
827  unset($tags);
828
829  $tag_ids = array_unique( $tag_ids );
830
831  $image_ids = array();
832  $image_tag_map = array();
833
834  if ( !empty($tag_ids) )
835  { // build list of image ids with associated tags per image
836    if ($params['tag_mode_and'])
837    {
838      $image_ids = get_image_ids_for_tags( $tag_ids );
839    }
840    else
841    {
842      $query = '
843SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
844  FROM '.IMAGE_TAG_TABLE.'
845  WHERE tag_id IN ('.implode(',',$tag_ids).')
846  GROUP BY image_id';
847      $result = pwg_query($query);
848      while ( $row=mysql_fetch_assoc($result) )
849      {
850        $row['image_id'] = (int)$row['image_id'];
851        array_push( $image_ids, $row['image_id'] );
852        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
853      }
854    }
855  }
856
857  $images = array();
858  if ( !empty($image_ids))
859  {
860    $where_clauses = ws_std_image_sql_filter($params);
861    $where_clauses[] = get_sql_condition_FandF(
862        array
863          (
864            'forbidden_categories' => 'category_id',
865            'visible_categories' => 'category_id',
866            'visible_images' => 'i.id'
867          ),
868        '', true
869      );
870    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
871    $where_clauses[] = ws_addControls( 'tags.getImages', $params, 'i.' );
872
873    $order_by = ws_std_image_sql_order($params);
874    if (empty($order_by))
875    {
876      $order_by = $conf['order_by'];
877    }
878    else
879    {
880      $order_by = 'ORDER BY '.$order_by;
881    }
882
883    $query = '
884SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
885  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
886  WHERE '. implode('
887    AND ', $where_clauses).'
888'.$order_by.'
889LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
890
891    $result = pwg_query($query);
892    while ($row = mysql_fetch_assoc($result))
893    {
894      foreach ( array('id', 'width', 'height', 'hit') as $k )
895      {
896        if (isset($row[$k]))
897        {
898          $image[$k] = (int)$row[$k];
899        }
900      }
901      foreach ( array('name', 'file') as $k )
902      {
903        $image[$k] = $row[$k];
904      }
905      $image = array_merge( $image, ws_std_get_urls($row) );
906
907      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
908      $image_tags = array();
909      foreach ($image_tag_ids as $tag_id)
910      {
911        $url = make_index_url(
912                 array(
913                  'section'=>'tags',
914                  'tags'=> array($tags_by_id[$tag_id])
915                )
916              );
917        $page_url = make_picture_url(
918                 array(
919                  'section'=>'tags',
920                  'tags'=> array($tags_by_id[$tag_id]),
921                  'image_id' => $row['id'],
922                  'image_file' => $row['file'],
923                )
924              );
925        array_push($image_tags, array(
926                'id' => (int)$tag_id,
927                'url' => $url,
928                'page_url' => $page_url,
929              )
930            );
931      }
932      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
933              array('id','url_name','url','page_url')
934            );
935      array_push($images, $image);
936    }
937  }
938
939  return array( 'images' =>
940    array (
941      WS_XML_ATTRIBUTES =>
942        array(
943            'page' => $params['page'],
944            'per_page' => $params['per_page'],
945            'count' => count($images)
946          ),
947       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
948          array('id', 'tn_url', 'element_url', 'file','width','height','hit') )
949      )
950    );
951}
952
953
954/**
955 * expand_id_list($ids) convert a human list expression to a full ordered list
956 * example : expand_id_list( array(5,2-3,2) ) returns array( 2, 3, 5)
957 * */
958function expand_id_list($ids)
959{
960  $tid = array();
961  foreach ( $ids as $id )
962  {
963    if ( is_numeric($id) )
964    {
965      $tid[] = (int) $id;
966    }
967    else
968    {
969      $range = explode( '-', $id );
970      if ( is_numeric($range[0]) and is_numeric($range[1]) )
971      {
972        $from = min($range[0],$range[1]);
973        $to = max($range[0],$range[1]);
974        for ($i = $from; $i <= $to; $i++)
975        {
976          $tid[] = (int) $i;
977        }
978      }
979    }
980  }
981  $result = array_unique ($tid); // remove duplicates...
982  sort ($result);
983  return $result;
984}
985
986
987/**
988 * converts a cat-ids array in image-ids array
989 * FIXME Function which should already exist somewhere else
990 * */
991function get_image_ids_for_cats($cat_ids)
992{
993  $cat_list = implode(',', $cat_ids);
994  $ret_ids = array();
995  $query = '
996  SELECT DISTINCT image_id
997    FROM '.IMAGE_CATEGORY_TABLE.'
998  WHERE category_id in ('.$cat_list.')
999  ;';
1000  return array_from_query($query, 'image_id');
1001}
1002
1003?>
Note: See TracBrowser for help on using the repository browser.