source: extensions/GMaps/gmaps_ajax.php @ 7457

Last change on this file since 7457 was 7453, checked in by grum, 13 years ago

fix bug:1972

File size: 43.3 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      if(!isset($_REQUEST['errcode'])) $_REQUEST['errcode']='';
63
64      // check if asked function is valid
65      if(!($_REQUEST['ajaxfct']=='admin.maps.getList' or
66           $_REQUEST['ajaxfct']=='admin.maps.setMap' or
67           $_REQUEST['ajaxfct']=='admin.maps.getMap' or
68           $_REQUEST['ajaxfct']=='admin.maps.deleteMap' or
69           $_REQUEST['ajaxfct']=='admin.assoc.getList' or
70           $_REQUEST['ajaxfct']=='admin.assoc.setAssoc' or
71           $_REQUEST['ajaxfct']=='admin.assoc.getAssoc' or
72           $_REQUEST['ajaxfct']=='admin.assoc.deleteAssoc' or
73           $_REQUEST['ajaxfct']=='admin.kmlFiles.getList' or
74           $_REQUEST['ajaxfct']=='admin.kmlFiles.setFile' or
75           $_REQUEST['ajaxfct']=='admin.kmlFiles.getFile' or
76           $_REQUEST['ajaxfct']=='admin.kmlFiles.deleteFile' or
77
78           $_REQUEST['ajaxfct']=='public.maps.init' or
79           $_REQUEST['ajaxfct']=='public.maps.getMarkers'
80           )) $_REQUEST['ajaxfct']='';
81
82      if(preg_match('/^admin\./i', $_REQUEST['ajaxfct']) and !is_admin()) $_REQUEST['ajaxfct']='';
83
84
85      if($_REQUEST['ajaxfct']!='')
86      {
87        /*
88         * no check for admin.maps.getList & admin.assoc.getList requests
89         */
90
91
92        /*
93         * check values for
94         *  admin.maps.getMap
95         *  admin.assoc.getAssoc
96         *  admin.kmlFiles.getFile
97         */
98        if($_REQUEST['ajaxfct']=="admin.maps.getMap" or
99           $_REQUEST['ajaxfct']=="admin.assoc.getAssoc" or
100           $_REQUEST['ajaxfct']=="admin.kmlFiles.getFile")
101        {
102          if(!isset($_REQUEST['id']) or
103             !is_numeric($_REQUEST['id']) or
104             $_REQUEST['id']=='') $_REQUEST['ajaxfct']='';
105        }
106
107        /*
108         * check values for
109         *  admin.maps.deleteMap
110         *  admin.assoc.deleteAssoc
111         *  admin.kmlFiles.deleteFile
112         */
113        if($_REQUEST['ajaxfct']=="admin.maps.deleteMap" or
114           $_REQUEST['ajaxfct']=="admin.assoc.deleteAssoc" or
115           $_REQUEST['ajaxfct']=="admin.kmlFiles.deleteFile")
116        {
117          if(!isset($_REQUEST['id']) or
118             !is_numeric($_REQUEST['id']) or
119             $_REQUEST['id']=='') $_REQUEST['ajaxfct']='';
120        }
121
122        /*
123         * check admin.maps.setMap values
124         */
125        if($_REQUEST['ajaxfct']=="admin.maps.setMap")
126        {
127          if(!isset($_REQUEST['id']) or
128             !isset($_REQUEST['datas']) or !is_array($_REQUEST['datas']))
129          {
130            $_REQUEST['ajaxfct']='';
131          }
132          else
133          {
134            if(!(isset($_REQUEST['datas']['displayType']) and
135                 isset($_REQUEST['datas']['sizeMode']) and
136                 isset($_REQUEST['datas']['name']) and
137                 isset($_REQUEST['datas']['width']) and
138                 isset($_REQUEST['datas']['height']) and
139                 isset($_REQUEST['datas']['zoomLevel']) and
140                 isset($_REQUEST['datas']['mapType']) and
141                 isset($_REQUEST['datas']['mapTypeControl']) and
142                 isset($_REQUEST['datas']['navigationControl']) and
143                 isset($_REQUEST['datas']['scaleControl']) and
144                 isset($_REQUEST['datas']['streetViewControl']) and
145                 isset($_REQUEST['datas']['style']) and
146                 isset($_REQUEST['datas']['zoomLevelMaxActivated'])
147                 ))
148            {
149              $_REQUEST['ajaxfct']='';
150            }
151            else
152            {
153              if(!($_REQUEST['datas']['displayType']=='IC' or
154                  $_REQUEST['datas']['displayType']=='IP' or
155                  $_REQUEST['datas']['displayType']=='MP')) $_REQUEST['ajaxfct']='';
156
157              if(!($_REQUEST['datas']['sizeMode']=='A' or
158                  $_REQUEST['datas']['sizeMode']=='F')) $_REQUEST['ajaxfct']='';
159
160              if(!is_numeric($_REQUEST['datas']['width']) or
161                  $_REQUEST['datas']['width']<100 or
162                  $_REQUEST['datas']['width']>1280) $_REQUEST['datas']['width']=470;
163
164              if(!is_numeric($_REQUEST['datas']['height']) or
165                  $_REQUEST['datas']['height']<100 or
166                  $_REQUEST['datas']['height']>1280) $_REQUEST['datas']['height']=210;
167
168              if(!is_numeric($_REQUEST['datas']['zoomLevel']) or
169                  $_REQUEST['datas']['zoomLevel']<1 or
170                  $_REQUEST['datas']['zoomLevel']>20) $_REQUEST['datas']['zoomLevel']=4;
171
172              if(!($_REQUEST['datas']['mapType']=='hybrid' or
173                  $_REQUEST['datas']['mapType']=='terrain' or
174                  $_REQUEST['datas']['mapType']=='roadmap' or
175                  $_REQUEST['datas']['mapType']=='satellite')) $_REQUEST['datas']['mapType']='hybrid';
176
177              if(!is_numeric($_REQUEST['datas']['mapTypeControl']) or
178                  $_REQUEST['datas']['mapTypeControl']<-1 or
179                  $_REQUEST['datas']['mapTypeControl']>2) $_REQUEST['datas']['mapTypeControl']=0;
180
181              if(!is_numeric($_REQUEST['datas']['navigationControl']) or
182                  $_REQUEST['datas']['navigationControl']<-1 or
183                  $_REQUEST['datas']['navigationControl']>3) $_REQUEST['datas']['navigationControl']=0;
184
185              if(!($_REQUEST['datas']['scaleControl']=='y' or
186                   $_REQUEST['datas']['scaleControl']=='n')) $_REQUEST['datas']['scaleControl']='y';
187
188              if(!($_REQUEST['datas']['streetViewControl']=='y' or
189                   $_REQUEST['datas']['streetViewControl']=='n')) $_REQUEST['datas']['streetViewControl']='n';
190
191              if(!($_REQUEST['datas']['zoomLevelMaxActivated']=='y' or
192                   $_REQUEST['datas']['zoomLevelMaxActivated']=='n')) $_REQUEST['datas']['zoomLevelMaxActivated']='n';
193            }
194          }
195        }
196
197
198        /*
199         * check admin.maps.setAssoc values
200         */
201        if($_REQUEST['ajaxfct']=="admin.assoc.setAssoc")
202        {
203          if(!isset($_REQUEST['id']) or
204             !isset($_REQUEST['datas']) or !is_array($_REQUEST['datas']))
205          {
206            $_REQUEST['ajaxfct']='';
207          }
208          else
209          {
210            if(!(isset($_REQUEST['datas']['categoryId']) and
211                 isset($_REQUEST['datas']['mapId']) and
212                 isset($_REQUEST['datas']['applySubCat']) and
213                 isset($_REQUEST['datas']['kmlFileId']) and
214                 isset($_REQUEST['datas']['kmlFileUrl']) and
215                 isset($_REQUEST['datas']['icon']) and
216                 isset($_REQUEST['datas']['marker']) and
217                 isset($_REQUEST['datas']['title']) ))
218            {
219              $_REQUEST['ajaxfct']='';
220            }
221            else
222            {
223              if($_REQUEST['datas']['categoryId']=='' or
224                 $_REQUEST['datas']['categoryId']<0) $_REQUEST['ajaxfct']='';
225
226              if($_REQUEST['datas']['mapId']=='') $_REQUEST['ajaxfct']='';
227
228              if(!($_REQUEST['datas']['applySubCat']=='y' or
229                   $_REQUEST['datas']['applySubCat']=='n')) $_REQUEST['datas']['applySubCat']='y';
230            }
231          }
232        }
233
234
235        /*
236         * check admin.kmlFiles.setFile values
237         */
238        if($_REQUEST['ajaxfct']=="admin.kmlFiles.setFile")
239        {
240          if(!isset($_REQUEST['id']) )
241          {
242            $_REQUEST['ajaxfct']='';
243          }
244          else
245          {
246            if($_REQUEST['id']=='')
247            {
248              if(!(isset($_FILES['file']['name']) and
249                   isset($_FILES['file']['tmp_name']))) $_REQUEST['ajaxfct']='';
250            }
251          }
252        }
253
254
255
256        /*
257         * check public.maps.getMarkers values
258         */
259        if($_REQUEST['ajaxfct']=="public.maps.getMarkers")
260        {
261          if(!isset($_REQUEST['datas']) or
262             !is_array($_REQUEST['datas']))
263          {
264            $_REQUEST['ajaxfct']='';
265          }
266          else
267          {
268            if(!(isset($_REQUEST['datas']['requestId']) and
269                 isset($_REQUEST['datas']['callId']) and
270                 isset($_REQUEST['datas']['bounds']) and
271                 isset($_REQUEST['datas']['width']) and
272                 isset($_REQUEST['datas']['height']) and
273                 isset($_REQUEST['datas']['distanceTreshold']) and
274                 isset($_REQUEST['datas']['bounds']['north']) and
275                 isset($_REQUEST['datas']['bounds']['south']) and
276                 isset($_REQUEST['datas']['bounds']['east']) and
277                 isset($_REQUEST['datas']['bounds']['west']) ))
278            {
279              $_REQUEST['ajaxfct']='';
280            }
281          }
282        }
283
284        /*
285         * check public.maps.getMarkerInfos values
286         */
287        if($_REQUEST['ajaxfct']=="public.maps.init")
288        {
289          if(!isset($_REQUEST['category']))
290          {
291            $_REQUEST['ajaxfct']='';
292          }
293        }
294      }
295    } //checkRequest
296
297
298    /**
299     * return ajax content
300     */
301    protected function returnAjaxContent()
302    {
303      $result="<p class='errors'>An error has occured</p>";
304      switch($_REQUEST['ajaxfct'])
305      {
306        case 'admin.maps.getList':
307          $result=$this->ajax_gmaps_admin_mapsGetList();
308          break;
309        case 'admin.maps.getMap':
310          $result=$this->ajax_gmaps_admin_mapsGetMap($_REQUEST['id']);
311          break;
312        case 'admin.maps.setMap':
313          $result=$this->ajax_gmaps_admin_mapsSetMap($_REQUEST['id'], $_REQUEST['datas']);
314          break;
315        case 'admin.maps.deleteMap':
316          $result=$this->ajax_gmaps_admin_mapsDeleteMap($_REQUEST['id']);
317          break;
318        case 'admin.assoc.getList':
319          $result=$this->ajax_gmaps_admin_assocGetList();
320          break;
321        case 'admin.assoc.getAssoc':
322          $result=$this->ajax_gmaps_admin_assocGetAssoc($_REQUEST['id']);
323          break;
324        case 'admin.assoc.setAssoc':
325          $result=$this->ajax_gmaps_admin_assocSetAssoc($_REQUEST['id'], $_REQUEST['datas']);
326          break;
327        case 'admin.assoc.deleteAssoc':
328          $result=$this->ajax_gmaps_admin_assocDeleteAssoc($_REQUEST['id']);
329          break;
330        case 'admin.kmlFiles.getList':
331          $result=$this->ajax_gmaps_admin_kmlFilesGetList();
332          break;
333        case 'admin.kmlFiles.getFile':
334          $result=$this->ajax_gmaps_admin_kmlFilesGetFile($_REQUEST['id']);
335          break;
336        case 'admin.kmlFiles.setFile':
337          $result=$this->ajax_gmaps_admin_kmlFilesSetFile($_REQUEST['id'], $_REQUEST['name']);
338          break;
339        case 'admin.kmlFiles.deleteFile':
340          $result=$this->ajax_gmaps_admin_kmlFilesDeleteFile($_REQUEST['id']);
341          break;
342
343
344        case 'public.maps.init':
345          $result=$this->ajax_gmaps_public_mapsInit($_REQUEST['category']);
346          break;
347        case 'public.maps.getMarkers':
348          $result=$this->ajax_gmaps_public_mapsGetMarkers($_REQUEST['datas']);
349          break;
350        case 'public.maps.getMarkersInfos':
351          $result=$this->ajax_gmaps_public_mapsGetMarkersInfos($_REQUEST['datas']);
352          break;
353      }
354      GPCAjax::returnResult($result);
355    }
356
357
358    /*------------------------------------------------------------------------*
359     *
360     * ADMIN FUNCTIONS
361     *
362     *----------------------------------------------------------------------- */
363
364    /**
365     * return a HTML list of defined maps
366     *
367     * @return String
368     */
369    private function ajax_gmaps_admin_mapsGetList()
370    {
371      global $template;
372
373      $template->set_filename('list_page',
374                    dirname($this->getFileLocation()).'/admin/gmaps_maps_iListMaps.tpl');
375
376      $datas=Array();
377
378      $sql="SELECT id, name, displayType, sizeMode, width, height, zoomLevel,
379                   mapType, mapTypeControl, navigationControl, scaleControl,
380                   streetViewControl, zoomLevelMaxActivated
381            FROM ".$this->tables['maps']."
382            ORDER BY displayType ASC, name ASC";
383      $result=pwg_query($sql);
384      if($result)
385      {
386        while($row=pwg_db_fetch_assoc($result))
387        {
388          if($row['displayType']=='IC')
389          {
390            $row['zoomLevel']=l10n('gmaps_auto');
391          }
392
393          $row['displayType']=l10n('gmaps_displayTypeShort'.$row['displayType']);
394
395          if($row['sizeMode']=='A')
396          {
397            $row['dimensions']=l10n('gmaps_auto');
398          }
399          else
400          {
401            $row['dimensions']=$row['width'].'x'.$row['height'];
402          }
403
404          $row['mapType']=l10n('gmaps_googleMapType_'.$row['mapType']);
405          $row['mapTypeControl']=l10n('gmaps_googleMapTypeControl_'.$row['mapTypeControl']);
406          $row['navigationControl']=l10n('gmaps_googleMapNavigationControl_'.$row['navigationControl']);
407          $row['scaleControl']=($row['scaleControl']=='y')?l10n('gmaps_display_visible'):l10n('gmaps_display_hidden');
408          $row['streetViewControl']=($row['streetViewControl']=='y')?l10n('gmaps_display_visible'):l10n('gmaps_display_hidden');
409          $datas[]=$row;
410        }
411      }
412
413      $template->assign('datas', $datas);
414      return($template->parse('list_page', true));
415    } //ajax_gmaps_admin_mapsGetList
416
417
418    /**
419     * set properties for a given map id ; if no map id is given, create a new
420     * map
421     *
422     * @param String id : the map Id
423     * @param Array datas : properties of the map (assuming array index were
424     *                      checked by the checkRequest function)
425     * @return String : the num id, or an error message
426     */
427    private function ajax_gmaps_admin_mapsSetMap($id, $properties)
428    {
429      global $template;
430
431      if($id=='')
432      {
433        $sql="INSERT INTO ".$this->tables['maps']."
434              VALUES ('', '".mysql_escape_string($properties['name'])."', '".
435                $properties['displayType']."', '".
436                $properties['sizeMode']."', '".
437                $properties['width']."', '".
438                $properties['height']."', '".
439                $properties['zoomLevel']."', '".
440                $properties['mapType']."', '".
441                $properties['mapTypeControl']."', '".
442                $properties['navigationControl']."', '".
443                $properties['scaleControl']."', '".
444                $properties['streetViewControl']."', '".
445                mysql_escape_string($properties['style'])."', '".
446                $properties['zoomLevelMaxActivated']."');";
447        $result=pwg_query($sql);
448        $id=pwg_db_insert_id();
449      }
450      else
451      {
452        $sql="UPDATE ".$this->tables['maps']."
453              SET name='".mysql_escape_string($properties['name'])."', displayType='".
454                $properties['displayType']."', sizeMode='".
455                $properties['sizeMode']."', width='".
456                $properties['width']."', height='".
457                $properties['height']."', zoomLevel='".
458                $properties['zoomLevel']."', mapType='".
459                $properties['mapType']."', mapTypeControl='".
460                $properties['mapTypeControl']."', navigationControl='".
461                $properties['navigationControl']."', scaleControl='".
462                $properties['scaleControl']."', streetViewControl='".
463                $properties['streetViewControl']."', style='".
464                mysql_escape_string($properties['style'])."', zoomLevelMaxActivated='".
465                $properties['zoomLevelMaxActivated']."'
466              WHERE id='$id';";
467        $result=pwg_query($sql);
468      }
469
470      return($id);
471    } //ajax_gmaps_admin_mapsSetMap
472
473
474    /**
475     * get properties for a given map id
476     *
477     * @param String id : the map Id
478     * @return String : data formatted in a JSON string
479     */
480    private function ajax_gmaps_admin_mapsGetMap($id)
481    {
482      $returned=array(
483        'id' => '',
484        'name' => '',
485        'displayType' => '',
486        'sizeMode' => '',
487        'width' => 470,
488        'height' => 210,
489        'zoomLevel' => 4,
490        'mapType' => 'hybrid',
491        'mapTypeControl' => 0,
492        'navigationControl' => 0,
493        'scaleControl' => 'y',
494        'streetViewControl' => 'n',
495        'zoomLevelMaxActivated' => 'n',
496        'associations' => 0,
497      );
498
499      $sql="SELECT pgmm.id, pgmm.displayType, pgmm.sizeMode, pgmm.name,
500                   pgmm.width, pgmm.height, pgmm.zoomLevel, pgmm.mapType,
501                   pgmm.mapTypeControl, pgmm.navigationControl,
502                   pgmm.scaleControl, pgmm.streetViewControl,
503                   pgmm.zoomLevelMaxActivated,
504                   COUNT(pgcm.id) AS nbAssoc
505            FROM ".$this->tables['maps']." pgmm
506                  LEFT JOIN ".$this->tables['category_maps']." pgcm
507                    ON pgcm.mapId=pgmm.id
508            WHERE pgmm.id='$id'
509            GROUP BY pgmm.id;";
510      $result=pwg_query($sql);
511      if($result)
512      {
513        while($row=pwg_db_fetch_assoc($result))
514        {
515          $returned=$row;
516        }
517      }
518
519      return(json_encode($returned));
520    } //ajax_gmaps_admin_mapsGetMap
521
522
523
524    /**
525     * delete a map
526     *
527     * @param String id : if of the map to delete
528     * @return String : ok or ko
529     */
530    private function ajax_gmaps_admin_mapsDeleteMap($id)
531    {
532      $sql="DELETE FROM ".$this->tables['maps']."
533            WHERE id='$id';";
534      $result=pwg_query($sql);
535      if($result)
536      {
537        $sql="DELETE FROM ".$this->tables['category_maps']."
538              WHERE map_id='$id';";
539        $result=pwg_query($sql);
540        if($result) return('ok');
541      }
542
543      return('ko!unknown error');
544    } //ajax_gmaps_admin_mapsDeleteMap
545
546
547
548
549
550    /**
551     * return a HTML list of defined associations
552     *
553     * @return String
554     */
555    private function ajax_gmaps_admin_assocGetList()
556    {
557      global $template;
558
559      $template->set_filename('list_page',
560                    dirname($this->getFileLocation()).'/admin/gmaps_category_maps_iListMaps.tpl');
561
562      $datas=Array();
563
564      $sql="SELECT pgcm.id, pgcm.categoryId, pct.name AS catName,
565                   pgmm.name AS mapName, pgmm.displayType,
566                   pgcm.kmlFileId, pgcm.kmlFileUrl, pgcm.imgSort, pgcm.applySubCat, pgcm.icon,
567                   pgcm.title, pgkf.name AS kmlName
568            FROM ((".$this->tables['category_maps']." pgcm
569                  LEFT JOIN ".CATEGORIES_TABLE." pct ON pct.id=pgcm.categoryId)
570                  LEFT JOIN ".$this->tables['maps']." pgmm ON pgcm.mapId = pgmm.id)
571                  LEFT JOIN ".$this->tables['kmlfiles']." pgkf ON pgkf.id = pgcm.kmlFileId
572            ORDER BY pct.name, pgmm.displayType, pgcm.imgSort";
573      $result=pwg_query($sql);
574      if($result)
575      {
576        $keys=array(
577          'prev' => '',
578          'curr' => ''
579        );
580        while($row=pwg_db_fetch_assoc($result))
581        {
582          $keys['prev']=$keys['curr'];
583
584          if($row['kmlFileId']>0)
585          {
586            $mapKmlFile=$row['kmlName'];
587          }
588          elseif($row['kmlFileUrl']!='')
589          {
590            $mapKmlFile='URL';
591          }
592          else
593          {
594            $mapKmlFile='';
595          }
596
597
598          $tmp=array(
599            'id' => $row['id'],
600            'catName' => ($row['categoryId']==0)?l10n('gmaps_applyForAllTheGallery'):$row['catName'],
601            'applySubCat' => l10n('gmaps_'.$row['applySubCat']),
602            'mapName' => $row['mapName'],
603            'mapKmlFile' => $mapKmlFile,
604            'icon' => $row['icon'],
605            'displayType' => l10n('gmaps_displayTypeShort'.$row['displayType']),
606            'title' => $row['title']
607          );
608
609          $keys['curr']=$row['categoryId'].$row['displayType'];
610
611          if($keys['curr']==$keys['prev'])
612          {
613            $tmp['catName']='';
614            $tmp['displayType']='';
615            $tmp['applySubCat']='';
616          }
617
618          $datas[]=$tmp;
619        }
620      }
621
622      $template->assign('datas', $datas);
623      return($template->parse('list_page', true));
624    } //ajax_gmaps_admin_assocGetList
625
626
627
628
629    /**
630     * set properties for a given association id ; if no association id is given
631     * create a new association
632     *
633     * @param String id : the association Id
634     * @param Array datas : properties of the association (assuming array index
635     *                      were checked by the checkRequest function)
636     * @return String : the num id, or an error message
637     */
638    private function ajax_gmaps_admin_assocSetAssoc($id, $properties)
639    {
640      global $template;
641
642      // if create a new assoc, get the last imgSort
643      $db=array(
644        'nbId' => 0,
645        'displayType' => '',
646        'maxImgSort' => 0
647      );
648
649      $sql="SELECT MAX(imgSort) AS maxImgSort, pgmm.displayType, COUNT(pgcm.id) AS nbId
650            FROM (".$this->tables['category_maps']." pgcm
651              LEFT JOIN ".$this->tables['maps']." pgmm ON pgmm.id = pgcm.mapId)
652              LEFT JOIN ".$this->tables['maps']." pgmm2 ON pgmm2.displayType=pgmm.displayType
653
654            WHERE categoryId='".$properties['categoryId']."'
655              AND pgmm2.id='".$properties['mapId']."'
656            GROUP BY pgmm.displayType;";
657      $result=pwg_query($sql);
658      if($result)
659      {
660        while($row=pwg_db_fetch_assoc($result))
661        {
662          $db=$row;
663        }
664      }
665
666      if($id=='' and
667          ($db['displayType']=='IC' or $db['displayType']=='IP') and
668          $db['nbId']>0
669        )
670      {
671        return('!'.l10n('gmaps_only_one_map_is_allowed_for_this_mode'));
672      }
673
674
675      if($id=='')
676      {
677        $sql="INSERT INTO ".$this->tables['category_maps']."
678              VALUES ('', '".
679                $properties['categoryId']."', '".
680                $properties['mapId']."', '".
681                ($db['maxImgSort']+1)."', '".
682                $properties['applySubCat']."', '".
683                $properties['kmlFileId']."', '".
684                $properties['kmlFileUrl']."', '".
685                basename($properties['icon'])."', '".
686                basename($properties['marker'])."', '".
687                mysql_escape_string($properties['title'])."');";
688        $result=pwg_query($sql);
689        $id=pwg_db_insert_id();
690      }
691      else
692      {
693        $sql="UPDATE ".$this->tables['category_maps']."
694              SET categoryId='".
695                $properties['categoryId']."', mapId='".
696                $properties['mapId']."', applySubCat='".
697                $properties['applySubCat']."', kmlFileUrl='".
698                $properties['kmlFileUrl']."', kmlFileId='".
699                $properties['kmlFileId']."', icon='".
700                basename($properties['icon'])."', marker='".
701                basename($properties['marker'])."', title='".
702                mysql_escape_string($properties['title'])."'
703              WHERE id='$id';";
704        $result=pwg_query($sql);
705      }
706
707      return($id);
708    } //ajax_gmaps_admin_assocSetAssoc
709
710
711
712
713    /**
714     * get properties for a given association id
715     *
716     * @param String id : the association Id
717     * @return String : data formatted in a JSON string
718     */
719    private function ajax_gmaps_admin_assocGetAssoc($id)
720    {
721      $returned=array(
722        'id' => '',
723        'categoryId' => 0,
724        'mapId' => '',
725        'applySubCat'=> 'y',
726        'kmlFileId' => 0,
727        'kmlFileUrl' => '',
728        'icon' => '',
729        'marker' => '',
730        'title' => ''
731      );
732
733      $sql="SELECT id, categoryId, mapId, applySubCat, kmlFileId, kmlFileUrl,
734                   icon, marker, title
735            FROM ".$this->tables['category_maps']."
736            WHERE id='$id';";
737      $result=pwg_query($sql);
738      if($result)
739      {
740        while($row=pwg_db_fetch_assoc($result))
741        {
742          $returned=$row;
743        }
744      }
745
746      return(json_encode($returned));
747    } //ajax_gmaps_admin_assocGetAssoc
748
749
750
751
752    /**
753     * delete an association
754     *
755     * @param String id : if of the association to delete
756     * @return String : ok or ko
757     */
758    private function ajax_gmaps_admin_assocDeleteAssoc($id)
759    {
760      $sql="DELETE FROM ".$this->tables['category_maps']."
761            WHERE id='$id';";
762      $result=pwg_query($sql);
763      if($result) return('ok');
764
765      return('ko!unknown error');
766    } //ajax_gmaps_admin_assocDeleteAssoc
767
768
769
770    /**
771     * return a HTML list of referenced kml files
772     *
773     * @return String
774     */
775    private function ajax_gmaps_admin_kmlFilesGetList()
776    {
777      global $template;
778
779      $template->set_filename('list_page',
780                    dirname($this->getFileLocation()).'/admin/gmaps_kmlfiles_iListFiles.tpl');
781
782      $datas=Array();
783
784      $sql="SELECT pgkf.id, pgkf.file, pgkf.name, pgkf.fileDate, pgkf.fileSize, COUNT(pgcm.id) AS nbAssoc
785            FROM ".$this->tables['kmlfiles']." pgkf
786                  LEFT JOIN ".$this->tables['category_maps']." pgcm ON pgcm.kmlFileId = pgkf.id
787            GROUP BY pgkf.id
788            ORDER BY pgkf.name";
789
790      $result=pwg_query($sql);
791      if($result)
792      {
793        while($row=pwg_db_fetch_assoc($result))
794        {
795          $row['fileSize']=GPCCore::formatOctet($row['fileSize']);
796          $datas[]=$row;
797        }
798      }
799
800      $template->assign('datas', $datas);
801      return($template->parse('list_page', true));
802    } //ajax_gmaps_admin_kmlFilesGetList
803
804
805
806
807    /**
808     * set properties for a given file id ; if no file id is given create a new
809     * file
810     *
811     * @param String $id : the file Id
812     * @param String $name : the name
813     * @param String $file : the file name
814     * @return String : the num id, or an error message
815     */
816    private function ajax_gmaps_admin_kmlFilesSetFile($id, $name)
817    {
818      global $template;
819
820      if(isset($_FILES['file']['name']))
821      {
822        $file=$_FILES['file']['name'];
823      }
824      else
825      {
826        $file='';
827      }
828
829      if($file=='' and $id!='')
830      {
831        // update name for an existing file
832        $sql="UPDATE ".$this->tables['kmlfiles']."
833              SET name='".mysql_escape_string($name)."'
834              WHERE id='$id';";
835        $result=pwg_query($sql);
836      }
837      elseif($file!='')
838      {
839        // check if this file is not already used by an another file id
840        $sql="SELECT file
841              FROM ".$this->tables['kmlfiles']."
842              WHERE file='".mysql_escape_string($_FILES['file']['name'])."'";
843        if($id!='') $sql.=" AND id!='$id'";
844        $result=pwg_query($sql);
845        if($result)
846        {
847          $ok='';
848          while($row=pwg_db_fetch_assoc($result))
849          {
850            $ok=$row['file'];
851          }
852          if($ok!='')
853          {
854            //file already used by another file id
855            header("Location: ".$_SERVER['HTTP_REFERER']."&errcode=aksf10");
856            exit();
857          }
858        }
859        else
860        {
861          //unknown error
862          header("Location: ".$_SERVER['HTTP_REFERER']."&errcode=aksf01");
863          exit();
864        }
865
866        $file=GPCCore::getPiwigoSystemPath().self::KML_DIRECTORY.$file;
867
868        if(file_exists($file)) unlink($file);
869        if($id!='')
870        {
871          $currentInfo=$this->ajax_gmaps_admin_kmlFilesGetFile($id, false);
872          if(file_exists(self::KML_DIRECTORY.$currentInfo['file'])) unlink(GPCCore::getPiwigoSystemPath().self::KML_DIRECTORY.$currentInfo['file']);
873        }
874
875
876        if(!move_uploaded_file($_FILES['file']['tmp_name'], $file))
877        {
878          /*
879           * something was wrong, previous file was deleted, so delete the file
880           * from the database
881           */
882          if($id!='') $this->ajax_gmaps_admin_kmlFilesDeleteFile($id);
883          // error when trying to copy the uploaded file
884          header("Location: ".$_SERVER['HTTP_REFERER']."&errcode=aksf02");
885          exit();
886        }
887
888        if($id!='')
889        {
890          // update file & name for an existing file
891          $sql="UPDATE ".$this->tables['kmlfiles']."
892                SET name='".mysql_escape_string($name)."',
893                    file='".mysql_escape_string($_FILES['file']['name'])."',
894                    fileSize=".filesize($file).",
895                    fileDate='".date('Y-m-d H:i:s', filemtime($file))."'
896                WHERE id='$id';";
897          $result=pwg_query($sql);
898        }
899        else
900        {
901          $sql="INSERT INTO ".$this->tables['kmlfiles']."
902                VALUES ('', '".mysql_escape_string($_FILES['file']['name'])."',
903                '".mysql_escape_string($name)."',
904                '".date('Y-m-d H:i:s', filemtime($file))."',
905                '".filesize($file)."')";
906          $result=pwg_query($sql);
907          $id=pwg_db_insert_id();
908        }
909
910        header("Location: ".$_SERVER['HTTP_REFERER']);
911        exit();
912      }
913
914
915
916      return($id);
917    } //ajax_gmaps_admin_kmlFilesSetFile
918
919
920
921    /**
922     * get properties for a given file id
923     *
924     * @param String id : the file Id
925     * @param Bool $json : if true, return a json string, otherwise an array
926     * @return String : data formatted in a JSON string
927     */
928    private function ajax_gmaps_admin_kmlFilesGetFile($id, $json=true)
929    {
930      $returned=array(
931        'id' => '',
932        'file' => '',
933        'name' => '',
934        'fileDate'=> '',
935        'fileSize' => 0,
936        'fileSizeUnits' => 0,
937      );
938
939      $sql="SELECT id, file, name, fileDate, fileSize
940            FROM ".$this->tables['kmlfiles']."
941            WHERE id='$id';";
942      $result=pwg_query($sql);
943      if($result)
944      {
945        while($row=pwg_db_fetch_assoc($result))
946        {
947          $row['fileSizeUnits']=GPCCore::formatOctet($row['fileSize']);
948          $returned=$row;
949        }
950      }
951
952      if($json)
953      {
954        return(json_encode($returned));
955      }
956      else
957      {
958        return($returned);
959      }
960    } //ajax_gmaps_admin_kmlFilesGetFile
961
962
963
964
965    /**
966     * delete a file
967     *
968     * @param String id : if of the file to delete
969     * @return String : ok or ko
970     */
971    private function ajax_gmaps_admin_kmlFilesDeleteFile($id)
972    {
973      $file='';
974
975      /*
976       * before deleting record in the table, get the associated file name stored
977       * on the server
978       */
979      $sql="SELECT file
980            FROM ".$this->tables['kmlfiles']."
981            WHERE id='$id';";
982      $result=pwg_query($sql);
983      if($result)
984      {
985        while($row=pwg_db_fetch_assoc($result))
986        {
987          $file=$row['file'];
988        }
989      }
990
991      // reset kmlFileId for assocation
992      $sql="UPDATE ".$this->tables['category_maps']."
993            SET kmlFileId='0'
994            WHERE kmlFileId='$id'";
995      pwg_query($sql);
996
997      // delete the file
998      $sql="DELETE FROM ".$this->tables['kmlfiles']."
999            WHERE id='$id';";
1000      $result=pwg_query($sql);
1001      if($result)
1002      {
1003        if($file!='' and file_exists(GPCCore::getPiwigoSystemPath().self::KML_DIRECTORY.$file))
1004        {
1005          unlink(GPCCore::getPiwigoSystemPath().self::KML_DIRECTORY.$file);
1006        }
1007        return('ok');
1008      }
1009      return('ko!unknown error');
1010    } //ajax_gmaps_admin_kmlFilesDeleteFile
1011
1012
1013
1014
1015    /**
1016     * prepare the cache for the user / category
1017     *
1018     *
1019     * @param Integer $category : the category Id, 0 if want to init map for all
1020     *                            the gallery
1021     * @return String : the requestId
1022     */
1023    private function ajax_gmaps_public_mapsInit($category)
1024    {
1025      global $prefixeTable, $template, $user, $conf;
1026
1027      $requestId='';
1028
1029      $this->buildMapList($category, 'C');
1030      if($category>0)
1031      {
1032        $sqlCatRestrict="AND FIND_IN_SET($category, pct.uppercats)!=0";
1033      }
1034      else
1035      {
1036        $sqlCatRestrict="";
1037      }
1038
1039      if(count($this->maps)>0)
1040      {
1041        $scripts=array();
1042        $bounds=array(
1043          'N' => -90,
1044          'S' => 90,
1045          'E' => -180,
1046          'W' => 180
1047        );
1048
1049        // there is some maps to display
1050        $requestId=date('Y-m-d h:i:s');
1051
1052        // delete cache (for user and data having more than 24h)
1053        $sql="DELETE FROM ".$this->tables['cache']."
1054              WHERE userId='".$user['id']."'
1055                 OR requestId<'".date('Y-m-d h:i:s', time()-86400)."';";
1056        pwg_query($sql);
1057
1058        // prepare the cache (same request in the 'GMaps_pip->displayCategoryPageMap' function)
1059        $sql="SELECT DISTINCT pic.image_id, GROUP_CONCAT(DISTINCT pait.value ORDER BY pait.numID ASC SEPARATOR ';') AS coords,
1060                GROUP_CONCAT(DISTINCT pic.category_id ORDER BY pic.category_id SEPARATOR ';') AS imageCatsId,
1061                GROUP_CONCAT(DISTINCT pct.name ORDER BY pct.id SEPARATOR ';') AS imageCatsNames,
1062                GROUP_CONCAT(DISTINCT IF(pct.permalink IS NULL, CONCAT('*', pct.id), pct.permalink) ORDER BY pct.id SEPARATOR ';') AS imageCatsPLink,
1063                pit.name AS imageName, pit.path, pit.tn_ext
1064              FROM ((((".USER_CACHE_CATEGORIES_TABLE." pucc
1065                LEFT JOIN ".CATEGORIES_TABLE." pct ON pucc.cat_id = pct.id)
1066                LEFT JOIN ".IMAGE_CATEGORY_TABLE." pic ON pic.category_id = pucc.cat_id)
1067                LEFT JOIN ".$prefixeTable."amd_images_tags pait ON pait.imageId = pic.image_id)
1068                LEFT JOIN ".$prefixeTable."amd_used_tags paut ON pait.numId = paut.numId)
1069                LEFT JOIN ".IMAGES_TABLE." pit ON pit.id = pic.image_id
1070              WHERE pucc.user_id = '".$user['id']."'
1071               AND (paut.tagId = 'magic.GPS.LatitudeNum' OR paut.tagId = 'magic.GPS.LongitudeNum')
1072               AND pic.image_id IS NOT NULL
1073               $sqlCatRestrict
1074               GROUP BY pic.image_id";
1075/*
1076 * get_sql_condition_FandF(
1077                array
1078                  (
1079                    'forbidden_categories' => 'pic.category_id',
1080                    'visible_categories' => 'pic.category_id',
1081                    'visible_images' => 'pic.image_id'
1082                  ),
1083                'AND'
1084              );
1085*/
1086
1087        $result=pwg_query($sql);
1088        if($result)
1089        {
1090          $massInsert=array();
1091
1092          while($row=pwg_db_fetch_assoc($result))
1093          {
1094            $coords=explode(';', $row['coords']);
1095            $this->updateBounds($bounds, array(
1096                'lat' => $coords[0],
1097                'lng' => $coords[1]
1098              )
1099            );
1100
1101            $massInsert[]=array(
1102              'userId' => $user['id'],
1103              'requestId' => $requestId,
1104              'imageId' => $row['image_id'],
1105              'latitude' => $coords[0],
1106              'longitude' => $coords[1],
1107              'imageName' => GPCCore::getUserLanguageDesc(mysql_escape_string($row['imageName'])),
1108              'imageTnFile' => dirname($row['path']).'/'.$conf['dir_thumbnail'].'/'.$conf['prefix_thumbnail'].get_filename_wo_extension(basename($row['path'])).'.'.$row['tn_ext'],
1109              'imageCatsId' => $row['imageCatsId'],
1110              'imageCatsNames' => mysql_escape_string($row['imageCatsNames']),
1111              'imageCatsPLink' => $row['imageCatsPLink']
1112            );
1113          }
1114
1115          mass_inserts($this->tables['cache'], array('userId', 'requestId', 'imageId', 'latitude', 'longitude', 'imageName', 'imageTnFile', 'imageCatsId', 'imageCatsNames', 'imageCatsPLink'), $massInsert);
1116
1117          $returned=$requestId;
1118        }
1119      }
1120
1121      return($requestId);
1122    }
1123
1124
1125    /**
1126     * returns a list of markers
1127     *
1128     *
1129     * @param Array $datas : 'requestId' id of the request
1130     *                       'bounds'  (north, east, west, south) : only markers
1131     *                          inside the given bounds are returned
1132     *                       'width' : width of maps in pixels
1133     *                       'height' : height of maps in pixels
1134     * @return Array|String : a JSON string of an array of points (nbPictures, lat, lng)
1135     */
1136    private function ajax_gmaps_public_mapsGetMarkers($datas)
1137    {
1138      global $user, $page;
1139
1140      $returned=array(
1141        'callId' => $datas['callId'],
1142        'markers' => array(),
1143        'datas' => array(
1144          'nbPhotos' => 0
1145        )
1146      );
1147
1148      /*
1149       * the 'make_picture_url' function use the 'get_root_url' function which
1150       * use the $page['root_path'] value
1151       *
1152       * here, this $page index doesn't exist, so we need to initialize it
1153       */
1154      $page['root_path']='';
1155
1156      if($datas['bounds']['east']<$datas['bounds']['west'])
1157      {
1158        /*  E = -xxx    W = +xxx
1159         *  a(lng E:+x)
1160         *  b(lng W:-x)
1161         *
1162         *  E         +180/-180     W
1163         * (+)                     (-)
1164         *  +-------------+---------+
1165         *  |             :         |
1166         *  |             :    b    |
1167         *  |     a       :         |
1168         *  |             :         |
1169         *  +-------------+---------+
1170         *
1171         */
1172        $lngClause="
1173              longitude <= ".$datas['bounds']['east']."
1174              OR longitude >= ".$datas['bounds']['west']." ";
1175      }
1176      else
1177      {
1178        /*  E = -xxx    W = +xxx
1179         *  a(lng W:-x)
1180         *  b(lng E:+x)
1181         *
1182         *  W             0         E
1183         * (-)                     (+)
1184         *  +-------------+---------+
1185         *  |             :         |
1186         *  |             :    b    |
1187         *  |      a      :         |
1188         *  |             :         |
1189         *  +-------------+---------+
1190         *
1191         */
1192        $lngClause="
1193              longitude >= ".$datas['bounds']['west']."
1194              AND longitude <= ".$datas['bounds']['east']." ";
1195      }
1196
1197      $sql="SELECT latitude, longitude, imageId, imageCatsId, imageCatsNames, imageTnFile, imageName, imageCatsPLink
1198            FROM ".$this->tables['cache']."
1199            WHERE userId='".$user['id']."'
1200              AND requestId='".$datas['requestId']."'
1201              AND ($lngClause)
1202              AND latitude >= ".$datas['bounds']['south']."
1203              AND latitude <= ".$datas['bounds']['north']."
1204            ORDER BY latitude, longitude;";
1205
1206      $result=pwg_query($sql);
1207      if($result)
1208      {
1209        // compute ratio map size / bound size
1210        $ratioW=($datas['bounds']['east']-$datas['bounds']['west'])/$datas['width'];
1211        $ratioH=($datas['bounds']['north']-$datas['bounds']['south'])/$datas['height'];
1212        // works with the highest ratio
1213        $ratio=max($ratioW, $ratioH);
1214        $datas['distanceTreshold']=pow($datas['distanceTreshold']*$ratio,2);
1215
1216
1217        $groups=array();
1218
1219
1220        /*
1221         *  build groups
1222         */
1223        while($row=pwg_db_fetch_assoc($result))
1224        {
1225          if(!$this->checkInGroup($row, $groups, $datas['distanceTreshold']))
1226          {
1227            $groups[]=array($row);
1228          }
1229        }
1230
1231
1232        /*
1233         * for each group, calculate coordinates for a unique representative
1234         * point
1235         */
1236        foreach($groups as $keyGroup => $group)
1237        {
1238          $coords=array(
1239            'nbImgTxt' => '',
1240            'nbImg' => 0,
1241            'lat' => 0,                   // 'lat' rather than 'latitude'
1242            'lng' => 0,                   // 'lng' rather than 'longitude'
1243            'imgTn' => array(),
1244            'imgCatsNames' => array(),
1245            'imgName' => array(),
1246            'imgCatsUrl' => array(),
1247          );
1248
1249          foreach($group as $point)
1250          {
1251            $tmpCatsUrl=array();
1252            $tmpCatsId=explode(';', $point['imageCatsId']);
1253            $tmpCatsNames=explode(';', $point['imageCatsNames']);
1254            $tmpCatsPLinks=explode(';', $point['imageCatsPLink']);
1255
1256            foreach($tmpCatsId as $key => $id)
1257            {
1258              $tmpCatsUrl[]=make_picture_url(
1259                array(
1260                  'image_id' => $point['imageId'],
1261                  'category' => array(
1262                    'id' => $id,
1263                    'name' => GPCCore::getUserLanguageDesc($tmpCatsNames[$key]),
1264                    'permalink' => (substr($tmpCatsPLinks[$key],0,1)=='*')?'':$tmpCatsPLinks[$key],
1265                  )
1266                )
1267              );
1268            }
1269
1270            if(count($tmpCatsId)<=1) $tmpCatsNames='';
1271
1272            $coords['nbImg']++;
1273
1274            $coords['lat']+=$point['latitude'];
1275            $coords['lng']+=$point['longitude'];
1276
1277            $coords['imgTn'][]=$point['imageTnFile'];
1278            $coords['imgCatsNames'][]=$tmpCatsNames;
1279            $coords['imgName'][]=GPCCore::getUserLanguageDesc($point['imageName']);
1280            $coords['imgCatsUrl'][]=$tmpCatsUrl;
1281          }
1282          $coords['lat']=$coords['lat']/count($group);
1283          $coords['lng']=$coords['lng']/count($group);
1284          $coords['uId']=md5($coords['lat'].$coords['lng']);
1285
1286          if($coords['nbImg']==1)
1287          {
1288            $coords['nbImgTxt']=l10n('gmaps_1_picture');
1289          }
1290          else
1291          {
1292            $coords['nbImgTxt']=sprintf(l10n('gmaps_nb_pictures'), $coords['nbImg']);
1293          }
1294
1295          $returned['markers'][]=$coords;
1296          $returned['datas']['nbPhotos']+=$coords['nbImg'];
1297        }
1298      }
1299
1300      if($returned['datas']['nbPhotos']>1)
1301      {
1302        $returned['datas']['nbPhotos']=sprintf(l10n('gmaps_nb_pictures'), $returned['datas']['nbPhotos']);
1303      }
1304      elseif($returned['datas']['nbPhotos']==1)
1305      {
1306        $returned['datas']['nbPhotos']=l10n('gmaps_1_picture');
1307      }
1308      else
1309      {
1310        $returned['datas']['nbPhotos']=l10n('gmaps_0_picture');
1311      }
1312
1313      return(json_encode($returned));
1314    } //ajax_gmaps_public_mapsGetMarkers
1315
1316    /**
1317     * check if a point is inside an existing group, and add it
1318     * @param Array $point : the point
1319     * @param Array &$groups : the groups
1320     * @param Float $maxDist : maximum distance to be inside group
1321     * @return Bool : true if added in a group, otherwise false
1322     */
1323    private function checkInGroup($point, &$groups, $maxDist)
1324    {
1325      foreach($groups as $key=>$group)
1326      {
1327        $dist=pow($point['latitude']-$group[0]['latitude'],2) + pow($point['longitude']-$group[0]['longitude'],2);
1328
1329        if($dist<=$maxDist)
1330        {
1331          $groups[$key][]=$point;
1332          return(true);
1333        }
1334      }
1335      return(false);
1336    }
1337
1338    /**
1339     * replace the root directroy for image
1340     *  => './galleries/' becomes "G"
1341     *  => './upload/' becomes "U"
1342     *  => other case : no chnages
1343     *
1344     * @param String $value : path
1345     * @returned String :
1346     */
1347    private function replaceImgRoot($value)
1348    {
1349      if(preg_match('/^\.\/galleries\//i', $value)>0)
1350      {
1351        return("G".substr($value,12));
1352      }
1353      elseif("U".preg_match('/^\.\/upload\//i', $value)>0)
1354      {
1355        return(substr($value,9));
1356      }
1357      return($value);
1358    }
1359
1360  } //class
1361
1362
1363  $returned=new GMaps_Ajax($prefixeTable, __FILE__);
1364?>
Note: See TracBrowser for help on using the repository browser.