aliroAbstractRequest.php

Go to the documentation of this file.
00001 <?php
00002 
00003 abstract class aliroAbstractRequest {
00004     // Singleton object holder - will contain the single instance of aliroUserRequest or aliroAdminRequest
00005     protected static $instance = null;
00006 
00007     // Request attributes
00008     protected $option = '';
00009     protected $isHome = false;
00010     protected $formcheck = 0;
00011     protected $component_name = '';
00012     protected $bestmatch = null;
00013     protected $aliroVersion = '';
00014     protected $urlerror = false;
00015     protected $title = '';
00016     protected $metatags = array();
00017     protected $customtags = array();
00018     protected $templateName = '';
00019     protected $templateObject = null;
00020     protected $do_gzip = false;
00021     protected $error_message = array();
00022     protected $overlib = false;
00023 
00024     // Core singleton objects providing key information resources
00025     protected $user = null;
00026     protected $critical = null;
00027     protected $configuration = null;
00028     protected $pathway = null;
00029     protected $version = null;
00030 
00031     // Singleton "handler" objects
00032     protected $mhandler = null;
00033     protected $chandler = null;
00034     protected $xhandler = null;
00035     protected $purifier = null;
00036 
00037 
00038     protected function __construct () {
00039         // This is not necessarily right - but should avoid getting a notice
00040         if (function_exists('date_default_timezone_set')) date_default_timezone_set('UTC');
00041         @set_magic_quotes_runtime( 0 );
00042         //require_once(criticalInfo::getInstance()->absolute_path.'/includes/phpgettext/phpgettext.class.php');
00043         // Note that none of the things called here can use aliroAbstractRequest!
00044         // Otherwise, a loop will be created and Aliro will fail!
00045         // Ensure session started straight away
00046 
00047         aliroSessionFactory::getSession();
00048         // Check for problems with globals - do after session has started to be able to handle session variables
00049         $this->handleGlobals();
00050         $this->setUsefulObjects();
00051         if (extension_loaded('zlib') AND $this->configuration->getCfg('gzip')) $this->do_gzip = true;
00052         $this->setHandlers();
00053         if (count($_POST)) $this->fixPostItems();
00054         $this->option = $this->component_name = strtolower($this->getParam($_REQUEST, 'option'));
00055         if ($this->option != 'login' AND $this->option != 'logout') $this->user = aliroUser::getInstance();
00056         if ($message = $this->getParam($_REQUEST, 'mosmsg')) {
00057             $severity = $this->getParam($_REQUEST, 'severity', _ALIRO_ERROR_INFORM);
00058             $this->setErrorMessage ($message, intval($severity));
00059         }
00060     }
00061 
00062     private function setHandlers () {
00063         $this->mhandler = aliroMenuHandler::getInstance();
00064         $this->chandler = aliroComponentHandler::getInstance();
00065         $this->xhandler = aliroExtensionHandler::getInstance();
00066     }
00067 
00068     private function setUsefulObjects () {
00069         $this->critical = criticalInfo::getInstance();
00070         // The include path is needed for HTMLpurifier (will possibly serve for other extensions too):
00071         set_include_path($this->critical->class_base.'/extclasses/');
00072         $this->version = version::getInstance();
00073         $this->aliroVersion = $this->version->RELEASE.'/'.$this->version->DEV_STATUS.'/'.$this->version->DEV_LEVEL;
00074         $this->configuration = aliroCore::getInstance();
00075         $this->configuration->fixLanguage();
00076     }
00077 
00078     protected function fixPostItems () {
00079         $this->formcheck = $this->checkFormStamp();
00080         if (_ALIRO_FORM_CHECK_EXPIRED == $this->formcheck OR _ALIRO_FORM_CHECK_FAIL == $this->formcheck) {
00081             $this->setErrorMessage(T_('Sorry, your request used an invalid or expired form, please try again'));
00082             $_POST = array();
00083         }
00084         if (_ALIRO_FORM_CHECK_REPEAT == $this->formcheck) {
00085             $this->setErrorMessage(T_('This form submission has already been processed'));
00086             $_POST = array();
00087         }
00088         if ($params = $this->getParam($_POST, 'params', null, _MOS_ALLOWHTML)) {
00089             $pobject = new aliroParameters();
00090             $pobject->processInput($params);
00091             $_POST['params'] = $pobject->asString();
00092         }
00093         if (isset($_POST['alironstask']) AND (!isset($_REQUEST['task']) OR !$_REQUEST['task'])) $_POST['task'] = $_REQUEST['task'] = $_POST['alironstask'];
00094     }
00095 
00096     protected function __clone () {
00097         // Declared to enforce singleton
00098     }
00099 
00100     public function __call ($method, $args) {
00101         // May want to add language
00102         foreach (array($this->configuration, $this->pathway) as $object) {
00103             if (method_exists($object, $method)) return call_user_func_array(array($object, $method), $args);
00104         }
00105         trigger_error (sprintf(T_('Invalid method call on aliroRequest - %s'), $method));
00106         echo aliroRequest::trace();
00107         return null;
00108     }
00109 
00110     public function __get ($property) {
00111         if (isset($this->critical->$property)) return $this->critical->$property;
00112         trigger_error (sprintf(T_('Invalid property request on aliroAbstractRequest - %s'), $property));
00113         return null;
00114     }
00115 
00116     private function handleGlobals () {
00117         $superglobals = array($_SERVER, $_ENV, $_FILES, $_COOKIE, $_POST, $_GET, $_SESSION);
00118 
00119         // Emulate register_globals on
00120         if (!ini_get('register_globals') AND aliroCore::getInstance()->getCfg('register_globals')) {
00121             foreach ($_GET as $key=>$value) {
00122                 if (!isset($GLOBALS[$key])) $GLOBALS[$key]=$value;
00123             }
00124             foreach ($_POST as $key=>$value) {
00125                 if (!isset($GLOBALS[$key])) $GLOBALS[$key]=$value;
00126             }
00127         }
00128         // Emulate register_globals off
00129         elseif (ini_get('register_globals') AND !$this->getCfg('register_globals')) {
00130             foreach ($superglobals as $superglobal) {
00131                 foreach ($superglobal as $key=>$value) {
00132                     unset( $GLOBALS[$key]);
00133                 }
00134             }
00135         }
00136     }
00137 
00138     public function getComponentName () {
00139         return $this->component_name;
00140     }
00141 
00142     public function showHead () {
00143         if (!isset($this->metatags['description'])) $this->appendMetaTag( 'description', $this->getCfg('MetaDesc') );
00144         if (!isset($this->metatags['keywords']))$this->appendMetaTag( 'keywords', $this->getCfg('MetaKeys') );
00145         $this->addMetaTag( 'robots', 'index, follow' );
00146         $html = $this->getHead();
00147         if ($this->getCfg('sef')) $html .= "<base href=\"{$this->getCfg('live_site')}/\" />\r\n";
00148         if ( $this->user->id ) $html .= "<script src='{$this->getCfg('live_site')}/includes/js/alirojavascript.js' type='text/javascript'></script>";
00149         return $html;
00150     }
00151 
00152     public function getFavIcon () {
00153         // Default favourites icon
00154         return $this->getCfg('live_site').'/images/favicon.ico';
00155     }
00156 
00157     public function getItemid () {
00158         return isset($this->bestmatch) ? $this->bestmatch->id : 0;
00159     }
00160 
00161     public function getOption () {
00162         return $this->option;
00163     }
00164 
00165     public function redirect ($url='', $message='', $severity=_ALIRO_ERROR_INFORM) {
00166         if (is_null($url) OR !$url) $url = '';
00167         else {
00168             $url = $this->stripFromURL($url, 'mosmsg');
00169             $url = $this->stripFromURL($url, 'severity');
00170         }
00171         if ($message AND !$url) $url = 'index.php';
00172         if (strpos($url, 'http') !== 0) {
00173             if ($url AND $url[0] != '/') $url = '/'.$url;
00174             $url = $this->siteBaseURL.$url;
00175         }
00176         if ($message) {
00177             $url .= (strpos($url, '?') ? '&' : '?').'mosmsg='.urlencode($message);
00178             if ($severity) $url .= '&severity='.intval($severity);
00179         }
00180         @session_write_close();
00181         if (headers_sent()) printf (T_('Please click on %s this link %s to continue'), "<a href='$url'>", '</a>');
00182         else {
00183             @ob_end_clean(); // clear output buffer
00184             header( "Location: $url" );
00185         }
00186         exit();
00187     }
00188 
00189     public function redirectSame ($message='', $severity=_ALIRO_ERROR_INFORM) {
00190         $url = 'index.php?'.$_SERVER['QUERY_STRING'];
00191         $this->redirect ($url, $message, $severity);
00192     }
00193 
00194     public function stripFromURL ($url, $property) {
00195         if ($position = strpos($url, $property)) {
00196             if ($endpos = strpos($url, '&', $position)) $url = substr($url, 0, $position).substr($url, $endpos+1);
00197             else $url = substr($url, 0, $position-1);
00198         }
00199         return $url;
00200     }
00201 
00202     public function setErrorMessage ($message, $severity=_ALIRO_ERROR_FATAL) {
00203         $this->error_message[$severity][] = $message;
00204     }
00205 
00206     public function isErrorLevelSet ($severity) {
00207         return isset($this->error_message[$severity]);
00208     }
00209 
00210     public function pullErrorMessages () {
00211         $messages = $this->error_message;
00212         $this->error_message = array();
00213         return $messages;
00214     }
00215 
00216     public function getUserState( $var_name ) {
00217         return is_array($_SESSION["aliro_{$this->prefix}state"]) ? $this->getParam($_SESSION["aliro_{$this->prefix}state"], $var_name) : null;
00218     }
00219 
00220     public function setUserState( $var_name, $var_value ) {
00221         $_SESSION["aliro_{$this->prefix}state"][$var_name] = $var_value;
00222     }
00223 
00224     protected function isUserStateSet ($var_name) {
00225         return isset($_SESSION["aliro_{$this->prefix}state"][$var_name]);
00226     }
00227 
00228     public function getUserStateFromRequest($var_name, $req_name, $var_default=null) {
00229         if (isset($_REQUEST[$req_name])) {
00230             if ((string) $var_default == (string) (int) $var_default) $_REQUEST[$req_name] = intval($_REQUEST[$req_name]);
00231             $this->setUserState($var_name, $_REQUEST[$req_name]);
00232         }
00233         elseif (isset($var_default) AND !$this->isUserStateSet($var_name)) $this->setUserState($var_name, $var_default);
00234         return $this->getUserState($var_name);
00235     }
00236 
00237     public function makeFormStamp () {
00238         $formid = md5(uniqid(mt_rand(), true));
00239         $checker = md5(uniqid(mt_rand(), true));
00240         $_SESSION['aliro_formid_'.$formid] = $checker;
00241         $_SESSION['aliro_formdone_'.$formid] = 0;
00242         $html = <<<FORM_STAMP
00243         <input type="hidden" name="aliroformid" value="$formid" />
00244         <input type="hidden" name="alirochecker" value="$checker" />
00245 FORM_STAMP;
00246         return $html;
00247     }
00248 
00249     public function getFormCheckError () {
00250         $messages = array (
00251         _ALIRO_FORM_CHECK_EXPIRED => T_('Sorry, the form you used has expired, please try again'),
00252         _ALIRO_FORM_CHECK_FAIL => T_('Sorry, the form you used is invalid'),
00253         _ALIRO_FORM_CHECK_NULL => T_('Sorry, the form you used did not have a required authentication'),
00254         _ALIRO_FORM_CHECK_REPEAT => T_('The form you used has already been processed')
00255         );
00256         if ($this->formcheck) {
00257             if (isset($messages[$this->formcheck])) return $messages[$this->formcheck];
00258             else return T_('Internal error - invalid form check value');
00259         }
00260         else return '';
00261     }
00262 
00263     private function checkFormStamp () {
00264         $formid = $this->getParam($_POST, 'aliroformid');
00265         $checker = $this->getParam($_POST, 'alirochecker');
00266         if ($formid) {
00267             if (!isset($_SESSION['aliro_formid_'.$formid])) return _ALIRO_FORM_CHECK_EXPIRED;
00268             if ($_SESSION['aliro_formid_'.$formid] == $checker) {
00269                 if ($_SESSION['aliro_formdone_'.$formid]) return _ALIRO_FORM_CHECK_REPEAT;
00270                 else {
00271                     $_SESSION['aliro_formdone_'.$formid] = 1;
00272                     return _ALIRO_FORM_CHECK_OK;
00273                 }
00274             }
00275             else {
00276                 $this->setErrorMessage(T_('Form failed consistency check'), _ALIRO_ERROR_FATAL);
00277                 return _ALIRO_FORM_CHECK_FAIL;
00278             }
00279         }
00280         else return _ALIRO_FORM_CHECK_NULL;
00281     }
00282 
00283     public function getParam( &$arr, $name, $def=null, $mask=0 ) {
00284         if (isset( $arr[$name] )) {
00285             if (is_array($arr[$name])) foreach ($arr[$name] as $key=>$element) {
00286                 $result[$key] = $this->getParam ($arr[$name], $key, $def, $mask);
00287             }
00288             else {
00289                 $result = $arr[$name];
00290                 if (!($mask&_MOS_NOTRIM)) $result = trim($result);
00291                 if (!is_numeric($result)) {
00292                     if (get_magic_quotes_gpc() AND !($mask & _MOS_NOSTRIP)) $result = stripslashes($result);
00293                     if (!($mask&_MOS_ALLOWRAW) AND is_numeric($def)) $result = $def;
00294                     elseif ($result) {
00295                         if ($mask & _MOS_ALLOWHTML) $result = $this->doPurify($result);
00296                         else {
00297                             $result = strip_tags($result);
00298                             // $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
00299                         }
00300                     }
00301                 }
00302             }
00303             return $result;
00304         }
00305         return $def;
00306     }
00307 
00308     public function doPurify ($string) {
00309         if (null == $this->purifier) {
00310             $config = HTMLPurifier_Config::createDefault();
00311             if (criticalInfo::getInstance()->isAdmin) $config->set('HTML', 'Trusted', true);
00312             $this->purifier = new HTMLPurifier($config);
00313         }
00314         return $this->purifier->purify($string);
00315     }
00316 
00317     // Cannot be applied to items that return an array, only to a scalar
00318     public function getStickyParam (&$arr, $name, $def=null, $mask=0) {
00319         $var = 'aliro_sticky_'.$this->getComponentName().'_'.$name;
00320         return $this->getSticky ($var, $arr, $name, $def=null, $mask=0);
00321     }
00322 
00323     public function getStickyAliroParam (&$arr, $name, $def=null, $mask=0) {
00324         $var = 'aliro_sticky_aliro_'.$name;
00325         return $this->getSticky ($var, $arr, $name, $def=null, $mask=0);
00326     }
00327 
00328     private function getSticky ($var, &$arr, $name, $def, $mask) {
00329         if ((!isset($arr[$name]) OR !$arr[$name]) AND isset($_SESSION[$var])) return $_SESSION[$var];
00330         $provided = $this->getParam($arr, $name, $def, $mask);
00331         if ($provided) $_SESSION[$var] = $provided;
00332         return $provided;
00333     }
00334 
00335     public function unstick ($name) {
00336         $var = 'aliro_sticky_'.$this->getComponentName().'_'.$name;
00337         if (isset($_SESSION[$var])) unset ($_SESSION[$var]);
00338     }
00339 
00340     public function getTemplate() {
00341         if (!$this->templateName) $this->templateName = aliroTemplateHandler::getInstance()->getDefaultTemplateName();
00342         return $this->templateName;
00343     }
00344 
00345     public function setPageTitle ($title=null) {
00346         if ($this->getCfg('pagetitles')) {
00347             $title = trim($title);
00348             $base = $this->getCfg('sitename');
00349             $this->title = $title ?  $title.' - '.$base : $base;
00350         }
00351     }
00352 
00353     public function getPageTitle () {
00354         return $this->title;
00355     }
00356 
00357     protected function fix_metatag ($operation, $name, $content, $prepend='', $append='') {
00358         $content = trim(htmlspecialchars($content));
00359         if (!$content) return;
00360         $name = trim(htmlspecialchars($name));
00361         $prepend = trim($prepend);
00362         $append = trim($append);
00363         if ('new' == $operation) $this->metatags[$name] = array($content, $prepend, $append);
00364         else {
00365             $tag = isset($this->metatags[$name]) ?  $this->metatags[$name] : array('', '', '');
00366             if ('pre' == $operation) $tag[0] = $content.$tag[0];
00367             else $tag[0] = $content.(($tag[0] AND $content) ? ',' : '').$tag[0];
00368             $this->metatags[$name] = $tag;
00369         }
00370     }
00371 
00372     public function addMetaTag($name, $content, $prepend='', $append='') {
00373         $this->fix_metatag ('new', $name, $content, $prepend, $append);
00374     }
00375 
00376     public function appendMetaTag ($name, $content) {
00377         $this->fix_metatag ('post', $name, $content);
00378     }
00379 
00380     public function prependMetaTag ($name, $content) {
00381         $this->fix_metatag ('pre', $name, $content);
00382     }
00383 
00384     public function addCustomHeadTag ($html) {
00385         $this->customtags[] = trim ($html);
00386     }
00387 
00388     public function addScript ($relativeFile) {
00389         $link = <<<SCRIPT_LINK
00390 
00391     <script type="text/javascript" src="{$this->getCfg('live_site')}$relativeFile"></script>
00392 
00393 SCRIPT_LINK;
00394 
00395         $this->addCustomHeadTag($link);
00396     }
00397 
00398     public function addCSS ($relativeFile, $media='screen') {
00399         $link = <<<CSS_LINK
00400 
00401     <link href="{$this->getCfg('live_site')}$relativeFile" rel="stylesheet" type="text/css" media="$media" />
00402 
00403 CSS_LINK;
00404 
00405         $this->addCustomHeadTag($link);
00406     }
00407 
00408     public function setMetadataInCache (&$cache_object) {
00409         $cache_object->title = $this->title;
00410         $cache_object->metatags = $this->metatags;
00411         $cache_object->customtags = $this->customtags;
00412     }
00413 
00414     public function setMetadataFromCache ($cache_object) {
00415         $this->title = $cache_object->title;
00416         $this->metatags = $cache_object->metatags;
00417         $this->customtags = $cache_object->customtags;
00418     }
00419 
00420     public function requestOverlib () {
00421         if ($this->overlib) return;
00422         $html = <<<OVERLIB
00423         <script type="text/javascript" src="{$this->getCfg('live_site')}/includes/js/overlib_mini.js"></script>
00424 OVERLIB;
00425         $this->addCustomHeadTag ($html);
00426         $this->overlib = true;
00427     }
00428 
00429     public function divOverlib () {
00430         if ($this->overlib) return '<div id="overDiv" style="position:absolute; visibility:hidden; z-index:10000;"></div>';
00431         return '';
00432     }
00433 
00434     public function getDebug () {
00435         if ($this->getCfg('debug')) {
00436             $database = aliroDatabase::getInstance();
00437             $log = $database->getLogged();
00438             $database = aliroCoreDatabase::getInstance();
00439             $log .= $database->getLogged();
00440             $loader = aliroDebug::getInstance();
00441             $log .= $loader->getLogged();
00442             return $log;
00443         }
00444         else return '';
00445     }
00446 
00447     public function getHead() {
00448         $head[] = '<title>'.$this->title.'</title>';
00449         foreach ($this->metatags as $name=>$meta) {
00450             if ($meta[1]) $head[] = $meta[1];
00451             $head[] = '<meta name="' . $name . '" content="' . $meta[0] . '" />';
00452             if ($meta[2]) $head[] = $meta[2];
00453         }
00454         foreach ($this->customtags as $html) $head[] = $html;
00455         return implode( "\n", $head )."\n";
00456     }
00457 
00458     public function getCustomTags () {
00459         if (count($this->customtags)) return implode("\n", $this->customtags);
00460         return '';
00461     }
00462 
00463     public function getComponentObject () {
00464         if ($this->core_item) {
00465             $component = new aliroComponent();
00466             $component->option = $component->extformalname = $this->core_item;
00467             $component->name = $this->core_item;
00468             $component->adminclass = 'aliroComponentAdminManager';
00469         }
00470         else $component = $this->chandler->getComponentByFormalName($this->option);
00471         return $component;
00472     }
00473 
00474     protected function invokeComponent ($menu=null) {
00475         try {
00476             $this->chandler->startBuffer();
00477             if (!$this->option AND $menu AND $menu->component) $this->option = $menu->component;
00478             $component = $this->getComponentObject();
00479             $message = T_('At entry of aliroRequest::invokeComponent');
00480             if (!$this->urlerror AND ($this->option OR $this->core_item)) {
00481                 $componentname = $this->option? $this->option : $this->core_item;
00482                 define ('_ALIRO_COMPONENT_NAME', $componentname);
00483                 if ($component) {
00484                     if ($this->pathway) $this->pathway->addItem($component->name, 'index.php?option='.$component->option);
00485                     $class = $this->getComponentClass($component);
00486                     if ($class) $this->standardCall ($component, $class, $menu);
00487                     else $this->urlerror = $this->retroCall ($menu);
00488                     if ($this->urlerror) trigger_error(T_('Retro call was unable to find component: ').$this->option);
00489                 }
00490                 else {
00491                     $this->urlerror = true;
00492                     $message = T_('Unable to find component object for ').$this->option;
00493                 }
00494             }
00495             else {
00496                 $this->urlerror = true;
00497                 if ($this->chandler->componentCount() AND $this->mhandler->getMenuCount('mainmenu')) {
00498                     $message = sprintf(T_('Failed on urlerror from SEF or no option (%s)'), $this->option);
00499                 }
00500             }
00501             if ($this->urlerror) new aliroPage404($message);
00502             $this->chandler->endBuffer();
00503         } catch (databaseException $exception) {
00504             $target = $this->core_item ? $this->core_item : $this->option;
00505             $message = sprintf(T_('A database error occurred on %s at %s while processing %s'), date('Y-M-d'), date('H:i:s'), $target);
00506             $errorkey = "SQL/{$exception->getCode()}/$target/$exception->dbname/{$exception->getMessage()}/$exception->sql";
00507             aliroErrorRecorder::getInstance()->recordError($message, $errorkey, $message, $exception);
00508             $this->redirect('', $message, _ALIRO_ERROR_FATAL);
00509         }
00510     }
00511 
00512     protected function standardCall ($component, $class, $menu) {
00513         $worker = new $class ($component, 'Aliro', $this->aliroVersion, $menu);
00514         $worker->activate();
00515     }
00516 
00517     protected function retroCall ($menu) {
00518         $mainframe = mosMainFrame::getInstance();
00519         $path = $mainframe->getPath($this->path_side);
00520         if (!$path) return true;
00521         $this->invokeRetroCode($path, null, $menu);
00522         return false;
00523     }
00524 
00525     public function invokeRetroCode ($path, $function=null, $menu=null) {
00526         $GLOBALS['task'] = $task = $this->getParam($_REQUEST, 'task');
00527         $GLOBALS['act'] = $act = $this->getParam($_REQUEST, 'act');
00528         $GLOBALS['id'] = $id = $this->getParam($_REQUEST, 'id', 0);
00529         $GLOBALS['section'] = $section = $this->getParam($_REQUEST, 'section');
00530         require_once ($this->critical->absolute_path.'/includes/mambofunc.php');
00531         $GLOBALS['acl'] = $acl = aliroAuthoriser::getInstance();
00532         $GLOBALS['my'] = $my = aliroUser::getInstance();
00533         $GLOBALS['gid'] = $gid = $my->gid;
00534         $GLOBALS['mainframe'] = $mainframe = mosMainFrame::getInstance();
00535         $GLOBALS['database'] = $database = aliroDatabase::getInstance();
00536         $GLOBALS['Itemid'] = $Itemid = $this->getItemid();
00537         $GLOBALS['option'] = $option = $this->option;
00538         $GLOBALS['_VERSION'] = $this->version;
00539 
00540         // This will not do - what should happen??
00541         $GLOBALS['mosConfig_lang'] = 'english';
00542 
00543         error_reporting(E_ALL);
00544         $this->globalizeConfig();
00545         foreach ($GLOBALS as $key=>$value) if ('mosConfig_' == substr($key,0,10)) $$key = $value;
00546         require($path);
00547         if ($function) $function();
00548         error_reporting(E_ALL|E_STRICT);
00549     }
00550 
00551 }

Generated on Thu Apr 17 13:03:26 2008 for ALIRO by  doxygen 1.5.5