Browse Source

...

tags/2.0.0-beta
Qiang Xue 13 years ago
parent
commit
945c6e6a41
  1. 487
      framework/base/ErrorHandler.php
  2. 40
      framework/base/HttpException.php
  3. 2
      framework/base/Module.php
  4. 329
      framework/base/SecurityManager.php
  5. 74
      framework/base/StatePersister.php
  6. 10
      framework/db/ar/ActiveFinder.php

487
framework/base/ErrorHandler.php

@ -0,0 +1,487 @@
<?php
/**
* This file contains the error handler application component.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2011 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
Yii::import('CHtml',true);
/**
* CErrorHandler handles uncaught PHP errors and exceptions.
*
* It displays these errors using appropriate views based on the
* nature of the error and the mode the application runs at.
* It also chooses the most preferred language for displaying the error.
*
* CErrorHandler uses two sets of views:
* <ul>
* <li>development views, named as <code>exception.php</code>;
* <li>production views, named as <code>error&lt;StatusCode&gt;.php</code>;
* </ul>
* where &lt;StatusCode&gt; stands for the HTTP error code (e.g. error500.php).
* Localized views are named similarly but located under a subdirectory
* whose name is the language code (e.g. zh_cn/error500.php).
*
* Development views are displayed when the application is in debug mode
* (i.e. YII_DEBUG is defined as true). Detailed error information with source code
* are displayed in these views. Production views are meant to be shown
* to end-users and are used when the application is in production mode.
* For security reasons, they only display the error message without any
* sensitive information.
*
* CErrorHandler looks for the view templates from the following locations in order:
* <ol>
* <li><code>themes/ThemeName/views/system</code>: when a theme is active.</li>
* <li><code>protected/views/system</code></li>
* <li><code>framework/views</code></li>
* </ol>
* If the view is not found in a directory, it will be looked for in the next directory.
*
* The property {@link maxSourceLines} can be changed to specify the number
* of source code lines to be displayed in development views.
*
* CErrorHandler is a core application component that can be accessed via
* {@link CApplication::getErrorHandler()}.
*
* @property array $error The error details. Null if there is no error.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id$
* @package system.base
* @since 1.0
*/
class CErrorHandler extends CApplicationComponent
{
/**
* @var integer maximum number of source code lines to be displayed. Defaults to 25.
*/
public $maxSourceLines=25;
/**
* @var integer maximum number of trace source code lines to be displayed. Defaults to 10.
* @since 1.1.6
*/
public $maxTraceSourceLines = 10;
/**
* @var string the application administrator information (could be a name or email link). It is displayed in error pages to end users. Defaults to 'the webmaster'.
*/
public $adminInfo='the webmaster';
/**
* @var boolean whether to discard any existing page output before error display. Defaults to true.
*/
public $discardOutput=true;
/**
* @var string the route (eg 'site/error') to the controller action that will be used to display external errors.
* Inside the action, it can retrieve the error information by Yii::app()->errorHandler->error.
* This property defaults to null, meaning CErrorHandler will handle the error display.
*/
public $errorAction;
private $_error;
/**
* Handles the exception/error event.
* This method is invoked by the application whenever it captures
* an exception or PHP error.
* @param CEvent $event the event containing the exception/error information
*/
public function handle($event)
{
// set event as handled to prevent it from being handled by other event handlers
$event->handled=true;
if($this->discardOutput)
{
// the following manual level counting is to deal with zlib.output_compression set to On
for($level=ob_get_level();$level>0;--$level)
{
@ob_end_clean();
}
}
if($event instanceof CExceptionEvent)
$this->handleException($event->exception);
else // CErrorEvent
$this->handleError($event);
}
/**
* Returns the details about the error that is currently being handled.
* The error is returned in terms of an array, with the following information:
* <ul>
* <li>code - the HTTP status code (e.g. 403, 500)</li>
* <li>type - the error type (e.g. 'CHttpException', 'PHP Error')</li>
* <li>message - the error message</li>
* <li>file - the name of the PHP script file where the error occurs</li>
* <li>line - the line number of the code where the error occurs</li>
* <li>trace - the call stack of the error</li>
* <li>source - the context source code where the error occurs</li>
* </ul>
* @return array the error details. Null if there is no error.
*/
public function getError()
{
return $this->_error;
}
/**
* Handles the exception.
* @param Exception $exception the exception captured
*/
protected function handleException($exception)
{
$app=Yii::app();
if($app instanceof CWebApplication)
{
if(($trace=$this->getExactTrace($exception))===null)
{
$fileName=$exception->getFile();
$errorLine=$exception->getLine();
}
else
{
$fileName=$trace['file'];
$errorLine=$trace['line'];
}
$trace = $exception->getTrace();
foreach($trace as $i=>$t)
{
if(!isset($t['file']))
$trace[$i]['file']='unknown';
if(!isset($t['line']))
$trace[$i]['line']=0;
if(!isset($t['function']))
$trace[$i]['function']='unknown';
unset($trace[$i]['object']);
}
$this->_error=$data=array(
'code'=>($exception instanceof CHttpException)?$exception->statusCode:500,
'type'=>get_class($exception),
'errorCode'=>$exception->getCode(),
'message'=>$exception->getMessage(),
'file'=>$fileName,
'line'=>$errorLine,
'trace'=>$exception->getTraceAsString(),
'traces'=>$trace,
);
if(!headers_sent())
header("HTTP/1.0 {$data['code']} ".get_class($exception));
if($exception instanceof CHttpException || !YII_DEBUG)
$this->render('error',$data);
else
{
if($this->isAjaxRequest())
$app->displayException($exception);
else
$this->render('exception',$data);
}
}
else
$app->displayException($exception);
}
/**
* Handles the PHP error.
* @param CErrorEvent $event the PHP error event
*/
protected function handleError($event)
{
$trace=debug_backtrace();
// skip the first 3 stacks as they do not tell the error position
if(count($trace)>3)
$trace=array_slice($trace,3);
$traceString='';
foreach($trace as $i=>$t)
{
if(!isset($t['file']))
$trace[$i]['file']='unknown';
if(!isset($t['line']))
$trace[$i]['line']=0;
if(!isset($t['function']))
$trace[$i]['function']='unknown';
$traceString.="#$i {$trace[$i]['file']}({$trace[$i]['line']}): ";
if(isset($t['object']) && is_object($t['object']))
$traceString.=get_class($t['object']).'->';
$traceString.="{$trace[$i]['function']}()\n";
unset($trace[$i]['object']);
}
$app=Yii::app();
if($app instanceof CWebApplication)
{
switch($event->code)
{
case E_WARNING:
$type = 'PHP warning';
break;
case E_NOTICE:
$type = 'PHP notice';
break;
case E_USER_ERROR:
$type = 'User error';
break;
case E_USER_WARNING:
$type = 'User warning';
break;
case E_USER_NOTICE:
$type = 'User notice';
break;
case E_RECOVERABLE_ERROR:
$type = 'Recoverable error';
break;
default:
$type = 'PHP error';
}
$this->_error=$data=array(
'code'=>500,
'type'=>$type,
'message'=>$event->message,
'file'=>$event->file,
'line'=>$event->line,
'trace'=>$traceString,
'traces'=>$trace,
);
if(!headers_sent())
header("HTTP/1.0 500 PHP Error");
if($this->isAjaxRequest())
$app->displayError($event->code,$event->message,$event->file,$event->line);
else if(YII_DEBUG)
$this->render('exception',$data);
else
$this->render('error',$data);
}
else
$app->displayError($event->code,$event->message,$event->file,$event->line);
}
/**
* whether the current request is an AJAX (XMLHttpRequest) request.
* @return boolean whether the current request is an AJAX request.
*/
protected function isAjaxRequest()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
}
/**
* Returns the exact trace where the problem occurs.
* @param Exception $exception the uncaught exception
* @return array the exact trace where the problem occurs
*/
protected function getExactTrace($exception)
{
$traces=$exception->getTrace();
foreach($traces as $trace)
{
// property access exception
if(isset($trace['function']) && ($trace['function']==='__get' || $trace['function']==='__set'))
return $trace;
}
return null;
}
/**
* Renders the view.
* @param string $view the view name (file name without extension).
* See {@link getViewFile} for how a view file is located given its name.
* @param array $data data to be passed to the view
*/
protected function render($view,$data)
{
if($view==='error' && $this->errorAction!==null)
Yii::app()->runController($this->errorAction);
else
{
// additional information to be passed to view
$data['version']=$this->getVersionInfo();
$data['time']=time();
$data['admin']=$this->adminInfo;
include($this->getViewFile($view,$data['code']));
}
}
/**
* Determines which view file should be used.
* @param string $view view name (either 'exception' or 'error')
* @param integer $code HTTP status code
* @return string view file path
*/
protected function getViewFile($view,$code)
{
$viewPaths=array(
Yii::app()->getTheme()===null ? null : Yii::app()->getTheme()->getSystemViewPath(),
Yii::app() instanceof CWebApplication ? Yii::app()->getSystemViewPath() : null,
YII_PATH.DIRECTORY_SEPARATOR.'views',
);
foreach($viewPaths as $i=>$viewPath)
{
if($viewPath!==null)
{
$viewFile=$this->getViewFileInternal($viewPath,$view,$code,$i===2?'en_us':null);
if(is_file($viewFile))
return $viewFile;
}
}
}
/**
* Looks for the view under the specified directory.
* @param string $viewPath the directory containing the views
* @param string $view view name (either 'exception' or 'error')
* @param integer $code HTTP status code
* @param string $srcLanguage the language that the view file is in
* @return string view file path
*/
protected function getViewFileInternal($viewPath,$view,$code,$srcLanguage=null)
{
$app=Yii::app();
if($view==='error')
{
$viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR."error{$code}.php",$srcLanguage);
if(!is_file($viewFile))
$viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR.'error.php',$srcLanguage);
}
else
$viewFile=$viewPath.DIRECTORY_SEPARATOR."exception.php";
return $viewFile;
}
/**
* Returns server version information.
* If the application is in production mode, empty string is returned.
* @return string server version information. Empty if in production mode.
*/
protected function getVersionInfo()
{
if(YII_DEBUG)
{
$version='<a href="http://www.yiiframework.com/">Yii Framework</a>/'.Yii::getVersion();
if(isset($_SERVER['SERVER_SOFTWARE']))
$version=$_SERVER['SERVER_SOFTWARE'].' '.$version;
}
else
$version='';
return $version;
}
/**
* Converts arguments array to its string representation
*
* @param array $args arguments array to be converted
* @return string string representation of the arguments array
*/
protected function argumentsToString($args)
{
$count=0;
$isAssoc=$args!==array_values($args);
foreach($args as $key => $value)
{
$count++;
if($count>=5)
{
if($count>5)
unset($args[$key]);
else
$args[$key]='...';
continue;
}
if(is_object($value))
$args[$key] = get_class($value);
else if(is_bool($value))
$args[$key] = $value ? 'true' : 'false';
else if(is_string($value))
{
if(strlen($value)>64)
$args[$key] = '"'.substr($value,0,64).'..."';
else
$args[$key] = '"'.$value.'"';
}
else if(is_array($value))
$args[$key] = 'array('.$this->argumentsToString($value).')';
else if($value===null)
$args[$key] = 'null';
else if(is_resource($value))
$args[$key] = 'resource';
if(is_string($key))
{
$args[$key] = '"'.$key.'" => '.$args[$key];
}
else if($isAssoc)
{
$args[$key] = $key.' => '.$args[$key];
}
}
$out = implode(", ", $args);
return $out;
}
/**
* Returns a value indicating whether the call stack is from application code.
* @param array $trace the trace data
* @return boolean whether the call stack is from application code.
*/
protected function isCoreCode($trace)
{
if(isset($trace['file']))
{
$systemPath=realpath(dirname(__FILE__).'/..');
return $trace['file']==='unknown' || strpos(realpath($trace['file']),$systemPath.DIRECTORY_SEPARATOR)===0;
}
return false;
}
/**
* Renders the source code around the error line.
* @param string $file source file path
* @param integer $errorLine the error line number
* @param integer $maxLines maximum number of lines to display
* @return string the rendering result
*/
protected function renderSourceCode($file,$errorLine,$maxLines)
{
$errorLine--; // adjust line number to 0-based from 1-based
if($errorLine<0 || ($lines=@file($file))===false || ($lineCount=count($lines))<=$errorLine)
return '';
$halfLines=(int)($maxLines/2);
$beginLine=$errorLine-$halfLines>0 ? $errorLine-$halfLines:0;
$endLine=$errorLine+$halfLines<$lineCount?$errorLine+$halfLines:$lineCount-1;
$lineNumberWidth=strlen($endLine+1);
$output='';
for($i=$beginLine;$i<=$endLine;++$i)
{
$isErrorLine = $i===$errorLine;
$code=sprintf("<span class=\"ln".($isErrorLine?' error-ln':'')."\">%0{$lineNumberWidth}d</span> %s",$i+1,CHtml::encode(str_replace("\t",' ',$lines[$i])));
if(!$isErrorLine)
$output.=$code;
else
$output.='<span class="error">'.$code.'</span>';
}
return '<div class="code"><pre>'.$output.'</pre></div>';
}
}

