7 static protected $country_list = null;
9 static protected $g2x = null;
11 static private $french_date_names = [
12 'January'=>'Janvier', 'February'=>'Février', 'March'=>'Mars', 'April'=>'Avril', 'May'=>'Mai',
13 'June'=>'Juin', 'July'=>'Juillet', 'August'=>'Août', 'September'=>'Septembre', 'October'=>'Octobre',
14 'November'=>'Novembre', 'December'=>'Décembre', 'Monday'=>'Lundi', 'Tuesday'=>'Mardi', 'Wednesday'=>'Mercredi',
15 'Thursday'=>'Jeudi','Friday'=>'Vendredi','Saturday'=>'Samedi','Sunday'=>'Dimanche',
16 'Feb'=>'Fév','Apr'=>'Avr','May'=>'Mai','Jun'=>'Juin', 'Jul'=>'Juil','Aug'=>'Aout','Dec'=>'Déc',
17 'Mon'=>'Lun','Tue'=>'Mar','Wed'=>'Mer','Thu'=>'Jeu','Fri'=>'Ven','Sat'=>'Sam','Sun'=>'Dim'];
19 static public function strftime_fr($format=null, $ts=null)
23 $format = '%d/%m/%Y à %H:%M';
26 $date = strftime($format, $ts);
27 $date = strtr($date, self
::$french_date_names);
28 $date = strtolower($date);
32 static public function date_fr($format=null, $ts=null)
36 $format = 'd/m/Y à H:i';
39 $date = date($format, $ts);
40 $date = strtr($date, self
::$french_date_names);
41 $date = strtolower($date);
45 static public function sqliteDateToFrench($d, $short = false)
47 if (strlen($d) == 10 ||
$short)
49 $d = substr($d, 0, 10);
53 elseif (strlen($d) == 16)
64 if ($dt = \DateTime
::createFromFormat($f, $d))
65 return $dt->format($f2);
70 static public function makeTimestampFromForm($d)
72 return mktime($d['h'], $d['min'], 0, $d['m'], $d['d'], $d['y']);
75 static public function modifyDate($str, $change)
77 $date = \DateTime
::createFromFormat('Y-m-d', $str);
78 $date->modify($change);
79 return $date->format('Y-m-d');
82 static public function checkDate($str)
84 if (!preg_match('!^(\d{4})-(\d{2})-(\d{2})$!', $str, $match))
87 if (!checkdate($match[2], $match[3], $match[1]))
93 static public function checkDateTime($str)
95 if (!preg_match('!^(\d{4}-\d{2}-\d{2})[T ](\d{2}):(\d{2})!', $str, $match))
98 if (!self
::checkDate($match[1]))
101 if ((int) $match[2] < 0 ||
(int) $match[2] > 23)
104 if ((int) $match[3] < 0 ||
(int) $match[3] > 59)
107 if (isset($match[4]) && ((int) $match[4] < 0 ||
(int) $match[4] > 59))
113 static public function getRequestURI()
115 if (!empty($_SERVER['REQUEST_URI']))
116 return $_SERVER['REQUEST_URI'];
121 static public function getSelfURL($no_qs = false)
123 $uri = self
::getRequestUri();
125 if (strpos($uri, WWW_URI
) === 0)
127 $uri = substr($uri, strlen(WWW_URI
));
130 if ($no_qs && (strpos($uri, '?') !== false))
132 $uri = substr($uri, 0, strpos($uri, '?'));
135 return WWW_URL
. $uri;
138 static public function disableHttpCaching()
140 header("Cache-Control: no-cache, must-revalidate");
141 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
142 header('Pragma: no-cache');
146 public static function redirect($destination=false, $exit=true)
148 if (empty($destination) ||
!preg_match('/^https?:\/\//', $destination))
150 if (empty($destination))
151 $destination = WWW_URL
;
153 $destination = WWW_URL
. preg_replace('/^\//', '', $destination);
161 ' <script type="text/javascript">' .
162 ' document.location = "' . htmlspecialchars($destination, ENT_QUOTES
, 'UTF-8', false) . '";' .
167 ' <a href="' . htmlspecialchars($destination, ENT_QUOTES
, 'UTF-8', false) . '">Cliquez ici pour continuer...</a>'.
178 header("Location: " . $destination);
185 static protected function _sessionStart($force = false)
187 if (!isset($_SESSION) && ($force ||
isset($_COOKIE[session_name()])))
194 static public function CSRF_create($key)
196 self
::_sessionStart(true);
198 if (!isset($_SESSION['csrf']))
200 $_SESSION['csrf'] = [];
203 $_SESSION['csrf'][$key] = sha1($key . uniqid($key, true) . time());
204 return $_SESSION['csrf'][$key];
207 static public function CSRF_check($key, $hash=null)
209 self
::_sessionStart();
213 $name = self
::CSRF_field_name($key);
215 if (!isset($_POST[$name]))
218 $hash = $_POST[$name];
221 if (empty($_SESSION['csrf'][$key]))
224 if ($_SESSION['csrf'][$key] != $hash)
227 unset($_SESSION['csrf'][$key]);
232 static public function CSRF_field_name($key)
234 return 'gecko/'.base64_encode(sha1($key, true));
237 static public function generatePassword($length, $chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890')
240 for ($i = 0; $i < $length; $i++
)
242 $pos = rand(0, strlen($chars)-1);
243 $string .= $chars[$pos];
248 static public function post($key)
250 return isset($_POST[$key]) ?
$_POST[$key] : '';
253 static public function get($key)
255 return isset($_GET[$key]) ?
$_GET[$key] : '';
258 static public function getIP()
260 if (!empty($_SERVER['REMOTE_ADDR']))
261 return $_SERVER['REMOTE_ADDR'];
265 static public function &getCountryList()
267 if (is_null(self
::$country_list))
269 require_once ROOT
. '/include/libs/countries/countries_fr.php';
270 self
::$country_list = $countries;
273 return self
::$country_list;
276 static public function getCountryName($code)
278 $list = self
::getCountryList();
280 if (!isset($list[$code]))
287 * Génération pagination à partir de la page courante ($current),
288 * du nombre d'items total ($total), et du nombre d'items par page ($bypage).
289 * $listLength représente la longueur d'items de la pagination à génerer
291 * @param int $current
294 * @param int $listLength
295 * @param bool $showLast Toggle l'affichage du dernier élément de la pagination
298 public static function getGenericPagination($current, $total, $bypage, $listLength=11, $showLast = true)
300 if ($total <= $bypage)
303 $total = ceil($total / $bypage);
305 if ($total < $current)
308 $length = ($listLength / 2);
310 $begin = $current - ceil($length);
316 $end = $begin +
$listLength;
319 $begin -= ($end - $total);
326 if($end==($total-1)) {
335 $out[] = ['id' => $current - 1, 'label' => '« ' . 'Page précédente', 'class' => 'prev', 'accesskey' => 'a'];
339 $out[] = ['id' => 1, 'label' => '1 ...', 'class' => 'first'];
342 for ($i = $begin; $i <= $end; $i++
)
344 $out[] = ['id' => $i, 'label' => $i, 'class' => ($i == $current) ?
'current' : ''];
347 if ($showLast && $end < $total) {
348 $out[] = ['id' => $total, 'label' => '... ' . $total, 'class' => 'last'];
351 if ($current < $total) {
352 $out[] = ['id' => $current +
1, 'label' => 'Page suivante' . ' »', 'class' => 'next', 'accesskey' => 'z'];
358 static public function transliterateToAscii($str, $charset='UTF-8')
360 // Don't process empty strings
364 // We only process non-ascii strings
365 if (preg_match('!^[[:ascii:]]+$!', $str))
368 $str = htmlentities($str, ENT_NOQUOTES
, $charset);
370 $str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
371 $str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str); // pour les ligatures e.g. 'œ'
373 $str = preg_replace('#&[^;]+;#', '', $str); // supprime les autres caractères
374 $str = preg_replace('![^[:ascii:]]+!', '', $str);
379 static public function htmlLinksOnUrls($str)
381 return preg_replace_callback('!(?<=\s|^)((?:(ftp|https?|file|ed2k|ircs?)://|(magnet|mailto|data|tel|fax|geo|sips?|xmpp):)([^\s<]+))!',
383 $proto = $match[2] ?
: $match[3];
384 $text = ($proto == 'http' ||
$proto == 'mailto') ?
$match[4] : $match[1];
385 return '<a class="'.$proto.'" href="'.htmlspecialchars($match[1], ENT_QUOTES
, 'UTF-8').'">'.htmlspecialchars($text, ENT_QUOTES
, 'UTF-8').'</a>';
389 static public function htmlGarbage2xhtml($str)
393 require_once ROOT
. '/include/libs/garbage2xhtml/lib.garbage2xhtml.php';
394 self
::$g2x = new \garbage2xhtml
;
395 self
::$g2x->core_attributes
= ['class', 'id', 'title'];
398 return self
::$g2x->process($str);
401 static public function htmlSpip($str, $prefix = '')
404 $str = preg_replace('/(?<!\\\\)\{{3}(\V*)\}{3}/', '<h3>$1</h3>', $str);
407 $str = preg_replace('/(?<!\\\\)\{{2}(\V*)\}{2}/', '<strong>$1</strong>', $str);
410 $str = preg_replace('/(?<!\\\\)\{(\V*)\}/', '<em>$1</em>', $str);
412 // Espaces typograhiques
413 $str = preg_replace('/\h*([?!;:»])(\s+|$)/u', ' $1$2', $str);
414 $str = preg_replace('/(^|\s+)([«])\h*/u', '$1$2 ', $str);
417 $str = preg_replace('/(?<!\\\\)\[(.+?)->(.+?)\]/', '<a href="$2">$1</a>', $str);
418 $str = preg_replace('/(?<!\\\\)\[(.+?)\]/', '<a href="$1">$1</a>', $str);
421 $str = preg_replace('/<a href="((?!http).*@.*)">/iU', '<a href="mailto:$1">', $str);
426 static public function mail($to, $subject, $content, $additional_headers = [])
428 // Création du contenu du message
429 $content = wordwrap($content);
430 $content = trim($content);
432 $content = preg_replace("#(?<!\r)\n#si", "\r\n", $content);
434 // Construction des entêtes
437 $config = Config
::getInstance();
439 if (empty($additional_headers['From']))
441 $additional_headers['From'] = '"NE PAS REPONDRE" <'.$config->get('email_envoi_automatique').'>';
444 $additional_headers['MIME-Version'] = '1.0';
445 $additional_headers['Content-type'] = 'text/plain; charset=UTF-8';
446 $additional_headers['Return-Path'] = $config->get('email_envoi_automatique');
448 foreach ($additional_headers as $name=>$value)
450 $headers .= $name . ': '.$value."\r\n";
453 $headers = preg_replace("#(?<!\r)\n#si", "\r\n", $headers);
455 $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
461 return mail($t, $suject, $content, $headers);
466 return mail($to, $subject, $content, $headers);
470 static public function clearCaches()
472 $path = DATA_ROOT
. '/cache/compiled';
475 while ($file = $dir->read())
479 unlink($path . '/' . $file);
487 static public function suggestPassword()
489 require_once ROOT
. '/include/libs/passphrase/lib.passphrase.french.php';
490 return \Passphrase
::generate();
493 static public function checkIBAN($iban)
495 $iban = substr($iban, 4) . substr($iban, 0, 4);
496 $iban = str_replace(range('A', 'Z'), range(10, 35), $iban);
497 return (bcmod($iban, 97) == 1);
500 static public function IBAN_RIB($iban)
502 if (substr($iban, 0, 2) != 'FR')
507 return substr($iban, 4, 5) // Code banque
508 . ' ' . substr($iban, 4+
5, 5) // Code guichet
509 . ' ' . substr($iban, 4+
5+
5, -2) // Numéro de compte
510 . ' ' . substr($iban, -2); // Clé RIB
513 static public function checkBIC($bic)
515 return preg_match('!^[A-Z]{4}[A-Z]{2}[1-9A-Z]{2}(?:[A-Z\d]{3})?$!', $bic);
518 static public function normalizePhoneNumber($n)
520 $n = preg_replace('!(\+\d+)\(0\)!', '\\1', $n);
521 $n = preg_replace('![^\d\+]!', '', $n);
525 static public function write_ini_string($in)
528 $get_ini_line = function ($key, $value) use (&$get_ini_line)
532 return $key . ' = ' . ($value ?
'true' : 'false');
534 elseif (is_numeric($value))
536 return $key . ' = ' . $value;
538 elseif (is_array($value))
541 foreach ($value as $row)
543 $out .= $get_ini_line($key . '[]', $row) . "\n";
546 return substr($out, 0, -1);
550 return $key . ' = "' . str_replace('"', '\\"', $value) . '"';
554 foreach ($in as $key=>$value)
556 if (is_array($value) && is_string($key))
558 $out .= '[' . $key . "]\n";
560 foreach ($value as $row_key=>$row_value)
562 $out .= $get_ini_line($row_key, $row_value) . "\n";
569 $out .= $get_ini_line($key, $value) . "\n";
576 static public function getMaxUploadSize()
579 self
::return_bytes(ini_get('upload_max_filesize')),
580 self
::return_bytes(ini_get('post_max_size')),
581 self
::return_bytes(ini_get('memory_limit'))
586 static public function return_bytes ($size_str)
588 switch (substr($size_str, -1))
590 case 'G': case 'g': return (int)$size_str * pow(1024, 3);
591 case 'M': case 'm': return (int)$size_str * pow(1024, 2);
592 case 'K': case 'k': return (int)$size_str * 1024;
593 default: return $size_str;
597 static public function deleteRecursive($path, $delete_target = false)
599 if (!file_exists($path))
603 if (!$dir) return false;
605 while ($file = $dir->read())
607 if ($file == '.' ||
$file == '..')
610 if (is_dir($path . '/' . $file))
612 if (!self
::deleteRecursive($path . '/' . $file, true))
617 unlink($path . '/' . $file);
627 static public function plugin_url($params = [])
629 if (isset($params['id']))
631 $url = WWW_URL
. 'admin/plugin/' . $params['id'] . '/';
638 if (!empty($params['file']))
639 $url .= $params['file'];
641 if (!empty($params['query']))
645 if (!(is_numeric($params['query']) && (int)$params['query'] === 1) && $params['query'] !== true)
646 $url .= $params['query'];
652 static public function find_csv_delim($fp)
656 while ($line === '' && !feof($fp))
658 $line = trim(fgets($fp, 4096));
661 // Delete the columns content
662 $line = preg_replace('/".*?"/', '', $line);
665 ';' => substr_count($line, ';'),
666 ',' => substr_count($line, ','),
667 "\t"=> substr_count($line, "\t")