/pradolite.php
PHP | 9635 lines | 9623 code | 1 blank | 11 comment | 266 complexity | 9963c86421231f6fd32c82a06ecb61a8 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * File Name: pradolite.php
- * Last Update: 2011/11/01 00:20:48
- * Generated By: buildscripts/phpbuilder/build.php
- *
- * This file is used in lieu of prado.php to boost PRADO application performance.
- * It is generated by expanding prado.php with included files.
- * Comments and trace statements are stripped off.
- *
- * Do not modify this file manually.
- */
- if(!defined('PRADO_DIR'))
- define('PRADO_DIR',dirname(__FILE__));
- if(!defined('PRADO_CHMOD'))
- define('PRADO_CHMOD',0777);
- class PradoBase
- {
- const CLASS_FILE_EXT='.php';
- private static $_aliases=array('System'=>PRADO_DIR);
- private static $_usings=array();
- private static $_application=null;
- private static $_logger=null;
- protected static $classExists = array();
- public static function getVersion()
- {
- return '3.1.10';
- }
- public static function initErrorHandlers()
- {
- set_error_handler(array('PradoBase','phpErrorHandler'),error_reporting());
- set_exception_handler(array('PradoBase','exceptionHandler'));
- }
- public static function autoload($className)
- {
- include_once($className.self::CLASS_FILE_EXT);
- if(!class_exists($className,false) && !interface_exists($className,false))
- self::fatalError("Class file for '$className' cannot be found.");
- }
- public static function poweredByPrado($logoType=0)
- {
- $logoName=$logoType==1?'powered2':'powered';
- if(self::$_application!==null)
- {
- $am=self::$_application->getAssetManager();
- $url=$am->publishFilePath(self::getPathOfNamespace('System.'.$logoName,'.gif'));
- }
- else
- $url='http://www.pradosoft.com/images/'.$logoName.'.gif';
- return '<a title="Powered by PRADO" href="http://www.pradosoft.com/" target="_blank"><img src="'.$url.'" style="border-width:0px;" alt="Powered by PRADO" /></a>';
- }
- public static function phpErrorHandler($errno,$errstr,$errfile,$errline)
- {
- if(error_reporting()!=0)
- throw new TPhpErrorException($errno,$errstr,$errfile,$errline);
- }
- public static function exceptionHandler($exception)
- {
- if(self::$_application!==null && ($errorHandler=self::$_application->getErrorHandler())!==null)
- {
- $errorHandler->handleError(null,$exception);
- }
- else
- {
- echo $exception;
- }
- exit(1);
- }
- public static function setApplication($application)
- {
- if(self::$_application!==null)
- throw new TInvalidOperationException('prado_application_singleton_required');
- self::$_application=$application;
- }
- public static function getApplication()
- {
- return self::$_application;
- }
- public static function getFrameworkPath()
- {
- return PRADO_DIR;
- }
- public static function serialize($data)
- {
- $arr[0]=$data;
- return serialize($arr);
- }
- public static function unserialize($str)
- {
- $arr=unserialize($str);
- return isset($arr[0])?$arr[0]:null;
- }
- public static function createComponent($type)
- {
- if(!isset(self::$classExists[$type]))
- self::$classExists[$type] = class_exists($type, false);
- if( !isset(self::$_usings[$type]) && !self::$classExists[$type]) {
- self::using($type);
- self::$classExists[$type] = class_exists($type, false);
- }
- if( ($pos = strrpos($type, '.')) !== false)
- $type = substr($type,$pos+1);
- if(($n=func_num_args())>1)
- {
- $args = func_get_args();
- switch($n) {
- case 2:
- return new $type($args[1]);
- break;
- case 3:
- return new $type($args[1], $args[2]);
- break;
- case 4:
- return new $type($args[1], $args[2], $args[3]);
- break;
- case 5:
- return new $type($args[1], $args[2], $args[3], $args[4]);
- break;
- default:
- $s='$args[1]';
- for($i=2;$i<$n;++$i)
- $s.=",\$args[$i]";
- eval("\$component=new $type($s);");
- return $component;
- break;
- }
- }
- else
- return new $type;
- }
- public static function using($namespace,$checkClassExistence=true)
- {
- if(isset(self::$_usings[$namespace]) || class_exists($namespace,false))
- return;
- if(($pos=strrpos($namespace,'.'))===false) {
- try
- {
- include_once($namespace.self::CLASS_FILE_EXT);
- }
- catch(Exception $e)
- {
- if($checkClassExistence && !class_exists($namespace,false))
- throw new TInvalidOperationException('prado_component_unknown',$namespace,$e->getMessage());
- else
- throw $e;
- }
- }
- else if(($path=self::getPathOfNamespace($namespace,self::CLASS_FILE_EXT))!==null)
- {
- $className=substr($namespace,$pos+1);
- if($className==='*') {
- self::$_usings[$namespace]=$path;
- set_include_path(get_include_path().PATH_SEPARATOR.$path);
- }
- else {
- self::$_usings[$namespace]=$path;
- if(!$checkClassExistence || !class_exists($className,false))
- {
- try
- {
- include_once($path);
- }
- catch(Exception $e)
- {
- if($checkClassExistence && !class_exists($className,false))
- throw new TInvalidOperationException('prado_component_unknown',$className,$e->getMessage());
- else
- throw $e;
- }
- }
- }
- }
- else
- throw new TInvalidDataValueException('prado_using_invalid',$namespace);
- }
- public static function getPathOfNamespace($namespace, $ext='')
- {
- if(self::CLASS_FILE_EXT === $ext || empty($ext))
- {
- if(isset(self::$_usings[$namespace]))
- return self::$_usings[$namespace];
- if(isset(self::$_aliases[$namespace]))
- return self::$_aliases[$namespace];
- }
- $segs = explode('.',$namespace);
- $alias = array_shift($segs);
- if(null !== ($file = array_pop($segs)) && null !== ($root = self::getPathOfAlias($alias)))
- return rtrim($root.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR ,$segs),'/\\').(($file === '*') ? '' : DIRECTORY_SEPARATOR.$file.$ext);
- return null;
- }
- public static function getPathOfAlias($alias)
- {
- return isset(self::$_aliases[$alias])?self::$_aliases[$alias]:null;
- }
- protected static function getPathAliases()
- {
- return self::$_aliases;
- }
- public static function setPathOfAlias($alias,$path)
- {
- if(isset(self::$_aliases[$alias]))
- throw new TInvalidOperationException('prado_alias_redefined',$alias);
- else if(($rp=realpath($path))!==false && is_dir($rp))
- {
- if(strpos($alias,'.')===false)
- self::$_aliases[$alias]=$rp;
- else
- throw new TInvalidDataValueException('prado_aliasname_invalid',$alias);
- }
- else
- throw new TInvalidDataValueException('prado_alias_invalid',$alias,$path);
- }
- public static function fatalError($msg)
- {
- echo '<h1>Fatal Error</h1>';
- echo '<p>'.$msg.'</p>';
- if(!function_exists('debug_backtrace'))
- return;
- echo '<h2>Debug Backtrace</h2>';
- echo '<pre>';
- $index=-1;
- foreach(debug_backtrace() as $t)
- {
- $index++;
- if($index==0) continue;
- echo '#'.$index.' ';
- if(isset($t['file']))
- echo basename($t['file']) . ':' . $t['line'];
- else
- echo '<PHP inner-code>';
- echo ' -- ';
- if(isset($t['class']))
- echo $t['class'] . $t['type'];
- echo $t['function'] . '(';
- if(isset($t['args']) && sizeof($t['args']) > 0)
- {
- $count=0;
- foreach($t['args'] as $item)
- {
- if(is_string($item))
- {
- $str=htmlentities(str_replace("\r\n", "", $item), ENT_QUOTES);
- if (strlen($item) > 70)
- echo "'". substr($str, 0, 70) . "...'";
- else
- echo "'" . $str . "'";
- }
- else if (is_int($item) || is_float($item))
- echo $item;
- else if (is_object($item))
- echo get_class($item);
- else if (is_array($item))
- echo 'array(' . count($item) . ')';
- else if (is_bool($item))
- echo $item ? 'true' : 'false';
- else if ($item === null)
- echo 'NULL';
- else if (is_resource($item))
- echo get_resource_type($item);
- $count++;
- if (count($t['args']) > $count)
- echo ', ';
- }
- }
- echo ")\n";
- }
- echo '</pre>';
- exit(1);
- }
- public static function getUserLanguages()
- {
- static $languages=null;
- if($languages===null)
- {
- if(!isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
- $languages[0]='en';
- else
- {
- $languages=array();
- foreach(explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']) as $language)
- {
- $array=explode(';q=',trim($language));
- $languages[trim($array[0])]=isset($array[1])?(float)$array[1]:1.0;
- }
- arsort($languages);
- $languages=array_keys($languages);
- if(empty($languages))
- $languages[0]='en';
- }
- }
- return $languages;
- }
- public static function getPreferredLanguage()
- {
- static $language=null;
- if($language===null)
- {
- $langs=Prado::getUserLanguages();
- $lang=explode('-',$langs[0]);
- if(empty($lang[0]) || !ctype_alpha($lang[0]))
- $language='en';
- else
- $language=$lang[0];
- }
- return $language;
- }
- public static function trace($msg,$category='Uncategorized')
- {
- if(self::$_application && self::$_application->getMode()===TApplicationMode::Performance)
- return;
- if(!self::$_application || self::$_application->getMode()===TApplicationMode::Debug)
- {
- $trace=debug_backtrace();
- if(isset($trace[0]['file']) && isset($trace[0]['line']))
- $msg.=" (line {$trace[0]['line']}, {$trace[0]['file']})";
- $level=TLogger::DEBUG;
- }
- else
- $level=TLogger::INFO;
- self::log($msg,$level,$category);
- }
- public static function log($msg,$level=TLogger::INFO,$category='Uncategorized')
- {
- if(self::$_logger===null)
- self::$_logger=new TLogger;
- self::$_logger->log($msg,$level,$category);
- }
- public static function getLogger()
- {
- if(self::$_logger===null)
- self::$_logger=new TLogger;
- return self::$_logger;
- }
- public static function varDump($var,$depth=10,$highlight=false)
- {
- Prado::using('System.Util.TVarDumper');
- return TVarDumper::dump($var,$depth,$highlight);
- }
- public static function localize($text, $parameters=array(), $catalogue=null, $charset=null)
- {
- Prado::using('System.I18N.Translation');
- $app = Prado::getApplication()->getGlobalization(false);
- $params = array();
- foreach($parameters as $key => $value)
- $params['{'.$key.'}'] = $value;
- if($app===null || ($config = $app->getTranslationConfiguration())===null)
- return strtr($text, $params);
- if ($catalogue===null)
- $catalogue=isset($config['catalogue'])?$config['catalogue']:'messages';
- Translation::init($catalogue);
- $appCharset = $app===null ? '' : $app->getCharset();
- $defaultCharset = ($app===null) ? 'UTF-8' : $app->getDefaultCharset();
- if(empty($charset)) $charset = $appCharset;
- if(empty($charset)) $charset = $defaultCharset;
- return Translation::formatter($catalogue)->format($text,$params,$catalogue,$charset);
- }
- }
- class TReflectionClass extends ReflectionClass
- {
- }
- PradoBase::using('System.TComponent');
- PradoBase::using('System.Exceptions.TException');
- PradoBase::using('System.Util.TLogger');
- if(!class_exists('Prado',false))
- {
- class Prado extends PradoBase
- {
- }
- }
- spl_autoload_register(array('Prado','autoload'));
- Prado::initErrorHandlers();
- interface IModule
- {
- public function init($config);
- public function getID();
- public function setID($id);
- }
- interface IService
- {
- public function init($config);
- public function getID();
- public function setID($id);
- public function getEnabled();
- public function setEnabled($value);
- public function run();
- }
- interface ITextWriter
- {
- public function write($str);
- public function flush();
- }
- interface IUser
- {
- public function getName();
- public function setName($value);
- public function getIsGuest();
- public function setIsGuest($value);
- public function getRoles();
- public function setRoles($value);
- public function isInRole($role);
- public function saveToString();
- public function loadFromString($string);
- }
- interface IStatePersister
- {
- public function load();
- public function save($state);
- }
- interface ICache
- {
- public function get($id);
- public function set($id,$value,$expire=0,$dependency=null);
- public function add($id,$value,$expire=0,$dependency=null);
- public function delete($id);
- public function flush();
- }
- interface ICacheDependency
- {
- public function getHasChanged();
- }
- interface IRenderable
- {
- public function render($writer);
- }
- interface IBindable
- {
- public function dataBind();
- }
- interface IStyleable
- {
- public function getHasStyle();
- public function getStyle();
- public function clearStyle();
- }
- interface IActiveControl
- {
- public function getActiveControl();
- }
- interface ICallbackEventHandler
- {
- public function raiseCallbackEvent($eventArgument);
- }
- interface IDataRenderer
- {
- public function getData();
- public function setData($value);
- }
- class TApplicationComponent extends TComponent
- {
- public function getApplication()
- {
- return Prado::getApplication();
- }
- public function getService()
- {
- return Prado::getApplication()->getService();
- }
- public function getRequest()
- {
- return Prado::getApplication()->getRequest();
- }
- public function getResponse()
- {
- return Prado::getApplication()->getResponse();
- }
- public function getSession()
- {
- return Prado::getApplication()->getSession();
- }
- public function getUser()
- {
- return Prado::getApplication()->getUser();
- }
- public function publishAsset($assetPath,$className=null)
- {
- if($className===null)
- $className=get_class($this);
- $class=new ReflectionClass($className);
- $fullPath=dirname($class->getFileName()).DIRECTORY_SEPARATOR.$assetPath;
- return $this->publishFilePath($fullPath);
- }
- public function publishFilePath($fullPath)
- {
- return Prado::getApplication()->getAssetManager()->publishFilePath($fullPath);
- }
- }
- abstract class TModule extends TApplicationComponent implements IModule
- {
- private $_id;
- public function init($config)
- {
- }
- public function getID()
- {
- return $this->_id;
- }
- public function setID($value)
- {
- $this->_id=$value;
- }
- }
- abstract class TService extends TApplicationComponent implements IService
- {
- private $_id;
- private $_enabled=true;
- public function init($config)
- {
- }
- public function getID()
- {
- return $this->_id;
- }
- public function setID($value)
- {
- $this->_id=$value;
- }
- public function getEnabled()
- {
- return $this->_enabled;
- }
- public function setEnabled($value)
- {
- $this->_enabled=TPropertyValue::ensureBoolean($value);
- }
- public function run()
- {
- }
- }
- class TErrorHandler extends TModule
- {
- const ERROR_FILE_NAME='error';
- const EXCEPTION_FILE_NAME='exception';
- const SOURCE_LINES=12;
- private $_templatePath=null;
- public function init($config)
- {
- $this->getApplication()->setErrorHandler($this);
- }
- public function getErrorTemplatePath()
- {
- if($this->_templatePath===null)
- $this->_templatePath=Prado::getFrameworkPath().'/Exceptions/templates';
- return $this->_templatePath;
- }
- public function setErrorTemplatePath($value)
- {
- if(($templatePath=Prado::getPathOfNamespace($value))!==null && is_dir($templatePath))
- $this->_templatePath=$templatePath;
- else
- throw new TConfigurationException('errorhandler_errortemplatepath_invalid',$value);
- }
- public function handleError($sender,$param)
- {
- static $handling=false;
- restore_error_handler();
- restore_exception_handler();
- if($handling)
- $this->handleRecursiveError($param);
- else
- {
- $handling=true;
- if(($response=$this->getResponse())!==null)
- $response->clear();
- if(!headers_sent())
- header('Content-Type: text/html; charset=UTF-8');
- if($param instanceof THttpException)
- $this->handleExternalError($param->getStatusCode(),$param);
- else if($this->getApplication()->getMode()===TApplicationMode::Debug)
- $this->displayException($param);
- else
- $this->handleExternalError(500,$param);
- }
- }
- protected static function hideSecurityRelated($value, $exception=null)
- {
- $aRpl = array();
- if($exception !== null && $exception instanceof Exception)
- {
- $aTrace = $exception->getTrace();
- foreach($aTrace as $item)
- {
- $file = $item['file'];
- $aRpl[dirname($file) . DIRECTORY_SEPARATOR] = '<hidden>' . DIRECTORY_SEPARATOR;
- }
- }
- $aRpl[$_SERVER['DOCUMENT_ROOT']] = '${DocumentRoot}';
- $aRpl[str_replace('/', DIRECTORY_SEPARATOR, $_SERVER['DOCUMENT_ROOT'])] = '${DocumentRoot}';
- $aRpl[PRADO_DIR . DIRECTORY_SEPARATOR] = '${PradoFramework}' . DIRECTORY_SEPARATOR;
- if(isset($aRpl[DIRECTORY_SEPARATOR])) unset($aRpl[DIRECTORY_SEPARATOR]);
- $aRpl = array_reverse($aRpl, true);
- return str_replace(array_keys($aRpl), $aRpl, $value);
- }
- protected function handleExternalError($statusCode,$exception)
- {
- if(!($exception instanceof THttpException))
- error_log($exception->__toString());
- $content=$this->getErrorTemplate($statusCode,$exception);
- $serverAdmin=isset($_SERVER['SERVER_ADMIN'])?$_SERVER['SERVER_ADMIN']:'';
- $isDebug = $this->getApplication()->getMode()===TApplicationMode::Debug;
- $errorMessage = $exception->getMessage();
- if($isDebug)
- $version=$_SERVER['SERVER_SOFTWARE'].' <a href="http://www.pradosoft.com/">PRADO</a>/'.Prado::getVersion();
- else
- {
- $version='';
- $errorMessage = self::hideSecurityRelated($errorMessage, $exception);
- }
- $tokens=array(
- '%%StatusCode%%' => "$statusCode",
- '%%ErrorMessage%%' => htmlspecialchars($errorMessage),
- '%%ServerAdmin%%' => $serverAdmin,
- '%%Version%%' => $version,
- '%%Time%%' => @strftime('%Y-%m-%d %H:%M',time())
- );
- if($isDebug)
- header("HTTP/1.0 $statusCode ".$exception->getMessage(), true, TPropertyValue::ensureInteger($statusCode));
- else
- header("HTTP/1.0 $statusCode", true, TPropertyValue::ensureInteger($statusCode));
- echo strtr($content,$tokens);
- }
- protected function handleRecursiveError($exception)
- {
- if($this->getApplication()->getMode()===TApplicationMode::Debug)
- {
- echo "<html><head><title>Recursive Error</title></head>\n";
- echo "<body><h1>Recursive Error</h1>\n";
- echo "<pre>".$exception->__toString()."</pre>\n";
- echo "</body></html>";
- }
- else
- {
- error_log("Error happened while processing an existing error:\n".$exception->__toString());
- header('HTTP/1.0 500 Internal Error');
- }
- }
- protected function displayException($exception)
- {
- if(php_sapi_name()==='cli')
- {
- echo $exception->getMessage()."\n";
- echo $exception->getTraceAsString();
- return;
- }
- if($exception instanceof TTemplateException)
- {
- $fileName=$exception->getTemplateFile();
- $lines=empty($fileName)?explode("\n",$exception->getTemplateSource()):@file($fileName);
- $source=$this->getSourceCode($lines,$exception->getLineNumber());
- if($fileName==='')
- $fileName='---embedded template---';
- $errorLine=$exception->getLineNumber();
- }
- else
- {
- if(($trace=$this->getExactTrace($exception))!==null)
- {
- $fileName=$trace['file'];
- $errorLine=$trace['line'];
- }
- else
- {
- $fileName=$exception->getFile();
- $errorLine=$exception->getLine();
- }
- $source=$this->getSourceCode(@file($fileName),$errorLine);
- }
- if($this->getApplication()->getMode()===TApplicationMode::Debug)
- $version=$_SERVER['SERVER_SOFTWARE'].' <a href="http://www.pradosoft.com/">PRADO</a>/'.Prado::getVersion();
- else
- $version='';
- $tokens=array(
- '%%ErrorType%%' => get_class($exception),
- '%%ErrorMessage%%' => $this->addLink(htmlspecialchars($exception->getMessage())),
- '%%SourceFile%%' => htmlspecialchars($fileName).' ('.$errorLine.')',
- '%%SourceCode%%' => $source,
- '%%StackTrace%%' => htmlspecialchars($exception->getTraceAsString()),
- '%%Version%%' => $version,
- '%%Time%%' => @strftime('%Y-%m-%d %H:%M',time())
- );
- $content=$this->getExceptionTemplate($exception);
- echo strtr($content,$tokens);
- }
- protected function getExceptionTemplate($exception)
- {
- $lang=Prado::getPreferredLanguage();
- $exceptionFile=Prado::getFrameworkPath().'/Exceptions/templates/'.self::EXCEPTION_FILE_NAME.'-'.$lang.'.html';
- if(!is_file($exceptionFile))
- $exceptionFile=Prado::getFrameworkPath().'/Exceptions/templates/'.self::EXCEPTION_FILE_NAME.'.html';
- if(($content=@file_get_contents($exceptionFile))===false)
- die("Unable to open exception template file '$exceptionFile'.");
- return $content;
- }
- protected function getErrorTemplate($statusCode,$exception)
- {
- $base=$this->getErrorTemplatePath().DIRECTORY_SEPARATOR.self::ERROR_FILE_NAME;
- $lang=Prado::getPreferredLanguage();
- if(is_file("$base$statusCode-$lang.html"))
- $errorFile="$base$statusCode-$lang.html";
- else if(is_file("$base$statusCode.html"))
- $errorFile="$base$statusCode.html";
- else if(is_file("$base-$lang.html"))
- $errorFile="$base-$lang.html";
- else
- $errorFile="$base.html";
- if(($content=@file_get_contents($errorFile))===false)
- die("Unable to open error template file '$errorFile'.");
- return $content;
- }
- private function getExactTrace($exception)
- {
- $trace=$exception->getTrace();
- $result=null;
- if($exception instanceof TPhpErrorException)
- $result=isset($trace[0]['file'])?$trace[0]:$trace[1];
- else if($exception instanceof TInvalidOperationException)
- {
- if(($result=$this->getPropertyAccessTrace($trace,'__get'))===null)
- $result=$this->getPropertyAccessTrace($trace,'__set');
- }
- if($result!==null && strpos($result['file'],': eval()\'d code')!==false)
- return null;
- return $result;
- }
- private function getPropertyAccessTrace($trace,$pattern)
- {
- $result=null;
- foreach($trace as $t)
- {
- if(isset($t['function']) && $t['function']===$pattern)
- $result=$t;
- else
- break;
- }
- return $result;
- }
- private function getSourceCode($lines,$errorLine)
- {
- $beginLine=$errorLine-self::SOURCE_LINES>=0?$errorLine-self::SOURCE_LINES:0;
- $endLine=$errorLine+self::SOURCE_LINES<=count($lines)?$errorLine+self::SOURCE_LINES:count($lines);
- $source='';
- for($i=$beginLine;$i<$endLine;++$i)
- {
- if($i===$errorLine-1)
- {
- $line=htmlspecialchars(sprintf("%04d: %s",$i+1,str_replace("\t",' ',$lines[$i])));
- $source.="<div class=\"error\">".$line."</div>";
- }
- else
- $source.=htmlspecialchars(sprintf("%04d: %s",$i+1,str_replace("\t",' ',$lines[$i])));
- }
- return $source;
- }
- private function addLink($message)
- {
- $baseUrl='http://www.pradosoft.com/docs/classdoc';
- return preg_replace('/\b(T[A-Z]\w+)\b/',"<a href=\"$baseUrl/\${1}\" target=\"_blank\">\${1}</a>",$message);
- }
- }
- class TList extends TComponent implements IteratorAggregate,ArrayAccess,Countable
- {
- private $_d=array();
- private $_c=0;
- private $_r=false;
- public function __construct($data=null,$readOnly=false)
- {
- if($data!==null)
- $this->copyFrom($data);
- $this->setReadOnly($readOnly);
- }
- public function getReadOnly()
- {
- return $this->_r;
- }
- protected function setReadOnly($value)
- {
- $this->_r=TPropertyValue::ensureBoolean($value);
- }
- public function getIterator()
- {
- return new ArrayIterator( $this->_d );
- }
- public function count()
- {
- return $this->getCount();
- }
- public function getCount()
- {
- return $this->_c;
- }
- public function itemAt($index)
- {
- if($index>=0 && $index<$this->_c)
- return $this->_d[$index];
- else
- throw new TInvalidDataValueException('list_index_invalid',$index);
- }
- public function add($item)
- {
- $this->insertAt($this->_c,$item);
- return $this->_c-1;
- }
- public function insertAt($index,$item)
- {
- if(!$this->_r)
- {
- if($index===$this->_c)
- $this->_d[$this->_c++]=$item;
- else if($index>=0 && $index<$this->_c)
- {
- array_splice($this->_d,$index,0,array($item));
- $this->_c++;
- }
- else
- throw new TInvalidDataValueException('list_index_invalid',$index);
- }
- else
- throw new TInvalidOperationException('list_readonly',get_class($this));
- }
- public function remove($item)
- {
- if(($index=$this->indexOf($item))>=0)
- {
- $this->removeAt($index);
- return $index;
- }
- else
- throw new TInvalidDataValueException('list_item_inexistent');
- }
- public function removeAt($index)
- {
- if(!$this->_r)
- {
- if($index>=0 && $index<$this->_c)
- {
- $this->_c--;
- if($index===$this->_c)
- return array_pop($this->_d);
- else
- {
- $item=$this->_d[$index];
- array_splice($this->_d,$index,1);
- return $item;
- }
- }
- else
- throw new TInvalidDataValueException('list_index_invalid',$index);
- }
- else
- throw new TInvalidOperationException('list_readonly',get_class($this));
- }
- public function clear()
- {
- for($i=$this->_c-1;$i>=0;--$i)
- $this->removeAt($i);
- }
- public function contains($item)
- {
- return $this->indexOf($item)>=0;
- }
- public function indexOf($item)
- {
- if(($index=array_search($item,$this->_d,true))===false)
- return -1;
- else
- return $index;
- }
- public function toArray()
- {
- return $this->_d;
- }
- public function copyFrom($data)
- {
- if(is_array($data) || ($data instanceof Traversable))
- {
- if($this->_c>0)
- $this->clear();
- foreach($data as $item)
- $this->add($item);
- }
- else if($data!==null)
- throw new TInvalidDataTypeException('list_data_not_iterable');
- }
- public function mergeWith($data)
- {
- if(is_array($data) || ($data instanceof Traversable))
- {
- foreach($data as $item)
- $this->add($item);
- }
- else if($data!==null)
- throw new TInvalidDataTypeException('list_data_not_iterable');
- }
- public function offsetExists($offset)
- {
- return ($offset>=0 && $offset<$this->_c);
- }
- public function offsetGet($offset)
- {
- return $this->itemAt($offset);
- }
- public function offsetSet($offset,$item)
- {
- if($offset===null || $offset===$this->_c)
- $this->insertAt($this->_c,$item);
- else
- {
- $this->removeAt($offset);
- $this->insertAt($offset,$item);
- }
- }
- public function offsetUnset($offset)
- {
- $this->removeAt($offset);
- }
- }
- class TListIterator implements Iterator
- {
- private $_d;
- private $_i;
- private $_c;
- public function __construct(&$data)
- {
- $this->_d=&$data;
- $this->_i=0;
- $this->_c=count($this->_d);
- }
- public function rewind()
- {
- $this->_i=0;
- }
- public function key()
- {
- return $this->_i;
- }
- public function current()
- {
- return $this->_d[$this->_i];
- }
- public function next()
- {
- $this->_i++;
- }
- public function valid()
- {
- return $this->_i<$this->_c;
- }
- }
- abstract class TCache extends TModule implements ICache, ArrayAccess
- {
- private $_prefix=null;
- private $_primary=true;
- public function init($config)
- {
- if($this->_prefix===null)
- $this->_prefix=$this->getApplication()->getUniqueID();
- if($this->_primary)
- {
- if($this->getApplication()->getCache()===null)
- $this->getApplication()->setCache($this);
- else
- throw new TConfigurationException('cache_primary_duplicated',get_class($this));
- }
- }
- public function getPrimaryCache()
- {
- return $this->_primary;
- }
- public function setPrimaryCache($value)
- {
- $this->_primary=TPropertyValue::ensureBoolean($value);
- }
- public function getKeyPrefix()
- {
- return $this->_prefix;
- }
- public function setKeyPrefix($value)
- {
- $this->_prefix=$value;
- }
- protected function generateUniqueKey($key)
- {
- return md5($this->_prefix.$key);
- }
- public function get($id)
- {
- if(($value=$this->getValue($this->generateUniqueKey($id)))!==false)
- {
- $data=unserialize($value);
- if(!is_array($data))
- return false;
- if(!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged())
- return $data[0];
- }
- return false;
- }
- public function set($id,$value,$expire=0,$dependency=null)
- {
- if(empty($value) && $expire === 0)
- $this->delete($id);
- else
- {
- $data=array($value,$dependency);
- return $this->setValue($this->generateUniqueKey($id),serialize($data),$expire);
- }
- }
- public function add($id,$value,$expire=0,$dependency=null)
- {
- if(empty($value) && $expire === 0)
- return false;
- $data=array($value,$dependency);
- return $this->addValue($this->generateUniqueKey($id),serialize($data),$expire);
- }
- public function delete($id)
- {
- return $this->deleteValue($this->generateUniqueKey($id));
- }
- public function flush()
- {
- throw new TNotSupportedException('cache_flush_unsupported');
- }
- abstract protected function getValue($key);
- abstract protected function setValue($key,$value,$expire);
- abstract protected function addValue($key,$value,$expire);
- abstract protected function deleteValue($key);
- public function offsetExists($id)
- {
- return $this->get($id) !== false;
- }
- public function offsetGet($id)
- {
- return $this->get($id);
- }
- public function offsetSet($id, $value)
- {
- $this->set($id, $value);
- }
- public function offsetUnset($id)
- {
- $this->delete($id);
- }
- }
- abstract class TCacheDependency extends TComponent implements ICacheDependency
- {
- }
- class TFileCacheDependency extends TCacheDependency
- {
- private $_fileName;
- private $_timestamp;
- public function __construct($fileName)
- {
- $this->setFileName($fileName);
- }
- public function getFileName()
- {
- return $this->_fileName;
- }
- public function setFileName($value)
- {
- $this->_fileName=$value;
- $this->_timestamp=@filemtime($value);
- }
- public function getTimestamp()
- {
- return $this->_timestamp;
- }
- public function getHasChanged()
- {
- return @filemtime($this->_fileName)!==$this->_timestamp;
- }
- }
- class TDirectoryCacheDependency extends TCacheDependency
- {
- private $_recursiveCheck=true;
- private $_recursiveLevel=-1;
- private $_timestamps;
- private $_directory;
- public function __construct($directory)
- {
- $this->setDirectory($directory);
- }
- public function getDirectory()
- {
- return $this->_directory;
- }
- public function setDirectory($directory)
- {
- if(($path=realpath($directory))===false || !is_dir($path))
- throw new TInvalidDataValueException('directorycachedependency_directory_invalid',$directory);
- $this->_directory=$path;
- $this->_timestamps=$this->generateTimestamps($path);
- }
- public function getRecursiveCheck()
- {
- return $this->_recursiveCheck;
- }
- public function setRecursiveCheck($value)
- {
- $this->_recursiveCheck=TPropertyValue::ensureBoolean($value);
- }
- public function getRecursiveLevel()
- {
- return $this->_recursiveLevel;
- }
- public function setRecursiveLevel($value)
- {
- $this->_recursiveLevel=TPropertyValue::ensureInteger($value);
- }
- public function getHasChanged()
- {
- return $this->generateTimestamps($this->_directory)!=$this->_timestamps;
- }
- protected function validateFile($fileName)
- {
- return true;
- }
- protected function validateDirectory($directory)
- {
- return true;
- }
- protected function generateTimestamps($directory,$level=0)
- {
- if(($dir=opendir($directory))===false)
- throw new TIOException('directorycachedependency_directory_invalid',$directory);
- $timestamps=array();
- while(($file=readdir($dir))!==false)
- {
- $path=$directory.DIRECTORY_SEPARATOR.$file;
- if($file==='.' || $file==='..')
- continue;
- else if(is_dir($path))
- {
- if(($this->_recursiveLevel<0 || $level<$this->_recursiveLevel) && $this->validateDirectory($path))
- $timestamps=array_merge($this->generateTimestamps($path,$level+1));
- }
- else if($this->validateFile($path))
- $timestamps[$path]=filemtime($path);
- }
- closedir($dir);
- return $timestamps;
- }
- }
- class TGlobalStateCacheDependency extends TCacheDependency
- {
- private $_stateName;
- private $_stateValue;
- public function __construct($name)
- {
- $this->setStateName($name);
- }
- public function getStateName()
- {
- return $this->_stateName;
- }
- public function setStateName($value)
- {
- $this->_stateName=$value;
- $this->_stateValue=Prado::getApplication()->getGlobalState($value);
- }
- public function getHasChanged()
- {
- return $this->_stateValue!==Prado::getApplication()->getGlobalState($this->_stateName);
- }
- }
- class TChainedCacheDependency extends TCacheDependency
- {
- private $_dependencies=null;
- public function getDependencies()
- {
- if($this->_dependencies===null)
- $this->_dependencies=new TCacheDependencyList;
- return $this->_dependencies;
- }
- public function getHasChanged()
- {
- if($this->_dependencies!==null)
- {
- foreach($this->_dependencies as $dependency)
- if($dependency->getHasChanged())
- return true;
- }
- return false;
- }
- }
- class TApplicationStateCacheDependency extends TCacheDependency
- {
- public function getHasChanged()
- {
- return Prado::getApplication()->getMode()!==TApplicationMode::Performance;
- }
- }
- class TCacheDependencyList extends TList
- {
- public function insertAt($index,$item)
- {
- if($item instanceof ICacheDependency)
- parent::insertAt($index,$item);
- else
- throw new TInvalidDataTypeException('cachedependencylist_cachedependency_required');
- }
- }
- class TTextWriter extends TComponent implements ITextWriter
- {
- private $_str='';
- public function flush()
- {
- $str=$this->_str;
- $this->_str='';
- return $str;
- }
- public function write($str)
- {
- $this->_str.=$str;
- }
- public function writeLine($str='')
- {
- $this->write($str."\n");
- }
- }
- class TMap extends TComponent implements IteratorAggregate,ArrayAccess,Countable
- {
- private $_d=array();
- private $_r=false;
- public function __construct($data=null,$readOnly=false)
- {
- if($data!==null)
- $this->copyFrom($data);
- $this->setReadOnly($readOnly);
- }
- public function getReadOnly()
- {
- return $this->_r;
- }
- protected function setReadOnly($value)
- {
- $this->_r=TPropertyValue::ensureBoolean($value);
- }
- public function getIterator()
- {
- return new ArrayIterator( $this->_d );
- }
- public function count()
- {
- return $this->getCount();
- }
- public function getCount()
- {
- return count($this->_d);
- }
- public function getKeys()
- {
- return array_keys($this->_d);
- }
- public function itemAt($key)
- {
- return isset($this->_d[$key]) ? $this->_d[$key] : null;
- }
- public function add($key,$value)
- {
- if(!$this->_r)
- $this->_d[$key]=$value;
- else
- throw new TInvalidOperationException('map_readonly',get_class($this));
- }
- public function remove($key)
- {
- if(!$this->_r)
- {
- if(isset($this->_d[$key]) || array_key_exists($key,$this->_d))
- {
- $value=$this->_d[$key];
- unset($this->_d[$key]);
- return $value;
- }
- else
- return null;
- }
- else
- throw new TInvalidOperationException('map_readonly',get_class($this));
- }
- public function clear()
- {
- foreach(array_keys($this->_d) as $key)
- $this->remove($key);
- }
- public function contains($key)
- {
- return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
- }
- public function toArray()
- {
- return $this->_d;
- }
- public function copyFrom($data)
- {
- if(is_array($data) || $data instanceof Traversable)
- {
- if($this->getCount()>0)
- $this->clear();
- foreach($data as $key=>$value)
- $this->add($key,$value);
- }
- else if($data!==null)
- throw new TInvalidDataTypeException('map_data_not_iterable');
- }
- public function mergeWith($data)
- {
- if(is_array($data) || $data instanceof Traversable)
- {
- foreach($data as $key=>$value)
- $this->add($key,$value);
- }
- else if($data!==null)
- throw new TInvalidDataTypeException('map_data_not_iterable');
- }
- public function offsetExists($offset)
- {
- return $this->contains($offset);
- }
- public function offsetGet($offset)
- {
- return $this->itemAt($offset);
- }
- public function offsetSet($offset,$item)
- {
- $this->add($offset,$item);
- }
- public function offsetUnset($offset)
- {
- $this->remove($offset);
- }
- }
- class TMapIterator implements Iterator
- {
- private $_d;
- private $_keys;
- private $_key;
- public function __construct(&$data)
- {
- $this->_d=&$data;
- $this->_keys=array_keys($data);
- }
- public function rewind()
- {
- $this->_key=reset($this->_keys);
- }
- public function key()
- {
- return $this->_key;
- }
- public function current()
- {
- return $this->_d[$this->_key];
- }
- public function next()
- {
- $this->_key=next($this->_keys);
- }
- public function valid()
- {
- return $this->_key!==false;
- }
- }
- class TStack extends TComponent implements IteratorAggregate,Countable
- {
- private $_d=array();
- private $_c=0;
- public function __construct($data=null)
- {
- if($data!==null)
- $this->copyFrom($data);
- }
- public function toArray()
- {
- return $this->_d;
- }
- public function copyFrom($data)
- {
- if(is_array($data) || ($data instanceof Traversable))
- {
- $this->clear();
- foreach($data as $item)
- {
- $this->_d[]=$item;
- ++$this->_c;
- }
- }
- else if($data!==null)
- throw new TInvalidDataTypeException('stack_data_not_iterable');
- }
- public function clear()
- {
- $this->_c=0;
- $this->_d=array();
- }
- public function contains($item)
- {
- return array_search($item,$this->_d,true)!==false;
- }
- public function peek()
- {
- if($this->_c===0)
- throw new TInvalidOperationException('stack_empty');
- else
- return $this->_d[$this->_c-1];
- }
- public function pop()
- {
- if($this->_c===0)
- throw new TInvalidOperationException('stack_empty');
- else
- {
- --$this->_c;
- return array_pop($this->_d);
- }
- }
- public function push($item)
- {
- ++$this->_c;
- $this->_d[] = $item;
- }
- public function getIterator()
- {
- return new ArrayIterator( $this->_d );
- }
- public function getCount()
- {
- return $this->_c;
- }
- public function count()
- {
- return $this->getCount();
- }
- }
- class TStackIterator implements Iterator
- {
- private $_d;
- private $_i;
- private $_c;
- public function __construct(&$data)
- {
- $this->_d=&$data;
- $this->_i=0;
- $this->_c=count($this->_d);
- }
- public function rewind()
- {
- $this->_i=0;
- }
- public function key()
- {
- return $this->_i;
- }
- public function current()
- {
- return $this->_d[$this->_i];
- }
- public function next()
- {
- $this->_i++;
- }
- public function valid()
- {
- return $this->_i<$this->_c;
- }
- }
- class TXmlElement extends TComponent
- {
- private $_parent=null;
- private $_tagName='unknown';
- private $_value='';
- private $_elements=null;
- private $_attributes=null;
- public function __construct($tagName)
- {
- $this->setTagName($tagName);
- }
- public function getParent()
- {
- return $this->_parent;
- }
- public function setParent($parent)
- {
- $this->_parent=$parent;
- }
- public function getTagName()
- {
- return $this->_tagName;
- }
- public function setTagName($tagName)
- {
- $this->_tagName=$tagName;
- }
- public function getValue()
- {
- return $this->_value;
- }
- public function setValue($value)
- {
- $this->_value=TPropertyValue::ensureString($value);
- }
- public function getHasElement()
- {
- return $this->_elements!==null && $this->_elements->getCount()>0;
- }
- public function getHasAttribute()
- {
- return $this->_attributes!==null && $this->_attributes->getCount()>0;
- }
- public function getAttribute($name)
- {
- if($this->_attributes!==null)
- return $this->_attributes->itemAt($name);
- else
- return null;
- }
- public function setAttribute($name,$value)
- {
- $this->getAttributes()->add($name,TPropertyValue::ensureString($value));
- }
- public function getElements()
- {
- if(!$this->_elements)
- $this->_elements=new TXmlElementList($this);
- return $this->_elements;
- }
- public function getAttributes()
- {
- if(!$this->_attributes)
- $this->_attributes=new TMap;
- return $this->_attributes;
- }
- public function getElementByTagName($tagName)
- {
- if($this->_elements)
- {
- foreach($this->_elements as $element)
- if($element->_tagName===$tagName)
- return $element;
- }
- return null;
- }
- public function getElementsByTagName($tagName)
- {
- $list=new TList;
- if($this->_elements)
- {
- foreach($this->_elements as $element)
- if($element->_tagName===$tagName)
- $list->add($element);
- }
- return $list;
- }
- public function toString($indent=0)
- {
- $attr='';
- if($this->_attributes!==null)
- {
- foreach($this->_attributes as $name=>$value)
- {
- $value=$this->xmlEncode($value);
- $attr.=" $name=\"$value\"";
- }
- }
- $prefix=str_repeat(' ',$indent*4);
- if($this->getHasElement())
- {
- $str=$prefix."<{$this->_tagName}$attr>\n";
- foreach($this->getElements() as $element)
- $str.=$element->toString($indent+1)."\n";
- $str.=$prefix."</{$this->_tagName}>";
- return $str;
- }
- else if(($value=$this->getValue())!=='')
- {
- $value=$this->xmlEncode($value);
- return $prefix."<{$this->_tagName}$attr>$value</{$this->_tagName}>";
- }
- else
- return $prefix."<{$this->_tagName}$attr />";
- }
- public function __toString()
- {
- return $this->toString();
- }
- private function xmlEncode($str)
- {
- return strtr($str,array(
- '>'=>'>',
- '<'=>'<',
- '&'=>'&',
- '"'=>'"',
- "\r"=>'
',
- "\t"=>'	',
- "\n"=>'
'));
- }
- }
- class TXmlDocument extends TXmlElement
- {
- private $_version;
- private $_encoding;
- public function __construct($version='1.0',$encoding='')
- {
- parent::__construct('');
- $this->setVersion($version);
- $this->setEncoding($encoding);
- }
- public function getVersion()
- {
- return $this->_version;
- }
- public function setVersion($version)
- {
- $this->_version=$version;
- }
- public function getEncoding()
- {
- return $this->_encoding;
- }
- public function setEncoding($encoding)
- {
- $this->_encoding=$encoding;
- }
- public function loadFromFile($file)
- {
- if(($str=@file_get_contents($file))!==false)
- return $this->loadFromString($str);
- else
- throw new TIOException('xmldocument_file_read_failed',$file);
- }
- public function loadFromString($string)
- {
- $doc=new DOMDocument();
- if($doc->loadXML($string)===false)
- return false;
- $this->setEncoding($doc->encoding);
- $this->setVersion($doc->version);
- $element=$doc->documentElement;
- $this->setTagName($element->tagName);
- $this->setValue($element->nodeValue);
- $elements=$this->getElements();
- $attributes=$this->getAttributes();
- $elements->clear();
- $attributes->clear();
- static $bSimpleXml;
- if($bSimpleXml === null)
- $bSimpleXml = (boolean)function_exists('simplexml_load_string');
- if($bSimpleXml)
- {
- $simpleDoc = simplexml_load_string($string);
- $docNamespaces = $simpleDoc->getDocNamespaces(false);
- $simpleDoc = null;
- foreach($docNamespaces as $prefix => $uri)
- {
- if($prefix === '')
- $attributes->add('xmlns', $uri);
- else
- $attributes->add('xmlns:'.$prefix, $uri);
- }
- }
- foreach($element->attributes as $name=>$attr)
- $attributes->add(($attr->prefix === '' ? '' : $attr->prefix . ':') .$name,$attr->value);
- foreach($element->childNodes as $child)
- {
- if($child instanceof DOMElement)
- $elements->add($this->buildElement($child));
- }
- return true;
- }
- public function saveToFile($file)
- {
- if(($fw=fopen($file,'w'))!==false)
- {
- fwrite($fw,$this->saveToString());
- fclose($fw);
- }
- else
- throw new TIOException('xmldocument_file_write_failed',$file);
- }
- public function saveToString()
- {
- $version=empty($this->_version)?' version="1.0"':' version="'.$this->_version.'"';
- $encoding=empty($this->_encoding)?'':' encoding="'.$this->_encoding.'"';
- return "<?xml{$version}{$encoding}?>\n".$this->toString(0);
- }
- public function __toString()
- {
- return $this->saveToString();
- }
- private function buildElement($node)
- {
- $element=new TXmlElement($node->tagName);
- $element->setValue($node->nodeValue);
- foreach($node->attributes as $name=>$attr)
- $element->getAttributes()->add(($attr->prefix === '' ? '' : $attr->prefix . ':') . $name,$attr->value);
- foreach($node->childNodes as $child)
- {
- if($child instanceof DOMElement)
- $element->getElements()->add($this->buildElement($child));
- }
- return $element;
- }
- }
- class TXmlElementList extends TList
- {
- private $_o;
- public function __construct(TXmlElement $owner)
- {
- $this->_o=$owner;
- }
- protected function getOwner()
- {
- return $this->_o;
- }
- public function insertAt($index,$item)
- {
- if($item instanceof TXmlElement)
- {
- parent::insertAt($index,$item);
- if($item->getParent()!==null)
- $item->getParent()->getElements()->remove($item);
- $item->setParent($this->_o);
- }
- else
- throw new TInvalidDataTypeException('xmlelementlist_xmlelement_required');
- }
- public function removeAt($index)
- {
- $item=parent::removeAt($index);
- if($item instanceof TXmlElement)
- $item->setParent(null);
- return $item;
- }
- }
- class TAuthorizationRule extends TComponent
- {
- private $_action;
- private $_users;
- private $_roles;
- private $_verb;
- private $_ipRules;
- private $_everyone;
- private $_guest;
- private $_authenticated;
- public function __construct($action,$users,$roles,$verb='',$ipRules='')
- {
- $action=strtolower(trim($action));
- if($action==='allow' || $action==='deny')
- $this->_action=$action;
- else
- throw new TInvalidDataValueException('authorizationrule_action_invalid',$action);
- $this->_users=array();
- $this->_roles=array();
- $this->_ipRules=array();
- $this->_everyone=false;
- $this->_guest=false;
- $this->_authenticated=false;
- if(trim($users)==='')
- $users='*';
- foreach(explode(',',$users) as $user)
- {
- if(($user=trim(strtolower($user)))!=='')
- {
- if($user==='*')
- {
- $this->_everyone=true;
- break;
- }
- else if($user==='?')
- $this->_guest=true;
- else if($user==='@')
- $this->_authenticated=true;
- else
- $this->_users[]=$user;
- }
- }
- if(trim($roles)==='')
- $roles='*';
- foreach(explode(',',$roles) as $role)
- {
- if(($role=trim(strtolower($role)))!=='')
- $this->_roles[]=$role;
- }
- if(($verb=trim(strtolower($verb)))==='')
- $verb='*';
- if($verb==='*' || $verb==='get' || $verb==='post')
- $this->_verb=$verb;
- else
- throw new TInvalidDataValueException('authorizationrule_verb_invalid',$verb);
- if(trim($ipRules)==='')
- $ipRules='*';
- foreach(explode(',',$ipRules) as $ipRule)
- {
- if(($ipRule=trim($ipRule))!=='')
- $this->_ipRules[]=$ipRule;
- }
- }
- public function getAction()
- {
- return $this->_action;
- }
- public function getUsers()
- {
- return $this->_users;
- }
- public function getRoles()
- {
- return $this->_roles;
- }
- public function getVerb()
- {
- return $this->_verb;
- }
- public function getIPRules()
- {
- return $this->_ipRules;
- }
- public function getGuestApplied()
- {
- return $this->_guest || $this->_everyone;
- }
- public function getEveryoneApplied()
- {
- return $this->_everyone;
- }
- public function getAuthenticatedApplied()
- {
- return $this->_authenticated || $this->_everyone;
- }
- public function isUserAllowed(IUser $user,$verb,$ip)
- {
- if($this->isVerbMatched($verb) && $this->isIpMatched($ip) && $this->isUserMatched($user) && $this->isRoleMatched($user))
- return ($this->_action==='allow')?1:-1;
- else
- return 0;
- }
- private function isIpMatched($ip)
- {
- if(empty($this->_ipRules))
- return 1;
- foreach($this->_ipRules as $rule)
- {
- if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && strncmp($ip,$rule,$pos)===0))
- return 1;
- }
- return 0;
- }
- private function isUserMatched($user)
- {
- return ($this->_everyone || ($this->_guest && $user->getIsGuest()) || ($this->_authenticated && !$user->getIsGuest()) || in_array(strtolower($user->getName()),$this->_users));
- }
- private function isRoleMatched($user)
- {
- foreach($this->_roles as $role)
- {
- if($role==='*' || $user->isInRole($role))
- return true;
- }
- return false;
- }
- private function isVerbMatched($verb)
- {
- return ($this->_verb==='*' || strcasecmp($verb,$this->_verb)===0);
- }
- }
- class TAuthorizationRuleCollection extends TList
- {
- public function isUserAllowed($user,$verb,$ip)
- {
- if($user instanceof IUser)
- {
- $verb=strtolower(trim($verb));
- foreach($this as $rule)
- {
- if(($decision=$rule->isUserAllowed($user,$verb,$ip))!==0)
- return ($decision>0);
- }
- return true;
- }
- else
- return false;
- }
- public function insertAt($index,$item)
- {
- if($item instanceof TAuthorizationRule)
- parent::insertAt($index,$item);
- else
- throw new TInvalidDataTypeException('authorizationrulecollection_authorizationrule_required');
- }
- }
- class TSecurityManager extends TModule
- {
- const STATE_VALIDATION_KEY = 'prado:securitymanager:validationkey';
- const STATE_ENCRYPTION_KEY = 'prado:securitymanager:encryptionkey';
- private $_validationKey = null;
- private $_encryptionKey = null;
- private $_validation = TSecurityManagerValidationMode::SHA1;
- private $_encryption = '3DES';
- public function init($config)
- {
- $this->getApplication()->setSecurityManager($this);
- }
- protected function generateRandomKey()
- {
- return rand().rand().rand().rand();
- }
- public function getValidationKey()
- {
- if(null === $this->_validationKey) {
- if(null === ($this->_validationKey = $this->getApplication()->getGlobalState(self::STATE_VALIDATION_KEY))) {
- $this->_validationKey = $this->generateRandomKey();
- $this->getApplication()->setGlobalState(self::STATE_VALIDATION_KEY, $this->_validationKey, null);
- }
- }
- return $this->_validationKey;
- }
- public function setValidationKey($value)
- {
- if('' === $value)
- throw new TInvalidDataValueException('securitymanager_validationkey_invalid');
- $this->_validationKey = $value;
- }
- public function getEncryptionKey()
- {
- if(null === $this->_encryptionKey) {
- if(null === ($this->_encryptionKey = $this->getApplication()->getGlobalState(self::STATE_ENCRYPTION_KEY))) {
- $this->_encryptionKey = $this->generateRandomKey();
- $this->getApplication()->setGlobalState(self::STATE_ENCRYPTION_KEY, $this->_encryptionKey, null);
- }
- }
- return $this->_encryptionKey;
- }
- public function setEncryptionKey($value)
- {
- if('' === $value)
- throw new TInvalidDataValueException('securitymanager_encryptionkey_invalid');
- $this->_encryptionKey = $value;
- }
- public function getValidation()
- {
- return $this->_validation;
- }
- public function setValidation($value)
- {
- $this->_validation = TPropertyValue::ensureEnum($value, 'TSecurityManagerValidationMode');
- }
- public function getEncryption()
- {
- return $this->_encryption;
- }
- public function setEncryption($value)
- {
- throw new TNotSupportedException('Currently only 3DES encryption is supported');
- }
- public function encrypt($data)
- {
- if(!function_exists('mcrypt_encrypt'))
- throw new TNotSupportedException('securitymanager_mcryptextension_required');
- $module = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
- $key = substr(md5($this->getEncryptionKey()), 0, mcrypt_enc_get_key_size($module));
- srand();
- $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
- mcrypt_generic_init($module, $key, $iv);
- $encrypted = $iv.mcrypt_generic($module, $data);
- mcrypt_generic_deinit($module);
- mcrypt_module_close($module);
- return $encrypted;
- }
- public function decrypt($data)
- {
- if(!function_exists('mcrypt_decrypt'))
- throw new TNotSupportedException('securitymanager_mcryptextension_required');
- $module = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
- $key = substr(md5($this->getEncryptionKey()), 0, mcrypt_enc_get_key_size($module));
- $ivSize = mcrypt_enc_get_iv_size($module);
- $iv = substr($data, 0, $ivSize);
- mcrypt_generic_init($module, $key, $iv);
- $decrypted = mdecrypt_generic($module, substr($data, $ivSize));
- mcrypt_generic_deinit($module);
- mcrypt_module_close($module);
- return $decrypted;
- }
- public function hashData($data)
- {
- $hmac = $this->computeH…
Large files files are truncated, but you can click here to view the full file