<?php

// SMARTY DISPLAY //

function display() {
    $GLOBALS['smarty'] -> assign('prefixe',isset($GLOBALS['prefixe']) ? $GLOBALS['prefixe'] : "");
    $GLOBALS['smarty'] -> assign('publicHTML',PUBLIC_HTML);
    $GLOBALS['smarty'] -> assign('publicHTMLadmin',PUBLIC_HTML_ADMIN);
    $GLOBALS['smarty'] -> assign('racine',isset($GLOBALS['racine']) ? $GLOBALS['racine'] : "");
    $GLOBALS['smarty'] -> assign('frameDisplay',isset($GLOBALS['frameDisplay']) ? $GLOBALS['frameDisplay'] : false);
    $GLOBALS['smarty'] -> assign('noMenu',isset($GLOBALS['noMenu']) ? $GLOBALS['noMenu'] : false);
    $GLOBALS['smarty'] -> assign('debug',isset($GLOBALS['debug']) ? $GLOBALS['debug'] : false);
    $GLOBALS['smarty'] -> assign('errors',isset($GLOBALS['errors']) ? $GLOBALS['errors'] : false);
    $GLOBALS['smarty'] -> assign('user',isset($_SESSION['user']) ? $_SESSION['user'] : false);
    $GLOBALS['smarty'] -> assign('gitVS',getGitVersion());

    if(isset($GLOBALS['frameDisplay']) && $GLOBALS['frameDisplay']) {
        $datas = array(
            'content'    =>    $GLOBALS['smarty'] -> fetch('msg.tpl').$GLOBALS['smarty'] -> fetch($GLOBALS['template']),
            'page'       =>    $GLOBALS['smarty']->getTemplateVars('page'),
            'jsFiles'    =>    $GLOBALS['jsFiles'],
            'cssFiles'   =>    $GLOBALS['cssFiles']
        );
        die(json_encode($datas));
    }
    else {
        $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);
    $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]).")";
    return $version;
}

// IMPORT EXCEL FILE

function uploadExcelFile($uploadFileName = 'csv_file') {
    if(file_exists($_FILES[$uploadFileName]['tmp_name'])) {
        $allow_mime_type=array('application/octet-stream',"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        if (in_array($_FILES[$uploadFileName]['type'],$allow_mime_type)) {
            $tmp = DOCS_TMP_DIR.'/tmp_'.time().'.xlsx';
            if(move_uploaded_file($_FILES[$uploadFileName]['tmp_name'], $tmp)) { // Déplace dans le dossier tmp
                return $tmp;
            }
        }
        else {
            $GLOBALS['errors'][] = "ERREUR : Le fichier chargé n'est pas un fichier Excel ! (".$_FILES[$uploadFileName]['type'].')<br/>';
        }
    }
    else {
        $GLOBALS['errors'][] = "ERREUR : Aucun fichier uplaodé !";
    }

    return false;
}

function parseExcelFile($file, $sheetName, $vals, $deleteIfNull=array(), $correctPhoneNum=array(), $correctNL2BR=array()) {
    if(isset($GLOBALS['prefixe'])) require_once $GLOBALS['prefixe'].'libs/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php';
    else require_once 'libs/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php';

    if(!file_exists($file)) return "ERREUR : le fichier n'éxiste pas !";

    // LOAD FILE
    try {
        $objPHPExcel = PHPExcel_IOFactory::load($file);
    }
    catch ( Exception $e ) {
      return "ERREUR : ".$e->getMessage();
    }

    // LOAD SHEET

    $sheet = $objPHPExcel->getSheetByName($sheetName);
    if(!$sheet) {
        return "ERREUR : la feuille '".$sheetName."' est introuvable ! <br/> feuilles disponible : ".afficheArray($objPHPExcel->getSheetNames());
    }

    // LOAD SHEETDATAS
    $sheetDatas = $sheet->toArray(null,true,true,true);

    // FIND LINKS
    $linkValsCols = array();
    $cols = $sheetDatas[1];
    foreach ($cols as $key => $val) {
        if($val !="" && in_array($val, $vals)) {
            $linkValsCols[ array_search($val,$vals) ] = $key; //
        }
    }

    if(count($linkValsCols) != count($vals)) {
        $er = "ERREUR : les valeurs suivantes sont introuvables dans le fichier importé !<ul>";
        foreach($vals as $key => $val) {
            if(!array_key_exists(array_search($val,$vals),$linkValsCols)) $er .= "<li>\"".$val."\"</li>";
        }
        $er.="</ul>";
        return $er;
    }

    // GET ROWS
    $liste = array();
    for($i=2;$i<=count($sheetDatas);$i++) {
        $row = array();
        foreach($linkValsCols as $val => $key) {
            $row[$val] = $sheetDatas[$i][$key];
        }
        $liste[] = $row;
    }

    $objPHPExcel->disconnectWorksheets();
    unset($objPHPExcel);


    $checkNull = (count($deleteIfNull)>0);
    $newListe = array();
    for($i=0;$i<count($liste);$i++) {

        // DELETE IF NULL
        $null = false;
        if($checkNull) {
            foreach($deleteIfNull as $key) {
                if(is_array($key)) {
                    $n = true;
                    foreach($key as $k) {
                        if((string)$liste[$i][$k]!="") $n = false;
                    }
                    $null = $n;
                }
                else if(!((string)$liste[$i][$key]!="")) $null = true;
            }
        }

        if(!$null) {
            // CORRECT PHONES
            foreach($correctPhoneNum as $key) {
                if(substr($liste[$i][$key],0,1) !="0" && strlen($liste[$i][$key])==9) {
                    $val = $liste[$i][$key];
                    $liste[$i][$key] = '0'.substr($val,0,1).".".substr($val,1,2).".".substr($val,3,2).".".substr($val,5,2).".".substr($val,7,2);
                }
            }

            // CORRECT NL2BR
            foreach($correctNL2BR as $key) {
                $liste[$i][$key] = nl2br($liste[$i][$key]);
            }

            // REMPLACE NULL PAR ''
            foreach($vals as $key => $val) {
                if(!((string)$liste[$i][$key]!="")) $liste[$i][$key] = "";
            }
            $newListe[] = $liste[$i];
        }
    }

    return $newListe;

}

