diff options
Diffstat (limited to 'lib/prado/framework/Util')
-rw-r--r-- | lib/prado/framework/Util/TBehavior.php | 86 | ||||
-rw-r--r-- | lib/prado/framework/Util/TCallChain.php | 146 | ||||
-rw-r--r-- | lib/prado/framework/Util/TClassBehavior.php | 35 | ||||
-rw-r--r-- | lib/prado/framework/Util/TDataFieldAccessor.php | 89 | ||||
-rw-r--r-- | lib/prado/framework/Util/TDateTimeStamp.php | 202 | ||||
-rw-r--r-- | lib/prado/framework/Util/TLogRouter.php | 1198 | ||||
-rw-r--r-- | lib/prado/framework/Util/TLogger.php | 234 | ||||
-rw-r--r-- | lib/prado/framework/Util/TParameterModule.php | 171 | ||||
-rw-r--r-- | lib/prado/framework/Util/TRpcClient.php | 357 | ||||
-rw-r--r-- | lib/prado/framework/Util/TSimpleDateFormatter.php | 369 | ||||
-rw-r--r-- | lib/prado/framework/Util/TVarDumper.php | 126 |
11 files changed, 3013 insertions, 0 deletions
diff --git a/lib/prado/framework/Util/TBehavior.php b/lib/prado/framework/Util/TBehavior.php new file mode 100644 index 0000000..56a81a8 --- /dev/null +++ b/lib/prado/framework/Util/TBehavior.php @@ -0,0 +1,86 @@ +<?php +/** + * TBehavior class file. + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @link http://www.yiiframework.com/ + * @copyright Copyright © 2008-2009 Yii Software LLC + * @license http://www.yiiframework.com/license/ + */ + +/** + * TBehavior is a convenient base class for behavior classes. + * @author Qiang Xue <qiang.xue@gmail.com> + * @package System.Util + * @since 3.2.3 + */ +class TBehavior extends TComponent implements IBehavior +{ + private $_enabled; + private $_owner; + + /** + * Declares events and the corresponding event handler methods. + * The events are defined by the {@link owner} component, while the handler + * methods by the behavior class. The handlers will be attached to the corresponding + * events when the behavior is attached to the {@link owner} component; and they + * will be detached from the events when the behavior is detached from the component. + * @return array events (array keys) and the corresponding event handler methods (array values). + */ + public function events() + { + return array(); + } + + /** + * Attaches the behavior object to the component. + * The default implementation will set the {@link owner} property + * and attach event handlers as declared in {@link events}. + * Make sure you call the parent implementation if you override this method. + * @param TComponent the component that this behavior is to be attached to. + */ + public function attach($owner) + { + $this->_owner=$owner; + foreach($this->events() as $event=>$handler) + $owner->attachEventHandler($event,array($this,$handler)); + } + + /** + * Detaches the behavior object from the component. + * The default implementation will unset the {@link owner} property + * and detach event handlers declared in {@link events}. + * Make sure you call the parent implementation if you override this method. + * @param TComponent the component that this behavior is to be detached from. + */ + public function detach($owner) + { + foreach($this->events() as $event=>$handler) + $owner->detachEventHandler($event,array($this,$handler)); + $this->_owner=null; + } + + /** + * @return TComponent the owner component that this behavior is attached to. + */ + public function getOwner() + { + return $this->_owner; + } + + /** + * @return boolean whether this behavior is enabled + */ + public function getEnabled() + { + return $this->_enabled; + } + + /** + * @param boolean whether this behavior is enabled + */ + public function setEnabled($value) + { + $this->_enabled=$value; + } +}
\ No newline at end of file diff --git a/lib/prado/framework/Util/TCallChain.php b/lib/prado/framework/Util/TCallChain.php new file mode 100644 index 0000000..4e9e23f --- /dev/null +++ b/lib/prado/framework/Util/TCallChain.php @@ -0,0 +1,146 @@ +<?php +/** + * TCallChain class file. + * + * @author Brad Anderson <javalizard@gmail.com> + * @link https://github.com/pradosoft/prado + * @copyright Copyright © 2008-2015 Pradosoft + * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT + */ + +/** + * TCallChain is a recursive event calling mechanism. This class implements + * the {@link IDynamicMethods} class so that any 'dy' event calls can be caught + * and patched through to the intended recipient + * @author Brad Anderson <javalizard@gmail.com> + * @package System.Util + * @since 3.2.3 + */ +class TCallChain extends TList implements IDynamicMethods +{ + /** + * @var {@link TListIterator} for moving through the chained method calls + */ + private $_iterator=null; + + /** + * @var string the method name of the call chain + */ + private $_method=null; + + /** + * This initializes the list and the name of the method to be called + * @param string the name of the function call + */ + public function __construct($method) { + $this->_method=$method; + parent::__construct(); + } + + + /** + * This initializes the list and the name of the method to be called + * @param string|array this is a callable function as a string or array with + * the object and method name as string + * @param array The array of arguments to the function call chain + */ + public function addCall($method,$args) + { + $this->add(array($method,$args)); + } + + /** + * This method calls the next Callable in the list. All of the method arguments + * coming into this method are substituted into the original method argument of + * call in the chain. + * + * If the original method call has these parameters + * <code> + * $originalobject->dyExampleMethod('param1', 'param2', 'param3') + * </code> + * <code> + * $callchain->dyExampleMethod('alt1', 'alt2') + * </code> + * then the next call in the call chain will recieve the parameters as if this were called + * <code> + * $behavior->dyExampleMethod('alt1', 'alt2', 'param3', $callchainobject) + * </code> + * + * When dealing with {@link IClassBehaviors}, the first parameter of the stored argument + * list in 'dy' event calls is always the object containing the behavior. This modifies + * the parameter replacement mechanism slightly to leave the object containing the behavior + * alone and only replacing the other parameters in the argument list. As per {@link __call}, + * any calls to a 'dy' event do not need the object containing the behavior as the addition of + * the object to the argument list as the first element is automatic for IClassBehaviors. + * + * The last parameter of the method parameter list for any callable in the call chain + * will be the TCallChain object itself. This is so that any behavior implementing + * these calls will have access to the call chain. Each callable should either call + * the TCallChain call method internally for direct chaining or call the method being + * chained (in which case the dynamic handler will pass through to this call method). + * + * If the dynamic intra object/behavior event is not called in the behavior implemented + * dynamic method, it will return to this method and call the following behavior + * implementation so as no behavior with an implementation of the dynamic event is left + * uncalled. This does break the call chain though and will not act as a "parameter filter". + * + * When there are no handlers or no handlers left, it returns the first parameter of the + * argument list. + * + */ + public function call() + { + $args=func_get_args(); + if($this->getCount()===0) + return isset($args[0])?$args[0]:null; + + if(!$this->_iterator) + { + $chain_array=array_reverse($this->toArray()); + $this->_iterator=new TListIterator($chain_array); + } + if($this->_iterator->valid()) + do { + $handler=$this->_iterator->current(); + $this->_iterator->next(); + if(is_array($handler[0])&&$handler[0][0] instanceof IClassBehavior) + array_splice($handler[1],1,count($args),$args); + else + array_splice($handler[1],0,count($args),$args); + $handler[1][]=$this; + $result=call_user_func_array($handler[0],$handler[1]); + } while($this->_iterator->valid()); + else + $result = $args[0]; + return $result; + } + + + /** + * This catches all the unpatched dynamic events. When the method call matches the + * call chain method, it passes the arguments to the original __call (of the dynamic + * event being unspecified in TCallChain) and funnels into the method {@link call}, + * so the next dynamic event handler can be called. + * If the original method call has these parameters + * <code> + * $originalobject->dyExampleMethod('param1', 'param2', 'param3') + * </code> + * and within the chained dynamic events, this can be called + * <code> + * class DyBehavior extends TBehavior { + * public function dyExampleMethod($param1, $param2, $param3, $callchain) + * $callchain->dyExampleMethod($param1, $param2, $param3) + * } + * { + * </code> + * to call the next event in the chain. + * @param string method name of the unspecified object method + * @param array arguments to the unspecified object method + */ + public function __dycall($method,$args) + { + if($this->_method==$method) + return call_user_func_array(array($this,'call'),$args); + return null; + } +}
\ No newline at end of file diff --git a/lib/prado/framework/Util/TClassBehavior.php b/lib/prado/framework/Util/TClassBehavior.php new file mode 100644 index 0000000..05f009d --- /dev/null +++ b/lib/prado/framework/Util/TClassBehavior.php @@ -0,0 +1,35 @@ +<?php +/** + * TClassBehavior class file. + * + * @author Brad Anderson <javalizard@gmail.com> + * @link https://github.com/pradosoft/prado + * @copyright Copyright © 2008-2011 Pradosoft + * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT + */ + +/** + * TClassBehavior is a convenient base class for whole class behaviors. + * @author Brad Anderson <javalizard@gmail.com> + * @package System.Util + * @since 3.2.3 + */ +class TClassBehavior extends TComponent implements IClassBehavior +{ + + /** + * Attaches the behavior object to the component. + * @param TComponent the component that this behavior is to be attached to. + */ + public function attach($component) + { + } + + /** + * Detaches the behavior object from the component. + * @param TComponent the component that this behavior is to be detached from. + */ + public function detach($component) + { + } +}
\ No newline at end of file diff --git a/lib/prado/framework/Util/TDataFieldAccessor.php b/lib/prado/framework/Util/TDataFieldAccessor.php new file mode 100644 index 0000000..e86b8c1 --- /dev/null +++ b/lib/prado/framework/Util/TDataFieldAccessor.php @@ -0,0 +1,89 @@ +<?php +/** + * TDataFieldAccessor class file + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @link https://github.com/pradosoft/prado + * @copyright Copyright © 2005-2015 The PRADO Group + * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT + * @package System.Util + */ + +/** + * TDataFieldAccessor class + * + * TDataFieldAccessor is a utility class that provides access to a field of some data. + * The accessor attempts to obtain the field value in the following order: + * - If the data is an array, then the field is treated as an array index + * and the corresponding element value is returned; + * - If the data is a TMap or TList object, then the field is treated as a key + * into the map or list, and the corresponding value is returned. + * - If the data is an object, the field is treated as a property or sub-property + * defined with getter methods. For example, if the object has a method called + * getMyValue(), then field 'MyValue' will retrieve the result of this method call. + * If getMyValue() returns an object which contains a method getMySubValue(), + * then field 'MyValue.MySubValue' will return that method call result. + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @package System.Util + * @since 3.0 + */ +class TDataFieldAccessor +{ + /** + * Evaluates the data value at the specified field. + * - If the data is an array, then the field is treated as an array index + * and the corresponding element value is returned; the field name can also include + * dots to access subarrays. For example a field named 'MyField.MySubField' will + * first try to access $data['MyField.MySubField'], then try $data['MyField']['MySubField']. + * - If the data is a TMap or TList object, then the field is treated as a key + * into the map or list, and the corresponding value is returned. + * - If the data is an object, the field is treated as a property or sub-property + * defined with getter methods. For example, if the object has a method called + * getMyValue(), then field 'MyValue' will retrieve the result of this method call. + * If getMyValue() returns an object which contains a method getMySubValue(), + * then field 'MyValue.MySubValue' will return that method call result. + * @param mixed data containing the field value, can be an array, TMap, TList or object. + * @param mixed field value + * @return mixed value at the specified field + * @throws TInvalidDataValueException if field or data is invalid + */ + public static function getDataFieldValue($data,$field) + { + try + { + if(is_array($data) || ($data instanceof ArrayAccess)) + { + if(isset($data[$field])) + return $data[$field]; + + $tmp = $data; + foreach (explode(".", $field) as $f) + $tmp = $tmp[$f]; + return $tmp; + } + else if(is_object($data)) + { + if(strpos($field,'.')===false) // simple field + { + if(method_exists($data, 'get'.$field)) + return call_user_func(array($data,'get'.$field)); + else + return $data->{$field}; + } + else // field in the format of xxx.yyy.zzz + { + $object=$data; + foreach(explode('.',$field) as $f) + $object = TDataFieldAccessor::getDataFieldValue($object, $f); + return $object; + } + } + } + catch(Exception $e) + { + throw new TInvalidDataValueException('datafieldaccessor_datafield_invalid',$field,$e->getMessage()); + } + throw new TInvalidDataValueException('datafieldaccessor_data_invalid',$field); + } +} diff --git a/lib/prado/framework/Util/TDateTimeStamp.php b/lib/prado/framework/Util/TDateTimeStamp.php new file mode 100644 index 0000000..2bc2a9f --- /dev/null +++ b/lib/prado/framework/Util/TDateTimeStamp.php @@ -0,0 +1,202 @@ +<?php +/** + * TDateTimeStamp class file. + + * @author Fabio Bas ctrlaltca[AT]gmail[DOT]com + * @link https://github.com/pradosoft/prado + * @copyright Copyright © 2005-2015 The PRADO Group + * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT + * @package System.Util + */ + +/** + * TDateTimeStamp Class + * + * TDateTimeStamp Class is a wrapper to DateTime: http://php.net/manual/book.datetime.php + * Prado implemented this class before php started shipping the DateTime extension. + * This class is deprecated and left here only for compatibility for legacy code. + * Please note that this class doesn't support automatic conversion from gregorian to + * julian dates anymore. + * + * @author Fabio Bas ctrlaltca[AT]gmail[DOT]com + * @package System.Util + * @since 3.0.4 + * @deprecated since 3.2.1 + */ +class TDateTimeStamp +{ + protected static $_month_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); + protected static $_month_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + + /** + * Returns the day of the week (0=Sunday, 1=Monday, .. 6=Saturday) + * @param int year + * @param int month + * @param int day + */ + public function getDayofWeek($year, $month, $day) + { + $dt = new DateTime(); + $dt->setDate($year, $month, $day); + return (int) $dt->format('w'); + } + + /** + * Checks for leap year, returns true if it is. No 2-digit year check. Also + * handles julian calendar correctly. + * @param float year to check + * @return boolean true if is leap year + */ + public function isLeapYear($year) + { + $year = $this->digitCheck($year); + $dt = new DateTime(); + $dt->setDate($year, 1, 1); + return (bool) $dt->format('L'); + } + + /** + * Fix 2-digit years. Works for any century. + * Assumes that if 2-digit is more than 30 years in future, then previous century. + * @return integer change two digit year into multiple digits + */ + protected function digitCheck($y) + { + if ($y < 100){ + $yr = (integer) date("Y"); + $century = (integer) ($yr /100); + + if ($yr%100 > 50) { + $c1 = $century + 1; + $c0 = $century; + } else { + $c1 = $century; + $c0 = $century - 1; + } + $c1 *= 100; + // if 2-digit year is less than 30 years in future, set it to this century + // otherwise if more than 30 years in future, then we set 2-digit year to the prev century. + if (($y + $c1) < $yr+30) $y = $y + $c1; + else $y = $y + $c0*100; + } + return $y; + } + + public function get4DigitYear($y) + { + return $this->digitCheck($y); + } + + /** + * @return integer get local time zone offset from GMT + */ + public function getGMTDiff($ts=false) + { + $dt = new DateTime(); + if($ts) + $dt->setTimeStamp($ts); + else + $dt->setDate(1970, 1, 2); + + return (int) $dt->format('Z'); + } + + /** + * @return array an array with date info. + */ + function parseDate($txt=false) + { + if ($txt === false) return getdate(); + + $dt = new DateTime($txt); + + return array( + 'seconds' => (int) $dt->format('s'), + 'minutes' => (int) $dt->format('i'), + 'hours' => (int) $dt->format('G'), + 'mday' => (int) $dt->format('j'), + 'wday' => (int) $dt->format('w'), + 'mon' => (int) $dt->format('n'), + 'year' => (int) $dt->format('Y'), + 'yday' => (int) $dt->format('z'), + 'weekday' => $dt->format('l'), + 'month' => $dt->format('F'), + 0 => (int) $dt->format('U'), + ); + } + + /** + * @return array an array with date info. + */ + function getDate($d=false,$fast=false) + { + if ($d === false) return getdate(); + + $dt = new DateTime(); + $dt->setTimestamp($d); + + return array( + 'seconds' => (int) $dt->format('s'), + 'minutes' => (int) $dt->format('i'), + 'hours' => (int) $dt->format('G'), + 'mday' => (int) $dt->format('j'), + 'wday' => (int) $dt->format('w'), + 'mon' => (int) $dt->format('n'), + 'year' => (int) $dt->format('Y'), + 'yday' => (int) $dt->format('z'), + 'weekday' => $dt->format('l'), + 'month' => $dt->format('F'), + 0 => (int) $dt->format('U'), + ); + } + + /** + * @return boolean true if valid date, semantic check only. + */ + public function isValidDate($y,$m,$d) + { + if ($this->isLeapYear($y)) + $marr =& self::$_month_leaf; + else + $marr =& self::$_month_normal; + + if ($m > 12 || $m < 1) return false; + + if ($d > 31 || $d < 1) return false; + + if ($marr[$m] < $d) return false; + + if ($y < 1000 && $y > 3000) return false; + + return true; + } + + /** + * @return string formatted date based on timestamp $d + */ + function formatDate($fmt,$ts=false,$is_gmt=false) + { + $dt = new DateTime(); + if($is_gmt) + $dt->setTimeZone(new DateTimeZone('UTC')); + $dt->setTimestamp($ts); + + return $dt->format($fmt); + } + + /** + * @return integer|float a timestamp given a local time + */ + function getTimeStamp($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_gmt=false) + { + $dt = new DateTime(); + if($is_gmt) + $dt->setTimeZone(new DateTimeZone('UTC')); + $dt->setDate($year!==false ? $year : date('Y'), + $mon!==false ? $mon : date('m'), + $day!==false ? $day : date('d')); + $dt->setTime($hr, $min, $sec); + return (int) $dt->format('U'); + } +} + diff --git a/lib/prado/framework/Util/TLogRouter.php b/lib/prado/framework/Util/TLogRouter.php new file mode 100644 index 0000000..5b40f54 --- /dev/null +++ b/lib/prado/framework/Util/TLogRouter.php @@ -0,0 +1,1198 @@ +<?php +/** + * TLogRouter, TLogRoute, TFileLogRoute, TEmailLogRoute class file + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @link https://github.com/pradosoft/prado + * @copyright Copyright © 2005-2015 The PRADO Group + * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT + * @package System.Util + */ + +Prado::using('System.Data.TDbConnection'); + +/** + * TLogRouter class. + * + * TLogRouter manages routes that record log messages in different media different ways. + * For example, a file log route {@link TFileLogRoute} records log messages + * in log files. An email log route {@link TEmailLogRoute} sends log messages + * to email addresses. + * + * Log routes may be configured in application or page folder configuration files + * or an external configuration file specified by {@link setConfigFile ConfigFile}. + * The format is as follows, + * <code> + * <route class="TFileLogRoute" Categories="System.Web.UI" Levels="Warning" /> + * <route class="TEmailLogRoute" Categories="Application" Levels="Fatal" Emails="admin@prado.local" /> + * </code> + * PHP configuration style: + * <code> + * + * </code> + * You can specify multiple routes with different filtering conditions and different + * targets, even if the routes are of the same type. + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @author Carl G. Mathisen <carlgmathisen@gmail.com> + * @package System.Util + * @since 3.0 + */ +class TLogRouter extends TModule +{ + /** + * @var array list of routes available + */ + private $_routes=array(); + /** + * @var string external configuration file + */ + private $_configFile=null; + + /** + * Initializes this module. + * This method is required by the IModule interface. + * @param mixed configuration for this module, can be null + * @throws TConfigurationException if {@link getConfigFile ConfigFile} is invalid. + */ + public function init($config) + { + if($this->_configFile!==null) + { + if(is_file($this->_configFile)) + { + if($this->getApplication()->getConfigurationType()==TApplication::CONFIG_TYPE_PHP) + { + $phpConfig = include $this->_configFile; + $this->loadConfig($phpConfig); + } + else + { + $dom=new TXmlDocument; + $dom->loadFromFile($this->_configFile); + $this->loadConfig($dom); + } + } + else + throw new TConfigurationException('logrouter_configfile_invalid',$this->_configFile); + } + $this->loadConfig($config); + $this->getApplication()->attachEventHandler('OnEndRequest',array($this,'collectLogs')); + } + + /** + * Loads configuration from an XML element or PHP array + * @param mixed configuration node + * @throws TConfigurationException if log route class or type is not specified + */ + private function loadConfig($config) + { + if(is_array($config)) + { + if(isset($config['routes']) && is_array($config['routes'])) + { + foreach($config['routes'] as $route) + { + $properties = isset($route['properties'])?$route['properties']:array(); + if(!isset($route['class'])) + throw new TConfigurationException('logrouter_routeclass_required'); + $route=Prado::createComponent($route['class']); + if(!($route instanceof TLogRoute)) + throw new TConfigurationException('logrouter_routetype_invalid'); + foreach($properties as $name=>$value) + $route->setSubproperty($name,$value); + $this->_routes[]=$route; + $route->init($route); + } + } + } + else + { + foreach($config->getElementsByTagName('route') as $routeConfig) + { + $properties=$routeConfig->getAttributes(); + if(($class=$properties->remove('class'))===null) + throw new TConfigurationException('logrouter_routeclass_required'); + $route=Prado::createComponent($class); + if(!($route instanceof TLogRoute)) + throw new TConfigurationException('logrouter_routetype_invalid'); + foreach($properties as $name=>$value) + $route->setSubproperty($name,$value); + $this->_routes[]=$route; + $route->init($routeConfig); + } + } + } + + /** + * Adds a TLogRoute instance to the log router. + * + * @param TLogRoute $route + * @throws TInvalidDataTypeException if the route object is invalid + */ + public function addRoute($route) + { + if(!($route instanceof TLogRoute)) + throw new TInvalidDataTypeException('logrouter_routetype_invalid'); + $this->_routes[]=$route; + $route->init(null); + } + + /** + * @return string external configuration file. Defaults to null. + */ + public function getConfigFile() + { + return $this->_configFile; + } + + /** + * @param string external configuration file in namespace format. The file + * must be suffixed with '.xml'. + * @throws TConfigurationException if the file is invalid. + */ + public function setConfigFile($value) + { + if(($this->_configFile=Prado::getPathOfNamespace($value,$this->getApplication()->getConfigurationFileExt()))===null) + throw new TConfigurationException('logrouter_configfile_invalid',$value); + } + + /** + * Collects log messages from a logger. + * This method is an event handler to application's EndRequest event. + * @param mixed event parameter + */ + public function collectLogs($param) + { + $logger=Prado::getLogger(); + foreach($this->_routes as $route) + $route->collectLogs($logger); + } +} + +/** + * TLogRoute class. + * + * TLogRoute is the base class for all log route classes. + * A log route object retrieves log messages from a logger and sends it + * somewhere, such as files, emails. + * The messages being retrieved may be filtered first before being sent + * to the destination. The filters include log level filter and log category filter. + * + * To specify level filter, set {@link setLevels Levels} property, + * which takes a string of comma-separated desired level names (e.g. 'Error, Debug'). + * To specify category filter, set {@link setCategories Categories} property, + * which takes a string of comma-separated desired category names (e.g. 'System.Web, System.IO'). + * + * Level filter and category filter are combinational, i.e., only messages + * satisfying both filter conditions will they be returned. + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @package System.Util + * @since 3.0 + */ +abstract class TLogRoute extends TApplicationComponent +{ + /** + * @var array lookup table for level names + */ + protected static $_levelNames=array( + TLogger::DEBUG=>'Debug', + TLogger::INFO=>'Info', + TLogger::NOTICE=>'Notice', + TLogger::WARNING=>'Warning', + TLogger::ERROR=>'Error', + TLogger::ALERT=>'Alert', + TLogger::FATAL=>'Fatal' + ); + /** + * @var array lookup table for level values + */ + protected static $_levelValues=array( + 'debug'=>TLogger::DEBUG, + 'info'=>TLogger::INFO, + 'notice'=>TLogger::NOTICE, + 'warning'=>TLogger::WARNING, + 'error'=>TLogger::ERROR, + 'alert'=>TLogger::ALERT, + 'fatal'=>TLogger::FATAL + ); + /** + * @var integer log level filter (bits) + */ + private $_levels=null; + /** + * @var array log category filter + */ + private $_categories=null; + + /** + * Initializes the route. + * @param TXmlElement configurations specified in {@link TLogRouter}. + */ + public function init($config) + { + } + + /** + * @return integer log level filter + */ + public function getLevels() + { + return $this->_levels; + } + + /** + * @param integer|string integer log level filter (in bits). If the value is + * a string, it is assumed to be comma-separated level names. Valid level names + * include 'Debug', 'Info', 'Notice', 'Warning', 'Error', 'Alert' and 'Fatal'. + */ + public function setLevels($levels) + { + if(is_integer($levels)) + $this->_levels=$levels; + else + { + $this->_levels=null; + $levels=strtolower($levels); + foreach(explode(',',$levels) as $level) + { + $level=trim($level); + if(isset(self::$_levelValues[$level])) + $this->_levels|=self::$_levelValues[$level]; + } + } + } + + /** + * @return array list of categories to be looked for + */ + public function getCategories() + { + return $this->_categories; + } + + /** + * @param array|string list of categories to be looked for. If the value is a string, + * it is assumed to be comma-separated category names. + */ + public function setCategories($categories) + { + if(is_array($categories)) + $this->_categories=$categories; + else + { + $this->_categories=null; + foreach(explode(',',$categories) as $category) + { + if(($category=trim($category))!=='') + $this->_categories[]=$category; + } + } + } + + /** + * @param integer level value + * @return string level name + */ + protected function getLevelName($level) + { + return isset(self::$_levelNames[$level])?self::$_levelNames[$level]:'Unknown'; + } + + /** + * @param string level name + * @return integer level value + */ + protected function getLevelValue($level) + { + return isset(self::$_levelValues[$level])?self::$_levelValues[$level]:0; + } + + /** + * Formats a log message given different fields. + * @param string message content + * @param integer message level + * @param string message category + * @param integer timestamp + * @return string formatted message + */ + protected function formatLogMessage($message,$level,$category,$time) + { + return @date('M d H:i:s',$time).' ['.$this->getLevelName($level).'] ['.$category.'] '.$message."\n"; + } + + /** + * Retrieves log messages from logger to log route specific destination. + * @param TLogger logger instance + */ + public function collectLogs(TLogger $logger) + { + $logs=$logger->getLogs($this->getLevels(),$this->getCategories()); + if(!empty($logs)) + $this->processLogs($logs); + } + + /** + * Processes log messages and sends them to specific destination. + * Derived child classes must implement this method. + * @param array list of messages. Each array elements represents one message + * with the following structure: + * array( + * [0] => message + * [1] => level + * [2] => category + * [3] => timestamp); + */ + abstract protected function processLogs($logs); +} + +/** + * TFileLogRoute class. + * + * TFileLogRoute records log messages in files. + * The log files are stored under {@link setLogPath LogPath} and the file name + * is specified by {@link setLogFile LogFile}. If the size of the log file is + * greater than {@link setMaxFileSize MaxFileSize} (in kilo-bytes), a rotation + * is performed, which renames the current log file by suffixing the file name + * with '.1'. All existing log files are moved backwards one place, i.e., '.2' + * to '.3', '.1' to '.2'. The property {@link setMaxLogFiles MaxLogFiles} + * specifies how many files to be kept. + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @package System.Util + * @since 3.0 + */ +class TFileLogRoute extends TLogRoute +{ + /** + * @var integer maximum log file size + */ + private $_maxFileSize=512; // in KB + /** + * @var integer number of log files used for rotation + */ + private $_maxLogFiles=2; + /** + * @var string directory storing log files + */ + private $_logPath=null; + /** + * @var string log file name + */ + private $_logFile='prado.log'; + + /** + * @return string directory storing log files. Defaults to application runtime path. + */ + public function getLogPath() + { + if($this->_logPath===null) + $this->_logPath=$this->getApplication()->getRuntimePath(); + return $this->_logPath; + } + + /** + * @param string directory (in namespace format) storing log files. + * @throws TConfigurationException if log path is invalid + */ + public function setLogPath($value) + { + if(($this->_logPath=Prado::getPathOfNamespace($value))===null || !is_dir($this->_logPath) || !is_writable($this->_logPath)) + throw new TConfigurationException('filelogroute_logpath_invalid',$value); + } + + /** + * @return string log file name. Defaults to 'prado.log'. + */ + public function getLogFile() + { + return $this->_logFile; + } + + /** + * @param string log file name + */ + public function setLogFile($value) + { + $this->_logFile=$value; + } + + /** + * @return integer maximum log file size in kilo-bytes (KB). Defaults to 1024 (1MB). + */ + public function getMaxFileSize() + { + return $this->_maxFileSize; + } + + /** + * @param integer maximum log file size in kilo-bytes (KB). + * @throws TInvalidDataValueException if the value is smaller than 1. + */ + public function setMaxFileSize($value) + { + $this->_maxFileSize=TPropertyValue::ensureInteger($value); + if($this->_maxFileSize<=0) + throw new TInvalidDataValueException('filelogroute_maxfilesize_invalid'); + } + + /** + * @return integer number of files used for rotation. Defaults to 2. + */ + public function getMaxLogFiles() + { + return $this->_maxLogFiles; + } + + /** + * @param integer number of files used for rotation. + */ + public function setMaxLogFiles($value) + { + $this->_maxLogFiles=TPropertyValue::ensureInteger($value); + if($this->_maxLogFiles<1) + throw new TInvalidDataValueException('filelogroute_maxlogfiles_invalid'); + } + + /** + * Saves log messages in files. + * @param array list of log messages + */ + protected function processLogs($logs) + { + $logFile=$this->getLogPath().DIRECTORY_SEPARATOR.$this->getLogFile(); + if(@filesize($logFile)>$this->_maxFileSize*1024) + $this->rotateFiles(); + foreach($logs as $log) + error_log($this->formatLogMessage($log[0],$log[1],$log[2],$log[3]),3,$logFile); + } + + /** + * Rotates log files. + */ + protected function rotateFiles() + { + $file=$this->getLogPath().DIRECTORY_SEPARATOR.$this->getLogFile(); + for($i=$this->_maxLogFiles;$i>0;--$i) + { + $rotateFile=$file.'.'.$i; + if(is_file($rotateFile)) + { + if($i===$this->_maxLogFiles) + unlink($rotateFile); + else + rename($rotateFile,$file.'.'.($i+1)); + } + } + if(is_file($file)) + rename($file,$file.'.1'); + } +} + +/** + * TEmailLogRoute class. + * + * TEmailLogRoute sends selected log messages to email addresses. + * The target email addresses may be specified via {@link setEmails Emails} property. + * Optionally, you may set the email {@link setSubject Subject} and the + * {@link setSentFrom SentFrom} address. + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @package System.Util + * @since 3.0 + */ +class TEmailLogRoute extends TLogRoute +{ + /** + * Regex pattern for email address. + */ + const EMAIL_PATTERN='/^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/'; + /** + * Default email subject. + */ + const DEFAULT_SUBJECT='Prado Application Log'; + /** + * @var array list of destination email addresses. + */ + private $_emails=array(); + /** + * @var string email subject + */ + private $_subject=''; + /** + * @var string email sent from address + */ + private $_from=''; + + /** + * Initializes the route. + * @param TXmlElement configurations specified in {@link TLogRouter}. + * @throws TConfigurationException if {@link getSentFrom SentFrom} is empty and + * 'sendmail_from' in php.ini is also empty. + */ + public function init($config) + { + if($this->_from==='') + $this->_from=ini_get('sendmail_from'); + if($this->_from==='') + throw new TConfigurationException('emaillogroute_sentfrom_required'); + } + + /** + * Sends log messages to specified email addresses. + * @param array list of log messages + */ + protected function processLogs($logs) + { + $message=''; + foreach($logs as $log) + $message.=$this->formatLogMessage($log[0],$log[1],$log[2],$log[3]); + $message=wordwrap($message,70); + $returnPath = ini_get('sendmail_path') ? "Return-Path:{$this->_from}\r\n" : ''; + foreach($this->_emails as $email) + mail($email,$this->getSubject(),$message,"From:{$this->_from}\r\n{$returnPath}"); + + } + + /** + * @return array list of destination email addresses + */ + public function getEmails() + { + return $this->_emails; + } + + /** + * @return array|string list of destination email addresses. If the value is + * a string, it is assumed to be comma-separated email addresses. + */ + public function setEmails($emails) + { + if(is_array($emails)) + $this->_emails=$emails; + else + { + $this->_emails=array(); + foreach(explode(',',$emails) as $email) + { + $email=trim($email); + if(preg_match(self::EMAIL_PATTERN,$email)) + $this->_emails[]=$email; + } + } + } + + /** + * @return string email subject. Defaults to TEmailLogRoute::DEFAULT_SUBJECT + */ + public function getSubject() + { + if($this->_subject===null) + $this->_subject=self::DEFAULT_SUBJECT; + return $this->_subject; + } + + /** + * @param string email subject. + */ + public function setSubject($value) + { + $this->_subject=$value; + } + + /** + * @return string send from address of the email + */ + public function getSentFrom() + { + return $this->_from; + } + + /** + * @param string send from address of the email + */ + public function setSentFrom($value) + { + $this->_from=$value; + } +} + +/** + * TBrowserLogRoute class. + * + * TBrowserLogRoute prints selected log messages in the response. + * + * @author Xiang Wei Zhuo <weizhuo[at]gmail[dot]com> + * @package System.Util + * @since 3.0 + */ +class TBrowserLogRoute extends TLogRoute +{ + /** + * @var string css class for indentifying the table structure in the dom tree + */ + private $_cssClass=null; + + public function processLogs($logs) + { + if(empty($logs) || $this->getApplication()->getMode()==='Performance') return; + $first = $logs[0][3]; + $even = true; + $response = $this->getApplication()->getResponse(); + $response->write($this->renderHeader()); + for($i=0,$n=count($logs);$i<$n;++$i) + { + if ($i<$n-1) + { + $timing['delta'] = $logs[$i+1][3] - $logs[$i][3]; + $timing['total'] = $logs[$i+1][3] - $first; + } + else + { + $timing['delta'] = '?'; + $timing['total'] = $logs[$i][3] - $first; + } + $timing['even'] = !($even = !$even); + $response->write($this->renderMessage($logs[$i],$timing)); + } + $response->write($this->renderFooter()); + } + + /** + * @param string the css class of the control + */ + public function setCssClass($value) + { + $this->_cssClass = TPropertyValue::ensureString($value); + } + + /** + * @return string the css class of the control + */ + public function getCssClass() + { + return TPropertyValue::ensureString($this->_cssClass); + } + + protected function renderHeader() + { + $string = ''; + if($className=$this->getCssClass()) + { + $string = <<<EOD +<table class="$className"> + <tr class="header"> + <th colspan="5"> + Application Log + </th> + </tr><tr class="description"> + <th> </th> + <th>Category</th><th>Message</th><th>Time Spent (s)</th><th>Cumulated Time Spent (s)</th> + </tr> +EOD; + } + else + { + $string = <<<EOD +<table cellspacing="0" cellpadding="2" border="0" width="100%" style="table-layout:auto"> + <tr> + <th style="background-color: black; color:white;" colspan="5"> + Application Log + </th> + </tr><tr style="background-color: #ccc; color:black"> + <th style="width: 15px"> </th> + <th style="width: auto">Category</th><th style="width: auto">Message</th><th style="width: 120px">Time Spent (s)</th><th style="width: 150px">Cumulated Time Spent (s)</th> + </tr> +EOD; + } + return $string; + } + + protected function renderMessage($log, $info) + { + $string = ''; + $total = sprintf('%0.6f', $info['total']); + $delta = sprintf('%0.6f', $info['delta']); + $msg = preg_replace('/\(line[^\)]+\)$/','',$log[0]); //remove line number info + $msg = THttpUtility::htmlEncode($msg); + if($this->getCssClass()) + { + $colorCssClass = $log[1]; + $messageCssClass = $info['even'] ? 'even' : 'odd'; + $string = <<<EOD + <tr class="message level$colorCssClass $messageCssClass"> + <td class="code"> </td> + <td class="category">{$log[2]}</td> + <td class="message">{$msg}</td> + <td class="time">{$delta}</td> + <td class="cumulatedtime">{$total}</td> + </tr> +EOD; + } + else + { + $bgcolor = $info['even'] ? "#fff" : "#eee"; + $color = $this->getColorLevel($log[1]); + $string = <<<EOD + <tr style="background-color: {$bgcolor}; color:#000"> + <td style="border:1px solid silver;background-color: $color;"> </td> + <td>{$log[2]}</td> + <td>{$msg}</td> + <td style="text-align:center">{$delta}</td> + <td style="text-align:center">{$total}</td> + </tr> +EOD; + } + return $string; + } + + protected function getColorLevel($level) + { + switch($level) + { + case TLogger::DEBUG: return 'green'; + case TLogger::INFO: return 'black'; + case TLogger::NOTICE: return '#3333FF'; + case TLogger::WARNING: return '#33FFFF'; + case TLogger::ERROR: return '#ff9933'; + case TLogger::ALERT: return '#ff00ff'; + case TLogger::FATAL: return 'red'; + } + return ''; + } + + protected function renderFooter() + { + $string = ''; + if($this->getCssClass()) + { + $string .= '<tr class="footer"><td colspan="5">'; + foreach(self::$_levelValues as $name => $level) + { + $string .= '<span class="level'.$level.'">'.strtoupper($name)."</span>"; + } + } + else + { + $string .= "<tr><td colspan=\"5\" style=\"text-align:center; background-color:black; border-top: 1px solid #ccc; padding:0.2em;\">"; + foreach(self::$_levelValues as $name => $level) + { + $string .= "<span style=\"color:white; border:1px solid white; background-color:".$this->getColorLevel($level); + $string .= ";margin: 0.5em; padding:0.01em;\">".strtoupper($name)."</span>"; + } + } + $string .= '</td></tr></table>'; + return $string; + } +} + + +/** + * TDbLogRoute class + * + * TDbLogRoute stores log messages in a database table. + * To specify the database table, set {@link setConnectionID ConnectionID} to be + * the ID of a {@link TDataSourceConfig} module and {@link setLogTableName LogTableName}. + * If they are not setting, an SQLite3 database named 'sqlite3.log' will be created and used + * under the runtime directory. + * + * By default, the database table name is 'pradolog'. It has the following structure: + * <code> + * CREATE TABLE pradolog + * ( + * log_id INTEGER NOT NULL PRIMARY KEY, + * level INTEGER, + * category VARCHAR(128), + * logtime VARCHAR(20), + * message VARCHAR(255) + * ); + * </code> + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @package System.Util + * @since 3.1.2 + */ +class TDbLogRoute extends TLogRoute +{ + /** + * @var string the ID of TDataSourceConfig module + */ + private $_connID=''; + /** + * @var TDbConnection the DB connection instance + */ + private $_db; + /** + * @var string name of the DB log table + */ + private $_logTable='pradolog'; + /** + * @var boolean whether the log DB table should be created automatically + */ + private $_autoCreate=true; + + /** + * Destructor. + * Disconnect the db connection. + */ + public function __destruct() + { + if($this->_db!==null) + $this->_db->setActive(false); + } + + /** + * Initializes this module. + * This method is required by the IModule interface. + * It initializes the database for logging purpose. + * @param TXmlElement configuration for this module, can be null + * @throws TConfigurationException if the DB table does not exist. + */ + public function init($config) + { + $db=$this->getDbConnection(); + $db->setActive(true); + + $sql='SELECT * FROM '.$this->_logTable.' WHERE 0=1'; + try + { + $db->createCommand($sql)->query()->close(); + } + catch(Exception $e) + { + // DB table not exists + if($this->_autoCreate) + $this->createDbTable(); + else + throw new TConfigurationException('db_logtable_inexistent',$this->_logTable); + } + + parent::init($config); + } + + /** + * Stores log messages into database. + * @param array list of log messages + */ + protected function processLogs($logs) + { + $sql='INSERT INTO '.$this->_logTable.'(level, category, logtime, message) VALUES (:level, :category, :logtime, :message)'; + $command=$this->getDbConnection()->createCommand($sql); + foreach($logs as $log) + { + $command->bindValue(':message',$log[0]); + $command->bindValue(':level',$log[1]); + $command->bindValue(':category',$log[2]); + $command->bindValue(':logtime',$log[3]); + $command->execute(); + } + } + + /** + * Creates the DB table for storing log messages. + * @todo create sequence for PostgreSQL + */ + protected function createDbTable() + { + $db = $this->getDbConnection(); + $driver=$db->getDriverName(); + $autoidAttributes = ''; + if($driver==='mysql') + $autoidAttributes = 'AUTO_INCREMENT'; + + $sql='CREATE TABLE '.$this->_logTable.' ( + log_id INTEGER NOT NULL PRIMARY KEY ' . $autoidAttributes . ', + level INTEGER, + category VARCHAR(128), + logtime VARCHAR(20), + message VARCHAR(255))'; + $db->createCommand($sql)->execute(); + } + + /** + * Creates the DB connection. + * @param string the module ID for TDataSourceConfig + * @return TDbConnection the created DB connection + * @throws TConfigurationException if module ID is invalid or empty + */ + protected function createDbConnection() + { + if($this->_connID!=='') + { + $config=$this->getApplication()->getModule($this->_connID); + if($config instanceof TDataSourceConfig) + return $config->getDbConnection(); + else + throw new TConfigurationException('dblogroute_connectionid_invalid',$this->_connID); + } + else + { + $db=new TDbConnection; + // default to SQLite3 database + $dbFile=$this->getApplication()->getRuntimePath().'/sqlite3.log'; + $db->setConnectionString('sqlite:'.$dbFile); + return $db; + } + } + + /** + * @return TDbConnection the DB connection instance + */ + public function getDbConnection() + { + if($this->_db===null) + $this->_db=$this->createDbConnection(); + return $this->_db; + } + + /** + * @return string the ID of a {@link TDataSourceConfig} module. Defaults to empty string, meaning not set. + */ + public function getConnectionID() + { + return $this->_connID; + } + + /** + * Sets the ID of a TDataSourceConfig module. + * The datasource module will be used to establish the DB connection for this log route. + * @param string ID of the {@link TDataSourceConfig} module + */ + public function setConnectionID($value) + { + $this->_connID=$value; + } + + /** + * @return string the name of the DB table to store log content. Defaults to 'pradolog'. + * @see setAutoCreateLogTable + */ + public function getLogTableName() + { + return $this->_logTable; + } + + /** + * Sets the name of the DB table to store log content. + * Note, if {@link setAutoCreateLogTable AutoCreateLogTable} is false + * and you want to create the DB table manually by yourself, + * you need to make sure the DB table is of the following structure: + * (key CHAR(128) PRIMARY KEY, value BLOB, expire INT) + * @param string the name of the DB table to store log content + * @see setAutoCreateLogTable + */ + public function setLogTableName($value) + { + $this->_logTable=$value; + } + + /** + * @return boolean whether the log DB table should be automatically created if not exists. Defaults to true. + * @see setAutoCreateLogTable + */ + public function getAutoCreateLogTable() + { + return $this->_autoCreate; + } + + /** + * @param boolean whether the log DB table should be automatically created if not exists. + * @see setLogTableName + */ + public function setAutoCreateLogTable($value) + { + $this->_autoCreate=TPropertyValue::ensureBoolean($value); + } + +} + +/** + * TFirebugLogRoute class. + * + * TFirebugLogRoute prints selected log messages in the firebug log console. + * + * {@link http://www.getfirebug.com/ FireBug Website} + * + * @author Enrico Stahn <mail@enricostahn.com>, Christophe Boulain <Christophe.Boulain@gmail.com> + * @package System.Util + * @since 3.1.2 + */ +class TFirebugLogRoute extends TBrowserLogRoute +{ + protected function renderHeader () + { + $string = <<<EOD + +<script type="text/javascript"> +/*<![CDATA[*/ +if (typeof(console) == 'object') +{ + console.log ("[Cumulated Time] [Time] [Level] [Category] [Message]"); + +EOD; + + return $string; + } + + protected function renderMessage ($log, $info) + { + $logfunc = $this->getFirebugLoggingFunction($log[1]); + $total = sprintf('%0.6f', $info['total']); + $delta = sprintf('%0.6f', $info['delta']); + $msg = trim($this->formatLogMessage($log[0], $log[1], $log[2], '')); + $msg = preg_replace('/\(line[^\)]+\)$/', '', $msg); //remove line number info + $msg = "[{$total}] [{$delta}] ".$msg; // Add time spent and cumulated time spent + $string = $logfunc . '(\'' . addslashes($msg) . '\');' . "\n"; + + return $string; + } + + + protected function renderFooter () + { + $string = <<<EOD + +} +</script> + +EOD; + + return $string; + } + + protected function getFirebugLoggingFunction($level) + { + switch ($level) + { + case TLogger::DEBUG: + case TLogger::INFO: + case TLogger::NOTICE: + return 'console.log'; + case TLogger::WARNING: + return 'console.warn'; + case TLogger::ERROR: + case TLogger::ALERT: + case TLogger::FATAL: + return 'console.error'; + default: + return 'console.log'; + } + } + +} + +/** + * TFirePhpLogRoute class. + * + * TFirePhpLogRoute prints log messages in the firebug log console via firephp. + * + * {@link http://www.getfirebug.com/ FireBug Website} + * {@link http://www.firephp.org/ FirePHP Website} + * + * @author Yves Berkholz <godzilla80[at]gmx[dot]net> + * @package System.Util + * @since 3.1.5 + */ +class TFirePhpLogRoute extends TLogRoute +{ + /** + * Default group label + */ + const DEFAULT_LABEL = 'System.Util.TLogRouter(TFirePhpLogRoute)'; + + private $_groupLabel = null; + + public function processLogs($logs) + { + if(empty($logs) || $this->getApplication()->getMode()==='Performance') + return; + + if(headers_sent()) { + echo ' + <div style="width:100%; background-color:darkred; color:#FFF; padding:2px"> + TFirePhpLogRoute.GroupLabel "<i>' . $this -> getGroupLabel() . '</i>" - + Routing to FirePHP impossible, because headers already sent! + </div> + '; + $fallback = new TBrowserLogRoute(); + $fallback->processLogs($logs); + return; + } + + require_once Prado::getPathOfNamespace('System.3rdParty.FirePHPCore') . '/FirePHP.class.php'; + $firephp = FirePHP::getInstance(true); + $firephp->setOptions(array('useNativeJsonEncode' => false)); + $firephp->group($this->getGroupLabel(), array('Collapsed' => true)); + $firephp->log('Time, Message'); + + $first = $logs[0][3]; + $c = count($logs); + for($i=0,$n=$c;$i<$n;++$i) + { + $message = $logs[$i][0]; + $level = $logs[$i][1]; + $category = $logs[$i][2]; + + if ($i<$n-1) + { + $delta = $logs[$i+1][3] - $logs[$i][3]; + $total = $logs[$i+1][3] - $first; + } + else + { + $delta = '?'; + $total = $logs[$i][3] - $first; + } + + $message = sPrintF('+%0.6f: %s', $delta, preg_replace('/\(line[^\)]+\)$/', '', $message)); + $firephp->fb($message, $category, self::translateLogLevel($level)); + } + $firephp->log(sPrintF('%0.6f', $total), 'Cumulated Time'); + $firephp->groupEnd(); + } + + /** + * Translates a PRADO log level attribute into one understood by FirePHP for correct visualization + * @param string prado log level + * @return string FirePHP log level + */ + protected static function translateLogLevel($level) + { + switch($level) + { + case TLogger::INFO: + return FirePHP::INFO; + case TLogger::DEBUG: + case TLogger::NOTICE: + return FirePHP::LOG; + case TLogger::WARNING: + return FirePHP::WARN; + case TLogger::ERROR: + case TLogger::ALERT: + case TLogger::FATAL: + return FirePHP::ERROR; + default: + return FirePHP::LOG; + } + } + + /** + * @return string group label. Defaults to TFirePhpLogRoute::DEFAULT_LABEL + */ + public function getGroupLabel() + { + if($this->_groupLabel===null) + $this->_groupLabel=self::DEFAULT_LABEL; + + return $this->_groupLabel; + } + + /** + * @param string group label. + */ + public function setGroupLabel($value) + { + $this->_groupLabel=$value; + } +} diff --git a/lib/prado/framework/Util/TLogger.php b/lib/prado/framework/Util/TLogger.php new file mode 100644 index 0000000..6f188b0 --- /dev/null +++ b/lib/prado/framework/Util/TLogger.php @@ -0,0 +1,234 @@ +<?php +/** + * TLogger class file + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @link https://github.com/pradosoft/prado + * @copyright Copyright © 2005-2015 The PRADO Group + * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT + * @package System.Util + */ + +/** + * TLogger class. + * + * TLogger records log messages in memory and implements the methods to + * retrieve the messages with filter conditions, including log levels, + * log categories, and by control. + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @package System.Util + * @since 3.0 + */ +class TLogger extends TComponent +{ + /** + * Log levels. + */ + const DEBUG=0x01; + const INFO=0x02; + const NOTICE=0x04; + const WARNING=0x08; + const ERROR=0x10; + const ALERT=0x20; + const FATAL=0x40; + /** + * @var array log messages + */ + private $_logs=array(); + /** + * @var integer log levels (bits) to be filtered + */ + private $_levels; + /** + * @var array list of categories to be filtered + */ + private $_categories; + /** + * @var array list of control client ids to be filtered + */ + private $_controls; + /** + * @var float timestamp used to filter + */ + private $_timestamp; + + /** + * Logs a message. + * Messages logged by this method may be retrieved via {@link getLogs}. + * @param string message to be logged + * @param integer level of the message. Valid values include + * TLogger::DEBUG, TLogger::INFO, TLogger::NOTICE, TLogger::WARNING, + * TLogger::ERROR, TLogger::ALERT, TLogger::FATAL. + * @param string category of the message + * @param string|TControl control of the message + */ + public function log($message,$level,$category='Uncategorized', $ctl=null) + { + if($ctl) { + if($ctl instanceof TControl) + $ctl = $ctl->ClientId; + else if(!is_string($ctl)) + $ctl = null; + } else + $ctl = null; + $this->_logs[]=array($message,$level,$category,microtime(true),memory_get_usage(),$ctl); + } + + /** + * Retrieves log messages. + * Messages may be filtered by log levels and/or categories and/or control client ids and/or timestamp. + * A level filter is specified by an integer, whose bits indicate the levels interested. + * For example, (TLogger::INFO | TLogger::WARNING) specifies INFO and WARNING levels. + * A category filter is specified by an array of categories to filter. + * A message whose category name starts with any filtering category + * will be returned. For example, a category filter array('System.Web','System.IO') + * will return messages under categories such as 'System.Web', 'System.IO', + * 'System.Web.UI', 'System.Web.UI.WebControls', etc. + * A control client id filter is specified by an array of control client id + * A message whose control client id starts with any filtering naming panels + * will be returned. For example, a category filter array('ctl0_body_header', + * 'ctl0_body_content_sidebar') + * will return messages under categories such as 'ctl0_body_header', 'ctl0_body_content_sidebar', + * 'ctl0_body_header_title', 'ctl0_body_content_sidebar_savebutton', etc. + * A timestamp filter is specified as an interger or float number. + * A message whose registered timestamp is less or equal the filter value will be returned. + * Level filter, category filter, control filter and timestamp filter are combinational, i.e., only messages + * satisfying all filter conditions will they be returned. + * @param integer level filter + * @param array category filter + * @param array control filter + * @return array list of messages. Each array elements represents one message + * with the following structure: + * array( + * [0] => message + * [1] => level + * [2] => category + * [3] => timestamp (by microtime(), float number)); + * [4] => memory in bytes + * [5] => control client id + */ + public function getLogs($levels=null,$categories=null,$controls=null,$timestamp=null) + { + $this->_levels=$levels; + $this->_categories=$categories; + $this->_controls=$controls; + $this->_timestamp=$timestamp; + if(empty($levels) && empty($categories) && empty($controls) && is_null($timestamp)) + return $this->_logs; + $logs = $this->_logs; + if(!empty($levels)) + $logs = array_values(array_filter( array_filter($logs,array($this,'filterByLevels')) )); + if(!empty($categories)) + $logs = array_values(array_filter( array_filter($logs,array($this,'filterByCategories')) )); + if(!empty($controls)) + $logs = array_values(array_filter( array_filter($logs,array($this,'filterByControl')) )); + if(!is_null($timestamp)) + $logs = array_values(array_filter( array_filter($logs,array($this,'filterByTimeStamp')) )); + return $logs; + } + + /** + * Deletes log messages from the queue. + * Messages may be filtered by log levels and/or categories and/or control client ids and/or timestamp. + * A level filter is specified by an integer, whose bits indicate the levels interested. + * For example, (TLogger::INFO | TLogger::WARNING) specifies INFO and WARNING levels. + * A category filter is specified by an array of categories to filter. + * A message whose category name starts with any filtering category + * will be deleted. For example, a category filter array('System.Web','System.IO') + * will delete messages under categories such as 'System.Web', 'System.IO', + * 'System.Web.UI', 'System.Web.UI.WebControls', etc. + * A control client id filter is specified by an array of control client id + * A message whose control client id starts with any filtering naming panels + * will be deleted. For example, a category filter array('ctl0_body_header', + * 'ctl0_body_content_sidebar') + * will delete messages under categories such as 'ctl0_body_header', 'ctl0_body_content_sidebar', + * 'ctl0_body_header_title', 'ctl0_body_content_sidebar_savebutton', etc. + * A timestamp filter is specified as an interger or float number. + * A message whose registered timestamp is less or equal the filter value will be returned. + * Level filter, category filter, control filter and timestamp filter are combinational, i.e., only messages + * satisfying all filter conditions will they be returned. + * @param integer level filter + * @param array category filter + * @param array control filter + */ + public function deleteLogs($levels=null,$categories=null,$controls=null,$timestamp=null) + { + $this->_levels=$levels; + $this->_categories=$categories; + $this->_controls=$controls; + $this->_timestamp=$timestamp; + if(empty($levels) && empty($categories) && empty($controls) && is_null($timestamp)) + { + $this->_logs=array(); + return; + } + $logs = $this->_logs; + if(!empty($levels)) + $logs = array_filter( array_filter($logs,array($this,'filterByLevels')) ); + if(!empty($categories)) + $logs = array_filter( array_filter($logs,array($this,'filterByCategories')) ); + if(!empty($controls)) + $logs = array_filter( array_filter($logs,array($this,'filterByControl')) ); + if(!is_null($timestamp)) + $logs = array_filter( array_filter($logs,array($this,'filterByTimeStamp')) ); + $this->_logs = array_values( array_diff_key($this->_logs, $logs) ); + } + + /** + * Filter function used by {@link getLogs}. + * @param array element to be filtered + */ + private function filterByCategories($value) + { + foreach($this->_categories as $category) + { + // element 2 is the category + if($value[2]===$category || strpos($value[2],$category.'.')===0) + return $value; + } + return false; + } + + /** + * Filter function used by {@link getLogs} + * @param array element to be filtered + */ + private function filterByLevels($value) + { + // element 1 are the levels + if($value[1] & $this->_levels) + return $value; + else + return false; + } + + /** + * Filter function used by {@link getLogs} + * @param array element to be filtered + */ + private function filterByControl($value) + { + // element 5 are the control client ids + foreach($this->_controls as $control) + { + if($value[5]===$control || strpos($value[5],$control)===0) + return $value; + } + return false; + } + + /** + * Filter function used by {@link getLogs} + * @param array element to be filtered + */ + private function filterByTimeStamp($value) + { + // element 3 is the timestamp + if($value[3] <= $this->_timestamp) + return $value; + else + return false; + } +} + diff --git a/lib/prado/framework/Util/TParameterModule.php b/lib/prado/framework/Util/TParameterModule.php new file mode 100644 index 0000000..4819d30 --- /dev/null +++ b/lib/prado/framework/Util/TParameterModule.php @@ -0,0 +1,171 @@ +<?php +/** + * TParameterModule class + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @link https://github.com/pradosoft/prado + * @copyright Copyright © 2005-2015 The PRADO Group + * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT + * @package System.Util + */ + +/** + * TParameterModule class + * + * TParameterModule enables loading application parameters from external + * storage other than the application configuration. + * To load parameters from an XML file, configure the module by setting + * its {@link setParameterFile ParameterFile} property. + * Note, the property only accepts a file path in namespace format with + * file extension being '.xml'. The file format is as follows, which is + * similar to the parameter portion in an application configuration, + * <code> + * <parameters> + * <parameter id="param1" value="paramValue1" /> + * <parameter id="param2" Property1="Value1" Property2="Value2" ... /> + * </parameters> + * </code> + * + * In addition, any content enclosed within the module tag is also treated + * as parameters, e.g., + * <code> + * <module class="System.Util.TParameterModule"> + * <parameter id="param1" value="paramValue1" /> + * <parameter id="param2" Property1="Value1" Property2="Value2" ... /> + * </module> + * </code> + * + * If a parameter is defined both in the external file and within the module + * tag, the former takes precedence. + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @author Carl G. Mathisen <carlgmathisen@gmail.com> + * @package System.Util + * @since 3.0 + */ +class TParameterModule extends TModule +{ + /** + * @deprecated since 3.2 + */ + const PARAM_FILE_EXT='.xml'; + private $_initialized=false; + private $_paramFile=null; + + /** + * Initializes the module by loading parameters. + * @param mixed content enclosed within the module tag + */ + public function init($config) + { + $this->loadParameters($config); + if($this->_paramFile!==null) + { + $configFile = null; + if($this->getApplication()->getConfigurationType()==TApplication::CONFIG_TYPE_XML && ($cache=$this->getApplication()->getCache())!==null) + { + $cacheKey='TParameterModule:'.$this->_paramFile; + if(($configFile=$cache->get($cacheKey))===false) + { + $configFile=new TXmlDocument; + $configFile->loadFromFile($this->_paramFile); + $cache->set($cacheKey,$configFile,0,new TFileCacheDependency($this->_paramFile)); + } + } + else + { + if($this->getApplication()->getConfigurationType()==TApplication::CONFIG_TYPE_PHP) + { + $configFile = include $this->_paramFile; + } + else + { + $configFile=new TXmlDocument; + $configFile->loadFromFile($this->_paramFile); + } + } + $this->loadParameters($configFile); + } + $this->_initialized=true; + } + + /** + * Loads parameters into application. + * @param mixed XML of PHP representation of the parameters + * @throws TConfigurationException if the parameter file format is invalid + */ + protected function loadParameters($config) + { + $parameters=array(); + if(is_array($config)) + { + foreach($config as $id => $parameter) + { + if(is_array($parameter) && isset($parameter['class'])) + { + $properties = isset($parameter['properties'])?$parameter['properties']:array(); + $parameters[$id]=array($parameter['class'],$properties); + } + else + { + $parameters[$id] = $parameter; + } + } + } + else if($config instanceof TXmlElement) + { + foreach($config->getElementsByTagName('parameter') as $node) + { + $properties=$node->getAttributes(); + if(($id=$properties->remove('id'))===null) + throw new TConfigurationException('parametermodule_parameterid_required'); + if(($type=$properties->remove('class'))===null) + { + if(($value=$properties->remove('value'))===null) + $parameters[$id]=$node; + else + $parameters[$id]=$value; + } + else + $parameters[$id]=array($type,$properties->toArray()); + } + } + + $appParams=$this->getApplication()->getParameters(); + foreach($parameters as $id=>$parameter) + { + if(is_array($parameter)) + { + $component=Prado::createComponent($parameter[0]); + foreach($parameter[1] as $name=>$value) + $component->setSubProperty($name,$value); + $appParams->add($id,$component); + } + else + $appParams->add($id,$parameter); + } + } + + /** + * @return string the parameter file path + */ + public function getParameterFile() + { + return $this->_paramFile; + } + + /** + * @param string the parameter file path. It must be in namespace format + * and the file extension is '.xml'. + * @throws TInvalidOperationException if the module is initialized + * @throws TConfigurationException if the file is invalid + */ + public function setParameterFile($value) + { + if($this->_initialized) + throw new TInvalidOperationException('parametermodule_parameterfile_unchangeable'); + else if(($this->_paramFile=Prado::getPathOfNamespace($value,$this->getApplication()->getConfigurationFileExt()))===null || !is_file($this->_paramFile)) + throw new TConfigurationException('parametermodule_parameterfile_invalid',$value); + } +} + diff --git a/lib/prado/framework/Util/TRpcClient.php b/lib/prado/framework/Util/TRpcClient.php new file mode 100644 index 0000000..c8920a2 --- /dev/null +++ b/lib/prado/framework/Util/TRpcClient.php @@ -0,0 +1,357 @@ +<?php + +/** + * @author Robin J. Rogge <rrogge@bigpoint.net> + * @link https://github.com/pradosoft/prado + * @copyright 2010 Bigpoint GmbH + * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT + * @since 3.2 + * @package System.Util + */ + +/** + * TRpcClient class + * + * Note: When using setIsNotification(true), *every* following request is also + * considered to be a notification until you use setIsNotification(false). + * + * Usage: + * + * First, you can use the factory: + * <pre> + * $_rpcClient = TRpcClient::create('xml', 'http://host/server'); + * $_result = $_rpcClient->remoteMethodName($param, $otherParam); + * </pre> + * + * or as oneliner: + * <pre> + * $_result = TRpcClient::create('json', 'http://host/server')->remoteMethod($param, ...); + * </pre> + * + * Second, you can also use the specific implementation directly: + * <pre> + * $_rpcClient = new TXmlRpcClient('http://host/server'); + * $_result = $_rpcClient->remoteMethod($param, ...); + * </pre> + * + * or as oneliner: + * <pre> + * $_result = TXmlRpcClient('http://host/server')->hello(); + * </pre> + * + * @author Robin J. Rogge <rrogge@bigpoint.net> + * @version $Id$ + * @package System.Util + * @since 3.2 + */ + +class TRpcClient extends TApplicationComponent +{ + /** + * @var string url of the RPC server + */ + private $_serverUrl; + + /** + * @var boolean whether the request is a notification and therefore should not care about the result (default: false) + */ + private $_isNotification = false; + + // magics + + /** + * @param string url to RPC server + * @param boolean whether requests are considered to be notifications (completely ignoring the response) (default: false) + */ + public function __construct($serverUrl, $isNotification = false) + { + $this->_serverUrl = $serverUrl; + $this->_isNotification = TPropertyValue::ensureBoolean($isNotification); + } + + // methods + + /** + * Creates an instance of the requested RPC client type + * @return TRpcClient instance + * @throws TApplicationException if an unsupported RPC client type was specified + */ + public static function create($type, $serverUrl, $isNotification = false) + { + if(($_handler = constant('TRpcClientTypesEnumerable::'.strtoupper($type))) === null) + throw new TApplicationException('rpcclient_unsupported_handler'); + + return new $_handler($serverUrl, $isNotification); + } + + /** + * Creates a stream context resource + * @param mixed $content + * @param string $contentType mime type + */ + protected function createStreamContext($content, $contentType) + { + return stream_context_create(array( + 'http' => array( + 'method' => 'POST', + 'header' => "Content-Type: {$contentType}", + 'content' => $content + ) + )); + } + + /** + * Performs the actual request + * @param string RPC server URL + * @param array payload data + * @param string request mime type + */ + protected function performRequest($serverUrl, $payload, $mimeType) + { + if(($_response = @file_get_contents($serverUrl, false, $this->createStreamContext($payload, $mimeType))) === false) + throw new TRpcClientRequestException('Request failed ("'.$http_response_header[0].'")'); + + return $_response; + } + + // getter/setter + + /** + * @return boolean whether requests are considered to be notifications (completely ignoring the response) + */ + public function getIsNotification() + { + return $this->_isNotification; + } + + /** + * @param string boolean whether the requests are considered to be notifications (completely ignoring the response) (default: false) + */ + public function setIsNotification($bool) + { + $this->_isNotification = TPropertyValue::ensureBoolean($bool); + } + + /** + * @return string url of the RPC server + */ + public function getServerUrl() + { + return $this->_serverUrl; + } + + /** + * @param string url of the RPC server + */ + public function setServerUrl($value) + { + $this->_serverUrl = $value; + } +} + +/** + * TRpcClientTypesEnumerable class + * + * @author Robin J. Rogge <rrogge@bigpoint.net> + * @version $Id$ + * @package System.Util + * @since 3.2 + */ + +class TRpcClientTypesEnumerable extends TEnumerable +{ + const JSON = 'TJsonRpcClient'; + const XML = 'TXmlRpcClient'; +} + +/** + * TRpcClientRequestException class + * + * This Exception is fired if the RPC request fails because of transport problems e.g. when + * there is no RPC server responding on the given remote host. + * + * @author Robin J. Rogge <rrogge@bigpoint.net> + * @version $Id$ + * @package System.Util + * @since 3.2 + */ + +class TRpcClientRequestException extends TApplicationException +{ +} + +/** + * TRpcClientResponseException class + * + * This Exception is fired when the + * + * @author Robin J. Rogge <rrogge@bigpoint.net> + * @version $Id$ + * @package System.Util + * @since 3.2 + */ + +class TRpcClientResponseException extends TApplicationException +{ + /** + * @param string error message + * @param integer error code (optional) + */ + public function __construct($errorMessage, $errorCode = null) + { + $this->setErrorCode($errorCode); + + parent::__construct($errorMessage); + } +} + +/** + * TJsonRpcClient class + * + * Note: When using setIsNotification(true), *every* following request is also + * considered to be a notification until you use setIsNotification(false). + * + * Usage: + * <pre> + * $_rpcClient = new TJsonRpcClient('http://host/server'); + * $_result = $_rpcClient->remoteMethod($param, $otherParam); + * // or + * $_result = TJsonRpcClient::create('http://host/server')->remoteMethod($param, $otherParam); + * </pre> + * + * @author Robin J. Rogge <rrogge@bigpoint.net> + * @version $Id$ + * @package System.Util + * @since 3.2 + */ + +class TJsonRpcClient extends TRpcClient +{ + // magics + + /** + * @param string RPC method name + * @param array RPC method parameters + * @return mixed RPC request result + * @throws TRpcClientRequestException if the client fails to connect to the server + * @throws TRpcClientResponseException if the response represents an RPC fault + */ + public function __call($method, $parameters) + { + // send request + $_response = $this->performRequest($this->getServerUrl(), $this->encodeRequest($method, $parameters), 'application/json'); + + // skip response handling if the request was just a notification request + if($this->isNotification) + return true; + + // decode response + if(($_response = json_decode($_response, true)) === null) + throw new TRpcClientResponseException('Empty response received'); + + // handle error response + if(!is_null($_response['error'])) + throw new TRpcClientResponseException($_response['error']); + + return $_response['result']; + } + + // methods + + /** + * @param string method name + * @param array method parameters + */ + public function encodeRequest($method, $parameters) + { + static $_requestId; + $_requestId = ($_requestId === null) ? 1 : $_requestId + 1; + + return json_encode(array( + 'method' => $method, + 'params' => $parameters, + 'id' => $this->isNotification ? null : $_requestId + )); + } + + /** + * Creates an instance of TJsonRpcClient + * @param string url of the rpc server + * @param boolean whether the requests are considered to be notifications (completely ignoring the response) (default: false) + */ + public static function create($type, $serverUrl, $isNotification = false) + { + return new self($serverUrl, $isNotification); + } +} + +/** + * TXmlRpcClient class + * + * Note: When using setIsNotification(true), *every* following request is also + * considered to be a notification until you use setIsNotification(false). + * + * Usage: + * <pre> + * $_rpcClient = new TXmlRpcClient('http://remotehost/rpcserver'); + * $_rpcClient->remoteMethod($param, $otherParam); + * </pre> + * + * @author Robin J. Rogge <rrogge@bigpoint.net> + * @version $Id$ + * @package System.Util + * @since 3.2 + */ + +class TXmlRpcClient extends TRpcClient +{ + // magics + + /** + * @param string RPC method name + * @param array RPC method parameters + * @return mixed RPC request result + * @throws TRpcClientRequestException if the client fails to connect to the server + * @throws TRpcClientResponseException if the response represents an RPC fault + */ + public function __call($method, $parameters) + { + // send request + $_response = $this->performRequest($this->getServerUrl(), $this->encodeRequest($method, $parameters), 'text/xml'); + + // skip response handling if the request was just a notification request + if($this->isNotification) + return true; + + // decode response + if(($_response = xmlrpc_decode($_response)) === null) + throw new TRpcClientResponseException('Empty response received'); + + // handle error response + if(xmlrpc_is_fault($_response)) + throw new TRpcClientResponseException($_response['faultString'], $_response['faultCode']); + + return $_response; + } + + // methods + + /** + * @param string method name + * @param array method parameters + */ + public function encodeRequest($method, $parameters) + { + return xmlrpc_encode_request($method, $parameters); + } + + /** + * Creates an instance of TXmlRpcClient + * @param string url of the rpc server + * @param boolean whether the requests are considered to be notifications (completely ignoring the response) (default: false) + */ + public static function create($type, $serverUrl, $isNotification = false) + { + return new self($serverUrl, $isNotification); + } +} diff --git a/lib/prado/framework/Util/TSimpleDateFormatter.php b/lib/prado/framework/Util/TSimpleDateFormatter.php new file mode 100644 index 0000000..7e9fec6 --- /dev/null +++ b/lib/prado/framework/Util/TSimpleDateFormatter.php @@ -0,0 +1,369 @@ +<?php +/** + * TSimpleDateFormatter class file + * + * @author Wei Zhuo <weizhuo[at]gmail[dot]com> + * @link https://github.com/pradosoft/prado + * @copyright Copyright © 2005-2015 The PRADO Group + * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT + * @package System.Util + */ + +/** + * TSimpleDateFormatter class. + * + * Formats and parses dates using the SimpleDateFormat pattern. + * This pattern is compatible with the I18N and java's SimpleDateFormatter. + * <code> + * Pattern | Description + * ---------------------------------------------------- + * d | Day of month 1 to 31, no padding + * dd | Day of monath 01 to 31, zero leading + * M | Month digit 1 to 12, no padding + * MM | Month digit 01 to 12, zero leading + * yy | 2 year digit, e.g., 96, 05 + * yyyy | 4 year digit, e.g., 2005 + * ---------------------------------------------------- + * </code> + * + * Usage example, to format a date + * <code> + * $formatter = new TSimpleDateFormatter("dd/MM/yyy"); + * echo $formatter->format(time()); + * </code> + * + * To parse the date string into a date timestamp. + * <code> + * $formatter = new TSimpleDateFormatter("d-M-yyy"); + * echo $formatter->parse("24-6-2005"); + * </code> + * + * @author Wei Zhuo <weizhuo[at]gmail[dot]com> + * @package System.Util + * @since 3.0 + */ +class TSimpleDateFormatter +{ + /** + * Formatting pattern. + * @var string + */ + private $pattern; + + /** + * Charset, default is 'UTF-8' + * @var string + */ + private $charset = 'UTF-8'; + + /** + * Constructor, create a new date time formatter. + * @param string formatting pattern. + * @param string pattern and value charset + */ + public function __construct($pattern, $charset='UTF-8') + { + $this->setPattern($pattern); + $this->setCharset($charset); + } + + /** + * @return string formatting pattern. + */ + public function getPattern() + { + return $this->pattern; + } + + /** + * @param string formatting pattern. + */ + public function setPattern($pattern) + { + $this->pattern = $pattern; + } + + /** + * @return string formatting charset. + */ + public function getCharset() + { + return $this->charset; + } + + /** + * @param string formatting charset. + */ + public function setCharset($charset) + { + $this->charset = $charset; + } + + /** + * Format the date according to the pattern. + * @param string|int the date to format, either integer or a string readable by strtotime. + * @return string formatted date. + */ + public function format($value) + { + $date = $this->getDate($value); + $bits['yyyy'] = $date['year']; + $bits['yy'] = substr("{$date['year']}", -2); + + $bits['MM'] = str_pad("{$date['mon']}", 2, '0', STR_PAD_LEFT); + $bits['M'] = $date['mon']; + + $bits['dd'] = str_pad("{$date['mday']}", 2, '0', STR_PAD_LEFT); + $bits['d'] = $date['mday']; + + $pattern = preg_replace('/M{3,4}/', 'MM', $this->pattern); + return str_replace(array_keys($bits), $bits, $pattern); + } + + public function getMonthPattern() + { + if(is_int(strpos($this->pattern, 'MMMM'))) + return 'MMMM'; + if(is_int(strpos($this->pattern, 'MMM'))) + return 'MMM'; + if(is_int(strpos($this->pattern, 'MM'))) + return 'MM'; + if(is_int(strpos($this->pattern, 'M'))) + return 'M'; + return false; + } + + public function getDayPattern() + { + if(is_int(strpos($this->pattern, 'dd'))) + return 'dd'; + if(is_int(strpos($this->pattern, 'd'))) + return 'd'; + return false; + } + + public function getYearPattern() + { + if(is_int(strpos($this->pattern, 'yyyy'))) + return 'yyyy'; + if(is_int(strpos($this->pattern, 'yy'))) + return 'yy'; + return false; + } + + public function getDayMonthYearOrdering() + { + $ordering = array(); + if(is_int($day= strpos($this->pattern, 'd'))) + $ordering['day'] = $day; + if(is_int($month= strpos($this->pattern, 'M'))) + $ordering['month'] = $month; + if(is_int($year= strpos($this->pattern, 'yy'))) + $ordering['year'] = $year; + asort($ordering); + return array_keys($ordering); + } + + /** + * Gets the time stamp from string or integer. + * @param string|int date to parse + * @return array date info array + */ + private function getDate($value) + { + $s = Prado::createComponent('System.Util.TDateTimeStamp'); + if(is_numeric($value)) + return $s->getDate($value); + else + return $s->parseDate($value); + } + + /** + * @return boolean true if the given value matches with the date pattern. + */ + public function isValidDate($value) + { + if($value === null) { + return false; + } else { + return $this->parse($value, false) !== null; + } + } + + /** + * Parse the string according to the pattern. + * @param string|int date string or integer to parse + * @return int date time stamp + * @throws TInvalidDataValueException if date string is malformed. + */ + public function parse($value,$defaultToCurrentTime=true) + { + if(is_int($value) || is_float($value)) + return $value; + else if(!is_string($value)) + throw new TInvalidDataValueException('date_to_parse_must_be_string', $value); + + if(empty($this->pattern)) return time(); + + $date = time(); + + if($this->length(trim($value)) < 1) + return $defaultToCurrentTime ? $date : null; + + $pattern = $this->pattern; + + $i_val = 0; + $i_format = 0; + $pattern_length = $this->length($pattern); + $c = ''; + $token=''; + $x=null; $y=null; + + + if($defaultToCurrentTime) + { + $year = "{$date['year']}"; + $month = $date['mon']; + $day = $date['mday']; + } + else + { + $year = null; + $month = null; + $day = null; + } + + while ($i_format < $pattern_length) + { + $c = $this->charAt($pattern,$i_format); + $token=''; + while ($this->charEqual($pattern, $i_format, $c) + && ($i_format < $pattern_length)) + { + $token .= $this->charAt($pattern, $i_format++); + } + + if ($token=='yyyy' || $token=='yy' || $token=='y') + { + if ($token=='yyyy') { $x=4;$y=4; } + if ($token=='yy') { $x=2;$y=2; } + if ($token=='y') { $x=2;$y=4; } + $year = $this->getInteger($value,$i_val,$x,$y); + if($year === null) + return null; + //throw new TInvalidDataValueException('Invalid year', $value); + $i_val += strlen($year); + if(strlen($year) == 2) + { + $iYear = (int)$year; + if($iYear > 70) + $year = $iYear + 1900; + else + $year = $iYear + 2000; + } + $year = (int)$year; + } + elseif($token=='MM' || $token=='M') + { + $month=$this->getInteger($value,$i_val, + $this->length($token),2); + $iMonth = (int)$month; + if($month === null || $iMonth < 1 || $iMonth > 12 ) + return null; + //throw new TInvalidDataValueException('Invalid month', $value); + $i_val += strlen($month); + $month = $iMonth; + } + elseif ($token=='dd' || $token=='d') + { + $day = $this->getInteger($value,$i_val, + $this->length($token), 2); + $iDay = (int)$day; + if($day === null || $iDay < 1 || $iDay >31) + return null; + //throw new TInvalidDataValueException('Invalid day', $value); + $i_val += strlen($day); + $day = $iDay; + } + else + { + if($this->substring($value, $i_val, $this->length($token)) != $token) + return null; + //throw new TInvalidDataValueException("Subpattern '{$this->pattern}' mismatch", $value); + else + $i_val += $this->length($token); + } + } + if ($i_val != $this->length($value)) + return null; + //throw new TInvalidDataValueException("Pattern '{$this->pattern}' mismatch", $value); + if(!$defaultToCurrentTime && ($month === null || $day === null || $year === null)) + return null; + else + { + if(empty($year)) { + $year = date('Y'); + } + $day = (int)$day <= 0 ? 1 : (int)$day; + $month = (int)$month <= 0 ? 1 : (int)$month; + $s = Prado::createComponent('System.Util.TDateTimeStamp'); + return $s->getTimeStamp(0, 0, 0, $month, $day, $year); + } + } + + /** + * Calculate the length of a string, may be consider iconv_strlen? + */ + private function length($string) + { + //use iconv_strlen or just strlen? + return strlen($string); + } + + /** + * Get the char at a position. + */ + private function charAt($string, $pos) + { + return $this->substring($string, $pos, 1); + } + + /** + * Gets a portion of a string, uses iconv_substr. + */ + private function substring($string, $start, $length) + { + return iconv_substr($string, $start, $length); + } + + /** + * Returns true if char at position equals a particular char. + */ + private function charEqual($string, $pos, $char) + { + return $this->charAt($string, $pos) == $char; + } + + /** + * Gets integer from part of a string, allows integers of any length. + * @param string string to retrieve the integer from. + * @param int starting position + * @param int minimum integer length + * @param int maximum integer length + * @return string integer portion of the string, null otherwise + */ + private function getInteger($str,$i,$minlength,$maxlength) + { + //match for digits backwards + for ($x = $maxlength; $x >= $minlength; $x--) + { + $token= $this->substring($str, $i,$x); + if ($this->length($token) < $minlength) + return null; + if (preg_match('/^\d+$/', $token)) + return $token; + } + return null; + } +} + diff --git a/lib/prado/framework/Util/TVarDumper.php b/lib/prado/framework/Util/TVarDumper.php new file mode 100644 index 0000000..c531848 --- /dev/null +++ b/lib/prado/framework/Util/TVarDumper.php @@ -0,0 +1,126 @@ +<?php +/** + * TVarDumper class file + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @link https://github.com/pradosoft/prado + * @copyright Copyright © 2005-2015 The PRADO Group + * @license https://github.com/pradosoft/prado/blob/master/COPYRIGHT + * @package System.Util + */ + +/** + * TVarDumper class. + * + * TVarDumper is intended to replace the buggy PHP function var_dump and print_r. + * It can correctly identify the recursively referenced objects in a complex + * object structure. It also has a recursive depth control to avoid indefinite + * recursive display of some peculiar variables. + * + * TVarDumper can be used as follows, + * <code> + * echo TVarDumper::dump($var); + * </code> + * + * @author Qiang Xue <qiang.xue@gmail.com> + * @package System.Util + * @since 3.0 + */ +class TVarDumper +{ + private static $_objects; + private static $_output; + private static $_depth; + + /** + * Converts a variable into a string representation. + * This method achieves the similar functionality as var_dump and print_r + * but is more robust when handling complex objects such as PRADO controls. + * @param mixed variable to be dumped + * @param integer maximum depth that the dumper should go into the variable. Defaults to 10. + * @return string the string representation of the variable + */ + public static function dump($var,$depth=10,$highlight=false) + { + self::$_output=''; + self::$_objects=array(); + self::$_depth=$depth; + self::dumpInternal($var,0); + if($highlight) + { + $result=highlight_string("<?php\n".self::$_output,true); + return preg_replace('/<\\?php<br \\/>/','',$result,1); + } + else + return self::$_output; + } + + private static function dumpInternal($var,$level) + { + switch(gettype($var)) + { + case 'boolean': + self::$_output.=$var?'true':'false'; + break; + case 'integer': + self::$_output.="$var"; + break; + case 'double': + self::$_output.="$var"; + break; + case 'string': + self::$_output.="'$var'"; + break; + case 'resource': + self::$_output.='{resource}'; + break; + case 'NULL': + self::$_output.="null"; + break; + case 'unknown type': + self::$_output.='{unknown}'; + break; + case 'array': + if(self::$_depth<=$level) + self::$_output.='array(...)'; + else if(empty($var)) + self::$_output.='array()'; + else + { + $keys=array_keys($var); + $spaces=str_repeat(' ',$level*4); + self::$_output.="array\n".$spaces.'('; + foreach($keys as $key) + { + self::$_output.="\n".$spaces." [$key] => "; + self::$_output.=self::dumpInternal($var[$key],$level+1); + } + self::$_output.="\n".$spaces.')'; + } + break; + case 'object': + if(($id=array_search($var,self::$_objects,true))!==false) + self::$_output.=get_class($var).'#'.($id+1).'(...)'; + else if(self::$_depth<=$level) + self::$_output.=get_class($var).'(...)'; + else + { + $id=array_push(self::$_objects,$var); + $className=get_class($var); + $members=(array)$var; + $keys=array_keys($members); + $spaces=str_repeat(' ',$level*4); + self::$_output.="$className#$id\n".$spaces.'('; + foreach($keys as $key) + { + $keyDisplay=strtr(trim($key),array("\0"=>':')); + self::$_output.="\n".$spaces." [$keyDisplay] => "; + self::$_output.=self::dumpInternal($members[$key],$level+1); + } + self::$_output.="\n".$spaces.')'; + } + break; + } + } +} + |