%PDF- %PDF-
Direktori : /home/alliance/domains/sedl.alnetis.fr/public_html/inc/ |
Current File : /home/alliance/domains/sedl.alnetis.fr/public_html/inc/functions.php |
<?php //////////////////////////////////////////////////////////////////////// ////////////////////// BIBLIOTHÈQUE DES FONCTIONS ////////////////////// //////////////////////////////////////////////////////////////////////// // clean une chaine pour insertion dans mysql function inputText2Sql ($string) { $string = trim ($string); $string = html_entity_decode($string); if (!get_magic_quotes_gpc()) { $string = addslashes($string); } return $string; } function br2nl($str) { return preg_replace('#<br\s*/?>#i', "\n", $str); } // Renvoie total HT function getTotalTTC($nb,$tva) { $result = $nb+($nb/(($tva/100)+1)); return $result; } // Renvoie total HT function getTotalHT($nb,$tva) { $result = $nb/(($tva/100)+1); return $result; } // Renvoie calcul TVA function getTVA($nb,$tva) { $result = $nb-($nb/(($tva/100)+1)); return $result; } // ajoute des zero devant un nombre genre; addZero(59,8) -> 00000059 function addZero($nb,$nbtotal) { $nbLen = strlen($nb); for ($i=0; $i<($nbtotal-$nbLen); $i++) { $nb = '0'.$nb; } return $nb; } // calcul l'âge suivant la date de naissance function age($BirthDate) { list($year, $month, $day) = explode('-', $BirthDate); $tmonth = date('n'); $tday = date('j'); $tyear = date('Y'); $years = $tyear - $year; if ($tmonth <= $month) { if ($month == $tmonth) { if ($day > $tday) $years--; } else $years--; } return $years; } // transforme date au format fr (jj/mm/anan) en date format us (anan-mm-jj) function dateUs ($date){ $date=preg_replace("@([[:digit:]]{2})/([[:digit:]]{2})/([[:digit:]]{4})@","\\3-\\2-\\1",$date); return $date; } // transforme date au format us (anan-mm-jj) en date format fr (jj/mm/anan) en function dateFr ($date){ $date = preg_replace("@([[:digit:]]{4})-([[:digit:]]{2})-([[:digit:]]{2})@","\\3/\\2/\\1",$date); return $date; } // retourne uniquement l'année d'une date format us (anan-mm-jj) function dateAnnee ($date){ list($year, $month, $day) = explode('-', $date); return $year; } // transforme date au format us (anan-mm-jj) en date lettre format fr; 10 novembre 2005 function fullDateFr ($date){ $moisFr = array ( "01" => "Janvier", "02" => "Février", "03" => "Mars", "04" => "Avril", "05" => "Mai", "06" => "Juin", "07" => "Juillet", "08" => "Août", "09" => "Septembre", "10" => "Octobre", "11" => "Novembre", "12" => "Décembre" ); $mois = preg_replace("@([[:digit:]]{4})-([[:digit:]]{2})-([[:digit:]]{2})@","\\2",$date); $date = preg_replace("@([[:digit:]]{4})-([[:digit:]]{2})-([[:digit:]]{2})@","\\3 /\\2/ \\1",$date); $fullDate = str_replace('/'.$mois.'/', $moisFr[$mois], $date); return $fullDate; } function dateLang($date,$lang){ //if($lang==1){ return dateFr($date); // } // else{ // return dateUs($date); // } } // clean nom de fichier pour linux function cleanFileString ($string){ $string = stripslashes($string); $string = preg_replace("@%20@", "-", "$string"); $a = "()!$'?: ,&+-/^ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ"; $b = "______________SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy"; $string = strtr($string, $a, $b); $string = strtolower($string); return $string; } // clean nom de fichier pour linux function cleanUrl($string){ $string = stripslashes($string); $string = preg_replace("@%20@", "-", "$string"); $a = "()!$'?: ,&+-/^–><»«."; $b = "--------------------"; $string = strtr($string, $a, $b); //$query = str_replace("\\\"", "\\'\\'", $query); $remplace = array('à'=>'a', 'á'=>'a', 'Á'=>'a', 'â'=>'a', 'Â'=>'a', 'À'=>'a', 'ã'=>'a', 'Ã'=>'a', 'ä'=>'a', 'Ä'=>'a', 'å'=>'a', 'Å'=>'a', 'ò'=>'o', 'Ò'=>'o', 'ó'=>'o', 'Ó'=>'o', 'ô'=>'o', 'Ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'Ö'=>'o', 'è'=>'e', 'È'=>'e', 'é'=>'e', 'ê'=>'e', 'É'=>'e', 'Ê'=>'e', 'ë'=>'e', 'Ë'=>'e', 'ì'=>'i', 'Ì'=>'i', 'í'=>'i', 'Í'=>'i', 'î'=>'i', 'Î'=>'i', 'ï'=>'i', 'Ï'=>'i', 'ù'=>'u', 'Ù'=>'u', 'ú'=>'u', 'Ú'=>'u', 'û'=>'u', 'Û'=>'u', '"'=>'-', 'ü'=>'u', 'Ü'=>'u', 'Š'=>'s', 'š'=>'s', 'ÿ'=>'y', 'Ÿ'=>'y', 'ñ'=>'n', 'Ñ'=>'n', 'ç'=>'c', 'Ç'=>'c', 'ø'=>'0', 'Ø'=>'0' ); $string = strtr($string,$remplace); $string = strtolower($string); return $string; } // clean nom de rep function cleanDirString ($string){ $string = stripslashes(trim($string)); $a = "\\/:*?\"<>|"; $b = "_________"; $string = strtr($string, $a, $b); return $string; } // converti une chaine en maj y compris caractères accentués function ultimateUpper ($string){ $string = strtoupper($string); $a = "àáâãäåæçèéêëìíîóôöùúûü"; $b = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÓÔÖÙÚÛÜ"; $string = strtr($string, $a, $b); return $string; } // converti une chaine en minuscule avec première lettre en maj y compris caractères accentués function ultimateUcFirstLower ($string){ $string = strtolower($string); $string = ucfirst($string); $a = "àáâãäåæçèéêëìíîóôöùúûü"; $b = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÓÔÖÙÚÛÜ"; if (preg_match("@(^[[:lower:]]{1})@",$string)) { $first = substr($string,0,1); $first = strtr($first, $a, $b); } $string = preg_replace("@(^[[:lower:]]{1})@","$first",$string); return $string; } // converti une chaine avec première lettre en maj y compris caractères accentués function ultimateUcFirst ($string){ $string = ucfirst($string); $a = "àáâãäåæçèéêëìíîóôöùúûü"; $b = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÓÔÖÙÚÛÜ"; if (preg_match("@(^[[:lower:]]{1})@",$string)) { $first = substr($string,0,1); $first = strtr($first, $a, $b); } $string = preg_replace("@(^[[:lower:]]{1})@",$first,$string); return $string; } // converti une chaine pour javascript function cleanJsString ($string) { $string = preg_replace("@\r@","<br>",$string); $string = preg_replace("@\n@","",$string); $string = htmlentities($string, ENT_COMPAT); $string = preg_replace("@([^\])@'","\\1\'",$string); return $string; } // converti une pour copier dans le presse-papier en javascript function cleanJsString2clipboard ($string) { $string = preg_replace("@\r@",'\n',$string); $string = preg_replace("@\n@",'\n',$string); $string = preg_replace("@[^\]'@","\'",$string); $string = preg_replace('@"@','``',$string); return $string; } // calcule le poids d'un fichier d'après url function taille($fichier) { global $size_unit; $taille=filesize($fichier); if ($taille >= 1073741824) { $taille = round($taille / 1073741824 * 100) / 100; $taille = number_format($taille, 2, ',', '') . " Go"; } elseif ($taille >= 1048576) { $taille = round($taille / 1048576 * 100) / 100; $taille = number_format($taille, 2, ',', '') . " Mo"; } elseif ($taille >= 1024) { $taille = round($taille / 1024 * 100) / 100; $taille = number_format($taille, 2, ',', '') . " Ko"; } else { $taille = number_format($taille, 2, ',', '') . " o"; } if($taille==0) {$taille="-";} return $taille; } // retourne l'extension d'un fichier function GetExtensionName($File) { $Ext = strtolower(substr($File, strrpos($File, '.') + 1)); return $Ext; } // convertit un nbe de secondes en xx h xx min xx sec function Convert2Time($Time) { if($Time < 3600) { $heures = 0; if($Time < 60) { $minutes = 0; } else { $minutes = round($Time / 60); } $secondes = floor($Time % 60); } else{ $heures = round($Time / 3600); $secondes = round($Time % 3600); $minutes = floor($secondes / 60); } $secondes2 = round($secondes % 60); if ($heures > 0) $TimeFinal .= "$heures h"; if ($minutes > 0 || $heures > 0) $TimeFinal .= " $minutes min"; $TimeFinal .= "$secondes2 s"; return $TimeFinal; } // retourne un mois chiffre en mois lettre function MoisFrancais($moisNombre) { $mois = array ( "01" => "Janvier", "02" => "Février", "03" => "Mars", "04" => "Avril", "05" => "Mai", "06" => "Juin", "07" => "Juillet", "08" => "Août", "09" => "Septembre", "10" => "Octobre", "11" => "Novembre", "12" => "Décembre" ); return $mois[$moisNombre]; } // retourne xx h xx min xx sec entre 2 timestamp function TempsRestant($timestamp_debut,$timestamp_fin) { //calcul du nombre de jours $difference = $timestamp_fin - $timestamp_debut; $residu = $difference % 86400; $nb_jours = floor(($difference - $residu) / 86400); //calcul du nombre d'heures $difference = $residu; $residu = $difference % 3600; $nb_heures = floor(($difference - $residu) / 3600); //calcul du nombre de minutes $difference = $residu; $residu = $difference % 60; $nb_minutes = floor(($difference - $residu) / 60); //nombre de secondes $nb_secondes = $residu; if ($nb_jours > 0) { $String_tps_restant .= '<b>'.$nb_jours; if ($nb_jours > 1 ) $String_tps_restant .= ' jours'; else $String_tps_restant .= ' jour'; } if ($nb_heures > 0) { $String_tps_restant .= '</b>, <b>'.$nb_heures; if ($nb_heures > 1 ) $String_tps_restant .= ' heures'; else $String_tps_restant .= ' heure'; } if ($nb_minutes > 0) { $String_tps_restant .= '</b>, <b>'.$nb_minutes; if ($nb_minutes > 1 ) $String_tps_restant .= ' minutes'; else $String_tps_restant .= ' minute'; } return $String_tps_restant; } // verifie syntaxe email function verifie_email($email){ $email = strtolower($email); if (strlen($email) < 6){ return "$email : Email trop court";} if (strlen($email) > 255) {return "$email : Email trop long";} if (!preg_match("/@/", $email)){ return "$email : arobase(@) manquant";} if (preg_match_all("/([^a-zA-Z0-9_\@\.\-])/i", $email, $trouve)) { return "$email : caractere(s) \"".implode(", ", $trouve[0])."\" interdit(s)"; } if (!preg_match("/^([.0-9a-z_-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,8})$/i", $email)) { return "$email : format d'email invalide."; } list($compte, $domaine)=explode("@", $email); return "ok"; } function verifie_num($champ,$lib){ if(!is_numeric($champ)) { return "$lib : format invalide."; } return "ok"; } // retourne le type/mime d'un fichier function getMime($filename) { $filename = strtolower($filename); $dot = substr (strrchr ($filename, "."), 1); $mimetypes = array( 'ez' => 'application/andrew-inset', 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'doc' => 'application/msword', 'bin' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'exe' => 'application/octet-stream', 'class' => 'application/octet-stream', 'so' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'oda' => 'application/oda', 'pdf' => 'application/pdf', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'mdb' => 'application/vnd.ms-access', 'pub' => 'application/vnd.ms-publisher', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'bcpio' => 'application/x-bcpio', 'vcd' => 'application/x-cdlink', 'pgn' => 'application/x-chess-pgn', 'cpio' => 'application/x-cpio', 'csh' => 'application/x-csh', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'spl' => 'application/x-futuresplash', 'gtar' => 'application/x-gtar', 'hdf' => 'application/x-hdf', 'js' => 'application/x-javascript', 'skp' => 'application/x-koan', 'skd' => 'application/x-koan', 'skt' => 'application/x-koan', 'skm' => 'application/x-koan', 'latex' => 'application/x-latex', 'nc' => 'application/x-netcdf', 'cdf' => 'application/x-netcdf', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'texinfo' => 'application/x-texinfo', 'texi' => 'application/x-texinfo', 't' => 'application/x-troff', 'tr' => 'application/x-troff', 'roff' => 'application/x-troff', 'man' => 'application/x-troff-man', 'me' => 'application/x-troff-me', 'ms' => 'application/x-troff-ms', 'ustar' => 'application/x-ustar', 'src' => 'application/x-wais-source', 'xhtml' => 'application/xhtml+xml', 'xht' => 'application/xhtml+xml', 'zip' => 'application/zip', 'rar' => 'application/rar', 'qxd' => 'application/quark-xpress', 'indd' => 'application/adobe-indesign', 'ai' => 'application/adobe-illustrator', 'psd' => 'application/adobe-photoshop', 'fla' => 'application/macromedia-flash', 'dwg' => 'application/x-autocad', 'au' => 'audio/basic', 'snd' => 'audio/basic', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'kar' => 'audio/midi', 'mpga' => 'audio/mpeg', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'aif' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'm3u' => 'audio/x-mpegurl', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'wav' => 'audio/x-wav', 'pdb' => 'chemical/x-pdb', 'xyz' => 'chemical/x-xyz', 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'ief' => 'image/ief', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'djvu' => 'image/vnd.djvu', 'djv' => 'image/vnd.djvu', 'wbmp' => 'image/vnd.wap.wbmp', 'ras' => 'image/x-cmu-raster', 'pnm' => 'image/x-portable-anymap', 'pbm' => 'image/x-portable-bitmap', 'pgm' => 'image/x-portable-graymap', 'ppm' => 'image/x-portable-pixmap', 'rgb' => 'image/x-rgb', 'xbm' => 'image/x-xbitmap', 'xpm' => 'image/x-xpixmap', 'xwd' => 'image/x-xwindowdump', 'igs' => 'model/iges', 'iges' => 'model/iges', 'msh' => 'model/mesh', 'mesh' => 'model/mesh', 'silo' => 'model/mesh', 'wrl' => 'model/vrml', 'vrml' => 'model/vrml', 'css' => 'text/css', 'html' => 'text/html', 'htm' => 'text/html', 'asc' => 'text/plain', 'txt' => 'text/plain', 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'sgml' => 'text/sgml', 'sgm' => 'text/sgml', 'tsv' => 'text/tab-separated-values', 'wml' => 'text/vnd.wap.wml', 'wmls' => 'text/vnd.wap.wmlscript', 'etx' => 'text/x-setext', 'xsl' => 'text/xml', 'xml' => 'text/xml', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'mxu' => 'video/vnd.mpegurl', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie', 'ice' => 'x-conference/x-cooltalk', ); if ($mimetypes[$dot] == "") $mimetypes[$dot] = 'inconnu'; return $mimetypes[$dot]; } // permet d'héviter l'écrasement d'un fichier existant -> rajoute _0.ext, _1.ext si le ficher existe deja function addFileName($Path,$File) { $i=0; $File1 = $File; while(file_exists($Path.'/'.$File)) { $File = $File1; $File = substr($File,0,strpos($File,"."))."_$i".strstr($File,"."); $i++; } return $File; } // Efface un dossier et tout son contenu function deleteDir($dir) { if (substr($dir, strlen($dir)-1, 1) != '/') $dir .= '/'; if ($handle = opendir($dir)) { while ($obj = readdir($handle)) { if ($obj != '.' && $obj != '..') { if (is_dir($dir.$obj)){ if (!deleteDir($dir.$obj)) return false; } elseif (is_file($dir.$obj)) { if (!unlink($dir.$obj)) return false; } } } closedir($handle); if (!@rmdir($dir)) return false; return true; } return false; } function verif_co() { if(!$_SESSION['logged'] || !isset($_SESSION['logged']) || empty($_SESSION['logged'])) { header('Location:connexion.php'); exit(0); } } function verif_co_admin() { if(!$_SESSION['logged'] || !isset($_SESSION['logged']) || empty($_SESSION['logged'])) { header('Location:connexion.php'); exit(0); } else { if($_SESSION['type'] != 2) { header('Location:404.html'); exit(0); } } } function verif_co_sec($connection,$section,$nextpage = false) { if(estco()) { if($_SESSION['type']==3){ $query = "SELECT pays FROM `section` WHERE id = ".$section; $result = mysqli_query($connection,$query) or die("Erreur SQL : <br />".$query."<br />Err no.".mysqli_errno()."<br />".mysqli_error()); $thesection = mysqli_fetch_array($result); if($thesection['pays']!=$_SESSION['id_country']){ header('Location:404.html'); exit(0); } } elseif(!estadmin()) { $query = "SELECT * FROM `user` WHERE id = '".$_SESSION['id']."'"; $result = mysqli_query($connection,$query) or die("Erreur SQL : <br />".$query."<br />Err no.".mysqli_errno()."<br />".mysqli_error()); $data = mysqli_fetch_array($result); if($data['section'] != $section) { header('Location:404.html'); exit(0); } } } else { if($nextpage) { header('Location:connexion.php?next='.$nextpage); exit(0); } else { header('Location:connexion.php'); exit(0); } } } function estco() { if (isset($_SESSION['logged']) && $_SESSION['logged']) return true; else return false; } function estadmin() { if ($_SESSION['logged'] && $_SESSION['type'] == 2) return true; else return false; } function estcoordinateur() { if ($_SESSION['logged'] && $_SESSION['type'] == 3) return true; else return false; } function verif_lang($lang){ if(estadmin() || $_SESSION['type']==3){ return true; } else{ if($lang==$_SESSION['lang']){ return true; } else{ return false; } } } function get_autre_lang(){ if($_SESSION['lang']==1){ return 2; } else{ return 1; } } function verif_get($get) { if(!isset($get) || !$get || !is_numeric($get)) { header('Location:404.html'); exit(0); } } function delog() { session_destroy(); session_start(); $_SESSION['logged'] = false; } function verif_disp_email($adresse) { $query = "SELECT COUNT(*) FROM `user` WHERE email = '".$adresse."'"; $result = mysql_query($query) or die("Erreur SQL : <br />".$query."<br />Err no.".mysql_errno()."<br />".mysql_error()); $data = mysql_fetch_array($result); return $data[0]; } function get_extension($nom) { $nom = explode(".", $nom); $nb = count($nom); return strtolower($nom[$nb-1]); } function substr2($text,$maxchar,$end='...') { if(strlen($text)>$maxchar){ return substr($text, 0, $maxchar).$end; } else return $text; } function substrwords($text,$maxchar,$end='...'){ if(strlen($text)>$maxchar){ $words=explode(" ",$text); $output = ''; $i=0; while(1){ $length = (strlen($output)+strlen($words[$i])); if($length>$maxchar){ break; }else{ $output = $output." ".$words[$i]; ++$i; }; }; }else{ return $output = $text; } return $output.$end; } function file_move($bloc="",$file,$temp_file){ $newname = cleanFileString($file); if($bloc==""){ while(file_exists("uploads/".$newname)) { list($nom, $ext) = explode('.', $newname); $nom = $nom.rand(0,999); $newname = $nom.".".$ext; } if(move_uploaded_file($temp_file, "uploads/".$newname)) { return $newname; } } else{ while(file_exists("uploads/bloc".$bloc.'/'.$newname)) { list($nom, $ext) = explode('.', $newname); $nom = $nom.rand(0,999); $newname = $nom.".".$ext; } if(move_uploaded_file($temp_file, "uploads/bloc".$bloc.'/'.$newname)) { return $newname; } } } function photo_move($photo) { $newname = cleanFileString($photo); while(file_exists("uploads/".$newname)) { list($nom, $ext) = explode('.', $newname); $nom = $nom.rand(0,999); $newname = $nom.".".$ext; } if (file_exists("temp/".$photo)) { rename("temp/".$photo,"uploads/".$newname); return $newname; } } function photo_supp($photo) { if(file_exists("uploads/".$photo)) { unlink("uploads/".$photo); } } require_once($base_path.'/phpThumb/phpThumb.config.php'); //require_once($_SERVER['DOCUMENT_ROOT'].'/srv01/sedlplateforme/phpThumb/phpThumb.config.php'); //Renvoie le lien de l'image taillée ou redimentionnée (src à la racine) function thumb($src, $width=false, $height=false, $zc=false) { $res = "photos/"; $res2="src=../uploads/".$src; if($width){ $res .= "w".$width."/"; $res2.="&w=".$width; } if($height){ $res .= "h".$height."/"; $res2.="&h=".$height; } if($zc){ $res .= "zc/"; $res2.="&zc=1"; } if(file_exists("uploads/".$src)){ $res .= $src; } else{ $res .= "no-img.jpg"; } return phpThumbURL($res2,'phpThumb/phpThumb.php'); //return $res."&hash=".phpThumbURL($res2,'phpThumb/phpThumb.php'); //src=../uploads/$3&w=$1&h=$2&zc=1 // echo '<img src="'.phpThumbURL('src=/images/pic.jpg&w=50').'">'; } //photos de l'autre site function thumb2($src, $width=false, $height=false, $zc=false) { $res = "photos/"; if($width) $res .= "w".$width."/"; if($height) $res .= "h".$height."/"; if($zc) $res .= "zc/"; //if(file_exists("uploads/".$src)) $res .= $src; //else //$res .= "no-img.jpg"; return $res; } function get_actu($filename, $actu, $url_site, $lang) { if (is_file($filename)) { ob_start(); include $filename; $contents = ob_get_contents(); ob_end_clean(); return $contents; } return false; } function get_section($filename, $sec, $url_site, $lang) { if (is_file($filename)) { $lg['is_a']['fr'] = "est une"; $lg['profil_1']['fr'] = 'Collectivité partenaire'; $lg['profil_2']['fr'] = 'Ville 12 étoiles'; $lg['profil_3']['fr'] = 'Association partenaire'; $lg['is_a']['en'] = "is a"; $lg['profil_1']['en'] = 'Community partner'; $lg['profil_2']['en'] = '12-Star City'; $lg['profil_3']['en'] = 'Partner association'; if($lang=="fr"){ $id_lang=1; } else{ $id_lang=2; } ob_start(); include $filename; $contents = ob_get_contents(); ob_end_clean(); return $contents; } return false; } function get_bloc($filename, $bloc, $url_site, $lang) { if (is_file($filename)) { ob_start(); include $filename; $contents = ob_get_contents(); ob_end_clean(); return $contents; } return false; } function get_temp($filename, $url_site, $lang = "fr") { if (is_file($filename)) { ob_start(); include $filename; $contents = ob_get_contents(); ob_end_clean(); return $contents; } return false; } // $texte : le texte formaté (avec des balises html) // $nbreCar : le nombre de caractères texte à afficher (sans compter les balises html) // $nbreCar (minimum) : pour ne pas couper un mot, le compte s'arrêtera a l espace suivant // -------------------------------- function old_texte_resume($texte, $nbreCar, $liensuite=false, $lientxt=false) { // longueur du texte brut sans html $LongueurTexteBrutSansHtml = strlen(strip_tags($texte)); $MasqueHtmlSplit = '#</?([a-zA-Z1-6]+)(?: +[a-zA-Z]+="[^"]*")*( ?/)?>#'; $MasqueHtmlMatch = '#<(?:/([a-zA-Z1-6]+)|([a-zA-Z1-6]+)(?: +[a-zA-Z]+="[^"]*")*( ?/)?)>#'; $texte .= ' '; $BoutsTexte = preg_split($MasqueHtmlSplit, $texte, -1, PREG_SPLIT_OFFSET_CAPTURE | PREG_SPLIT_NO_EMPTY); $NombreBouts = count($BoutsTexte); echo count( $BoutsTexte); if( $NombreBouts == 1 ) { $longueur = strlen($texte); // pour ne pas couper un mot, on va à l espace suivant return $texte; } $longueur = 0; $indexDernierBout = $NombreBouts - 1; $position = $BoutsTexte[$indexDernierBout][1] + strlen($BoutsTexte[$indexDernierBout][0]) - 1; $indexBout = $indexDernierBout; $rechercheEspace = true; foreach( $BoutsTexte as $index => $bout ) { $longueur += strlen($bout[0]); // Si la longueur désirée de l'extrait à obtenir est atteinte if( $longueur >= $nbreCar ) { // On calcule la position de césure du texte (position de chaîne + sa longueur -1 ) $position_fin_bout = $bout[1] + strlen($bout[0]) - 1; // calcul de la position de césure $position = $position_fin_bout - ($longueur - $nbreCar); // On regarde si un espace est présent après la position dans le bout de texte if( ($positionEspace = strpos($bout[0], ' ', $position - $bout[1])) !== false ) { // Un espace est détecté dans le bout de texte APRÈS la position $position = $bout[1] + $positionEspace; $rechercheEspace = false; } // Si on ne se trouve pas sur le dernier élément if( $index != $indexDernierBout ) $indexBout = $index + 1; break; } } // Donc il n'y avait pas d'espace dans le bout de texte où la position de césure sert de référence if( $rechercheEspace === true ) { // Recherche d'un espace dans les bouts de texte suivants for( $i=$indexBout; $i<=$indexDernierBout; $i++ ) { $position = $BoutsTexte[$i][1]; if( ($positionEspace = strpos($BoutsTexte[$i][0], ' ')) !== false ) { $position += $positionEspace; break; } } } // On effectue la césure sur le texte suivant la position calculée $texte = substr($texte, 0, $position); // Récupération de toutes les balises du texte et de leur position (PREG_OFFSET_CAPTURE) preg_match_all($MasqueHtmlMatch, $texte, $retour, PREG_OFFSET_CAPTURE); $BoutsTag = array(); // ---------------------------------- foreach( $retour[0] as $index => $tag ) { // Si on se trouve sur une balise unique, on passe au tour suivant if( isset($retour[3][$index][0]) ) { continue; } // Si le caractère slash n'est pas détecté en seconde position dans la balise entière, on est sur une balise ouvrante if( $retour[0][$index][0][1] != '/' ) { // On empile l'élément en début de l'array array_unshift($BoutsTag, $retour[2][$index][0]); } // Donc balise fermante else { // suppression du premier élément de l'array array_shift($BoutsTag); } } if( !empty($BoutsTag) ) { foreach( $BoutsTag as $tag ) { $texte .= '</' . $tag . '>'; } } // ---------------------------------- // si le texte brut est plus long que $nbreCar : on ajoute [...] a la fin if ($LongueurTexteBrutSansHtml > $nbreCar) { $texte .= ' [......]'; if(!$liensuite) $next = ' ...'; else $next = ' ... <a href="'.$liensuite.'">'.$lientxt.'</a>'; // si on a une balise fermante (/p ou /ul ou /div) a la fin : $texte = str_replace('</p> [......]', $next.' </p>', $texte); $texte = str_replace('</ul> [......]', $next.' </ul>', $texte); $texte = str_replace('</div> [......]', $next.' </div>', $texte); } // ---------------------------------- // On renvoie le résumé du texte correctement formaté. return nl2br($texte); } function htmldecode($source) { return html_entity_decode($source, ENT_COMPAT, "UTF-8"); } // retourne la liste des pays au format <option>Pays</option> function getCountry($id_lang){ $rqt_country="SELECT id_country,name FROM country_lang WHERE id_lang=".$id_lang." ORDER BY name ASC"; echo $rqt_country; $result=mysql_query($rqt_country); $html=""; while($pays=mysql_fetch_assoc($result)){ $html.='<option value="'.$pays['id_country'].'">'.utf8_encode($pays['name']).'</option>'; } return $html; } function texte_resume($texte, $nbreCar, $liensuite = false, $lientxt = 'Lire la suite') { // Si la longueur du texte est inférieure ou égale au nombre de caractères demandés, on retourne le texte complet if (strlen($texte) <= $nbreCar) { return $texte; } // Charger le texte dans DOMDocument $dom = new DOMDocument(); @$dom->loadHTML('<?xml encoding="UTF-8">' . $texte, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $content = ''; // Parcourir les nœuds pour accumuler le texte $iterator = new RecursiveIteratorIterator( new RecursiveDOMIterator($dom->documentElement), RecursiveIteratorIterator::SELF_FIRST ); $length = 0; foreach ($iterator as $node) { if ($node instanceof DOMText) { $text = $node->wholeText; if ($length + strlen($text) > $nbreCar) { // Si le texte total dépasse la limite, on coupe au dernier espace $cutPosition = strrpos(substr($text, 0, $nbreCar - $length), ' '); $content .= substr($text, 0, $cutPosition); break; } else { $content .= $text; $length += strlen($text); } } else { // Ajout des balises HTML non textuelles $tag = $dom->saveHTML($node); if ($node->nodeType !== XML_TEXT_NODE) { $content .= $tag; } } } // Fermer les balises ouvertes while ($dom->firstChild) { $dom->removeChild($dom->firstChild); } $dom->loadHTML('<?xml encoding="UTF-8">' . $content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $content = $dom->saveHTML(); // Ajouter le lien de continuation si nécessaire if ($liensuite) { $content .= ' <a href="' . $liensuite . '">' . $lientxt . '</a>'; } return $content; } // Classe pour l'itération recursive des nœuds DOM class RecursiveDOMIterator implements RecursiveIterator { private $position; private $nodeList; public function __construct(DOMNode $domNode) { $this->position = 0; $this->nodeList = $domNode->childNodes; } public function getChildren() { return new self($this->nodeList->item($this->position)); } public function hasChildren() { return $this->nodeList->item($this->position)->hasChildNodes(); } public function current() { return $this->nodeList->item($this->position); } public function next() { $this->position++; } public function key() { return $this->position; } public function valid() { return $this->position < $this->nodeList->length; } public function rewind() { $this->position = 0; } } function createRandomPassword() { $chars = "abcdefghijkmnopqrstuvwxyz023456789"; srand((double)microtime()*1000000); $i = 0; $pass = '' ; while ($i <= 7) { $num = rand() % 33; $tmp = substr($chars, $num, 1); $pass = $pass . $tmp; $i++; } return $pass; } ?>