// EXPORT EXCEL FILE

function createExcelObj($title,$subject,$desc) {
    if(isset($GLOBALS['prefixe'])) require_once $GLOBALS['prefixe'].'libs/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php';
    else require_once 'libs/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php';

    // CREATE OBJ
    try {

        // CREATION DE L'OBJECT EXCEL
        $objPHPExcel = new PHPExcel();

        $objPHPExcel->getProperties()->setCreator("ERP - alabama");
        $objPHPExcel->getProperties()->setLastModifiedBy("ERP");
        $objPHPExcel->getProperties()->setTitle($title);
        $objPHPExcel->getProperties()->setSubject($subject);
        $objPHPExcel->getProperties()->setDescription($desc);

        return $objPHPExcel;
    }
    catch ( Exception $e ) {
      return "ERREUR : ".$e->getMessage();
    }
}

function writeSheetInExcelObj($objPHPExcel, $sheetIndex, $sheetName, $vals, $datas, $colSizes=array() ,$colAlign=array(), $correctNL2R=array()) {
    if(isset($GLOBALS['prefixe'])) require_once $GLOBALS['prefixe'].'libs/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php';
    else require_once 'libs/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php';

    // ON CREER LA FEUILLE
    if($sheetIndex>0) {
        $objPHPExcel->createSheet($sheetIndex);
        $objPHPExcel->setActiveSheetIndex($sheetIndex);
    }
    $sheet=$objPHPExcel->getActiveSheet();
    $sheet->setTitle($sheetName);

    // ON CREER LES TITRES DE COLONNES
    $styleArrayTitre = array(
        'font' => array(
            'name' => 'Arial',
            'bold' => true,
            'size' => 14
        ),
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
            'wrapText' => true
        ),
        'borders' => array(
            'top' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'left' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'right' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'bottom' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
        ),
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'startcolor' => array(
                'argb' => 'FFC1C1C1',
            ),
        )
    );
    $col = 0;
    $sheet->getRowDimension(1)->setRowHeight(30);
    $lastCol = "A";
    foreach($vals as $k => $v) {
        $cell = $sheet->getCellByColumnAndRow($col, 1);
        $crd = $cell->getCoordinate();
        $lastCol = $cell->getColumn();

        $cell->setValue($v);
        $sheet->getStyle($crd)->applyFromArray($styleArrayTitre);
        $sheet->getStyle($crd)->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_PROTECTED);

        // LARGEUR DE COLONNE
        if(array_key_exists($k,$colSizes)) $sheet->getColumnDimension($cell->getColumn())->setWidth($colSizes[$k]);

        // ALIGNEMENT
        if(array_key_exists($k,$colAlign)) {
            if($colAlign[$k]=="center")
                $sheet->getStyle($lastCol)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            else if($colAlign[$k]=="right")
                $sheet->getStyle($lastCol)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
            else
                $sheet->getStyle($lastCol)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        }

        $col++;
    }

    // ON CREER LES LIGNES DE VALEURS
    $styleArrayValPair = array(
        'font' => array(
            'name' => 'Arial',
            'bold' => false,
            'size' => 12
        ),
        'alignment' => array(
            'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
            'wrapText' => true
        ),
        'borders' => array(
            'top' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'left' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'right' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'bottom' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
        ),
    );

    $styleArrayValImpair = $styleArrayValPair;
    $styleArrayValImpair['fill'] = array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'startcolor' => array(
                'argb' => 'FFADE9FF'
            )
    );
    $row = 2;
    foreach($datas as $l) {
        // APPLY FORMAT
        if($row%2 == 1) $sheet->getStyle("A".$row.":".$lastCol.$row)->applyFromArray($styleArrayValImpair);
        else $sheet->getStyle("A".$row.":".$lastCol.$row)->applyFromArray($styleArrayValPair);
        $sheet->getRowDimension($row)->setRowHeight(50);

        $col = 0;
        foreach($vals as $k => $v) {
            $cell = $sheet->getCellByColumnAndRow($col, $row);
            $crd = $cell->getCoordinate();

            if(in_array($k,$correctNL2R)) {
                $val = str_replace(array("<br/>","\n"),"\r",$l[$v]);
                $sheet->getStyle($crd)->getAlignment()->setWrapText(true);
            }
            else $val = str_replace(array("<br/>","\n"),"",$l[$v]);

            $cell->setValue($val);

            $col++;
        }
        $row++;
    }
    return $objPHPExcel;
}

function downloadExcelObj($objPHPExcel, $fileName) {
    if(isset($GLOBALS['prefixe'])) require_once $GLOBALS['prefixe'].'libs/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php';
    else require_once 'libs/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php';

    // SAVE FILE
    try {
        $objPHPExcel->setActiveSheetIndex(0);

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->setIncludeCharts(true);
        
        ini_set('zlib.output_compression', 0);
        
        $date = gmdate(DATE_RFC1123);
        
        header('Pragma: public');
        header('Cache-Control: must-revalidate, pre-check=0, post-check=0, max-age=0');
        
        header('Content-Tranfer-Encoding: none');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; name="'.$fileName.'"');
        header('Content-Disposition: inline; filename="'.$fileName.'"');
        
        $objWriter->save('php://output');
        exit();
    }
    catch ( Exception $e ) {
      return "ERREUR : ".$e->getMessage();
    }
}

