/class.xshell.inc
PHP | 1037 lines | 874 code | 75 blank | 88 comment | 250 complexity | 689fa915ee24eea94b6e11455cf32e74 MD5 | raw file
Possible License(s): LGPL-2.0, LGPL-2.1, GPL-3.0, Apache-2.0, BSD-3-Clause
- <?php
- @require_once 'Log.php';
- @require_once 'Log/file.php';
- class XShell implements ISec {
- public $tpldata = array();
- public $rawdata = array();
- public $_debug = false;
- public $_starttime=0.0000;
- public $_cache = true;
- public $_callback = NULL;
- public $_function = NULL;
- public $_next=NULL; /* dans le cas ou on envisage une redirection apres traitement */
- static $_log=NULL;
- static $_bdxprefix='0'; // prefix of the back stack
- static $_bdx=0; // index of the back stack
- function __construct($ar='*',$cache=true) {
- $this->_starttime=TZR_START_TIME;
- $this->_cache = $cache;
- $matches=array();
- $this->_loginurl=$GLOBALS['TZR_SELF'].'?';
- self::$_log=XLogs::_initLogFile();
- }
- /// Recupere le bdx en cours
- function getBdx(){
- if(@$_REQUEST['_bdxnewstack']==1){
- XShell::$_bdxprefix=max(array_keys($_SESSION['BACK']))+1;
- XShell::$_bdx=0;
- }elseif(!empty($_REQUEST['_bdx']) && preg_match('/^([0-9]+)_([0-9]+)$/i',$_REQUEST['_bdx'],$matches)){
- if(!empty($matches[2]) || $matches[2]==='0'){
- XShell::$_bdxprefix=$matches[1];
- XShell::$_bdx=$matches[2];
- }else{
- XShell::$_bdxprefix='0';
- XShell::$_bdx=$matches[1];
- }
- }
- }
- /// securite des fonctions accessibles par le web
- function secGroups($function, $group=NULL) {
- $g=array();
- $g['index']=array('none','ro','rw','rwv','admin');
- if(isset($g[$function])) {
- if(!empty($group)) return in_array($group, $g[$function]);
- return $g[$function];
- }
- return NULL;
- }
- function secList() {
- return array('none','ro','rw','rwv','admin');
- }
- static public function _function() {
- return $GLOBALS['XSHELL']->_function;
- }
- // Retourne le niveau de traitement à effectuer (0 => tout, 1 => desactive les callbacks, 2 => desactive les menus)
- static public function _raw() {
- return $GLOBALS['XSHELL']->_raw;
- }
- // Retourne vrai si la requete exécuté est en mode ajax
- static public function _ajax() {
- return $GLOBALS['XSHELL']->_ajax;
- }
- // Retourne vrai si la requete exécuté doit etre traité pour une iframe
- static public function _iframeencode() {
- return $GLOBALS['XSHELL']->_iframeencode;
- }
- static public function uniqid(){
- if(empty($GLOBALS['XSHELL']->_uniqid)){
- if(!empty($_REQUEST['_uniqid'])) $GLOBALS['XSHELL']->_uniqid=$_REQUEST['_uniqid'];
- else $GLOBALS['XSHELL']->_uniqid=uniqid();
- }
- return $GLOBALS['XSHELL']->_uniqid;
- }
- public function setLoginUrl($url) {
- $this->_loginurl=$url;
- }
- public function getLoginUrl() {
- return $this->_loginurl;
- }
- public static function isRoot() { return getSessionVar('root'); }
- public static function admin_mode() { return getSessionVar('ADMIN'); }
- public static function getLangData($l=NULL,$redo=false,$unsetcache=false) {
- static $computed_lang=NULL;
- if(empty($l) && !$redo && !empty($computed_lang)) return $computed_lang;
- $lg=TZR_DEFAULT_LANG;
- if(XShell::admini_mode()) {
- if(!empty($l)) $lg=$l;
- elseif(!empty($_REQUEST['LANG_DATA'])) $lg=$_REQUEST['LANG_DATA'];
- elseif(!empty($_SESSION['LANG_DATA'])) $lg=$_SESSION['LANG_DATA'];
- elseif(!empty($_REQUEST['_lang'])) $lg=$_REQUEST['_lang'];
- elseif(!empty($GLOBALS['LANG_DATA'])) $lg=$GLOBALS['LANG_DATA'];
- } else {
- if(!empty($_REQUEST['LANG_DATA'])) $lg=$_REQUEST['LANG_DATA'];
- elseif(!empty($_REQUEST['_lang'])) $lg=$_REQUEST['_lang'];
- elseif(!empty($_SESSION['LANG_DATA'])) $lg=$_SESSION['LANG_DATA'];
- }
- if(!array_key_exists($lg,$GLOBALS['TZR_LANGUAGES'])) $lg=TZR_DEFAULT_LANG;
- if(empty($l)) $computed_lang=$lg;
- if($unsetcache) $computed_lang=NULL;
- return $lg;
- }
- public static function getLangTrad($l=NULL,$notrad=NULL) {
- if(XShell::admini_mode() && empty($_REQUEST['_notrad']) && empty($notrad)) {
- $lg=NULL;
- if(!empty($l)) $lg=TZR_DEFAULT_LANG;
- elseif(!empty($_REQUEST['LANG_TRAD'])) $lg=TZR_DEFAULT_LANG;
- elseif(!empty($_SESSION['LANG_TRAD'])) $lg=TZR_DEFAULT_LANG;
- if(array_key_exists($lg, $GLOBALS['TZR_LANGUAGES'])) return $lg;
- }
- return NULL;
- }
- public static function getLangUser($l=NULL) {
- if(empty($l)) {
- if(!empty($_REQUEST['LANG_USER'])) $l=$_REQUEST['LANG_USER'];
- elseif(!empty($_SESSION['LANG_USER'])) $l=$_SESSION['LANG_USER'];
- elseif(!empty($_REQUEST['_lang'])) $l=$_REQUEST['_lang'];
- elseif(!empty($GLOBALS['LANG_USER'])) $l=$GLOBALS['LANG_USER'];
- }
- if(array_key_exists($l, $GLOBALS['TZR_ADMIN_LANGUAGES'])) return $l;
- else return TZR_DEFAULT_LANG;
- }
- /// Recupere le _next en cours
- public static function getNext(){
- return $GLOBALS['XSHELL']->_next;
- }
- /// Change le _next
- public static function setNext($url=NULL) {
- $_REQUEST['_next']='';
- if(empty($url)) $GLOBALS['XSHELL']->_next=NULL;
- elseif(preg_match('@(^https?://|^/)@',$url)) $GLOBALS['XSHELL']->_next=$url;
- else $GLOBALS['XSHELL']->_next=$GLOBALS['TZR_SESSION_MANAGER']::complete_self().$url;
- }
- /// Ajoute des données au _next
- public static function setNextData($var, $value) {
- $GLOBALS['XSHELL']->_nextData[$var]=$value;
- }
- /// Ajoute un fichier au _next
- public static function setNextFile($file, $name, $mime) {
- $GLOBALS['XSHELL']->_nextData['filename'] = $file;
- $GLOBALS['XSHELL']->_nextData['fileoriginalname'] = $name;
- $GLOBALS['XSHELL']->_nextData['filemime'] = $mime;
- }
- /// Vérifie si un _next est positionné
- public static function hasNext(){
- if(!empty($GLOBALS['XSHELL']->next) || !empty($_REQUEST['_next'])) return true;
- return false;
- }
- static function admini_mode() {
- return defined('TZR_ADMINI');
- }
- function showStack($ar) {
- $ar2=debug_backtrace() ;
- VarDump($ar2,false,0,2,1);
- }
- function quit($ar) {
- if(XIni::get('debug_die')>0) {
- $ar2=debug_backtrace() ;
- if(is_string($ar)) $message =$ar;
- if(is_array($ar)) $message =$ar['message'];
- $level = XIni::get('debug_die');
- $details = XIni::get('debug_details');
- $ex=VarDump($ar2,false,0,$level,$details,true);
- }
- XLogs::critical("XShell::quit",' panic '.$message.' '.$_SERVER['QUERY_STRING']).' '.$ex;
- exit();
- }
- /// Affecte une variable smarty $prefix_ (ecrase la valeur existantes)
- static function &toScreen1($prefix,&$p1) {
- if($prefix!=TZR_RETURN_DATA) $GLOBALS['XSHELL']->tpldata[$prefix]=$p1;
- return $p1;
- }
- /// Affecte une variable smarty $prefix_$p1 (ecrase la valeur existantes)
- static function &toScreen2($prefix,$p1,$p2) {
- if($prefix!=TZR_RETURN_DATA){
- if(!@is_array($GLOBALS['XSHELL']->tpldata[$prefix][$p1])) $GLOBALS['XSHELL']->tpldata[$prefix][$p1]=array();
- $GLOBALS['XSHELL']->tpldata[$prefix][$p1]=$p2;
- }
- return $p2;
- }
- /// Affecte une variable smarty $prefix_ (merge avec la valeur existantes)
- static function toScreen1Merge($prefix,&$p1){
- if($prefix!=TZR_RETURN_DATA){
- if(is_array($GLOBALS['XSHELL']->tpldata[$prefix]))
- $GLOBALS['XSHELL']->tpldata[$prefix]=array_merge_recursive($GLOBALS['XSHELL']->tpldata[$prefix],$p1);
- else
- $GLOBALS['XSHELL']->tpldata[$prefix]=$p1;
- }
- return $p1;
- }
- /// Supprime la variable smarty $prefix_ ou $prefix_$p1
- static function clearScreen($prefix,$p1=NULL){
- if(!empty($p1)) unset($GLOBALS['XSHELL']->tpldata[$prefix][$p1]);
- else unset($GLOBALS['XSHELL']->tpldata[$prefix]);
- }
- static function &from_screen($prefix,$var=NULL) {
- if($prefix==TZR_RETURN_DATA) return NULL;
- if(isset($var)) return $GLOBALS['XSHELL']->tpldata[$prefix][$var];
- else return $GLOBALS['XSHELL']->tpldata[$prefix];
- }
- static function exit_tzr($message=NULL) {
- XLogs::_closeLogger();
- exit();
- }
- // empile une info dans la pile de la barre de navig
- //
- function push_navbar($label, $url) {
- if(!is_array($this->tpldata['nav'])) $this->tpldata['nav']=array();
- if(!is_array($this->tpldata['nav']['url'])) {
- $this->tpldata['nav']['url']=array();
- $this->tpldata['nav']['label']=array();
- }
- array_push($this->tpldata['nav']['url'],$url);
- array_push($this->tpldata['nav']['label'],$label);
- if(empty($this->tpldata['nav']['lastlabel'])) {
- $this->tpldata['nav']['lasturl']=$url;
- $this->tpldata['nav']['lastlabel']=$label;
- }
- }
- // depile une info dans la pile de la barre de navig
- //
- function pop_navbar() {
- if(is_array($this->tpldata['nav'])) {
- $i=count($this->tpldata['nav']['url']);
- unset($this->tpldata['nav']['url'][$i-1]);
- unset($this->tpldata['nav']['label'][$i-1]);
- }
- }
- function title_navbar($title) {
- $this->tpldata['nav']['title']=$title;
- }
- // nettoyage de la barre de navig
- //
- function clear_navbar() {
- if(@is_array($this->tpldata['nav'])) {
- $this->tpldata['nav']['label']=array();
- $this->tpldata['nav']['url']=array();
- } else {
- $this->tpldata['nav']=array();
- }
- }
- public function set_navbar_pagetitle($label, $url) {
- $this->tpldata['nav']['lasturl']=$url;
- $this->tpldata['nav']['lastlabel']=$label;
- }
- // appel d'une fonction a chaque affichage de page
- function set_callback($f) {
- unset($this->_callback);
- $this->_callback=array();
- $this->_callback[]=$f;
- }
- function add_callback($f) {
- $this->_callback[]=$f;
- }
- function _load_user($ar=NULL) {
- if(issetSessionVar('UID'))
- $GLOBALS['XUSER'] = new XUser(array('UID'=>getSessionVar('UID')));
- else
- $GLOBALS['XUSER'] = new XUser();
- $lang = $GLOBALS['XUSER']->language();
- if(empty($_SESSION['LANG_DATA'])) {
- if(!empty($lang[0])) {
- $GLOBALS['LANG_DATA']=$lang[0];
- }
- if(empty($GLOBALS['LANG_DATA'])) $GLOBALS['LANG_DATA']=TZR_DEFAULT_LANG;
- }
- if(empty($_SESSION['LANG_USER'])) {
- if(!empty($lang[1])) {
- $GLOBALS['LANG_USER']=$lang[1];
- }
- if(empty($GLOBALS['LANG_USER'])) $GLOBALS['LANG_USER']=TZR_DEFAULT_LANG;
- }
- }
- private function security_check($class, $function, $moid, $lang, &$koid, $interactive=false) {
- if(is_array($koid)){
- $all=$koid;
- foreach($all as $k=>&$v){
- if(Kernel::isAKoid($k)){
- $ok=$this->security_check($class,$function,$moid,$lang,$k,true);
- }else{
- $ok=$this->security_check($class,$function,$moid,$lang,$v,true);
- }
- if(!$ok){
- unset($koid[$k]);
- }
- }
- unset($v);
- if(!empty($koid)) return true;
- else{
- $ok=false;
- $koid=$all;
- }
- if(!empty($moid)) {
- if(!empty($class)) $mod=new $class(array('moid'=>$moid, 'tplentry'=>TZR_RETURN_DATA));
- else $mod=&XModule::objectFactory(array('moid'=>$moid, 'tplentry'=>TZR_RETURN_DATA));
- }
- }else{
- // Assure la compatibilité avec d'ancienne url sans moid. Ne fonctionne que si la methode est publique ou en root.
- // Si d'autres cas sont rencontrés, il faut faire en sorte de tjs passer par un module..
- if(empty($moid) && XUser::secure8class($class,$function)) {
- $ok=true;
- }else{
- $ok=false;
- if(!empty($moid)) {
- $props=XModule::findParam($moid);
- if(!empty($class)) {
- $mod=new $class(array('moid'=>$moid, 'tplentry'=>TZR_RETURN_DATA));
- $ok=$mod->secure($koid,$function,$GLOBALS['XUSER'],$lang);
- } else {
- $mod=&XModule::objectFactory(array('moid'=>$moid, 'tplentry'=>TZR_RETURN_DATA));
- if(!empty($mod)) $ok=$mod->secure($koid,$function,$GLOBALS['XUSER'],$lang);
- }
- }
- }
- }
- if($ok) {
- debug("access ok |$class|$function|$moid|$lang|$koid|");
- if(!XUser::isNobody()){
- $suid=getSessionVar('SUID');
- if(!empty($suid)){
- $xuser=new XUser(array('UID'=>$suid));
- XModStats::count($koid, $lang, $moid, $xuser, $function);
- }else{
- XModStats::count($koid, $lang, $moid, $GLOBALS['XUSER'], $function);
- }
- }
- return true;
- }else{
- if(!is_array($koid)){
- $message=XLabels::getSysLabel('security.permission_denied');
- XLogs::update('security',$koid, $message.'<!-- |'.$class.'|'.$function.'|'.$moid.'|'.$lang.'|'.$koid.'| failed -->');
- XLogs::critical('security', "access denied |$class|$function|$moid|$lang|$koid| user ".XUser::get_current_user_uid());
- }
- if(!$interactive) {
- // Si mode ajax, on renvoie une erreur 401
- if(XShell::_ajax()){
- header("HTTP/1.1 401 Unauthorized");
- exit(0);
- }elseif(XShell::_iframeencode()){
- header("HTTP/1.1 401 Unauthorized");
- echo '401 Unauthorized';
- exit(0);
- }
- if($_SERVER['REQUEST_METHOD']=='GET') $next=$_SERVER["REQUEST_URI"];
- // Authentification CAS
- if(@$GLOBALS['CAS_SERVER_URL'] && @$GLOBALS['CAS_SERVER_VERSION']){
- debug("cas authentification (access denied |$class|$function|$moid|$lang|$koid|)");
- if(empty($next)) {
- $moidadmin=XModule::getMoid(XMODADMIN_TOID);
- $next=$GLOBALS['TZR_SESSION_MANAGER']::admin_url(false,false).'&template=home.html&function=portail&moid='.$moidadmin.
- '&message='.urlencode(XLabels::getSysLabel('xsession.reauth_lost_post'));
- }
- $cas=AuthCas::getAuthCas(array('server'=>$GLOBALS['CAS_SERVER_URL'],
- 'version'=>$GLOBALS['CAS_SERVER_VERSION'],
- 'next'=>$next
- )
- );
- $cas->forceAuthentication();
- debug("cas authentification OK (access |$class|$function|$moid|$lang|$koid|)");
- $sessionclass=$GLOBALS['TZR_SESSION_MANAGER'];
- $session=new $sessionclass();
- $arauth=array('withcas'=>true,'tplentry'=>TZR_RETURN_DATA);
- if(preg_match('/^'.preg_quote(TZR_SHARE_ADMIN_PHP,'/').'/',$GLOBALS['TZR_SESSION_MANAGER']::complete_self()))
- $arauth['admin']=$arauth['admini']=true;
- $session->procAuth($arauth);
- $sec=$this->security_check($class, $function, $moid, $lang, $koid, true);
- if(!$sec) $cas->redirectToError();
- else {
- header('Location: '.$GLOBALS['TZR_SESSION_MANAGER']::makeDomainName().$next);
- die();
- }
- return $sec;
- }
- if(empty($next)) {
- $moidadmin=XModule::getMoid(XMODADMIN_TOID);
- $next='&template=home.html&function=portail&moid='.$moidadmin;
- }
- // on utilise la gestion specifique d'erreur du module si elle existe
- if(is_object($mod)) $mod->secFailHandler($function,$koid,NULL,$next,NULL);
- // dans tous les cas on ne doit pas aller plus loin
- XShell::redirect2auth($message,$next);
- } else {
- return false;
- }
- }
- return true;
- }
- static function redirect2auth($message=NULL,$next=NULL){
- if(empty($next)) {
- $moidadmin=XModule::getMoid(XMODADMIN_TOID);
- $next='&template=home.html&function=portail&moid='.$moidadmin;
- }
- if(empty($message)) $message=XLabels::getSysLabel('security.permission_denied');
- header('Location: '.$GLOBALS['XSHELL']->getLoginUrl().'&message='.urlencode($message).'&next='.urlencode($next));
- die();
- }
- static function redirect2error($ar=NULL) {
- header('Location: '.$GLOBALS['TZR_SESSION_MANAGER']::complete_self().'&skip=1&template=basic/message.html&message='.rawurlencode($ar['message']));
- die();
- }
- // traitement du changement de langue courante
- //
- protected function _changeLang(){
- if(isset($_REQUEST['_lang'])) {
- $_SESSION['LANG_DATA'] = $_REQUEST['_lang'];
- $_SESSION['LANG_USER'] = $_REQUEST['_lang'];
- }
- if(isset($_REQUEST['_lang_data'])) {
- $_SESSION['LANG_DATA'] = $_REQUEST['_lang_data'];
- }
- if(isset($_REQUEST['_lang_user'])) {
- $_SESSION['LANG_USERS'] = $_REQUEST['_lang_user'];
- }
- if(isset($_REQUEST['_lang_trad'])) {
- $_SESSION['LANG_TRAD'] = $_REQUEST['_lang_trad'];
- }
- if(isset($_REQUEST['LANG_DATA'])) $_SESSION['LANG_DATA']=$_REQUEST['LANG_DATA'];
- if(isset($_REQUEST['LANG_USER'])) $_SESSION['LANG_USER']=$_REQUEST['LANG_USER'];
- if(isset($_REQUEST['LANG_TRAD'])) $_SESSION['LANG_TRAD']=$_REQUEST['LANG_TRAD'];
- }
- function error($ar=NULL) {
- $p = new XParam($ar, array("message"=>"Unexpected error"));
- $GLOBALS['XSHELL']->tpldata[""]["message"]=$p->get("message");
- }
- static function getTemplate(){
- if(isset($_REQUEST["_template"])) return $_REQUEST["_template"];
- elseif(isset($_REQUEST["template"])) return $_REQUEST["template"];
- }
- /// Définit les templates à utiliser
- function setTemplates($temp=NULL,$security2=false) {
- static $insidefile_checked=false;
- if(empty($temp)) $temp=XShell::getTemplate();
- else $_REQUEST["_template"]=$temp;
- // Changement des templates
- $templates=$temp;
- $generic=TZR_DEFAULT_TEMPLATE;
- // Test pour eviter que le template ne serve de cross scripting
- checkIfTemplateIsSecure($templates,$security2);
- // Tests sur insidefile s'il existe
- if(!$insidefile_checked && !empty($_REQUEST['insidefile'])) checkIfTemplateIsSecure($_REQUEST['insidefile'],true);
- if(!$insidefile_checked && defined('TZR_ALLOW_USER_TEMPLATES') &&
- !empty($_REQUEST['insidefile']) && file_exists($GLOBALS['USER_TEMPLATES_DIR'].$_REQUEST['insidefile'])) {
- $_REQUEST['insidefile']=$GLOBALS['USER_TEMPLATES_DIR'].$_REQUEST['insidefile'];
- }
- $insidefile_checked=true;
- if(!is_array($templates)) {
- if(!file_exists($GLOBALS['TEMPLATES_DIR'].$templates)) {
- if(defined('TZR_ALLOW_USER_TEMPLATES') && file_exists($GLOBALS['USER_TEMPLATES_DIR'].$templates)) {
- $templates=array(0=>$GLOBALS['USER_TEMPLATES_DIR'].$templates);
- }
- }
- }
- if(!empty($_REQUEST['insidefile']))
- XLogs::debug('XShell::setTemplates: using insidefile '.$_REQUEST['insidefile']);
- if(is_array($templates)) $template=$templates[0];
- else $template=$templates;
- return array($template,$templates);
- }
- function run($ar='*') {
- XLogs::debug('XShell::run: start');
- // creation des variables globales
- $GLOBALS['XLANG'] = new XLang;
- // verification des numero de version
- $this->_checkupgrade();
- // Chargement d'une page via l'url du contenu
- if(!empty($_REQUEST['_direct'])){
- header('Location: '.$GLOBALS['TZR_SESSION_MANAGER']::complete_self().'&moid='.XModule::getMoid(XMODADMIN_TOID).
- '&template=home.html&function=portail&gopage='.
- urlencode(str_replace('&_direct=1','',$_SERVER['REQUEST_URI'])));
- exit(0);
- }
- // on verifie que le back est enregistre
- if(XShell::admini_mode() && empty($_SESSION['BACK'])) $_SESSION['BACK']=array();
- if(!XShell::admini_mode() && TZR_COUNT_REFERER) {
- XModRef::countRobot();
- XModRef::countReferer();
- }
- // chargement de la classe
- $class='';
- $moid = (empty($_REQUEST['moid'])?NULL:$_REQUEST['moid']);
- if(XShell::admini_mode()){
- if(empty($moid)){
- if(!empty($_REQUEST['_class'])) $class=$_REQUEST['_class'];
- elseif(!empty($_REQUEST['class'])) $class=$_REQUEST['class'];
- }
- }else{
- if(!empty($_REQUEST['_class'])) $class=$_REQUEST['_class'];
- elseif(!empty($_REQUEST['class'])) $class=$_REQUEST['class'];
- }
- // chargement de la function
- if(!empty($_REQUEST['_function'])) $f=$_REQUEST['_function'];
- elseif(!empty($_REQUEST['function'])) $f=$_REQUEST['function'];
- // insertion et traitement du back
- if((XShell::admini_mode() || !empty($this->activeHistory)) && ($f!='back')) {
- $this->getBdx();
- $skip=!empty($_REQUEST['_skip']) || !empty($_REQUEST['skip']) || $f=='goto1';
- if(empty($skip)) $this->insert_back();
- } elseif($f=='back') {
- $this->back();
- $this->run($ar);
- return;
- }
- // on regarde si il s'agit d'une url 'simple' c'est a dire qu'on
- // ne calcule rien dans les callback etc.
- $this->_raw=!empty($_REQUEST['_raw'])?$_REQUEST['_raw']:0;
- $this->_ajax=!empty($_REQUEST['_ajax']);
- $this->_iframeencode=!empty($_REQUEST['_iframeencode']);
- list($template, $templates)=$this->setTemplates();
- // test pour eviter que le template ne serve de cross scripting
- if(!preg_match('@^([_a-z0-9\./-]*)$@i',$class))
- securityWarning("(e3) class <$class> is not secure",true,true);
- // dans le cas ou il y a une demande de changement de langue
- if(!empty($_REQUEST['_setlang'])) {
- $this->_changeLang();
- }
- // dans le cas ou on veut des chemins absolus pour les donnes
- if(!empty($_REQUEST['_fqn'])) {
- $GLOBALS['SELF_PREFIX']=$GLOBALS['HOME_ROOT_URL'].$GLOBALS['SELF_PREFIX'];
- }
- if(!XShell::admini_mode() && XIni::get('site_closed') && ($f!='error') &&
- ($template!='auth.html') && ($f!='procAuth'))
- $this->redirect2error(array('message'=>'Sorry, at this point the site is closed'));
- // determination du type mime de la reponse
- // par défaut text/html
- $mime='text/html';
- $mimes['html']='text/html';
- $mimes['xml']='text/xml';
- $mimes['svg']='image/svg+xml';
- $mimes['css']='text/css';
- $mimes['js']='application/x-javascript';
- $mimes['downl']='application/x-octet-stream';
- $mimes['txt']='text/plain';
- $mimes['js']='application/x-javascript';
- $mimes['png']='image/png';
- $mimes['kml']='application/vnd.google-earth.kml+xml';
- $mimes['json']='application/json';
- if(empty($_REQUEST['_mime']) && preg_match('/\.([a-z0-9]{1,6})$/i',$template,$eregs)) {
- $extension=$eregs[1];
- if(!empty($mimes[$extension]))
- $mime=$mimes[$extension];
- }
- if(!empty($_REQUEST['_mime']) && in_array($_REQUEST['_mime'], $mimes)) {
- $mime=$_REQUEST['_mime'];
- }
- $disps=array('attachment','inline');
- if(!empty($_REQUEST['_disp']) && in_array($_REQUEST['_disp'], $disps)) {
- $_disp=$_REQUEST['_disp'];
- }
- // si le cache est utilisable (Front)
- if($this->_cache) {
- $cache = new XCache(XIni::get('cache_timeout'));
- $cache->setCachePolicy();
- // essayer de servir la page depuis le cache
- if ($cache->delivery($template, $mime, $_disp, $ar)) {
- XLogs::debug('XShell::run: page delivered by cache');
- $this->exit_tzr();
- }
- }
-
- // ouverture d'une connexion base de donnees globales
- if(!isset($GLOBALS['TZR_DB'])) $GLOBALS['TZR_DB']=&DBNewConnection();
- // chargement de l'utilisateur
- $this->_load_user();
- // Creation de l'objet reservation si necessaire
- if(XModule::getMoid(XMODLOCK_TOID))
- $GLOBALS['XLOCK']=new XModLock();
- // creation de l'object de replication si necessaire
- if ($replication_moid = XModule::getMoid(XMODREPLICATION_TOID)) {
- if (XModReplication::initsetRunning())
- die('Initialisation en cours, patientez ...');
- $GLOBALS['XREPLI'] = XModule::objectFactory($replication_moid);
- }
-
- // creation d'un objet qui permet de charger les labels fonction de la langue
- $this->labels = new XLabels();
- XLabels::loadLabels('general');
- XLabels::loadLabels('xfielddef');
- // cas ou il y a une classe
- if(!empty($moid) && empty($class)) {
- $ob = XModule::objectFactory(array('moid'=>$moid,'interactive'=>true));
- XLogs::debug('XShell::run: class is empty, moid='.$moid);
- } elseif(!empty($class) && (strtolower($class)!=strtolower(get_class($this)))) {
- // dans le cas ou la classe n'existe pas encore, on essaie d'include
- // le fichier qui correspond a la classe
- if(!class_exists($class)) {
- header('Location: /index.php');
- exit;
- }
- XLogs::debug('XShell::run: class is '.$class);
- $ob = new $class(array('interactive'=>true));
- } else {
- XLogs::debug('XShell::run: class is empty and moid is empty');
- $ob=$this;
- $class=get_class($this);
- }
- // cas ou il y a une fonction
- $LANG_DATA=XShell::getLangData();
- if(!empty($f)) {
- // verification des droits : on créé un tableau avec tout les elements succeptibles d'etre utilisés
- if(isset($_REQUEST['oidit'])) $oid['oidit']=$_REQUEST['oidit'];
- if(!empty($_REQUEST['_selectedok']) && $_REQUEST['_selectedok']=='ok' && !empty($_REQUEST['_selected']))
- $oid['_selected']=&$_REQUEST['_selected'];
- if(!empty($_REQUEST['oid'])) $oid['oids']=&$_REQUEST['oid'];
- else $oid['oids']='';
- XLogs::notice('uri_decode',@$_SERVER['REQUEST_URI']."->class=$class&function=$f&oid=$oid&template=$template&moid=$moid&lang=$LANG_DATA");
- $this->security_check($class, $f, $moid, $LANG_DATA, $oid);
- $oid2='';
- if(isset($oid['oidit'])) $oid2=$oid['oidit'];
- elseif(!empty($oid['oids'])) $oid2=$oid['oids'];
- if(method_exists($ob, 'secObjectAccess') && !is_array($oid2)) {
- $ob->secObjectAccess($f, $LANG_DATA, $oid2);
- }
- // mecanisme permettant d'eviter les doubles insert en gerant deux etats
- if(isset($_REQUEST["uniqid"])) {
- $uniqid=$_REQUEST["uniqid"];
- if($_SESSION["LASTCOMMITEDFORM"]==$uniqid){
- XLogs::notice('XShell::run','Form already submitted');
- XShell::redirect2error(array('message'=>XLabels::getSysLabel('general','operation_duplicated','text')));
- }
- else
- $_SESSION["LASTCOMMITEDFORM"]=$uniqid;
- }
- }
- $ar2=array();
- if(!isset($_REQUEST['tplentry'])) $ar2['tplentry']='';
- $ar2['interactive']=true;
- // appel de la fonction de la page en cours
- if(!empty($f)) {
- $ob->$f($ar2);
- $this->_function=$f;
- }
- // redirection sur la page next. calcul du next eventuel.
- // le next positionne par l'application avec la methode setNext est prioritaire sur
- // la query string (_next)
- if (empty($this->_next) && !empty($_REQUEST['_next']))
- $this->setNext($_REQUEST['_next']);
- if(!empty($this->_next)) {
- if(XShell::_iframeencode())
- XShell::setNextData('_iframeencode',1);
- $more='';
- if(!empty($this->_nextData))
- $more=(strpos($this->_next,'?')===false?'?':'&').http_build_query($this->_nextData);
- XLogs::debug('redirect to '.$this->_next.$more);
- header('Location: '.$this->_next.$more);
- exit(0);
- }
- if(XShell::admini_mode() && XShell::_raw()<2) {
- // generation des menus specifiques des modules
- if(method_exists($ob, 'nav')) {
- $ar2['_function']=$f;
- $ob->nav($ar2);
- }
- if(method_exists($ob,'actionlist')) {
- $navig=&$ob->actionlist1();
- XShell::toScreen1('inav', $navig);
- }
- }
- // appel des callback
- if(!XShell::_raw() && !empty($this->_callback)) {
- for($i=0;$i<count($this->_callback);$i++) {
- $func=$this->_callback[$i];
- if(!empty($func))
- $this->$func();
- }
- }
- // si la réponse est pas déjà caculéé
- if (!empty($this->response) && !empty($this->response->complete)) {
- $display = $this->response->content;
- } else {
- list($template,$templates)=$this->setTemplates(NULL,true);
- // par defaut instanciation de templetisation
- // par defaut template en parametre
- if(is_array($templates)) {
- $template=$templates[0];
- } else $template=$templates;
- $xtemplate = new XTemplate($template);
- // recherche des libelles en fonction de la langue lorsqu'on est en mode admnistration.
- if(issetSessionVar('ADMIN') || ($template=='proc_auth.html')||($template=='auth.html')) {
- XLabels::loadLabels('admini');
- }
- $labels = $this->labels->get_labels(array('selectors'=>array('global'),'local'=>true));
- // application du template
- // recherche des donnees a transmettre en auto
- $xtemplate->set_glob(array('templates'=>&$templates));
- if(is_array($ar)) {
- $xtemplate->set_glob($ar);
- }
- if(isset($labels) && is_array($labels)) {
- $xtemplate->set_glob(array('labels'=>&$labels));
- }
- XLogs::debug('XShell::run: before parse file');
- $display = $xtemplate->parse($this->tpldata,$this->rawdata);
- }
- // mettre en cache
- if ($this->_cache)
- $cache->store($display, $template, $ar);
- // Suppression des parametress contextuel en session
- if(issetSessionVar('message')) clearSessionVar('message');
- if(issetSessionVar('_reloadmenu')) clearSessionVar('_reloadmenu');
- if(issetSessionVar('_reloadmods')) clearSessionVar('_reloadmods');
- // Met à jour le token d'activité
- if(XUser::get_current_user_uid()){
- XUser::updateDbSessionDataUPD('last_activity');
- }
- $charset = XLang::getCharset();
- header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
- header('Content-type: '.$mime.'; charset='.strtolower($charset));
- if(!empty($_disp)) {
- $filename = is_array($templates) ? $templates[0] : $templates;
- header('Content-disposition: '.$_disp.'; filename='.$filename);
- }
- XLogs::debug('XShell::run: start sending file');
- if( (empty($_SERVER['HTTP_USER_AGENT']) || substr($_SERVER['HTTP_USER_AGENT'],0,6) != "Smarty") && $charset != TZR_INTERNAL_CHARSET){
- convert_charset($display, TZR_INTERNAL_CHARSET, $charset);
- }
- // Dans le cas d'une soumission d'un formulaire via iframe caché, on me le réultat dans un textarea pour empecher l'execution des scripts dans l'iframe
- if(XShell::_iframeencode())
- echo '<textarea id="_iframeencode">'.@htmlentities($display,ENT_COMPAT,$charset).'</textarea>';
- else
- echo $display;
- XLogs::debug('XShell::run: end sending file');
- XLogs::debug('XShell::run: end');
- // log audit infos
- XLogs::debug(XAudit::show());
- return true;
- }
- static function changeTemplate($t) {
- $_REQUEST["_template"]=$t;
- }
- /// Insere les données de la page dans la pile historique
- function insert_back() {
- if(!is_array($_SESSION['BACK'])) $_SESSION['BACK']=array();
- $CTXT=array('_REQUEST'=>$_REQUEST,
- '_SERVER'=>array('REQUEST_URI'=>@$_SERVER['REQUEST_URI'],'REQUEST_METHOD'=>@$_SERVER['REQUEST_METHOD']));
- $_SESSION['BACK'][XShell::$_bdxprefix][XShell::$_bdx]=$CTXT;
- XShell::$_bdx++;
- // On supprime ce qui est trop vieux dans l'historique pour éviter de faire exploser la pile
- unset($_SESSION['BACK'][XShell::$_bdxprefix-TZR_BACK_STACK_SIZE-3]);
- unset($_SESSION['BACK'][XShell::$_bdxprefix][XShell::$_bdx-TZR_BACK_STACK_SIZE-3]);
- }
- function back() {
- list($p,$n)=explode('_',$_REQUEST['n']);
- $tokeep=array('_iframeencode','_nohistory','_bdxnewstack','LANG_DATA','LANG_TRAD','skip','_skip','_reloadmods','_reloadmenu','message','_tabs','filename','fileoriginalname','filemime');
- $tokeepvalues=array();
- if(!empty($_SESSION['BACK'][$p][$n])) {
- foreach($tokeep as $f) $tokeepvalues[$f]=@$_REQUEST[$f];
- $_REQUEST=$_SESSION['BACK'][$p][$n]['_REQUEST'];
- $_SERVER=array_merge($_SERVER,$_SESSION['BACK'][$p][$n]['_SERVER']);
- foreach($tokeepvalues as $f=>$v){
- if($v!==NULL) $_REQUEST[$f]=$v;
- else unset($_REQUEST[$f]);
- }
- } else {
- $ar["message"]=XLabels::getSysLabel('xsession.messages','noback');
- $this->redirect2error($ar);
- die();
- }
- }
- function get_back_url($delta=-1) {
- $topback=XShell::$_bdx+$delta-1;
- if(isset($_SESSION['BACK'][XShell::$_bdxprefix][$topback]) && is_array($_SESSION['BACK'][XShell::$_bdxprefix][$topback]['_REQUEST'])) {
- return $GLOBALS['TZR_SESSION_MANAGER']::complete_self().'&function=back&n='.XShell::$_bdxprefix.'_'.$topback;
- } else {
- return NULL;
- }
- }
- function redirect($ar) {
- if(XShell::admini_mode()) {
- $this->_bdx--;
- unset($_SESSION['BACK'][XShell::$_bdxprefix][XShell::$_bdx]);
- }
- if(is_array($ar)) {
- reset($ar);
- while(list($a, $b)=each($ar)){
- $_REQUEST[$a]=$b;
- }
- }
- $this->run($ar);
- $this->exit_tzr();
- }
- // gestion des upgrades
- protected function _checkupgrade() {
- $current=(int)XIni::get('console_release');
- $past=(int)XIni::get('upgrades_release');
- if(empty($past) || ($past<112)) {
- die('Vous devez upgrader en version 7.1 avant de passer en version 8');
- }
- if($past<$current) {
- if(!getLock('consoleupgrade')) exit('upgrade en cours');
- $ini=new XIni();
- for($releases=$past+1;$releases<=$current;$releases++) {
- XLogs::notice('checkupgrade','upgrading from '.$releases.' to '.$current);
- // Fait un dump de la base sans la table de logs pour alleger
- $foo=explode(':',$GLOBALS['DATABASE_HOST']);
- system('mysqldump --add-drop-table -u'.$GLOBALS['DATABASE_USER'].' -p'.$GLOBALS['DATABASE_PASSWORD'].' '.
- '-h'.$foo[0].(!empty($foo[1])?' -P'.$foo[1]:'').' --ignore-table '.$GLOBALS['DATABASE_NAME'].'.LOGS '.
- $GLOBALS['DATABASE_NAME'].'>'.TZR_TMP_DIR.'dumppre'.$releases.'.sql');
- include('upgrades/'.$releases.'.inc');
- $ini->addVariable(array('section'=>'Upgrades',
- 'variable'=>'upgrades_release',
- 'value'=>$releases));
- loadIni(true);
- echo $releases;
- if (isset($GLOBALS['_REQUEST']) && isset($GLOBALS['_REQUEST']['message'])){
- echo $GLOBALS['_REQUEST']['message'];
- $tmess = preg_replace("/<br( \/)?>/i", "\n", $GLOBALS['_REQUEST']['message']);
- bugWarning("upgrade $releases\n".$tmess, false, false);
- } else {
- echo ' ok';
- }
- die();
- }
- }
- }
- // decodage de l'url quand on arrive avec une url de la forme
- // /toto.html ou toto est un alias, par exemple
- //
- public function decodeRewriting($url) {
- $nurl="index.php?";
- if(preg_match('@^/([^/\.]+)\.html$@i',$url) && file_exists(TZR_WWW_DIR.$url)) {
- header('Content-type: text/html');
- @readfile(TZR_WWW_DIR.$url);
- die();
- }
- if(preg_match('@^/([^/\.]+)\.xml$@i',$url) && file_exists(TZR_WWW_DIR.$url)) {
- header('Content-type: text/xml');
- @readfile(TZR_WWW_DIR.$url);
- die();
- }
- if(preg_match('@^/GOOGLE([A-Za-z0-9]+)\.html$@',$url)) {
- header("HTTP/1.1 404 Not Found");
- exit(0);
- }
- if(preg_match('@^/noexist_([A-Za-z0-9]+)\.html$@',$url)) {
- header("HTTP/1.1 404 Not Found");
- exit(0);
- }
- $matches=array();
- if(preg_match('/^\/google([A-Za-z0-9]+)\.html$/',$url,$matches)) {
- echo 'google-site-verification: google'.$matches[1].'.html';
- header("HTTP/1.1 200 OK");
- exit(0);
- }
- if(preg_match('@^/'.TZR_REWRITING_PREFIX.'([^\.]*).(html|xml)@i',$url,$eregs)) {
- $rw=&$GLOBALS['TZR_REWRITING'];
- foreach($rw as $src => $dst) {
- $src=preg_replace('/(%%[0-9]+)/','',$src);
- $dst=preg_replace('/\(%%([0-9]+)[^\)]+\)/','{$eregs[$1]}',$dst);
- if(preg_match('@'.$src.'@i',$url,$eregs)) {
- eval("\$vars=\"$dst\";");
- break;
- }
- }
- if(!empty($vars)) {
- parse_str($vars, $nvars);
- $_REQUEST=array_merge($_REQUEST,$nvars);
- $nurl.='&'.$vars;
- }
- } else {
- /* decodage des alias */
- $ks = array_keys($GLOBALS['TZR_LANGUAGES']);
- $ks1='('.implode('|',$ks).')';
- if(preg_match('@^/'.$ks1.'_([^\./]+)\.html$@',$url)) {
- if(preg_match('@^/'.$ks1.'_oidit_([^_]+)_([^/\._]+)\.html(.*)$@',$url,$eregs)) {
- $params=parse_url($eregs[4]);
- $_REQUEST['_lang']=$eregs[1];
- $_REQUEST['oidit']=$eregs[2].":".$eregs[3];
- $nurl.="_lang=".$eregs[1]."&oidit=".$eregs[2].":".$eregs[3];
- } elseif(preg_match('@^/'.$ks1.'_([^_]{1}[^/\.]+)\.html(.*)$@',$url,$eregs)) {
- $params=parse_url($eregs[3]);
- $_REQUEST['_lang']=$eregs[1];
- $_REQUEST['alias']=$eregs[2];
- $nurl.="_lang=".$eregs[1]."&alias=".$eregs[2];
- }
- } else {
- if(preg_match('@^/oidit_([^/\._]+)_([^/\._]+)\.html(.*)$@',$url,$eregs)) {
- $params=parse_url($eregs[3]);
- $_REQUEST['oidit']=$eregs[1].":".$eregs[2];
- $nurl.="oidit=".$eregs[1].":".$eregs[2];
- } elseif(preg_match('@^/([^/\.]+)\.html(.*)$@',$url,$eregs)) {
- $rw = &$GLOBALS['TZR_REWRITING'];
- if (array_key_exists($eregs[1], $rw)) {
- $params = explode('&', $rw[$eregs[1]]);
- foreach ($params as $p) {
- list($k, $v) = explode('=', $p);
- $_REQUEST[$k] = $v;
- }
- $params = parse_url($eregs[2]);
- } else {
- $params=parse_url($eregs[2]);
- $_REQUEST['alias']=$eregs[1];
- $nurl.="alias=".$eregs[1]."&".$eregs[2];
- }
- }
- }
- }
- if(!empty($params)) $_REQUEST=array_merge($_REQUEST,$params);
- if(!empty($_REQUEST['alias']) && XSystem::tableExists('_REWRITE')){
- $lg=XShell::getLangData();
- $ors=selectQueryGetOne('select * from _REWRITE where alias="'.$_REQUEST['alias'].'" and LANG="'.$lg.'" limit 1');
- if(!empty($ors)){
- unset($_REQUEST['alias']);
- $_REQUEST['oidit']=$ors['rub'];
- parse_str($ors['cplt'],$params);
- if(!empty($params)) $_REQUEST=array_merge($_REQUEST,$params);
- }
- }
- if($nurl!="index.php?") {
- $_SERVER['REQUEST_URI']="/".$nurl;
- $GLOBALS['TZR_SELF']='/index.php';
- $_SERVER['SCRIPT_NAME']='/index.php';
- }
- XShell::_changeLang();
- XShell::getLangData(NULL,true);
- XLogs::debug('XShell::decoderewriting: <'.$url.'>-><'.$nurl.'>');
- }
- // encodage d'une url d'une url dynamique vers une url statique
- //
- public function encodeRewriting(&$html) {
- $scriptname=$GLOBALS["TZR_SELF"];
- if(substr($scriptname,0,1)=='/') $scriptname=substr($scriptname,1);
- $todst='';
- if(strpos($scriptname,'index.php')===false && strpos($scriptname,'mobile.php')===false) {
- if(preg_match('@^([a-z0-9]+)\.php$@i',$scriptname,$eregs1)) {
- $todst=$eregs1[1].'_';
- }
- }
- $limiter='("|;|#)';
- $rw=&$GLOBALS['TZR_REWRITING'];
- foreach($rw as $src => $dst) {
- $dst=preg_replace('/(%%[0-9]+)/','',$dst);
- $src=preg_replace('@\(%%([0-9]+)([^\)]+)\)@','\$\\1',$src);
- $dst='index.php?&*'.$dst;
- $dst=str_replace('?','\?', $dst);
- if($GLOBALS['TZR_REWRITING_CASESENSITIVE']) {
- $html=preg_replace('@'.$dst.'@', TZR_REWRITING_PREFIX.$src, $html);
- XLogs::debug("XShell::encodeRewritingCaseSensitive: $dst -> $src");
- } else {
- $html=preg_replace('@'.$dst.'@i', TZR_REWRITING_PREFIX.$src, $html);
- XLogs::debug("XShell::encodeRewriting: $dst -> $src");
- }
- }
- /* rewriting avec les alias */
- if(count($GLOBALS['TZR_LANGUAGES'])>1) {
- $html=preg_replace('@'.$scriptname.'\?&*_lang=([A-Z]{2})&alias=([A-Za-z0-9_-]{2,80})("|;|`|\#|<)'.'@',
- $todst.'$1_$2.html$3',$html);
- $html=preg_replace('@'.$scriptname.'\?&*_lang=([A-Z]{2})&oidit=([A-Za-z0-9:]{2,10}):([A-Za-z0-9]{2,40})("|;|\#|`|<)@',
- $todst.'$1_oidit_$2_$3.html$4',$html);
- }
- $html=preg_replace('@'.$scriptname.'\?&*(amp;)?alias=([A-Za-z0-9_-]{2,80})("|;|`|\#|<)@',$todst.'$2.html$3',$html);
- $html=preg_replace('@'.$scriptname.'\?&*(amp;)?oidit=([A-Za-z0-9]{2,10}):([A-Za-z0-9]{2,40})("|`|;|#)@',
- $todst.'oidit_$2_$3.html$4',$html);
- $html=preg_replace('@'.$scriptname.'\?&*(amp;)?oidit=([A-Za-z0-9:]{2,40})("|`|;|#)@',$todst.'$2.html$3',$html);
- }
- function index() {
- if(is_array($_REQUEST['labels'])){
- foreach($_REQUEST['labels'] as $l){
- XLabels::loadLabels($l);
- }
- }
- }
- function dummy() {
- return array(0=>"toto");
- }
- }
- ?>