source: extensions/GMaps/gmaps_root.class.inc.php @ 7616

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

fix bug:2004 - Cache table becomes very huge
fix bug:2005 - Category map is not displayed when a [gmaps] map is inserted in category description

  • Property svn:executable set to *
File size: 12.2 KB
Line 
1<?php
2/* -----------------------------------------------------------------------------
3  Plugin     : GMaps
4  Author     : Grum
5    email    : grum@piwigo.org
6    website  : http://photos.grum.fr
7
8    << May the Little SpaceFrog be with you ! >>
9  ------------------------------------------------------------------------------
10  See main.inc.php for release information
11
12  GMaps_root : common classe for admin and public classes
13
14  --------------------------------------------------------------------------- */
15  include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/CommonPlugin.class.inc.php');
16  include_once(PHPWG_PLUGINS_PATH.'GrumPluginClasses/classes/GPCCss.class.inc.php');
17
18  class GMaps_root extends CommonPlugin
19  {
20    const KML_DIRECTORY='/local/plugins/GMaps/kml/';
21    const ID_MODE_CATEGORY = 'C';
22    const ID_MODE_MAP='M';
23
24    protected $css;
25    protected $maps=array();
26    protected $forceDisplay=0;
27
28    /**
29     * check the available AMD release
30     */
31    static public function checkAMDRelease()
32    {
33      if(!defined('AMD_VERSION')) return(false);
34
35      $currentAMDRelease = explode(".", GPC_VERSION);
36
37      $neededAMDRelease=explode('.', GMAPS_AMD_NEEDED);
38      $major=$neededAMDRelease[0];
39      $minor=$neededAMDRelease[1];
40      $minor2=$neededAMDRelease[2];
41
42      if(($currentAMDRelease[0]>$major) ||
43         ($currentAMDRelease[0]==$major)&&($currentAMDRelease[1]>$minor) ||
44         ($currentAMDRelease[0]==$major)&&($currentAMDRelease[1]==$minor)&&($currentAMDRelease[2]>=$minor2))
45      {
46        return(true);
47      }
48      return(false);
49    }
50
51    /**
52     * check if AMD plugin is activated and mode
53     *
54     * @return String : 'none' if plugin is not installed
55     *                  'inactive' if plugin is not active
56     *                  'basic' if plugin active in basic mode
57     *                  'advanced' if plugin active in advanced mode
58     */
59    static public function checkAMDActivated()
60    {
61      if(!self::checkAMDRelease()) return('none');
62
63      $sql="SELECT state FROM ".PLUGINS_TABLE." WHERE id='AMetaData';";
64      $result=pwg_query($sql);
65      if($result)
66      {
67        $row=pwg_db_fetch_assoc($result);
68        if(!(isset($row['state']) and $row['state']='active')) return('inactive');
69
70        $amdConfig=array();
71        GPCCore::loadConfig('amd', $amdConfig);
72
73        if($amdConfig['newInstall']=='n') return($amdConfig['amd_InterfaceMode']);
74      }
75
76      return('none');
77    }
78
79
80    public function __construct($prefixeTable, $filelocation)
81    {
82      $this->setPluginName('GMaps');
83      $this->setPluginNameFiles("gmaps");
84      parent::__construct($prefixeTable, $filelocation);
85      $this->section_name=$this->getPluginNameFiles();
86
87      $this->setTablesList(array('maps', 'category_maps', 'cache', 'cache_id', 'kmlfiles'));
88      $this->css = new GPCCss(dirname($this->getFileLocation()).'/'.$this->getPluginNameFiles().".css");
89    }
90
91    public function __destruct()
92    {
93      parent::__destruct();
94    }
95
96    public function initEvents()
97    {
98    }
99
100
101    /*
102      surchage of CommonPlugin->saveConfig function
103    */
104    public function saveConfig()
105    {
106      if(parent::saveConfig())
107      {
108        return(true);
109      }
110      return(false);
111    }
112
113    /*
114      surchage of CommonPlugin->saveConfig function
115    */
116    public function loadConfig()
117    {
118      parent::loadConfig();
119    }
120
121    /*
122      intialize default values
123    */
124    public function initConfig()
125    {
126      //global $user;
127      $this->config=array(
128        'popupAutomaticSize' => 0.8
129      );
130    }
131
132
133    /**
134     *
135     */
136    protected function configForTemplate()
137    {
138      global $template;
139
140      $template->assign('gmapsConfig', $this->config);
141    }
142
143
144    public function getAdminLink($mode='')
145    {
146      if($mode=='ajax')
147      {
148        return('plugins/'.basename(dirname($this->getFileLocation())).'/gmaps_ajax.php');
149      }
150      else
151      {
152        return(parent::getAdminLink());
153      }
154    }
155
156    protected function displayResult($action_msg, $result)
157    {
158      global $page;
159
160      if($result)
161      {
162        array_push($page['infos'], $action_msg);
163      }
164      else
165      {
166        array_push($page['errors'], $action_msg);
167      }
168    }
169
170
171    /* ---------------------------------------------------------------------------
172
173    --------------------------------------------------------------------------- */
174
175    /**
176     * update the given bound with the given coords
177     *
178     * @param &Array $bounds : the bounds (N,S,E,W)
179     * @param Array $coords  : coords (0=>lat, 1=>lng)
180     */
181    protected function updateBounds(&$bounds, $coords)
182    {
183      if($bounds['E']<$coords['lng']) $bounds['E']=$coords['lng'];
184      if($bounds['N']<$coords['lat']) $bounds['N']=$coords['lat'];
185      if($bounds['W']>$coords['lng']) $bounds['W']=$coords['lng'];
186      if($bounds['S']>$coords['lat']) $bounds['S']=$coords['lat'];
187    }
188
189    /**
190     * build the list of maps (initialize the $this->maps var)
191     *
192     * used by GMaps_ajax & GMaps_pip classes
193     *
194     * @param String $category : id of categories id
195     * @param String $page : 'P' for picture page, 'C' for category page
196     * @param String $mode : self::ID_MODE_CATEGORY = given id is a category id
197     *                       self::ID_MODE_MAP      = given id is a map id
198     */
199    protected function buildMapList($id, $page, $mode)
200    {
201      global $template ;
202
203      $this->maps=array();
204      $this->forceDisplay=0;
205
206      if($mode==self::ID_MODE_CATEGORY)
207      {
208        if($page=='C')
209        {
210          $where=" displayType='IC' ";
211        }
212        else
213        {
214          $where=" (displayType='IP' or displayType='MP') ";
215        }
216
217        /*
218         * sql request select all possible association, sorted from the highest to
219         * the lowest priority
220         */
221        $sql="SELECT DISTINCT pgcm.id, pgcm.categoryId,
222                pgcm.imgSort, pgcm.applySubCat, pgcm.kmlFileUrl, pgcm.kmlFileId, pgkf.file AS kmlFileUrlId,
223                pgcm.icon, pgcm.title, pgcm.marker,
224                pgmm.displayType, pgmm.sizeMode,
225                pgmm.width, pgmm.height, pgmm.zoomLevel,
226                pgmm.mapType, pgmm.mapTypeControl, pgmm.scaleControl, pgmm.streetViewControl,
227                pgmm.navigationControl, pgmm.style, pgmm.zoomLevelMaxActivated,
228                IF(pgcm.categoryId=0, 0, pct.global_rank) AS priorityRank,
229                pgcm.forceDisplay
230              FROM ((".$this->tables['category_maps']." pgcm
231                    LEFT JOIN ".$this->tables['maps']." pgmm ON pgcm.mapId = pgmm.id)
232                    LEFT JOIN ".CATEGORIES_TABLE." pct ON (FIND_IN_SET(pgcm.categoryId, pct.uppercats)!=0 OR pgcm.categoryId=0))
233                    LEFT JOIN ".$this->tables['kmlfiles']." pgkf ON  pgkf.id = pgcm.kmlFileId
234              WHERE $where ";
235        if($id!=0)
236        {
237          $sql.=" AND pct.id = '$id' ";
238        }
239        else
240        {
241          $sql.=" AND pgcm.categoryId = 0 ";
242        }
243        $sql.=" AND pgcm.applySubCat='y'
244              ORDER BY priorityRank DESC, pgmm.displayType ASC, pgcm.categoryId ASC, pgcm.imgSort ASC;";
245      }
246      elseif($mode==self::ID_MODE_MAP)
247      {
248        $sql="SELECT DISTINCT
249                pgmm.displayType, pgmm.sizeMode,
250                pgmm.width, pgmm.height, pgmm.zoomLevel,
251                pgmm.mapType, pgmm.mapTypeControl, pgmm.scaleControl, pgmm.streetViewControl,
252                pgmm.navigationControl, pgmm.style, pgmm.zoomLevelMaxActivated,
253                '' AS kmlFileUrl, 0 AS kmlFileId, 'y' AS forceDisplay
254              FROM ".$this->tables['maps']." pgmm
255              WHERE pgmm.id=$id";
256      }
257      else
258      {
259        return(false);
260      }
261
262      $result=pwg_query($sql);
263
264      if($result)
265      {
266        // for each found row, choose the highest only
267        $pcat='';
268        $displayType=array(
269         'IC' => true,
270         'IP' => true,
271         'MP' => true,
272        );
273        while($row=pwg_db_fetch_assoc($result))
274        {
275          // if an kml file id is given, apply the url of the file (needs to give the complete URI for google)
276          if($row['kmlFileId']>0 and $row['kmlFileUrlId']!='') $row['kmlFileUrl']=dirname($_SERVER['SCRIPT_URI']).self::KML_DIRECTORY.rawurlencode($row['kmlFileUrlId']);
277
278          if($row['displayType']!='MP' and $mode==self::ID_MODE_CATEGORY)
279          {
280            $themeConf=$template->get_template_vars('themeconf');
281            $fileName=preg_replace('/^([i|c]\d+x\d+)(?:_\d+){0,1}(\..*)/i', '$1$2', $row['icon']);
282
283            if(file_exists(PHPWG_ROOT_PATH.$themeConf['icon_dir'].'/gmaps/'.$fileName))
284            {
285              $row['icon']=$themeConf['icon_dir'].'/gmaps/'.$fileName;
286              $row['iconStyle']=false;
287            }
288            else
289            {
290              $row['icon']='plugins/GMaps/img/'.$row['icon'];
291              $row['iconStyle']=true;
292            }
293          }
294
295          if($displayType[$row['displayType']])
296          {
297            if($row['displayType']=='MP')
298            {
299              if($displayType['MP'] and ($row['categoryId']==$pcat or $pcat=='')) $this->maps[]=$row;
300              if($displayType['MP'] and $row['categoryId']!=$pcat and $pcat!='') $displayType['MP']=false;
301              $pcat=$row['categoryId'];
302            }
303            else
304            {
305              $this->maps[]=$row;
306              $displayType[$row['displayType']]=false;
307              if($row['forceDisplay']=='y' and ($row['kmlFileUrl']!='' or $row['kmlFileId']!=0)) $this->forceDisplay++;
308            }
309          }
310        }
311      }
312    }
313
314
315    /**
316     * returns a new requestId for the cache
317     */
318    protected function getCacheRequestId()
319    {
320      global $user;
321
322      $returned=0;
323
324      // new requestId
325      $sql="INSERT INTO ".$this->tables['cache_id']."
326            VALUES ('', '".$user['id']."', '".date('Y-m-d h:i:s')."');";
327      $result=pwg_query($sql);
328      if($result)
329      {
330        $returned=pwg_db_insert_id();
331      }
332
333      return($returned);
334    }
335
336    /**
337     * update date for a cache requestId
338     */
339    protected function updateCacheRequestId($requestId)
340    {
341      global $user;
342
343      // new requestId
344      $sql="UPDATE ".$this->tables['cache_id']."
345            SET `date` = '".date('Y-m-d h:i:s')."'
346            WHERE requestId='$requestId';";
347      pwg_query($sql);
348    }
349
350    /**
351     * clean the cache : cache values older than given number of second are
352     * deleted
353     *
354     * @param Integer $time : number of second
355     */
356    protected function cleanCache($time=300)
357    {
358      $date=date('Y-m-d h:i:s', time()-$time);
359
360      $sql="DELETE FROM ".$this->tables['cache']." pgc
361              USING ".$this->tables['cache']." pgc
362                JOIN ".$this->tables['cache_id']." pgci
363                ON pgc.requestId = pgci.requestId
364            WHERE pgci.`date` < '$date';";
365      pwg_query($sql);
366
367      $sql="DELETE FROM ".$this->tables['cache_id']."
368            WHERE `date` < '$date';";
369      pwg_query($sql);
370    }
371
372  } //class
373
374
375
376class GMaps_functions
377{
378  static private $tables = Array();
379  static private $config = Array();
380
381  /**
382   * initialise the class
383   *
384   * @param String $prefixeTable : the piwigo prefixe used on tables name
385   * @param String $pluginNameFile : the plugin name used for tables name
386   */
387  static public function init($prefixeTable)
388  {
389    GPCCore::loadConfig(GMaps_root::$pluginNameFile, self::$config);
390    $list=GMaps_root::$pluginTables;
391
392    for($i=0;$i<count($list);$i++)
393    {
394      self::$tables[$list[$i]]=$prefixeTable.GMaps_root::$pluginNameFile.'_'.$list[$i];
395    }
396  }
397
398
399  /**
400   *  return all HTML&JS code necessary to display a dialogbox to choose
401   *  geographic area
402   */
403  static public function dialogBoxGMaps()
404  {
405    global $template;
406
407    $template->set_filename('gmaps_choose',
408                  dirname(__FILE__).'/templates/gmaps_dialog_area_choose.tpl');
409
410    $datas=Array();
411
412    $template->assign('datas', $datas);
413
414    return($template->parse('gmaps_choose', true));
415  }
416
417  /**
418   * convert a decimal degree to D°M'S'
419   *
420   * @param Float $value : the value to convert
421   * @return String : value converted in DMS
422   */
423  static public function DDtoDMS($value)
424  {
425    $degrees=(int)$value;
426    $value=($value-$degrees)*60;
427    $minutes=(int)$value;
428    $seconds=($value-$minutes)*60;
429
430    return(sprintf('%d° %d\' %.2f"', $degrees, $minutes, $seconds));
431  }
432} //GMaps_functions
433
434
435
436?>
Note: See TracBrowser for help on using the repository browser.