function htmlDisplayExcelObj($objPHPExcel) {
    if(isset($GLOBALS['prefixe'])) require_once $GLOBALS['prefixe'].'libs/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php';
    else require_once 'libs/PHPExcel_1.8.0_doc/Classes/PHPExcel/IOFactory.php';

    // DISPLAY OBJ
    try {
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
        $objWriter->save('php://output');

        return true;
    }
    catch ( Exception $e ) {
      return "ERREUR : ".$e->getMessage();
    }
}

// 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

function getTime($date,$moment='start',$format=DATE_FORMAT) { // Retourne un timestamp à partir d'une date jj/mm/aaaa
    $infos = strptime($date,$format);
    if (is_array($infos)) {
        if ($moment=='start') {
            return mktime(
            '0',
            '0',
            '0',
            ($infos['tm_mon']+1),
            $infos['tm_mday'],
            (1900+$infos['tm_year'])
            );
        }
        elseif ($moment=='end') {
            return mktime(
            '23',
            '59',
            '59',
            ($infos['tm_mon']+1),
            $infos['tm_mday'],
            (1900+$infos['tm_year'])
            );
        }
        return mktime(
            $infos['tm_hour'],
            $infos['tm_min'],
            $infos['tm_sec'],
            ($infos['tm_mon']+1),
            $infos['tm_mday'],
            (1900+$infos['tm_year'])
        );
    }
    return NULL;
}

function getDateTxt($timestamp,$format=DATE_FORMAT) {
    if ($timestamp==0) {
        return '';
    }
    return strftime($format,(int)$timestamp);
}

$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'
);

function checkDateFormat($date, $format = 'mysql_datetime', $default = NULL) {
    if($default == "now") $default = formatDate('', $format);
    return isValidDate($date, $format) ? $date : $default;
}

function isValidDate($date, $format = 'mysql_datetime') {
    $f = "Y-m-d";
    switch($format) {
        case 'date': $f = "d/m/Y"; break;
        case 'datetime': $f = "d/m/Y - H:i"; break;
        case 'mysql_date': $f = "Y-m-d"; break;
        case 'mysql_datetime': $f = "Y-m-d H:i:s"; break;
        case 'strdatetime': $f = "Y-m-d_H.i.s"; break;
        default; $f = "Y-m-d";
    }
    $d = DateTime::createFromFormat($f, $date);
    if($d && $d->format($f) == $date) return true;
    return false;
}

function getRequestDate($name, $format="mysql_date") {
    if(isset($_REQUEST[$name]) && $_REQUEST[$name]!="") return checkDateFormat($_REQUEST[$name], $format);
    return NULL;
}

function buildDate($day = 0, $month = 0, $year = 0, $forceBuild = false, $default = NULL) {
    $date = $default;
    
    if((int)$year>0) {
        $date = $year;
        if((int)$month>0 && (int)$month<13) {
            $date .= "-".sprintf("%02d", $month);
            $nbJ = cal_days_in_month(CAL_GREGORIAN, $month, $year);
            if((int)$day>0 && (int)$day<($nbJ+1)) {
                $date .= "-".sprintf("%02d", $day);
            }
            else if($forceBuild) $date .= "-1";
        }
        else if($forceBuild) $date .= "-1-1";
    }
    return $date;
}

function buildDatePrint ($day = 0, $month = 0, $year = 0, $default = ".") {
    $date = $default;
    if((int)$year>0) {
        $date = $year;
        if((int)$month>0 && (int)$month<13) {
            $date = $GLOBALS['PRINT_MOIS'][$month]." ".$date;
            $nbJ = cal_days_in_month(CAL_GREGORIAN, $month, $year);
            if((int)$day>0 && (int)$day<($nbJ+1)) {
                $d = $year."-".sprintf("%02d", $month)."-".sprintf("%02d", $day);
                $date = formatDate($d, 'mysql_date', 'print_date_with_day');
            }
        }
    }
    return $date;
}

function buildDatePrintShort ($day = 0, $month = 0, $year = 0, $default = ".") {
    $date = $default;
    if((int)$year>0) {
        $date = $year;
        if((int)$month>0 && (int)$month<13) {
            $date = $GLOBALS['PRINT_MOIS'][$month]." ".$date;
            $nbJ = cal_days_in_month(CAL_GREGORIAN, $month, $year);
            if((int)$day>0 && (int)$day<($nbJ+1)) {
                $d = $year."-".sprintf("%02d", $month)."-".sprintf("%02d", $day);
                $date = formatDate($d, 'mysql_date', 'date');
            }
        }
    }
    return $date;
}

function checkExplodeDate($day = 0, $month = 0, $year = 0, $default = NULL) {
    $r = array(
        "day" => $default,
        "month" => $default,
        "year" => $default,
        "date" => $default
    );
    
    if((int)$year>0 && $year<2101) {
        $r["year"] = $year;
        if((int)$month>0 && (int)$month<13) {
            $r["month"] = $month;
            $nbJ = cal_days_in_month(CAL_GREGORIAN, $month, $year);
            if((int)$day>0 && (int)$day<($nbJ+1)) $r["day"] = $day;
        }
    }
    
    $r['date'] = buildDate($r["day"], $r["month"], $r["year"], true);

    return $r;
}

