source: extensions/GMaps/gmaps_ajax.php @ 7147

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

change interface for icons&marker style selection

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