<?php

class ParamGlobal
{

    private $langue = 'FR';

    private $profil = null;

    private $connected = null;

    private $profilXML = null;

    private $dateFormat = null;

    private $cssEditor = null;

    private $jsLinks = null;

    private $capList = null;

    function __construct()
    {
        $this->profil = array();
        $this->profilXML = array();
        $this->connected = false;
        $this->dateFormat = 'dd/mm/yyyy';
        $this->jsLinks = array();
        $this->capList = array();
        $this->langue = 'FR';
    }

    // LANGUE ET DATE
    function setLangue($lng)
    {
        $this->langue = $lng;
        $this->save();
    }

    function &getLangue()
    {
        return $this->langue;
    }

    function setDateFormat($v)
    {
        $this->dateFormat = $v;
        $this->save();
    }

    function &getDateFormat()
    {
        return $this->dateFormat;
    }

    function dateToSql($d)
    {
        if ($d) 
        {
            $arr = explode('/', $d);
            
            // si tous les composant de la date sont à 0
            if (intval($d[0]) == 0 && intval($d[1]) == 0 && intval($d[2]) == 0) {
                return NULL;
            }
            
            if ($this->dateFormat == 'jj/mm/aaaa' || $this->dateFormat == 'dd/mm/yyyy') {
                return $arr[2] . '-' . $arr[1] . '-' . $arr[0];
            } else if ($this->dateFormat == 'mm/jj/aaaa' || $this->dateFormat == 'mm/dd/yyyy') {
                return $arr[2] . '-' . $arr[0] . '-' . $arr[1];
            } else
                return $d;
        } 
        else {
            return NULL;
        }
    }

      /**
     * return le format date en fonction du DATE_FORMAT
     * @param string $date
     * @return string
     */
    public static function dateConverte($date, $format = null)
    {
        $year=substr($date,0,4);
        $month=substr($date,4,2);
        $day=substr($date,6,2);
        $format = $format ?? $_SESSION['DATE_FORMAT'];
        
        $dateConvertie = $year."/".$month."/".$day;
        
        if(!$date || $date==' ' || $date=='        ')
        {
            $date='00000000';
        }
        
        if ('aaaa/mm/jj' == $format) // format : aaaa/mm/jj
        {
            $dateConvertie = $year."/".$month."/".$day;
            return $dateConvertie;
        }
        elseif ('mm/jj/aaaa' == $format)  // format : mm/jj/aaaa
        {            
            $dateConvertie = $month."/".$day."/".$year;
            return $dateConvertie;
        }
        elseif ('aa-mm-jj' == $format)  // format : aa-mm-jj
        {
            $year=substr($year,2,2);
            
            $dateConvertie = $year."-". $month."-".$day;
            return $dateConvertie;
        }
        elseif ('aaaa-mm-jj' == $format)  // format : aaaa-mm-jj
        {
            $dateConvertie = $year."-". $month."-".$day;
            return $dateConvertie;
        }
        elseif ('jj/mm/aaaa' == $format) // format : jj/mm/aaaa
        {            
            $dateConvertie = $day."/". $month."/".$year;
            return $dateConvertie;
        }
        else 
        {
            //mode Hors connexion
            $dateConvertie = $day."/". $month."/".$year;
            return $dateConvertie;
        }
    }

    function sqlToDate($d)
    {
        $arr = explode('-', $d);
        if ($this->dateFormat == 'jj/mm/aaaa' || $this->dateFormat == 'dd/mm/yyyy') {
            return $arr[2] . '/' . $arr[1] . '/' . $arr[0];
        } else if ($this->dateFormat == 'mm/jj/aaaa' || $this->dateFormat == 'mm/dd/yyyy') {
            return $arr[1] . '/' . $arr[2] . '/' . $arr[0];
        } else if (is_null($d)) {
            return '0000-00-00';
        } else
            return $d;
    }

    function fromTime($t = 0)
    {
        return date('Y-m-d', $t);
    }

    function nowDate($offset = 0)
    {
        return date('Y-m-d', time() + $offset);
    }

    function nowTime($offset = 0)
    {
        if ($this->dateFormat == 'jj/mm/aaaa' || $this->dateFormat == 'dd/mm/yyyy') {
            return date('H:i:s', time() + $offset);
        } else if ($this->dateFormat == 'mm/jj/aaaa' || $this->dateFormat == 'mm/dd/yyyy') {
            return date('h:i:s A', time() + $offset);
        } else
            return date('H:i:s', time() + $offset);
    }