function formatDate($original='', $originalFormat="mysql_datetime", $destinationFormat="datetime", $moment=false) {
    $infos = false;
    if($original!='' && intVal($original)!=0) {
        switch($originalFormat) {
            case 'date':
                $originalFormat = "%d/%m/%Y";
                $infos = strptime($original,$originalFormat);
            break;
            case 'datetime':
                $originalFormat = "%d/%m/%Y - %H:%M";
                $infos = strptime($original,$originalFormat);
            break;
            case 'mysql_date':
                $originalFormat = "%Y-%m-%d";
                $infos = strptime($original,$originalFormat);
            break;
            case 'mysql_datetime':
                $originalFormat = "%Y-%m-%d %H:%M:%S";
                $infos = strptime($original,$originalFormat);
            break;
            case 'strdatetime':
                $originalFormat = "%Y-%m-%d_%H.%M.%S";
                $infos['tm_mday_week'] = sprintf("%02d", $infos['tm_mday']);
            break;
            case 'timestamp':
                $infos = array(
                    'tm_hour' => date('G',$original),
                    'tm_min' => intval( date('i',$original) ),
                    'tm_sec' => intval( date('s',$original) ),
                    'tm_mday' => date('j',$original),
                    'tm_wday' => date('N',$original),
                    'tm_mon' => date('n',$original)-1,
                    'tm_year' => date('Y',$original)-1900
                );
                if($infos["tm_wday"]==7) $infos["tm_wday"] = 0;
                //echo($original.' : '.$infos['tm_year'].'   ');
            break;
            default;
                $infos = strptime(strftime("%c"),"%c");
        }

        if($originalFormat=="date" || $originalFormat=="mysql_date" || ($moment=="start" || $moment=="end")) {
            if($moment=="start") {
                $infos['tm_hour'] = 0;
                $infos['tm_min'] = 0;
                $infos['tm_sec'] = 0;
            }
            else {
                $infos['tm_hour'] = 23;
                $infos['tm_min'] = 59;
                $infos['tm_sec'] = 59;
            }
        }
    }
    else {
        $infos = strptime(strftime("%c"),"%c");
    }
    $infos['tm_hour'] = sprintf("%02d", $infos['tm_hour']);
    $infos['tm_min'] = sprintf("%02d", $infos['tm_min']);
    $infos['tm_sec'] = sprintf("%02d", $infos['tm_sec']);
    $infos['tm_mday'] = sprintf("%02d", $infos['tm_mday']);
    $infos['tm_mon'] = sprintf("%02d", ($infos['tm_mon']+1));
    $infos['tm_year'] = (1900+$infos['tm_year']);
    
    //echo($original.' : '.$infos['tm_year'].'   ');

    switch($destinationFormat) {
        case 'date': // "%d/%m/%Y"
            return $infos['tm_mday']."/".$infos['tm_mon']."/".$infos['tm_year'];
        break;
        case 'time': // "%d/%m/%Y"
            return $infos['tm_hour'].":".$infos['tm_min'];
        break;
        case '%m-%d':
            return $infos['tm_mon']."-".$infos['tm_mday'];
        break;
        case 'strdate': // "%Y-%m-%d"
            return $infos['tm_year']."-".$infos['tm_mon']."-".$infos['tm_mday'];
        break;
        case 'strdatetime': // "%Y-%m-%d_%H.%M.%S"
            return $infos['tm_year']."-".$infos['tm_mon']."-".$infos['tm_mday']."_".$infos['tm_hour'].".".$infos['tm_min'].".".$infos['tm_sec'];
        break;
        case 'datetime': // "%d/%m/%Y - %H:%M"
            return $infos['tm_mday']."/".$infos['tm_mon']."/".$infos['tm_year']." - ".$infos['tm_hour'].":".$infos['tm_min'];
        break;
        case 'print_date': // "j mois annee"
            return $infos['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infos['tm_mon'])]." ".$infos['tm_year'];
        break;
        case 'print_date_with_day': // "jour j mois annee"
            return $GLOBALS['PRINT_JOUR'][$infos['tm_wday']]." ".$infos['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infos['tm_mon'])]." ".$infos['tm_year'];
        break;
        case 'print_datetime': // "j mois annee à heure h min"
            return $infos['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infos['tm_mon'])]." ".$infos['tm_year']." à ".$infos['tm_hour']."h".$infos['tm_min'];
        break;
        case 'mysql_date': // "%Y-%m-%d"
            return $infos['tm_year']."-".$infos['tm_mon']."-".$infos['tm_mday'];
        break;
        case 'mysql_datetime': //"%Y-%m-%d %H:%M:%S"
            return $infos['tm_year']."-".$infos['tm_mon']."-".$infos['tm_mday']." ".$infos['tm_hour'].":".$infos['tm_min'].":".$infos['tm_sec'];
        break;
        case 'timestamp': //timestamp
            return mktime(intval($infos['tm_hour']),intval($infos['tm_min']),intval($infos['tm_sec']),intval($infos['tm_mon']),intval($infos['tm_mday']),intval($infos['tm_year']));
        break;
        default;
            return "";
    }
}

function formatPeriode($originalDeb='', $originalFin='', $originalFormat="mysql_datetime", $time=true) {
    // DEBUT
    $infosDeb = false;
    if($originalDeb!='' && intVal($originalDeb)!=0) {
        switch($originalFormat) {
            case 'date':
                $infosDeb = strptime($originalDeb,"%d/%m/%Y");
            break;
            case 'datetime':
                $infosDeb = strptime($originalDeb,"%d/%m/%Y - %H:%M");
            break;
            case 'mysql_date':
                $infosDeb = strptime($originalDeb,"%Y-%m-%d");
            break;
            case 'mysql_datetime':
                $infosDeb = strptime($originalDeb,"%Y-%m-%d %H:%M:%S");
            break;
            case 'timestamp':
                $infosDeb = array(
                    'tm_hour' => date('G',$originalDeb),
                    'tm_min' => intval( date('i',$originalDeb) ),
                    'tm_sec' => intval( date('s',$originalDeb) ),
                    'tm_mday' => date('j',$originalDeb),
                    'tm_mon' => date('n',$originalDeb)-1,
                    'tm_year' => date('Y',$originalDeb)-1900
                );
            break;
            default;
                $infosDeb = strptime(strftime("%c"),"%c");
        }
        
        if($originalFormat=="date" || $originalFormat=="mysql_date") {
            $infosDeb['tm_hour'] = 0;
            $infosDeb['tm_min'] = 0;
            $infosDeb['tm_sec'] = 0;
        }
    }
    else {
        $infosDeb = strptime(strftime("%c"),"%c");
    }
    
    $infosDeb['tm_hour'] = sprintf("%02d", $infosDeb['tm_hour']);
    $infosDeb['tm_min'] = sprintf("%02d", $infosDeb['tm_min']);
    $infosDeb['tm_sec'] = sprintf("%02d", $infosDeb['tm_sec']);
    $infosDeb['tm_mday'] = sprintf("%02d", $infosDeb['tm_mday']);
    $infosDeb['tm_mon'] = sprintf("%02d", ($infosDeb['tm_mon']+1));
    $infosDeb['tm_year'] = (1900+$infosDeb['tm_year']);
    
    // FIN
    $infosFin = false;
    if($originalFin && ($originalFin!='' && intVal($originalFin)!=0)) {
        switch($originalFormat) {
            case 'date':
                $infosFin = strptime($originalFin,"%d/%m/%Y");
            break;
            case 'datetime':
                $infosFin = strptime($originalFin,"%d/%m/%Y - %H:%M");
            break;
            case 'mysql_date':
                $infosFin = strptime($originalFin,"%Y-%m-%d");
            break;
            case 'mysql_datetime':
                $infosFin = strptime($originalFin,"%Y-%m-%d %H:%M:%S");
            break;
            case 'timestamp':
                $infosFin = array(
                    'tm_hour' => date('G',$originalFin),
                    'tm_min' => intval( date('i',$originalFin) ),
                    'tm_sec' => intval( date('s',$originalFin) ),
                    'tm_mday' => date('j',$originalFin),
                    'tm_mon' => date('n',$originalFin)-1,
                    'tm_year' => date('Y',$originalFin)-1900
                );
            break;
            default;
                $infosFin = strptime(strftime("%c"),"%c");
        }

        if($originalFormat=="date" || $originalFormat=="mysql_date") {
            $infosFin['tm_hour'] = 0;
            $infosFin['tm_min'] = 0;
            $infosFin['tm_sec'] = 0;
        }
    }
    
    if(!$infosFin) {
        if($time && ($originalFormat!="date" && $originalFormat!="mysql_date")) return 'le '.$infosDeb['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosDeb['tm_mon'])]." ".$infosDeb['tm_year']." à ".$infosDeb['tm_hour']."h".$infosDeb['tm_min'];
        else return 'le '.$infosDeb['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosDeb['tm_mon'])]." ".$infosDeb['tm_year'];
    }
    else {
        $infosFin['tm_hour'] = sprintf("%02d", $infosFin['tm_hour']);
        $infosFin['tm_min'] = sprintf("%02d", $infosFin['tm_min']);
        $infosFin['tm_sec'] = sprintf("%02d", $infosFin['tm_sec']);
        $infosFin['tm_mday'] = sprintf("%02d", $infosFin['tm_mday']);
        $infosFin['tm_mon'] = sprintf("%02d", ($infosFin['tm_mon']+1));
        $infosFin['tm_year'] = (1900+$infosFin['tm_year']);
        
        if($time && ($originalFormat!="date" && $originalFormat!="mysql_date")) {
            if($infosDeb['tm_hour']==$infosFin['tm_hour'] 
               && $infosDeb['tm_min']==$infosFin['tm_min']
               && $infosDeb['tm_mday']==$infosFin['tm_mday']
               && $infosDeb['tm_mon']==$infosFin['tm_mon']
               && $infosDeb['tm_year']==$infosFin['tm_year']) {
                // MEME JOUR, MEME HEURE
                return 'le '.$infosDeb['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosDeb['tm_mon'])]." ".$infosDeb['tm_year']." à ".$infosDeb['tm_hour']."h".$infosDeb['tm_min'];
            }
            elseif($infosDeb['tm_mday']==$infosFin['tm_mday']
               && $infosDeb['tm_mon']==$infosFin['tm_mon']
               && $infosDeb['tm_year']==$infosFin['tm_year']) {
                // MEME JOUR, HEURE DIFF
                return 'le '.$infosDeb['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosDeb['tm_mon'])]." ".$infosDeb['tm_year']." de ".$infosDeb['tm_hour']."h".$infosDeb['tm_min']." à ".$infosFin['tm_hour']."h".$infosFin['tm_min'];
            }
            elseif($infosDeb['tm_mon']==$infosFin['tm_mon']
               && $infosDeb['tm_year']==$infosFin['tm_year']) {
                // MEME MOIS, JOUR & HEURE DIFF
                return 'du '.$infosDeb['tm_mday']." à ".$infosDeb['tm_hour']."h".$infosDeb['tm_min']." au ".$infosFin['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosFin['tm_mon'])]." ".$infosFin['tm_year']." à ".$infosFin['tm_hour']."h".$infosFin['tm_min'];
            }
            elseif($infosDeb['tm_year']==$infosFin['tm_year']) {
                // MEME ANNEE, JOUR/MOIS & HEURE DIFF
                return 'du '.$infosDeb['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosDeb['tm_mon'])]." à ".$infosDeb['tm_hour']."h".$infosDeb['tm_min']." au ".$infosFin['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosFin['tm_mon'])]." ".$infosFin['tm_year']." à ".$infosFin['tm_hour']."h".$infosFin['tm_min'];
            }
            else {
                return 'du '.$infosDeb['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosDeb['tm_mon'])]." ".$infosDeb['tm_year']." à ".$infosDeb['tm_hour']."h".$infosDeb['tm_min']." au ".$infosFin['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosFin['tm_mon'])]." ".$infosFin['tm_year']." à ".$infosFin['tm_hour']."h".$infosFin['tm_min'];
            }

        }
        else {
            if($infosDeb['tm_mday']==$infosFin['tm_mday']
               && $infosDeb['tm_mon']==$infosFin['tm_mon']
               && $infosDeb['tm_year']==$infosFin['tm_year']) {
                // MEME JOUR
                return 'le '.$infosDeb['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosFin['tm_mon'])]." ".$infosFin['tm_year'];
            }
            elseif($infosDeb['tm_mon']==$infosFin['tm_mon']
               && $infosDeb['tm_year']==$infosFin['tm_year']) {
                // MEME MOIS, JOUR DIFF
                return 'du '.$infosDeb['tm_mday']." au ".$infosFin['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosFin['tm_mon'])]." ".$infosFin['tm_year'];
            }
            elseif($infosDeb['tm_year']==$infosFin['tm_year']) {
                // MEME ANNEE, JOUR/MOIS
                return 'du '.$infosDeb['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosDeb['tm_mon'])]." au ".$infosFin['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosFin['tm_mon'])]." ".$infosFin['tm_year'];
            }
            else {
                return 'du '.$infosDeb['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosDeb['tm_mon'])]." ".$infosDeb['tm_year']." au ".$infosFin['tm_mday']." ".$GLOBALS['PRINT_MOIS_COURT'][intVal($infosFin['tm_mon'])]." ".$infosFin['tm_year'];
            }
        }
    }
}

function getPeriode($target=false,$duree="3m") {
    if(!$target) $target=strftime("%d/%m/%Y");

    $targetDT = new DateTime(formatDate($target,"date","mysql_datetime"), new DateTimeZone(DATE_TIME_ZONE));

    $limit1 = new DateTime("now", new DateTimeZone(DATE_TIME_ZONE));
    $limit1->setDate($targetDT->format("Y"), $targetDT->format("m"), 0);
    $limit1->setTime(0,0,0);

    $limit2 = new DateTime("now", new DateTimeZone(DATE_TIME_ZONE));
    $limit2->setDate($targetDT->format("Y"), $targetDT->format("m"), $targetDT->format("t"));
    $limit2->setTime(23,59,59);

    $int = new DateInterval('P0M');

    switch($_SESSION['periode_view']) {
        case "1m":
            $int = new DateInterval('P1M');
        break;
        case "3m":
            $int = new DateInterval('P3M');
        break;
        case "6m":
            $int = new DateInterval('P6M');
        break;
        case "1y":
            $int = new DateInterval('P1Y');
        break;
    }

    $limit1->sub($int);
    $limit2->add($int);
    
    return array(
        "start" => array(
            'datetime' => $limit1,
            'mysql_date' => $limit1->format('Y-m-d H:i:s')
        ),
        "end" => array(
            'datetime' => $limit2,
            'mysql_date' => $limit2->format('Y-m-d H:i:s')
        )
    );
}

function getPeriodeJoursFeries($debut,$fin,$format="Y-m-d") {
    $liste = array();
    
    $dt = new DateTime($debut, new DateTimeZone("Europe/Paris"));
    $dt->setTime(0, 0, 0);
    $ft = new DateTime($fin, new DateTimeZone("Europe/Paris"));
    $ft->setTime(23,59, 59);
    
    $ndt = clone $dt;
    while($ndt < $ft) {
        $jf = getYearJoursFeries($ndt->format('Y'),$format);
        foreach($jf as $k => $j) {
            if( $j['datetime'] >= $dt && $j['datetime'] <= $ft ) $liste[$k] = $j;
        }
        $ndt->add( new DateInterval('P1Y') );
        $ndt->setDate((int)$ndt->format('Y'),1,1);
    }
    
    ksort($liste);
    
    return $liste;
}

function getYearJoursFeries($year=false,$format="Y-m-d") {
    if(!$year) $year = intval(date('Y'));
    $liste = array();
    
    $date = new DateTime();
    $date->setTimezone(new DateTimeZone('Europe/Paris'));
    $date->setTime(0,0,0);
    
    $easter_date = new DateTime('@' . easter_date($year));
    $easter_date->setTimezone(new DateTimeZone('Europe/Paris'));
    $easter_date->setTime(0,0,0);
    
    // Jour de l'an - 1er janvier
    $date->setDate($year, 1, 1);
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Jour de l'An"
    );
    // Fête du travail - 1er mai
    $date->setDate($year, 5, 1);
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Fête du Travail"
    );
    // Victoire des alliés - 8 mai 1945
    $date->setDate($year, 5, 8);
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Victoire des Alliés - 8 mai 1945"
    );
    // Fête nationale - 14 juillet
    $date->setDate($year, 7, 14);
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Fête Nationale"
    );
    // Assomption - 15 août
    $date->setDate($year, 8, 15);
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Assomption"
    );
    // Toussaint - 1er novembre
    $date->setDate($year, 11, 1);
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Toussaint"
    );
    // Armistice 1ère Guerre Mondiale - 11 novembre
    $date->setDate($year, 11, 11);
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Armistice 1ère Guerre Mondiale"
    );
    // Noël - 25 décembre
    $date->setDate($year, 12, 25);
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Noël"
    );
    // Lundi de Pâques - lendemain du dimanche de Pâques
    $date = clone $easter_date;
    $date->add(new DateInterval('P1D'));
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Lundi de Pâques"
    );
    // Jeudi de l'ascension - 10 jours avant le Dimanche de Pentecôte
    $date = clone $easter_date;
    $date->add(new DateInterval('P39D'));
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Jeudi de l'Ascension"
    );
    // Lundi de Pentecôte - lendemain de la Pentecôte - 7 semaines après le lundi de pâque
    $date = clone $easter_date;
    $date->add(new DateInterval('P50D'));
    $liste[ $date->format($format) ] = array(
        'datetime' => clone $date,
        'description' => "Lundi de Pentecôte"
    );   
    return $liste;
}

