function.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  1. <?php
  2. function secondToTime($seconds) {
  3. $t = round($seconds);
  4. return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
  5. }
  6. function app_autoloader($class_name) {
  7. if(file_exists(__ROOT__.'class/'.$class_name.'.class.php'))
  8. require_once(__ROOT__.'class/'.$class_name.'.class.php');
  9. }
  10. function errorToException( $errno, $errstr, $errfile, $errline, $errcontext) {
  11. throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
  12. }
  13. function unhandledException($ex){
  14. //Récuperation de la requete échouée si l'utilisateur n'est pas authentifié
  15. if($ex->getCode()==401) $_SESSION['last_request'] = $_SERVER['REQUEST_URI'];
  16. echo '<div id="message" class="alert alert-danger"><strong>Erreur : </strong><span>'.$ex->getMessage().' - <small style="opacity:0.5;">'.$ex->getFile().' L'.$ex->getLine().'</small></span></div>';
  17. require_once('footer.php');
  18. exit();
  19. }
  20. function ip(){
  21. if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  22. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  23. elseif(isset($_SERVER['HTTP_CLIENT_IP']))
  24. $ip = $_SERVER['HTTP_CLIENT_IP'];
  25. else
  26. $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] :'';
  27. return $ip;
  28. }
  29. //Check si l'url serveur est en HTTPS
  30. function is_url_securised(){
  31. return isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off';
  32. }
  33. //Définit le schéma d'URL à utiliser
  34. function define_url_scheme(){
  35. return is_url_securised() ? 'https' : 'http';
  36. }
  37. //Définit la racine des médias en
  38. //fonction du schéma d'URL (http ou https)
  39. function define_media_root(){
  40. return is_url_securised() ? preg_replace('|http(s)?://|i',define_url_scheme().'://',ROOT_URL) : ROOT_URL;
  41. }
  42. function encrypt($data){
  43. $keyHash = md5(CRYPTKEY);
  44. $data = openssl_encrypt ($data,'aes256',$keyHash,true,'1234567812345678');
  45. return base64_encode($data);
  46. }
  47. function decrypt($data){
  48. $keyHash = md5(CRYPTKEY);
  49. $data = base64_decode($data);
  50. return openssl_decrypt ($data,'aes256',$keyHash,true,'1234567812345678');
  51. }
  52. function slugify($text,$allowChars = '') {
  53. setlocale(LC_CTYPE, 'fr_FR.UTF-8');
  54. try{
  55. $encoding = mb_detect_encoding($text, mb_detect_order(), false);
  56. if($encoding == "UTF-8") $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
  57. $clean = iconv(mb_detect_encoding($text, mb_detect_order(), false), 'ASCII//TRANSLIT', $text);
  58. }catch(Exception $e){
  59. $clean = $text;
  60. }
  61. $clean = normalize_chars($clean);
  62. $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -".preg_quote($allowChars)."]/", '', $clean);
  63. $clean = strtolower(trim($clean, '-'));
  64. $clean = preg_replace("/[\/_|+ -]+/", '-', $clean);
  65. return $clean;
  66. }
  67. if(!function_exists('glob_recursive')) {
  68. // Does not support flag GLOB_BRACE
  69. function glob_recursive($pattern, $flags = 0,$forbiddenPathes = array(),$root = null){
  70. $files = glob($pattern, $flags);
  71. foreach (glob(dirname($pattern).SLASH.'*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
  72. if(isset($root))
  73. if(in_array(str_replace($root,'',$dir), $forbiddenPathes)) continue;
  74. $files = array_merge($files, glob_recursive($dir.SLASH.basename($pattern), $flags,$forbiddenPathes,$root));
  75. }
  76. return $files;
  77. }
  78. }
  79. function core_reference(){
  80. $token = 'az9e87qS65d4A32f1d65df4s8d5d2cc';
  81. $constant = __ROOT__.'constant.php';
  82. if(!file_exists($constant)) return;
  83. if(!function_exists('curl_init')) return;
  84. $infos = array();
  85. $infos['installation'] = filectime($constant);
  86. $infos['technician'] = PROGRAM_TECHNICIAN;
  87. $infos['uid'] = PROGRAM_UID;
  88. $infos['label'] = PROGRAM_NAME;
  89. $infos['files'] = array();
  90. foreach(glob_recursive(__DIR__.SLASH.'/*') as $file){
  91. //evite le referencement du dossier .git
  92. if(substr($file, 0,1)=='.') continue;
  93. $infos['files'][] = array(
  94. 'label' => base64_encode($file),
  95. 'modification' => filemtime($file)
  96. );
  97. }
  98. $infos['plugin'] = array();
  99. foreach(Plugin::getAll(true) as $plugin){
  100. $iterator = new DirectoryIterator(PLUGIN_PATH.SLASH.$plugin->folder.SLASH);
  101. $mtime = -1;
  102. $file;
  103. foreach ($iterator as $fileinfo) {
  104. if ($fileinfo->isFile()) {
  105. if ($fileinfo->getMTime() > $mtime) {
  106. $file = $fileinfo->getFilename();
  107. $mtime = $fileinfo->getMTime();
  108. }
  109. }
  110. }
  111. $infos['plugin'][] = array(
  112. 'label' => $plugin->name,
  113. 'uid' => $plugin->id,
  114. 'modification' => $mtime
  115. );
  116. }
  117. $infos['server'] = array(
  118. 'http' => $_SERVER['SERVER_SOFTWARE'],
  119. 'ip' => $_SERVER['SERVER_ADDR'],
  120. 'protocol' => $_SERVER['REQUEST_SCHEME'],
  121. 'root' => __ROOT__
  122. );
  123. $ch = curl_init();
  124. curl_setopt($ch, CURLOPT_URL,REFERENCE_URL);
  125. curl_setopt($ch, CURLOPT_POST, 1);
  126. curl_setopt($ch, CURLOPT_POSTFIELDS,"token=".$token."&data=".base64_encode(json_encode($infos)));
  127. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  128. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  129. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  130. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  131. $stream = curl_exec ($ch);
  132. if(!$stream) $stream = curl_error($ch).' : '.curl_strerror(curl_errno($ch));
  133. curl_close ($ch);
  134. return $stream;
  135. }
  136. function array_map_recursive($callback, $array) {
  137. $func = function ($item) use (&$func, &$callback) {
  138. return is_array($item) ? array_map($func, $item) : call_user_func($callback, $item);
  139. };
  140. return array_map($func, $array);
  141. }
  142. function secure_user_vars($var){
  143. if(is_array($var)){
  144. $array = array();
  145. foreach($var as $key=>$value):
  146. $array[secure_user_vars($key)] = secure_user_vars($value);
  147. endforeach;
  148. return $array;
  149. } else {
  150. return str_replace('&amp;','&',htmlspecialchars($var, ENT_NOQUOTES, "UTF-8"));
  151. }
  152. }
  153. function base64_to_image($base64_string, $output_file) {
  154. $ifp = fopen($output_file, "wb");
  155. $data = explode(',', $base64_string);
  156. fwrite($ifp, base64_decode($data[1]));
  157. fclose($ifp);
  158. return $output_file;
  159. }
  160. function getExt($file){
  161. $ext = explode('.',$file);
  162. return strtolower(array_pop($ext));
  163. }
  164. function get_gravatar($mail,$size = 100){
  165. return file_get_contents("http://www.gravatar.com/avatar/" . md5( strtolower( trim( $mail ) ) ) . "?&s=".$size);
  166. }
  167. function getExtIcon($ext){
  168. $icon = '';
  169. switch($ext){
  170. case '7z':
  171. case 'rar':
  172. case 'gz':
  173. case 'zip':
  174. $icon = 'far fa-file-archive text-warning';
  175. break;
  176. case 'php':
  177. case 'js':
  178. case 'py':
  179. case 'c':
  180. case 'cpp':
  181. case 'css':
  182. case 'h':
  183. case 'hpp':
  184. case 'html':
  185. case 'htm':
  186. case 'asp':
  187. case 'jsp':
  188. $icon = 'fas fa-file-code text-secondary text-warning';
  189. break;
  190. case 'xls':
  191. case 'xlsx':
  192. case 'csv':
  193. $icon = 'far fa-file-excel text-success';
  194. break;
  195. case 'bmp':
  196. case 'jpg':
  197. case 'jpeg':
  198. case 'ico':
  199. case 'gif':
  200. case 'png':
  201. case 'svg':
  202. $icon = 'far fa-file-image text-info';
  203. break;
  204. case 'pdf':
  205. $icon = 'far fa-file-pdf text-danger';
  206. break;
  207. case 'ppt':
  208. case 'pptx':
  209. $icon = 'fa-file-powerpoint-o text-warning' ;
  210. break;
  211. case 'txt':
  212. case 'htaccess':
  213. case 'md':
  214. $icon = 'far fa-file-alt';
  215. break;
  216. case 'doc':
  217. case 'docx':
  218. case 'word':
  219. $icon = 'far fa-file-word text-primary';
  220. break;
  221. case 'avi':
  222. case 'wmv':
  223. case 'mov':
  224. case 'divx':
  225. case 'xvid':
  226. case 'mkv':
  227. case 'flv':
  228. case 'mpeg':
  229. case 'h264':
  230. case 'rmvb':
  231. case 'mp4':
  232. $icon = 'far fa-file-movie text-secondary';
  233. break;
  234. case 'wav':
  235. case 'ogg':
  236. case 'ogv':
  237. case 'ogx':
  238. case 'oga':
  239. case 'riff':
  240. case 'bwf':
  241. case 'wma':
  242. case 'flac':
  243. case 'aac':
  244. case 'mp3':
  245. $icon = 'far fa-file-audio text-secondary';
  246. break;
  247. default:
  248. $icon = 'far fa-file';
  249. break;
  250. }
  251. return $icon;
  252. }
  253. function getExtContentType($ext){
  254. $cType = '';
  255. switch($ext){
  256. //@TODO: compléter les types MIME par extension
  257. // case 'php':
  258. // case 'js':
  259. // case 'py':
  260. // case 'c':
  261. // case 'cpp':
  262. // case 'css':
  263. // case 'h':
  264. // case 'hpp':
  265. // case 'html':
  266. // case 'htm':
  267. // case 'asp':
  268. // case 'jsp':
  269. // case 'ico':
  270. // case 'svg':
  271. // case 'avi':
  272. // case 'wmv':
  273. // case 'mov':
  274. // case 'divx':
  275. // case 'xvid':
  276. // case 'mkv':
  277. // case 'flv':
  278. // case 'mpeg':
  279. // case 'h264':
  280. // case 'rmvb':
  281. // case 'mp4':
  282. // case 'ogg':
  283. // case 'ogv':
  284. // case 'ogx':
  285. // case 'oga':
  286. // case 'riff':
  287. // case 'bwf':
  288. // case 'wma':
  289. // case 'flac':
  290. // break;
  291. case '7z':
  292. $cType = 'application/x-7z-compressed';
  293. break;
  294. case 'rar':
  295. $cType = 'application/x-rar-compressed';
  296. break;
  297. case 'gz':
  298. $cType = 'application/x-gzip';
  299. break;
  300. case 'zip':
  301. $cType = 'application/zip';
  302. break;
  303. case 'xls':
  304. $cType = 'application/vnd.ms-excel';
  305. break;
  306. case 'xlsx':
  307. $cType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  308. break;
  309. case 'csv':
  310. $cType = 'text/csv';
  311. break;
  312. case 'jpg':
  313. case 'jpeg':
  314. $cType = 'image/jpeg';
  315. break;
  316. case 'bmp':
  317. case 'gif':
  318. case 'png':
  319. $cType = 'image/'.$ext;
  320. break;
  321. case 'ppt':
  322. $cType = 'application/vnd.ms-powerpoint';
  323. break;
  324. case 'pptx':
  325. $cType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
  326. break;
  327. case 'pdf':
  328. $cType = 'application/pdf';
  329. break;
  330. case 'txt':
  331. $cType = 'text/plain';
  332. break;
  333. case 'doc':
  334. case 'word':
  335. $cType = 'application/msword';
  336. break;
  337. case 'docx':
  338. $cType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  339. break;
  340. case 'aac':
  341. case 'wav':
  342. $cType = 'audio/'.$ext;
  343. break;
  344. $cType = 'audio/aac';
  345. break;
  346. case 'mp3':
  347. $cType = 'audio/mpeg3';
  348. break;
  349. default:
  350. $cType = 'application/octet-stream';
  351. break;
  352. }
  353. return $cType;
  354. }
  355. function max_upload_size($limits = array()){
  356. $limits[] = str_replace('M','',ini_get('post_max_size')) *1048576;
  357. $limits[] = str_replace('M','',ini_get('upload_max_filesize')) *1048576;
  358. return readable_size(min($limits));
  359. }
  360. function readable_size($bytes)
  361. {
  362. if($bytes<1024){
  363. return round(($bytes / 1024), 2).' o';
  364. }elseif(1024<$bytes && $bytes<1048576){
  365. return round(($bytes / 1024), 2).' ko';
  366. }elseif(1048576<=$bytes && $bytes<1073741824){
  367. return round(($bytes / 1024)/1024, 2).' Mo';
  368. }elseif(1073741824<=$bytes){
  369. return round(($bytes / 1024)/1024/1024, 2).' Go';
  370. }
  371. }
  372. function relative_time($date,$date2 = null, $relativeLimit = null, $detailled = false){
  373. $from = new DateTime();
  374. $from->setTimestamp($date);
  375. $to = new DateTime("now");
  376. if(isset($date2)) $to->setTimestamp($date2);
  377. $intervalle = $from->diff($to);
  378. if(isset($relativeLimit) && $intervalle->format('%d') > $relativeLimit){
  379. $limitFormat = $detailled ? 'd/m/Y H:i' : 'd/m/Y';
  380. return 'Le '.date($limitFormat, $date);
  381. }
  382. $prefixe = $from > $to ? 'Dans ' :'Il y a ' ;
  383. if(isset($date2)) $prefixe = '';
  384. $years = $intervalle->format('%y');
  385. $month = $intervalle->format('%m');
  386. $days = $intervalle->format('%d');
  387. $hours = $intervalle->format('%h');
  388. $minutes = $intervalle->format('%i');
  389. if ($years != 0) {
  390. $relative_date = $prefixe . $years . ' an' . (($years > 1) ? 's' : '');
  391. if ($month >= 6) $relative_date .= ' et demi';
  392. } elseif ($month != 0) {
  393. $relative_date = $prefixe . $month . ' mois';
  394. if ($days >= 15) $relative_date .= ' et demi';
  395. } elseif ($days != 0) {
  396. $relative_date = $prefixe . $days . ' jour' . (($days > 1) ? 's' : '');
  397. } elseif ($hours != 0) {
  398. $relative_date = $prefixe . $hours . ' heure' . (($hours > 1) ? 's' : '');
  399. } elseif ($minutes != 0) {
  400. $relative_date = $prefixe . $minutes . ' minute' . (($minutes > 1) ? 's' : '');
  401. } else {
  402. $relative_date = $prefixe . ' quelques secondes';
  403. }
  404. return $relative_date;
  405. }
  406. function image_resize($image,$w,$h){
  407. $resource = imagecreatefromstring(file_get_contents($image));
  408. $size = getimagesize($image);
  409. $h = (($size[1] * (($w)/$size[0])));
  410. $thumbnail = imagecreatetruecolor($w , $h);
  411. imagecopyresampled($thumbnail ,$resource, 0,0, 0,0, $w, $h, $size[0],$size[1]);
  412. imagedestroy($resource);
  413. imagejpeg($thumbnail , $image, 100);
  414. }
  415. function arand($array){
  416. return $array[array_rand($array)];
  417. }
  418. //Convertis une date en timestamp
  419. //(format possible dd-mm-yyyy ou dd/mm/yyyy)
  420. function timestamp_date($date){
  421. $date = explode('/',str_replace('-', '/', $date));
  422. if(count($date)!=3) return 0;
  423. $year = $date[2];
  424. $m = 0;
  425. $h = 0;
  426. if(strpos($year, ':')){
  427. $yinfos = explode(' ',$year);
  428. $year = $yinfos[0];
  429. list($h,$m) = explode(':',$yinfos[1]);
  430. }
  431. return mktime($h,$m,0,$date[1],$date[0],$year);
  432. }
  433. //Convertis une heur en timestamp à partir du 01/01/1970
  434. //(format possible hh:mm)
  435. function timestamp_hour($hour){
  436. $hour = explode(':',$hour);
  437. if(count($hour)!=2) return 0;
  438. return mktime($hour[0],$hour[1],0,1,1,1970);
  439. }
  440. // Récupère la différence entre 2 dates
  441. // avec le format spécifique fourni en paramètres
  442. // On compare Date1 à Date2
  443. // (format possible)
  444. function format_date_diff($date1, $date2, $format='%a'){
  445. $datetime1 = date_create($date1);
  446. $datetime2 = date_create($date2);
  447. $interval = $datetime1->diff($datetime2);
  448. return $interval->format($format);
  449. }
  450. // Construit une requete sécurisée pour le composant filtre
  451. function filter_secure_query($filters,$allowedColumns,&$query,&$data){
  452. foreach ($filters as $i=>$filter) {
  453. $filter['operator'] = html_entity_decode($filter['operator']);
  454. if(!in_array($filter['column'], $allowedColumns)) return;
  455. if(!in_array(strtolower($filter['operator']), array('<','>','=','!=','like','in','not in','between','is null','is not null'))) return;
  456. if(!in_array(strtolower($filter['join']), array('and','or'))) return;
  457. if(strtolower($filter['type']) == 'date'){
  458. $filter['column'] = 'UNIX_TIMESTAMP(STR_TO_DATE(DATE_FORMAT(FROM_UNIXTIME('.$filter['column'].'),"%d/%m/%Y"), "%d/%m/%Y"))';
  459. if(is_array($filter['value'])){
  460. foreach($filter['value'] as $i=>$value){
  461. $filter['value'][$i] = timestamp_date($value);
  462. }
  463. } else {
  464. $filter['value'] = timestamp_date($filter['value']);
  465. }
  466. }
  467. switch(strtolower($filter['operator'])){
  468. case 'like':
  469. $query .= ' '.$filter['join'].' '.$filter['column'].' '.$filter['operator'].' ?';
  470. $data[] = '%'.$filter['value'].'%' ;
  471. break;
  472. case 'is null':
  473. $query .= ' '.$filter['join'].' ('.$filter['column'].' IS NULL OR '.$filter['column'].'="") ';
  474. break;
  475. case 'is not null':
  476. $query .= ' '.$filter['join'].' ('.$filter['column'].' IS NOT NULL AND '.$filter['column'].'!="") ';
  477. break;
  478. case 'between':
  479. if(is_array($filter['value'])){
  480. $query .= ' '.$filter['join'].' '.$filter['column'].' '.$filter['operator'].' ? AND ?';
  481. $data[] = $filter['value'][0] ;
  482. $data[] = $filter['value'][1];
  483. }
  484. break;
  485. default:
  486. if(is_array($filter['value']))
  487. $filter['value'] = array_pop($filter['value']);
  488. $query .= ' '.$filter['join'].' '.$filter['column'].' '.$filter['operator'].' ?';
  489. $data[] = $filter['value'];
  490. break;
  491. }
  492. }
  493. }
  494. function sort_secure_query($sort,$allowedColumns,&$query){
  495. if(!in_array($sort['sortable'], $allowedColumns)) return;
  496. if(!in_array(strtolower($sort['sort']), array('asc','desc',''))) return;
  497. $query .= ' ORDER BY '.$sort['sortable'].' '.$sort['sort'];
  498. }
  499. function check_mail($mail){
  500. return ($mail && !empty($mail) && filter_var($mail, FILTER_VALIDATE_EMAIL));
  501. }
  502. function truncate($text, $length = 100, $options = array()) {
  503. $default = array(
  504. 'ending' => '...', 'exact' => true, 'html' => false
  505. );
  506. $options = array_merge($default, $options);
  507. extract($options);
  508. if ($html) {
  509. if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  510. return $text;
  511. }
  512. $totalLength = mb_strlen(strip_tags($ending));
  513. $openTags = array();
  514. $truncate = '';
  515. preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
  516. foreach ($tags as $tag) {
  517. if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
  518. if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
  519. array_unshift($openTags, $tag[2]);
  520. } else if (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
  521. $pos = array_search($closeTag[1], $openTags);
  522. if ($pos !== false) {
  523. array_splice($openTags, $pos, 1);
  524. }
  525. }
  526. }
  527. $truncate .= $tag[1];
  528. $contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
  529. if ($contentLength + $totalLength > $length) {
  530. $left = $length - $totalLength;
  531. $entitiesLength = 0;
  532. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE)) {
  533. foreach ($entities[0] as $entity) {
  534. if ($entity[1] + 1 - $entitiesLength <= $left) {
  535. $left--;
  536. $entitiesLength += mb_strlen($entity[0]);
  537. } else {
  538. break;
  539. }
  540. }
  541. }
  542. $truncate .= mb_substr($tag[3], 0 , $left + $entitiesLength);
  543. break;
  544. } else {
  545. $truncate .= $tag[3];
  546. $totalLength += $contentLength;
  547. }
  548. if ($totalLength >= $length) {
  549. break;
  550. }
  551. }
  552. } else {
  553. if (mb_strlen($text) <= $length) {
  554. return $text;
  555. } else {
  556. $truncate = mb_substr($text, 0, $length - mb_strlen($ending));
  557. }
  558. }
  559. if (!$exact) {
  560. $spacepos = mb_strrpos($truncate, ' ');
  561. if (isset($spacepos)) {
  562. if ($html) {
  563. $bits = mb_substr($truncate, $spacepos);
  564. preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
  565. if (!empty($droppedTags)) {
  566. foreach ($droppedTags as $closingTag) {
  567. if (!in_array($closingTag[1], $openTags)) {
  568. array_unshift($openTags, $closingTag[1]);
  569. }
  570. }
  571. }
  572. }
  573. $truncate = mb_substr($truncate, 0, $spacepos);
  574. }
  575. }
  576. $truncate .= $ending;
  577. if ($html) {
  578. foreach ($openTags as $tag) {
  579. $truncate .= '</'.$tag.'>';
  580. }
  581. }
  582. return $truncate;
  583. }
  584. /**
  585. * Permet de tronquer un texte en fonction d'un
  586. * nombre de caractères donné
  587. * @param string $content le texte à tronquer
  588. * @param int $limit le nombre de caractères qu'on garde
  589. * @param string $limiter le caractère de remplacement de fin de chaine
  590. * @return string le texte final, tronqué
  591. */
  592. function truncate_content($content,$limit,$limiter){
  593. if(strlen($content)>$limit) $content = mb_substr($content, 0,$limit).$limiter;
  594. return $content;
  595. }
  596. //Permet de décoder la chaîne d'entrée $string
  597. //en UTF-8 et de décoder les caractères spéciaux
  598. //pour l'affichage HTML
  599. function html_decode_utf8($string){
  600. return htmlspecialchars(html_entity_decode($string), ENT_QUOTES, 'UTF-8');
  601. }
  602. //Permet de checker si l'élément est
  603. //setté et non vide
  604. function set_not_empty($element){
  605. return (isset($element) && !empty($element));
  606. }
  607. //Permet de checker si l'élément est
  608. //non setté ou vide
  609. function not_set_empty($element){
  610. return (!isset($element) || empty($element));
  611. }
  612. // Permet de mettre au bon format le n° de
  613. // téléphone fourni dans le formulaire
  614. function normalize_phone_number($number){
  615. $nb = str_replace(array(' ', '.', ','), '', $number);
  616. $nb = chunk_split($nb, 2, ' ');
  617. $nb = rtrim($nb);
  618. preg_match("/^[0-9]{2} [0-9]{2} [0-9]{2} [0-9]{2} [0-9]{2}/", $nb, $matches);
  619. return isset($matches[0]) ? $matches[0] : $nb;
  620. }
  621. // Permet de voir si le format du n° de téléphone
  622. // fourni correspond à un format correct
  623. function check_phone_number($number){
  624. $nb = str_replace(array(' ', '.', ','), '', $number);
  625. if (!is_numeric($nb)) return false;
  626. return true;
  627. }
  628. //Retourne la valeur la plus proche d'un
  629. //nombre donné par rapport à un tableau de
  630. //nombres
  631. function get_closest_number($search, $arr){
  632. $closest = null;
  633. foreach ($arr as $item) {
  634. if ($closest === null || abs($search - $closest) > abs($item - $search)) {
  635. $closest = $item;
  636. }
  637. }
  638. return $closest;
  639. }
  640. // Permet de convertir string encodée en UTF-8
  641. // en ASCII pour ensuite appliquer une méthode
  642. // de Levenshtein sans avoir de divergences
  643. // trop importantes dues aux accents présents.
  644. function utf8_to_extended_ascii($str, &$map) {
  645. // find all multibyte characters (cf. utf-8 encoding specs)
  646. $matches = array();
  647. if (!preg_match_all('/[\xC0-\xF7][\x80-\xBF]+/', $str, $matches))
  648. return $str; // plain ascii string
  649. // update the encoding map with the characters not already met
  650. foreach ($matches[0] as $mbc)
  651. if (!isset($map[$mbc]))
  652. $map[$mbc] = chr(128 + count($map));
  653. // finally remap non-ascii characters
  654. return strtr($str, $map);
  655. }
  656. // Override de la méthode de Levenshtein pour
  657. // compérer 2 strings encondées en UTF-8
  658. function levenshtein_utf8($s1, $s2) {
  659. $charMap = array();
  660. $s1 = utf8_to_extended_ascii($s1, $charMap);
  661. $s2 = utf8_to_extended_ascii($s2, $charMap);
  662. return levenshtein($s1, $s2);
  663. }
  664. // Méthode qui retourne sous forme de tableau
  665. // les metaphones // des différents mots d'une
  666. // phrase.
  667. function get_metaphones($sentence) {
  668. $metaphones = array();
  669. $words = explode(' ',$sentence);
  670. foreach ($words as $word) {
  671. $metaphones[] = metaphone($word);
  672. }
  673. return $metaphones;
  674. }
  675. // Permet de trouver une chaîne de caractère s'approchant
  676. // le plus de l'entrée fournie en paramètres
  677. function find_best_match($words = array(), $input = '') {
  678. $closest = '';
  679. $foundBestMatch = -1;
  680. $tmpInput = implode(' ', get_metaphones($input));
  681. foreach($words as $word) {
  682. $tmpGauge = implode(' ', get_metaphones($word));
  683. $similarity = levenshtein_utf8($tmpInput, $tmpGauge);
  684. if ($similarity == 0) {
  685. $closest = $word;
  686. $foundBestMatch = 0;
  687. break;
  688. }
  689. if ($similarity <= $foundBestMatch || $foundBestMatch < 0) {
  690. $closest = $word;
  691. $foundBestMatch = $similarity;
  692. }
  693. }
  694. return $closest;
  695. }
  696. // Convertit nombres en lettres (utile pour Excel)
  697. function numbers_to_letters($num){
  698. $num = intval($num);
  699. if ($num <= 0) return '';
  700. $letter = '';
  701. while($num != 0){
  702. $p = ($num - 1) % 26;
  703. $num = intval(($num - $p) / 26);
  704. $letter = chr(65 + $p) . $letter;
  705. }
  706. return $letter;
  707. }
  708. // Convertit nombres en lettres (utile pour Excel)
  709. // eg: 1==A
  710. function numbers_to_letters_2($num) {
  711. $numeric = ($num - 1) % 26;
  712. $letter = chr(65 + $numeric);
  713. $num2 = intval(($num - 1) / 26);
  714. if ($num2 > 0) {
  715. return getNameFromNumber($num2) . $letter;
  716. } else {
  717. return $letter;
  718. }
  719. }
  720. //Convertit lettres en nombres (utile pour Excel)
  721. function letters_to_numbers($col){
  722. $col = str_pad($col,3,'0', STR_PAD_LEFT);
  723. $i = 0;
  724. if ($col{0} != '0') {
  725. $i = ((ord($col{0}) - 64) * 676) + 26;
  726. $i += ($col{1} == '0') ? 0 : (ord($col{1}) - 65) * 26;
  727. } else {
  728. $i += ($col{1} == '0') ? 0 : (ord($col{1}) - 64) * 26;
  729. }
  730. $i += ord($col{2}) - 64;
  731. return $i;
  732. }
  733. //Check si c'est un date bien formattée
  734. function is_date($date){
  735. $date = str_replace(array('-',' ','\\'),'/',trim($date));
  736. if(trim($date)=='') return false;
  737. if (count(explode('/',$date)) < 3) return false;
  738. list($d,$m,$y) = explode('/',$date);
  739. if( !is_numeric($d) || !is_numeric($m) || !is_numeric($y) ) return false;
  740. return checkdate ( $m , $d , $y );
  741. }
  742. //Cherche la position de $needles dans
  743. //$haystack, où $needles est un array
  744. //de string et $haystack est le string à
  745. //comparer
  746. function strpos_array($haystack, $needles=array(), $offset=0) {
  747. $chr = array();
  748. foreach($needles as $needle) {
  749. $res = strpos($haystack, $needle, $offset);
  750. if ($res !== false) $chr[$needle] = $res;
  751. }
  752. if(empty($chr)) return false;
  753. return min($chr);
  754. }
  755. //Supprime un dossier et son contenu
  756. //de manière récursive
  757. function delete_folder_tree($dir, $selfDestroy=false) {
  758. $files = array_diff(scandir($dir), array('.','..'));
  759. foreach ($files as $file) {
  760. (is_dir("$dir/$file")) ? delete_folder_tree("$dir/$file") : unlink("$dir/$file");
  761. }
  762. if($selfDestroy) return delete_folder_tree($dir);
  763. }
  764. //Normalise les caractères un peu spéciaux
  765. //d'une chaîne de calculhmac(ractère, data)
  766. function normalize_chars($string) {
  767. $normalizeChars = array(
  768. 'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A',
  769. 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I',
  770. 'Ï'=>'I', 'Ñ'=>'N', 'Ń'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
  771. 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a',
  772. 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i',
  773. 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ń'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o',
  774. 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ü'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f',
  775. 'ă'=>'a', 'î'=>'i', 'â'=>'a', 'ș'=>'s', 'ț'=>'t', 'Ă'=>'A', 'Î'=>'I', 'Â'=>'A', 'Ș'=>'S', 'Ț'=>'T',
  776. );
  777. return strtr($string, $normalizeChars);
  778. }
  779. //Convertit un nombre en son équivalent écrit
  780. //e.g: 23 --> VINGT-TROIS
  781. function number_to_words($number, $feminine=false) {
  782. $hyphen = '-';
  783. $conjunction = ' et ';
  784. $separator = ', ';
  785. $negative = 'moins ';
  786. $decimal = ' virgule ';
  787. $dictionary = array(
  788. 0 => 'zero',
  789. 1 => !$feminine?'un':'une',
  790. 2 => 'deux',
  791. 3 => 'trois',
  792. 4 => 'quatre',
  793. 5 => 'cinq',
  794. 6 => 'six',
  795. 7 => 'sept',
  796. 8 => 'huit',
  797. 9 => 'neuf',
  798. 10 => 'dix',
  799. 11 => 'onze',
  800. 12 => 'douze',
  801. 13 => 'treize',
  802. 14 => 'quatorze',
  803. 15 => 'quinze',
  804. 16 => 'seize',
  805. 17 => 'dix-sept',
  806. 18 => 'dix-huit',
  807. 19 => 'dix-neuf',
  808. 20 => 'vingt',
  809. 30 => 'trente',
  810. 40 => 'quarante',
  811. 50 => 'cinquante',
  812. 60 => 'soixante',
  813. 70 => 'soixante-dix',
  814. 80 => 'quatre-vingt',
  815. 90 => 'quatre-vingt dix',
  816. 100 => 'cent',
  817. 1000 => 'mille',
  818. 1000000 => 'million',
  819. 1000000000 => 'milliard',
  820. 1000000000000 => 'trillion',
  821. 1000000000000000 => 'quadrillion',
  822. 1000000000000000000 => 'quintillion'
  823. );
  824. if (!is_numeric($number)) return false;
  825. if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) throw new Exception('number_to_words accepte uniquement des nombres compris entre -'.PHP_INT_MAX.' et '.PHP_INT_MAX);
  826. if ($number < 0) return $negative.number_to_words(abs($number));
  827. $string = $fraction = null;
  828. if (strpos($number, '.') !== false)
  829. list($number, $fraction) = explode('.', $number);
  830. switch (true) {
  831. case $number < 21:
  832. $string = $dictionary[$number];
  833. break;
  834. case $number == 21:
  835. $string = $dictionary[20].$conjunction.$dictionary[1];
  836. break;
  837. case $number == 31:
  838. $string = $dictionary[30].$conjunction.$dictionary[1];
  839. break;
  840. case $number == 41:
  841. $string = $dictionary[40].$conjunction.$dictionary[1];
  842. break;
  843. case $number == 51:
  844. $string = $dictionary[50].$conjunction.$dictionary[1];
  845. break;
  846. case $number == 61:
  847. $string = $dictionary[60].$conjunction.$dictionary[1];
  848. break;
  849. case $number == 71:
  850. $string = $dictionary[60].$conjunction.$dictionary[11];
  851. break;
  852. case $number == 81:
  853. $string = $dictionary[80].$hyphen.$dictionary[1];
  854. break;
  855. case $number == 91:
  856. $string = $dictionary[80].$hyphen.$dictionary[11];
  857. break;
  858. case $number < 100:
  859. $tens = ((int) ($number / 10)) * 10;
  860. $units = $number % 10;
  861. $string = $dictionary[$tens];
  862. if ($units) {
  863. $string .= $hyphen . $dictionary[$units];
  864. }
  865. break;
  866. case $number < 1000:
  867. $hundreds = $number / 100;
  868. $remainder = $number % 100;
  869. $string = ((int)$hundreds==1 ? '' : $dictionary[$hundreds].' ') . $dictionary[100];
  870. if ($remainder) {
  871. $string .= ' ' . number_to_words($remainder);
  872. }
  873. break;
  874. default:
  875. $baseUnit = pow(1000, floor(log($number, 1000)));
  876. $numBaseUnits = (int) ($number / $baseUnit);
  877. $remainder = $number % $baseUnit;
  878. $string = number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
  879. if ($remainder) {
  880. $string .= $remainder < 100 ? $conjunction : ' ';
  881. $string .= number_to_words($remainder);
  882. }
  883. break;
  884. }
  885. if (null !== $fraction && is_numeric($fraction)) {
  886. $string .= $decimal;
  887. if(strlen($fraction) <= 3) {
  888. $string .= number_to_words($fraction);
  889. } else {
  890. $words = array();
  891. foreach (str_split((string) $fraction) as $number)
  892. $words[] = $dictionary[$number];
  893. $string .= implode(' ', $words);
  894. }
  895. }
  896. return mb_strtoupper($string);
  897. }
  898. /**
  899. * Retrourne le numéral ordinal compact
  900. * d'un nombre passé en paramètre.
  901. * eg:
  902. * 1 --> 1er,
  903. * 2 --> 2ème, etc..
  904. * Les nombres ordinaux sont définis par un
  905. * l'ensemble des entiers naturels non nuls
  906. * représenté N*={1,2,3,...}
  907. */
  908. function number_to_ordinal($number, $feminine=false){
  909. $number = (int) $number;
  910. //Aucun ordinal pour le rang 0
  911. if($number == 0) return;
  912. if($number == 1)
  913. return $number.($feminine?'ère':'er');
  914. return $number.'ème';
  915. }
  916. /**
  917. * Retourne les fonction interdites
  918. * utilisées dans une fonction eval()
  919. * @param string $source [le string qui va $etre eval()]
  920. * @return Array [Tableau des méthodes utilisées interdites]
  921. */
  922. function forbidden_macro($source){
  923. $tokens = token_get_all('<?php '.$source.' ?>');
  924. $forbiddens = array();
  925. $allowed_functions = array(
  926. 'ucfirst',
  927. 'strto.*',
  928. 'str_.*',
  929. 'substr',
  930. 'password_encrypt',
  931. 'strpos',
  932. 'date',
  933. '[im|ex]plode',
  934. 'preg_*',
  935. 'count',
  936. 'time',
  937. 'array_.*',
  938. '.sort',
  939. );
  940. foreach($tokens as $token){
  941. if(is_string($token)) continue;
  942. list($id, $text,$line) = $token;
  943. if(in_array($id, array(T_FUNCTION,T_FUNC_C,T_EVAL,T_STRING))){
  944. $allowed = false;
  945. foreach ($allowed_functions as $function) {
  946. preg_match('/'.$function.'/i', $text, $matches);
  947. if(count($matches)!=0){
  948. $allowed = true;
  949. break;
  950. }
  951. }
  952. if(!$allowed) $forbiddens[] = $text.' L'.$line;
  953. }
  954. if(in_array($id, array(
  955. T_INCLUDE,
  956. T_EXTENDS,
  957. T_CLONE,
  958. T_EXIT,
  959. T_GLOBAL,
  960. T_HALT_COMPILER,
  961. T_IMPLEMENTS,
  962. T_INCLUDE_ONCE,
  963. T_REQUIRE,
  964. T_REQUIRE_ONCE,
  965. T_IMPLEMENTS
  966. ))){
  967. $forbiddens[] = $text.' L'.$line;
  968. }
  969. }
  970. return $forbiddens;
  971. }
  972. function template($stream,$data){
  973. //loop
  974. $stream = preg_replace_callback('/{{\:([^\/\:\?}]*)}}(.*?){{\/\:[^\/\:\?}]*}}/',function($matches) use ($data) {
  975. $tag = $matches[1];
  976. $streamTpl = $matches[2];
  977. $stream = '';
  978. if(!isset($data[$tag])) return $stream;
  979. $i = 0;
  980. $values = $data[$tag];
  981. foreach($values as $join){
  982. $occurence = $streamTpl;
  983. foreach($join as $key=>$value){
  984. $occurence = str_replace(array('{{'.$key.'}}'),array($value),$occurence);
  985. }
  986. $stream.= $occurence;
  987. }
  988. return $stream;
  989. },$stream);
  990. //conditions
  991. $stream = preg_replace_callback('/{{\?([^\/\:\?}]*)}}(.*?){{\/\?[^\/\:\?}]*}}/',function($matches) use ($data) {
  992. $key = $matches[1];
  993. $stream = $matches[2];
  994. return !isset($data[$key]) || (is_array($data[$key]) && count($data[$key])==0) ?'':$stream;
  995. },$stream);
  996. //simple vars
  997. $stream = preg_replace_callback('/{{([^\/\:\;\?}]*)}}/',function($matches) use ($data) {
  998. $key = $matches[1];
  999. if (isset($data[$key]) ) return $data[$key];
  1000. $value = '';
  1001. $attributes = explode('.',$key);
  1002. $current = $data;
  1003. foreach ($attributes as $attribute) {
  1004. if ( !isset($current[$attribute]) ) return;
  1005. $current = $current[$attribute];
  1006. $value = $current;
  1007. }
  1008. return $value;
  1009. },$stream);
  1010. return $stream;
  1011. }
  1012. /**
  1013. * Incrémente automatiquement le nom d'un
  1014. * fichier si celui-ci existe déjà
  1015. * Fonction récursive.
  1016. * @param String $extension [extension du fichier]
  1017. * @param String $folder [dossier où localiser le fichier]
  1018. * @param String $filename [nom du fichier]
  1019. * @return String [nom de fichier final]
  1020. */
  1021. function autoincrement_filename($extension, $folder, $filename){
  1022. static $counter = 0;
  1023. $fileNb = count(glob(FILE_PATH.$folder.$filename));
  1024. $filenameProps = explode('.', $filename);
  1025. unset($filenameProps[count($filenameProps)-1]);
  1026. $finalFilename = implode('.', $filenameProps);
  1027. if($fileNb>0) {
  1028. $counter+=1;
  1029. $filename = preg_match("/(^.*?\()(\d+)([^\\d]*\)\..*$)/", $filename, $matches) ? $matches[1].$counter.$matches[3] : $finalFilename.'('.$counter.')'.'.'.$extension;
  1030. $filename = autoincrement_filename($extension, $folder, $filename);
  1031. }
  1032. return $filename;
  1033. }
  1034. function relative_path($absolutePath,$reference = __ROOT__){
  1035. $absolutePath = str_replace(array('\\','/'),SLASH,$absolutePath);
  1036. $reference = str_replace(array('\\','/'),SLASH,$reference);
  1037. return str_replace($reference,'',$absolutePath);
  1038. }
  1039. //Définit si une couleur hexadecimale est claire
  1040. //ou sombre en fonction d'un seuil de luminosité
  1041. function get_light($hexcode,$treshold = 510.0) {
  1042. $rgb = to_rgb($hexcode);
  1043. return (max($rgb[0], $rgb[1], $rgb[2]) + min($rgb[0], $rgb[1], $rgb[2])) / $treshold;
  1044. }
  1045. //Génère une couleur hexadécimale aléatoire
  1046. function random_hex_color() {
  1047. return '#'.str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
  1048. }
  1049. //Génère une couleur pastel basé sur
  1050. //le hash md5 du mot passé en paramètre
  1051. function random_hex_pastel_color($name) {
  1052. $hash = md5($name);
  1053. $red = hexdec(substr($hash, 8, 2));
  1054. $green = hexdec(substr($hash, 4, 2));
  1055. $blue = hexdec(substr($hash, 0, 2));
  1056. if($red < 128) $red += 128;
  1057. if($green < 128) $green += 128;
  1058. if($blue < 128) $blue += 128;
  1059. return "#" . dechex($red) . dechex($green) . dechex($blue);
  1060. }
  1061. //Convertit un code hexadecimal en code RGB
  1062. function to_rgb($hexcode) {
  1063. $hexcode = substr($hexcode, 1);
  1064. return array(hexdec($hexcode[0] . $hexcode[1]),
  1065. hexdec($hexcode[2] . $hexcode[3]),
  1066. hexdec($hexcode[4] . $hexcode[5]));
  1067. }
  1068. //Retourne le nom complet d'un mois en fonction de son numéro
  1069. function month_name($month){
  1070. $translates = array('Janvier','Fevrier','Mars','Avril','Mai','Juin','Juillet','Aout','Septembre','Octobre','Novembre','Décembre');
  1071. return $translates[$month-1];
  1072. }
  1073. //Retourne le nom complet d'un jour en fonction de son numéro (1 : lundi,..., 7 :dimanche)
  1074. function day_name($day){
  1075. $translates = array('Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi','Dimanche');
  1076. return $translates[$day-1];
  1077. }
  1078. //Récuperation des jours féries
  1079. function get_not_workable($date=null){
  1080. if ($date === null)
  1081. $date = time();
  1082. $date = strtotime(date('m/d/Y',$date));
  1083. $year = date('Y',$date);
  1084. $easterDate = easter_date($year);
  1085. $easterDay = date('j', $easterDate);
  1086. $easterMonth = date('n', $easterDate);
  1087. $easterYear = date('Y', $easterDate);
  1088. $holidays = array(
  1089. // Dates fixes
  1090. mktime(0, 0, 0, 1, 1, $year), // 1er janvier
  1091. mktime(0, 0, 0, 5, 1, $year), // Fête du travail
  1092. mktime(0, 0, 0, 5, 8, $year), // Victoire des alliés
  1093. mktime(0, 0, 0, 7, 14, $year), // Fête nationale
  1094. mktime(0, 0, 0, 8, 15, $year), // Assomption
  1095. mktime(0, 0, 0, 11, 1, $year), // Toussaint
  1096. mktime(0, 0, 0, 11, 11, $year), // Armistice
  1097. mktime(0, 0, 0, 12, 25, $year), // Noel
  1098. // Dates variables
  1099. mktime(0, 0, 0, $easterMonth, $easterDay + 1, $easterYear),
  1100. mktime(0, 0, 0, $easterMonth, $easterDay + 39, $easterYear),
  1101. mktime(0, 0, 0, $easterMonth, $easterDay + 50, $easterYear),
  1102. );
  1103. return $holidays;
  1104. }
  1105. //Retourne le chemin web d'un fichier en fonction de son chemin
  1106. //physique (ex : /img/logo.png pour /var/www/erp-core/img/logo.png)
  1107. function webpath($path){
  1108. $url = ROOT_URL.str_replace(array(__DIR__.SLASH,"\\","/"),array('','/','/'),$path);
  1109. $url = preg_replace('/([^\:])(\/{2,})/i', '$1/', $url);
  1110. return $url;
  1111. }
  1112. //Retourne un tableau clé/valeur des valeurs
  1113. //existantes en doublons du tableau passé en paramètre
  1114. function array_not_unique($array=array()){
  1115. return array_diff_key($array, array_unique($array));
  1116. }
  1117. //Retourne true si aucune valeur du tableau passé
  1118. //en paramètre a un doublon, false sinon.
  1119. function is_array_unique($array=array()){
  1120. return empty(array_not_unique($array));
  1121. }
  1122. function make_cookie($nom, $valeur, $expire='',$ns ='/') {
  1123. if($expire == ''){
  1124. setcookie($nom, $valeur, mktime(0,0,0, date("d"), date("m"), (date("Y")+1)), $ns);
  1125. } else {
  1126. setcookie($nom, '', mktime(0,0,0, date("d"), date("m"), (date("Y")-1)), $ns);
  1127. }
  1128. }
  1129. //Permet de formatter les prix à afficher
  1130. //de la même manière partout sur l'ERP.
  1131. //Si jamais on veut changer de normalisation
  1132. //pour l'affichage des prix, il suffit de changer
  1133. //le fonctionnement ici uniquement.
  1134. function display_price($price){
  1135. return number_format($price, 2, ',', ' ');
  1136. }
  1137. //Permet de formatter les prix à enregistrer
  1138. //de la même manière partout sur l'ERP.
  1139. //Si jamais on veut changer de normalisation
  1140. //pour l'enregistrement des prix, il suffit de changer
  1141. //le fonctionnement ici uniquement.
  1142. function format_price($price){
  1143. return str_replace(',','.',$price);
  1144. }
  1145. //Permet de calculer un age en fonction de la date du jour
  1146. //Paramètre : la date de départ(format timestamp), l'unité de retour souhaitée(format 'd', 'm', 'Y'... voir fonction diff de php)
  1147. //Renvoie : l'age en entier
  1148. function age($from,$unit = 'y'){
  1149. if(!isset($from) || !is_numeric($from)) return 'N/A';
  1150. $from = new \DateTime(date('Y-m-d',$from));
  1151. $to = new \DateTime('today');
  1152. $age = $from->diff($to);
  1153. if(!$age || !array_key_exists($unit, $age))
  1154. return 'N/A';
  1155. return $age = $age->$unit;
  1156. }
  1157. //Permet d'échapper tous les caractères interdits dans une chaine json
  1158. function escape_json_string($value) { # list from www.json.org: (\b backspace, \f formfeed)
  1159. $escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
  1160. $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
  1161. $result = str_replace($escapers, $replacements, $value);
  1162. return $result;
  1163. }
  1164. if( !function_exists('apache_request_headers') ) {
  1165. ///
  1166. function apache_request_headers() {
  1167. $arh = array();
  1168. $rx_http = '/\AHTTP_/';
  1169. foreach($_SERVER as $key => $val) {
  1170. if( preg_match($rx_http, $key) ) {
  1171. $arh_key = preg_replace($rx_http, '', $key);
  1172. $rx_matches = array();
  1173. // do some nasty string manipulations to restore the original letter case
  1174. // this should work in most cases
  1175. $rx_matches = explode('_', $arh_key);
  1176. if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
  1177. foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
  1178. $arh_key = implode('-', $rx_matches);
  1179. }
  1180. $arh[$arh_key] = $val;
  1181. }
  1182. }
  1183. return( $arh );
  1184. }
  1185. }
  1186. //Effectue un basename en tenant compte des caractères utf8( non pris en compte par basename PHP sous linux)
  1187. function mt_basename($path){
  1188. $path = str_replace(array("\\","/"),SLASH, $path);
  1189. $nameSplit = explode(SLASH,$path);
  1190. return end($nameSplit);
  1191. }
  1192. ?>