    /**
     * vérifie si la $date est correctement saisie et si
     * elle est comprise entre after et before
     *
     * @return cette fonction renvoie true si elle s'est bien passé, sinon un message d'erreur pour les cas standards
     *         ou 0xF si la date dépasse $before, sinon -0xF si la date est trop petite par rapport a $after
     *        
     *        
     */
    function validerDate($date, $after = NULL, $before = NULL)
    {
        $arr = explode('/', $date);
        
        if (! is_numeric($arr[0]) || ! is_numeric($arr[1]) || ! is_numeric($arr[2]))
            return strBuild(trad("Des caractères inatendus sont présent dans la date @1@"), $arr[0] . $arr[1] . $arr[2]);
        
        if ($this->dateFormat == 'jj/mm/aaaa' || $this->dateFormat == 'dd/mm/yyyy') {
            $jour = $arr[0];
            $mois = $arr[1];
            $an = $arr[2];
        } else if ($this->dateFormat == 'mm/jj/aaaa' || $this->dateFormat == 'mm/dd/yyyy') {
            $jour = $arr[1];
            $mois = $arr[0];
            $an = $arr[2];
        }
        
        $tm = mktime(0, 0, 0, $mois, $jour, $an);
        if ($mois >= 1 && $mois <= 12) {
            $nbj = date('t', $tm); // nombre de jours dans le mois saisi
            if (! ($jour >= 1 && $jour <= $nbj)) // si le jour n'est pas compris entre le 1er du mois et le dernier
{
                return trad("Jour de la date incorrect");
            }
        } else {
            return trad("Mois de la date incorrect");
        }
        
        // si la date doit etre plus grande que after
        if ($after != NULL && $before == NULL && $tm < $after) {
            return - 0xF;
        }
        
        // si la date doit etre plus petite que before
        if ($after == NULL && $before != NULL && $tm > $before) {
            return 0xF;
        }
        
        return true;
    }

    // AUTOSAVE
    function save()
    {
        $_SESSION['CL_PARAM_GLOBAL'] = serializeSecure($this);
    }

    // CSS EDITOR
    function getCSSEditor()
    {
        return unserializeSecure($this->cssEditor);
    }

    function setCSSEditor($editor)
    {
        $this->cssEditor = serializeSecure($editor);
        $this->save();
    }

    // FONCTIONS PROFIL
    function &getProfil()
    {
        return $this->profil;
    }

    function &getProfilProperty($k)
    {
        return $this->profil[$k];
    }

    function &getProfilXML()
    {
        return $this->profilXML;
    }

    function setProfil($arr)
    {
        foreach ($arr as $k => & $v) {
            $this->profil[$k] = $v;
            $this->profilXML["!{$k}"] = $v;
        }
        $this->setLangue($arr['CODE_LANGUE']);
        $this->connected = true;
        $this->profilXML["!URL"] = 'gestion_global.php';
        $this->profilXML["!OBJECT"] = "{'OBJECT':'DISCONNECT_MEMBER','form':document.getElementById('t1').form.name}";
        
        $this->save();
    }

    function deleteProfil()
    {
        $this->profilXML = array();
        $this->profil = array();
        $this->connected = false;
        $this->setLangue('FR');
        
        $this->save();
    }

    function &isConnected()
    {
        return $this->connected;
    }

    function isFour()
    {
        return ($this->connected && $this->profil['CODE_FOURNISSEUR']);
    }

    // OFFUSQUEUR JS
    function getJSLink()
    {
        if (count($this->jsLinks) == 0) {
            if (file_exists('../webroot/linker.ljs')) {
                $file = file_get_contents('../webroot/linker.ljs', true);
                if ($file != false) {
                    $xml = new XMLStruct($file);
                    $nodes = $xml->getNodes('//functions/*');
                    foreach ($nodes as $n)
                        $this->jsLinks[$n->nodeName] = $n->getAttribute('is');
                    
                    $this->save();
                    return true;
                } else
                    return false;
            } else
                return false;
        } else
            return true;
    }

    function JSLinkOf($str)
    {
        if (count($this->jsLink) > 0) {
            $strc = $str;
            $arr = array();
            $fnc = array();
            while (preg_match("#([a-zA-Z0-9_-]+)\((.+?)\);#", $strc, $arr)) {
                $strc = substr($strc, strpos($strc, $arr[0]) + strlen($arr[0]));
                
                if (! in_array($arr[1], $fnc))
                    $fnc[] = $arr[1];
            }
            
            foreach ($fnc as $f) {
                if (in_array($f, array_keys($this->jsLinks)))
                    $str = str_replace($f . "(", $this->jsLinks[$f] . "(", $str);
            }
        }
        
        return $str;
    }

    // CAPTCHA
    function createCaptcha($input, $id = -1)
    {
        $alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $word = '';
        for ($i = 0; $i < 5; $i ++)
            $word .= $alpha[mt_rand(0, 25)];
        
        if (! in_array($input, array_keys($this->capList)) || $this->capList[$input]["id"] != $id)
            $this->capList[$input] = array(
                'code' => $word,
                'id' => $id
            );
        
        $this->save();
    }

    function getCaptcha($input)
    {
        if (! in_array($input, array_keys($this->capList)))
            return null;
        else
            return $this->capList[$input];
    }

    function deleteCaptcha($input)
    {
        unset($this->capList[$input]);
        $this->save();
    }
}// Fin classe param global
