'Janvier', 'February'=>'Février', 'March'=>'Mars', 'April'=>'Avril', 'May'=>'Mai',
'June'=>'Juin', 'July'=>'Juillet', 'August'=>'Août', 'September'=>'Septembre', 'October'=>'Octobre',
'November'=>'Novembre', 'December'=>'Décembre', 'Monday'=>'Lundi', 'Tuesday'=>'Mardi', 'Wednesday'=>'Mercredi',
'Thursday'=>'Jeudi','Friday'=>'Vendredi','Saturday'=>'Samedi','Sunday'=>'Dimanche',
'Feb'=>'Fév','Apr'=>'Avr','May'=>'Mai','Jun'=>'Juin', 'Jul'=>'Juil','Aug'=>'Aout','Dec'=>'Déc',
'Mon'=>'Lun','Tue'=>'Mar','Wed'=>'Mer','Thu'=>'Jeu','Fri'=>'Ven','Sat'=>'Sam','Sun'=>'Dim');
static public function frenchDateFormat($format, $ts)
{
$date = date($format, (int)$ts);
$date = strtr($date, self::$french_date_names);
return strtolower($date);
}
static public function french_strftime($format, $ts)
{
$date = strftime($format, (int)$ts);
$date = strtr($date, self::$french_date_names);
return strtolower($date);
}
static public function makeTimestampFromForm($d)
{
foreach (array('h', 'min', 'm', 'd', 'y') as $key)
{
if (!isset($d[$key]))
$d[$key] = 0;
}
return mktime($d['h'], $d['min'], 0, $d['m'], $d['d'], $d['y']);
}
static public function getCurrentUrl()
{
$host = $protocol = $path = $query = '';
if (!empty($_SERVER['HTTP_HOST']))
$host = strtolower(preg_replace('!:\d+$!', '', $_SERVER['HTTP_HOST']));
elseif (!empty($_SERVER['SERVER_NAME']))
$host = strtolower($_SERVER['SERVER_NAME']);
else
throw new Exception("Can't find url host");
if (!empty($_SERVER['REQUEST_URI']))
{
$r = explode('?', $_SERVER['REQUEST_URI']);
$path = $r[0];
if (!empty($r[1]))
$query = $r[1];
unset($r);
}
else
{
throw new Exception("Can't find url path");
}
$protocol = 'http';
if (!empty($_SERVER['HTTPS']))
$protocol .= 's';
return $protocol . '://' . $host . $path . ($query ? '?' . $query : '');
}
public static function redirect($destination=false, $exit=true)
{
$protocol = 'http';
if (!empty($_SERVER['HTTPS']))
$protocol .= 's';
if (empty($destination) || !preg_match('/^https?:\/\//', $destination))
{
$host = LENCRIER_ADMIN_HOST;
if (empty($destination))
$destination = $protocol . '://' . $host . '/';
else
$destination = $protocol . '://' . $host . '/' . preg_replace('/^\//', '', $destination);
}
if (headers_sent())
{
echo
''.
'
' .
' ' .
' '.
' '.
' '.
' '.
'';
if ($exit)
exit();
return true;
}
header("Location: " . $destination);
if ($exit)
exit();
}
static public function sessionStart($force = false)
{
if (!isset($_SESSION) && ($force || isset($_COOKIE[session_name()])))
{
// lifetime / path / domain / force ssl / http_only
// using http_only means the cookie will only get transmitted on HTTP requests
// and not to javascript
session_set_cookie_params(0, '/', LENCRIER_COOKIE_DOMAIN, false, true);
session_start();
}
return true;
}
static public function keepSessionAlive()
{
self::sessionStart(true);
}
static public function CSRF_create($key)
{
self::sessionStart(true);
if (!isset($_SESSION['csrf']))
{
$_SESSION['csrf'] = array();
}
$_SESSION['csrf'][$key] = sha1($key . self::$random_hash . time());
return $_SESSION['csrf'][$key];
}
static public function CSRF_check($key, $hash=null)
{
self::sessionStart();
if (is_null($hash))
{
$name = self::CSRF_field_name($key);
if (!isset($_POST[$name]))
return false;
$hash = $_POST[$name];
}
if (empty($_SESSION['csrf'][$key]))
return false;
if ($_SESSION['csrf'][$key] != $hash)
return false;
return true;
}
static public function CSRF_field_name($key)
{
return 'godzilla/'.base64_encode(sha1($key, true));
}
public static function cleanProtectedArray($arr, $prefix='')
{
$out = array();
foreach ($arr as $key=>$hash)
{
if (self::CSRF_check($prefix . $key, $hash))
{
$out[] = $key;
}
}
return $out;
}
static public function checkEmailSyntax($email)
{
if (preg_match('!^[a-z0-9._%+-]+@[a-z0-9.-]+\.([a-z]{2}|com|org|net|gov|biz|info|name|aero|biz|info|jobs|museum)$!i', $email))
return true;
else
return false;
}
static public function checkJournalIDSyntax($id)
{
if (preg_match('!^[a-z0-9][a-z0-9_-]{0,28}[a-z0-9]$!', $id))
return true;
else
return false;
}
static public function checkEmailDomain($email)
{
if (LENCRIER_FORBID_MAIL_DOMAINS != '')
{
$domains = explode(',', LENCRIER_FORBID_MAIL_DOMAINS);
$email = explode('@', $email);
if (empty($email[1]))
return true;
if (in_array($email[1], $domains))
return false;
}
return true;
}
static public function getTimezoneList()
{
return DateTimeZone::listIdentifiers();
}
static public function generatePassword($length, $chars='abcdefghijklmnopqrstuvwxyz1234567890')
{
$string = '';
for ($i = 0; $i < $length; $i++)
{
$pos = rand(0, strlen($chars)-1);
$string .= $chars{$pos};
}
return $string;
}
static public function getEcritURL($journal, $ecrit = null)
{
$url = self::getJournalURL($journal);
if (is_array($ecrit))
{
$url.= $ecrit['uri'];
}
elseif (is_int($ecrit))
{
$uri = DB::aQuery('SELECT uri FROM ecrits WHERE journal = "'.DB::esc($journal).'" AND id = "'.(int)$ecrit.'" LIMIT 1;', false, DB::FETCH_NUM);
if (!empty($uri[0][0]))
$url .= $uri[0][0];
}
return $url;
}
static public function getForumUrl($journal, $debut = 0)
{
$url = self::getJournalURL($journal);
$url.= 'forum/';
if ($debut > 0)
$url.= '+'.(int)$debut;
return $url;
}
static public function getForumMessageUrl($journal, $uri, $post = null)
{
$url = self::getJournalURL($journal);
$url.= 'forum/' . $uri;
if ($post)
$url .= '#msg-'.(int)$post;
return $url;
}
static public function getJournalURL($name)
{
$protocol = !empty($_SERVER['HTTPS']) ? 'https' : 'http';
if (LENCRIER_JOURNAL_URL_TYPE == LENCRIER_JOURNAL_URL_TYPE_DOMAIN)
{
return $protocol . '://'.$name.'.'.LENCRIER_JOURNAL_URL_DOMAIN.'/';
}
else
{
return $protocol . '://'.LENCRIER_JOURNAL_URL_DOMAIN.'/'.$name.'/';
}
}
static public function getJournalDatasURL($id, $type='documents')
{
$protocol = !empty($_SERVER['HTTPS']) ? 'https' : 'http';
return $protocol . '://' . LENCRIER_ADMIN_HOST . '/datas/' . $type . '/' . $id. '/';
}
static public function getJournalDatasPath($id, $type='documents')
{
return LENCRIER_DATA_ROOT . '/' . $type . '/' . $id;
}
static public function getThumbPath($journal, $path, $relative = false)
{
$path = preg_replace('!^/!', '', $path);
$hash = sha1($journal . $path);
$ext = substr($path, strrpos($path, '.') + 1);
$ext = strtolower($ext);
$path = 'cache/thumbs/' . substr($hash, -2);
if (!file_exists(LENCRIER_DATA_ROOT . '/' . $path))
@mkdir(LENCRIER_DATA_ROOT . '/' . $path);
$path .= '/' . $hash . '.' . $ext;
if ($relative)
return $path;
else
return LENCRIER_DATA_ROOT . '/' . $path;
}
static public function getThumbUrl($journal, $path)
{
$protocol = !empty($_SERVER['HTTPS']) ? 'httpss' : 'http';
return $protocol . '://' . LENCRIER_ADMIN_HOST . '/datas/' . self::getThumbPath($journal, $path, true);
}
static public function getIP()
{
if (!empty($_SERVER['REMOTE_ADDR']))
return $_SERVER['REMOTE_ADDR'];
return '';
}
static public function transliterateToAscii($str, $charset='UTF-8')
{
// Don't process empty strings
if (!trim($str))
return $str;
// We only process non-ascii strings
if (preg_match('!^[[:ascii:]]+$!', $str))
return $str;
$str = htmlentities($str, ENT_NOQUOTES, $charset);
$str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
$str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str); // pour les ligatures e.g. 'œ'
$str = preg_replace('#&[^;]+;#', '', $str); // supprime les autres caractères
$str = preg_replace('![^[:ascii:]]+!', '', $str);
return $str;
}
static public function makeURI($str)
{
$str = self::transliterateToAscii($str);
$str = preg_replace('/[^\w\d_\s\'\:\/\[\]-]/i', '', $str);
$str = preg_replace('/[\s\'\:\/\[\]-]+/', ' ', trim($str));
$str = substr($str, 0, 64);
$str = str_replace(' ', '-', trim($str));
return $str;
}
static public function baseConv($num, $base=62, $index=false)
{
if (!$index)
$index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base);
$out = "";
for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--)
{
$a = floor($num / pow($base, $t));
$out = $out . substr($index, $a, 1);
$num = $num - ($a * pow($base, $t));
}
return $out;
}
static public function id2url($id)
{
return self::baseConv($id, 36, '0123456789abcdefghijklmnopqrstuvwxyz');
}
static public function recurseDelete($path)
{
if (!file_exists($path))
return true;
$dir = dir($path);
while ($file = $dir->read())
{
if ($file == '.' || $file == '..')
continue;
if (is_dir($path . '/' . $file))
{
self::recurseDelete($path . '/' . $file);
}
else
{
unlink($path . '/' . $file);
}
}
$dir->close();
if (is_dir($path))
{
rmdir($path);
}
return true;
}
static public function recurseListFiles($path)
{
$files = array();
if (!file_exists($path))
return false;
$dir = dir($path);
while ($file = $dir->read())
{
if ($file == '.' || $file == '..')
continue;
if (is_dir($path . '/' . $file))
{
$files = array_merge($files, self::recurseListFiles($path . '/' . $file));
}
else
{
$files[] = $path . '/' . $file;
}
}
$dir->close();
return $files;
}
static public function recurseFileSize($path)
{
$size = 0;
if (!file_exists($path))
return false;
$dir = dir($path);
while ($file = $dir->read())
{
if ($file == '.' || $file == '..')
continue;
if (is_dir($path . '/' . $file))
{
$size += self::recurseFileSize($path . '/' . $file);
}
else
{
$size += filesize($path . '/' . $file);
}
}
$dir->close();
return $size;
}
static public function recurseCopy($src, $dst, $ignore=false)
{
if (!file_exists($src))
return false;
if (!file_exists($dst))
return false;
$dir = dir($src);
while ($file = $dir->read())
{
if ($file == '.' || $file == '..')
continue;
if ($ignore && preg_match('!'.$ignore.'!', $file))
continue;
if (is_dir($src . '/' . $file))
{
if (!file_exists($dst . '/' . $file))
mkdir($dst . '/' . $file);
self::recurseCopy($src . '/' . $file, $dst . '/' . $file, $ignore);
}
else
{
if (!file_exists($dst . '/' . $file))
copy($src . '/' . $file, $dst . '/' . $file);
}
}
$dir->close();
return true;
}
static public function HTTP_getHeaders($url)
{
$context = stream_context_create(array(
'http' => array(
'method' => 'HEAD',
'max_redirects' => 5,
'timeout' => 5,
)));
@file_get_contents($url, null, $context);
if (empty($http_response_header))
return false;
$headers = array();
foreach ($http_response_header as $row)
{
$row = trim($row);
if (preg_match('!^HTTP/1\.[01] ([0-9]{3})!', $row, $match))
$headers['_code'] = $match[1];
elseif (preg_match('!^([\w_-]+): (.*)$!i', $row, $match))
$headers[$match[1]] = $match[2];
}
return $headers;
}
static public function pageNotFound($msg = '')
{
header('HTTP/1.1 404 Not Found', true, 404);
echo '404 Not Found
';
echo ''.$msg.'
';
exit;
}
static public function post($key)
{
return isset($_POST[$key]) ? $_POST[$key] : '';
}
static public function get($key)
{
return isset($_GET[$key]) ? $_GET[$key] : '';
}
static public function return_bytes($size_str)
{
switch (substr($size_str, -1))
{
case 'G': case 'g': return (int)$size_str * pow(1024, 3);
case 'M': case 'm': return (int)$size_str * pow(1024, 2);
case 'K': case 'k': return (int)$size_str * 1024;
default: return $size_str;
}
}
static public function getMaxFileSize()
{
$size = self::return_bytes(ini_get('upload_max_filesize'));
$post = self::return_bytes(ini_get('post_max_size'));
if ($post < $size)
$size = $post;
$memory = self::return_bytes(ini_get('memory_limit'));
if ($memory < $size)
$size = $memory;
if ((LENCRIER_MAX_FILE_SIZE * 1024 * 1024) < $size)
$size = LENCRIER_MAX_FILE_SIZE * 1024 * 1024;
return $size;
}
/**
* Génération pagination à partir de la page courante ($current),
* du nombre d'items total ($total), et du nombre d'items par page ($bypage).
* $listLength représente la longueur d'items de la pagination à génerer
*
* @param int $current
* @param int $total
* @param int $bypage
* @param int $listLength
* @param bool $showLast Toggle l'affichage du dernier élément de la pagination
* @return array
*/
public static function getGenericPagination($current, $total, $bypage, $listLength=11, $showLast = true)
{
if ($total <= $bypage)
return false;
$total = ceil($total / $bypage);
if ($total < $current)
return false;
$length = ($listLength / 2);
$begin = $current - ceil($length);
if ($begin < 1)
{
$begin = 1;
}
$end = $begin + $listLength;
if($end > $total)
{
$begin -= ($end - $total);
$end = $total;
}
if ($begin < 1)
{
$begin = 1;
}
if($end==($total-1)) {
$end = $total;
}
if($begin == 2) {
$begin = 1;
}
$out = array();
if ($current > 1) {
$out[] = array('id' => $current - 1, 'label' => '« ' . 'Page précédente', 'class' => 'prev', 'accesskey' => 'a');
}
if ($begin > 1) {
$out[] = array('id' => 1, 'label' => '1 ...', 'class' => 'first');
}
for ($i = $begin; $i <= $end; $i++)
{
$out[] = array('id' => $i, 'label' => $i, 'class' => ($i == $current) ? 'current' : '');
}
if ($showLast && $end < $total) {
$out[] = array('id' => $total, 'label' => '... ' . $total, 'class' => 'last');
}
if ($current < $total) {
$out[] = array('id' => $current + 1, 'label' => 'Page suivante' . ' »', 'class' => 'next', 'accesskey' => 'z');
}
return $out;
}
static public function HTMLtoText($str, $journal = false)
{
if (is_null(self::$g2x))
{
require_once LENCRIER_ROOT . '/include/garbage2xhtml/lib.garbage2xhtml.php';
self::$g2x = new garbage2xhtml;
self::$g2x->indent = false;
}
$str = htmlspecialchars_decode($str, ENT_QUOTES);
$str = preg_replace('!
\n!i', '
', $str);
if ($journal)
{
$str = preg_replace('!image:\[([^\]]+)\]!', utils::getJournalURL($journal) . 'i/$1', $str);
$str = preg_replace_callback('!href="(\d+)"!', function ($match) use ($journal) {
return 'href="'.utils::getEcritURL($journal, (int)$match[1]).'"';
}, $str);
}
$str = self::$g2x->process($str);
$str = preg_replace('!?(?:b|strong)(?:\s+[^>]*)?>!i', '*', $str);
$str = preg_replace('!?(?:i|em)(?:\s+[^>]*)?>!i', '/', $str);
$str = preg_replace('!?(?:u|ins)(?:\s+[^>]*)?>!i', '_', $str);
$str = preg_replace('!]*)?>!i', '== ', $str);
$str = preg_replace('!
!i', ' ==', $str);
$str = str_replace("\r", "\n", $str);
$str = preg_replace("!\n*!i", "\n\n", $str);
$str = preg_replace("!
]*>\n*!i", "\n", $str);
$str = preg_replace('!]*src=([\'"])([^\1]*?)\1[^>]*>!i', 'Image : $2', $str);
preg_match_all('!]href=([\'"])([^\1]*?)\1[^>]*>(.*?)!i', $str, $match, PREG_SET_ORDER);
if (!empty($match))
{
$i = 1;
$str .= "\n\n== Liens cités ==\n";
foreach ($match as $link)
{
$str = str_replace($link[0], $link[3] . '['.$i.']', $str);
$str.= str_pad($i, 2, ' ', STR_PAD_LEFT).'. '.$link[2]."\n";
$i++;
}
}
$str = strip_tags($str);
$str = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
$str = preg_replace("!\n{3,}!", "\n\n", $str);
return $str;
}
}
?>