function getHeadCol($target=false,$start=false,$end=false) {
    if(!$start && !$end) {
        if(!$target) $target=strftime("%d/%m/%Y");
        $target = getTime($target,"start","%d/%m/%Y");

        switch($_SESSION['periode_view']) {
            case "m":
                return getYearHeadCol(date('Y',$target),date('n',$target),date('n',$target));
            break;
            case "1m":
                $mois = array();

                if(date('n',$target)>1) $mois[] = getMonthHeadCol(date('Y',$target),date('n',$target)-1);
                else  $mois[] = getMonthHeadCol((date('Y',$target)-1),12);

                $mois[] = getMonthHeadCol(date('Y',$target),date('n',$target));

                if(date('n',$target)<12) $mois[] = getMonthHeadCol(date('Y',$target),date('n',$target)+1);
                else $mois[] = getMonthHeadCol((date('Y',$target)+1),1);

                return $mois;
            break;
            case "3m":
                $mois = array();

                if(date('n',$target)>3) $mois = getYearHeadCol(date('Y',$target),(date('n',$target)-3),date('n',$target));
                else  {
                    $mois = getYearHeadCol((date('Y',$target)-1),(date('n',$target)-3+12),12);

                    $ms = getYearHeadCol(date('Y',$target),1,date('n',$target));
                    foreach($ms as $m) array_push($mois, $m);
                }

                if(date('n',$target)<10) {
                    $ms = getYearHeadCol(date('Y',$target),(date('n',$target)+1),(date('n',$target)+3));
                    foreach($ms as $m) array_push($mois, $m);
                }
                else {
                    $ms = getYearHeadCol(date('Y',$target),(date('n',$target)+1),12);
                    foreach($ms as $m) array_push($mois, $m);

                    $ms = getYearHeadCol((date('Y',$target)+1),1,(date('n',$target)+3-12));
                    foreach($ms as $m) array_push($mois, $m);
                }

                return $mois;
            break;
            case "6m":
                $mois = array();

                if(date('n',$target)>6) $mois = getYearHeadCol(date('Y',$target),(date('n',$target)-6),date('m',$target));
                else  {
                    $mois = getYearHeadCol((date('Y',$target)-1),(date('n',$target)-6+12),12);

                    $ms = getYearHeadCol(date('Y',$target),1,date('n',$target));
                    foreach($ms as $m) array_push($mois, $m);
                }

                if(date('n',$target)<7) {
                    $ms = getYearHeadCol(date('Y',$target),(date('n',$target)+1),(date('n',$target)+6));
                    foreach($ms as $m) array_push($mois, $m);
                }
                else {
                    $ms = getYearHeadCol(date('Y',$target),(date('n',$target)+1),12);
                    foreach($ms as $m) array_push($mois, $m);

                    $ms = getYearHeadCol((date('Y',$target)+1),1,(date('n',$target)+6-12));
                    foreach($ms as $m) array_push($mois, $m);
                }

                return $mois;
            break;
            case "1y":
                $year = array(date('Y',$target)-1, date('Y',$target), date('Y',$target)+1);
                $mois = array();

                foreach($year as $y) {
                    $ms = getYearHeadCol($y);

                    foreach($ms as $m) {
                        array_push($mois, $m);
                    }
                }

                return $mois;
            break;
            default :
                return getYearHeadCol(date('Y',$target),date('n',$target),date('n',$target));
            break;
        }
    }
    else {
        $start = getTime($start,'start',"%Y-%m-%d");
        $end = getTime($end,'start',"%Y-%m-%d");
        
        $mois = array();
        
        $t = $start;
        while($t<$end) {
            $j = date('j',$t);
            $m = date('n',$t);
            $mNbj = date('t',$t);
            $y = date('Y',$t);
            $mEnd = mktime('0','0','0',$m,$mNbj,$y);
            
            if($mEnd < $end) {
                // Mois en cours jusqu'à la fin du mois
                $mois[] = getMonthHeadCol($y,$m,$j,$mNbj);
                $t = $mEnd + 86400;
            }
            else {
                // Mois en cours jusqu'à la date de fin
                $mois[] = getMonthHeadCol($y,$m,$j,date('j',$end));
                $t = $end;
            }
        }
        return $mois;
    }
}