40
framework/base/HttpException.php

@ -0,0 +1,40 @@
<?php
/**
* HttpException class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* HttpException represents an exception caused by an improper request of the end-user.
*
* HttpException can be differentiated via its [[statusCode]] property value which
* keeps a standard HTTP status code (e.g. 404, 500). Error handlers may use this status code
* to decide how to format the error page.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class HttpException extends Exception
{
/**
* @var integer HTTP status code, such as 403, 404, 500, etc.
*/
public $statusCode;
/**
* Constructor.
* @param integer $status HTTP status code, such as 404, 500, etc.
* @param string $message error message
* @param integer $code error code
*/
public function __construct($status, $message = null, $code = 0)
{
$this->statusCode = $status;
parent::__construct($message, $code);
}
}

2
framework/base/Module.php

@ -393,7 +393,7 @@ abstract class Module extends Component implements Initable
* ) * )
* ~~~ * ~~~
* *
* @param array $components application components (id => component configuration or instances) * @param array $components application components (id => component configuration or instance)
*/ */
public function setComponents($components) public function setComponents($components)
{ {

329
framework/base/SecurityManager.php

@ -0,0 +1,329 @@
<?php
/**
* This file contains classes implementing security manager feature.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2011 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* CSecurityManager provides private keys, hashing and encryption functions.
*
* CSecurityManager is used by Yii components and applications for security-related purpose.
* For example, it is used in cookie validation feature to prevent cookie data
* from being tampered.
*
* CSecurityManager is mainly used to protect data from being tampered and viewed.
* It can generate HMAC and encrypt the data. The private key used to generate HMAC
* is set by {@link setValidationKey ValidationKey}. The key used to encrypt data is
* specified by {@link setEncryptionKey EncryptionKey}. If the above keys are not
* explicitly set, random keys will be generated and used.
*
* To protected data with HMAC, call {@link hashData()}; and to check if the data
* is tampered, call {@link validateData()}, which will return the real data if
* it is not tampered. The algorithm used to generated HMAC is specified by
* {@link validation}.
*
* To encrypt and decrypt data, call {@link encrypt()} and {@link decrypt()}
* respectively, which uses 3DES encryption algorithm. Note, the PHP Mcrypt
* extension must be installed and loaded.
*
* CSecurityManager is a core application component that can be accessed via
* {@link CApplication::getSecurityManager()}.
*
* @property string $validationKey The private key used to generate HMAC.
* If the key is not explicitly set, a random one is generated and returned.
* @property string $encryptionKey The private key used to encrypt/decrypt data.
* If the key is not explicitly set, a random one is generated and returned.
* @property string $validation
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id$
* @package system.base
* @since 1.0
*/
class CSecurityManager extends CApplicationComponent
{
const STATE_VALIDATION_KEY='Yii.CSecurityManager.validationkey';
const STATE_ENCRYPTION_KEY='Yii.CSecurityManager.encryptionkey';
/**
* @var string the name of the hashing algorithm to be used by {@link computeHMAC}.
* See {@link http://php.net/manual/en/function.hash-algos.php hash-algos} for the list of possible
* hash algorithms. Note that if you are using PHP 5.1.1 or below, you can only use 'sha1' or 'md5'.
*
* Defaults to 'sha1', meaning using SHA1 hash algorithm.
* @since 1.1.3
*/
public $hashAlgorithm='sha1';
/**
* @var mixed the name of the crypt algorithm to be used by {@link encrypt} and {@link decrypt}.
* This will be passed as the first parameter to {@link http://php.net/manual/en/function.mcrypt-module-open.php mcrypt_module_open}.
*
* This property can also be configured as an array. In this case, the array elements will be passed in order
* as parameters to mcrypt_module_open. For example, <code>array('rijndael-256', '', 'ofb', '')</code>.
*
* Defaults to 'des', meaning using DES crypt algorithm.
* @since 1.1.3
*/
public $cryptAlgorithm='des';
private $_validationKey;
private $_encryptionKey;
private $_mbstring;
public function init()
{
parent::init();
$this->_mbstring=extension_loaded('mbstring');
}
/**
* @return string a randomly generated private key
*/
protected function generateRandomKey()
{
return sprintf('%08x%08x%08x%08x',mt_rand(),mt_rand(),mt_rand(),mt_rand());
}
/**
* @return string the private key used to generate HMAC.
* If the key is not explicitly set, a random one is generated and returned.
*/
public function getValidationKey()
{
if($this->_validationKey!==null)
return $this->_validationKey;
else
{
if(($key=Yii::app()->getGlobalState(self::STATE_VALIDATION_KEY))!==null)
$this->setValidationKey($key);
else
{
$key=$this->generateRandomKey();
$this->setValidationKey($key);
Yii::app()->setGlobalState(self::STATE_VALIDATION_KEY,$key);
}
return $this->_validationKey;
}
}
/**
* @param string $value the key used to generate HMAC
* @throws CException if the key is empty
*/
public function setValidationKey($value)
{
if(!empty($value))
$this->_validationKey=$value;
else
throw new CException(Yii::t('yii','CSecurityManager.validationKey cannot be empty.'));
}
/**
* @return string the private key used to encrypt/decrypt data.
* If the key is not explicitly set, a random one is generated and returned.
*/
public function getEncryptionKey()
{
if($this->_encryptionKey!==null)
return $this->_encryptionKey;
else
{
if(($key=Yii::app()->getGlobalState(self::STATE_ENCRYPTION_KEY))!==null)
$this->setEncryptionKey($key);
else
{
$key=$this->generateRandomKey();
$this->setEncryptionKey($key);
Yii::app()->setGlobalState(self::STATE_ENCRYPTION_KEY,$key);
}
return $this->_encryptionKey;
}
}
/**
* @param string $value the key used to encrypt/decrypt data.
* @throws CException if the key is empty
*/
public function setEncryptionKey($value)
{
if(!empty($value))
$this->_encryptionKey=$value;
else
throw new CException(Yii::t('yii','CSecurityManager.encryptionKey cannot be empty.'));
}
/**
* This method has been deprecated since version 1.1.3.
* Please use {@link hashAlgorithm} instead.
* @return string
*/
public function getValidation()
{
return $this->hashAlgorithm;
}
/**
* This method has been deprecated since version 1.1.3.
* Please use {@link hashAlgorithm} instead.
* @param string $value -
*/
public function setValidation($value)
{
$this->hashAlgorithm=$value;
}
/**
* Encrypts data.
* @param string $data data to be encrypted.
* @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
* @return string the encrypted data
* @throws CException if PHP Mcrypt extension is not loaded
*/
public function encrypt($data,$key=null)
{
$module=$this->openCryptModule();
$key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,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;
}
/**
* Decrypts data
* @param string $data data to be decrypted.
* @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
* @return string the decrypted data
* @throws CException if PHP Mcrypt extension is not loaded
*/
public function decrypt($data,$key=null)
{
$module=$this->openCryptModule();
$key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
$ivSize=mcrypt_enc_get_iv_size($module);
$iv=$this->substr($data,0,$ivSize);
mcrypt_generic_init($module,$key,$iv);
$decrypted=mdecrypt_generic($module,$this->substr($data,$ivSize,$this->strlen($data)));
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return rtrim($decrypted,"\0");
}
/**
* Opens the mcrypt module with the configuration specified in {@link cryptAlgorithm}.
* @return resource the mycrypt module handle.
* @since 1.1.3
*/
protected function openCryptModule()
{
if(extension_loaded('mcrypt'))
{
if(is_array($this->cryptAlgorithm))
$module=@call_user_func_array('mcrypt_module_open',$this->cryptAlgorithm);
else
$module=@mcrypt_module_open($this->cryptAlgorithm,'', MCRYPT_MODE_CBC,'');
if($module===false)
throw new CException(Yii::t('yii','Failed to initialize the mcrypt module.'));
return $module;
}
else
throw new CException(Yii::t('yii','CSecurityManager requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));
}
/**
* Prefixes data with an HMAC.
* @param string $data data to be hashed.
* @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
* @return string data prefixed with HMAC
*/
public function hashData($data,$key=null)
{
return $this->computeHMAC($data,$key).$data;
}
/**
* Validates if data is tampered.
* @param string $data data to be validated. The data must be previously
* generated using {@link hashData()}.
* @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
* @return string the real data with HMAC stripped off. False if the data
* is tampered.
*/
public function validateData($data,$key=null)
{
$len=$this->strlen($this->computeHMAC('test'));
if($this->strlen($data)>=$len)
{
$hmac=$this->substr($data,0,$len);
$data2=$this->substr($data,$len,$this->strlen($data));
return $hmac===$this->computeHMAC($data2,$key)?$data2:false;
}
else
return false;
}
/**
* Computes the HMAC for the data with {@link getValidationKey ValidationKey}.
* @param string $data data to be generated HMAC
* @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
* @return string the HMAC for the data
*/
protected function computeHMAC($data,$key=null)
{
if($key===null)
$key=$this->getValidationKey();
if(function_exists('hash_hmac'))
return hash_hmac($this->hashAlgorithm, $data, $key);
if(!strcasecmp($this->hashAlgorithm,'sha1'))
{
$pack='H40';
$func='sha1';
}
else
{
$pack='H32';
$func='md5';
}
if($this->strlen($key) > 64)
$key=pack($pack, $func($key));
if($this->strlen($key) < 64)
$key=str_pad($key, 64, chr(0));
$key=$this->substr($key,0,64);
return $func((str_repeat(chr(0x5C), 64) ^ $key) . pack($pack, $func((str_repeat(chr(0x36), 64) ^ $key) . $data)));
}
/**
* Returns the length of the given string.
* If available uses the multibyte string function mb_strlen.
* @param string $string the string being measured for length
* @return int the length of the string
*/
private function strlen($string)
{
return $this->_mbstring ? mb_strlen($string,'8bit') : strlen($string);
}
/**
* Returns the portion of string specified by the start and length parameters.
* If available uses the multibyte string function mb_substr
* @param string $string the input string. Must be one character or longer.
* @param int $start the starting position
* @param int $length the desired portion length
* @return string the extracted part of string, or FALSE on failure or an empty string.
*/
private function substr($string,$start,$length)
{
return $this->_mbstring ? mb_substr($string,$start,$length,'8bit') : substr($string,$start,$length);
}
}

74
framework/base/StatePersister.php

@ -0,0 +1,74 @@
<?php
/**
* StatePersister class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* CStatePersister implements a file-based persistent data storage.
*
* It can be used to keep data available through multiple requests and sessions.
*
* By default, CStatePersister stores data in a file named 'state.bin' that is located
* under the application {@link CApplication::getRuntimePath runtime path}.
* You may change the location by setting the {@link stateFile} property.
*
* To retrieve the data from CStatePersister, call {@link load()}. To save the data,
* call {@link save()}.
*
* Comparison among state persister, session and cache is as follows:
* <ul>
* <li>session: data persisting within a single user session.</li>
* <li>state persister: data persisting through all requests/sessions (e.g. hit counter).</li>
* <li>cache: volatile and fast storage. It may be used as storage medium for session or state persister.</li>
* </ul>
*
* Since server resource is often limited, be cautious if you plan to use CStatePersister
* to store large amount of data. You should also consider using database-based persister
* to improve the throughput.
*
* CStatePersister is a core application component used to store global application state.
* It may be accessed via {@link CApplication::getStatePersister()}.
* page state persistent method based on cache.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class StatePersister extends ApplicationComponent
{
/**
* @var string the file path for keeping the state data. Make sure the directory containing
* the file exists and is writable by the Web server process. If using relative path, also
* make sure the path is correct. You may use a path alias here. If not set, it defaults
* to the `state.bin` file under the application's runtime directory.
*/
public $dataFile;
/**
* Loads state data from persistent storage.
* @return mixed state data. Null if no state data available.
*/
public function load()
{
$dataFile = \Yii::getAlias($this->dataFile);
if (is_file($dataFile) && ($data = file_get_contents($dataFile)) !== false) {
return unserialize($data);
} else {
return null;
}
}
/**
* Saves application state in persistent storage.
* @param mixed $state state data (must be serializable).
*/
public function save($state)
{
file_put_contents(\Yii::getAlias($this->dataFile), serialize($state), LOCK_EX);
}
}

10
framework/db/ar/ActiveFinder.php

@ -245,7 +245,7 @@ class ActiveFinder extends \yii\base\Object
} }
if (is_array($with)) { if (is_array($with)) {
foreach ($with as $name => $value) { foreach ($with as $name => $value) {
if (is_array($value)) { if (is_array($value) || $value instanceof \Closure) {
$this->buildJoinTree($parent, $name, $value); $this->buildJoinTree($parent, $name, $value);
} else { } else {
$this->buildJoinTree($parent, $value); $this->buildJoinTree($parent, $value);
@ -299,8 +299,12 @@ class ActiveFinder extends \yii\base\Object
} }
} }
foreach ($config as $name => $value) { if ($config instanceof \Closure) {
$child->query->$name = $value; call_user_func($config, $child->query);
} else {
foreach ($config as $name => $value) {
$child->query->$name = $value;
}
} }
return $child; return $child;

Loading…
Cancel
Save