source: extensions/GMaps/gmaps_ajax.php @ 7125

Last change on this file since 7125 was 7125, checked in by grum, 14 years ago

Admin interface + Gallery integration finished

File size: 31.4 KB
Line 
1<?php
2/*
3 * -----------------------------------------------------------------------------
4 * Plugin Name: GMaps
5 * -----------------------------------------------------------------------------
6 * Author     : Grum
7 *   email    : grum@piwigo.org
8 *   website  : http://photos.grum.fr
9 *   PWG user : http://forum.piwigo.org/profile.php?id=3706
10 *
11 *   << May the Little SpaceFrog be with you ! >>
12 *
13 * -----------------------------------------------------------------------------
14 *
15 * See main.inc.php for release information
16 *
17 * manage all the ajax requests
18 * -----------------------------------------------------------------------------
19 */
20
21  define('PHPWG_ROOT_PATH',dirname(dirname(dirname(__FILE__))).'/');
22
23  /*
24   * set ajax module in admin mode if request is used for admin interface
25   */
26  if(!isset($_REQUEST['ajaxfct'])) $_REQUEST['ajaxfct']='';
27  if(preg_match('/^admin\./i', $_REQUEST['ajaxfct']))
28  {
29    define('IN_ADMIN', true);
30  }
31
32  // the common.inc.php file loads all the main.inc.php plugins files
33  include_once(PHPWG_ROOT_PATH.'include/common.inc.php' );
34  include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCAjax.class.inc.php');
35  include_once('gmaps_root.class.inc.php');
36
37  load_language('plugin.lang', GMAPS_PATH);
38
39
40  class GMaps_Ajax extends GMaps_root
41  {
42    /**
43     * constructor
44     */
45    public function __construct($prefixeTable, $filelocation)
46    {
47      parent::__construct($prefixeTable, $filelocation);
48      $this->loadConfig();
49      $this->checkRequest();
50      $this->returnAjaxContent();
51    }
52
53    /**
54     * check the $_REQUEST values and set default values
55     *
56     */
57    protected function checkRequest()
58    {
59      global $user;
60
61      if(!isset($_REQUEST['ajaxfct'])) $_REQUEST['ajaxfct']='';
62
63      // check if asked function is valid
64      if(!($_REQUEST['ajaxfct']=='admin.maps.getList' or
65           $_REQUEST['ajaxfct']=='admin.maps.setMap' or
66           $_REQUEST['ajaxfct']=='admin.maps.getMap' or
67           $_REQUEST['ajaxfct']=='admin.maps.deleteMap' or
68           $_REQUEST['ajaxfct']=='admin.assoc.getList' or
69           $_REQUEST['ajaxfct']=='admin.assoc.setAssoc' or
70           $_REQUEST['ajaxfct']=='admin.assoc.getAssoc' or
71           $_REQUEST['ajaxfct']=='admin.assoc.deleteAssoc' or
72
73           $_REQUEST['ajaxfct']=='public.maps.init' or
74           $_REQUEST['ajaxfct']=='public.maps.getMarkers' or
75           $_REQUEST['ajaxfct']=='public.maps.getMarkerInfos'
76           )) $_REQUEST['ajaxfct']='';
77
78      if(preg_match('/^admin\./i', $_REQUEST['ajaxfct']) and !is_admin()) $_REQUEST['ajaxfct']='';
79
80
81      if($_REQUEST['ajaxfct']!='')
82      {
83        /*
84         * no check for admin.maps.getList & admin.assoc.getList requests
85         */
86
87
88        /*
89         * check admin.maps.getMap & admin.assoc.getAssoc values
90         */
91        if($_REQUEST['ajaxfct']=="admin.maps.getMap" or
92           $_REQUEST['ajaxfct']=="admin.assoc.getAssoc")
93        {
94          if(!isset($_REQUEST['id']) or
95             !is_numeric($_REQUEST['id']) or
96             $_REQUEST['id']=='') $_REQUEST['ajaxfct']='';
97        }
98
99        /*
100         * check admin.maps.deleteMap values
101         */
102        if($_REQUEST['ajaxfct']=="admin.maps.deleteMap" or
103           $_REQUEST['ajaxfct']=="admin.maps.deleteAssoc")
104        {
105          if(!isset($_REQUEST['id']) or
106             !is_numeric($_REQUEST['id']) or
107             $_REQUEST['id']=='') $_REQUEST['ajaxfct']='';
108        }
109
110        /*
111         * check admin.maps.setMap values
112         */
113        if($_REQUEST['ajaxfct']=="admin.maps.setMap")
114        {
115          if(!isset($_REQUEST['id']) or
116             !isset($_REQUEST['datas']) or !is_array($_REQUEST['datas']))
117          {
118            $_REQUEST['ajaxfct']='';
119          }
120          else
121          {
122            if(!(isset($_REQUEST['datas']['displayType']) &&
123                 isset($_REQUEST['datas']['sizeMode']) &&
124                 isset($_REQUEST['datas']['name']) &&
125                 isset($_REQUEST['datas']['width']) &&
126                 isset($_REQUEST['datas']['height']) &&
127                 isset($_REQUEST['datas']['zoomLevel']) &&
128                 isset($_REQUEST['datas']['mapType']) &&
129                 isset($_REQUEST['datas']['mapTypeControl']) &&
130                 isset($_REQUEST['datas']['navigationControl']) &&
131                 isset($_REQUEST['datas']['scaleControl']) &&
132                 isset($_REQUEST['datas']['style'])))
133            {
134              $_REQUEST['ajaxfct']='';
135            }
136            else
137            {
138              if(!($_REQUEST['datas']['displayType']=='IC' or
139                  $_REQUEST['datas']['displayType']=='IP' or
140                  $_REQUEST['datas']['displayType']=='MP')) $_REQUEST['ajaxfct']='';
141
142              if(!($_REQUEST['datas']['sizeMode']=='A' or
143                  $_REQUEST['datas']['sizeMode']=='F')) $_REQUEST['ajaxfct']='';
144
145              if(!is_numeric($_REQUEST['datas']['width']) or
146                  $_REQUEST['datas']['width']<100 or
147                  $_REQUEST['datas']['width']>1280) $_REQUEST['datas']['width']=470;
148
149              if(!is_numeric($_REQUEST['datas']['height']) or
150                  $_REQUEST['datas']['height']<100 or
151                  $_REQUEST['datas']['height']>1280) $_REQUEST['datas']['height']=210;
152
153              if(!is_numeric($_REQUEST['datas']['zoomLevel']) or
154                  $_REQUEST['datas']['zoomLevel']<1 or
155                  $_REQUEST['datas']['zoomLevel']>20) $_REQUEST['datas']['zoomLevel']=4;
156
157              if(!($_REQUEST['datas']['mapType']=='hybrid' or
158                  $_REQUEST['datas']['mapType']=='terrain' or
159                  $_REQUEST['datas']['mapType']=='roadmap' or
160                  $_REQUEST['datas']['mapType']=='satellite')) $_REQUEST['datas']['mapType']='hybrid';
161
162              if(!is_numeric($_REQUEST['datas']['mapTypeControl']) or
163                  $_REQUEST['datas']['mapTypeControl']<-1 or
164                  $_REQUEST['datas']['mapTypeControl']>2) $_REQUEST['datas']['mapTypeControl']=0;
165
166              if(!is_numeric($_REQUEST['datas']['navigationControl']) or
167                  $_REQUEST['datas']['navigationControl']<-1 or
168                  $_REQUEST['datas']['navigationControl']>3) $_REQUEST['datas']['navigationControl']=0;
169
170              if(!($_REQUEST['datas']['scaleControl']=='y' or
171                   $_REQUEST['datas']['scaleControl']=='n')) $_REQUEST['datas']['scaleControl']='y';
172            }
173          }
174        }
175
176
177        /*
178         * check admin.maps.setAssoc values
179         */
180        if($_REQUEST['ajaxfct']=="admin.assoc.setAssoc")
181        {
182          if(!isset($_REQUEST['id']) or
183             !isset($_REQUEST['datas']) or !is_array($_REQUEST['datas']))
184          {
185            $_REQUEST['ajaxfct']='';
186          }
187          else
188          {
189            if(!(isset($_REQUEST['datas']['categoryId']) &&
190                 isset($_REQUEST['datas']['mapId']) &&
191                 isset($_REQUEST['datas']['applySubCat']) &&
192                 isset($_REQUEST['datas']['kmlFileUrl']) &&
193                 isset($_REQUEST['datas']['icon']) &&
194                 isset($_REQUEST['datas']['title']) ))
195            {
196              $_REQUEST['ajaxfct']='';
197            }
198            else
199            {
200              if($_REQUEST['datas']['categoryId']=='' or
201                 $_REQUEST['datas']['categoryId']<0) $_REQUEST['ajaxfct']='';
202
203              if($_REQUEST['datas']['mapId']=='') $_REQUEST['ajaxfct']='';
204
205              if(!($_REQUEST['datas']['applySubCat']=='y' or
206                   $_REQUEST['datas']['applySubCat']=='n')) $_REQUEST['datas']['applySubCat']='y';
207            }
208          }
209        }
210
211
212        /*
213         * check public.maps.getMarkers values
214         */
215        if($_REQUEST['ajaxfct']=="public.maps.getMarkers")
216        {
217          if(!isset($_REQUEST['datas']) or
218             !is_array($_REQUEST['datas']))
219          {
220            $_REQUEST['ajaxfct']='';
221          }
222          else
223          {
224            if(!(isset($_REQUEST['datas']['requestId']) &&
225                 isset($_REQUEST['datas']['bounds']) &&
226                 isset($_REQUEST['datas']['width']) &&
227                 isset($_REQUEST['datas']['height']) &&
228                 isset($_REQUEST['datas']['distanceTreshold']) &&
229                 isset($_REQUEST['datas']['bounds']['north']) &&
230                 isset($_REQUEST['datas']['bounds']['south']) &&
231                 isset($_REQUEST['datas']['bounds']['east']) &&
232                 isset($_REQUEST['datas']['bounds']['west']) ))
233            {
234              $_REQUEST['ajaxfct']='';
235            }
236          }
237        }
238
239        /*
240         * check public.maps.getMarkerInfos values
241         */
242        if($_REQUEST['ajaxfct']=="public.maps.init")
243        {
244          if(!isset($_REQUEST['category']))
245          {
246            $_REQUEST['ajaxfct']='';
247          }
248        }
249
250      }
251    } //checkRequest
252
253
254    /**
255     * return ajax content
256     */
257    protected function returnAjaxContent()
258    {
259      $result="<p class='errors'>An error has occured</p>";
260      switch($_REQUEST['ajaxfct'])
261      {
262        case 'admin.maps.getList':
263          $result=$this->ajax_gmaps_admin_mapsGetList();
264          break;
265        case 'admin.maps.getMap':
266          $result=$this->ajax_gmaps_admin_mapsGetMap($_REQUEST['id']);
267          break;
268        case 'admin.maps.setMap':
269          $result=$this->ajax_gmaps_admin_mapsSetMap($_REQUEST['id'], $_REQUEST['datas']);
270          break;
271        case 'admin.maps.deleteMap':
272          $result=$this->ajax_gmaps_admin_mapsDeleteMap($_REQUEST['id']);
273          break;
274        case 'admin.assoc.getList':
275          $result=$this->ajax_gmaps_admin_assocGetList();
276          break;
277        case 'admin.assoc.getAssoc':
278          $result=$this->ajax_gmaps_admin_assocGetAssoc($_REQUEST['id']);
279          break;
280        case 'admin.assoc.setAssoc':
281          $result=$this->ajax_gmaps_admin_assocSetAssoc($_REQUEST['id'], $_REQUEST['datas']);
282          break;
283        case 'admin.assoc.deleteAssoc':
284          $result=$this->ajax_gmaps_admin_assocDeleteAssoc($_REQUEST['id']);
285          break;
286
287        case 'public.maps.init':
288          $result=$this->ajax_gmaps_public_mapsInit($_REQUEST['category']);
289          break;
290        case 'public.maps.getMarkers':
291          $result=$this->ajax_gmaps_public_mapsGetMarkers($_REQUEST['datas']);
292          break;
293      }
294      GPCAjax::returnResult($result);
295    }
296
297
298    /*------------------------------------------------------------------------*
299     *
300     * ADMIN FUNCTIONS
301     *
302     *----------------------------------------------------------------------- */
303
304    /**
305     * return a HTML list of defined maps
306     *
307     * @return String
308     */
309    private function ajax_gmaps_admin_mapsGetList()
310    {
311      global $template;
312
313      $template->set_filename('list_page',
314                    dirname($this->getFileLocation()).'/admin/gmaps_maps_iListMaps.tpl');
315
316      $datas=Array();
317
318      $sql="SELECT id, name, displayType, sizeMode, width, height, zoomLevel, mapType, mapTypeControl, navigationControl, scaleControl
319            FROM ".$this->tables['maps']."
320            ORDER BY displayType ASC, name ASC";
321      $result=pwg_query($sql);
322      if($result)
323      {
324        while($row=pwg_db_fetch_assoc($result))
325        {
326          if($row['displayType']=='IC')
327          {
328            $row['zoomLevel']=l10n('gmaps_auto');
329          }
330
331          $row['displayType']=l10n('gmaps_displayTypeShort'.$row['displayType']);
332
333          if($row['sizeMode']=='A')
334          {
335            $row['dimensions']=l10n('gmaps_auto');
336          }
337          else
338          {
339            $row['dimensions']=$row['width'].'x'.$row['height'];
340          }
341
342          $row['mapType']=l10n('gmaps_googleMapType_'.$row['mapType']);
343          $row['mapTypeControl']=l10n('gmaps_googleMapTypeControl_'.$row['mapTypeControl']);
344          $row['navigationControl']=l10n('gmaps_googleMapNavigationControl_'.$row['navigationControl']);
345          $row['scaleControl']=($row['scaleControl']=='y')?l10n('gmaps_display_visible'):l10n('gmaps_display_hidden');
346          $datas[]=$row;
347        }
348      }
349
350      $template->assign('datas', $datas);
351      return($template->parse('list_page', true));
352    } //ajax_gmaps_admin_mapsGetList
353
354
355    /**
356     * set properties for a given map id ; if no map id is given, create a new
357     * map
358     *
359     * @param String id : the map Id
360     * @param Array datas : properties of the map (assuming array index were
361     *                      checked by the checkRequest function)
362     * @return String : the num id, or an error message
363     */
364    private function ajax_gmaps_admin_mapsSetMap($id, $properties)
365    {
366      global $template;
367
368      if($id=='')
369      {
370        $sql="INSERT INTO ".$this->tables['maps']."
371              VALUES ('', '".mysql_escape_string($properties['name'])."', '".
372                $properties['displayType']."', '".
373                $properties['sizeMode']."', '".
374                $properties['width']."', '".
375                $properties['height']."', '".
376                $properties['zoomLevel']."', '".
377                $properties['mapType']."', '".
378                $properties['mapTypeControl']."', '".
379                $properties['navigationControl']."', '".
380                $properties['scaleControl']."', '".
381                mysql_escape_string($properties['style'])."');";
382        $result=pwg_query($sql);
383        $id=pwg_db_insert_id();
384      }
385      else
386      {
387        $sql="UPDATE ".$this->tables['maps']."
388              SET name='".mysql_escape_string($properties['name'])."', displayType='".
389                $properties['displayType']."', sizeMode='".
390                $properties['sizeMode']."', width='".
391                $properties['mapId']."', width='".
392                $properties['width']."', height='".
393                $properties['height']."', zoomLevel='".
394                $properties['zoomLevel']."', mapType='".
395                $properties['mapType']."', mapTypeControl='".
396                $properties['mapTypeControl']."', navigationControl='".
397                $properties['navigationControl']."', scaleControl='".
398                $properties['scaleControl']."', style='".
399                mysql_escape_string($properties['style'])."'
400              WHERE id='$id';";
401        $result=pwg_query($sql);
402      }
403
404      return($id);
405    } //ajax_gmaps_admin_mapsSetMap
406
407
408    /**
409     * get properties for a given map id
410     *
411     * @param String id : the map Id
412     * @return String : data formatted in a JSON string
413     */
414    private function ajax_gmaps_admin_mapsGetMap($id)
415    {
416      $returned=array(
417        'id' => '',
418        'name' => '',
419        'displayType' => '',
420        'sizeMode' => '',
421        'width' => 470,
422        'height' => 210,
423        'zoomLevel' => 4,
424        'mapType' => 'hybrid',
425        'mapTypeControl' => 0,
426        'navigationControl' => 0,
427        'scaleControl' => 'y'
428      );
429
430      $sql="SELECT id, displayType, sizeMode, name, width, height, zoomLevel, mapType, mapTypeControl, navigationControl, scaleControl
431            FROM ".$this->tables['maps']."
432            WHERE id='$id';";
433      $result=pwg_query($sql);
434      if($result)
435      {
436        while($row=pwg_db_fetch_assoc($result))
437        {
438          $returned=$row;
439        }
440      }
441
442      return(json_encode($returned));
443    } //ajax_gmaps_admin_mapsGetMap
444
445
446
447    /**
448     * delete a map
449     *
450     * @param String id : if of the map to delete
451     * @return String : ok or ko
452     */
453    private function ajax_gmaps_admin_mapsDeleteMap($id)
454    {
455      $sql="DELETE FROM ".$this->tables['maps']."
456            WHERE id='$id';";
457      $result=pwg_query($sql);
458      if($result)
459      {
460        $sql="DELETE FROM ".$this->tables['category_maps']."
461              WHERE map_id='$id';";
462        $result=pwg_query($sql);
463        if($result) return('ok');
464      }
465
466      return('ko!unknown error');
467    } //ajax_gmaps_admin_mapsDeleteMap
468
469
470
471
472
473    /**
474     * return a HTML list of defined associations
475     *
476     * @return String
477     */
478    private function ajax_gmaps_admin_assocGetList()
479    {
480      global $template;
481
482      $template->set_filename('list_page',
483                    dirname($this->getFileLocation()).'/admin/gmaps_category_maps_iListMaps.tpl');
484
485      $datas=Array();
486
487      $sql="SELECT pgcm.id, pgcm.categoryId, pct.name AS catName,
488                   pgmm.name AS mapName, pgmm.displayType,
489                   pgcm.kmlFileUrl, pgcm.imgSort, pgcm.applySubCat, pgcm.icon,
490                   pgcm.title
491            FROM (".$this->tables['category_maps']." pgcm
492                  LEFT JOIN ".CATEGORIES_TABLE." pct ON pct.id=pgcm.categoryId)
493                  LEFT JOIN ".$this->tables['maps']." pgmm ON pgcm.mapId = pgmm.id
494            ORDER BY pct.name, pgmm.displayType, pgcm.imgSort";
495      $result=pwg_query($sql);
496      if($result)
497      {
498        $keys=array(
499          'prev' => '',
500          'curr' => ''
501        );
502        while($row=pwg_db_fetch_assoc($result))
503        {
504          $keys['prev']=$keys['curr'];
505
506          $tmp=array(
507            'id' => $row['id'],
508            'catName' => ($row['categoryId']==0)?l10n('gmaps_applyForAllTheGallery'):$row['catName'],
509            'applySubCat' => l10n('gmaps_'.$row['applySubCat']),
510            'mapName' => $row['mapName'],
511            'mapKmlFile' => l10n('gmaps_'.(($row['kmlFileUrl']=='')?'n':'y')),
512            'icon' => $row['icon'],
513            'displayType' => l10n('gmaps_displayTypeShort'.$row['displayType']),
514            'title' => $row['title']
515          );
516
517          $keys['curr']=$row['categoryId'].$row['displayType'];
518
519          if($keys['curr']==$keys['prev'])
520          {
521            $tmp['catName']='';
522            $tmp['displayType']='';
523            $tmp['applySubCat']='';
524          }
525
526          $datas[]=$tmp;
527        }
528      }
529
530      $template->assign('datas', $datas);
531      return($template->parse('list_page', true));
532    } //ajax_gmaps_admin_assocGetList
533
534
535
536
537    /**
538     * set properties for a given association id ; if no association id is given
539     * create a new association
540     *
541     * @param String id : the association Id
542     * @param Array datas : properties of the association (assuming array index
543     *                      were checked by the checkRequest function)
544     * @return String : the num id, or an error message
545     */
546    private function ajax_gmaps_admin_assocSetAssoc($id, $properties)
547    {
548      global $template;
549
550      // if create a new assoc, get the last imgSort
551      $db=array(
552        'nbId' => 0,
553        'displayType' => '',
554        'maxImgSort' => 0
555      );
556
557      $sql="SELECT MAX(imgSort) AS maxImgSort, pgmm.displayType, COUNT(pgcm.id) AS nbId
558            FROM (".$this->tables['category_maps']." pgcm
559              LEFT JOIN ".$this->tables['maps']." pgmm ON pgmm.id = pgcm.mapId)
560              LEFT JOIN ".$this->tables['maps']." pgmm2 ON pgmm2.displayType=pgmm.displayType
561
562            WHERE categoryId='".$properties['categoryId']."'
563              AND pgmm2.id='".$properties['mapId']."'
564            GROUP BY pgmm.displayType;";
565      $result=pwg_query($sql);
566      if($result)
567      {
568        while($row=pwg_db_fetch_assoc($result))
569        {
570          $db=$row;
571        }
572      }
573
574      if($id=='' and
575          ($db['displayType']=='IC' or $db['displayType']=='IP') and
576          $db['nbId']>0
577        )
578      {
579        return('!'.l10n('gmaps_only_one_map_is_allowed_for_this_mode'));
580      }
581
582
583      if($id=='')
584      {
585        $sql="INSERT INTO ".$this->tables['category_maps']."
586              VALUES ('', '".
587                $properties['categoryId']."', '".
588                $properties['mapId']."', '".
589                ($db['maxImgSort']+1)."', '".
590                $properties['applySubCat']."', '".
591                $properties['kmlFileUrl']."', '".
592                $properties['icon']."', '".
593                mysql_escape_string($properties['title'])."');";
594        $result=pwg_query($sql);
595        $id=pwg_db_insert_id();
596      }
597      else
598      {
599        $sql="UPDATE ".$this->tables['category_maps']."
600              SET categoryId='".
601                $properties['categoryId']."', mapId='".
602                $properties['mapId']."', applySubCat='".
603                $properties['applySubCat']."', kmlFileUrl='".
604                $properties['kmlFileUrl']."', icon='".
605                $properties['icon']."', title='".
606                mysql_escape_string($properties['title'])."'
607              WHERE id='$id';";
608        $result=pwg_query($sql);
609      }
610
611      return($id);
612    } //ajax_gmaps_admin_assocSetAssoc
613
614
615
616
617    /**
618     * get properties for a given association id
619     *
620     * @param String id : the association Id
621     * @return String : data formatted in a JSON string
622     */
623    private function ajax_gmaps_admin_assocGetAssoc($id)
624    {
625      $returned=array(
626        'id' => '',
627        'categoryId' => 0,
628        'mapId' => '',
629        'applySubCat'=> 'y',
630        'kmlFileUrl' => '',
631        'icon' => '',
632        'title' => ''
633      );
634
635      $sql="SELECT id, categoryId, mapId, applySubCat, kmlFileUrl,
636                   icon, title
637            FROM ".$this->tables['category_maps']."
638            WHERE id='$id';";
639      $result=pwg_query($sql);
640      if($result)
641      {
642        while($row=pwg_db_fetch_assoc($result))
643        {
644          $returned=$row;
645        }
646      }
647
648      return(json_encode($returned));
649    } //ajax_gmaps_admin_assocGetAssoc
650
651
652
653
654    /**
655     * delete an association
656     *
657     * @param String id : if of the association to delete
658     * @return String : ok or ko
659     */
660    private function ajax_gmaps_admin_assocDeleteAssoc($id)
661    {
662      $sql="DELETE FROM ".$this->tables['category_maps']."
663            WHERE id='$id';";
664      $result=pwg_query($sql);
665      if($result) return('ok');
666
667      return('ko!unknown error');
668    } //ajax_gmaps_admin_assocDeleteAssoc
669
670
671    /**
672     * prepare the cache for the user / category
673     *
674     *
675     * @param Integer $category : the category Id, 0 if want to init map for all
676     *                            the gallery
677     * @return String : the requestId
678     */
679    private function ajax_gmaps_public_mapsInit($category)
680    {
681      global $prefixeTable, $template, $user, $conf;
682
683      $returned='';
684
685      $this->buildMapList($category, 'C');
686      if($category>0)
687      {
688        $sqlCatRestrict="AND FIND_IN_SET($category, pct.uppercats)!=0";
689      }
690      else
691      {
692        $sqlCatRestrict="";
693      }
694
695      if(count($this->maps)>0)
696      {
697        $scripts=array();
698        $bounds=array(
699          'N' => -90,
700          'S' => 90,
701          'E' => -180,
702          'W' => 180
703        );
704
705        // there is some maps to display
706        $requestId=date('Y-m-d h:i:s');
707
708        // delete cache (for user and data having more than 24h)
709        $sql="DELETE FROM ".$this->tables['cache']."
710              WHERE userId='".$user['id']."'
711                 OR requestId<'".date('Y-m-d h:i:s', time()-86400)."';";
712        pwg_query($sql);
713
714        // prepare the cache (same request in the 'GMaps_pip->displayCategoryPageMap' function)
715        $sql="SELECT DISTINCT pic.image_id, GROUP_CONCAT(DISTINCT pait.value ORDER BY pait.numID ASC SEPARATOR ';') AS coords,
716                GROUP_CONCAT(DISTINCT pic.category_id ORDER BY pic.category_id SEPARATOR ';') AS imageCatsId,
717                GROUP_CONCAT(DISTINCT pct.name ORDER BY pct.id SEPARATOR ';') AS imageCatsNames,
718                GROUP_CONCAT(DISTINCT IF(pct.permalink IS NULL, CONCAT('*', pct.id), pct.permalink) ORDER BY pct.id SEPARATOR ';') AS imageCatsPLink,
719                pit.name AS imageName, pit.path, pit.tn_ext
720              FROM ((((".USER_CACHE_CATEGORIES_TABLE." pucc
721                LEFT JOIN ".CATEGORIES_TABLE." pct ON pucc.cat_id = pct.id)
722                LEFT JOIN ".IMAGE_CATEGORY_TABLE." pic ON pic.category_id = pucc.cat_id)
723                LEFT JOIN ".$prefixeTable."amd_images_tags pait ON pait.imageId = pic.image_id)
724                LEFT JOIN ".$prefixeTable."amd_used_tags paut ON pait.numId = paut.numId)
725                LEFT JOIN ".IMAGES_TABLE." pit ON pit.id = pic.image_id
726              WHERE pucc.user_id = '".$user['id']."'
727               AND (paut.tagId = 'magic.GPS.LatitudeNum' OR paut.tagId = 'magic.GPS.LongitudeNum')
728               AND pic.image_id IS NOT NULL
729               $sqlCatRestrict
730               GROUP BY pic.image_id";
731/*
732 * get_sql_condition_FandF(
733                array
734                  (
735                    'forbidden_categories' => 'pic.category_id',
736                    'visible_categories' => 'pic.category_id',
737                    'visible_images' => 'pic.image_id'
738                  ),
739                'AND'
740              );
741*/
742        $result=pwg_query($sql);
743        if($result)
744        {
745          $massInsert=array();
746
747          while($row=pwg_db_fetch_assoc($result))
748          {
749            $coords=explode(';', $row['coords']);
750            $this->updateBounds($bounds, array(
751                'lat' => $coords[0],
752                'lng' => $coords[1]
753              )
754            );
755
756            $massInsert[]=array(
757              'userId' => $user['id'],
758              'requestId' => $requestId,
759              'imageId' => $row['image_id'],
760              'latitude' => $coords[0],
761              'longitude' => $coords[1],
762              'imageName' => mysql_escape_string($row['imageName']),
763              'imageTnFile' => dirname($row['path']).'/'.$conf['dir_thumbnail'].'/'.$conf['prefix_thumbnail'].get_filename_wo_extension(basename($row['path'])).'.'.$row['tn_ext'],
764              'imageCatsId' => $row['imageCatsId'],
765              'imageCatsNames' => mysql_escape_string($row['imageCatsNames']),
766              'imageCatsPLink' => $row['imageCatsPLink']
767            );
768          }
769
770          mass_inserts($this->tables['cache'], array('userId', 'requestId', 'imageId', 'latitude', 'longitude', 'imageName', 'imageTnFile', 'imageCatsId', 'imageCatsNames', 'imageCatsPLink'), $massInsert);
771
772          $returned=$requestId;
773        }
774      }
775
776      return($requestId);
777    }
778
779
780    /**
781     * returns a list of markers
782     *
783     *
784     * @param Array $datas : 'requestId' id of the request
785     *                       'bounds'  (north, east, west, south) : only markers
786     *                          inside the given bounds are returned
787     *                       'width' : width of maps in pixels
788     *                       'height' : height of maps in pixels
789     * @return Array|String : a JSON string of an array of points (nbPictures, lat, lng)
790     */
791    private function ajax_gmaps_public_mapsGetMarkers($datas)
792    {
793      global $user, $page;
794
795      $returned=array();
796
797      /*
798       * the 'make_picture_url' function use the 'get_root_url' function which
799       * use the $page['root_path'] value
800       *
801       * here, this $page index doesn't exist, so we need to initialize it
802       */
803      $page['root_path']='';
804
805      if($datas['bounds']['east']<$datas['bounds']['west'])
806      {
807        /*  E = -xxx    W = +xxx
808         *  a(lng E:+x)
809         *  b(lng W:-x)
810         *
811         *  E         +180/-180     W
812         * (+)                     (-)
813         *  +-------------+---------+
814         *  |             :         |
815         *  |             :    b    |
816         *  |     a       :         |
817         *  |             :         |
818         *  +-------------+---------+
819         *
820         */
821        $lngClause="
822              longitude <= ".$datas['bounds']['east']."
823              OR longitude >= ".$datas['bounds']['west']." ";
824      }
825      else
826      {
827        /*  E = -xxx    W = +xxx
828         *  a(lng W:-x)
829         *  b(lng E:+x)
830         *
831         *  W             0         E
832         * (-)                     (+)
833         *  +-------------+---------+
834         *  |             :         |
835         *  |             :    b    |
836         *  |      a      :         |
837         *  |             :         |
838         *  +-------------+---------+
839         *
840         */
841        $lngClause="
842              longitude >= ".$datas['bounds']['west']."
843              AND longitude <= ".$datas['bounds']['east']." ";
844      }
845
846      $sql="SELECT latitude, longitude, imageId, imageCatsId, imageCatsNames, imageTnFile, imageName, imageCatsPLink
847            FROM ".$this->tables['cache']."
848            WHERE userId='".$user['id']."'
849              AND requestId='".$datas['requestId']."'
850              AND ($lngClause)
851              AND latitude >= ".$datas['bounds']['south']."
852              AND latitude <= ".$datas['bounds']['north']."
853            ORDER BY latitude, longitude;";
854
855      $result=pwg_query($sql);
856      if($result)
857      {
858        // compute ratio map size / bound size
859        $ratioW=($datas['bounds']['east']-$datas['bounds']['west'])/$datas['width'];
860        $ratioH=($datas['bounds']['north']-$datas['bounds']['south'])/$datas['height'];
861        // works with the highest ratio
862        $ratio=max($ratioW, $ratioH);
863
864
865        $points=array();
866        $groups=array();
867
868        while($row=pwg_db_fetch_assoc($result))
869        {
870          $points[]=$row;
871        }
872
873        /*
874         *  build groups
875         */
876        while(count($points)>0)
877        {
878          $currentGroup=array();
879          $currentGroup[]=array_shift($points);
880
881          $i=0;
882          while($i<count($points))
883          {
884            $dist=sqrt(pow($points[$i]['latitude']-$currentGroup[0]['latitude'],2) + pow($points[$i]['longitude']-$currentGroup[0]['longitude'],2))/$ratio;
885
886            if($dist <= $datas['distanceTreshold'])
887            {
888              $tmp=array_splice($points, $i, 1);
889              $currentGroup[]=$tmp[0];
890              $points=array_values($points); // reset array index...
891            }
892            else
893            {
894              $i++;
895            }
896          }
897
898          $groups[]=$currentGroup;
899          unset($currentGroup);
900        }
901
902        /*
903         * for each group, calculate coordinates for a unique representative
904         * point
905         */
906        foreach($groups as $keyGroup => $group)
907        {
908          $coords=array(
909            'nbImagesTxt' => '',
910            'nbImages' => 0,
911            'latitude' => 0,
912            'longitude' => 0,
913            'imagesTnFile' => array(),
914            'imagesCatsNames' => array(),
915            'imagesName' => array(),
916            'imagesCatsUrl' => array(),
917          );
918
919          foreach($group as $point)
920          {
921            $tmpCatsUrl=array();
922            $tmpCatsId=explode(';', $point['imageCatsId']);
923            $tmpCatsNames=explode(';', $point['imageCatsNames']);
924            $tmpCatsPLinks=explode(';', $point['imageCatsPLink']);
925
926            foreach($tmpCatsId as $key => $id)
927            {
928              $tmpCatsUrl[]=make_picture_url(
929                array(
930                  'image_id' => $point['imageId'],
931                  'category' => array(
932                    'id' => $id,
933                    'name' => $tmpCatsNames[$key],
934                    'permalink' => (substr($tmpCatsPLinks[$key],0,1)=='*')?'':$tmpCatsPLinks[$key],
935                  )
936                )
937              );
938            }
939
940            $coords['nbImages']++;
941            $coords['latitude']+=$point['latitude'];
942            $coords['longitude']+=$point['longitude'];
943            $coords['imagesTnFile'][]=$point['imageTnFile'];
944            $coords['imagesCatsNames'][]=$tmpCatsNames;
945            $coords['imagesName'][]=$point['imageName'];
946            $coords['imagesCatsUrl'][]=$tmpCatsUrl;
947          }
948          $coords['latitude']=$coords['latitude']/count($group);
949          $coords['longitude']=$coords['longitude']/count($group);
950          $coords['uniqueId']=md5($coords['latitude'].$coords['latitude']);
951
952          if($coords['nbImages']==1)
953          {
954            $coords['nbImagesTxt']=l10n('gmaps_1_picture');
955          }
956          else
957          {
958            $coords['nbImagesTxt']=sprintf(l10n('gmaps_nb_pictures'), $coords['nbImages']);
959          }
960
961          $returned[]=$coords;
962        }
963      }
964
965      return(json_encode($returned));
966    }
967
968
969  } //class
970
971
972  $returned=new GMaps_Ajax($prefixeTable, __FILE__);
973?>
Note: See TracBrowser for help on using the repository browser.