/**
 * Plugin smarty type modifier
 * Purpose:  format a date given by its timestamp (YYYMMDD) to a date according
 *   to the current languages settings
 * if an incorrect date is given, returns the string without any modification
 * Input: YYYYMMDDHHIISS
 * Output: (french) DD/MM/YYYY HH:II:SS, (english) MM/DD/YYYY HH:II:SS
 * Example:  {$date|datetimei18n}
 * @return string
 */
function smarty_modifier_datetimei18n($string, $format = "")
{
    if ($format == "") {
        return ($date = CopixDateTime::yyyymmddhhiissToDateTime($string)) !== false ? $date : $string;
    }
    return ($date = CopixDateTime::yyyymmddhhiissToText($string)) !== false ? $date : $string;
}
 public function _createContent(&$toReturn)
 {
     _classInclude('agenda|dateservices');
     $ppo = new CopixPPO();
     // Récupération des paramètres
     $ppo->cahierId = $this->getParam('cahierId');
     $ppo->jour = $this->getParam('date_jour');
     $ppo->mois = $this->getParam('date_mois');
     $ppo->annee = $this->getParam('date_annee');
     $ppo->current = $this->getParam('current');
     // Timestamp de la date sélectionnée
     $ppo->dateSelectionnee = mktime(0, 0, 0, $ppo->mois, $ppo->jour, $ppo->annee);
     $numeroSemaine = date('W', $ppo->dateSelectionnee);
     $service = new DateService();
     // Récupération des timestamp des jours de la semaine
     $ppo->lun = CopixDateTime::timestampToyyyymmdd($service->numweekToDate($numeroSemaine, $ppo->annee, 1));
     $ppo->mar = CopixDateTime::timestampToyyyymmdd($service->numweekToDate($numeroSemaine, $ppo->annee, 2));
     $ppo->mer = CopixDateTime::timestampToyyyymmdd($service->numweekToDate($numeroSemaine, $ppo->annee, 3));
     $ppo->jeu = CopixDateTime::timestampToyyyymmdd($service->numweekToDate($numeroSemaine, $ppo->annee, 4));
     $ppo->ven = CopixDateTime::timestampToyyyymmdd($service->numweekToDate($numeroSemaine, $ppo->annee, 5));
     $ppo->sam = CopixDateTime::timestampToyyyymmdd($service->numweekToDate($numeroSemaine, $ppo->annee, 6));
     $ppo->semainePrecedente = strtotime("-1 week", $service->numweekToDate($numeroSemaine, $ppo->annee, 1));
     $ppo->semaineSuivante = strtotime("+1 week", $service->numweekToDate($numeroSemaine, $ppo->annee, 1));
     $toReturn = $this->_usePPO($ppo, '_menu_eleve.tpl');
 }
/**
 * Formatte une date ou une heure selon strftime
 *
 * @author Christophe Beyer <*****@*****.**>
 * @since 2012/02/22
 * @see http://php.net/manual/fr/function.strftime.php
 * @param string $string Date ou heure
 * @param string $format Format demandé
 * @return string
 */
function smarty_modifier_strftime($string, $format)
{
    if (preg_match('/^[0-9]{8}$/', $string)) {
        // Format YYYYMMDD
        $ts = CopixDateTime::yyyymmddToTimestamp($string);
    } else {
        throw new CopixException(sprintf('Date %s mal formatee', $string));
    }
    return strftime($format, $ts);
}
 public function get($id)
 {
     $get = false;
     $sp = _daoSp();
     $sp->addCondition('idinter', '=', $id);
     if (count($r = $this->findBy($sp)) > 0) {
         $get = $r[0];
         $now = date('d/m/Y');
         $d1 = CopixDateTime::yyyymmddhhiissToTimeStamp($get->datederniere);
         $d2 = CopixDateTime::timestampToyyyymmdd($d1);
         $datederniere = CopixDateTime::yyyymmddToDate($d2, '/');
         $get->depuis = round(CopixDateTime::timeBetween($datederniere, $now) / (60 * 60 * 24));
         //var_dump($get->depuis);
     }
     return $get;
 }
/**
 * Plugin smarty type modifier
 * Purpose:  format a date given by its timestamp (YYYMMDD) to a date according
 *   to the current languages settings
 * if an incorrect date is given, returns the string without any modification
 * Input: YYYYMMDD
 * Output: (french) DD/MM/YYYY, (english) MM/DD/YYYY
 * Output plain text date if text is given as an extra parameter
 *
 * Example:  {$date|datei18n}
 *           {$date|datei18n:text}
 *
 * @return string
 */