function getOpeHeadCol($debut,$fin) {
    $mois = array();
    
    // CREATION DES JOURS
    $edt = new DateTime($debut, new DateTimeZone("Europe/Paris"));
    $edt->setTime(0, 0, 0);
    $eft = new DateTime($fin, new DateTimeZone("Europe/Paris"));
    $eft->setTime(23,59, 59);
    
    foreach (new DatePeriod($edt, new DateInterval('P1D'), $eft) as $dt) {
        $dt->setTime(0, 0, 0);
        
        $j = intval($dt->format('d'));
        $m = $dt->format('Y-m');
        $im = intval($dt->format('m'));
        $y = intval($dt->format('Y'));
        
        if(!isset($mois[$m])) {
            $mois[$m] = array(
                'num' => $im,
                'nom' => $GLOBALS['PRINT_MOIS'][$im],
                'nom_court' => $GLOBALS['PRINT_MOIS_COURT'][$im],
                'annee' => $y,
                'nb_jours' => 0,
                'jours' => array()
            );
        }
        
        $t = mktime('0', '0', '0', $im, $j, $y);
        $ind = strftime('%w',$t);
        
        $mois[$m]['jours'][$j] = array(
            'num' => $j,
            'jour' => $GLOBALS['PRINT_JOUR'][$ind],
            'jour_court' => $GLOBALS['PRINT_JOUR_COURT'][$ind],
            'ind' => $ind,
            'date' => $dt->format('d/m/Y'),strftime('%d/%m/%Y',$t),
            'date_link' => $dt->format('Y-m-d'),
            'time' => $t
        );
        $mois[$m]['nb_jours']++;
    }
    return $mois;
}

