helpers_default.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. <?php
  2. use \KarmaFW\App\Response;
  3. use \KarmaFW\Routing\Router;
  4. if (! function_exists('pre')) {
  5. function pre($var, $exit = false, $prefix = '') {
  6. $out = '';
  7. $out .= "<pre>";
  8. if (!empty($prefix)) {
  9. $out .= $prefix;
  10. }
  11. if (is_null($var)) {
  12. $out .= "NULL";
  13. } else if ($var === true) {
  14. $out .= "TRUE";
  15. } else if ($var === false) {
  16. $out .= "FALSE";
  17. } else if (is_string($var)) {
  18. $out .= '"' . $var . '"';
  19. } else {
  20. $out .= print_r($var, true);
  21. }
  22. $out .= "</pre>";
  23. if ($exit) {
  24. //exit;
  25. throw new \Exception($out, 200);
  26. } else {
  27. echo $out;
  28. }
  29. }
  30. }
  31. if (! function_exists('ifEmpty')) {
  32. function ifEmpty($val, $default_value='-1') {
  33. return empty($val) ? $default_value : $val;
  34. }
  35. }
  36. if (! function_exists('errorHttp')) {
  37. function errorHttp($error_code, $message='An error has occured', $title='Error') {
  38. /*
  39. header("HTTP/1.0 " . $error_code . " " . $title);
  40. echo '<h1>' . $title . '</h1>';
  41. echo '<p>' . $message . '</p>';
  42. exit;
  43. */
  44. $content = '<html>';
  45. $content .= '<head>';
  46. $content .= '<title>' . $title . '</title>';
  47. $content .= '</head>';
  48. $content .= '<body>';
  49. $content .= '<h1>' . $title . '</h1>';
  50. $content .= '<p>' . $message . '</p>';
  51. $content .= '</body>';
  52. $content .= '</html>';
  53. throw new \Exception($content, $error_code);
  54. }
  55. }
  56. if (! function_exists('redirect')) {
  57. function redirect($url, $http_code=302) {
  58. if ($http_code == 'link' || $http_code == 'debug') {
  59. echo 'continue to <a href="' . $url . '">' . $url . '</a>';
  60. exit;
  61. }
  62. throw new \Exception($url, $http_code);
  63. //exit;
  64. //header('Location: ' . $url, true, $http_code);
  65. }
  66. }
  67. if (! function_exists('get')) {
  68. function get($key, $default_value=null) {
  69. return isset($_GET[$key]) ? $_GET[$key] : $default_value;
  70. }
  71. }
  72. if (! function_exists('post')) {
  73. function post($key, $default_value=null) {
  74. return isset($_POST[$key]) ? $_POST[$key] : $default_value;
  75. }
  76. }
  77. if (! function_exists('session')) {
  78. function session($key, $default_value=null) {
  79. return isset($_SESSION[$key]) ? $_SESSION[$key] : $default_value;
  80. }
  81. }
  82. if (! function_exists('cookie')) {
  83. function cookie($key, $default_value=null) {
  84. return isset($_COOKIE[$key]) ? $_COOKIE[$key] : $default_value;
  85. }
  86. }
  87. if (! function_exists('slugify')) {
  88. function slugify($text, $max_length=null) {
  89. // https://stackoverflow.com/questions/2955251/php-function-to-make-slug-url-string
  90. // https://stackoverflow.com/questions/3371697/replacing-accented-characters-php
  91. $unwanted_array = array( 'Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
  92. 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
  93. 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
  94. 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
  95. 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
  96. $text = strtr( $text, $unwanted_array );
  97. // replace non letter or digits by -
  98. $text = preg_replace('~[^\pL\d]+~u', '-', $text);
  99. // transliterate
  100. $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
  101. // remove unwanted characters
  102. $text = preg_replace('~[^-\w]+~', '', $text);
  103. // trim
  104. $text = trim($text, '-');
  105. // remove duplicate -
  106. $text = preg_replace('~-+~', '-', $text);
  107. // lowercase
  108. $text = strtolower($text);
  109. if (empty($text)) {
  110. return 'n-a';
  111. }
  112. if (! empty($max_length) && strlen($text) > $max_length) {
  113. $text = substr(0, $max_length);
  114. }
  115. return $text;
  116. }
  117. }
  118. if (! function_exists('generate_uid')) {
  119. function generate_uid() {
  120. if (function_exists('com_create_guid')) {
  121. return trim(com_create_guid(), '{}');
  122. }
  123. if (function_exists('openssl_random_pseudo_bytes') === true) {
  124. $data = openssl_random_pseudo_bytes(16);
  125. $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
  126. $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
  127. return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
  128. }
  129. mt_srand((double)microtime()*10000);
  130. $charid = strtoupper(md5(uniqid(rand(), true)));
  131. $uuid = sprintf(
  132. "%s-%s-%s-%s-%s",
  133. substr($charid, 0, 8),
  134. substr($charid, 8, 4),
  135. substr($charid,12, 4),
  136. substr($charid,16, 4),
  137. substr($charid,20,12)
  138. );
  139. return strtolower($uuid);
  140. }
  141. }
  142. if (! function_exists('generate_password')) {
  143. function generate_password($nb_chars = 8) {
  144. $ref = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 62 caractères au total
  145. $ref = $ref . $ref . $ref; // permet d'avoir jusqu'à 3 fois le meme caractere dans le mot de passe
  146. $ref = str_shuffle($ref);
  147. return substr($ref, 0, $nb_chars);
  148. }
  149. }
  150. if (! function_exists('getRouteUrl')) {
  151. function getRouteUrl($route_name, $urls_args=[]) {
  152. return Router::getRouteUrl($route_name, $urls_args);
  153. }
  154. }
  155. if (! function_exists('date_us_to_fr')) {
  156. function date_us_to_fr($date_us, $include_time=false) {
  157. if (empty($date_us)) {
  158. return null;
  159. }
  160. $time = ($include_time) ? substr($date_us, 10) : "";
  161. $date_us = substr($date_us, 0, 10);
  162. $parts = explode('-', $date_us);
  163. return implode('/', array_reverse($parts)) . $time;
  164. }
  165. }
  166. if (! function_exists('date_us2_to_fr')) {
  167. function date_us2_to_fr($date_us, $include_time=false) {
  168. //pre($date_us, "date_us2_to_fr: "); exit;
  169. if (empty($date_us) || strlen($date_us) < 8) {
  170. return null;
  171. }
  172. $time = ($include_time) ? substr($date_us, 10) : "";
  173. $date_us = substr($date_us, 0, 10);
  174. $parts = explode('/', $date_us);
  175. $parts2 = [
  176. substr('00' . $parts[1], -2),
  177. substr('00' . $parts[0], -2),
  178. $parts[2],
  179. ];
  180. return implode('/', $parts2) . $time;
  181. }
  182. }
  183. if (! function_exists('date_fr_to_us')) {
  184. function date_fr_to_us($date_fr, $include_time=false) {
  185. if (empty($date_fr)) {
  186. return null;
  187. }
  188. $time = ($include_time) ? substr($date_fr, 10) : "";
  189. $date_fr = substr($date_fr, 0, 10);
  190. $parts = explode('/', $date_fr);
  191. return implode('-', array_reverse($parts)) . $time;
  192. }
  193. }
  194. if (! function_exists('truncate_str')) {
  195. function truncate_str($str, $max_length) {
  196. if (strlen($str) > $max_length) {
  197. $str = substr($str, 0, $max_length-1) . '…';
  198. }
  199. return $str;
  200. }
  201. }
  202. if (! function_exists('get_url_path')) {
  203. function get_url_path($url, $with_querystring=true, $with_url_hash=false) {
  204. $url_parts = parse_url($url);
  205. $url = $url_parts['path'];
  206. if ($with_querystring && ! empty($url_parts['query'])) {
  207. $url .= '?' . $url_parts['query'];
  208. }
  209. if ($with_url_hash && ! empty($url_parts['fragment'])) {
  210. $url .= '#' . $url_parts['fragment'];
  211. }
  212. return $url;
  213. }
  214. }
  215. if (! function_exists('rrmdir')) {
  216. function rrmdir($src) {
  217. // https://www.php.net/manual/fr/function.rmdir.php
  218. $dir = opendir($src);
  219. while(false !== ( $file = readdir($dir)) ) {
  220. if (( $file != '.' ) && ( $file != '..' )) {
  221. $full = $src . '/' . $file;
  222. if ( is_dir($full) ) {
  223. rrmdir($full);
  224. }
  225. else {
  226. unlink($full);
  227. }
  228. }
  229. }
  230. closedir($dir);
  231. rmdir($src);
  232. }
  233. }
  234. if (! function_exists('formatSize')) {
  235. function formatSize($bytes, $format = '%.2f',$lang = 'fr') {
  236. // http://dev.petitchevalroux.net/php/afficher-taille-fichier-avec-une-unite-php.271.html
  237. if (empty($bytes)) {
  238. return '0';
  239. }
  240. static $units = array(
  241. 'fr' => array(
  242. 'o',
  243. 'Ko',
  244. 'Mo',
  245. 'Go',
  246. 'To'
  247. ),
  248. 'en' => array(
  249. 'B',
  250. 'KB',
  251. 'MB',
  252. 'GB',
  253. 'TB'
  254. ),
  255. );
  256. $translatedUnits = &$units[$lang];
  257. if(isset($translatedUnits) === false) {
  258. $translatedUnits = &$units['en'];
  259. }
  260. $b = (double)$bytes;
  261. /*On gére le cas des tailles de fichier négatives*/
  262. if ($b > 0) {
  263. $e = (int)(log($b,1024));
  264. /**Si on a pas l'unité on retourne en To*/
  265. if(isset($translatedUnits[$e]) === false) {
  266. $e = 4;
  267. }
  268. $b = $b/pow(1024,$e);
  269. } else {
  270. $b = 0;
  271. $e = 0;
  272. }
  273. return sprintf($format.' %s',$b,$translatedUnits[$e]);
  274. }
  275. }
  276. if (! function_exists('formatTel')) {
  277. function formatTel($num, $sep=' ') {
  278. if (is_null($num)) {
  279. return null;
  280. }
  281. $num = trim($num);
  282. $num = str_replace(' ', '', $num);
  283. $num = str_replace('.', '', $num);
  284. $num = str_replace('-', '', $num);
  285. if (strlen($num) == 10) {
  286. $parts = str_split($num, 2);
  287. return implode($sep, $parts);
  288. }
  289. if (strlen($num) == 12 && substr($num, 0, 3) == '+33') {
  290. $parts = str_split(substr($num, 4), 2);
  291. return substr($num, 0, 3) . ' ' . substr($num, 3, 1) . ' ' . implode($sep, $parts);
  292. }
  293. return $num;
  294. }
  295. }
  296. if (! function_exists('formatPrice')) {
  297. function formatPrice($price, $devise='') {
  298. if (empty($price)) {
  299. $price = 0;
  300. }
  301. $str = number_format($price, 2, ".", " ");
  302. if (! empty($devise)) {
  303. $str .= " " . $devise;
  304. }
  305. return $str;
  306. }
  307. }
  308. if (! function_exists('formatDuration')) {
  309. function formatDuration($seconds) {
  310. if (empty($seconds)) {
  311. return 0 . " s";
  312. } else if ($seconds < 1/1000) {
  313. return round($seconds*1000*1000, 4) . " µs";
  314. } else if ($seconds < 1) {
  315. return round($seconds*1000, 4) . " ms";
  316. } else if ($seconds < 60) {
  317. return $seconds . " s";
  318. } else if ($seconds < 3600) {
  319. $minutes = floor($seconds/60);
  320. $seconds2 = $seconds - ($minutes * 60);
  321. return $minutes . " min " . $seconds2 . " s";
  322. } else if ($seconds < 86400) {
  323. $hours = floor($seconds/3600);
  324. $seconds2 = $seconds - ($hours * 3600);
  325. $minutes = floor($seconds2/60);
  326. $seconds3 = $seconds2 - ($minutes * 60);
  327. return $hours . " h " . $minutes . " min"; // . " " . $seconds3 . " s";
  328. } else {
  329. $days = floor($seconds/86400);
  330. $seconds2 = $seconds - ($days * 3600);
  331. $hours = floor($seconds2/3600);
  332. $seconds3 = $seconds2 - ($hours * 3600);
  333. $minutes = floor($seconds3/60);
  334. $seconds4 = $seconds3 - ($minutes * 60);
  335. return $days . " d " . $hours . " h";// . " " . $minutes . " min " . $seconds4 . " s"
  336. }
  337. }
  338. }
  339. if (! function_exists('IPv6ToIPv4')) {
  340. function IPv6ToIPv4($ip) {
  341. // source: https://stackoverflow.com/questions/12435582/php-serverremote-addr-shows-ipv6
  342. /*
  343. Fonctionne uniquement pour les IPv4 encapsulées dans IPv6 :
  344. ::ffff:192.000.002.123
  345. ::ffff:192.0.2.123
  346. 0000:0000:0000:0000:0000:ffff:c000:027b
  347. ::ffff:c000:027b
  348. ::ffff:c000:27b
  349. 192.000.002.123
  350. 192.0.2.123
  351. */
  352. // Known prefix
  353. $v4mapped_prefix_hex = '00000000000000000000ffff';
  354. //$v4mapped_prefix_bin = pack("H*", $v4mapped_prefix_hex); // PHP < 5.4
  355. $v4mapped_prefix_bin = hex2bin($v4mapped_prefix_hex); // PHP >= 5.4
  356. // Parse
  357. $addr_bin = inet_pton($ip);
  358. if( $addr_bin === FALSE ) {
  359. // Unparsable? How did they connect?!?
  360. return null;
  361. }
  362. // Check prefix
  363. if( substr($addr_bin, 0, strlen($v4mapped_prefix_bin)) == $v4mapped_prefix_bin) {
  364. // Strip prefix
  365. $addr_bin = substr($addr_bin, strlen($v4mapped_prefix_bin));
  366. }
  367. // Convert back to printable address in canonical form
  368. $ip4 = inet_ntop($addr_bin);
  369. return $ip4;
  370. }
  371. }