function smarty_modifier_datei18n($string, $format = "")
{
    // COPIX 3
    /*
       if ($format == ""){
     return (($date = CopixDateTime::yyyymmddToDate ($string)) !== false) ? $date : $string;
       }elseif ($format == "text"){
     return (($date = CopixDateTime::yyyymmddToText ($string)) !== false) ? $date : $string;
       }
    */
    require_once COPIX_UTILS_PATH . 'CopixDateTime.class.php';
    // COPIX 2
    if ($format == "") {
        return ($date = CopixDateTime::yyyymmddToDate($string)) !== false ? $date : $string;
    } elseif ($format == "text") {
        return ($date = CopixDateTime::yyyymmddToText($string)) !== false ? $date : $string;
    } elseif ($format == "date_short") {
        // JJ/MM/AAAA (fr)
        //var_dump($string);
        //return CopixDateTime::yyyymmddToDate($string);
        $mktime = smarty_make_timestamp($string);
        //var_dump($mktime.'/'.date('d/m/Y',$mktime));
        $yyyymmdd = CopixDateTime::timestampToyyyymmdd($mktime);
        $res = CopixDateTime::yyyymmddToDate($yyyymmdd);
        return $res;
        /*
        return Kernel::ymd2dmy($string);
        
        $mktime = smarty_make_timestamp($string);
        $timestamp = date("Ymd", $mktime);
              //return (($date = CopixDateTime::timestampToDate ($timestamp)) !== false) ? $date : $string;
        $timestamp2 = CopixDateTime::dateToTimestamp ($string);
        
        var_dump($string);
        
        return (($timestamp==$timestamp2) ? CopixDateTime::timestampToDate ($timestamp) : $string);
        */
    } elseif ($format == "date_short_time") {
        // JJ/MM/AAAA HHhMM (fr)
        $mktime = smarty_make_timestamp($string);
        return ($date = CopixDateTime::mktimeToDatetime($mktime)) !== false ? $date : $string;
    }
}
 /**
  * getAllArchivesFromBlog
  * @param
  * @return
  */
 public function getAllArchivesFromBlog($id_blog)
 {
     $sp = _daoSp();
     $sp->addCondition('id_blog', '=', $id_blog);
     $sp->addCondition('is_online', '=', 1);
     $sp->orderBy(array('date_bact', 'desc'));
     $sp->orderBy(array('id_bact', 'desc'));
     $result = $this->findBy($sp);
     $arArchive = array();
     $lastMonth = null;
     foreach ($result as $article) {
         $monthYear = substr($article->date_bact, 4, 2) . '/' . substr($article->date_bact, 0, 4);
         if ($monthYear != $lastMonth) {
             $article->drawDate = CopixDateTime::YYYYMMtoYearMonthName(substr($article->date_bact, 0, 6));
             $article->dateValue = substr($article->date_bact, 0, 6);
             array_push($arArchive, $article);
             $lastMonth = $monthYear;
         }
     }
     return $arArchive;
 }
 /**
  * Methode qui fait les tests sur la $pValue
  *
  * @param mixed $pValue La valeur
  * Paramètres pouvant être passée :
  * date_format : format de la date
  * date_sup et date_inf permettre de définir un intervalle de date
  * entre lesquelles la date doit être située
  */
 protected function _validate($pValue)
 {
     $toReturn = array();
     if ($pValue === null) {
         return true;
     }
     // Paramètres d'intervalle de date
     $date_sup = CopixDateTime::dateToYYYYMMDD($this->getParam('max'));
     $date_inf = CopixDateTime::dateToYYYYMMDD($this->getParam('min'));
     if (($date = CopixDateTime::dateToYYYYMMDD($pValue)) === false) {
         return _i18n('copix:copixdatetime.validator.invaliddate', $pValue);
     }
     if (!is_null($date_sup)) {
         if ($date_sup < $date) {
             $toReturn[] = _i18n('copix:copixdatetime.validator.datesup', array($pValue, $this->getParam('max')));
         }
     }
     if (!is_null($date_inf)) {
         if ($date_inf > $date) {
             $toReturn[] = _i18n('copix:copixdatetime.validator.dateinf', array($pValue, $this->getParam('min')));
         }
     }
     return empty($toReturn) ? true : $toReturn;
 }
 /**
  * Ajoute une affectation pour un élève (inscription / admission et affectation)
  * - sans suppression des autres affectations -
  *
  * @param int                         $studentId      Identifiant de l'élève
  * @param DAOKernel_bu_ecole_classe   $classroom      Classe
  * @param int                         $level          Niveau dans la classe
  */
 public static function addStudentAssignment($studentId, $classroom, $level)
 {
     $studentAssignmentDAO = _ioDAO('kernel|kernel_bu_ele_affect');
     $studentAdmissionDAO = _ioDAO('kernel|kernel_bu_eleve_admission');
     $studentRegistrationDAO = _ioDAO('kernel|kernel_bu_eleve_inscription');
     if (!($studentRegistration = $studentRegistrationDAO->getByStudentAndSchool($studentId, $classroom->ecole))) {
         $studentRegistration = _record('kernel|kernel_bu_eleve_inscription');
         $studentRegistration->eleve = $studentId;
         $studentRegistration->annee_scol = $classroom->annee_scol;
         $studentRegistration->date_preinscript = CopixDateTime::timestampToYYYYMMDD(time());
         $studentRegistration->date_effet_preinscript = CopixDateTime::timestampToYYYYMMDD(time());
         $studentRegistration->date_inscript = CopixDateTime::timestampToYYYYMMDD(time());
         $studentRegistration->date_effet_inscript = CopixDateTime::timestampToYYYYMMDD(time());
         $studentRegistration->etablissement = $classroom->ecole;
         $studentRegistration->etablissement_refus = 0;
         $studentRegistration->id_niveau = $level;
         $studentRegistration->id_typ_cla = 11;
         $studentRegistration->vaccins_aj = 0;
         $studentRegistration->attente = 0;
         $studentRegistration->derogation_dem = 0;
         $studentRegistration->temporaire = 0;
         $studentRegistration->current_inscr = 1;
         $studentRegistrationDAO->insert($studentRegistration);
     }
     // Admission de l'élève dans l'école
     if (!($studentAdmission = $studentAdmissionDAO->getByStudentAndSchool($studentId, $classroom->ecole, DAOKernel_bu_eleve_admission::STATE_NEW))) {
         $studentAdmission = _record('kernel|kernel_bu_eleve_admission');
         $studentAdmission->admission_eleve = $studentId;
         $studentAdmission->admission_etablissement = $classroom->ecole;
         $studentAdmission->admission_annee_scol = $classroom->annee_scol;
         $studentAdmission->admission_id_niveau = $level;
         $studentAdmission->admission_etat_eleve = DAOKernel_bu_eleve_admission::STATE_NEW;
         $studentAdmission->admission_date = CopixDateTime::timestampToYYYYMMDD(time());
         $studentAdmission->admission_date_effet = CopixDateTime::timestampToYYYYMMDD(time());
         $studentAdmission->admission_code_radiation = 0;
         $studentAdmission->admission_previsionnel = 0;
         $studentAdmissionDAO->insert($studentAdmission);
     }
     if ($studentAssignment = $studentAssignmentDAO->getByStudentAndClass($studentId, $classroom->id, 1)) {
         $studentAssignment->affect_current = 0;
         $studentAssignmentDAO->update($studentAssignment);
     }
     // Affectation de l'élève dans la classe
     $studentAssignment = _record('kernel|kernel_bu_ele_affect');
     $studentAssignment->affect_eleve = $studentId;
     $studentAssignment->affect_annee_scol = $classroom->annee_scol;
     $studentAssignment->affect_classe = $classroom->id;
     $studentAssignment->affect_niveau = $level;
     $studentAssignment->affect_current = 1;
     $studentAssignment->affect_previsionnel_cl = 0;
     $studentAssignmentDAO->insert($studentAssignment);
 }
 /**
  * retourne la valeur de la variable en fonction de son type, de sa valeur et du type de driver
  *
  * @param string	$pType
  * @param mixed		$pValue
  * @param string $pDriverName
  * @return mixed
  */
 private function _variableValue($pType, $pValue, $pDriverName)
 {
     if ($pDriverName == 'mysql' || $pDriverName == 'sqlite') {
         //Mysql et Sqlite gèrent les mêmes formats d'entrée pour les dates / datetime / time
         switch ($pType) {
             case 'date':
                 return CopixDateTime::yyyymmddToFormat($pValue, 'Y-m-d H:i:s');
             case 'datetime':
                 return CopixDateTime::yyyymmddhhiissToFormat($pValue, 'Y-m-d H:i:s');
             case 'time':
                 return CopixDateTime::hhiissToFormat($pValue, 'Y-m-d H:i:s');
         }
     }
     return $pValue;
 }
 public function processValidateMultipleStudentsListing()
 {
     $ppo = new CopixPPO();
     // Récupération des paramètres
     $ppo->nodeId = _request('id_node', null);
     $ppo->nodeType = _request('type_node', null);
     $nodeInfos = Kernel::getNodeInfo($ppo->nodeType, $ppo->nodeId, true);
     if (is_null($ppo->nodeId) || is_null($ppo->nodeType)) {
         return CopixActionGroup::process('generictools|Messages::getError', array('message' => "Une erreur est survenue.", 'back' => CopixUrl::get('gestionautonome||showTree')));
     }
     $classroomDAO = _ioDAO('kernel|kernel_bu_ecole_classe');
     if (!$classroomDAO->get($ppo->nodeId)) {
         return CopixActionGroup::process('generictools|Messages::getError', array('message' => "Une erreur est survenue.", 'back' => CopixUrl::get('gestionautonome||showTree')));
     }
     _currentUser()->assertCredential('module:classroom|' . $ppo->nodeId . '|student|create@gestionautonome');
     // Récupération des informations du formulaire
     $keys = _request('keys', array());
     // Elèves de la liste à créer (checkbox de confirmation)
     $logins = _request('logins', array());
     // Logins des élèves (possibilité de changer le login généré)
     $passwords = _request('passwords', array());
     // Passwords des élèves (possibilité de changer le mot de passe généré)
     $levels = _request('levels', array());
     // Niveau des élèves dans la classe
     // Récupération des élèves déjà créés en session
     if (!($ppo->studentsSuccess = _sessionGet('gestionautonome|addMultipleStudents|success'))) {
         $ppo->studentsSuccess = array();
     }
     // RAZ des créations en erreur
     _sessionSet('gestionautonome|addMultipleStudents|error', array());
     // DAO
     $studentDAO = _ioDAO('kernel_bu_eleve');
     $studentRegistrationDAO = _ioDAO('kernel|kernel_bu_eleve_inscription');
     $studentAdmissionDAO = _ioDAO('kernel|kernel_bu_eleve_admission');
     $studentAssignmentDAO = _ioDAO('kernel_bu_eleve_affectation');
     $dbuserDAO = _ioDAO('kernel|kernel_copixuser');
     $dbLinkDAO = _ioDAO('kernel_link_bu2user');
     $classDAO = _ioDAO('kernel|kernel_bu_ecole_classe');
     $personDAO = _ioDAO('kernel_bu_responsable');
     $personLinkDAO = _ioDAO('kernel_bu_responsables');
     $schoolClassLevelDAO = _ioDAO('kernel|kernel_bu_ecole_classe_niveau');
     $node_infos = Kernel::getNodeInfo($ppo->nodeType, $ppo->nodeId, false);
     // Récupération des élèves en création
     $studentsInSession = _sessionGet('gestionautonome|addMultipleStudents');
     // Récupération des données nécessaires à l'ajout des enregistrements inscription / adhésion / admission
     $class = $classDAO->get($ppo->nodeId);
     $schoolClassLevels = $schoolClassLevelDAO->getByClass($ppo->nodeId);
     $classType = $schoolClassLevels[0]->type;
     $schoolId = $class->ecole;
     // Récupération de l'année scolaire
     if (is_null($grade = _sessionGet('grade'))) {
         $grade = Kernel::getAnneeScolaireCourante()->id_as;
     }
     // Boucle sur les élèves de la liste à créer
     $students = array();
     foreach ($keys as $key) {
         // La création n'est possible que si le login est disponible
         if (!is_null($logins[$key]) && !is_null($passwords[$key]) && Kernel::isLoginAvailable($logins[$key])) {
             $students[$key] = $studentsInSession[$key];
             $students[$key]['login'] = $logins[$key];
             // Récupération des logins pour les élèves en création
             $students[$key]['password'] = $passwords[$key];
             // Récupération des passwords pour les élèves en création
             $students[$key]['level'] = $levels[$key];
             // Récupération des niveaux pour les élèves en création
             $students[$key]['type_nom'] = Kernel::Code2Name('USER_ELE');
             $students[$key]['node_nom'] = Kernel::Code2Name($ppo->nodeType) . " " . $node_infos['nom'];
             // Création de l'élève
             $ppo->student = _record('kernel_bu_eleve');
             $ppo->student->numero = '';
             $ppo->student->nom = $students[$key]['lastname'];
             $ppo->student->prenom1 = $students[$key]['firstname'];
             $ppo->student->id_sexe = $students[$key]['gender'];
             $ppo->student->date_nais = isset($students[$key]['birthdate']) ? CopixDateTime::dateToYYYYMMDD(strip_tags(trim($students[$key]['birthdate']))) : '';
             $ppo->student->flag = 0;
             $ppo->student->ele_last_update = CopixDateTime::timestampToYYYYMMDDHHIISS(time());
             $studentDAO->insert($ppo->student);
             $students[$key]['id'] = $ppo->student->idEleve;
             // Création du compte dbuser
             $dbuser = _record('kernel|kernel_copixuser');
             $dbuser->login_dbuser = $students[$key]['login'];
             $dbuser->password_dbuser = md5($students[$key]['password']);
             $dbuser->email_dbuser = '';
             $dbuser->enabled_dbuser = 1;
             $dbuserDAO->insert($dbuser);
             // Création du link bu2user
             $dbLink = _record('kernel_link_bu2user');
             $dbLink->user_id = $dbuser->id_dbuser;
             $dbLink->bu_type = 'USER_ELE';
             $dbLink->bu_id = $ppo->student->idEleve;
             $dbLinkDAO->insert($dbLink);
             // Inscription de l'élève dans l'école
             $studentRegistration = _record('kernel|kernel_bu_eleve_inscription');
             $studentRegistration->eleve = $ppo->student->idEleve;
             $studentRegistration->annee_scol = $grade;
             $studentRegistration->date_preinscript = CopixDateTime::timestampToYYYYMMDD(time());
             $studentRegistration->date_effet_preinscript = CopixDateTime::timestampToYYYYMMDD(time());
             $studentRegistration->date_inscript = CopixDateTime::timestampToYYYYMMDD(time());
             $studentRegistration->date_effet_inscript = CopixDateTime::timestampToYYYYMMDD(time());
             $studentRegistration->etablissement = $schoolId;
             $studentRegistration->etablissement_refus = 0;
             $studentRegistration->id_niveau = $students[$key]['level'];
             $studentRegistration->id_typ_cla = $classType;
             $studentRegistration->vaccins_aj = 0;
             $studentRegistration->attente = 0;
             $studentRegistration->derogation_dem = 0;
             $studentRegistration->temporaire = 0;
             $studentRegistration->current_inscr = 1;
             $studentRegistrationDAO->insert($studentRegistration);
             // Admission de l'élève dans l'école
             $studentAdmission = _record('kernel|kernel_bu_eleve_admission');
             $studentAdmission->admission_eleve = $ppo->student->idEleve;
             $studentAdmission->admission_etablissement = $schoolId;
             $studentAdmission->admission_annee_scol = $grade;
             $studentAdmission->admission_id_niveau = $students[$key]['level'];
             $studentAdmission->admission_etat_eleve = 1;
             $studentAdmission->admission_date = CopixDateTime::timestampToYYYYMMDD(time());
             $studentAdmission->admission_date_effet = CopixDateTime::timestampToYYYYMMDD(time());
             $studentAdmission->admission_code_radiation = 0;
             $studentAdmission->admission_previsionnel = 0;
             $studentAdmissionDAO->insert($studentAdmission);
             // Affectation de l'élève dans les classes
             $studentAssignment = _record('kernel_bu_eleve_affectation');
             $studentAssignment->eleve = $ppo->student->idEleve;
             $studentAssignment->annee_scol = $grade;
             $studentAssignment->classe = $ppo->nodeId;
             $studentAssignment->niveau = $students[$key]['level'];
             $studentAssignment->dateDebut = CopixDateTime::timestampToYYYYMMDD(time());
             $studentAssignment->current = 1;
             $studentAssignment->previsionnel_cl = 0;
             $studentAssignmentDAO->insert($studentAssignment);
             // Récupération des responsables sélectionnés pour l'élève
             $personsKeys = _request('person-keys' . $key, array());
             $personsLogins = _request('logins' . $key, array());
             // Récupération des logins des responsables de l'élève
             $personsPasswords = _request('passwords' . $key, array());
             // Récupération des passwords des responsables de l'élève
             $students[$key]['person'] = array();
             foreach ($personsKeys as $personKey) {
                 // La création du responsable n'est possible que si le login est disponible
                 if (!is_null($personsLogins[$personKey]) && !is_null($personsPasswords[$personKey]) && Kernel::isLoginAvailable($personsLogins[$personKey])) {
                     $students[$key]['person'][$personKey] = $studentsInSession[$key]['person'][$personKey];
                     $students[$key]['person'][$personKey]['login'] = $personsLogins[$personKey];
                     $students[$key]['person'][$personKey]['password'] = $personsPasswords[$personKey];
                     $students[$key]['person'][$personKey]['type_nom'] = Kernel::Code2Name('USER_RES');
                     $students[$key]['person'][$personKey]['node_nom'] = Kernel::Code2Name($ppo->nodeType) . " " . $node_infos['nom'];
                     // Création du responsable
                     $ppo->person = _record('kernel_bu_responsable');
                     $ppo->person->nom = $students[$key]['person'][$personKey]['lastname'];
                     $ppo->person->prenom1 = $students[$key]['person'][$personKey]['firstname'];
                     $ppo->person->id_sexe = $students[$key]['person'][$personKey]['gender'];
                     $personDAO->insert($ppo->person);
                     $students[$key]['person'][$personKey]['id'] = $ppo->person->numero;
                     // Création du compte dbuser
                     $dbuser = _record('kernel|kernel_copixuser');
                     $dbuser->login_dbuser = $students[$key]['person'][$personKey]['login'];
                     $dbuser->password_dbuser = md5($students[$key]['person'][$personKey]['password']);
                     $dbuser->email_dbuser = '';
                     $dbuser->enabled_dbuser = 1;
                     $dbuserDAO->insert($dbuser);
                     // Création du link bu2user
                     $dbLink = _record('kernel_link_bu2user');
                     $dbLink->user_id = $dbuser->id_dbuser;
                     $dbLink->bu_type = 'USER_RES';
                     $dbLink->bu_id = $ppo->person->numero;
                     $dbLinkDAO->insert($dbLink);
                     // Création de l'association personne->rôle
                     $newPersonLink = _record('kernel_bu_responsables');
                     $newPersonLink->id_beneficiaire = $ppo->student->idEleve;
                     $newPersonLink->type_beneficiaire = 'eleve';
                     $newPersonLink->id_responsable = $ppo->person->numero;
                     $newPersonLink->type = 'responsable';
                     $newPersonLink->auth_parentale = '0';
                     $newPersonLink->id_par = $students[$key]['person'][$personKey]['id_par'];
                     $personLinkDAO->insert($newPersonLink);
                 }
             }
             // Récupération de l'élève (et de ses responsables) dans le tableau des élèves créés avec succès
             $ppo->studentsSuccess[] = $students[$key];
         } else {
             // Ajout de l'élève (et de ses responsables) dans le tableau des créations en erreur
             $ppo->studentsError[] = $students[$key];
         }
     }
     // Si des créations ont bien eu lieu, les mettre en session pour affichage de confirmation
     if (!empty($ppo->studentsSuccess)) {
         _sessionSet('gestionautonome|addMultipleStudents|success', $ppo->studentsSuccess);
     }
     // Si des créations sont en erreur, les mettre en session pour possibilité de recréation après correction des erreurs
     if (!empty($ppo->studentsError)) {
         _sessionSet('gestionautonome|addMultipleStudents|error', $ppo->studentsError);
         $ppo->students = $ppo->studentsError;
         _sessionSet('gestionautonome|addMultipleStudents', $ppo->studentsError);
         // Récupération des niveaux de la classe
         $classSchoolLevelDAO = _ioDAO('kernel|kernel_bu_ecole_classe_niveau');
         $classLevelDAO = _ioDAO('kernel|kernel_bu_classe_niveau');
         $classSchoolLevels = $classSchoolLevelDAO->getByClass($ppo->nodeId);
         $ppo->levelNames = array();
         $ppo->levelIds = array();
         foreach ($classSchoolLevels as $classSchoolLevel) {
             $level = $classLevelDAO->get($classSchoolLevel->niveau);
             $ppo->levelNames[] = $level->niveau_court;
             $ppo->levelIds[] = $level->id_n;
         }
         // Flag pour affichage du message d'erreur
         $ppo->error = 1;
         // Get vocabulary catalog to use
         $nodeVocabularyCatalogDAO = _ioDAO('kernel|kernel_i18n_node_vocabularycatalog');
         $ppo->vocabularyCatalog = $nodeVocabularyCatalogDAO->getCatalogForNode($ppo->nodeType, $ppo->nodeId);
         // Breadcrumbs
         $breadcrumbs = Kernel::generateBreadcrumbs($nodeInfos);
         $breadcrumbs[] = array('txt' => CopixCustomI18N::get('gestionautonome|gestionautonome.message.add%%structure_element_persons%%list', array('catalog' => $ppo->vocabularyCatalog->id_vc)));
         $ppo->breadcrumbs = Kernel::PetitPoucet($breadcrumbs, ' &raquo; ');
         $ppo->TITLE_PAGE = CopixConfig::get('gestionautonome|moduleTitle');
         // Get vocabulary catalog to use
         $nodeVocabularyCatalogDAO = _ioDAO('kernel|kernel_i18n_node_vocabularycatalog');
         $ppo->vocabularyCatalog = $nodeVocabularyCatalogDAO->getCatalogForNode($ppo->nodeType, $ppo->nodeId);
         return _arPPO($ppo, 'add_multiple_students_listing.tpl');
     }
     // Mise en session des comptes créés
     $passwordsList = _sessionGet('modules|gestionautonome|passwordsList');
     if (!is_array($passwordsList)) {
         $passwordsList = array();
     }
     foreach ($ppo->studentsSuccess as $student) {
         $studentAr = array('lastname' => $student['lastname'], 'firstname' => $student['firstname'], 'login' => $student['login'], 'password' => $student['password'], 'bu_type' => 'USER_ELE', 'bu_id' => $student['id'], 'type_nom' => Kernel::Code2Name('USER_ELE'), 'node_nom' => Kernel::Code2Name('BU_CLASSE') . ' ' . $nodeInfos['nom'], 'gender' => $student['gender']);
         $passwordsList['USER_ELE'][$student['id']] = $studentAr;
         // Enregistrement des personnes
         if (!empty($student['person'])) {
             foreach ($student['person'] as $person) {
                 $personAr = array('lastname' => $person['lastname'], 'firstname' => $person['firstname'], 'login' => $person['login'], 'password' => $person['password'], 'bu_type' => 'USER_RES', 'bu_id' => $person['id'], 'type_nom' => Kernel::Code2Name('USER_RES'), 'node_nom' => Kernel::Code2Name('BU_CLASSE') . ' ' . $nodeInfos['nom'], 'gender' => $person['gender']);
                 $passwordsList['USER_RES'][$person['id']] = $personAr;
             }
         }
     }
     $passwordsList = _sessionSet('modules|gestionautonome|passwordsList', $passwordsList);
     return _arRedirect(CopixUrl::get('gestionautonome||showMultipleAccountsListing'));
 }
 public function publish($id, $data)
 {
     $articleDAO = _dao('blog|blogarticle');
     $article = _record('blog|blogarticle');
     $article->id_blog = $id;
     $article->name_bact = $data['title'];
     $article->format_bact = 'wiki';
     $article->sumary_bact = $data['body'];
     $article->sumary_html_bact = smarty_modifier_blog_format_article($article->sumary_bact, $article->format_bact);
     $article->content_bact = '';
     $article->content_html_bact = smarty_modifier_blog_format_article($article->content_bact, $article->format_bact);
     $article->author_bact = 'Publication par mail...';
     $article->date_bact = CopixDateTime::dateToTimestamp(date('d/m/Y'));
     $article->time_bact = timeToBD(date('H:i'));
     $article->url_bact = killBadUrlChars($article->name_bact);
     $article->sticky_bact = 0;
     $article->is_online = 1;
     $articleDAO->insert($article);
     $article->url_bact = killBadUrlChars($article->id_bact . '-' . $article->name_bact);
     $articleDAO->update($article);
     return "yo" . print_r($article, true) . "yo";
 }
 /**
  * Construction du code HTML
  * On utilise également les modifications d'en tête HTML
  */
 public function process($pParams, $pContent = null)
 {
     extract($pParams);
     if (empty($name)) {
         throw new CopixTemplateTagException('[calendar] missing name parameter');
     }
     if (empty($image)) {
         $image = '"' . _resource("img/tools/calendar.png") . '"';
     } else {
         $image = '"' . $image . '"';
     }
     if (empty($extra)) {
         $extra = '';
     }
     if (empty($size)) {
         $size = 8;
     }
     if (!isset($mask)) {
         $mask = true;
     }
     _tag('mootools', array('plugin' => array('datepicker')));
     if ($mask) {
         _tag('mootools', array('plugin' => array('imask')));
         CopixHTMLHeader::addJsCode("\n             window.addEvent('domready', function () {\n                    new iMask({\n                         onFocus: function(obj) {\n                         },\n\n                         onBlur: function(obj) {\n                         },\n\n                         onValid: function(event, obj) {\n                         },\n\n                         onInvalid: function(event, obj) {\n                             if(!event.shift) {\n                             }\n                         }\n                     });\n             });\n             ", 'calendarmask');
     }
     if (empty($lang)) {
         $lang = CopixI18N::getLang();
     }
     if (empty($format)) {
         $format = str_replace(array('d', 'm', 'Y'), array('dd', 'mm', 'yyyy'), CopixI18N::getDateFormat('/'));
     } else {
         $format = strtolower($format);
     }
     $maskFormat = str_replace(array('d', 'm', 'y'), array('9', '9', '9'), $format);
     if (!empty($yyyymmdd)) {
         $value = date(str_replace(array('dd', 'mm', 'yyyy'), array('d', 'm', 'Y'), $format), CopixDateTime::yyyymmddToTimestamp($yyyymmdd));
     }
     if (!empty($timestamp)) {
         $value = date(str_replace(array('dd', 'mm', 'yyyy'), array('d', 'm', 'Y'), $format), $timestamp);
     }
     if (empty($sizeday)) {
         $sizeday = 3;
     }
     if (!isset($beforeyear)) {
         $beforeyear = 10;
     }
     if (!isset($afteryear)) {
         $afteryear = 10;
     }
     if (!isset($duration)) {
         $duration = 500;
     }
     if (!isset($closebuttonsrc)) {
         $closebuttonsrc = null;
     } else {
         $closebuttonsrc = _resource($closebuttonsrc);
     }
     if (!isset($draggable)) {
         $draggable = true;
     }
     $draggable = $draggable ? 'true' : 'false';
     if (!isset($title)) {
         $title = null;
     }
     if (empty($value)) {
         if ($mask) {
             $value = str_replace('9', '_', $maskFormat);
         } else {
             $value = null;
         }
     }
     $strMask = '';
     if ($mask) {
         $strMask = 'style="text-align:center" class="iMask" alt="{  type:\'fixed\', mask:\'' . $maskFormat . '\', stripMask: false }"';
     }
     $out = '<input type="text" id="' . $name . '" name="' . $name . '" value="' . _copix_utf8_htmlentities($value) . '" ' . $extra . ' size="' . $size . '" ';
     //name of the input.
     if (!empty($tabindex)) {
         $out .= ' tabindex="' . $tabindex . '" ';
     }
     $out .= $strMask . ' />' . "\n\r";
     $out .= '<script type="text/javascript">' . "\n\r";
     $out .= "\$('" . $name . "').makeDatePicker({draggable:{$draggable}, title: '" . str_replace("'", "\\'", $title) . "', closebuttonsrc: '" . $closebuttonsrc . "', value: '" . $value . "', format: '" . $format . "', language: '" . $lang . "', sizeday:" . $sizeday . ", beforeyear:" . $beforeyear . ", afteryear:" . $afteryear . ", duration:" . $duration . ", imageCalendar:" . $image;
     //class du calendrier.
     if (!empty($classe)) {
         $out .= ', classe:"' . $classe . '"';
     }
     $out .= "});" . "\n\r";
     return $out .= '</script>';
 }
 /**
  * Edition d'un mémo - * Enseignant *
  */
 public function processEditerMemo()
 {
     $ppo = new CopixPPO();
     if (is_null($ppo->cahierId = _request('cahierId', null))) {
         return CopixActionGroup::process('generictools|Messages::getError', array('message' => CopixI18N::get('kernel|kernel.error.errorOccurred'), 'back' => CopixUrl::get('')));
     } elseif (Kernel::getLevel('MOD_CAHIERDETEXTES', $ppo->cahierId) < PROFILE_CCV_PUBLISH) {
         return CopixActionGroup::process('genericTools|Messages::getError', array('message' => CopixI18N::get('kernel|kernel.error.noRights'), 'back' => CopixUrl::get('')));
     }
     // Récupération des paramètres
     $ppo->jour = _request('jour', date('d'));
     $ppo->mois = _request('mois', date('m'));
     $ppo->annee = _request('annee', date('Y'));
     $ppo->msgSuccess = _request('msgSuccess', false);
     $ppo->dateSelectionnee = mktime(0, 0, 0, $ppo->mois, $ppo->jour, $ppo->annee);
     $ppo->format = CopixConfig::get('cahierdetextes|format_par_defaut');
     $cahierInfos = Kernel::getModParent('MOD_CAHIERDETEXTES', $ppo->cahierId);
     $ppo->nodeInfos = array('type' => $cahierInfos[0]->module_type, 'id' => $cahierInfos[0]->module_id);
     if (is_null($memoId = _request('memoId', null))) {
         $ppo->memo = _record('cahierdetextes|cahierdetextesmemo');
     } else {
         $memoDAO = _ioDAO('cahierdetextes|cahierdetextesmemo');
         $ppo->memo = $memoDAO->get($memoId);
         $ppo->memo->date_creation = CopixDateTime::yyyymmddToDate($ppo->memo->date_creation);
         $ppo->memo->date_validite = CopixDateTime::yyyymmddToDate($ppo->memo->date_validite);
         $ppo->memo->date_max_signature = CopixDateTime::yyyymmddToDate($ppo->memo->date_max_signature);
         // Récupération des élèves liés au mémo
         $memo2eleveDAO = _ioDAO('cahierdetextes|cahierdetextesmemo2eleve');
         $ppo->elevesSelectionnes = $memo2eleveDAO->findElevesParMemo($ppo->memo->id);
         // Récupération des fichiers liés au mémo
         $fichierMalleDAO = _ioDAO('malle|malle_files');
         $fichierClasseurDAO = _ioDAO('classeur|classeurfichier');
         $memo2fichiersDAO = _ioDAO('cahierdetextes|cahierdetextesmemo2files');
         $memo2fichiers = $memo2fichiersDAO->retrieveByMemo($ppo->memo->id);
         $ppo->fichiers = array();
         $fichiers = array();
         foreach ($memo2fichiers as $memo2fichier) {
             if ($memo2fichier->module_file == 'MOD_MALLE') {
                 if ($fichier = $fichierMalleDAO->get($memo2fichier->file_id)) {
                     $ppo->fichiers[] = array('type' => $memo2fichier->module_file, 'id' => $memo2fichier->file_id, 'nom' => $fichier->nom);
                 }
             } elseif ($memo2fichier->module_file == 'MOD_CLASSEUR') {
                 if ($fichier = $fichierClasseurDAO->get($memo2fichier->file_id)) {
                     $ppo->fichiers[] = array('type' => $memo2fichier->module_file, 'id' => $memo2fichier->file_id, 'nom' => $fichier);
                 }
             }
         }
     }
     if (CopixRequest::isMethod('post')) {
         $cahierInfos = Kernel::getModParent('MOD_CAHIERDETEXTES', $ppo->cahierId);
         $ppo->memo->classe_id = $cahierInfos[0]->node_id;
         $ppo->memo->date_creation = CopixDateTime::dateToyyyymmdd(_request('memo_date_creation', null));
         $ppo->memo->date_validite = CopixDateTime::dateToyyyymmdd(_request('memo_date_validite', null));
         $ppo->memo->message = _request('memo_message', null);
         $ppo->memo->avec_signature = _request('memo_avec_signature', 0);
         $ppo->memo->date_max_signature = CopixDateTime::dateToyyyymmdd(_request('memo_date_max_signature', null));
         $ppo->memo->supprime = 0;
         $ppo->elevesSelectionnes = _request('eleves', array());
         $ppo->fichiers = _request('memo_fichiers', array());
         // Traitement des erreurs
         $ppo->erreurs = array();
         if ($ppo->memo->date_creation == '') {
             $ppo->erreurs[] = CopixI18N::get('cahierdetextes|cahierdetextes.error.noCreationDate');
         }
         if ($ppo->memo->date_validite == '') {
             $ppo->erreurs[] = CopixI18N::get('cahierdetextes|cahierdetextes.error.noValidityDate');
         }
         if (!is_null($ppo->memo->date_validite) && $ppo->memo->date_validite < $ppo->memo->date_creation) {
             $ppo->erreurs[] = CopixI18N::get('cahierdetextes|cahierdetextes.error.wrongValidityDate');
         }
         if ($ppo->memo->message == '') {
             $ppo->erreurs[] = CopixI18N::get('cahierdetextes|cahierdetextes.error.noContent');
         }
         if ($ppo->memo->avec_signature && $ppo->memo->date_max_signature == '') {
             $ppo->erreurs[] = CopixI18N::get('cahierdetextes|cahierdetextes.error.noSignatureDate');
         }
         if (!is_null($ppo->memo->date_max_signature) && !is_null($ppo->memo->date_validite) && ($ppo->memo->date_max_signature > $ppo->memo->date_validite || $ppo->memo->date_max_signature < $ppo->memo->date_creation)) {
             $ppo->erreurs[] = CopixI18N::get('cahierdetextes|cahierdetextes.error.wrongMaxSignatureDate');
         }
         if (empty($ppo->elevesSelectionnes)) {
             $ppo->erreurs[] = CopixI18N::get('cahierdetextes|cahierdetextes.error.noStudents');
         }
         if (!empty($ppo->fichiers)) {
             $ppo->fichiers = array_unique($ppo->fichiers);
             // Récupération de l'identifiant de la malle du node
             $mods = Kernel::getModEnabled($cahierInfos[0]->node_type, $cahierInfos[0]->node_id);
             if ($malle = Kernel::filterModuleList($mods, 'MOD_MALLE')) {
                 $malleId = $malle[0]->module_id;
             }
             // Récupération des identifiants de classeur
             $classeurIds = array();
             // Classeur du node
             $mods = Kernel::getModEnabled($cahierInfos[0]->node_type, $cahierInfos[0]->node_id);
             if ($classeur = Kernel::filterModuleList($mods, 'MOD_CLASSEUR')) {
                 $classeurIds[] = $classeur[0]->module_id;
             }
             // Classeur personnel
             $mods = Kernel::getModEnabled(_currentUser()->getExtra('type'), _currentUser()->getExtra('id'));
             if ($classeur = Kernel::filterModuleList($mods, 'MOD_CLASSEUR')) {
                 $classeurIds[] = $classeur[0]->module_id;
             }
             // On détermine s'il s'agit de documents de la malle ou du classeur
             foreach ($ppo->fichiers as $fichierInfos) {
                 $fichierInfos = explode('-', $fichierInfos);
                 if ($fichierInfos[0] == 'MOD_MALLE') {
                     // Erreur : le fichier n'appartient pas à la malle du node
                     if (!$fichierMalleDAO->isFileOfMalle($fichierInfos[1], $malleId)) {
                         $ppo->erreurs[] = CopixI18N::get('cahierdetextes|cahierdetextes.error.invalidFile');
                         break;
                     } else {
                         $fichier = $fichierMalleDAO->get($fichierInfos[1]);
                         $fichiers[] = array('type' => $fichierInfos[0], 'id' => $fichierInfos[1], 'nom' => $fichier->nom);
                     }
                 } elseif ($fichierInfos[0] == 'MOD_CLASSEUR') {
                     $fichier = $fichierClasseurDAO->get($fichierInfos[1]);
                     // Erreur : le fichier n'appartient pas aux classeurs disponible à l'utilisateur
                     if (!in_array($fichier->classeur_id, $classeurIds)) {
                         $ppo->erreurs[] = CopixI18N::get('cahierdetextes|cahierdetextes.error.invalidFile');
                         break;
                     } else {
                         $fichiers[] = array('type' => $fichierInfos[0], 'id' => $fichierInfos[1], 'nom' => $fichier);
                     }
                 }
             }
         }
         if (!empty($ppo->erreurs)) {
             $ppo->memo->date_creation = _request('memo_date_creation', null);
             $ppo->memo->date_validite = _request('memo_date_validite', null);
             $ppo->memo->date_max_signature = _request('memo_date_max_signature', null);
             if (isset($fichiers)) {
                 $ppo->fichiers = $fichiers;
             }
             $modParentInfo = Kernel::getModParentInfo('MOD_CAHIERDETEXTES', $ppo->cahierId);
             $ppo->TITLE_PAGE = $modParentInfo['nom'];
             return _arPPO($ppo, 'editer_memo.tpl');
         }
         $memoDAO = _ioDAO('cahierdetextes|cahierdetextesmemo');
         $memo2eleveDAO = _ioDAO('cahierdetextes|cahierdetextesmemo2eleve');
         $memo2fichierDAO = _ioDAO('cahierdetextes|cahierdetextesmemo2files');
         // Création
         if ($ppo->memo->id == '') {
             // Insertion de l'enregistrement "memo"
             $memoDAO->insert($ppo->memo);
         } else {
             // Mise à jour de l'enregistrement "memo"
             $memoDAO->update($ppo->memo);
             // Suppression des relations memo - eleves existantes
             $memo2eleveDAO->deleteByMemo($ppo->memo->id);
             // Suppression des relations memo - fichiers existantes
             $memo2fichierDAO->deleteByMemo($ppo->memo->id);
         }
         // Insertion des nouveaux liens memo > eleve
         foreach ($ppo->elevesSelectionnes as $eleveId) {
             $memo2eleve = _record('cahierdetextes|cahierdetextesmemo2eleve');
             $memo2eleve->memo_id = $ppo->memo->id;
             $memo2eleve->eleve_id = $eleveId;
             $memo2eleveDAO->insert($memo2eleve);
         }
         // Insertion des liens "mémo > fichiers"
         if (!empty($fichiers)) {
             foreach ($fichiers as $fichier) {
                 $memo2fichier = _record('cahierdetextes|cahierdetextesmemo2files');
                 $memo2fichier->memo_id = $ppo->memo->id;
                 $memo2fichier->module_file = $fichier['type'];
                 $memo2fichier->file_id = $fichier['id'];
                 $memo2fichierDAO->insert($memo2fichier);
             }
         }
         return _arRedirect(CopixUrl::get('cahierdetextes||voirMemos', array('cahierId' => $ppo->cahierId, 'msgSuccess' => CopixI18N::get('cahierdetextes|cahierdetextes.message.success'))));
     }
     $modParentInfo = Kernel::getModParentInfo('MOD_CAHIERDETEXTES', $ppo->cahierId);
     $ppo->TITLE_PAGE = $modParentInfo['nom'];
     return _arPPO($ppo, 'editer_memo.tpl');
 }
 /**
  * Enregistrement de la modification d'un membre d'un groupe
  *
  * @author Christophe Beyer <*****@*****.**>
  * @since 2007/01/09
  * @param integer $id Id du groupe
  * @param string $user_type Type du membre
  * @param integer $user_id Id du membre
  * @param integer $droit Son nouveau droit
  * @param string $debut Sa nouvelle date de d�but de validit�
  * @param string $fin Sa nouvelle date de fin de validit�
  */
 public function doModifyMember()
 {
     $dao = CopixDAOFactory::create("groupe");
     $kernel_service =& CopixClassesFactory::Create('kernel|kernel');
     $groupeService =& CopixClassesFactory::Create('groupe|groupeService');
     $id = $this->getRequest('id', null);
     $user_type = $this->getRequest('user_type', null);
     $user_id = $this->getRequest('user_id', null);
     $droit = $this->getRequest('droit', null);
     $req_debut = $this->getRequest('debut', null);
     $req_fin = $this->getRequest('fin', null);
     //$debut     = dateService::dateFrToDateBdd($req_debut);
     //$fin     = dateService::dateFrToDateBdd($req_fin);
     $debut = CopixDateTime::dateToTimestamp($req_debut);
     $fin = CopixDateTime::dateToTimestamp($req_fin);
     $critical_errors = $errors = array();
     $groupe = $dao->getGroupe($id);
     if (!$groupe) {
         $critical_errors[] = CopixI18N::get('groupe|groupe.error.noGroup');
     } else {
         $mondroit = $kernel_service->getLevel("CLUB", $id);
         if (!$groupeService->canMakeInGroupe('ADMIN', $mondroit)) {
             $critical_errors[] = CopixI18N::get('kernel|kernel.error.noRights');
         } else {
             // On v�rifie que le membre demand� fait bien partie du groupe /* et qu'il n'est pas le propri�taire */
             $level = Kernel::getLevel('CLUB', $id, $user_type, $user_id);
             if ($level <= PROFILE_CCV_SHOW) {
                 $critical_errors[] = CopixI18N::get('kernel|kernel.error.noRights');
             }
         }
     }
     if ($critical_errors) {
         return CopixActionGroup::process('genericTools|Messages::getError', array('message' => implode('<br/>', $critical_errors), 'back' => CopixUrl::get('groupe||')));
     } else {
         // Tests sur les dates
         if ($req_debut) {
             if (CopixDateTime::timestampToDate($debut) === false) {
                 $errors[] = CopixI18N::get('groupe|groupe.error.formdatedeb');
             }
         }
         if ($req_fin) {
             if (CopixDateTime::timestampToDate($fin) === false) {
                 $errors[] = CopixI18N::get('groupe|groupe.error.formdatefin');
             }
         }
         if ($req_debut && $req_fin && $debut && $fin && $debut > $fin) {
             $errors[] = CopixI18N::get('groupe|groupe.error.inversiondate');
         }
         if ($droit && !$errors) {
             $dao = CopixDAOFactory::create("kernel|kernel_link_user2node");
             $his = $dao->get($user_type, $user_id, "CLUB", $id);
             $his->droit = $droit;
             $his->debut = $debut ? $debut : NULL;
             $his->fin = $fin ? $fin : NULL;
             $dao->update($his);
         }
         if ($errors) {
             return CopixActionGroup::process('groupe|groupe::getHomeAdminMember', array('id' => $id, 'user_type' => $user_type, 'user_id' => $user_id, 'droit' => $droit, 'debut' => $req_debut, 'fin' => $req_fin, 'errors' => $errors));
         }
         return new CopixActionReturn(COPIX_AR_REDIRECT, CopixUrl::get('groupe||getHomeAdminMembers', array("id" => $id)));
     }
 }