function getYearHeadCol($year,$startM=1,$endM=12) {
    //addDebug("de ".$GLOBALS['PRINT_MOIS_COURT'][$startM]." à ".$GLOBALS['PRINT_MOIS_COURT'][$endM]." ".$year,"getYearHeadCol");
    $mois = array();
    for($i=$startM;$i<=$endM;$i++) {
        $mois[$i] = array(
            'num' => $i,
            'nom' => $GLOBALS['PRINT_MOIS'][$i],
            'nom_court' => $GLOBALS['PRINT_MOIS_COURT'][$i],
            'annee' => $year,
            'nb_jours' => cal_days_in_month(CAL_GREGORIAN, $i, $year),
            'jours' => array()
        );
        
        for($j=1 ; $j<=cal_days_in_month(CAL_GREGORIAN, $i, $year) ; $j++) {
            $t = mktime('0', '0', '0', $i, $j, $year);
            $ind = strftime('%w',$t);
            $mois[$i]['jours'][$j] = array(
                'num' => $j,
                'jour' => $GLOBALS['PRINT_JOUR'][$ind],
                'jour_court' => $GLOBALS['PRINT_JOUR_COURT'][$ind],
                'ind' => $ind,
                'date' => strftime('%d/%m/%Y',$t),
                'date_link' => strftime('%Y-%m-%d',$t),
                'time' => $t
            );
        }
        
    }
    return $mois;
}

