source: extensions/GrumPluginClasses/classes/GPCCore.class.inc.php @ 7387

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

Fix bugs

File size: 14.1 KB
Line 
1<?php
2
3/* -----------------------------------------------------------------------------
4  class name     : GPCCore
5  class version  : 1.3.1
6  plugin version : 3.3.2
7  date           : 2010-10-20
8  ------------------------------------------------------------------------------
9  author: grum at piwigo.org
10  << May the Little SpaceFrog be with you >>
11  ------------------------------------------------------------------------------
12
13  :: HISTORY
14
15| release | date       |
16| 1.0.0   | 2010/03/30 | * Update class & function names
17|         |            |
18| 1.1.0   | 2010/03/30 | * add the BBtoHTML function
19|         |            |
20| 1.2.0   | 2010/07/28 | * add the loadConfigFromFile function
21|         |            |
22| 1.3.0   | 2010/10/13 | * add the addHeaderCSS, addHeaderJS functions
23|         |            |
24| 1.3.1   | 2010/10/20 | * applyHeaderItems functions implemented with an
25|         |            |   higher priority on the 'loc_begin_page_header' event
26|         |            |
27|         |            | * implement the getUserLanguageDesc() function, using
28|         |            |   extended description function if present
29|         |            |
30|         |            | * implement the getPiwigoSystemPath function
31|         |            |
32|         |            | * implement the rmDir function
33|         |            |
34|         |            |
35
36  ------------------------------------------------------------------------------
37    no constructor, only static function are provided
38    - static function loadConfig
39    - static function loadConfigFromFile
40    - static function saveConfig
41    - static function deleteConfig
42    - static function getRegistered
43    - static function getModulesInfos
44    - static function register
45    - static function unregister
46    - static function BBtoHTML
47    - static function addHeaderCSS
48    - static function addHeaderJS
49    - static function getUserLanguageDesc
50    - static function getPiwigoSystemPath
51    - static function formatOctet
52    - static function rmDir
53   ---------------------------------------------------------------------- */
54
55
56
57class GPCCore
58{
59  static private $piwigoSystemPath;
60
61  static public $pluginName = "GPCCore";
62  static protected $headerItems = array(
63    'css' => array(),
64    'js'  => array()
65  );
66
67  static public function init()
68  {
69    self::$piwigoSystemPath=dirname(dirname(dirname(dirname(__FILE__))));
70  }
71
72  /* ---------------------------------------------------------------------------
73   * grum plugin classes informations functions
74   * -------------------------------------------------------------------------*/
75  static public function getModulesInfos()
76  {
77    return(
78      Array(
79        Array('name' => "CommonPlugin", 'version' => "2.2.0"),
80        Array('name' => "GPCAjax", 'version' => "3.0.0"),
81        Array('name' => "GPCCore", 'version' => "1.3.1"),
82        Array('name' => "GPCCss", 'version' => "3.0.0"),
83        Array('name' => "GPCPagesNavigations", 'version' => "2.0.0"),
84        Array('name' => "GPCPublicIntegration", 'version' => "2.0.0"),
85        Array('name' => "GPCRequestBuilder", 'version' => "1.1.0"),
86        Array('name' => "GPCTables", 'version' => "1.5.0"),
87        Array('name' => "GPCTabSheet", 'version' => "1.1.1"),
88        Array('name' => "GPCTranslate", 'version' => "2.1.0"),
89        Array('name' => "GPCUsersGroups", 'version' => "2.0.0"),
90      )
91    );
92  }
93
94
95  /* ---------------------------------------------------------------------------
96   * register oriented functions
97   * -------------------------------------------------------------------------*/
98
99  /**
100   * register a plugin using GPC
101   *
102   * @param String $pluginName : the plugin name
103   * @param String $release : the plugin version like "2.0.0"
104   * @param String $GPCNeed : the minimal version of GPC needed by the plugin to
105   *                          work
106   * @return Boolean : true if registering is Ok, otherwise false
107   */
108  static public function register($plugin, $release, $GPCneeded)
109  {
110    $config=Array();
111    if(self::loadConfig(self::$pluginName, $config))
112    {
113      $config['registered'][$plugin]=Array(
114        'name' => $plugin,
115        'release' => $release,
116        'needed' => $GPCneeded,
117        'date' => date("Y-m-d"),
118      );
119      return(self::saveConfig(self::$pluginName, $config));
120    }
121    return(false);
122  }
123
124  /**
125   * unregister a plugin using GPC
126   *
127   * assume that if the plugin was not registerd before, unregistering returns
128   * a true value
129   *
130   * @param String $pluginName : the plugin name
131   * @return Boolean : true if registering is Ok, otherwise false
132   */
133  static public function unregister($plugin)
134  {
135    $config=Array();
136    if(self::loadConfig(self::$pluginName, $config))
137    {
138      if(array_key_exists('registered', $config))
139      {
140        if(array_key_exists($plugin, $config['registered']))
141        {
142          unset($config['registered'][$plugin]);
143          return(self::saveConfig(self::$pluginName, $config));
144        }
145      }
146    }
147    // assume if the plugin was not registered before, unregistering it is OK
148    return(true);
149  }
150
151  /**
152   * @return Array : list of registered plugins
153   */
154  static public function getRegistered()
155  {
156    $config=Array();
157    if(self::loadConfig(self::$pluginName, $config))
158    {
159      if(array_key_exists('registered', $config))
160      {
161        return($config['registered']);
162      }
163    }
164    return(Array());
165  }
166
167
168
169  /* ---------------------------------------------------------------------------
170   * config oriented functions
171   * -------------------------------------------------------------------------*/
172
173  /**
174   *  load config from CONFIG_TABLE into an array
175   *
176   * @param String $pluginName : the plugin name, must contain only alphanumerical
177   *                             character
178   * @param Array $config : array, initialized or not with default values ; the
179   *                        config values are loaded in this value
180   * @return Boolean : true if config is loaded, otherwise false
181   */
182  static public function loadConfig($pluginName, &$config=Array())
183  {
184    if(!is_array($config))
185    {
186      return(false);
187    }
188
189    $sql="SELECT value FROM ".CONFIG_TABLE."
190          WHERE param = '".$pluginName."_config'";
191    $result=pwg_query($sql);
192    if($result)
193    {
194      $row=pwg_db_fetch_row($result);
195      if(is_string($row[0]))
196      {
197        $configValues = unserialize($row[0]);
198        reset($configValues);
199        while (list($key, $val) = each($configValues))
200        {
201          if(is_array($val))
202          {
203            foreach($val as $key2 => $val2)
204            {
205              $config[$key][$key2]=$val2;
206            }
207          }
208          else
209          {
210            $config[$key] =$val;
211          }
212        }
213      }
214      return(true);
215    }
216    return(false);
217  }
218
219  /**
220   *  load config from a file into an array
221   *
222   *  note : the config file is a PHP file one var $conf used as an array,
223   *  like the piwigo $conf var
224   *
225   * @param String $fileName : the file name
226   * @param Array $config : array, initialized or not with default values ; the
227   *                        config values are loaded in this value
228   * @return Boolean : true if config is loaded, otherwise false
229   */
230  static public function loadConfigFromFile($fileName, &$config=Array())
231  {
232    $conf=array();
233
234    if(!is_array($config) or !file_exists($fileName))
235    {
236      return(false);
237    }
238
239    include_once($fileName);
240
241    foreach($conf as $key=>$val)
242    {
243      $config[$key]=$val;
244    }
245    return(true);
246  }
247
248
249  /**
250   * save var $my_config into CONFIG_TABLE
251   *
252   * @param String $pluginName : the plugin name, must contain only alphanumerical
253   *                             character
254   * @param Array $config : array of configuration values
255   * @return Boolean : true if config is saved, otherwise false
256   */
257  static public function saveConfig($pluginName, $config)
258  {
259    $sql="REPLACE INTO ".CONFIG_TABLE."
260           VALUES('".$pluginName."_config', '"
261           .serialize($config)."', '')";
262    $result=pwg_query($sql);
263    if($result)
264    { return true; }
265    else
266    { return false; }
267  }
268
269  /**
270   * delete config from CONFIG_TABLE
271   *
272   * @param String $pluginName : the plugin name, must contain only alphanumerical
273   *                             character
274   * @return Boolean : true if config is deleted, otherwise false
275   */
276  static public function deleteConfig($pluginName)
277  {
278    $sql="DELETE FROM ".CONFIG_TABLE."
279          WHERE param='".$pluginName."_config'";
280    $result=pwg_query($sql);
281    if($result)
282    { return true; }
283    else
284    { return false; }
285  }
286
287
288  /**
289   * convert (light) BB tag to HTML tag
290   *
291   * all BB codes are not recognized, only :
292   *  - [ul] [/ul]
293   *  - [li] [/li]
294   *  - [b] [/b]
295   *  - [i] [/i]
296   *  - [url] [/url]
297   *  - carriage return is replaced by a <br>
298   *
299   * @param String $text : text to convert
300   * @return String : BB to HTML text
301   */
302  static public function BBtoHTML($text)
303  {
304    $patterns = Array(
305      '/\[li\](.*?)\[\/li\]\n*/im',
306      '/\[b\](.*?)\[\/b\]/ism',
307      '/\[i\](.*?)\[\/i\]/ism',
308      '/\[p\](.*?)\[\/p\]/ism',
309      '/\[url\]([\w]+?:\/\/[^ \"\n\r\t<]*?)\[\/url\]/ism',
310      '/\[url=([\w]+?:\/\/[^ \"\n\r\t<]*?)\](.*?)\[\/url\]/ism',
311      '/\n{0,1}\[ul\]\n{0,1}/im',
312      '/\n{0,1}\[\/ul\]\n{0,1}/im',
313      '/\n{0,1}\[ol\]\n{0,1}/im',
314      '/\n{0,1}\[\/ol\]\n{0,1}/im',
315      '/\n/im',
316    );
317    $replacements = Array(
318      '<li>\1</li>',
319      '<b>\1</b>',
320      '<i>\1</i>',
321      '<p>\1</p>',
322      '<a href="\1">\1</a>',
323      '<a href="\1">\2</a>',
324      '<ul>',
325      '</ul>',
326      '<ol>',
327      '</ol>',
328      '<br>',
329    );
330
331    return(preg_replace($patterns, $replacements, $text));
332  }
333
334  /**
335   * used to add a css file in the header
336   *
337   * @param String $id : a unique id for the file
338   * @param String $file : the css file
339   */
340  static public function addHeaderCSS($id, $file)
341  {
342    if(!array_key_exists($file, self::$headerItems['css']))
343    {
344      self::$headerItems['css'][$id]=$file;
345    }
346  }
347  static public function addHeaderJS($id, $file)
348  {
349    global $template;
350
351    if(!isset($template->known_scripts)) $template->known_scripts=array();
352
353    if(!array_key_exists($id,  $template->known_scripts) and !array_key_exists($file, self::$headerItems['js']))
354    {
355     $template->known_scripts[$id]=$file;
356     self::$headerItems['js'][$id]=$file;
357    }
358  }
359
360  /**
361   * declared as public to be accessible by the event manager, but this funcion
362   * is not aimed to be used directly
363   */
364  static public function applyHeaderItems()
365  {
366    global $template;
367
368    foreach(self::$headerItems['css'] as $file)
369    {
370      $template->append('head_elements', '<link rel="stylesheet" type="text/css" href="'.$file.'"/>');
371    }
372
373    foreach(self::$headerItems['js'] as $file)
374    {
375      $template->append('head_elements', '<script type="text/javascript" src="'.$file.'"></script>');
376    }
377  }
378
379  /**
380   * use the extended description get_user_language_desc() function if exist
381   * otherwise returns the value
382   *
383   * @param String $value : value to translate
384   * @return String : translated value
385   */
386  static public function getUserLanguageDesc($value)
387  {
388    if(function_exists('get_user_language_desc'))
389    {
390      return(get_user_language_desc($value));
391    }
392    else
393    {
394      return($value);
395    }
396  }
397
398
399  /**
400   * remove a path recursively
401   *
402   * @param String $directory : directory to remove
403   * @param Bool $removePath : if set to true, remove the path himself, if set
404   *                           to false, remove only file & sub-directories
405   * @return Bool : true if directory was succesfully removed, otherwise false
406   */
407  static public function rmDir($directory, $removePath=true)
408  {
409    $directory=rtrim($directory, '\/').'/';
410    $returned=true;
411    if(file_exists($directory) and is_dir($directory) and $directory!='./' and $directory!='../')
412    {
413      $dhandle=scandir($directory);
414      foreach($dhandle as $file)
415      {
416        if($file!='.' and $file!='..' )
417        {
418          if(is_dir($directory.$file))
419          {
420            $returned=self::rmDir($directory.$file, true) & $returned;
421          }
422          else
423          {
424            $returned=unlink($directory.$file) & $returned;
425          }
426        }
427      }
428      if($returned and $removePath) $returned=rmdir($directory);
429    }
430    return($returned);
431  }
432
433
434  /**
435   * returns the piwigo system path
436   * @return String
437   */
438  static public function getPiwigoSystemPath()
439  {
440    return(self::$piwigoSystemPath);
441  }
442
443
444 /**
445  * formats a file size into a human readable size
446  *
447  * @param String $format : "A"  : auto
448  *                         "Ai" : auto (io)
449  *                         "O"  : o
450  *                         "K"  : Ko
451  *                         "M"  : Mo
452  *                         "G"  : Go
453  *                         "Ki" : Kio
454  *                         "Mi" : Mio
455  *                         "Gi" : Gio
456  * @param String $thsep : thousand separator
457  * @param Integer $prec : number of decimals
458  * @param Bool $visible : display or not the unit
459  * @return String : a formatted file size
460  */
461 static public function formatOctet($octets, $format="Ai", $thsep="", $prec=2, $visible=true)
462 {
463  if($format=="Ai")
464  {
465   if($octets<1024)
466   { $format="O"; }
467   elseif($octets<1024000)
468   { $format="Ki"; }
469   elseif($octets<1024000000)
470   { $format="Mi"; }
471   else
472   { $format="Gi"; }
473  }
474  elseif($format=="A")
475  {
476   if($octets<1000)
477   { $format="O"; }
478   elseif($octets<1000000)
479   { $format="Ki"; }
480   elseif($octets<1000000000)
481   { $format="Mi"; }
482   else
483   { $format="Gi"; }
484  }
485
486  switch($format)
487  {
488   case "O":
489    $unit="o"; $div=1;
490    break;
491   case "K":
492    $unit="Ko"; $div=1000;
493    break;
494   case "M":
495    $unit="Mo"; $div=1000000;
496    break;
497   case "G":
498    $unit="Go"; $div=1000000000;
499    break;
500   case "Ki":
501    $unit="Kio"; $div=1024;
502    break;
503   case "Mi":
504    $unit="Mio"; $div=1024000;
505    break;
506   case "Gi":
507    $unit="Gio"; $div=1024000000;
508    break;
509  }
510
511  $returned=number_format($octets/$div, $prec, '.', $thsep);
512  if($visible) $returned.=' '.$unit;
513  return($returned);
514 } //function formatOctet
515
516
517} //class
518
519add_event_handler('loc_begin_page_header', array('GPCCore', 'applyHeaderItems'), 10);
520
521GPCCore::init();
522
523?>
Note: See TracBrowser for help on using the repository browser.