/**
 * Plugin smarty type modifier
 * Purpose:  format a time given by its timestamp (HHMMSS) to a time (HH:MM:SS)
 * if an incorrect date is given, returns the string without any modification
 * Input: HHMMSS
 * Output: HH:MM:SS
 * Example:  {$time|time}
 * @return string
 */
function smarty_modifier_time($string)
{
    return ($time = CopixDateTime::hhmmssToTime($string)) !== false ? $time : $string;
}
 /**
  * Validation d'un article.
  */
 public function doValidArticle()
 {
     CopixHTMLHeader::addJSLink(_resource("js/jquery/jquery.ui.datepicker-fr.js"));
     $id_blog = $this->getRequest('id_blog', null);
     $go = $this->getRequest('go', 'preview');
     //die ("go=$go");
     if ($id_blog == null) {
         return CopixActionGroup::process('genericTools|Messages::getError', array('message' => CopixI18N::get('blog.error.param'), 'back' => CopixUrl::get('blog|admin|listBlog')));
     }
     if (!BlogAuth::canMakeInBlog('ADMIN_ARTICLES', create_blog_object($id_blog))) {
         return CopixActionGroup::process('genericTools|Messages::getError', array('message' => CopixI18N::get('blog.error.cannotManageCategory'), 'back' => CopixUrl::get('blog|admin|listBlog')));
     }
     $tpl = new CopixTpl();
     // On r�cup�re l'utilisateur connect�
     $user = BlogAuth::getUserInfos();
     $articleDAO = CopixDAOFactory::create('blog|blogarticle');
     // Cat�gories coch�es...
     $tabSelectCat = array();
     if (_request('tabSelectCat')) {
         $tabSelectCat = (array) _request('tabSelectCat');
     }
     $id_bact = $this->getRequest('id_bact', null);
     if (strlen($id_bact) == 0) {
         $id_bact = null;
     }
     $showErrors = false;
     if ($id_bact != null) {
         // EDITION D'UN ARTICLE
         $article = $articleDAO->get($id_bact);
         $this->_validFromPostProperties($article);
         if (!$article->date_bact) {
             $article->date_bact = date('d/m/Y');
         }
         if (!$article->time_bact) {
             $article->time_bact = date('H:i');
         }
         $article->date_bact = CopixDateTime::dateToTimestamp($article->date_bact);
         $article->time_bact = timeToBD($article->time_bact);
         $article->author_bact = $user->userId;
         $tpl->assign('TITLE_PAGE', CopixI18N::get('blog.get.edit.article.title'));
         //print_r($article);
         $errors = $articleDAO->check($article);
         if (count($tabSelectCat) == 0) {
             $errors = array();
             array_push($errors, CopixI18N::get('blog.error.nocategoryselect'));
         }
         if ($errors != 1) {
             // Traitement des erreurs
             $showErrors = true;
         } elseif ($go == 'save') {
             // Modification dans la base
             $article->url_bact = killBadUrlChars($article->id_bact . '-' . $article->name_bact);
             $article->sumary_html_bact = smarty_modifier_blog_format_article($article->sumary_bact, $article->format_bact);
             $article->content_html_bact = smarty_modifier_blog_format_article($article->content_bact, $article->format_bact);
             $articleDAO->update($article);
             // Insertion dans la base blogarticle_blogarticlecategory
             $artctgDAO = CopixDAOFactory::create('blog|blogarticle_blogarticlecategory');
             $artctgDAO->deleteAndInsert($article->id_bact, $tabSelectCat);
             return new CopixActionReturn(COPIX_AR_REDIRECT, CopixUrl::get('blog|admin|showBlog', array("id_blog" => $id_blog, "kind" => $this->getRequest('kind', '0'))));
         }
     } else {
         // CREATION D'UN ARTICLE
         $article = CopixDAOFactory::createRecord('blogarticle');
         $this->_validFromPostProperties($article);
         if (!$article->date_bact) {
             $article->date_bact = date('d/m/Y');
         }
         if (!$article->time_bact) {
             $article->time_bact = date('H:i');
         }
         $article->date_bact = CopixDateTime::dateToTimestamp($article->date_bact);
         $article->time_bact = timeToBD($article->time_bact);
         $article->author_bact = $user->userId;
         $tpl->assign('TITLE_PAGE', CopixI18N::get('blog.get.create.article.title'));
         $errors = $articleDAO->check($article);
         if (count($tabSelectCat) == 0) {
             $errors = array();
             array_push($errors, CopixI18N::get('blog.error.nocategoryselect'));
         }
         if ($errors != 1) {
             // Traitement des erreurs
             $showErrors = true;
         } elseif ($go == 'save') {
             // Insertion dans la base
             $article->sumary_html_bact = smarty_modifier_blog_format_article($article->sumary_bact, $article->format_bact);
             $article->content_html_bact = smarty_modifier_blog_format_article($article->content_bact, $article->format_bact);
             $articleDAO->insert($article);
             $article->url_bact = killBadUrlChars($article->id_bact . '-' . $article->name_bact);
             $articleDAO->update($article);
             // Insertion dans la base blogarticle_blogarticlecategory
             $artctgDAO = CopixDAOFactory::create('blog|blogarticle_blogarticlecategory');
             $artctgDAO->deleteAndInsert($article->id_bact, $tabSelectCat);
             return new CopixActionReturn(COPIX_AR_REDIRECT, CopixUrl::get('blog|admin|showBlog', array("id_blog" => $id_blog, "kind" => $this->getRequest('kind', '0'))));
         }
     }
     // Pr�paration du filtre CATEGORIES
     $blogArticleCategoryDAO = CopixDAOFactory::create('blog|blogarticlecategory');
     $resArticleCategory = $blogArticleCategoryDAO->findAllOrder($id_blog);
     $tabArticleCategory = array();
     foreach ($resArticleCategory as $cat) {
         if (in_array($cat->id_bacg, $tabSelectCat)) {
             $cat->selected = true;
         } else {
             $cat->selected = false;
         }
         array_push($tabArticleCategory, $cat);
     }
     $article->time_bact = BDToTime($article->time_bact);
     $tpl->assign('BODY_ON_LOAD', "setDatePicker('#date_bact')");
     $tpl->assign('MAIN', CopixZone::process('EditArticle', array('id_blog' => $id_blog, 'id_bact' => $id_bact, 'article' => $article, 'kind' => $this->getRequest('kind', '0'), 'errors' => $errors, 'showErrors' => $showErrors, 'tabArticleCategory' => $tabArticleCategory, 'preview' => $go == 'preview' ? 1 : 0)));
     return new CopixActionReturn(COPIX_AR_DISPLAY, $tpl);
 }
 public function testToFormat()
 {
     $this->assertEquals(CopixDateTime::yyyymmddToFormat('20071201', 'Y-m-d'), '2007-12-01');
     $this->assertEquals(CopixDateTime::yyyymmddhhiissToFormat('20070213201235', 'Y-m-d H:i:s'), '2007-02-13 20:12:35');
     $this->assertEquals(CopixDateTime::hhiissToFormat('231436', 'H:i:s'), '23:14:36');
 }
 /**
  * Fonction qui fait la v�rification sur les champs de saisie du formulaire d'ajout d'un �v�nement
  * @access: private
  * @return array $toReturn tableau qui contient les erreurs de saisie de l'utilisateur
  */
 public function _check($obj)
 {
     $toReturn = array();
     //var_dump($obj);
     $datedeb = $obj->datedeb_event;
     $datefin = $obj->datefin_event;
     $datejusquau = isset($obj->dateendrepeat_event) ? $obj->dateendrepeat_event : null;
     $datedebTs = CopixDateTime::dateToTimestamp($datedeb);
     $datefinTs = CopixDateTime::dateToTimestamp($datefin);
     $datejusquauTs = CopixDateTime::dateToTimestamp($datejusquau);
     //conversion des heures au format hhmm pour pouvoir les comparer
     $heuredeb = dateService::heureWithSeparateurToheureWithoutSeparateur($obj->heuredeb_event);
     $heurefin = dateService::heureWithSeparateurToheureWithoutSeparateur($obj->heurefin_event);
     $endrepeat_event = isset($obj->endrepeat_event) ? $obj->endrepeat_event : false;
     //$dateendrepeat_event = $this->getRequest('dateendrepeat_event', null);
     $repeat_event = isset($obj->repeat_event) ? $obj->repeat_event : false;
     //v�rification si les champs sont bien remplis
     if ($obj->title_event == null || $obj->title_event == '') {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.notitle');
     }
     if ($endrepeat_event == 'nbfois' && isset($obj->nb_fois) && !is_numeric($obj->nb_fois)) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.nbFoisIsNotNumeric');
     }
     if (!$datedeb) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.nodatedeb');
     }
     if (!$datefin) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.nodatefin');
     }
     if ($obj->alldaylong_event == null && ($obj->heuredeb_event == null || $obj->heuredeb_event == '')) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.noheuredeb');
     }
     if ($obj->alldaylong_event == null && ($obj->heurefin_event == null || $obj->heurefin_event == '')) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.noheurefin');
     }
     if ($endrepeat_event == 'nbfois' && ($obj->nb_fois == '' || $obj->nb_fois == null)) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.nonbfois');
     }
     if ($endrepeat_event == 'date' && ($datejusquau == '' || $datejusquau == null) && $obj->repeat == 1) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.nodateendrepeat');
     }
     if ($endrepeat_event == 'date' && ($obj->endrepeat_event == '' || $obj->endrepeat_event == null)) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.nodatefinrepeat');
     }
     if (isset($obj->repeat) && $obj->repeat == 1 && (!isset($obj->endrepeat_event) || $obj->endrepeat_event == null)) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.noprecisionrepeat');
     }
     //var_dump($datedebTs);
     //var_dump($datefinTs);
     //v�rification sur le format des dates
     if ($datedeb) {
         if (CopixDateTime::timestampToDate($datedebTs) === false) {
             $toReturn[] = CopixI18N::get('agenda|agenda.error.formdatedeb');
         }
     }
     if ($datefin) {
         if (CopixDateTime::timestampToDate($datefinTs) === false) {
             $toReturn[] = CopixI18N::get('agenda|agenda.error.formdatefin');
         }
     }
     //v�rification sur la coh�rence des dates de d�but et de fin
     if ($datedeb && $datefin && $datedebTs && $datefinTs && $datedebTs > $datefinTs) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.inversiondate');
     }
     if (isset($obj->repeat) && $obj->repeat == 1 && $datedebTs && $datejusquauTs && $obj->endrepeat_event != null && $datedebTs > $datejusquauTs && $obj->endrepeat_event == 'date') {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.inversiondaterepeat');
     }
     //v�rification sur la coh�rence des heures de d�but et de fin
     if ($datedebTs && $datefinTs && $datedebTs == $datefinTs && $heuredeb > $heurefin && $obj->alldaylong_event != 1 && ($obj->heurefin_event != null || $obj->heurefin_event != '')) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.inversionheure');
     }
     if ($datejusquau) {
         if (CopixDateTime::timestampToDate($datejusquauTs) === false) {
             $toReturn[] = CopixI18N::get('agenda|agenda.error.formdatejusqu');
         }
     }
     //v�rification sur le format des heures
     if ($obj->heuredeb_event != null || $obj->heuredeb_event != '') {
         if (!ereg("([0-2])?[0-9]:[0-5][0-9]", $obj->heuredeb_event)) {
             $toReturn[] = CopixI18N::get('agenda|agenda.error.formheuredeb');
         } else {
             $heure = explode(":", $obj->heuredeb_event);
             if ($heure[0] < 0 || $heure[0] > 23 || $heure[1] < 0 || $heure[1] > 59) {
                 $toReturn[] = CopixI18N::get('agenda|agenda.error.formheuredeb');
             }
         }
     }
     if ($obj->heurefin_event != null || $obj->heurefin_event != '') {
         if (!ereg("([0-2])?[0-9]:[0-5][0-9]", $obj->heurefin_event)) {
             $toReturn[] = CopixI18N::get('agenda|agenda.error.formheurefin');
         } else {
             $heure = explode(":", $obj->heurefin_event);
             if ($heure[0] < 0 || $heure[0] > 23 || $heure[1] < 0 || $heure[1] > 59) {
                 $toReturn[] = CopixI18N::get('agenda|agenda.error.formheurefin');
             }
         }
     }
     //v�rifier que la fr�quence de r�p�tition est coh�rente avec la dur�e de l'�v�nement
     if ($obj->datedeb_event && $obj->datefin_event && $obj->heuredeb_event && $obj->heurefin_event && $repeat_event == 'everyday_event' && DateService::getNomberDaysBeetweenTwoDates($obj->datedeb_event, $obj->datefin_event, $obj->heuredeb_event, $obj->heurefin_event) > 1) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.freqrepetitionday');
     }
     if ($repeat_event == 'everyweek_event' && DateService::getNomberDaysBeetweenTwoDates($obj->datedeb_event, $obj->datefin_event, $obj->heuredeb_event, $obj->heurefin_event) > 7) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.freqrepetitionweek');
     }
     if ($repeat_event == 'everymonth_event' && DateService::getNomberDaysBeetweenTwoDates($obj->datedeb_event, $obj->datefin_event, $obj->heuredeb_event, $obj->heurefin_event) > 28) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.freqrepetitionmonth');
     }
     if ($repeat_event == 'everyyear_event' && DateService::getNomberDaysBeetweenTwoDates($obj->datedeb_event, $obj->datefin_event, $obj->heuredeb_event, $obj->heurefin_event) > 365) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.freqrepetitionyear');
     }
     return $toReturn;
 }
 /**
  *
  * @param
  * @return
  * @access private
  */
 function _decodeValue($valuetag)
 {
     $childs = $valuetag->childs();
     $value = null;
     if (count($childs)) {
         switch ($childs[0]->name()) {
             case 'I4':
             case 'INT':
                 $value = intval($childs[0]->content());
                 break;
             case 'DOUBLE':
                 $value = doubleval($childs[0]->content());
                 break;
             case 'STRING':
                 $value = html_entity_decode($childs[0]->content());
                 break;
             case 'BOOLEAN':
                 $value = intval($childs[0]->content()) ? true : false;
                 break;
             case 'ARRAY':
                 $value = array();
                 if (isset($childs[0]->DATA->VALUE)) {
                     $listvalue = is_array($childs[0]->DATA->VALUE) ? $childs[0]->DATA->VALUE : array($childs[0]->DATA->VALUE);
                     foreach ($listvalue as $val) {
                         $value[] = CopixXmlRpc::_decodeValue($val);
                     }
                 }
                 break;
             case 'STRUCT':
                 $value = array();
                 if (isset($childs[0]->MEMBER)) {
                     $listvalue = is_array($childs[0]->MEMBER) ? $childs[0]->MEMBER : array($childs[0]->MEMBER);
                     foreach ($listvalue as $val) {
                         if (isset($val->NAME) && isset($val->VALUE)) {
                             $value[$val->NAME->content()] = CopixXmlRpc::_decodeValue($val->VALUE);
                         }
                     }
                 }
                 break;
             case 'DATETIME.ISO8601':
                 $value = new CopixDateTime();
                 $value->setFromString($childs[0]->content(), $value->ISO8601_FORMAT);
                 break;
             case 'BASE64':
                 $value = new CopixBinary();
                 $value->setFromBase64String($childs[0]->content());
                 break;
         }
     } else {
         $value = $valuetag->content();
     }
     return $value;
 }
 /**
  * Récupère l'objet en session
  * Appelle les zones agendamenu et agendaeditlecon
  * @author Audrey Vassal <*****@*****.**>
  */
 public function processGetEdit()
 {
     CopixHTMLHeader::addCSSLink(_resource("styles/module_agenda.css"));
     require_once COPIX_UTILS_PATH . 'CopixDateTime.class.php';
     $serviceAuth = new AgendaAuth();
     $serviceType = new AgendaType();
     $serviceAgenda = new AgendaService();
     $serviceDate = new DateService();
     if (!($toEdit = $this->_getSessionLecon())) {
         return CopixActionGroup::process('genericTools|Messages::getError', array('message' => CopixI18N::get('agenda.unableToGetEdited'), 'back' => CopixUrl::get('agenda|agenda|vueSemaine')));
     }
     $serviceAuth->getCapability($toEdit->id_agenda);
     if ($serviceAuth->getCapability($toEdit->id_agenda) < $serviceAuth->getWriteLecon() || $serviceAgenda->getTypeAgendaByIdAgenda($toEdit->id_agenda) != $serviceType->getClassRoom()) {
         return CopixActionGroup::process('genericTools|Messages::getError', array('message' => CopixI18N::get('agenda.error.enableToWrite'), 'back' => CopixUrl::get('agenda|agenda|vueSemaine')));
     }
     $listAgendas = $serviceAgenda->getAvailableAgenda();
     $listAgendasAffiches = $serviceAgenda->getAgendaAffiches();
     //template pour agenda
     $tplAgenda = new CopixTpl();
     $tplAgenda->assign('MAIN_AGENDA', CopixZone::process('agenda|agendaeditlecon', array('e' => _request('e'), 'errors' => _request('errors'), 'toEdit' => $toEdit)));
     //template principal
     $tpl = new CopixTpl();
     $tpl->assign('TITLE_PAGE', CopixI18N::get('agenda|agenda.title.lecon', array('jour' => CopixDateTime::yyyymmddToDate($toEdit->date_lecon))));
     $menu = $serviceAgenda->getAgendaMenu('');
     $tpl->assign('MENU', $menu);
     $tpl->assign('MAIN', $tplAgenda->fetch('agenda|main.agenda.tpl'));
     return new CopixActionReturn(COPIX_AR_DISPLAY, $tpl);
 }
 public function beforeDisplay(&$display)
 {
     $jscode = array();
     $logs = array();
     foreach (CopixConfig::instance()->copixlog_getRegistered() as $profil) {
         $name = CopixConfig::instance()->copixlog_getProfile($profil);
         $name = $name['strategy'];
         if (strtoupper($name) == "FIREBUG") {
             $logs[] = CopixLog::getLog($profil);
         }
     }
     //merge last logs to new logs
     if (CopixSession::get('plugin|firebug|log') !== null) {
         $logs = array_merge(CopixSession::get('plugin|firebug|log'), $logs);
         CopixSession::set('plugin|firebug|log', null);
     }
     $logs = array_reverse($logs);
     foreach ($logs as $arlog) {
         foreach ($arlog as $log) {
             foreach (array('message', 'file', 'line', 'level', 'classname', 'functionname', 'type') as $var) {
                 if (isset($log->{$var})) {
                     ${$var} = $log->{$var};
                     unset($log->{$var});
                 } else {
                     ${$var} = null;
                 }
             }
             $log->date = CopixDateTime::yyyymmddhhiissToDateTime($log->date);
             $log->location = "{$file}:{$line}";
             $log->function = ($classname ? "{$classname}::" : "") . $functionname;
             switch ($level) {
                 case CopixLog::INFORMATION:
                     $type = "info";
                     break;
                 case CopixLog::WARNING:
                 case CopixLog::NOTICE:
                     $type = "warn";
                     break;
                 case CopixLog::EXCEPTION:
                 case CopixLog::ERROR:
                 case CopixLog::FATAL_ERROR:
                     $type = "error";
                     break;
                 default:
                     $type = "log";
             }
             unset($log->level);
             $jscode[] = sprintf('_l(%s,%s,%s,%s);', CopixJSON::encode($type), CopixJSON::encode($message), CopixJSON::encode($log->location), CopixJSON::encode($log));
         }
     }
     foreach (CopixConfig::instance()->copixlog_getRegistered() as $profil) {
         $name = CopixConfig::instance()->copixlog_getProfile($profil);
         $name = $name['strategy'];
         if (strtoupper($name) == "FIREBUG") {
             CopixLog::deleteProfile($profil);
         }
     }
     if (count($jscode) > 0) {
         $jscode[] = "if(window.console && console.firebug){var _l=function(t,m,l,e){console.group('[COPIX] - '+t+' - '+l);console[t](m);console.dir(e);console.groupEnd();}";
         $jscode = array_reverse($jscode);
         $jscode[] = "}";
         CopixHTMLHeader::addJSCode(implode("\n", $jscode));
     }
 }
 /**
  * Fonction qui fait la vérification sur les champs de saisie du formulaire d'import
  * @author Audrey Vassal <*****@*****.**>
  * @access: private
  * @return array $toReturn tableau qui contient les erreurs de saisie de l'utilisateur
  */
 public function _checkExport($obj)
 {
     $toReturn = array();
     $datedeb = $datedebTs = null;
     $datefin = $datefinTs = null;
     if (isset($obj->datedeb_export)) {
         $datedeb = $obj->datedeb_export;
         $datedebTs = CopixDateTime::dateToTimestamp($datedeb);
     }
     if (isset($obj->datefin_export)) {
         $datefin = $obj->datefin_export;
         $datefinTs = CopixDateTime::dateToTimestamp($datefin);
     }
     //vérification si les champs sont bien remplis
     if (!$datedeb) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.nodatedeb');
     }
     if (!$datefin) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.nodatefin');
     }
     //vérification sur la cohérence des dates de début et de fin
     if ($datedeb && $datefin && $datedebTs && $datefinTs && $datedebTs > $datefinTs) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.inversiondate');
     }
     if (!$obj->agenda) {
         $toReturn[] = CopixI18N::get('agenda|agenda.error.noagenda');
     }
     return $toReturn;
 }
 /**
  * Fonction qui donne le nombre de jour écoulés entre deux dates+heure
  * @author Audrey Vassal <*****@*****.**>
  * @since 2006/07/28
  * @param date $pDateBegin au format jj/mm/aaaa
  * @param date $pDateEnd au format jj/mm/aaaa
  * @param date $pHeureDeb heure au format hh:mm
  * @param date $pHeureFin heure au format hh:mm
  * @return integer $nbDays nombre de jours qui se sont écoulés entre les deux dates
  */
 public function getNomberDaysBeetweenTwoDates($pDateBegin, $pDateEnd, $pHeureBegin, $pHeureEnd)
 {
     //Extraction des données
     //list($jour1, $mois1, $annee1) = explode('/', $pDateBegin);
     //list($jour2, $mois2, $annee2) = explode('/', $pDateEnd);
     $pDate = CopixDateTime::dateToTimestamp($pDateBegin);
     $jour1 = substr($pDate, 6, 2);
     $mois1 = substr($pDate, 4, 2);
     $annee1 = substr($pDate, 0, 4);
     $pDate = CopixDateTime::dateToTimestamp($pDateEnd);
     $jour2 = substr($pDate, 6, 2);
     $mois2 = substr($pDate, 4, 2);
     $annee2 = substr($pDate, 0, 4);
     list($heure1, $minutes1) = explode(':', $pHeureBegin);
     list($heure2, $minutes2) = explode(':', $pHeureEnd);
     //Calcul des timestamp
     $timestamp1 = mktime($heure1, $minutes1, 0, $mois1, $jour1, $annee1);
     $timestamp2 = mktime($heure2, $minutes2, 0, $mois2, $jour2, $annee2);
     $nbDays = ($timestamp2 - $timestamp1) / 86400;
     return $nbDays;
     //echo abs($timestamp2 - $timestamp1)/(86400*7); //Affichage du nombre de semaine : 3.85
 }