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

Last change on this file since 20461 was 20461, checked in by rvelices, 11 years ago

rv* plugins use pwg_db_* instead of mysql_* functions

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 14.3 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 = pwg_db_fetch_assoc($result))
322  {
323    $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
365define('RVM_BUILD_ARRAY',     0);
366define('RVM_BUILD_HASH',      1);
367define('RVM_BUILD_AGGREGATE', 2);
368
369function rvm_build_section_items($img_fields, $where_sql, $mode, $order_by=null)
370{
371  global $page, $conf, $user;
372
373  $page['items'] = array();
374
375  if (empty($where_sql))
376    $where_sql .= 'i.lat IS NOT NULL';
377  $where_sql_images_only = $where_sql;
378  $where_sql .= get_sql_condition_FandF(
379      array
380        (
381          'forbidden_categories' => 'category_id',
382          'visible_categories' => 'category_id',
383          'visible_images' => 'i.id'
384        ),
385      "\n  AND"
386  );
387
388  switch ($mode)
389  {
390    case RVM_BUILD_ARRAY:
391      $func = 'array_from_query';
392      $group_by = '
393  GROUP BY i.id';
394      break;
395    case RVM_BUILD_HASH:
396      $func = create_function( '$q', 'return hash_from_query($q, "id");' );
397      $group_by = '
398  GROUP BY i.id';
399      break;
400    case RVM_BUILD_AGGREGATE:
401      $func = 'array_from_query';
402      $group_by = '';
403      break;
404  }
405
406  if ($mode != RVM_BUILD_AGGREGATE )
407  {
408    if ($order_by==null and pwg_get_session_var('image_order',0) > 0)
409    {
410      $orders = get_category_preferred_image_orders();
411
412      $conf['order_by'] = str_replace(
413        'ORDER BY ',
414        'ORDER BY '.$orders[ pwg_get_session_var('image_order',0) ][1].',',
415        $conf['order_by']
416        );
417      $page['super_order_by'] = true;
418    }
419    elseif ($order_by!=null)
420    {
421      $conf['order_by']=$order_by;
422      $page['super_order_by'] = true;
423    }
424    elseif ( 'categories' == $page['section'] and isset($page['category']['image_order']) )
425    {
426      $conf['order_by'] = 'ORDER BY '.$page['category']['image_order'];
427    }
428  }
429  else
430  {
431    $conf['order_by'] = 'ORDER BY NULL';
432    $page['super_order_by'] = true;
433  }
434
435  if ('categories' == $page['section'])
436  {
437    if ( isset($page['flat']) or isset($page['category']) )
438    {
439      if (isset($page['flat']))
440      {
441        if ( isset($page['category']) )
442        {
443          $subcat_ids = get_subcat_ids( array($page['category']['id']) );
444          $where_sql .= ' AND category_id IN ('.implode(',',$subcat_ids).')';
445        }
446      }
447      else
448      {
449        $where_sql .= ' AND category_id='.$page['category']['id'];
450      }
451
452      $query='
453SELECT '.$img_fields.'
454  FROM '.IMAGES_TABLE.' i INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON i.id=image_id
455  WHERE '.$where_sql.$group_by.'
456  '.$conf['order_by'];
457
458      $page['items'] = $func($query);
459    }
460    if ( isset($page['category']) )
461    {
462      $page['title'] = trigger_event('render_category_name', $page['category']['name']);
463      $page['comment'] = $page['category']['comment'];
464    }
465    else
466      $page['title'] = $conf['gallery_title'];
467  }
468  else if ('tags' == $page['section'])
469  {
470    $items = get_image_ids_for_tags( array($page['tags'][0]['id']), 'AND', $where_sql_images_only, 'ORDER BY NULL' );
471    if ( !empty($items) )
472    {
473      $query = '
474SELECT '.$img_fields.'
475  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.IMAGES_TABLE.' i ON i.id=image_id
476  WHERE image_id IN ('.implode(',', $items).')'
477  .$group_by.'
478  '.$conf['order_by'];
479
480      $page['items'] = $func($query);
481    }
482    $page['title'] = strip_tags( get_tags_content_title() );
483  }
484  elseif ('search' == $page['section'])
485  {
486    include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
487    $search_result = get_search_results($page['search'], @$page['super_order_by'], $where_sql_images_only);
488    if ( !empty($search_result['items']) )
489    {
490      $query = '
491SELECT '.$img_fields.'
492  FROM '.IMAGES_TABLE.' i
493  WHERE id IN ('.implode(',', $search_result['items']).')'
494  .$group_by.'
495  '.$conf['order_by'].'
496;';
497
498      if ($mode != RVM_BUILD_AGGREGATE )
499      {
500        $page['items'] = hash_from_query($query, 'id' );
501
502        global $item_ranks;
503        $item_ranks = array_flip($search_result['items']);
504        function cmp_item_hash($a, $b)
505        {
506          global $item_ranks;
507          return $item_ranks [ $a['id'] ] - $item_ranks [ $b['id'] ];
508        }
509        uasort( $page['items'], 'cmp_item_hash' );
510        unset( $item_ranks );
511      }
512      else
513        $page['items'] = $func($query);
514    }
515
516    $page['title'] = l10n('Search results');
517  }
518  elseif ('recent_pics' == $page['section'])
519  {
520    $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
521
522    $query ='
523SELECT '.$img_fields.'
524  FROM '.IMAGES_TABLE.' i
525    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
526  WHERE date_available >= SUBDATE(
527      CURRENT_DATE,INTERVAL '.$user['recent_period'].' DAY)
528    AND '.$where_sql
529  .$group_by.'
530  '.$conf['order_by'].'
531  LIMIT 0, '.$conf['top_number'].'
532;';
533
534    $page['items'] = $func($query);
535    $page['title'] = l10n('Recent photos');
536  }
537  else if ('list'==$page['section'])
538  {
539    $query ='
540SELECT '.$img_fields.'
541  FROM '.IMAGES_TABLE.' i
542    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
543  WHERE image_id IN ('.implode(',', $page['list']).')
544    AND '.$where_sql
545  .$group_by.'
546  '.$conf['order_by'].'
547;';
548
549    $page['items'] = $func($query);
550    $page['title'] = l10n('Random photos');
551  }
552  else
553    fatal_error( 'section '.$page['section']. ' not handled '. __FILE__);
554}
555
556?>
Note: See TracBrowser for help on using the repository browser.