function.php 40 KB

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