source: extensions/rv_gmaps/trunk/include/functions_map.php @ 15907

Last change on this file since 15907 was 13092, checked in by rvelices, 12 years ago

rv_gmaps compatible with core version 2.4

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 14.5 KB
Line 
1<?php
2/* Reminder about urls
3map      unused but passes flat to map_data ...
4map_data automatic show flat, start is unused
5mapl     automatic show flat, start is used in GET only (blowup)
6kml      if flat network links, start is unused*/
7
8function rvm_get_config_file_name()
9{
10  global $page, $conf;
11  unset( $page['__rvm_config__'] );
12  return PHPWG_ROOT_PATH.$conf['data_location'].'/plugins/'.basename(dirname(dirname(__FILE__))).'.dat';
13}
14
15function rvm_get_config()
16{
17  global $page;
18  if (isset($page['__rvm_config__']))
19    return $page['__rvm_config__'];
20  $x = @file_get_contents( rvm_get_config_file_name() );
21  if ($x!==false)
22    $page['__rvm_config__'] = unserialize($x);
23  if ( !is_array(@$page['__rvm_config__']) )
24    $page['__rvm_config__'] = array();
25  return $page['__rvm_config__'];
26}
27
28function rvm_get_config_var($var, $default)
29{
30  global $page;
31  if (!isset($page['__rvm_config__']))
32    rvm_get_config();
33  if ( array_key_exists($var,$page['__rvm_config__']) )
34    return $page['__rvm_config__'][$var];
35  return $default;
36}
37
38function rvm_parse_map_data_url($tokens, &$next_token)
39{
40  $page=array();
41
42  $page = array_merge($page, parse_section_url($tokens, $next_token) );
43  if ( !isset($page['section']) )
44    $page['section'] = 'categories';
45
46  $page = array_merge( $page, parse_well_known_params_url( $tokens, $next_token) );
47  $page['start']=0;
48  $page['box'] = rvm_bounds_from_url( @$_GET['box'] );
49  return $page;
50}
51
52function rvm_parse_kml_url($tokens, &$next_token)
53{
54  $page=array();
55
56  $page = array_merge($page, parse_section_url($tokens, $next_token) );
57  if ( !isset($page['section']) )
58    $page['section'] = 'categories';
59
60  $page = array_merge( $page, parse_well_known_params_url( $tokens, $next_token) );
61  $page['start']=0;
62  $page['box'] = rvm_bounds_from_url( @$_GET['box'] );
63  if ( isset($_GET['ll']) )
64    $page['ll'] = rvm_ll_from_url( $_GET['ll'] );
65  return $page;
66}
67
68function rvm_duplicate_blowup_url($redefined=array(), $removed=array())
69{
70  return rvm_make_blowup_url(
71    params_for_duplication($redefined, $removed)
72    );
73}
74
75function rvm_make_blowup_url($params)
76{
77  global $conf, $rvm_dir;
78  if ( file_exists(PHPWG_ROOT_PATH.'mapl.php') )
79    $url = get_root_url().'mapl';
80  else
81    $url = get_root_url().'plugins/'.$rvm_dir.'/mapl';
82  if ($conf['php_extension_in_urls'])
83    $url .= '.php';
84  if ($conf['question_mark_in_urls'])
85    $url .= '?';
86  $url .= make_section_in_url($params);
87  $url = add_well_known_params_in_url($url, array_intersect_key($params, array('flat'=>1) ) );
88
89  $get_params = array();
90  if ( isset($params['box']) and !empty($params['box']) and !bounds_is_world($params['box']) )
91    $get_params['box'] = bounds_to_url($params['box']);
92  elseif ( isset($params['ll']) and !empty($params['ll']) )
93    $get_params['ll'] = $params['ll']['lat'].','.$params['ll']['lon'];
94  if ( isset($params['start']) and $params['start']>0 )
95    $get_params['start'] = $params['start'];
96  $url = add_url_params($url, $get_params );
97  return $url;
98}
99
100function rvm_parse_blowup_url($tokens, &$next_token)
101{
102  $page=array();
103  $page = array_merge($page, parse_section_url($tokens, $next_token) );
104  if ( !isset($page['section']) )
105    $page['section'] = 'categories';
106  $page = array_merge( $page, parse_well_known_params_url( $tokens, $next_token) );
107  $page['start']=0;
108  if ( isset($_GET['start']) )
109    $page['start']=$_GET['start'];
110  $page['box'] = rvm_bounds_from_url( @$_GET['box'] );
111  if ( isset($_GET['ll']) )
112    $page['ll'] = rvm_ll_from_url( $_GET['ll'] );
113  return $page;
114}
115
116function rvm_bounds_from_url($str)
117{
118  if ( !isset($str) or strlen($str)==0 )
119    return null;
120  $r = explode(',', $str );
121  if ( count($r) != 4)
122    bad_request( $str.' is not a valid geographical bound' );
123  $b = array(
124      's' => $r[0],
125      'w' => $r[1],
126      'n' => $r[2],
127      'e' => $r[3],
128    );
129  return $b;
130}
131
132function rvm_bounds_to_sql( $b )
133{
134  if ( !isset($b) or empty($b) )
135    return null;
136  $sql_where = 'i.lat BETWEEN '.$b['s'].' AND '.($b['n']);
137  $sql_where .= ' AND ';
138  if ($b['e'] >= $b['w'])
139    $sql_where .= 'i.lon BETWEEN '.$b['w'].' AND '.($b['e']);
140  else
141    $sql_where .= 'i.lon NOT BETWEEN '.($b['e']+1e-7).' AND '.($b['w']-1e-7);
142  return $sql_where;
143}
144
145function bounds_to_url($b, $p = 6 )
146{
147  if ( empty($b) )
148    return '';
149  return round($b['s'],$p).','.round($b['w'],$p).','.round($b['n'],$p).','.round($b['e'],$p);
150}
151
152function rvm_ll_from_url($str)
153{
154  if ( !isset($str) or strlen($str)==0 )
155    return null;
156  $r = explode(',', $str );
157  if ( count($r) != 2)
158    bad_request( $str.' is not a valid geographical position' );
159  $b = array('lat'=>$r[0],'lon'=>$r[1]);
160  return $b;
161}
162
163function rvm_ll_to_sql( $ll, &$order_by )
164{
165  $cos_lat = max( 1e-2, cos($ll['lat']*M_PI/180) );
166  $dlat = 3; // 1 degree is approx between 111 and 116 km
167  $dlon = min( 3/$cos_lat, 180 );
168  $bounds = array(
169      's' => $ll['lat'] - $dlat,
170      'w' => $ll['lon'] - $dlon,
171      'n' => $ll['lat'] + $dlat,
172      'e' => $ll['lon'] + $dlon,
173    );
174  if ($bounds['s']<-90) $bounds['s']=-90;
175  if ($bounds['w']<-180) $bounds['w']+=360;
176  if ($bounds['n']>90) $bounds['n']=90;
177  if ($bounds['e']>180) $bounds['e']-=360;
178  $where_sql = rvm_bounds_to_sql( $bounds );
179  $order_by = 'ORDER BY POW('.$ll['lat'].'-i.lat,2)+POW('.$cos_lat.'*('.$ll['lon'].'-i.lon),2)';
180  return $where_sql;
181}
182
183
184function bounds_is_world( $b )
185{
186  if (empty($b)) return false;
187  return $b['n']>=90 and $b['s']<=-90 and $b['w']<=-180 and $b['e']>=180;
188}
189
190function bounds_add($bounds, $lat, $lon)
191{
192  if ( empty($bounds) )
193  {
194    $bounds = array(
195      's' => $lat,
196      'n' => $lat,
197      'w' => $lon,
198      'e' => $lon,
199      'count' => 1
200      );
201  }
202  else
203  {
204    if ( $lat>$bounds['n'] )
205      $bounds['n']=$lat;
206    elseif ( $lat<$bounds['s'] )
207      $bounds['s']=$lat;
208    if ( $lon>$bounds['e'] )
209      $bounds['e']=$lon;
210    elseif ( $lon<$bounds['w'] )
211      $bounds['w']=$lon;
212    $bounds['count']=$bounds['count']+1;
213  }
214
215  return $bounds;
216}
217
218function bounds_union($b1, $b2)
219{
220  $total_count = $b1['count'] + $b2['count'];
221  $res =
222    array_merge(
223      $b1,
224      array(
225        's' => min( $b1['s'], $b2['s'] ),
226        'n' => max( $b1['n'], $b2['n'] ),
227        'w' => min( $b1['w'], $b2['w'] ),
228        'e' => max( $b1['e'], $b2['e'] ),
229        'count' => $total_count,
230      )
231    );
232  if ( isset($b2['min_date']) )
233    $res = array_merge(
234      $res,
235      array(
236        'min_date' => min( $b1['min_date'], $b2['max_date'] ),
237        'max_date' => max( $b1['max_date'], $b2['max_date'] ),
238      )
239    );
240  return $res;
241}
242
243function bounds_center($b)
244{
245  if (empty($b))
246    return array();
247  return array(
248    'lat' => ($b['s']+$b['n'])/2,
249    'lon' => ($b['w']+$b['e'])/2,
250    );
251}
252
253function bounds_sw($b)
254{
255  if (empty($b))
256    return array();
257  return array(
258    'lat' => $b['s'],
259    'lon' => $b['w'],
260    );
261}
262
263function bounds_ne($b)
264{
265  if (empty($b))
266    return array();
267  return array(
268    'lat' => $b['n'],
269    'lon' => $b['e'],
270    );
271}
272
273
274function bounds_lat_range($b)
275{
276  if (empty($b))
277    return 0;
278  return $b['n'] - $b['s'];
279}
280
281function bounds_lon_range($b)
282{
283  if (empty($b))
284    return 0;
285  return $b['e'] - $b['w'];
286}
287
288
289function rvm_get_cat_bounds()
290{
291  $cache_file_name = rvm_get_cache_file_name();
292  if ( file_exists($cache_file_name) )
293  {
294    return unserialize( file_get_contents($cache_file_name) );
295  }
296  $forbidden = get_sql_condition_FandF(
297        array
298          (
299            'forbidden_categories' => 'category_id',
300            'visible_categories' => 'category_id',
301            'visible_images' => 'i.id'
302          ),
303        'AND'
304    );
305
306  $query = '
307SELECT category_id cat_id, uppercats, MAX(lat) AS n, MIN(lat) AS s, MAX(lon) AS e, MIN(lon) AS w, COUNT(i.id) count, MIN(i.date_creation) min_date, MAX(i.date_creation) max_date
308  FROM
309    '.CATEGORIES_TABLE.' as c
310      INNER JOIN
311    '.IMAGE_CATEGORY_TABLE.' ON category_id = c.id
312      INNER JOIN
313    '.IMAGES_TABLE.' i ON image_id=i.id
314  WHERE lat IS NOT NULL '.$forbidden.'
315  GROUP BY category_id
316;';
317
318  $result = pwg_query($query);
319  $uppercats_list = array();
320  $cat_bounds = array();
321  while ($row = mysql_fetch_assoc($result))
322  {
323    array_push($uppercats_list, $row['uppercats']);
324    $cat_id = $row['cat_id'];
325    unset( $row['cat_id'], $row['uppercats'] );
326    $cat_bounds[ $cat_id ] = $row;
327    $cat_bounds[ $cat_id ]['self'] = $row;
328  }
329  natsort($uppercats_list);
330  //echo "<pre>" . var_export($uppercats_list,true);
331
332  foreach ( array_reverse($uppercats_list) as $uppercats)
333  {
334    $cat_ids = explode(',', $uppercats);
335    $bounds = $cat_bounds[ $cat_ids[count($cat_ids)-1] ];
336    for ($i=count($cat_ids)-2; $i>=0; $i--)
337    {
338      $this_bounds = @$cat_bounds[ $cat_ids[$i] ];
339      if ( !isset($this_bounds) )
340      {
341        $this_bounds = $bounds;
342        unset($this_bounds['self']);
343      }
344      else
345      {
346//        if ($cat_ids[$i]==43) echo "<pre>Before\n" . var_export($this_bounds,true);
347//        if ($cat_ids[$i]==43) echo "<pre>Union\n" . var_export($bounds,true);
348        $this_bounds = bounds_union($this_bounds, $bounds);
349      }
350      $this_bounds['nb_cats'] = 1 + @$this_bounds['nb_cats'];
351//      if ($cat_ids[$i]==43) echo "<pre>" . var_export($this_bounds,true);
352      $cat_bounds[ $cat_ids[$i] ] = $this_bounds;
353    }
354  }
355  //echo "<pre>" . var_export($cat_bounds,true);
356        mkgetdir( dirname($cache_file_name) );
357  $file = fopen($cache_file_name , 'w' );
358  fwrite($file, serialize($cat_bounds) );
359  fclose( $file );
360
361  return $cat_bounds;
362}
363
364
365function marray_from_query($query)
366{
367  $ret = array();
368  $result = pwg_query($query);
369  while ($row = mysql_fetch_assoc($result))
370    $ret[] = $row;
371  return $ret;
372}
373
374define('RVM_BUILD_ARRAY',     0);
375define('RVM_BUILD_HASH',      1);
376define('RVM_BUILD_AGGREGATE', 2);
377
378function rvm_build_section_items($img_fields, $where_sql, $mode, $order_by=null)
379{
380  global $page, $conf, $user;
381
382  $page['items'] = array();
383
384  if (empty($where_sql))
385    $where_sql .= 'i.lat IS NOT NULL';
386  $where_sql_images_only = $where_sql;
387  $where_sql .= get_sql_condition_FandF(
388      array
389        (
390          'forbidden_categories' => 'category_id',
391          'visible_categories' => 'category_id',
392          'visible_images' => 'i.id'
393        ),
394      "\n  AND"
395  );
396
397  switch ($mode)
398  {
399    case RVM_BUILD_ARRAY:
400      $func = 'marray_from_query';
401      $group_by = '
402  GROUP BY i.id';
403      break;
404    case RVM_BUILD_HASH:
405      $func = create_function( '$q', 'return hash_from_query($q, "id");' );
406      $group_by = '
407  GROUP BY i.id';
408      break;
409    case RVM_BUILD_AGGREGATE:
410      $func = 'marray_from_query';
411      $group_by = '';
412      break;
413  }
414
415  if ($mode != RVM_BUILD_AGGREGATE )
416  {
417    if ($order_by==null and pwg_get_session_var('image_order',0) > 0)
418    {
419      $orders = get_category_preferred_image_orders();
420
421      $conf['order_by'] = str_replace(
422        'ORDER BY ',
423        'ORDER BY '.$orders[ pwg_get_session_var('image_order',0) ][1].',',
424        $conf['order_by']
425        );
426      $page['super_order_by'] = true;
427    }
428    elseif ($order_by!=null)
429    {
430      $conf['order_by']=$order_by;
431      $page['super_order_by'] = true;
432    }
433    elseif ( 'categories' == $page['section'] and isset($page['category']['image_order']) )
434    {
435      $conf['order_by'] = 'ORDER BY '.$page['category']['image_order'];
436    }
437  }
438  else
439  {
440    $conf['order_by'] = 'ORDER BY NULL';
441    $page['super_order_by'] = true;
442  }
443
444  if ('categories' == $page['section'])
445  {
446    if ( isset($page['flat']) or isset($page['category']) )
447    {
448      if (isset($page['flat']))
449      {
450        if ( isset($page['category']) )
451        {
452          $subcat_ids = get_subcat_ids( array($page['category']['id']) );
453          $where_sql .= ' AND category_id IN ('.implode(',',$subcat_ids).')';
454        }
455      }
456      else
457      {
458        $where_sql .= ' AND category_id='.$page['category']['id'];
459      }
460
461      $query='
462SELECT '.$img_fields.'
463  FROM '.IMAGES_TABLE.' i INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
464  WHERE '.$where_sql.$group_by.'
465  '.$conf['order_by'];
466
467      $page['items'] = $func($query);
468    }
469    if ( isset($page['category']) )
470    {
471      $page['title'] = $page['category']['name'];
472      $page['comment'] = $page['category']['comment'];
473    }
474    else
475      $page['title'] = $conf['gallery_title'];
476  }
477  else if ('tags' == $page['section'])
478  {
479    $items = get_image_ids_for_tags( array($page['tags'][0]['id']), 'AND', $where_sql_images_only, 'ORDER BY NULL' );
480    if ( !empty($items) )
481    {
482      $query = '
483SELECT '.$img_fields.'
484  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.IMAGES_TABLE.' i ON i.id=image_id
485  WHERE image_id IN ('.implode(',', $items).')'
486  .$group_by.'
487  '.$conf['order_by'];
488
489      $page['items'] = $func($query);
490    }
491    $page['title'] = strip_tags( get_tags_content_title() );
492  }
493  elseif ('search' == $page['section'])
494  {
495    include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
496    $search_result = get_search_results($page['search'], @$page['super_order_by'], $where_sql_images_only);
497    if ( !empty($search_result['items']) )
498    {
499      $query = '
500SELECT '.$img_fields.'
501  FROM '.IMAGES_TABLE.' i
502  WHERE id IN ('.implode(',', $search_result['items']).')'
503  .$group_by.'
504  '.$conf['order_by'].'
505;';
506
507      if ($mode != RVM_BUILD_AGGREGATE )
508      {
509        $page['items'] = hash_from_query($query, 'id' );
510
511        global $item_ranks;
512        $item_ranks = array_flip($search_result['items']);
513        function cmp_item_hash($a, $b)
514        {
515          global $item_ranks;
516          return $item_ranks [ $a['id'] ] - $item_ranks [ $b['id'] ];
517        }
518        uasort( $page['items'], 'cmp_item_hash' );
519        unset( $item_ranks );
520      }
521      else
522        $page['items'] = $func($query);
523    }
524
525    $page['title'] = l10n('search_result');
526  }
527  elseif ('recent_pics' == $page['section'])
528  {
529    $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
530
531    $query ='
532SELECT '.$img_fields.'
533  FROM '.IMAGES_TABLE.' i
534    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
535  WHERE date_available >= SUBDATE(
536      CURRENT_DATE,INTERVAL '.$user['recent_period'].' DAY)
537    AND '.$where_sql
538  .$group_by.'
539  '.$conf['order_by'].'
540  LIMIT 0, '.$conf['top_number'].'
541;';
542
543    $page['items'] = $func($query);
544    $page['title'] = l10n('recent_pics_cat');
545  }
546  else if ('list'==$page['section'])
547  {
548    $query ='
549SELECT '.$img_fields.'
550  FROM '.IMAGES_TABLE.' i
551    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
552  WHERE image_id IN ('.implode(',', $page['list']).')
553    AND '.$where_sql
554  .$group_by.'
555  '.$conf['order_by'].'
556;';
557
558    $page['items'] = $func($query);
559    $page['title'] = l10n('random_cat');
560  }
561  else
562    fatal_error( 'section '.$page['section']. ' not handled '. __FILE__);
563}
564
565?>
Note: See TracBrowser for help on using the repository browser.