paniers/functions/functions.php

1599 lines
54 KiB
PHP

<?php
// SMARTY DISPLAY //
function display() {
$GLOBALS['smarty'] -> assign('gitVS',getGitVersion());
$GLOBALS['smarty'] -> assign('debug',isset($GLOBALS['debug']) ? $GLOBALS['debug'] : false);
$GLOBALS['smarty'] -> assign('errors',isset($GLOBALS['errors']) ? $GLOBALS['errors'] : false);
$GLOBALS['smarty'] -> assign('jsFiles',$GLOBALS['jsFiles']);
$GLOBALS['smarty'] -> assign('cssFiles',$GLOBALS['cssFiles']);
$GLOBALS['smarty'] -> display($GLOBALS['template']);
die();
}
// DEBUG & ERRORS //
$GLOBALS['debug'] = array();
function addDebug($var,$label='') {
$txt = '';
if($label!='') {
$txt = $label.' : ';
}
if(is_array($var)) {
$GLOBALS['debug'][] = $txt.afficheArray($var);
}
elseif(is_bool($var)) {
if($var) {
$GLOBALS['debug'][] = $txt.'true';
}
else {
$GLOBALS['debug'][] = $txt.'false';
}
}
else {
$GLOBALS['debug'][] = $txt.print_r($var,1);
}
}
$GLOBALS['errors'] = array();
function afficheArray($array,$echo=false,$indent=20,$displayType=false) {
if(!is_array($array)) return "NOT AN ARRAY !".(($echo) ? "<br/>" : "");
$htmlTxt = "array(";
if(count($array)==0) return "array()";
foreach($array as $key => $val) {
$htmlTxt.="<br/><span style='margin-left:".$indent."px'>";
$htmlTxt.= (is_string($key)) ? "'".$key."'" : $key;
$htmlTxt.= " = ";
$htmlTxt.= (is_array($val)) ? afficheArray($val, false, ($indent+20), false) : getReadableVar($val,$displayType);
$htmlTxt.= ",</span>";
}
$htmlTxt = substr($htmlTxt,0,-8).'</span><br/>';
$htmlTxt.="<span style='margin-left:".($indent-20)."px'>)</span>";
if($echo) {
echo($htmlTxt."<br/>");
return;
}
return $htmlTxt;
}
function getReadableVar($var,$displayType=false) {
$ret = "";
$type = "";
if(is_array($var)) { $type = "array"; $ret = afficheArray($var,false,20); }
elseif(is_bool($var)) { $type = "bool"; $ret = ($var) ? 'true' : 'false'; }
elseif(is_string($var) && $var=='') { $type = "string"; $ret = "Ø (empty string)"; }
elseif(is_string($var)) { $type = "string"; $ret = '"'.$var.'"'; }
elseif(is_null($var)) { $type = "null"; $ret = 'NULL'; }
elseif($var instanceof DateTime) { $type = "datetime"; $ret = $var->format('d/m/Y - H:i:s'); }
else { $type = gettype($var); $ret = print_r($var,1); }
if($displayType) return "[".$type."] : ".$ret;
return $ret;
}
function getGitVersion() {
exec('git describe --always',$version_mini_hash);
exec('git rev-list HEAD | wc -l',$version_number);
exec('git log -1',$line);
exec('git log -1 --format=%cd --date=iso',$date);
$version['short'] = "v1.".trim($version_number[0]).".".$version_mini_hash[0];
$version['full'] = "v1.".trim($version_number[0]).".$version_mini_hash[0] (".str_replace('commit ','',$line[0]).")";
$version['date'] = formatDate($date[0], 'iso', 'datetime');
return $version;
}
// FORMAT
function br2nl($string) {
return preg_replace('/\<br(\s*)?\/?\>/i', "", $string);
}
function orderListByKey($list, $key, $sens='ASC', $sort_type=SORT_REGULAR) {
$keyList = array();
$itemList = array();
foreach($list as $k => $i) {
$keyList[] = $k;
$itemList[] = $i[$key];
}
$sort_sens = ($sens=="ASC") ? SORT_ASC : SORT_DESC;
array_multisort($itemList, $sort_sens, $sort_type, $keyList);
$newList = array();
foreach($keyList as $k) {
$newList[] = $list[$k];
}
return $newList;
}
function strtoupperFirstLetter($str) {
if(strlen($str)==0) return $str;
return strtoupper(substr($str,0,1)).substr($str,1);
}
// DATE
{
$GLOBALS['PRINT_MOIS_COURT'] = array(
1 => 'janv.',
2 => 'fév.',
3 => 'mars',
4 => 'avril',
5 => 'mai',
6 => 'juin',
7 => 'juil.',
8 => 'août',
9 => 'sept.',
10 => 'oct.',
11 => 'nov.',
12 => 'déc.'
);
$GLOBALS['PRINT_MOIS'] = array(
1 => 'janvier',
2 => 'février',
3 => 'mars',
4 => 'avril',
5 => 'mai',
6 => 'juin',
7 => 'juillet',
8 => 'août',
9 => 'septembre',
10 => 'octobre',
11 => 'novembre',
12 => 'décembre'
);
$GLOBALS['PRINT_JOUR_INI'] = array(
0 => 'D.',
1 => 'L.',
2 => 'Ma.',
3 => 'Me.',
4 => 'J.',
5 => 'V.',
6 => 'S.'
);
$GLOBALS['PRINT_JOUR_COURT'] = array(
0 => 'dim.',
1 => 'lun.',
2 => 'mar.',
3 => 'mer.',
4 => 'jeu.',
5 => 'ven.',
6 => 'sam.'
);
$GLOBALS['PRINT_JOUR'] = array(
0 => 'dimanche',
1 => 'lundi',
2 => 'mardi',
3 => 'mercredi',
4 => 'jeudi',
5 => 'vendredi',
6 => 'samedi'
);
$GLOBALS['DATE_FORMATS'] = array(
'date' => "d/m/Y",
'datetime' => "d/m/Y - H:i",
'mysql_date' => "Y-m-d",
'mysql_datetime' => "Y-m-d H:i:s",
'strdate' => "Y-m-d",
'strdatetime' => "Y-m-d_H.i.s",
'iso' => "Y-m-d H:i:s P",
'time' => "H:i",
'print_time' => "H:i",
'mois' => "m-d"
);
}
function dateFormatHasDate($format) {
return $format=='date'
|| $format=='datetime'
|| $format=='mysql_date'
|| $format=='mysql_datetime'
|| $format=='strdate'
|| $format=='strdatetime'
|| $format=='iso'
|| $format=='timestamp';
}
function dateFormatHasTime($format) {
return $format=='datetime' || $format=='mysql_datetime' || $format=='strdatetime' || $format=='iso' || $format=='timestamp';
}
function parseDate($dateTxt='', $format="mysql_datetime", $moment=false, $dateTimeZoneTxt = "Europe/Paris") {
$dateObj = false;
$dateTimeZone = new DateTimeZone( $dateTimeZoneTxt );
if($dateTxt=="now") $dateObj = new DateTime('now', $dateTimeZone);
else if($format=="timestamp" && (int)$dateTxt>0) $dateObj = new DateTime('@'.$dateTxt, $dateTimeZone);
else if($dateTxt!='' && intval($dateTxt)!=0) {
if(array_key_exists($format, $GLOBALS['DATE_FORMATS'])) $dateObj = DateTime::createFromFormat($GLOBALS['DATE_FORMATS'][$format], $dateTxt, $dateTimeZone);
}
if(!isValidDateObj($dateObj)) return false;
if($moment=="start" || !dateFormatHasTime($format)) $dateObj->setTime(0, 0, 0);
else if($moment=="end") $dateObj->setTime(23, 59, 59);
return $dateObj;
}
function isValidDateObj($dateObj) { return $dateObj!==false && $dateObj!==NULL && $dateObj instanceof DateTime; }
function isValidDate($dateTxt, $format = 'mysql_datetime', $dateTimeZoneTxt = "Europe/Paris") {
$dateObj = parseDate($dateTxt, $format, $dateTimeZoneTxt);
return isValidDateObj($dateObj);
}
function checkDateFormat($date, $format = 'mysql_datetime', $default = NULL) {
if($default == "now") $default = formatDate('now', $format);
return isValidDate($date, $format) ? $date : $default;
}
function formatDate($dateTxt='', $originalFormat="mysql_datetime", $destinationFormat="datetime", $moment=false, $dateTimeZoneTxt = "Europe/Paris") {
$dateObj = parseDate($dateTxt, $originalFormat, $moment, $dateTimeZoneTxt);
return formatDateObj($dateObj, $destinationFormat);
}
function formatDateObj($dateObj, $format="datetime", $moment=false) {
if(!isValidDateObj($dateObj)) return "";
if($moment=="start") $dateobj->setTime(0, 0, 0);
else if($moment=="end") $dateobj->setTime(23, 59, 59);
if(array_key_exists($format, $GLOBALS['DATE_FORMATS'])) return $dateObj->format( $GLOBALS['DATE_FORMATS'][$format] );
$j = $GLOBALS['PRINT_JOUR'][ intval($dateObj->format("w")) ];
$d = intval( $dateObj->format("j") );
$m = $GLOBALS['PRINT_MOIS_COURT'][ intval($dateObj->format("m")) ];
$y = intval( $dateObj->format("Y") );
$t = $dateObj->format("H")."h".((int)$dateObj->format("i")>0 ? $dateObj->format("i") : "");
switch($format) {
case 'print_date': return "$d $m $y"; break; // "j mois annee"
case 'print_date_with_day': return "$j $d $m $y"; break; // "jour j mois annee"
case 'print_datetime': return "$d $m $y à $t"; break; // "j mois annee à heure h min"
case 'timestamp': return $dateObj->getTimestamp(); break; // timestamp
}
return "";
}
function formatPeriode($dateTxtDeb='', $dateTxtFin='', $format="mysql_datetime", $time=true, $dateTimeZoneTxt = "Europe/Paris") {
// DEBUT
$deb = parseDate($dateTxtDeb, $format, $dateTimeZoneTxt);
if(!$deb) return "";
// FIN
$fin = parseDate($dateTxtFin, $format, $dateTimeZoneTxt);
if($time) $time = dateFormatHasTime($format);
$deb_day = intval( $deb->format("j") );
$deb_month = $GLOBALS['PRINT_MOIS_COURT'][ intval($deb->format("m")) ];
$deb_year = intval( $deb->format("Y") );
$deb_date = "$deb_day $deb_month $deb_year";
$deb_time = $deb->format("G")."h".(intval($deb->format("i"))>0 ? $deb->format("i") : "");
$ret = "";
if(!$fin) {
$ret = "le ".$deb_date;
if($time) $ret .= " à ".$deb_time;
}
else {
$same_date = $deb->format('mysql_date') == $fin->format('mysql_date');
$same_time = $time ? $deb->format('time') == $fin->format('time') : false;
$same_month = $deb->format('Y-m') == $fin->format('Y-m');
$same_year = $deb->format('Y') == $fin->format('Y');
$fin_day = intval( $fin->format("j") );;
$fin_month = $GLOBALS['PRINT_MOIS_COURT'][ intval($fin->format("m")) ];
$fin_year = intval( $fin->format("Y") );
$fin_date = "$fin_day $fin_month $fin_year";
$fin_time = $fin->format("G")."h".(intval($fin->format("i"))>0 ? $fin->format("i") : "");
if($same_date) { // MEME JOUR
$ret = "le ".$deb_date;
if($time) {
if($same_time) $ret .= " à ".$deb_time; // MEME HEURE
else $ret .= " de ".$deb_time." à ".$fin_time; // HEURE DIFFERENTE
}
}
else if($same_month) { // MEME MOIS
if($time) $ret = "du $deb_day à $deb_time au $fin_date à $fin_time";
else $ret = "du $deb_day au $fin_date";
}
else if($same_year) { // MEME ANNEE
if($time) $ret = "du $deb_day $deb_month à $deb_time au ".$fin_date." à ".$fin_time;
else $ret = "du $deb_day $deb_month au $fin_date";
}
else {
if($time) $ret = "du $deb_date à $deb_time au ".$fin_date." à ".$fin_time;
else $ret = "du $deb_date au $fin_date";
}
}
return $ret;
}
/*** REMPLACE SYMBOLES ***/
function replaceSymboles($string){
$replaceSymboles = Array(
" " => "_",
"/" => "-",
'"' => "",
"'" => "",
":" => "_",
"&" => "_",
"+" => "_",
"à" => "a",
"á" => "a",
"â" => "a",
"ã" => "a",
"ä" => "a",
"ç" => "c",
"è" => "e",
"é" => "e",
"ê" => "e",
"ë" => "e",
"ì" => "i",
"í" => "i",
"î" => "i",
"ï" => "i",
"ñ" => "n",
"ò" => "o",
"ó" => "o",
"ô" => "o",
"õ" => "o",
"ö" => "o",
"ù" => "u",
"ú" => "u",
"û" => "u",
"ü" => "u",
"ý" => "y",
"ÿ" => "y",
"À" => "A",
"Á" => "A",
"Â" => "A",
"Ã" => "A",
"Ä" => "A",
"Ç" => "C",
"È" => "E",
"É" => "E",
"Ê" => "E",
"Ë" => "E",
"Ì" => "I",
"Í" => "I",
"Î" => "I",
"Ï" => "I",
"Ñ" => "N",
"Ò" => "O",
"Ó" => "O",
"Ô" => "O",
"Õ" => "O",
"Ö" => "O",
"Ù" => "U",
"Ú" => "U",
"Û" => "U",
"Ü" => "U",
"Ý" => "Y"
);
return strtr($string,$replaceSymboles);
}
/*** REFUSE TOUTE CONNECTION AUTRE QUE AJAX ***/
function preventDirectAccess() {
// prevent direct access
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
if(!$isAjax) {
$user_error = 'Access denied - not an AJAX request...';
trigger_error($user_error, E_USER_ERROR);
return;
}
return true;
}
/*** AUTO COMPLETE HIGHLIGHT ***/
/**
* mb_stripos all occurences
* based on http://www.php.net/manual/en/function.strpos.php#87061
*
* Find all occurrences of a needle in a haystack
*
* @param string $haystack
* @param string $needle
* @return array or false
*/
function mb_stripos_all($haystack, $needle) {
$s = 0;
$i = 0;
while(is_integer($i)) {
$i = mb_stripos($haystack, $needle, $s);
if(is_integer($i)) {
$aStrPos[] = $i;
$s = $i + mb_strlen($needle);
}
}
if(isset($aStrPos)) {
return $aStrPos;
} else {
return false;
}
}
/**
* Apply highlight to row label
*
* @param string $a_json json data
* @param array $parts strings to search
* @return array
*/
function apply_highlight($a_json, $parts) {
error_reporting(0);
$p = count($parts);
$rows = count($a_json);
for($row = 0; $row < $rows; $row++) {
$label = $a_json[$row]["label"];
$a_label_match = array();
for($i = 0; $i < $p; $i++) {
$part_len = mb_strlen($parts[$i]);
$a_match_start = mb_stripos_all($label, $parts[$i]);
foreach($a_match_start as $part_pos) {
$overlap = false;
foreach($a_label_match as $pos => $len) {
if($part_pos - $pos >= 0 && $part_pos - $pos < $len) {
$overlap = true;
break;
}
}
if(!$overlap) {
$a_label_match[$part_pos] = $part_len;
}
}
}
if(count($a_label_match) > 0) {
ksort($a_label_match);
$label_highlight = '';
$start = 0;
$label_len = mb_strlen($label);
foreach($a_label_match as $pos => $len) {
if($pos - $start > 0) {
$no_highlight = mb_substr($label, $start, $pos - $start);
$label_highlight .= $no_highlight;
}
$highlight = '<span class="hl_results">' . mb_substr($label, $pos, $len) . '</span>';
$label_highlight .= $highlight;
$start = $pos + $len;
}
if($label_len - $start > 0) {
$no_highlight = mb_substr($label, $start);
$label_highlight .= $no_highlight;
}
$a_json[$row]["label"] = $label_highlight;
}
}
return $a_json;
}
// HCARD
function makeHCard(
$type="contact",
$nom="",
$prenom="",
$societe="",
$adresse="",
$cp="",
$ville="",
$pays=""
) {
$hcard = "";
// HEADER
if($type=="contact") {
$txt = "";
if($nom!="" && $prenom!="") $txt = $prenom." ".$nom;
else if($nom!="") $txt = $nom;
else if($prenom!="") $txt = $prenom;
$hcard = '<div id="hcard-'.str_replace(" ","-",$txt).'" class="vcard">';
if($nom!="" || $prenom!="") {
$hcard .= "<span class='n main-name'>";
if($prenom!="") $hcard .= '<span class="given-name">'.$prenom.'</span>';
if($nom!="") $hcard .= '<span class="family-name">'.$nom.'</span>';
$hcard.= '</span>';
}
if($societe!="") $hcard .= '<div class="org">'.$societe.'</div>';
}
else if($type=="societe") {
$hcard = '<div id="hcard-'.str_replace(" ","-",$societe).'" class="vcard">';
$hcard .= '<div class="org main-name">'.$societe.'</div>';
if($nom!="" || $prenom!="") {
$hcard .= "<span class='n sub-name'>";
$hcard.= "<span class='prefix'>à l'attention de</span>";
if($prenom!="") $hcard .= '<span class="given-name">'.$prenom.'</span>';
if($nom!="") $hcard .= '<span class="family-name">'.$nom.'</span>';
$hcard.= '</span>';
}
}
else {
$hcard = '<div id="hcard" class="vcard">';
}
// ADRESSE
$hcard .= '<div class="adr">';
$hcard .= '<div class="street-address">'.nl2br($adresse).'</div>';
$hcard .= '<span class="postal-code">'.$cp.'</span>';
$hcard .= '<span class="locality">'.$ville.'</span>';
$hcard .= '<span class="country-name">'.$pays.'</span>';
$hcard .= '</div>';
$hcard.="</div>";
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."<br/>");
// 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.'<br/>');
$zip->addEmptyDir($newDir);
$zip = addFilesInZipDir($srcDir.'/'.$f, $zip, $newDir);
}
else {
//echo("AJOUT FICHIERS : ".$zipDir.'/'.$f.'<br/>');
$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)."%</br>";
}
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 <noreply@alabama-media.fr>";
if(!$replyTo || $replyTo!="") $replyTo = "taeki <noreply@alabama-media.fr>";
//=====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 = "</br>sql: ".$r['sql']."</br>result: ".getReadableVar($r['result'])."</br>error: ".getReadableVar($r['erreur'])."</br>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 = "</br>sql: ".$r['sql']."</br>result: ".getReadableVar($r['result'])."</br>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 = "</br>sql: ".$r['sql']."</br>result: ".getReadableVar($r['result'])."</br>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 = "</br>sql: ".$r['sql']."</br>result: ".getReadableVar($r['result'])."</br>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 = "</br>sql: ".$r['sql']."</br>result: ".getReadableVar($r['result'])."</br>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 = "<br/>sql: ".$r['sql']."<br/>result: ".getReadableVar($r['result'])."<br/>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 = "<br/>sql: ".$r['sql']."<br/>result: ".getReadableVar($r['result'])."<br/>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);
}
?>