source: extensions/GMaps/gmaps_ajax.php @ 7177

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

Fix bugs on install process ; add street view control management

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