function getMonthHeadCol($year,$m,$startJ=false,$endJ=false) {
    //addDebug($GLOBALS['PRINT_MOIS_COURT'][$m]." ".$year ,"getMonthHeadCol");
    $mois = array(
        'num' => $m,
        'nom' => $GLOBALS['PRINT_MOIS'][$m],
        'nom_court' => $GLOBALS['PRINT_MOIS_COURT'][$m],
        'annee' => $year,
        'nb_jours' => cal_days_in_month(CAL_GREGORIAN, $m, $year),
        'jours' => array()
    );
    
    $nbj = cal_days_in_month(CAL_GREGORIAN, $m, $year);
    if(!$startJ || $startJ>$nbj || (int)$startJ==0) $startJ = 1;
    
    if(!$endJ || $endJ>$nbj || (int)$endJ==0) $endJ = $nbj;

    for($j=$startJ ; $j<=$endJ ; $j++) {
        $t = mktime('0', '0', '0', $m, $j, $year);
        $ind = strftime('%w',$t);
        $mois['jours'][$j] = array(
            'num' => $j,
            'jour' => $GLOBALS['PRINT_JOUR'][$ind],
            'jour_court' => $GLOBALS['PRINT_JOUR_COURT'][$ind],
            'ind' => $ind,
            'date' => strftime('%d/%m/%Y',$t),
            'date_link' => strftime('%Y-%m-%d',$t),
            'time' => $t
        );
    }
    
    return $mois;
}

function diffNbJours($debut, $fin,$format='date') {
    //60 secondes X 60 minutes X 24 heures dans une journée
    $nbSecondes= 60*60*24;
    
    $debut_s = formatDate($debut,$format,'strdate');
    $fin_s = formatDate($fin,$format,'strdate');

    $debut_ts = strtotime($debut_s);
    $fin_ts = strtotime($fin_s);
    
    $diff = $fin_ts - $debut_ts;
    
    return floor($diff / $nbSecondes)+1;
}

function diffNbJours2($debut, $fin) {
    $dt1 = new DateTime($debut);
    $dt1->setTime(0, 0, 0);
    $dt2 = new DateTime($fin);
    $dt2->setTime(23,59, 59);
    $itv = date_diff($dt1, $dt2);
    return intval($itv->format('%a'))+1;
}

function getNbOpenDays($date_start, $date_end) {
    // $date_depart && $date_end au format YYYY-MM-DD
    
    $dtd = date_create($date_start);
    $dtd->setTime(0, 0, 0);
    $dtf = date_create($date_end);
    $dtf->setTime(0, 0, 0);
    $dtf->modify( '+1 day' );
    
	$arr_bank_holidays = array(); // Tableau des jours feriés	
	
	// On boucle dans le cas où l'année de départ serait différente de l'année d'arrivée
	$diff_year = $dtf->format('Y') - $dtd->format('Y');
	for ($i = 0; $i <= $diff_year; $i++) {			
		$year = (int)$dtd->format('Y') + $i;
		// Liste des jours feriés
		$arr_bank_holidays[] = '1_1_'.$year; // Jour de l'an
		$arr_bank_holidays[] = '1_5_'.$year; // Fete du travail
		$arr_bank_holidays[] = '8_5_'.$year; // Victoire 1945
		$arr_bank_holidays[] = '14_7_'.$year; // Fete nationale
		$arr_bank_holidays[] = '15_8_'.$year; // Assomption
		$arr_bank_holidays[] = '1_11_'.$year; // Toussaint
		$arr_bank_holidays[] = '11_11_'.$year; // Armistice 1918
		$arr_bank_holidays[] = '25_12_'.$year; // Noel
				
		// Récupération de paques. Permet ensuite d'obtenir le jour de l'ascension et celui de la pentecote	
		$easter = easter_date($year);
		$arr_bank_holidays[] = date('j_n_'.$year, $easter + 86400); // Paques
		$arr_bank_holidays[] = date('j_n_'.$year, $easter + (86400*39)); // Ascension
		$arr_bank_holidays[] = date('j_n_'.$year, $easter + (86400*50)); // Pentecote	
	}
    
	$nb_days_open = 0;

    foreach (new DatePeriod($dtd, new DateInterval('P1D'), $dtf) as $dt) {
        $dt = new DateTime($dt->format('Y-m-d'), new DateTimeZone("Europe/Paris"));
        // Si le jour suivant n'est ni un dimanche (0) ou un samedi (6), ni un jour férié, on incrémente les jours ouvrés	
		if (!in_array($dt->format('w'), array(0, 6)) && !in_array($dt->format('j_n_Y'), $arr_bank_holidays)) $nb_days_open++;
    }

	return $nb_days_open;
}

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(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);
}

?>
