olasoft/Common.php line 233

  1. <?php
  2. namespace OlaSoft;
  3. use Symfony\Component\HttpFoundation\RedirectResponse;
  4. use Symfony\Component\Config\Definition\Exception\Exception;
  5. use Symfony\Component\Intl\Countries;
  6. use Symfony\Component\Yaml\Yaml;
  7. class Common{
  8.     
  9.     public static function CheckDealineFilter(\Datetime $date,$differenceFormat '%R%a'){
  10.         $current date_create(date("Y-m-d H:i:s"));
  11.         $diff date_diff($current,$date)->format($differenceFormat);
  12.         if($diff 0)
  13.             return $diff;
  14.         else
  15.             return date_diff($current,$date)->format('%R%a,%h Heure(s)');
  16.     }
  17.     public static function export($htmlString,$name){
  18.         $reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
  19.         $spreadsheet $reader->loadFromString($htmlString);
  20.         $styleArray = [
  21.             'borders' => [
  22.                 'allBorders' => [
  23.                     'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
  24.                     'color' => ['argb' => '000000'],
  25.                 ],
  26.             ],
  27.         ];
  28.         $spreadsheet->getDefaultStyle()->applyFromArray($styleArray);
  29.         // $spreadsheet->getActiveSheet()->getColumnDimension('E')->setVisible(false);
  30.         $spreadsheet->getActiveSheet()->getRowDimension('1')->setVisible(false);
  31.         $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
  32.         $spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20);
  33.         $writer \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet'Xlsx');
  34.         $dir 'upload/files/exports/'.$name.'.xlsx';
  35.         $writer->save($dir);
  36.         header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  37.         header('Content-Disposition: attachment; '. ($name 'filename="'.self::slug($name).'.xlsx"' ''));
  38.         readfile($dir);
  39.         unlink($dir);
  40.     }
  41.     public static function isDecree($decree){
  42.         $t explode("-",$decree);
  43.         return count($t) == && is_numeric($t[0]) && (strlen($t[0]) == || strlen($t[0]) == 4) && is_numeric($t[1]);
  44.     }
  45.     public static function downloadPDF($file,$name null){
  46.         header('Content-type: application/pdf');
  47.         header('Content-Disposition: attachment; '. ($name 'filename="'.self::slug($name).'.pdf"' ''));
  48.         readfile($file);
  49.     }
  50.     public static function trackChange($em$object$user$action$info null){
  51.         $userActivity = new \App\Entity\UsersActivities;
  52.         $userActivity->setAction($action);
  53.         $userActivity->setObject(get_class($object));
  54.         $userActivity->setObjectID($object->getId());
  55.         $userActivity->setUser($user);
  56.         $userActivity->setDate(new \Datetime());
  57.         $userActivity->setInfo($info);
  58.         $em->persist($userActivity);
  59.         $em->flush();
  60.     }
  61.     public static function generatePassword($n 10){
  62.         $r "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  63.         $r str_shuffle($r);
  64.         $r uniqid($r,true);
  65.         $r substr($r,0,$n);
  66.         return $r;
  67.     }
  68.     public static function generateToken($n 30){
  69.         return bin2hex(random_bytes($n));;
  70.     }
  71.     public static function generateCode($n 5){
  72.         $r "0123456789";
  73.         $r str_shuffle($r);
  74.         $r uniqid($r,true);
  75.         $r substr($r,0,$n);
  76.         return $r;
  77.     }
  78.     public static function generateName(){
  79.         $generateName microtime();
  80.         $generateNameTable preg_split('/[\s,\.]/',$generateName);
  81.         $generateName $generateNameTable[0].$generateNameTable[1].$generateNameTable[2];
  82.         return $generateName;
  83.     }
  84.     public static function transliterateString($txt) {
  85.         $transliterationTable = array('œ' => 'oe''á' => 'a''Á' => 'A''à' => 'a''À' => 'A''ă' => 'a''Ă' => 'A''â' => 'a''Â' => 'A''å' => 'a''Å' => 'A''ã' => 'a''Ã' => 'A''ą' => 'a''Ą' => 'A''ā' => 'a''Ā' => 'A''ä' => 'ae''Ä' => 'AE''æ' => 'ae''Æ' => 'AE''ḃ' => 'b''Ḃ' => 'B''ć' => 'c''Ć' => 'C''ĉ' => 'c''Ĉ' => 'C''č' => 'c''Č' => 'C''ċ' => 'c''Ċ' => 'C''ç' => 'c''Ç' => 'C''ď' => 'd''Ď' => 'D''ḋ' => 'd''Ḋ' => 'D''đ' => 'd''Đ' => 'D''ð' => 'dh''Ð' => 'Dh''é' => 'e''É' => 'E''è' => 'e''È' => 'E''ĕ' => 'e''Ĕ' => 'E''ê' => 'e''Ê' => 'E''ě' => 'e''Ě' => 'E''ë' => 'e''Ë' => 'E''ė' => 'e''Ė' => 'E''ę' => 'e''Ę' => 'E''ē' => 'e''Ē' => 'E''ḟ' => 'f''Ḟ' => 'F''ƒ' => 'f''Ƒ' => 'F''ğ' => 'g''Ğ' => 'G''ĝ' => 'g''Ĝ' => 'G''ġ' => 'g''Ġ' => 'G''ģ' => 'g''Ģ' => 'G''ĥ' => 'h''Ĥ' => 'H''ħ' => 'h''Ħ' => 'H''í' => 'i''Í' => 'I''ì' => 'i''Ì' => 'I''î' => 'i''Î' => 'I''ï' => 'i''Ï' => 'I''ĩ' => 'i''Ĩ' => 'I''į' => 'i''Į' => 'I''ī' => 'i''Ī' => 'I''ĵ' => 'j''Ĵ' => 'J''ķ' => 'k''Ķ' => 'K''ĺ' => 'l''Ĺ' => 'L''ľ' => 'l''Ľ' => 'L''ļ' => 'l''Ļ' => 'L''ł' => 'l''Ł' => 'L''ṁ' => 'm''Ṁ' => 'M''ń' => 'n''Ń' => 'N''ň' => 'n''Ň' => 'N''ñ' => 'n''Ñ' => 'N''ņ' => 'n''Ņ' => 'N''ó' => 'o''Ó' => 'O''ò' => 'o''Ò' => 'O''ô' => 'o''Ô' => 'O''ő' => 'o''Ő' => 'O''õ' => 'o''Õ' => 'O''ø' => 'oe''Ø' => 'OE''ō' => 'o''Ō' => 'O''ơ' => 'o''Ơ' => 'O''ö' => 'oe''Ö' => 'OE''ṗ' => 'p''Ṗ' => 'P''ŕ' => 'r''Ŕ' => 'R''ř' => 'r''Ř' => 'R''ŗ' => 'r''Ŗ' => 'R''ś' => 's''Ś' => 'S''ŝ' => 's''Ŝ' => 'S''š' => 's''Š' => 'S''ṡ' => 's''Ṡ' => 'S''ş' => 's''Ş' => 'S''ș' => 's''Ș' => 'S''ß' => 'SS''ť' => 't''Ť' => 'T''ṫ' => 't''Ṫ' => 'T''ţ' => 't''Ţ' => 'T''ț' => 't''Ț' => 'T''ŧ' => 't''Ŧ' => 'T''ú' => 'u''Ú' => 'U''ù' => 'u''Ù' => 'U''ŭ' => 'u''Ŭ' => 'U''û' => 'u''Û' => 'U''ů' => 'u''Ů' => 'U''ű' => 'u''Ű' => 'U''ũ' => 'u''Ũ' => 'U''ų' => 'u''Ų' => 'U''ū' => 'u''Ū' => 'U''ư' => 'u''Ư' => 'U''ü' => 'ue''Ü' => 'UE''ẃ' => 'w''Ẃ' => 'W''ẁ' => 'w''Ẁ' => 'W''ŵ' => 'w''Ŵ' => 'W''ẅ' => 'w''Ẅ' => 'W''ý' => 'y''Ý' => 'Y''ỳ' => 'y''Ỳ' => 'Y''ŷ' => 'y''Ŷ' => 'Y''ÿ' => 'y''Ÿ' => 'Y''ź' => 'z''Ź' => 'Z''ž' => 'z''Ž' => 'Z''ż' => 'z''Ż' => 'Z''þ' => 'th''Þ' => 'Th''µ' => 'u''а' => 'a''А' => 'a''б' => 'b''Б' => 'b''в' => 'v''В' => 'v''г' => 'g''Г' => 'g''д' => 'd''Д' => 'd''е' => 'e''Е' => 'E''ё' => 'e''Ё' => 'E''ж' => 'zh''Ж' => 'zh''з' => 'z''З' => 'z''и' => 'i''И' => 'i''й' => 'j''Й' => 'j''к' => 'k''К' => 'k''л' => 'l''Л' => 'l''м' => 'm''М' => 'm''н' => 'n''Н' => 'n''о' => 'o''О' => 'o''п' => 'p''П' => 'p''р' => 'r''Р' => 'r''с' => 's''С' => 's''т' => 't''Т' => 't''у' => 'u''У' => 'u''ф' => 'f''Ф' => 'f''х' => 'h''Х' => 'h''ц' => 'c''Ц' => 'c''ч' => 'ch''Ч' => 'ch''ш' => 'sh''Ш' => 'sh''щ' => 'sch''Щ' => 'sch''ъ' => '''Ъ' => '''ы' => 'y''Ы' => 'y''ь' => '''Ь' => '''э' => 'e''Э' => 'e''ю' => 'ju''Ю' => 'ju''я' => 'ja''Я' => 'ja');
  86.         return str_replace(array_keys($transliterationTable), array_values($transliterationTable), $txt);
  87.     }
  88.     public static function slug($text){
  89.         $t1 "/\,|;|\?|!|:|\(|\)|\[|\]|\{|\}|'|’| |«|»|°|\*|\+|=|\\|\//";
  90.         $t2 "/-+((.{1,3}|pour)-+((.{1,3}|pour)-+)*)/";
  91.         $slug preg_replace(["/\s+/",$t1,$t2,"/-+/","|/|"],"-",strtolower(Common::transliterateString($text)));
  92.         return $slug;
  93.     }
  94.     public static function isMobile(){
  95.         $isMobile $_SESSION['isMobile'] ?? null;
  96.         if($isMobile !== null && !isset($_GET['force']))
  97.             return $isMobile;
  98.         $useragent $_SERVER['HTTP_USER_AGENT'];
  99.         $_SESSION['isMobile'] = (preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)
  100.         ||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)));
  101.         return $_SESSION['isMobile'];
  102.     }
  103.     public static function isDesktop(){
  104.         return !self::isMobile();
  105.     }
  106.     public static function mobile($s){
  107.         return self::isMobile() ? $s "";
  108.     }
  109.     public  function desktop($s){
  110.         return self::isMobile() ? "" $s;
  111.     }
  112.     public static function getBrowser()
  113.     {
  114.         $u_agent $_SERVER['HTTP_USER_AGENT'];
  115.         $bname 'Unknown';
  116.         $platform 'Unknown';
  117.         $version"";
  118.         $ub "";
  119.         //First get the platform?
  120.         if (preg_match('/linux/i'$u_agent)) {
  121.             $platform 'linux';
  122.         }
  123.         elseif (preg_match('/macintosh|mac os x/i'$u_agent)) {
  124.             $platform 'mac';
  125.         }
  126.         elseif (preg_match('/windows|win32/i'$u_agent)) {
  127.             $platform 'windows';
  128.         }
  129.         elseif (preg_match('/android/i'$u_agent)) {
  130.             $platform 'android';
  131.         }
  132.         elseif (preg_match('/ios/i'$u_agent)) {
  133.             $platform 'ios';
  134.         }
  135.         // Next get the name of the useragent yes seperately and for good reason
  136.         if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
  137.         {
  138.             $bname 'Internet Explorer';
  139.             $ub "MSIE";
  140.         }
  141.         elseif(preg_match('/Firefox/i',$u_agent))
  142.         {
  143.             $bname 'Mozilla Firefox';
  144.             $ub "Firefox";
  145.         }
  146.         elseif(preg_match('/Chrome/i',$u_agent))
  147.         {
  148.             $bname 'Google Chrome';
  149.             $ub "Chrome";
  150.         }
  151.         elseif(preg_match('/Safari/i',$u_agent))
  152.         {
  153.             $bname 'Apple Safari';
  154.             $ub "Safari";
  155.         }
  156.         elseif(preg_match('/Opera/i',$u_agent))
  157.         {
  158.             $bname 'Opera';
  159.             $ub "Opera";
  160.         }
  161.         elseif(preg_match('/Netscape/i',$u_agent))
  162.         {
  163.             $bname 'Netscape';
  164.             $ub "Netscape";
  165.         }
  166.         // finally get the correct version number
  167.         $known = array('Version'$ub'other');
  168.         $pattern '#(?<browser>' join('|'$known) .
  169.         ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
  170.         if (!preg_match_all($pattern$u_agent$matches)) {
  171.             // we have no matching number just continue
  172.         }
  173.         // see how many we have
  174.         $i count($matches['browser']);
  175.         if ($i != 1) {
  176.             //we will have two since we are not using 'other' argument yet
  177.             //see if version is before or after the name
  178.             if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
  179.                 $version$matches['version'][0];
  180.             }
  181.             else {
  182.                 if(count$matches['version'])>1)
  183.                     $version$matches['version'][1];
  184.             }
  185.         }
  186.         else {
  187.             $version$matches['version'][0];
  188.         }
  189.         // check if we have a number
  190.         if ($version==null || $version=="") {$version="?";}
  191.         return array(
  192.             'userAgent' => $u_agent,
  193.             'name'      => $bname,
  194.             'version'   => $version,
  195.             'platform'  => $platform,
  196.             'pattern'    => $pattern
  197.         );
  198.     }
  199.     public static function FrDate(\DateTime $date$isLong false){
  200.         setlocale(LC_TIME"fr_FR.utf8");
  201.         return strftime($isLong "%d %B %Y" "%d %b %Y"$date->getTimestamp());
  202.     }
  203.     public static function FrDateTime(\DateTime $date$isLong false){
  204.         setlocale(LC_TIME"fr_FR.utf8");
  205.         return strftime($isLong "%d %B %Y à %H:%M" "%d %b %Y à %H:%M"$date->getTimestamp());
  206.     }
  207.     public static function strftime(\DateTime $date$format){
  208.         setlocale(LC_TIME"fr_FR.utf8");
  209.         return strftime($format$date->getTimestamp());
  210.     }
  211.     public static function FrMonth(\DateTime $date$isLong false){
  212.         setlocale(LC_TIME"fr_FR.utf8");
  213.         return strftime($isLong "%B" "%b"$date->getTimestamp());
  214.     }
  215.     public static function FrDay(\DateTime $date$isLong false){
  216.         setlocale(LC_TIME"fr_FR.utf8");
  217.         return strftime($isLong "%A" "%a"$date->getTimestamp());
  218.     }
  219.     public static function prettyDate(\DateTime $date$isLongDate false){
  220.         $now = new \DateTime;
  221.         $now->setTime(0,0,0);
  222.         $i = ($now $date ? -1) * $date->diff($now)->days;
  223.         return $i >= -7
  224.             $i >= -6
  225.             $i >= -2
  226.             $i >= -1
  227.             $i >= 0
  228.             $i >= 1
  229.             $i >= 2
  230.             $i >= 3
  231.             $i >= 5
  232.             self::FrDate($date,$isLongDate)
  233.             : 'Dans 3 jours'
  234.             'Après-demain'
  235.             'Demain'
  236.             'Aujourd\'hui'
  237.             'Hier'
  238.             'Avant-hier'
  239.             'Il y a '.-$i.' jours'
  240.             'Il y a une semaine'
  241.             :  self::FrDate($date,$isLongDate)
  242.         ;
  243.     }
  244.     public static function prettyDateTime(\DateTime $date$isLongDate false){
  245.         $now = new \DateTime;
  246.         return $date >= $now->modify('-1 day')
  247.             ? $date >= $now->modify('-1 day')
  248.             ? $date $now
  249.             'Aujourd\'hui à '.$date->format('H:i')
  250.             : 'Hier à '.$date->format('H:i')
  251.             : 'Avant-hier à '.$date->format('H:i')
  252.             : self::FrDateTime($date,$isLongDate)
  253.         ;
  254.     }
  255.     public static function resizeImage($file$width 1520$height 1520){
  256.         $file urldecode($file);
  257.         if(is_file($file)) {
  258.             $size = ['width'=>0,'height'=>0];
  259.             list($size['width'], $size['height']) = getimagesize(realpath($file));
  260.             if($size['width'] > 600 || $size['height'] > 600){
  261.                 $imagick = new \Imagick(realpath($file));
  262.                 $imagick->setImageCompressionQuality(75);
  263.                 $imagick->thumbnailImage($width$width1false);
  264.                 $imagick->writeimage(realpath($file));
  265.                 $size = [$imagick->getImageWidth(), $imagick->getImageHeight()];
  266.                 $imagick->clear();
  267.                 $imagick->destroy();
  268.             }
  269.             return $size;
  270.         }
  271.         else
  272.             throw new Exception("Veuillez choisir une image valide et réessayer => ".$file);
  273.     }
  274.     public static function thumbnailImage($file$target$quality 60){
  275.         $file urldecode($file);
  276.         $extension pathinfo($filePATHINFO_EXTENSION);
  277.         $filename pathinfo($filePATHINFO_FILENAME);
  278.         if (is_file($file)) {
  279.             $imagick = new \Imagick(($file));
  280.             if($imagick->getImageWidth() > 600 || $imagick->getImageHeight() > 600){
  281.                 $imagick->setImageFormat(strtolower($extension));
  282.                 $imagick->setImageCompressionQuality($quality);
  283.                 $imagick->thumbnailImage(6006001false);
  284.             }
  285.             $imagick->writeimage(realpath($target).'/'.$filename.'.'.$extension);
  286.             $imagick->clear();
  287.             $imagick->destroy();
  288.             return true;
  289.         }
  290.         else
  291.             throw new Exception("Veuillez choisir une image valide et réessayer.");
  292.     }
  293.     public static function thumbnailImage2($file$target){
  294.         $extension strtolower(pathinfo($filePATHINFO_EXTENSION));
  295.         $filename strtolower(pathinfo($filePATHINFO_FILENAME));
  296.         $realSize getimagesize($file);
  297.         $image null;
  298.         if($extension == 'jpg' || $extension == 'jpeg'$image imagecreatefromjpeg($file);
  299.         else if($extension == 'png'$image imagecreatefrompng($file);
  300.         else if ($extension == 'gif'$image imagecreatefromgif($file);
  301.         else return false;
  302.         $target $target $target './upload/images/articles/thumbnails/';
  303.         $width 600;
  304.         $height = ($width $realSize[0]) * $realSize[1];
  305.         $top $left $coef 0;
  306.         $newImage imagecreatetruecolor($width,$height);
  307.         $coef min($realSize[0]/$width,$realSize[1]/$height);
  308.         $deltax $realSize[0]-($coef $width);
  309.         $deltay $realSize[1]-($coef $height);
  310.         imagecopyresampled($newImage,$image,0,0,$deltax/2,$deltay/2,$width,$height,$realSize[0]-$deltax,$realSize[1]-$deltay);
  311.         $fullpath $target.$filename.'.'.$extension;
  312.         if($extension == 'jpg' || $extension == 'jpeg'imagejpeg($newImage,$fullpath);
  313.         else if($extension == 'png'imagepng($newImage,$fullpath);
  314.         else if ($extension == 'gif'imagegif($newImage,$fullpath);
  315.         $imagevariable ob_get_contents();
  316.         imagedestroy($image);
  317.         imagedestroy($newImage);
  318.         return $fullpath;
  319.     }
  320.     public static function prettySize($size){
  321.         $bytes null;
  322.         if ($size >= 1073741824)
  323.             $bytes round($size 1073741824) . ' Go';
  324.         elseif ($size >= 1048576)
  325.             $bytes round($size 1048576) . ' Mo';
  326.         elseif ($size >= 1000)
  327.             $bytes round($size 1024) . ' Ko';
  328.         else
  329.             $bytes $size ' O';
  330.         return $bytes;
  331.     }
  332.     // Code from https://stackoverflow.com/a/6121972
  333.     public static function getYoutubeId($link){
  334.         preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=embed/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#"$link$id);
  335.         return $id[0];
  336.     }
  337.     public static function getYoutubeEmbed($id){
  338.         return 'https://youtube.com/embed/'.$id;
  339.     }
  340.     public static function getYoutubeThumbnail($link$quality 'l') {
  341.         $id self::getYoutubeId($link);
  342.         switch (strtolower(substr($quality01)))
  343.         {
  344.             case 'l'//low
  345.             return 'https://img.youtube.com/vi/'.$id.'/sddefault.jpg';
  346.             case 'h'//high
  347.             return 'https://img.youtube.com/vi/'.$id.'/hqdefault.jpg';
  348.             case 'm'//maximum
  349.             return 'https://img.youtube.com/vi/'.$id.'/maxresdefault.jpg';
  350.             default:
  351.             return 'https://img.youtube.com/vi/'.$id.'/mqdefault.jpg';
  352.         }
  353.     }
  354.     
  355.     public static function getVimeoThumbnail($link) {
  356.         $id explode("?h="$link)[0] ? explode("?h="$link)[0] : $link;
  357.         if($id){
  358.             
  359.             $id explode("https://player.vimeo.com/video/"$id)[1];
  360.         // die(var_dump($id));
  361.             $data file_get_contents("http://vimeo.com/api/v2/video/".$id.".json");
  362.             $data json_decode($data);
  363.             return $data[0]->thumbnail_medium;
  364.         }
  365.             return false;
  366.     }
  367.     public static function imagesize($file){
  368.         $size = ['width'=>0,'height'=>0];
  369.         list($size['width'], $size['height']) = getimagesize($file);
  370.         return $size ;
  371.     }
  372.     public static function filesize($file){
  373.         return file_exists($file) ? filesize($file) : false ;
  374.     }
  375.     public static function country($countryCode,$locale "fr"){
  376.         return Countries::getName($countryCode$locale);
  377.     }
  378.     public static function filterArray($list$property$s$subProperty null){
  379.         if (is_array($list)){
  380.             $m "get".ucfirst($property);
  381.             if($subProperty !== null){
  382.                 $subM "get".ucfirst($subProperty);
  383.                 return array_filter($list,function($o) use(&$property, &$s, &$m, &$subProperty, &$subM){
  384.                     $sub is_object($o) && property_exists($o$property) ? $o->$m() : null;
  385.                     return is_object($sub) && property_exists($sub$subProperty) ? $sub->$subM() == $s false;
  386.                 });
  387.             }
  388.             else
  389.                 return array_filter($list,function($o) use(&$property, &$s, &$m){
  390.                     if(is_object($o))
  391.                         return property_exists($o$property) ? $o->$m() == $s false;
  392.                     elseif(is_array($o))
  393.                         return array_key_exists($property,$o) ? $o[$property] == $s false;
  394.                 });
  395.         }
  396.         return [];
  397.     }
  398.     public static function imageColor($file$default="rgb(255, 255, 255)"){
  399.         $explode explode('.'$file);
  400.         $extension end($explode);
  401.         if($extension){
  402.             $img=null;
  403.             switch (strtolower($extension)){
  404.                 case 'png':
  405.                     $img imagecreatefrompng($file);
  406.                     break;
  407.                 case 'jpg':
  408.                 case 'jpeg':
  409.                     $img imagecreatefromjpeg($file);
  410.                     break;
  411.                 case 'gif':
  412.                     $img imagecreatefromgif($file);
  413.                     break;
  414.                 default:
  415.                     break;
  416.             }
  417.             if($img){
  418.                 $rgb imagecolorat($img11);
  419.                 $r = ($rgb >> 16) & 0xFF;
  420.                 $g = ($rgb >> 8) & 0xFF;
  421.                 $b $rgb 0xFF;
  422.                 return "rgb(".$r.", ".$g.", ".$b.")";
  423.             }
  424.         }
  425.         return $default;
  426.     }
  427.     public static function createElement(\DOMDocument $domObj$tag_name$value NULL$attributes NULL)
  428.     {
  429.         $element = ($value != NULL ) ? $domObj->createElement($tag_name$value) : $domObj->createElement($tag_name);
  430.         if( $attributes != NULL )
  431.             foreach ($attributes as $attr=>$val)
  432.                 $element->setAttribute($attr$val);
  433.         return $element;
  434.     }
  435.     public static function summary($htmlCode){
  436.         $resp= [];
  437.         $doc = new \DOMDocument('1.0''UTF-8');
  438.         libxml_use_internal_errors(true);
  439.         $doc->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'.$htmlCode,LIBXML_NOWARNING);//Chargement du contenu de l'article
  440.         libxml_clear_errors();
  441.             $summaryDom = new \DOMDocument('1.0''utf-8');
  442.             /** @var $node \DOMElement */
  443.             foreach ($doc->getElementsByTagName('body')->item(0)->childNodes as $node){
  444.                 if(isset($node->tagName) && preg_match('/(h1|h2|h3|h4)/'$node->tagName)){
  445.                     $idCommon::slug($node->nodeValue);
  446.                     $node->setAttribute("id"$id);
  447.                     $h Common::createElement($summaryDom"li"null, [
  448.                         "class" => "title-header title-".$node->tagName
  449.                     ]);
  450.                     $link Common::createElement($summaryDom"a"$node->nodeValue, ["href"=> "#$id""class"=>"os-scroll"]);
  451.                     $h->insertBefore($link);
  452.                     $summaryDom->appendChild($h);
  453.                 }
  454.             }
  455.             $summary$summaryDom->saveHTML();
  456.             $content$doc->saveHTML($doc->documentElement);
  457.             $resp=[
  458.                 "summary"=>$summary,
  459.                 "content"=>$content,
  460.             ];
  461.         return $resp;
  462.     }
  463.     public static function getParameter($prop){
  464.         $params Yaml::parseFile("../config/packages/olasoft.yaml")["parameters"];
  465.         return in_array($prop$params) ? "" $params[$prop];
  466.     }
  467.     // Code from https://stackoverflow.com/questions/13076480/
  468.     // Returns a file size limit in bytes based on the PHP upload_max_filesize
  469.     // and post_max_size
  470.     public static function getUploadMaxFileSize() {
  471.         static $max_size = -1;
  472.         if ($max_size 0) {
  473.             // Start with post_max_size.
  474.             $post_max_size self::parseSize(ini_get('post_max_size'));
  475.             if ($post_max_size 0) {
  476.                 $max_size $post_max_size;
  477.             }
  478.             // If upload_max_size is less, then reduce. Except if upload_max_size is
  479.             // zero, which indicates no limit.
  480.             $upload_max self::parseSize(ini_get('upload_max_filesize'));
  481.             if ($upload_max && $upload_max $max_size) {
  482.               $max_size $upload_max;
  483.             }
  484.         }
  485.         return $max_size;
  486.     }
  487.     public static function parseSize($size) {
  488.         $unit preg_replace('/[^bkmgtpezy]/i'''$size); // Remove the non-unit characters from the size.
  489.         $size preg_replace('/[^0-9\.]/'''$size); // Remove the non-numeric characters from the size.
  490.         if ($unit) {
  491.             // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
  492.             return round($size pow(1024stripos('bkmgtpezy'$unit[0])));
  493.         }
  494.         else {
  495.             return round($size);
  496.         }
  497.     }
  498.     public static function formatPrice($number$decimals 0$decPoint ','$thousandsSep ' ')
  499.     {
  500.         $price number_format($number$decimals$decPoint$thousandsSep);
  501.         $price $price;
  502.         return $price;
  503.     }
  504.     public static function getLocale(){
  505.         $session = new \Symfony\Component\HttpFoundation\Session\Session();
  506.         $locale $_GET['_locale'] ?? $session->get('_locale') ?? 'fr';
  507.         return $locale;
  508.     }
  509.     public static function localeIsEn(){
  510.         return self::getLocale() == 'en';
  511.     }
  512.     public static function localeIsFr(){
  513.         return self::getLocale() == 'fr';
  514.     }
  515.     public static function translate($item$property){
  516.         if(is_object($item)){
  517.             $lang self::localeIsFr() ? "" ucfirst(self::getLocale());
  518.             return $item->{"get".ucfirst($property).$lang}();
  519.         }
  520.         return self::translateText($item,$property);
  521.     }
  522.     public static function translateText($value$translation){
  523.         return self::localeIsFr() ? $value $translation;
  524.     }
  525. }