source: extensions/GMaps/gmaps_ajax.php @ 7128

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

Connect the plugin to the RBuilder component + fixe some small bugs

File size: 32.4 KB
RevLine 
[7054]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
[7125]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
[7128]74           $_REQUEST['ajaxfct']=='public.maps.getMarkers' //or
75           //$_REQUEST['ajaxfct']=='public.maps.getMarkerInfos'
[7054]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        /*
[7125]84         * no check for admin.maps.getList & admin.assoc.getList requests
[7054]85         */
86
[7125]87
[7054]88        /*
[7125]89         * check admin.maps.getMap & admin.assoc.getAssoc values
[7054]90         */
[7125]91        if($_REQUEST['ajaxfct']=="admin.maps.getMap" or
92           $_REQUEST['ajaxfct']=="admin.assoc.getAssoc")
[7054]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         */
[7125]102        if($_REQUEST['ajaxfct']=="admin.maps.deleteMap" or
103           $_REQUEST['ajaxfct']=="admin.maps.deleteAssoc")
[7054]104        {
105          if(!isset($_REQUEST['id']) or
106             !is_numeric($_REQUEST['id']) or
107             $_REQUEST['id']=='') $_REQUEST['ajaxfct']='';
108        }
109
110        /*
[7125]111         * check admin.maps.setMap values
[7054]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          {
[7125]122            if(!(isset($_REQUEST['datas']['displayType']) &&
123                 isset($_REQUEST['datas']['sizeMode']) &&
[7054]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            {
[7125]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
[7054]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
[7125]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            }
[7128]236            else
237            {
238              if(!isset($_REQUEST['datas']['levelInfo'])) $_REQUEST['datas']['levelInfo']=1;
239
240              if(!($_REQUEST['datas']['levelInfo']==0 or
241                   $_REQUEST['datas']['levelInfo']==1)) $_REQUEST['datas']['levelInfo']=1;
242            }
[7125]243          }
244        }
245
246        /*
247         * check public.maps.getMarkerInfos values
248         */
249        if($_REQUEST['ajaxfct']=="public.maps.init")
250        {
251          if(!isset($_REQUEST['category']))
252          {
253            $_REQUEST['ajaxfct']='';
254          }
[7128]255
256
[7125]257        }
258
[7054]259      }
260    } //checkRequest
261
262
263    /**
264     * return ajax content
265     */
266    protected function returnAjaxContent()
267    {
268      $result="<p class='errors'>An error has occured</p>";
269      switch($_REQUEST['ajaxfct'])
270      {
271        case 'admin.maps.getList':
272          $result=$this->ajax_gmaps_admin_mapsGetList();
273          break;
274        case 'admin.maps.getMap':
275          $result=$this->ajax_gmaps_admin_mapsGetMap($_REQUEST['id']);
276          break;
277        case 'admin.maps.setMap':
278          $result=$this->ajax_gmaps_admin_mapsSetMap($_REQUEST['id'], $_REQUEST['datas']);
279          break;
280        case 'admin.maps.deleteMap':
281          $result=$this->ajax_gmaps_admin_mapsDeleteMap($_REQUEST['id']);
282          break;
[7125]283        case 'admin.assoc.getList':
284          $result=$this->ajax_gmaps_admin_assocGetList();
285          break;
286        case 'admin.assoc.getAssoc':
287          $result=$this->ajax_gmaps_admin_assocGetAssoc($_REQUEST['id']);
288          break;
289        case 'admin.assoc.setAssoc':
290          $result=$this->ajax_gmaps_admin_assocSetAssoc($_REQUEST['id'], $_REQUEST['datas']);
291          break;
292        case 'admin.assoc.deleteAssoc':
293          $result=$this->ajax_gmaps_admin_assocDeleteAssoc($_REQUEST['id']);
294          break;
295
296        case 'public.maps.init':
297          $result=$this->ajax_gmaps_public_mapsInit($_REQUEST['category']);
298          break;
299        case 'public.maps.getMarkers':
300          $result=$this->ajax_gmaps_public_mapsGetMarkers($_REQUEST['datas']);
301          break;
[7054]302      }
303      GPCAjax::returnResult($result);
304    }
305
306
307    /*------------------------------------------------------------------------*
308     *
309     * ADMIN FUNCTIONS
310     *
311     *----------------------------------------------------------------------- */
312
313    /**
314     * return a HTML list of defined maps
315     *
316     * @return String
317     */
318    private function ajax_gmaps_admin_mapsGetList()
319    {
320      global $template;
321
322      $template->set_filename('list_page',
323                    dirname($this->getFileLocation()).'/admin/gmaps_maps_iListMaps.tpl');
324
325      $datas=Array();
326
[7125]327      $sql="SELECT id, name, displayType, sizeMode, width, height, zoomLevel, mapType, mapTypeControl, navigationControl, scaleControl
[7054]328            FROM ".$this->tables['maps']."
[7125]329            ORDER BY displayType ASC, name ASC";
[7054]330      $result=pwg_query($sql);
331      if($result)
332      {
333        while($row=pwg_db_fetch_assoc($result))
334        {
[7125]335          if($row['displayType']=='IC')
336          {
337            $row['zoomLevel']=l10n('gmaps_auto');
338          }
[7054]339
[7125]340          $row['displayType']=l10n('gmaps_displayTypeShort'.$row['displayType']);
341
342          if($row['sizeMode']=='A')
343          {
344            $row['dimensions']=l10n('gmaps_auto');
345          }
346          else
347          {
348            $row['dimensions']=$row['width'].'x'.$row['height'];
349          }
350
[7054]351          $row['mapType']=l10n('gmaps_googleMapType_'.$row['mapType']);
352          $row['mapTypeControl']=l10n('gmaps_googleMapTypeControl_'.$row['mapTypeControl']);
353          $row['navigationControl']=l10n('gmaps_googleMapNavigationControl_'.$row['navigationControl']);
354          $row['scaleControl']=($row['scaleControl']=='y')?l10n('gmaps_display_visible'):l10n('gmaps_display_hidden');
355          $datas[]=$row;
356        }
357      }
358
359      $template->assign('datas', $datas);
360      return($template->parse('list_page', true));
361    } //ajax_gmaps_admin_mapsGetList
362
363
364    /**
365     * set properties for a given map id ; if no map id is given, create a new
366     * map
367     *
368     * @param String id : the map Id
369     * @param Array datas : properties of the map (assuming array index were
370     *                      checked by the checkRequest function)
371     * @return String : the num id, or an error message
372     */
373    private function ajax_gmaps_admin_mapsSetMap($id, $properties)
374    {
375      global $template;
376
377      if($id=='')
378      {
379        $sql="INSERT INTO ".$this->tables['maps']."
[7125]380              VALUES ('', '".mysql_escape_string($properties['name'])."', '".
381                $properties['displayType']."', '".
382                $properties['sizeMode']."', '".
[7054]383                $properties['width']."', '".
384                $properties['height']."', '".
385                $properties['zoomLevel']."', '".
386                $properties['mapType']."', '".
387                $properties['mapTypeControl']."', '".
388                $properties['navigationControl']."', '".
389                $properties['scaleControl']."', '".
390                mysql_escape_string($properties['style'])."');";
391        $result=pwg_query($sql);
392        $id=pwg_db_insert_id();
393      }
394      else
395      {
396        $sql="UPDATE ".$this->tables['maps']."
[7125]397              SET name='".mysql_escape_string($properties['name'])."', displayType='".
398                $properties['displayType']."', sizeMode='".
399                $properties['sizeMode']."', width='".
[7054]400                $properties['mapId']."', width='".
401                $properties['width']."', height='".
402                $properties['height']."', zoomLevel='".
403                $properties['zoomLevel']."', mapType='".
404                $properties['mapType']."', mapTypeControl='".
405                $properties['mapTypeControl']."', navigationControl='".
406                $properties['navigationControl']."', scaleControl='".
407                $properties['scaleControl']."', style='".
408                mysql_escape_string($properties['style'])."'
409              WHERE id='$id';";
410        $result=pwg_query($sql);
411      }
412
413      return($id);
414    } //ajax_gmaps_admin_mapsSetMap
415
416
417    /**
418     * get properties for a given map id
419     *
420     * @param String id : the map Id
421     * @return String : data formatted in a JSON string
422     */
423    private function ajax_gmaps_admin_mapsGetMap($id)
424    {
425      $returned=array(
426        'id' => '',
427        'name' => '',
[7125]428        'displayType' => '',
429        'sizeMode' => '',
[7054]430        'width' => 470,
431        'height' => 210,
432        'zoomLevel' => 4,
433        'mapType' => 'hybrid',
434        'mapTypeControl' => 0,
435        'navigationControl' => 0,
436        'scaleControl' => 'y'
437      );
438
[7125]439      $sql="SELECT id, displayType, sizeMode, name, width, height, zoomLevel, mapType, mapTypeControl, navigationControl, scaleControl
[7054]440            FROM ".$this->tables['maps']."
441            WHERE id='$id';";
442      $result=pwg_query($sql);
443      if($result)
444      {
445        while($row=pwg_db_fetch_assoc($result))
446        {
447          $returned=$row;
448        }
449      }
450
451      return(json_encode($returned));
[7125]452    } //ajax_gmaps_admin_mapsGetMap
[7054]453
454
455
456    /**
457     * delete a map
458     *
459     * @param String id : if of the map to delete
460     * @return String : ok or ko
461     */
462    private function ajax_gmaps_admin_mapsDeleteMap($id)
463    {
464      $sql="DELETE FROM ".$this->tables['maps']."
465            WHERE id='$id';";
466      $result=pwg_query($sql);
467      if($result)
468      {
469        $sql="DELETE FROM ".$this->tables['category_maps']."
470              WHERE map_id='$id';";
471        $result=pwg_query($sql);
472        if($result) return('ok');
473      }
474
475      return('ko!unknown error');
[7125]476    } //ajax_gmaps_admin_mapsDeleteMap
477
478
479
480
481
482    /**
483     * return a HTML list of defined associations
484     *
485     * @return String
486     */
487    private function ajax_gmaps_admin_assocGetList()
488    {
489      global $template;
490
491      $template->set_filename('list_page',
492                    dirname($this->getFileLocation()).'/admin/gmaps_category_maps_iListMaps.tpl');
493
494      $datas=Array();
495
496      $sql="SELECT pgcm.id, pgcm.categoryId, pct.name AS catName,
497                   pgmm.name AS mapName, pgmm.displayType,
498                   pgcm.kmlFileUrl, pgcm.imgSort, pgcm.applySubCat, pgcm.icon,
499                   pgcm.title
500            FROM (".$this->tables['category_maps']." pgcm
501                  LEFT JOIN ".CATEGORIES_TABLE." pct ON pct.id=pgcm.categoryId)
502                  LEFT JOIN ".$this->tables['maps']." pgmm ON pgcm.mapId = pgmm.id
503            ORDER BY pct.name, pgmm.displayType, pgcm.imgSort";
504      $result=pwg_query($sql);
505      if($result)
506      {
507        $keys=array(
508          'prev' => '',
509          'curr' => ''
510        );
511        while($row=pwg_db_fetch_assoc($result))
512        {
513          $keys['prev']=$keys['curr'];
514
515          $tmp=array(
516            'id' => $row['id'],
517            'catName' => ($row['categoryId']==0)?l10n('gmaps_applyForAllTheGallery'):$row['catName'],
518            'applySubCat' => l10n('gmaps_'.$row['applySubCat']),
519            'mapName' => $row['mapName'],
520            'mapKmlFile' => l10n('gmaps_'.(($row['kmlFileUrl']=='')?'n':'y')),
521            'icon' => $row['icon'],
522            'displayType' => l10n('gmaps_displayTypeShort'.$row['displayType']),
523            'title' => $row['title']
524          );
525
526          $keys['curr']=$row['categoryId'].$row['displayType'];
527
528          if($keys['curr']==$keys['prev'])
529          {
530            $tmp['catName']='';
531            $tmp['displayType']='';
532            $tmp['applySubCat']='';
533          }
534
535          $datas[]=$tmp;
536        }
537      }
538
539      $template->assign('datas', $datas);
540      return($template->parse('list_page', true));
541    } //ajax_gmaps_admin_assocGetList
542
543
544
545
546    /**
547     * set properties for a given association id ; if no association id is given
548     * create a new association
549     *
550     * @param String id : the association Id
551     * @param Array datas : properties of the association (assuming array index
552     *                      were checked by the checkRequest function)
553     * @return String : the num id, or an error message
554     */
555    private function ajax_gmaps_admin_assocSetAssoc($id, $properties)
556    {
557      global $template;
558
559      // if create a new assoc, get the last imgSort
560      $db=array(
561        'nbId' => 0,
562        'displayType' => '',
563        'maxImgSort' => 0
564      );
565
566      $sql="SELECT MAX(imgSort) AS maxImgSort, pgmm.displayType, COUNT(pgcm.id) AS nbId
567            FROM (".$this->tables['category_maps']." pgcm
568              LEFT JOIN ".$this->tables['maps']." pgmm ON pgmm.id = pgcm.mapId)
569              LEFT JOIN ".$this->tables['maps']." pgmm2 ON pgmm2.displayType=pgmm.displayType
570
571            WHERE categoryId='".$properties['categoryId']."'
572              AND pgmm2.id='".$properties['mapId']."'
573            GROUP BY pgmm.displayType;";
574      $result=pwg_query($sql);
575      if($result)
576      {
577        while($row=pwg_db_fetch_assoc($result))
578        {
579          $db=$row;
580        }
581      }
582
583      if($id=='' and
584          ($db['displayType']=='IC' or $db['displayType']=='IP') and
585          $db['nbId']>0
586        )
587      {
588        return('!'.l10n('gmaps_only_one_map_is_allowed_for_this_mode'));
589      }
590
591
592      if($id=='')
593      {
594        $sql="INSERT INTO ".$this->tables['category_maps']."
595              VALUES ('', '".
596                $properties['categoryId']."', '".
597                $properties['mapId']."', '".
598                ($db['maxImgSort']+1)."', '".
599                $properties['applySubCat']."', '".
600                $properties['kmlFileUrl']."', '".
601                $properties['icon']."', '".
602                mysql_escape_string($properties['title'])."');";
603        $result=pwg_query($sql);
604        $id=pwg_db_insert_id();
605      }
606      else
607      {
608        $sql="UPDATE ".$this->tables['category_maps']."
609              SET categoryId='".
610                $properties['categoryId']."', mapId='".
611                $properties['mapId']."', applySubCat='".
612                $properties['applySubCat']."', kmlFileUrl='".
613                $properties['kmlFileUrl']."', icon='".
614                $properties['icon']."', title='".
615                mysql_escape_string($properties['title'])."'
616              WHERE id='$id';";
617        $result=pwg_query($sql);
618      }
619
620      return($id);
621    } //ajax_gmaps_admin_assocSetAssoc
622
623
624
625
626    /**
627     * get properties for a given association id
628     *
629     * @param String id : the association Id
630     * @return String : data formatted in a JSON string
631     */
632    private function ajax_gmaps_admin_assocGetAssoc($id)
633    {
634      $returned=array(
635        'id' => '',
636        'categoryId' => 0,
637        'mapId' => '',
638        'applySubCat'=> 'y',
639        'kmlFileUrl' => '',
640        'icon' => '',
641        'title' => ''
642      );
643
644      $sql="SELECT id, categoryId, mapId, applySubCat, kmlFileUrl,
645                   icon, title
646            FROM ".$this->tables['category_maps']."
647            WHERE id='$id';";
648      $result=pwg_query($sql);
649      if($result)
650      {
651        while($row=pwg_db_fetch_assoc($result))
652        {
653          $returned=$row;
654        }
655      }
656
657      return(json_encode($returned));
658    } //ajax_gmaps_admin_assocGetAssoc
659
660
661
662
663    /**
664     * delete an association
665     *
666     * @param String id : if of the association to delete
667     * @return String : ok or ko
668     */
669    private function ajax_gmaps_admin_assocDeleteAssoc($id)
670    {
671      $sql="DELETE FROM ".$this->tables['category_maps']."
672            WHERE id='$id';";
673      $result=pwg_query($sql);
674      if($result) return('ok');
675
676      return('ko!unknown error');
677    } //ajax_gmaps_admin_assocDeleteAssoc
678
679
680    /**
681     * prepare the cache for the user / category
682     *
683     *
684     * @param Integer $category : the category Id, 0 if want to init map for all
685     *                            the gallery
686     * @return String : the requestId
687     */
688    private function ajax_gmaps_public_mapsInit($category)
689    {
690      global $prefixeTable, $template, $user, $conf;
691
692      $returned='';
693
694      $this->buildMapList($category, 'C');
695      if($category>0)
696      {
697        $sqlCatRestrict="AND FIND_IN_SET($category, pct.uppercats)!=0";
698      }
699      else
700      {
701        $sqlCatRestrict="";
702      }
703
704      if(count($this->maps)>0)
705      {
706        $scripts=array();
707        $bounds=array(
708          'N' => -90,
709          'S' => 90,
710          'E' => -180,
711          'W' => 180
712        );
713
714        // there is some maps to display
715        $requestId=date('Y-m-d h:i:s');
716
717        // delete cache (for user and data having more than 24h)
718        $sql="DELETE FROM ".$this->tables['cache']."
719              WHERE userId='".$user['id']."'
720                 OR requestId<'".date('Y-m-d h:i:s', time()-86400)."';";
721        pwg_query($sql);
722
723        // prepare the cache (same request in the 'GMaps_pip->displayCategoryPageMap' function)
724        $sql="SELECT DISTINCT pic.image_id, GROUP_CONCAT(DISTINCT pait.value ORDER BY pait.numID ASC SEPARATOR ';') AS coords,
725                GROUP_CONCAT(DISTINCT pic.category_id ORDER BY pic.category_id SEPARATOR ';') AS imageCatsId,
726                GROUP_CONCAT(DISTINCT pct.name ORDER BY pct.id SEPARATOR ';') AS imageCatsNames,
727                GROUP_CONCAT(DISTINCT IF(pct.permalink IS NULL, CONCAT('*', pct.id), pct.permalink) ORDER BY pct.id SEPARATOR ';') AS imageCatsPLink,
728                pit.name AS imageName, pit.path, pit.tn_ext
729              FROM ((((".USER_CACHE_CATEGORIES_TABLE." pucc
730                LEFT JOIN ".CATEGORIES_TABLE." pct ON pucc.cat_id = pct.id)
731                LEFT JOIN ".IMAGE_CATEGORY_TABLE." pic ON pic.category_id = pucc.cat_id)
732                LEFT JOIN ".$prefixeTable."amd_images_tags pait ON pait.imageId = pic.image_id)
733                LEFT JOIN ".$prefixeTable."amd_used_tags paut ON pait.numId = paut.numId)
734                LEFT JOIN ".IMAGES_TABLE." pit ON pit.id = pic.image_id
735              WHERE pucc.user_id = '".$user['id']."'
736               AND (paut.tagId = 'magic.GPS.LatitudeNum' OR paut.tagId = 'magic.GPS.LongitudeNum')
737               AND pic.image_id IS NOT NULL
738               $sqlCatRestrict
739               GROUP BY pic.image_id";
740/*
741 * get_sql_condition_FandF(
742                array
743                  (
744                    'forbidden_categories' => 'pic.category_id',
745                    'visible_categories' => 'pic.category_id',
746                    'visible_images' => 'pic.image_id'
747                  ),
748                'AND'
749              );
750*/
751        $result=pwg_query($sql);
752        if($result)
753        {
754          $massInsert=array();
755
756          while($row=pwg_db_fetch_assoc($result))
757          {
758            $coords=explode(';', $row['coords']);
759            $this->updateBounds($bounds, array(
760                'lat' => $coords[0],
761                'lng' => $coords[1]
762              )
763            );
764
765            $massInsert[]=array(
766              'userId' => $user['id'],
767              'requestId' => $requestId,
768              'imageId' => $row['image_id'],
769              'latitude' => $coords[0],
770              'longitude' => $coords[1],
771              'imageName' => mysql_escape_string($row['imageName']),
772              'imageTnFile' => dirname($row['path']).'/'.$conf['dir_thumbnail'].'/'.$conf['prefix_thumbnail'].get_filename_wo_extension(basename($row['path'])).'.'.$row['tn_ext'],
773              'imageCatsId' => $row['imageCatsId'],
774              'imageCatsNames' => mysql_escape_string($row['imageCatsNames']),
775              'imageCatsPLink' => $row['imageCatsPLink']
776            );
777          }
778
779          mass_inserts($this->tables['cache'], array('userId', 'requestId', 'imageId', 'latitude', 'longitude', 'imageName', 'imageTnFile', 'imageCatsId', 'imageCatsNames', 'imageCatsPLink'), $massInsert);
780
781          $returned=$requestId;
782        }
783      }
784
785      return($requestId);
[7054]786    }
787
788
[7125]789    /**
790     * returns a list of markers
791     *
792     *
793     * @param Array $datas : 'requestId' id of the request
794     *                       'bounds'  (north, east, west, south) : only markers
795     *                          inside the given bounds are returned
796     *                       'width' : width of maps in pixels
797     *                       'height' : height of maps in pixels
[7128]798     *                       'levelInfo' : 0 = don't return pictures info (name, url, ...)
799     *                                     1 = return pictures informations
[7125]800     * @return Array|String : a JSON string of an array of points (nbPictures, lat, lng)
801     */
802    private function ajax_gmaps_public_mapsGetMarkers($datas)
803    {
804      global $user, $page;
[7054]805
[7128]806      $returned=array(
807        'markers' => array(),
808        'datas' => array(
809          'nbPhotos' => 0
810        )
811      );
[7125]812
813      /*
814       * the 'make_picture_url' function use the 'get_root_url' function which
815       * use the $page['root_path'] value
816       *
817       * here, this $page index doesn't exist, so we need to initialize it
818       */
819      $page['root_path']='';
820
821      if($datas['bounds']['east']<$datas['bounds']['west'])
822      {
823        /*  E = -xxx    W = +xxx
824         *  a(lng E:+x)
825         *  b(lng W:-x)
826         *
827         *  E         +180/-180     W
828         * (+)                     (-)
829         *  +-------------+---------+
830         *  |             :         |
831         *  |             :    b    |
832         *  |     a       :         |
833         *  |             :         |
834         *  +-------------+---------+
835         *
836         */
837        $lngClause="
838              longitude <= ".$datas['bounds']['east']."
839              OR longitude >= ".$datas['bounds']['west']." ";
840      }
841      else
842      {
843        /*  E = -xxx    W = +xxx
844         *  a(lng W:-x)
845         *  b(lng E:+x)
846         *
847         *  W             0         E
848         * (-)                     (+)
849         *  +-------------+---------+
850         *  |             :         |
851         *  |             :    b    |
852         *  |      a      :         |
853         *  |             :         |
854         *  +-------------+---------+
855         *
856         */
857        $lngClause="
858              longitude >= ".$datas['bounds']['west']."
859              AND longitude <= ".$datas['bounds']['east']." ";
860      }
861
862      $sql="SELECT latitude, longitude, imageId, imageCatsId, imageCatsNames, imageTnFile, imageName, imageCatsPLink
863            FROM ".$this->tables['cache']."
864            WHERE userId='".$user['id']."'
865              AND requestId='".$datas['requestId']."'
866              AND ($lngClause)
867              AND latitude >= ".$datas['bounds']['south']."
868              AND latitude <= ".$datas['bounds']['north']."
869            ORDER BY latitude, longitude;";
870
871      $result=pwg_query($sql);
872      if($result)
873      {
874        // compute ratio map size / bound size
875        $ratioW=($datas['bounds']['east']-$datas['bounds']['west'])/$datas['width'];
876        $ratioH=($datas['bounds']['north']-$datas['bounds']['south'])/$datas['height'];
877        // works with the highest ratio
878        $ratio=max($ratioW, $ratioH);
879
880
881        $points=array();
882        $groups=array();
883
884        while($row=pwg_db_fetch_assoc($result))
885        {
886          $points[]=$row;
887        }
888
889        /*
890         *  build groups
891         */
892        while(count($points)>0)
893        {
894          $currentGroup=array();
895          $currentGroup[]=array_shift($points);
896
897          $i=0;
898          while($i<count($points))
899          {
900            $dist=sqrt(pow($points[$i]['latitude']-$currentGroup[0]['latitude'],2) + pow($points[$i]['longitude']-$currentGroup[0]['longitude'],2))/$ratio;
901
902            if($dist <= $datas['distanceTreshold'])
903            {
904              $tmp=array_splice($points, $i, 1);
905              $currentGroup[]=$tmp[0];
906              $points=array_values($points); // reset array index...
907            }
908            else
909            {
910              $i++;
911            }
912          }
913
914          $groups[]=$currentGroup;
915          unset($currentGroup);
916        }
917
918        /*
919         * for each group, calculate coordinates for a unique representative
920         * point
921         */
922        foreach($groups as $keyGroup => $group)
923        {
924          $coords=array(
[7128]925            'nbImgTxt' => '',
[7125]926            'nbImages' => 0,
[7128]927            'lat' => 0,                   // 'lat' rather than 'latitude'
928            'lng' => 0,                   // 'lng' rather than 'longitude'
929            'imgTn' => array(),
930            'imgCatsNames' => array(),
931            'imgName' => array(),
932            'imgCatsUrl' => array(),
[7125]933          );
934
935          foreach($group as $point)
936          {
937            $tmpCatsUrl=array();
938            $tmpCatsId=explode(';', $point['imageCatsId']);
939            $tmpCatsNames=explode(';', $point['imageCatsNames']);
940            $tmpCatsPLinks=explode(';', $point['imageCatsPLink']);
941
942            foreach($tmpCatsId as $key => $id)
943            {
944              $tmpCatsUrl[]=make_picture_url(
945                array(
946                  'image_id' => $point['imageId'],
947                  'category' => array(
948                    'id' => $id,
949                    'name' => $tmpCatsNames[$key],
950                    'permalink' => (substr($tmpCatsPLinks[$key],0,1)=='*')?'':$tmpCatsPLinks[$key],
951                  )
952                )
953              );
954            }
955
[7128]956            if(count($tmpCatsId)<=1) $tmpCatsNames='';
957
[7125]958            $coords['nbImages']++;
[7128]959
960            $coords['lat']+=$point['latitude'];
961            $coords['lng']+=$point['longitude'];
962
963            if($datas['levelInfo']==1)
964            {
965              $coords['imgTn'][]=substr($point['imageTnFile'],12);
966              $coords['imgCatsNames'][]=$tmpCatsNames;
967              $coords['imgName'][]=$point['imageName'];
968              $coords['imgCatsUrl'][]=$tmpCatsUrl;
969            }
[7125]970          }
[7128]971          $coords['lat']=$coords['lat']/count($group);
972          $coords['lng']=$coords['lng']/count($group);
973          $coords['uniqueId']=md5($coords['lat'].$coords['lng']);
[7125]974
975          if($coords['nbImages']==1)
976          {
[7128]977            $coords['nbImgTxt']=l10n('gmaps_1_picture');
[7125]978          }
979          else
980          {
[7128]981            $coords['nbImgTxt']=sprintf(l10n('gmaps_nb_pictures'), $coords['nbImages']);
[7125]982          }
983
[7128]984
985
986          $returned['markers'][]=$coords;
987          $returned['datas']['nbPhotos']+=$coords['nbImages'];
[7125]988        }
989      }
990
[7128]991      if($returned['datas']['nbPhotos']>1)
992      {
993        $returned['datas']['nbPhotos']=sprintf(l10n('gmaps_nb_pictures'), $returned['datas']['nbPhotos']);
994      }
995      else
996      {
997        $returned['datas']['nbPhotos']=l10n('gmaps_1_picture');
998      }
999
[7125]1000      return(json_encode($returned));
1001    }
1002
1003
[7054]1004  } //class
1005
1006
1007  $returned=new GMaps_Ajax($prefixeTable, __FILE__);
1008?>
Note: See TracBrowser for help on using the repository browser.