';
$hcard .= '
'.$societe.'
';
if($nom!="" || $prenom!="") {
$hcard .= "
";
$hcard.= "à l'attention de";
if($prenom!="") $hcard .= ''.$prenom.'';
if($nom!="") $hcard .= ''.$nom.'';
$hcard.= '';
}
}
else {
$hcard = '
';
}
// ADRESSE
$hcard .= '
';
$hcard .= '
'.nl2br($adresse).'
';
$hcard .= '
'.$cp.'';
$hcard .= '
'.$ville.'';
$hcard .= '
'.$pays.'';
$hcard .= '
';
$hcard.="
";
return $hcard;
}
function msleep($time) {
usleep($time * 1000);
}
// FICHIERS
function parseDir($url_dir, $ignore=false, $recursive=false) {
if($url_dir=="") return array();
$lastChar = substr($url_dir, -1);
if($lastChar == '\\' || $lastChar == '/') $url_dir = substr($url_dir, 0, -1);
$dir = opendir($url_dir);
$files= array();
while($element = readdir($dir)) {
if(!$ignore && $element != '.' && $element != '..') {
if($recursive) $files[strval($element)] = $element;
else $files[] = $element;
}
elseif ($ignore && $element != '.' && $element != '..' && $element != '.DS_Store' && $element != '.gitignore') {
if($recursive) {
$file_url = $url_dir."/".$element;
if(is_dir($file_url)) $files[strval($element)] = parseDir($file_url, $ignore, $recursive);
else $files[strval($element)] = $element;
}
else $files[] = $element;
}
}
closedir($dir);
if(!$recursive) sort($files);
return $files;
}
function copyRecusive($srcPath, $dirDest) {
if(!file_exists($srcPath) || !is_dir($srcPath)) return "Le dossier source est invalide ! (".$srcPath.')';
if(!file_exists($dirDest) || !is_dir($dirDest)) return "Le dossier de destination est invalide ! (".$srcPath.')';
mkdir($dirDest, 0755);
foreach ($iterator = new \RecursiveIteratorIterator (
new \RecursiveDirectoryIterator($srcPath, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST) as $item ) {
if ($item->isDir()) {
mkdir($dirDest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
else {
copy($item, $dirDest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
}
return true;
}
function truncateDir($dir_path) {
if(!file_exists($dir_path)) return "Dossier Introuvable ! (".$dir_path.')';
else if(!is_dir($dir_path)) return "Le path transmis pointe sur un fichier... (".$dir_path.')';
$dir = opendir($dir_path);
$files = readdir($dir);
while($files = readdir($dir)) {
if($files != "..") {
$filepath = $dir_path."/".$files;
if(is_dir($filepath)) rmRecursive($filepath);
else unlink( $dir_path."/".$files );
}
}
closedir($dir);
}
function rmRecursive($path) {
if(!file_exists($path)) return "Fichier Introuvable ! (".$path.')';
if(is_dir($path)) { // DOSSIER
$dir = scandir($path, SCANDIR_SORT_DESCENDING);
if(count($dir)>2) { // LE DOSSIER N'EST PAS VIDE (en tenant compte de '.' && '..')
foreach($dir as $file_in_dir){
if($file_in_dir == '.' or $file_in_dir == '..') break; // on sort de boucle : il n'y aura rien d'autre
$r = rmRecursive("$path/$file_in_dir");
if(!( is_bool($r) && $r)) return $r;
}
}
$r = rmdir($path);
if(!$r) return "Un problème est survenu à la supression d'un dossier ! (".$path.')';
}
else { // FICHIER
$r = unlink($path);
if(!$r) return "Un problème est survenu à la supression d'un fichier ! (".$path.')';
}
return true;
}
function rmLocalDir($path,$secondTry=false) {
if(!file_exists($path)) return "Fichier/Dossier Introuvable ! (".$path.')';
$outputs = array();
$result = 0;
$r = exec('rm -rf '.realpath($path), $outputs, $result);
msleep(200);
if(!file_exists($path)) return true;
else if(!secondTry) rmLocalDir($path,true);
else return "Un problème est survenu à la supression du dossier ! (".$path.')';
}
function copyLocalDir($srcPath, $destDir, $destName=false) {
if(!file_exists($srcPath)) return "Le fichier source n'éxiste pas ! (".$srcPath.')';
if(!file_exists($destDir)) return "Le dossier de destination est invalide ! (".$destDir.')';
if($destName==false) $destName = basename($srcPath);
$destPath = realpath($destDir)."/".$destName;
$cmd = 'cp -R '.realpath($srcPath)." ".$destPath;
$r = shell_exec($cmd);
if(file_exists($destPath)) return true;
else return "Un problème est survenu à la copie du dossier ! (".$cmd.')';
}
function syncLocalDir($srcPath, $destDir) {
if(!file_exists($srcPath)) return "Le dossier source est invalide ! (".$srcPath.')';
if(!file_exists($destDir)) return "Le dossier de destination est invalide ! (".$destDir.')';
$destPath = $destDir."/".basename($srcPath);
if(!file_exists($destPath)) return "Le dossier de synchronisation à destination n'éxistes pas ! (".$destPath.')';
$cmd = 'rsync -r -q --ignore-existing '.realpath($srcPath)." ".realpath($destDir);
$r = shell_exec($cmd);
if(file_exists($destPath)) return true;
else return "Un problème est survenu à la synchronisation du dossier ! (".$cmd.')';
}
function getFileType($path) {
if(!(file_exists($path) && is_file($path))) return "Fichier Introuvable ! (".$path.')';
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mt = finfo_file($finfo, $path);
$type = explode('/',$mt);
$type = $type[0];
$pinfos = pathinfo($path);
// PDF
if ($mt == 'application/pdf') {
$pdf = true;
$type = 'pdf';
}
else $pdf = false;
// VIDEO
$mvt = array('video/x-flv','video/mp4','application/x-mpegURL','video/MP2T','video/3gpp','video/quicktime','video/x-msvideo','video/x-ms-wmv');
if (in_array($mt,$mvt)) {
$video = true;
$type = 'video';
}
else $video = false;
// AUDIO
$mat = array('audio/basic','auido/L24','audio/mid','audio/mpeg','audio/mp4','audio/x-aiff','audio/x-mpegurl','audio/vnd.rn-realaudio','audio/ogg','audio/vorbis','audio/vnd.wav');
if (in_array($mt,$mat)) {
$audio = true;
$type = 'audio';
}
else $audio = false;
// DMG
$mdt = array('application/octet-stream', 'application/x-apple-diskimage', 'application/x-diskcopy', 'application/x-bzip2');
if(in_array($mt,$mdt) && $pinfos['extension']=="dmg") {
$type = "dmg";
}
// EXE
$met = array('application/octet-stream', 'application/x-msdownload', 'application/exe', 'application/x-exe', 'application/dos-exe', 'vms/exe', 'application/x-winexe', 'application/msdos-windows', 'application/x-msdos-program','application/x-dosexec');
if(in_array($mt,$met) && $pinfos['extension']=="exe") {
$type = "exe";
}
//echo($path." => ".$mt." - ".$type."
");
// BROWSER SUPPORT
$browser_support = ($type=='image' XOR $pdf XOR $audio XOR $video);
return array('type' => $type, 'browser_support' => $browser_support);
}
function forceDownloadFile($f,$file_name=false,$unlink=false) {
if(file_exists($f)) {
if(!$file_name || $file_name=="") $file_name = basename($f);
session_write_close();
set_time_limit(0);
ignore_user_abort(false);
ini_set('output_buffering', 0);
ini_set('zlib.output_compression', 0);
$date = gmdate(DATE_RFC1123);
header('Pragma: public');
header('Content-Description: File Transfer');
header('Set-Cookie: fileDownload=true; path=/');
header('Cache-Control: must-revalidate, pre-check=0, post-check=0, max-age=0');
header('Content-Tranfer-Encoding: none');
header('Content-Length: '.filesize($f));
header('Content-MD5: '.base64_encode(md5_file($f)));
header('Content-Type: application/octetstream;');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Date: '.$date);
header('Expires: '.gmdate(DATE_RFC1123, time()+1));
header('Last-Modified: '.gmdate(DATE_RFC1123, filemtime($f)));
ob_end_clean();
flush();
$chunk = 10 * 1024 * 1024; // bytes per chunk (10 MB)
$fh = fopen($f, "rb");
while (!feof($fh)) {
echo fread($fh, $chunk);
ob_flush(); // flush output
flush();
if (connection_status()!=0) {
@fclose($fh);
die();
}
}
if($unlink) unlink($f);
exit;
}
else return('ERREUR : Impossible de trouver le fichier à télécharger ! ("'.$f.'")');
return;
}
function downloadFile($f,$file_name=false,$unlink=false) {
if(file_exists($f)) {
if(!$file_name || $file_name=="") $file_name = basename($f);
session_write_close();
set_time_limit(0);
ignore_user_abort(false);
ini_set('output_buffering', 0);
ini_set('zlib.output_compression', 0);
$date = gmdate(DATE_RFC1123);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type= finfo_file($finfo, $f);
header('Pragma: public');
header('Cache-Control: must-revalidate, pre-check=0, post-check=0, max-age=0');
header('Content-Tranfer-Encoding: none');
header('Content-Length: '.filesize($f));
header('Content-MD5: '.base64_encode(md5_file($f)));
header('Content-Type: '.$type.'; name="'.$file_name.'"');
header('Content-Disposition: inline; filename="'.$file_name.'"');
header('Date: '.$date);
header('Expires: '.gmdate(DATE_RFC1123, time()+1));
header('Last-Modified: '.gmdate(DATE_RFC1123, filemtime($f)));
ob_end_clean();
flush();
$chunk = 10 * 1024 * 1024; // bytes per chunk (10 MB)
$fh = fopen($f, "rb");
while (!feof($fh)) {
echo fread($fh, $chunk);
ob_flush(); // flush output
flush();
if (connection_status()!=0) {
@fclose($fh);
die();
}
}
if($unlink) unlink($f);
exit;
}
else return('ERREUR : Impossible de trouver le fichier à télécharger ! ("'.$f.'")');
return;
}
function downloadFileAlt($f,$file_name=false,$force=false) {
if(!$file_name || $file_name=="") $file_name = basename($f);
if(is_readable($f)) {
$fd = fopen($f, "rb");
if ($fd) {
$date = gmdate(DATE_RFC1123);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type= finfo_file($finfo, $f);
header('Pragma: public');
header('Cache-Control: must-revalidate, pre-check=0, post-check=0, max-age=0');
header('Content-Length: '.filesize($f));
header('Content-MD5: '.base64_encode(md5_file($f)));
header('Content-Type: '.$type.'; name="'.$file_name.'"');
if($force) header("Content-Disposition: attachment; filename=\"".$file_name."\"");
else header('Content-Disposition: inline; filename="'.$file_name.'"');
while(!feof($fd)) {
$buffer = fread($fd, 1*(1024*1024));
echo $buffer;
ob_flush();
flush();
}
}
else echo "Error opening file";
fclose($fd);
}
exit();
}
function formatFileSize($s, $decimals = 2) {
$units = array("o", "ko", "Mo", "Go", "To", "Po");
$factor = floor((strlen($s) - 1) / 3);
return sprintf("%.{$decimals}f", intval($s) / pow(1024, $factor))." ".$units[$factor];
}
function addFilesInZipDir($srcDir, $zip, $zipDir) {
$files = parseDir($srcDir,1);
//afficheArray($files,1);
foreach($files as $f) {
if(is_dir($srcDir.'/'.$f)) {
$newDir = $zipDir.'/'.$f;
//echo("AJOUT DIR : ".$newDir.'
');
$zip->addEmptyDir($newDir);
$zip = addFilesInZipDir($srcDir.'/'.$f, $zip, $newDir);
}
else {
//echo("AJOUT FICHIERS : ".$zipDir.'/'.$f.'
');
$zip->addFile($srcDir.'/'.$f,$zipDir.'/'.$f);
}
}
return $zip;
}
function file_upload_max_size($format=true) {
static $max_size = -1;
if ($max_size < 0) {
// Start with post_max_size.
$max_size = parse_size(ini_get('post_max_size'));
// If upload_max_size is less, then reduce. Except if upload_max_size is
// zero, which indicates no limit.
$upload_max = parse_size(ini_get('upload_max_filesize'));
if ($upload_max > 0 && $upload_max < $max_size) $max_size = $upload_max;
}
return ($format) ? formatFileSize($max_size) : $max_size;
}
function parse_size($size) {
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
$size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
if ($unit) {
// Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
}
else return round($size);
}
function exec_command($command) {
exec($command,$output, $exit_code);
$result = array(
'command' => $command,
'output' => $output,
'exit_code' => $exit_code,
'error' => false
);
if($exit_code==0) return $result;
else if($exit_code==1) $result['error'] = "Une erreur général s'est produite durant l'execution de la commande";
else if($exit_code==2) $result['error'] = "Détournement de fonction shell";
else if($exit_code==126) $result['error'] = "La commande invoquée ne peut être exécutée. (Problème de permission ou de commande non-exécutable...)";
else if($exit_code==127) $result['error'] = "La commande invoquée est introuvalbe !";
else if($exit_code==128) $result['error'] = "L'argument de sortie est invalide ! (ce doit être un entier compirs entre 0 & 255)";
else if($exit_code==130) $result['error'] = "La commande à été interrompu manuellement";
else if($exit_code>128 && $exit_code<255) $result['error'] = "Erreur fatale (code = ".($exit_code-128).")";
return $result;
}
// REMOTE FILE
# setup a global file pointer
$remoteFileHandler = null;
function saveRemoteFile($url, $file_output_path, $post_datas = false, $progressCallbackFct="", $auth = false, $ssl_disable=false) {
global $remoteFileHandler;
set_time_limit(0);
# Open the file for writing...
if(file_exists($file_output_path)) return "ERROR : file output already exists !";
$remoteFileHandler = fopen($file_output_path, 'w+');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FILE, $remoteFileHandler);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"); //Make this valid if possible
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); # optional
curl_setopt($ch, CURLOPT_TIMEOUT, -1); # optional: -1 = unlimited, 3600 = 1 hour
curl_setopt($ch, CURLOPT_VERBOSE, false); # Set to true to see all the innards
// AUTH FORMAT : 'user:password'
if($auth){
curl_setopt($ch, CURLOPT_USERPWD, "$auth");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
}
// POST DATAS
if($post_datas){
$post_fields = http_build_query($post_datas);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
}
# Only if you need to bypass SSL certificate validation
if($ssl_disable) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
# Assign a callback function to the CURL Write-Function
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'saveRemoteFileHandler');
# Assign a callback function to the CURL Download Progression
if($progressCallbackFct!="" && function_exists($progressCallbackFct)) {
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $progressCallbackFct);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
}
else if($progressCallbackFct=="default") {
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'saveRemoteFileProgression');
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
}
# Execute the download - note we DO NOT put the result into a variable!
curl_exec($ch);
# ERROR ?
if(curl_errno($ch)) return curl_error($ch);
# HTTP CODE
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
# Close CURL
curl_close($ch);
# Close the file pointer
fclose($remoteFileHandler);
# Return HTTP Code
return (is_int($httpcode) && $httpcode<400);
}
function saveRemoteFileHandler($cp, $data) {
global $remoteFileHandler;
$len = fwrite($remoteFileHandler, $data);
return $len;
}
function saveRemoteFileProgression($resource,$download_size, $downloaded, $upload_size, $uploaded) {
if($download_size > 0) echo floor($downloaded / $download_size * 100)."%";
}
function getRemoteFileContent($url, $post_datas = false, $progressCallbackFct="", $auth = false, $ssl_disable=false) {
set_time_limit(0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FILE, $remoteFileHandler);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"); //Make this valid if possible
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); # optional
curl_setopt($ch, CURLOPT_TIMEOUT, -1); # optional: -1 = unlimited, 3600 = 1 hour
curl_setopt($ch, CURLOPT_VERBOSE, false); # Set to true to see all the innards
curl_setopt($ch, CURLOPT_FAILONERROR, true);
// AUTH FORMAT : 'user:password'
if($auth){
curl_setopt($ch, CURLOPT_USERPWD, "$auth");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
}
// POST DATAS
if($post_datas){
$post_fields = http_build_query($post_datas);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
}
# Only if you need to bypass SSL certificate validation
if($ssl_disable) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
# Assign a callback function to the CURL Download Progression
if($progressCallbackFct!="" && function_exists($progressCallbackFct)) {
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $progressCallbackFct);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
}
$ret = array("response" => false, "error" => false, "httpcode" => 0, "success" => false);
# Execute the download
$ret["response"] = curl_exec($ch);
# ERROR ?
if(curl_errno($ch)) $ret["error"] = curl_error($ch);
# HTTP CODE
$ret["httpcode"] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$ret["success"] = (is_int($ret["httpcode"]) && $ret["httpcode"]<400);
# Close CURL
curl_close($ch);
return $ret;
}
// GENERATION MOT DE PASSE
function makeNewPassword($nb_car, $chaine = 'azertyuiopqsdfghjklmwxcvbn123456789') {
$nb_lettres = strlen($chaine) - 1;
$generation = '';
for($i=0; $i < $nb_car; $i++)
{
$pos = mt_rand(0, $nb_lettres);
$car = $chaine[$pos];
$generation .= $car;
}
return $generation;
}
// ENVOIE EMAIL
function sendHTMLemail($dest, $subject, $msg, $from=false, $replyTo=false) {
// DESTINATAIRE
if(is_string($dest) && $dest!="") {
$mailTo = $dest;
}
else return "WRONG DEST : "+$dest;
if (!preg_match("#^[a-z0-9._-]+@(hotmail|live|msn).[a-z]{2,4}$#", $mailTo)) $br = "\r\n";
else $br = "\n";
// SUBJECT
if($subject=="") return "WRONG SUBJECT";
// MESSAGE
if($msg=="") return "WRONG MSG";
// FROM & REPLY TO
if(!$from || $from!="") $from = "taeki
";
if(!$replyTo || $replyTo!="") $replyTo = "taeki ";
//=====Création des headers de l'e-mail
$headers = "From: ".$from.$br;
$headers .= "Reply-to: ".$replyTo.$br;
$headers .= "MIME-Version: 1.0".$br;
$headers .= "Content-type: text/html; charset=utf-8".$br;
$headers .= "Content-Transfer-Encoding: 8bit".$br;
//==========
// Envoi
return mail($mailTo, $subject, $msg, $headers);
}
// IMAGE
function redimg($img_src,$img_dst,$dst_w,$dst_h,$destroy=false,$constant_aspect_ratio=true,$crop=false,$ext=false) {
// EXTENSION
if(!$ext) $ext = getImgExtFromMimeType($img_src);
// CHARGEMENT IMAGE
$img_orig = loadImage($img_src, $ext);
if(!$img_orig) return;
// IMAGE SIZE
$src_w = imagesx($img_orig);
$src_h = imagesy($img_orig);
// SIMPLE COPIE DU FICHIER SI L'IMAGE D'ORIGINE EST PLUS PETITE QUE L'IMAGE SOUHAITEE
if($src_w<$dst_w && $src_h<$dst_h) saveImage($img_orig, $ext, $img_dst);
else {
$sx = 0;
$sy = 0;
// CALCUL DE LA TAILLE DE LA NOUVELLE IMAGE
if($constant_aspect_ratio) {
// CROP
if($crop && $dst_w>0 && $dst_h>0 && $src_w>0 && $src_h>0) {
// on calcul les dimensions d'origine en concervant le ratio finale
$test_w = round(($dst_w * $src_h) / $dst_h);
$test_h = round(($dst_h * $src_w) / $dst_w);
if($test_h < $src_h) { // ON CROP EN HAUT ET EN BAS
$src_dif = $src_h - $test_h;
$sy = round( $src_dif /2 );
$src_h = $src_h - $src_dif;
}
else { // ON CROP A GAUCHE ET A DROITE
$src_dif = $src_w - $test_w;
$sx = round( $src_dif /2 );
$src_w = $src_w - $src_dif;
}
}
// REDUIT DEST SIZE
else {
// on calcul les dimensions final en concervant le ratio
$test_h = round(($dst_w / $src_w) * $src_h);
$test_w = round(($dst_h / $src_h) * $src_w);
// Si Height final non précisé (0) => on réduit la hauteur finale
if(!$dst_h) $dst_h = $test_h;
// Sinon si Width final non précisé (0) => on réduit la largeur finale
elseif(!$dst_w) $dst_w = $test_w;
// Sinon teste quel redimensionnement tient dans la zone
elseif($test_h>$dst_h) $dst_w = $test_w; // => on réduit la largeur finale
else $dst_h = $test_h; // => on réduit la hauteur finale
}
}
// CREATION DE LA NOUVELLE IMAGE
$img_new = imagecreatetruecolor($dst_w, $dst_h);
// CONSERVE LA TRANSPARENCE
if(in_array($ext, array("png", "gif", "webp"))) {
$transparency = imagecolortransparent($img_orig);
if($transparency >= 0) {
$transparent_color = imagecolorsforindex($img_orig, $tIdx);
$transparency = imagecolorallocate($img_new, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
imagefill($img_new, 0, 0, $transparency);
imagecolortransparent($img_new, $transparency);
}
else if(in_array($ext, array("png", "webp"))) {
imagealphablending($img_new, false);
imagefill($img_new, 0, 0, imagecolorallocatealpha($img_new, 0, 0, 0, 127));
imagesavealpha($img_new, true);
}
}
imagecopyresampled($img_new,$img_orig,0,0,$sx,$sy,$dst_w,$dst_h,$src_w,$src_h); // Redimenssionnement et écriture de l'image dans l'image vierge en cache
imagedestroy($img_orig); // Efface image originale
if($destroy && file_exists($img_src)) unlink($img_src); // Suppression de l'image d'origine
// SAVE IMAGE
saveImage($img_new, $ext, $img_dst);
if(is_resource($img_new)) imagedestroy($img_new);
}
if($destroy && file_exists($img_src)) unlink($img_src); // Suppression de l'image d'origine
}
function loadImage($img_path, $ext=false) {
if(!$ext) { $ext = getImgExtFromMimeType($img_path); }
$img = false;
switch($ext) {
case "png": $img = imagecreatefrompng($img_path); break;
case "webp": $img = imagecreatefromwebp($img_path); break;
case "bmp": $img = imagecreatefrombmp($img_path); break;
case "gif": $img = imagecreatefromgif($img_path); break;
case "jpg": $img = imagecreatefromjpegexif($img_path); break;
}
return $img;
}
function imagecreatefromjpegexif($filename) {
$img = imagecreatefromjpeg($filename);
$exif = exif_read_data($filename);
if ($img && $exif && isset($exif['Orientation']))
{
$ort = $exif['Orientation'];
if ($ort == 6 || $ort == 5)
$img = imagerotate($img, 270, null);
if ($ort == 3 || $ort == 4)
$img = imagerotate($img, 180, null);
if ($ort == 8 || $ort == 7)
$img = imagerotate($img, 90, null);
if ($ort == 5 || $ort == 4 || $ort == 7)
imageflip($img, IMG_FLIP_HORIZONTAL);
}
return $img;
}
function getImgSize($img_src) {
$size = GetImageSize($img_src);
return array('width' => $size[0], 'height' => $size[1]);
}
function getImgExtFromMimeType($path) {
$ext = false;
if(file_exists($path)) {
$mt = mime_content_type($path);
switch($mt) {
case "image/png" :
case "image/x-png":
$ext = "png";
break;
case "image/pjpeg":
case "image/jpeg" :
case "image/jpg" :
$ext = "jpg";
break;
case "image/gif" : $ext = "gif"; break;
case "image/bmp" : $ext = "bmp"; break;
case "image/svg+xml" : $ext = "svg"; break;
case "image/tiff" : $ext = "tiff"; break;
case "image/webp" : $ext = "webp"; break;
default: $ext = false;
}
}
return $ext;
}
function getImgMimeTypeFromExt($ext) {
$mt = false;
switch($ext) {
case "png" : $mt = "image/png"; break;
case "jpg" : $mt = "image/jpg"; break;
case "gif" : $mt = "image/gif"; break;
case "bmp" : $mt = "image/bmp"; break;
case "svg" : $mt = "image/svg+xml"; break;
case "tiff" : $mt = "image/tiff"; break;
case "webp" : $mt = "image/webp"; break;
default: $mt = false;
}
return $mt;
}
function saveImage($img, $ext, $path=false) {
if($path==false) {
$mt = getImgMimeTypeFromExt($ext);
header('Content-Type: '.$mt);
}
else if($path!="" && file_exists($path)) unlink($path);
if($ext == 'png') imagepng($img,$path,5);
else if($ext == 'gif') imagegif($img,$path);
else if($ext == 'bmp') imagebmp($img,$path,true);
else if($ext == 'webp') imagewebp($img,$path,90);
else imagejpeg($img,$path,90);
imagedestroy($img); // Efface l'image en cache
if($path==false) die();
return file_exists($path);
}
// MANAGE TABLE DATAS
function getRequestTableDatas($table_structure, $force_default_values=false) {
$ret = array();
foreach($table_structure as $key => $infos) {
switch($infos["type"]) {
// INTEGER
case "int":
if(isset($_REQUEST[$key])) {
$val = intval($_REQUEST[$key]);
// TEST MIN
if(is_int($infos["min"])) {
if($val < $infos["min"]) $val = (isset($infos["force_default_under_min"]) && $infos["force_default_under_min"] == true) ? $infos["default"] : $infos["min"];
}
// TEST MAX
if(is_int($infos["max"])) {
if($val > $infos["max"]) $val = (isset($infos["force_default_upper_max"]) && $infos["force_default_upper_max"] == true) ? $infos["default"] : $infos["max"];
}
$ret[$key] = $val;
}
else if($force_default_values) $ret[$key] = $infos["default"];
break;
// FLOAT
case "float":
if(isset($_REQUEST[$key])) {
$val = floatval($_REQUEST[$key]);
// TEST MIN
if(is_float($infos["min"])) {
if($val < $infos["min"]) $val = (isset($infos["force_default_under_min"]) && $infos["force_default_under_min"] == true) ? $infos["default"] : $infos["min"];
}
// TEST MAX
if(is_float($infos["max"])) {
if($val > $infos["max"]) $val = (isset($infos["force_default_upper_max"]) && $infos["force_default_upper_max"] == true) ? $infos["default"] : $infos["max"];
}
$ret[$key] = $val;
}
else if($force_default_values) $ret[$key] = $infos["default"];
break;
// BOOL
case "bool":
if(isset($_REQUEST[$key])) {
$ret[$key] = is_bool($_REQUEST[$key]) ? $_REQUEST[$key] : (intval($_REQUEST[$key]) > 0);
}
else if($force_default_values) $ret[$key] = $infos["default"];
break;
// DATE
case "date":
if(isset($_REQUEST[$key])) $ret[$key] = checkDateFormat($_REQUEST[$key], 'mysql_date', $infos["default"]);
else if($force_default_values) $ret[$key] = $infos["default"];
break;
// SET
case "set":
if(isset($_REQUEST[$key])) $ret[$key] = in_array($_REQUEST[$key], $infos["values"]) ? strval($_REQUEST[$key]) : $infos["default"];
else if($force_default_values) $ret[$key] = $infos["default"];
break;
// TEXT
default:
if(isset($_REQUEST[$key])) {
$val = strval($_REQUEST[$key]);
// TEST LENGTH
if(strlen($val) == 0) $val = $infos["default"];
else if(isset($infos["length"]) && is_int($infos["length"]) && strlen($val) > $infos["length"]) $val = substr($val, 0, $infos["length"]);
$ret[$key] = $val;
}
else if($force_default_values) $ret[$key] = $infos["default"];
}
}
return $ret;
}
function buildSqlSearch($sql, $search, $partBuilderFct) {
if($search && $search!="" && is_callable($partBuilderFct)) {
$parts = explode(" ", $search);
if($parts && is_array($parts) && count($parts)>0) {
$search_sql = "";
foreach($parts as $p) {
if($p!="") $search_sql .= (($search_sql!="") ? " OR " : "").$partBuilderFct($p);
}
if($search_sql!="") {
if(strpos($sql, "WHERE")>0) $sql .= " AND (".$search_sql.")";
else $sql .= " WHERE (".$search_sql.")";
}
}
}
return $sql;
}
function buildTableDatas($table_structure, $datas, $force_default_values=false) {
$ret = array();
foreach($table_structure as $key => $infos) {
if(array_key_exists($key, $datas)) {
switch($infos["type"]) {
// INTEGER
case "int": $ret[$key] = is_null($datas[$key]) ? NULL : intval( $datas[$key] ); break;
// FLOAT
case "float": $ret[$key] = is_null($datas[$key]) ? NULL : floatval( $datas[$key] ); break;
// BOOL
case "bool": $ret[$key] = is_null($datas[$key]) ? NULL : ($datas[$key] ? 1 : 0); break;
// DATE
case "date": $ret[$key] = is_null($datas[$key]) ? NULL : $datas[$key]; break;
// SET
case "set": $ret[$key] = is_null($datas[$key]) ? NULL : strval($datas[$key]); break;
// TEXT
default: $ret[$key] = is_null($datas[$key]) ? NULL : strval($datas[$key]);
}
}
else if($force_default_values) $ret[$key] = $infos["default"];
}
return $ret;
}
function addDatasInTable($db_manager, $table_name, $table_structure, $datas, $error_str="de l'information") {
$infos = buildTableDatas($table_structure, $datas, true);
$r = $db_manager->insert($table_name,$infos);
if($r["result"] && !$r["error"]) return ((int)$r['id']>0) ? $r['id'] : true;
else {
$er = "sql: ".$r['sql']."result: ".getReadableVar($r['result'])."error: ".getReadableVar($r['erreur'])."insert id: ".getReadableVar($r['id']);
return "ERREUR : Une erreur est survenue durant l'enregistrement ".$error_str." dans la base de données ! ".$er;
}
}
function updateDatasInTable($db_manager, $table_name, $table_structure, $id, $datas, $null_str="à la fiche", $error_str="de l'information") {
$infos = buildTableDatas($table_structure, $datas, false);
if(count($infos)==0) return "ERREUR : aucune modification à apporter ".$null_str." !";
$r = $db_manager->update($table_name,$infos,"WHERE ref=".intVal($id));
if($r && !$r['erreur']) return 1;
else {
$er = "sql: ".$r['sql']."result: ".getReadableVar($r['result'])."error: ".getReadableVar($r['erreur']);
return "ERREUR : Une erreur est survenue durant l'enregistrement des modifications ".$error_str." dans la base de données ! ".$er;
}
}
function updateDatasInTableByCondition($db_manager, $table_name, $table_structure, $condition, $datas, $null_str="à la fiche", $error_str="de l'information") {
$infos = buildTableDatas($table_structure, $datas, false);
if(count($infos)==0) return "ERREUR : aucune modification à apporter ".$null_str." !";
$r = $db_manager->update($table_name,$infos,$condition);
if($r && !$r['erreur']) return 1;
else {
$er = "sql: ".$r['sql']."result: ".getReadableVar($r['result'])."error: ".getReadableVar($r['erreur']);
return "ERREUR : Une erreur est survenue durant l'enregistrement des modifications ".$error_str." dans la base de données ! ".$er;
}
}
function deleteItemInTable($db_manager, $table_name, $id, $error_str="de l'information") {
$infos = array("del" => 1);
$r = $db_manager->update($table_name,$infos,"WHERE ref=".intVal($id));
if($r && !$r['erreur']) return 1;
else {
$er = "sql: ".$r['sql']."result: ".getReadableVar($r['result'])."error: ".getReadableVar($r['erreur']);
return "ERREUR : Une erreur est survenue durant la suppression ".$error_str." dans la base de données ! ".$er;
}
}
function deleteItemInTableByCondition($db_manager, $table_name, $condition, $error_str="de l'information") {
$infos = array("del" => 1);
$r = $db_manager->update($table_name,$infos,$condition);
if($r && !$r['erreur']) return 1;
else {
$er = "sql: ".$r['sql']."result: ".getReadableVar($r['result'])."error: ".getReadableVar($r['erreur']);
return "ERREUR : Une erreur est survenue durant la suppression ".$error_str." dans la base de données ! ".$er;
}
}
function eraseItemInTable($db_manager, $table_name, $id, $error_str="de l'information") {
$r = $db_manager->deleteWithCondition($table_name,"WHERE ref=".intVal($id));
if($r && !$r['erreur']) return 1;
else {
$er = "
sql: ".$r['sql']."
result: ".getReadableVar($r['result'])."
error: ".getReadableVar($r['erreur']);
return "ERREUR : Une erreur est survenue durant la suppression définitive ".$error_str." dans la base de données ! ".$er;
}
}
function eraseItemInTableByCondition($db_manager, $table_name, $condition, $error_str="de l'information") {
$r = $db_manager->deleteWithCondition($table_name,$condition);
if($r && !$r['erreur']) return 1;
else {
$er = "
sql: ".$r['sql']."
result: ".getReadableVar($r['result'])."
error: ".getReadableVar($r['erreur']);
return "ERREUR : Une erreur est survenue durant la suppression définitive ".$error_str." dans la base de données ! ".$er;
}
}
if(!function_exists("array_key_first")) {
function array_key_first($array) {
reset($array);
return key($array);
}
}
// PHP OUTPUT CACHE
function disablePHPoutputCache() {
session_write_close();
set_time_limit(0);
ini_set('output_buffering', 'off'); // Turn off output buffering
ini_set('zlib.output_compression', false); // Turn off PHP output compression
ini_set('implicit_flush', true); // Implicitly flush the buffer(s)
ob_implicit_flush(true);
ob_end_flush();
// Clear, and turn off output buffering
while (ob_get_level() > 0) {
$level = ob_get_level(); // Get the curent level
ob_end_clean(); // End the buffering
// If the current level has not changed, abort
if (ob_get_level() == $level) break;
}
// Disable apache output buffering/compression
if (function_exists('apache_setenv')) {
apache_setenv('no-gzip', '1');
apache_setenv('dont-vary', '1');
}
}
function disablePHPoutputBuffering() {
disablePHPoutputCache();
return;
session_write_close();
ini_set('output_buffering', 0); // Turn off output buffering
ini_set('zlib.output_compression', 0); // Turn off PHP output compression
ini_set('implicit_flush', true); // Implicitly flush the buffer(s)
// Disable apache output buffering/compression
if (function_exists('apache_setenv')) {
apache_setenv('no-gzip', '1');
apache_setenv('dont-vary', '1');
}
set_time_limit(0);
}
?>