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

Last change on this file since 1744 was 1744, checked in by rvelices, 17 years ago
  • revert feature 564: log the login of each user; but add the possibility to be

done by a plugin

  • create a "standard" way to define PHP functions that we use but might not be

available in the current php version

  • when a comment is rejected (spam, anti-flood etc), put the content back to the

browser in case there is a real user behind it

  • now a comment can be entered only if the page was retrieved between 2 seconds

ago and 1 hour ago

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Rev URL
File size: 19.4 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 1744 2007-01-23 01:22:52Z rvelices $
8// | last update   : $Date: 2007-01-23 01:22:52 +0000 (Tue, 23 Jan 2007) $
9// | last modifier : $Author: rvelices $
10// | revision      : $Rev: 1744 $
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 * returns a "standard" (for our web service) array of sql where clauses that
31 * filters the images (images table only)
32 */
33function ws_std_image_sql_filter( $params, $tbl_name='' )
34{
35  $clauses = array();
36  if ( is_numeric($params['f_min_rate']) )
37  {
38    $clauses[] = $tbl_name.'average_rate>'.$params['f_min_rate'];
39  }
40  if ( is_numeric($params['f_max_rate']) )
41  {
42    $clauses[] = $tbl_name.'average_rate<='.$params['f_max_rate'];
43  }
44  if ( is_numeric($params['f_min_hit']) )
45  {
46    $clauses[] = $tbl_name.'hit>'.$params['f_min_hit'];
47  }
48  if ( is_numeric($params['f_max_hit']) )
49  {
50    $clauses[] = $tbl_name.'hit<='.$params['f_max_hit'];
51  }
52  if ( isset($params['f_min_date_posted']) )
53  {
54    $clauses[] = $tbl_name."date_available>='".$params['f_min_date_posted']."'";
55  }
56  if ( isset($params['f_max_date_posted']) )
57  {
58    $clauses[] = $tbl_name."date_available<'".$params['f_max_date_posted']."'";
59  }
60  if ( isset($params['f_min_date_created']) )
61  {
62    $clauses[] = $tbl_name."date_creation>='".$params['f_min_date_created']."'";
63  }
64  if ( isset($params['f_max_date_created']) )
65  {
66    $clauses[] = $tbl_name."date_creation<'".$params['f_max_date_created']."'";
67  }
68  if ( is_numeric($params['f_min_ratio']) )
69  {
70    $clauses[] = $tbl_name.'width/'.$tbl_name.'height>'.$params['f_min_ratio'];
71  }
72  if ( is_numeric($params['f_max_ratio']) )
73  {
74    $clauses[] = $tbl_name.'width/'.$tbl_name.'height<='.$params['f_max_ratio'];
75  }
76  if ( $params['f_with_thumbnail'] )
77  {
78    $clauses[] = $tbl_name.'tn_ext IS NOT NULL';
79  }
80  return $clauses;
81}
82
83/**
84 * returns a "standard" (for our web service) ORDER BY sql clause for images
85 */
86function ws_std_image_sql_order( $params, $tbl_name='' )
87{
88  $ret = '';
89  if ( empty($params['order']) )
90  {
91    return $ret;
92  }
93  $matches = array();
94  preg_match_all('/([a-z_]+) *(?:(asc|desc)(?:ending)?)? *(?:, *|$)/i',
95    $params['order'], $matches);
96  for ($i=0; $i<count($matches[1]); $i++)
97  {
98    switch ($matches[1][$i])
99    {
100      case 'date_created':
101        $matches[1][$i] = 'date_creation'; break;
102      case 'date_posted':
103        $matches[1][$i] = 'date_available'; break;
104      case 'rand': case 'random':
105        $matches[1][$i] = 'RAND()'; break;
106    }
107    $sortable_fields = array('id', 'file', 'name', 'hit', 'average_rate',
108      'date_creation', 'date_available', 'RAND()' );
109    if ( in_array($matches[1][$i], $sortable_fields) )
110    {
111      if (!empty($ret))
112        $ret .= ', ';
113      if ($matches[1][$i] != 'RAND()' )
114      {
115        $ret .= $tbl_name;
116      }
117      $ret .= $matches[1][$i];
118      $ret .= ' '.$matches[2][$i];
119    }
120  }
121  return $ret;
122}
123
124/**
125 * returns an array map of urls (thumb/element) for image_row - to be returned
126 * in a standard way by different web service methods
127 */
128function ws_std_get_urls($image_row)
129{
130  $ret = array(
131    'tn_url' => get_thumbnail_url($image_row),
132    'element_url' => get_element_url($image_row)
133  );
134  global $user;
135  if ($user['enabled_high'] and $image_row['has_high'] )
136  {
137    $ret['high_url'] = get_high_url($image_row);
138  }
139  return $ret;
140}
141
142
143function ws_getVersion($params, &$service)
144{
145  return PHPWG_VERSION;
146}
147
148/**
149 * returns images per category (wb service method)
150 */
151function ws_categories_getImages($params, &$service)
152{
153  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
154  global $user, $conf;
155
156  $images = array();
157
158  //------------------------------------------------- get the related categories
159  $where_clauses = array();
160  foreach($params['cat_id'] as $cat_id)
161  {
162    $cat_id = (int)$cat_id;
163    if ($cat_id<=0)
164      continue;
165    if ($params['recursive'])
166    {
167      $where_clauses[] = 'uppercats REGEXP \'(^|,)'.$cat_id.'(,|$)\'';
168    }
169    else
170    {
171      $where_clauses[] = 'id='.$cat_id;
172    }
173  }
174  if (!empty($where_clauses))
175  {
176    $where_clauses = array( '('.
177    implode('
178    OR ', $where_clauses) . ')'
179      );
180  }
181  $where_clauses[] = 'id NOT IN ('.$user['forbidden_categories'].')';
182
183  $query = '
184SELECT id, name, image_order
185  FROM '.CATEGORIES_TABLE.'
186  WHERE '. implode('
187    AND ', $where_clauses);
188  $result = pwg_query($query);
189  $cats = array();
190  while ($row = mysql_fetch_assoc($result))
191  {
192    $row['id'] = (int)$row['id'];
193    $cats[ $row['id'] ] = $row;
194  }
195
196  //-------------------------------------------------------- get the images
197  if ( !empty($cats) )
198  {
199    $where_clauses = ws_std_image_sql_filter( $params, 'i.' );
200    $where_clauses[] = 'category_id IN ('
201      .implode(',', array_keys($cats) )
202      .')';
203    $order_by = ws_std_image_sql_order($params, 'i.');
204    if (empty($order_by))
205    {// TODO check for category order by (image_order)
206      $order_by = $conf['order_by'];
207    }
208    else
209    {
210      $order_by = 'ORDER BY '.$order_by;
211    }
212    $query = '
213SELECT i.*, GROUP_CONCAT(category_id) cat_ids
214  FROM '.IMAGES_TABLE.' i
215    INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
216  WHERE '. implode('
217    AND ', $where_clauses).'
218GROUP BY i.id
219'.$order_by.'
220LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
221
222    $result = pwg_query($query);
223    while ($row = mysql_fetch_assoc($result))
224    {
225      $image = array();
226      foreach ( array('id', 'width', 'height', 'hit') as $k )
227      {
228        if (isset($row[$k]))
229        {
230          $image[$k] = (int)$row[$k];
231        }
232      }
233      foreach ( array('name', 'file') as $k )
234      {
235        $image[$k] = $row[$k];
236      }
237      $image = array_merge( $image, ws_std_get_urls($row) );
238
239      $image_cats = array();
240      foreach ( explode(',', $row['cat_ids']) as $cat_id )
241      {
242        $url = make_index_url(
243                array(
244                  'category' => $cat_id,
245                  'cat_name' => $cats[$cat_id]['name'],
246                  )
247                );
248        $page_url = make_picture_url(
249                array(
250                  'category' => $cat_id,
251                  'cat_name' => $cats[$cat_id]['name'],
252                  'image_id' => $row['id'],
253                  'image_file' => $row['file'],
254                  )
255                );
256        array_push( $image_cats,  array(
257              WS_XML_ATTRIBUTES => array (
258                  'id' => (int)$cat_id,
259                  'url' => $url,
260                  'page_url' => $page_url,
261                )
262            )
263          );
264      }
265
266      $image['categories'] = new PwgNamedArray(
267            $image_cats,'category', array('id','url','page_url')
268          );
269      array_push($images, $image);
270    }
271  }
272
273  return array( 'images' =>
274    array (
275      WS_XML_ATTRIBUTES =>
276        array(
277            'page' => $params['page'],
278            'per_page' => $params['per_page'],
279            'count' => count($images)
280          ),
281       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
282          array('id', 'tn_url', 'element_url', 'file','width','height','hit') )
283      )
284    );
285}
286
287/**
288 * returns a list of categories
289 */
290function ws_categories_getList($params, &$service)
291{
292  global $user;
293
294  $where = array();
295  $where[]= 'user_id='.$user['id'];
296  if ($params['cat_id']>0)
297  {
298    $where[] = 'uppercats REGEXP \'(^|,)'.
299      (int)($params['cat_id'])
300      .'(,|$)\'';
301  }
302
303  if (!$params['recursive'])
304  {
305    if ($params['cat_id']>0)
306      $where[] = 'id_uppercat='.(int)($params['cat_id']);
307    else
308      $where[] = 'id_uppercat IS NULL';
309  }
310
311  if ($params['public'])
312  {
313    $where[] = 'status = "public"';
314    $where[] = 'visible = "true"';
315  }
316  else
317  {
318    $where[] = 'id NOT IN ('.$user['forbidden_categories'].')';
319  }
320
321  $query = '
322SELECT id, name, uppercats, global_rank,
323    max_date_last, count_images AS nb_images, count_categories AS nb_categories
324  FROM '.CATEGORIES_TABLE.'
325   INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.' ON id=cat_id
326  WHERE '. implode('
327    AND ', $where);
328  $query .= '
329ORDER BY global_rank';
330
331  $result = pwg_query($query);
332
333  $cats = array();
334  while ($row = mysql_fetch_assoc($result))
335  {
336    $row['url'] = make_index_url(
337        array(
338          'category' => $row['id'],
339          'cat_name' => $row['name'],
340          )
341      );
342    foreach( array('id','nb_images','nb_categories') as $key)
343    {
344      $row[$key] = (int)$row[$key];
345    }
346    array_push($cats, $row);
347  }
348  usort($cats, 'global_rank_compare');
349  return array(
350      'categories' =>
351          new PwgNamedArray($cats,'category',
352            array('id','url','nb_images','nb_categories','max_date_last')
353          )
354    );
355}
356
357function ws_images_getInfo($params, &$service)
358{
359  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
360  global $user;
361  $params['image_id'] = (int)$params['image_id'];
362  if ( $params['image_id']<=0 )
363  {
364    return new PwgError(WS_ERR_INVALID_PARAM, "Invalid image_id");
365  }
366  $query='
367SELECT * FROM '.IMAGES_TABLE.'
368  WHERE id='.$params['image_id'].
369    get_sql_condition_FandF(
370      array('visible_images' => 'id'),
371      ' AND'
372    ).'
373LIMIT 1';
374
375  $image_row = mysql_fetch_assoc(pwg_query($query));
376  if ($image_row==null)
377  {
378    return new PwgError(999, "image_id not found");
379  }
380  array_merge( $image_row, ws_std_get_urls($image_row) );
381
382  //-------------------------------------------------------- related categories
383  $query = '
384SELECT c.id,c.name,c.uppercats,c.global_rank
385  FROM '.IMAGE_CATEGORY_TABLE.'
386    INNER JOIN '.CATEGORIES_TABLE.' c ON category_id = id
387  WHERE image_id = '.$image_row['id'].'
388    AND category_id NOT IN ('.$user['forbidden_categories'].')
389;';
390  $result = pwg_query($query);
391  $related_categories = array();
392  while ($row = mysql_fetch_assoc($result))
393  {
394    $row['url'] = make_index_url(
395        array(
396          'category' => $row['id'],
397          'cat_name' => $row['name'],
398          )
399      );
400
401    $row['page_url'] = make_picture_url(
402        array(
403          'image_id' => $image_row['id'],
404          'image_file' => $image_row['file'],
405          'category' => $row['id'],
406          'cat_name' => $row['name'],
407          )
408      );
409    array_push($related_categories, $row);
410  }
411  usort($related_categories, 'global_rank_compare');
412  if ( empty($related_categories) )
413  {
414    return new PwgError(401, 'Access denied');
415  }
416
417  //-------------------------------------------------------------- related tags
418  $query = '
419SELECT id, name, url_name
420  FROM '.IMAGE_TAG_TABLE.'
421    INNER JOIN '.TAGS_TABLE.' ON tag_id = id
422  WHERE image_id = '.$image_row['id'].'
423;';
424  $result = pwg_query($query);
425  $related_tags = array();
426  while ($row = mysql_fetch_assoc($result))
427  {
428    $row['url'] = make_index_url(
429        array(
430          'tags' => array($row)
431          )
432      );
433    $row['page_url'] = make_picture_url(
434        array(
435          'image_id' => $image_row['id'],
436          'image_file' => $image_row['file'],
437          'tags' => array($row),
438          )
439      );
440    array_push($related_tags, $row);
441  }
442  //---------------------------------------------------------- related comments
443  $query = '
444SELECT COUNT(id) nb_comments
445  FROM '.COMMENTS_TABLE.'
446  WHERE image_id = '.$image_row['id'];
447  list($nb_comments) = array_from_query($query, 'nb_comments');
448
449  $query = '
450SELECT id, date, author, content
451  FROM '.COMMENTS_TABLE.'
452  WHERE image_id = '.$image_row['id'].'
453    AND validated="true"';
454  $query .= '
455  ORDER BY date DESC
456  LIMIT 0, 5';
457
458  $result = pwg_query($query);
459  $related_comments = array();
460  while ($row = mysql_fetch_assoc($result))
461  {
462    array_push($related_comments, $row);
463  }
464
465  //------------------------------------------------------------- related rates
466  $query = '
467SELECT COUNT(rate) AS count
468     , ROUND(AVG(rate),2) AS average
469     , ROUND(STD(rate),2) AS stdev
470  FROM '.RATE_TABLE.'
471  WHERE element_id = '.$image_row['id'].'
472;';
473  $row = mysql_fetch_assoc(pwg_query($query));
474
475  $ret = $image_row;
476  $ret['rates'] = array( WS_XML_ATTRIBUTES => $row );
477  $ret['categories'] = new PwgNamedArray($related_categories, 'category', array('id','url', 'page_url') );
478  $ret['tags'] = new PwgNamedArray($related_tags, 'tag', array('id','url_name','url','page_url') );
479  $ret['comments'] = array(
480     WS_XML_ATTRIBUTES => array('nb_comments' => $nb_comments),
481     WS_XML_CONTENT => new PwgNamedArray($related_comments, 'comment', array('id') )
482      );
483  unset($ret['path']);
484  unset($ret['storage_category_id']);
485  return new PwgNamedStruct('image',$ret, null, array('name','comment') );
486}
487
488
489function ws_session_login($params, &$service)
490{
491  global $conf;
492
493  if (!$service->isPost())
494  {
495    return new PwgError(400, "This method requires POST");
496  }
497  if (try_log_user($params['username'], $params['password'],false))
498  {
499    return true;
500  }
501  return new PwgError(999, 'Invalid username/password');
502}
503
504function ws_session_logout($params, &$service)
505{
506  global $user, $conf;
507  if (!$user['is_the_guest'])
508  {
509    $_SESSION = array();
510    session_unset();
511    session_destroy();
512    setcookie(session_name(),'',0,
513        ini_get('session.cookie_path'),
514        ini_get('session.cookie_domain')
515      );
516    setcookie($conf['remember_me_name'], '', 0, cookie_path());
517  }
518  return true;
519}
520
521function ws_session_getStatus($params, &$service)
522{
523  global $user;
524  $res = array();
525  $res['username'] = $user['is_the_guest'] ? 'guest' : $user['username'];
526  $res['status'] = $user['status'];
527  return $res;
528}
529
530
531function ws_tags_getList($params, &$service)
532{
533  global $user;
534  $tags = get_available_tags();
535  if ($params['sort_by_counter'])
536  {
537    usort($tags, create_function('$a,$b', 'return -$a["counter"]+$b["counter"];') );
538  }
539  else
540  {
541    usort($tags, 'name_compare');
542  }
543  for ($i=0; $i<count($tags); $i++)
544  {
545    $tags[$i]['id'] = (int)$tags[$i]['tag_id'];
546    $tags[$i]['counter'] = (int)$tags[$i]['counter'];
547    unset($tags[$i]['tag_id']);
548    $tags[$i]['url'] = make_index_url(
549        array(
550          'section'=>'tags',
551          'tags'=>array($tags[$i])
552        )
553      );
554  }
555  return array('tags' => new PwgNamedArray($tags, 'tag', array('id','url_name','url', 'counter' )) );
556}
557
558function ws_tags_getImages($params, &$service)
559{
560  @include_once(PHPWG_ROOT_PATH.'include/functions_picture.inc.php');
561  global $user, $conf;
562
563  // first build all the tag_ids we are interested in
564  $tag_ids = array();
565  $tags = get_available_tags();
566  $tags_by_id = array();
567  for( $i=0; $i<count($tags); $i++ )
568  {
569    $tags[$i]['tag_id']=(int)$tags[$i]['tag_id'];
570    $tags[$i]['id']=(int)$tags[$i]['tag_id']; //required by make_xxx_url
571  }
572  foreach( $tags as $tag )
573  {
574    $tags_by_id[ $tag['tag_id'] ] = $tag;
575    if (
576        in_array($tag['name'], $params['tag_name'])
577      or
578        in_array($tag['url_name'], $params['tag_url_name'])
579       )
580    {
581      $tag_ids[] = $tag['tag_id'];
582    }
583  }
584  unset($tags);
585
586  foreach( $params['tag_id'] as $tag_id )
587  {
588    if ( (int)$tag_id > 0 )
589    {
590      $tag_ids[] = $tag_id;
591    }
592  }
593
594  $tag_ids = array_unique( $tag_ids );
595
596  $image_ids = array();
597  $image_tag_map = array();
598
599  if ( !empty($tag_ids) )
600  { // build list of image ids with associated tags per image
601    if ($params['tag_mode_and'])
602    {
603      $image_ids = get_image_ids_for_tags( $tag_ids );
604    }
605    else
606    {
607      $query = '
608SELECT image_id, GROUP_CONCAT(tag_id) tag_ids
609  FROM '.IMAGE_TAG_TABLE.'
610  WHERE tag_id IN ('.implode(',',$tag_ids).')
611  GROUP BY image_id';
612      $result = pwg_query($query);
613      while ( $row=mysql_fetch_assoc($result) )
614      {
615        $row['image_id'] = (int)$row['image_id'];
616        array_push( $image_ids, $row['image_id'] );
617        $image_tag_map[ $row['image_id'] ] = explode(',', $row['tag_ids']);
618      }
619    }
620  }
621
622  $images = array();
623  if ( !empty($image_ids))
624  {
625    $where_clauses = ws_std_image_sql_filter($params);
626    $where_clauses[] = get_sql_condition_FandF(
627        array
628          (
629            'forbidden_categories' => 'category_id',
630            'visible_categories' => 'category_id',
631            'visible_images' => 'i.id'
632          ),
633        '', true
634      );
635    $where_clauses[] = 'id IN ('.implode(',',$image_ids).')';
636    $order_by = ws_std_image_sql_order($params);
637    if (empty($order_by))
638    {
639      $order_by = $conf['order_by'];
640    }
641    else
642    {
643      $order_by = 'ORDER BY '.$order_by;
644    }
645
646    $query = '
647SELECT DISTINCT i.* FROM '.IMAGES_TABLE.' i
648  INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
649  WHERE '. implode('
650    AND ', $where_clauses).'
651'.$order_by.'
652LIMIT '.$params['per_page']*$params['page'].','.$params['per_page'];
653
654    $result = pwg_query($query);
655    while ($row = mysql_fetch_assoc($result))
656    {
657      foreach ( array('id', 'width', 'height', 'hit') as $k )
658      {
659        if (isset($row[$k]))
660        {
661          $image[$k] = (int)$row[$k];
662        }
663      }
664      foreach ( array('name', 'file') as $k )
665      {
666        $image[$k] = $row[$k];
667      }
668      $image = array_merge( $image, ws_std_get_urls($row) );
669
670      $image_tag_ids = ($params['tag_mode_and']) ? $tag_ids : $image_tag_map[$image['id']];
671      $image_tags = array();
672      foreach ($image_tag_ids as $tag_id)
673      {
674        $url = make_index_url(
675                 array(
676                  'section'=>'tags',
677                  'tags'=> array($tags_by_id[$tag_id])
678                )
679              );
680        $page_url = make_picture_url(
681                 array(
682                  'section'=>'tags',
683                  'tags'=> array($tags_by_id[$tag_id]),
684                  'image_id' => $row['id'],
685                  'image_file' => $row['file'],
686                )
687              );
688        array_push($image_tags, array(
689                'id' => (int)$tag_id,
690                'url' => $url,
691                'page_url' => $page_url,
692              )
693            );
694      }
695      $image['tags'] = new PwgNamedArray($image_tags, 'tag',
696              array('id','url_name','url','page_url')
697            );
698      array_push($images, $image);
699    }
700  }
701
702  return array( 'images' =>
703    array (
704      WS_XML_ATTRIBUTES =>
705        array(
706            'page' => $params['page'],
707            'per_page' => $params['per_page'],
708            'count' => count($images)
709          ),
710       WS_XML_CONTENT => new PwgNamedArray($images, 'image',
711          array('id', 'tn_url', 'element_url', 'file','width','height','hit') )
712      )
713    );
714}
715
716?>
Note: See TracBrowser for help on using the repository browser.