Browse Source

...

tags/2.0.0-beta
Qiang Xue 12 years ago
parent
commit
d876da383e
  1. 75
      framework/base/SecurityManager.php
  2. 9
      framework/web/Application.php
  3. 15
      framework/web/Cookie.php
  4. 238
      framework/web/CookieCollection.php
  5. 10
      tests/unit/data/ar/Customer.php
  6. 24
      tests/unit/data/ar/Order.php

75
framework/base/SecurityManager.php

@ -12,38 +12,8 @@ namespace yii\base;
/** /**
* SecurityManager provides private keys, hashing and encryption functions. * SecurityManager provides private keys, hashing and encryption functions.
* *
* SecurityManager 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.
*
* SecurityManager 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.
*
* SecurityManager 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> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id$ * @since 2.0
* @package system.base
* @since 1.0
*/ */
class SecurityManager extends ApplicationComponent class SecurityManager extends ApplicationComponent
{ {
@ -56,7 +26,6 @@ class SecurityManager extends ApplicationComponent
* hash algorithms. Note that if you are using PHP 5.1.1 or below, you can only use 'sha1' or 'md5'. * 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. * Defaults to 'sha1', meaning using SHA1 hash algorithm.
* @since 1.1.3
*/ */
public $hashAlgorithm = 'sha1'; public $hashAlgorithm = 'sha1';
/** /**
@ -67,19 +36,11 @@ class SecurityManager extends ApplicationComponent
* as parameters to mcrypt_module_open. For example, <code>array('rijndael-256', '', 'ofb', '')</code>. * as parameters to mcrypt_module_open. For example, <code>array('rijndael-256', '', 'ofb', '')</code>.
* *
* Defaults to 'des', meaning using DES crypt algorithm. * Defaults to 'des', meaning using DES crypt algorithm.
* @since 1.1.3
*/ */
public $cryptAlgorithm = 'des'; public $cryptAlgorithm = 'des';
private $_validationKey; private $_validationKey;
private $_encryptionKey; private $_encryptionKey;
private $_mbstring;
public function init()
{
parent::init();
$this->_mbstring = extension_loaded('mbstring');
}
/** /**
* @return string a randomly generated private key * @return string a randomly generated private key
@ -97,12 +58,10 @@ class SecurityManager extends ApplicationComponent
{ {
if ($this->_validationKey !== null) { if ($this->_validationKey !== null) {
return $this->_validationKey; return $this->_validationKey;
} } else {
else {
if (($key = \Yii::$application->getGlobalState(self::STATE_VALIDATION_KEY)) !== null) { if (($key = \Yii::$application->getGlobalState(self::STATE_VALIDATION_KEY)) !== null) {
$this->setValidationKey($key); $this->setValidationKey($key);
} } else {
else {
$key = $this->generateRandomKey(); $key = $this->generateRandomKey();
$this->setValidationKey($key); $this->setValidationKey($key);
\Yii::$application->setGlobalState(self::STATE_VALIDATION_KEY, $key); \Yii::$application->setGlobalState(self::STATE_VALIDATION_KEY, $key);
@ -119,8 +78,7 @@ class SecurityManager extends ApplicationComponent
{ {
if (!empty($value)) { if (!empty($value)) {
$this->_validationKey = $value; $this->_validationKey = $value;
} } else {
else {
throw new CException(Yii::t('yii', 'SecurityManager.validationKey cannot be empty.')); throw new CException(Yii::t('yii', 'SecurityManager.validationKey cannot be empty.'));
} }
} }
@ -133,12 +91,10 @@ class SecurityManager extends ApplicationComponent
{ {
if ($this->_encryptionKey !== null) { if ($this->_encryptionKey !== null) {
return $this->_encryptionKey; return $this->_encryptionKey;
} } else {
else {
if (($key = \Yii::$application->getGlobalState(self::STATE_ENCRYPTION_KEY)) !== null) { if (($key = \Yii::$application->getGlobalState(self::STATE_ENCRYPTION_KEY)) !== null) {
$this->setEncryptionKey($key); $this->setEncryptionKey($key);
} } else {
else {
$key = $this->generateRandomKey(); $key = $this->generateRandomKey();
$this->setEncryptionKey($key); $this->setEncryptionKey($key);
\Yii::$application->setGlobalState(self::STATE_ENCRYPTION_KEY, $key); \Yii::$application->setGlobalState(self::STATE_ENCRYPTION_KEY, $key);
@ -155,8 +111,7 @@ class SecurityManager extends ApplicationComponent
{ {
if (!empty($value)) { if (!empty($value)) {
$this->_encryptionKey = $value; $this->_encryptionKey = $value;
} } else {
else {
throw new CException(Yii::t('yii', 'SecurityManager.encryptionKey cannot be empty.')); throw new CException(Yii::t('yii', 'SecurityManager.encryptionKey cannot be empty.'));
} }
} }
@ -231,8 +186,7 @@ class SecurityManager extends ApplicationComponent
if (extension_loaded('mcrypt')) { if (extension_loaded('mcrypt')) {
if (is_array($this->cryptAlgorithm)) { if (is_array($this->cryptAlgorithm)) {
$module = @call_user_func_array('mcrypt_module_open', $this->cryptAlgorithm); $module = @call_user_func_array('mcrypt_module_open', $this->cryptAlgorithm);
} } else {
else {
$module = @mcrypt_module_open($this->cryptAlgorithm, '', MCRYPT_MODE_CBC, ''); $module = @mcrypt_module_open($this->cryptAlgorithm, '', MCRYPT_MODE_CBC, '');
} }
@ -241,8 +195,7 @@ class SecurityManager extends ApplicationComponent
} }
return $module; return $module;
} } else {
else {
throw new CException(Yii::t('yii', 'SecurityManager requires PHP mcrypt extension to be loaded in order to use data encryption feature.')); throw new CException(Yii::t('yii', 'SecurityManager requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));
} }
} }
@ -273,8 +226,7 @@ class SecurityManager extends ApplicationComponent
$hmac = $this->substr($data, 0, $len); $hmac = $this->substr($data, 0, $len);
$data2 = $this->substr($data, $len, $this->strlen($data)); $data2 = $this->substr($data, $len, $this->strlen($data));
return $hmac === $this->computeHMAC($data2, $key) ? $data2 : false; return $hmac === $this->computeHMAC($data2, $key) ? $data2 : false;
} } else {
else {
return false; return false;
} }
} }
@ -298,8 +250,7 @@ class SecurityManager extends ApplicationComponent
if (!strcasecmp($this->hashAlgorithm, 'sha1')) { if (!strcasecmp($this->hashAlgorithm, 'sha1')) {
$pack = 'H40'; $pack = 'H40';
$func = 'sha1'; $func = 'sha1';
} } else {
else {
$pack = 'H32'; $pack = 'H32';
$func = 'md5'; $func = 'md5';
} }
@ -321,7 +272,7 @@ class SecurityManager extends ApplicationComponent
*/ */
private function strlen($string) private function strlen($string)
{ {
return $this->_mbstring ? mb_strlen($string, '8bit') : strlen($string); return function_exists('mb_strlen') ? mb_strlen($string, '8bit') : strlen($string);
} }
/** /**
@ -334,6 +285,6 @@ class SecurityManager extends ApplicationComponent
*/ */
private function substr($string, $start, $length) private function substr($string, $start, $length)
{ {
return $this->_mbstring ? mb_substr($string, $start, $length, '8bit') : substr($string, $start, $length); return function_exists('mb_substr') ? mb_substr($string, $start, $length, '8bit') : substr($string, $start, $length);
} }
} }

9
framework/web/Application.php

@ -18,6 +18,15 @@ namespace yii\web;
class Application extends \yii\base\Application class Application extends \yii\base\Application
{ {
/** /**
* Sets default path aliases.
*/
public function registerDefaultAliases()
{
parent::registerDefaultAliases();
\Yii::$aliases['@www'] = dirname($_SERVER['SCRIPT_FILENAME']);
}
/**
* Processes the request. * Processes the request.
* @return integer the exit status of the controller action (0 means normal, non-zero values mean abnormal) * @return integer the exit status of the controller action (0 means normal, non-zero values mean abnormal)
*/ */

15
framework/web/Cookie.php

@ -7,6 +7,8 @@
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\web;
/** /**
* Cookie represents information related with a cookie, such as [[name]], [[value]], [[domain]], etc. * Cookie represents information related with a cookie, such as [[name]], [[value]], [[domain]], etc.
* *
@ -46,17 +48,4 @@ class Cookie extends \yii\base\Object
* such as JavaScript, which can effectively help to reduce identity theft through XSS attacks. * such as JavaScript, which can effectively help to reduce identity theft through XSS attacks.
*/ */
public $httpOnly = false; public $httpOnly = false;
/**
* Constructor.
* @param string $name name of this cookie
* @param string $value value of this cookie
* @param array $config name-value pairs that will be used to initialize the object properties
*/
public function __construct($name, $value, $config = array())
{
$this->name = $name;
$this->value = $value;
parent::__construct($config);
}
} }

238
framework/web/CookieCollection.php

@ -0,0 +1,238 @@
<?php
/**
* Dictionary class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\web;
use yii\base\DictionaryIterator;
/**
* Dictionary implements a collection that stores key-value pairs.
*
* You can access, add or remove an item with a key by using
* [[itemAt()]], [[add()]], and [[remove()]].
*
* To get the number of the items in the dictionary, use [[getCount()]].
*
* Because Dictionary implements a set of SPL interfaces, it can be used
* like a regular PHP array as follows,
*
* ~~~
* $dictionary[$key] = $value; // add a key-value pair
* unset($dictionary[$key]); // remove the value with the specified key
* if (isset($dictionary[$key])) // if the dictionary contains the key
* foreach ($dictionary as $key=>$value) // traverse the items in the dictionary
* $n = count($dictionary); // returns the number of items in the dictionary
* ~~~
*
* @property integer $count the number of items in the dictionary
* @property array $keys The keys in the dictionary
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \ArrayAccess, \Countable
{
/**
* @var Cookie[] internal data storage
*/
private $_cookies = array();
/**
* Constructor.
* Initializes the dictionary with an array or an iterable object.
* @param array $cookies the initial data to be populated into the dictionary.
* This can be an array or an iterable object.
* @param array $config name-value pairs that will be used to initialize the object properties
*/
public function __construct($cookies = array(), $config = array())
{
$this->_cookies = $cookies;
parent::__construct($config);
}
/**
* Returns an iterator for traversing the items in the dictionary.
* This method is required by the SPL interface `IteratorAggregate`.
* It will be implicitly called when you use `foreach` to traverse the dictionary.
* @return DictionaryIterator an iterator for traversing the items in the dictionary.
*/
public function getIterator()
{
return new DictionaryIterator($this->_cookies);
}
/**
* Returns the number of items in the dictionary.
* This method is required by the SPL `Countable` interface.
* It will be implicitly called when you use `count($dictionary)`.
* @return integer number of items in the dictionary.
*/
public function count()
{
return $this->getCount();
}
/**
* Returns the number of items in the dictionary.
* @return integer the number of items in the dictionary
*/
public function getCount()
{
return count($this->_cookies);
}
/**
* Returns the keys stored in the dictionary.
* @return array the key list
*/
public function getNames()
{
return array_keys($this->_cookies);
}
/**
* Returns the item with the specified key.
* @param mixed $name the key
* @return Cookie the element with the specified key.
* Null if the key cannot be found in the dictionary.
*/
public function getCookie($name)
{
return isset($this->_cookies[$name]) ? $this->_cookies[$name] : null;
}
/**
* Adds an item into the dictionary.
* Note, if the specified key already exists, the old value will be overwritten.
* @param Cookie $cookie value
* @throws Exception if the dictionary is read-only
*/
public function add(Cookie $cookie)
{
if (isset($this->_cookies[$cookie->name])) {
$this->remove($this->_cookies[$cookie->name]);
}
setcookie($cookie->name, $cookie->value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
$this->_cookies[$cookie->name] = $cookie;
}
/**
* Removes an item from the dictionary by its key.
* @param mixed $key the key of the item to be removed
* @return mixed the removed value, null if no such key exists.
* @throws Exception if the dictionary is read-only
*/
public function remove(Cookie $cookie)
{
setcookie($cookie->name, '', 0, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
unset($this->_cookies[$cookie->name]);
}
/**
* Removes all items from the dictionary.
* @param boolean $safeClear whether to clear every item by calling [[remove]].
* Defaults to false, meaning all items in the dictionary will be cleared directly
* without calling [[remove]].
*/
public function clear($safeClear = false)
{
if ($safeClear) {
foreach (array_keys($this->_cookies) as $key) {
$this->remove($key);
}
} else {
$this->_cookies = array();
}
}
/**
* Returns the dictionary as a PHP array.
* @return array the list of items in array
*/
public function toArray()
{
return $this->_cookies;
}
/**
* Returns whether there is an element at the specified offset.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `isset($dictionary[$offset])`.
* This is equivalent to [[contains]].
* @param mixed $offset the offset to check on
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->_cookies[$offset]);
}
/**
* Returns the element at the specified offset.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `$value = $dictionary[$offset];`.
* This is equivalent to [[itemAt]].
* @param mixed $offset the offset to retrieve element.
* @return mixed the element at the offset, null if no element is found at the offset
*/
public function offsetGet($offset)
{
return $this->getCookie($offset);
}
/**
* Sets the element at the specified offset.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `$dictionary[$offset] = $item;`.
* If the offset is null, the new item will be appended to the dictionary.
* Otherwise, the existing item at the offset will be replaced with the new item.
* This is equivalent to [[add]].
* @param mixed $offset the offset to set element
* @param mixed $item the element value
*/
public function offsetSet($offset, $item)
{
$this->add($item);
}
/**
* Unsets the element at the specified offset.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `unset($dictionary[$offset])`.
* This is equivalent to [[remove]].
* @param mixed $offset the offset to unset element
*/
public function offsetUnset($offset)
{
if (isset($this->_cookies[$offset])) {
$this->remove($this->_cookies[$offset]);
}
}
/**
* @return array list of validated cookies
*/
protected function loadCookies($data)
{
$cookies = array();
if ($this->_request->enableCookieValidation) {
$sm = Yii::app()->getSecurityManager();
foreach ($_COOKIE as $name => $value) {
if (is_string($value) && ($value = $sm->validateData($value)) !== false) {
$cookies[$name] = new CHttpCookie($name, @unserialize($value));
}
}
} else {
foreach ($_COOKIE as $name => $value) {
$cookies[$name] = new CHttpCookie($name, $value);
}
}
return $cookies;
}
}

10
tests/unit/data/ar/Customer.php

@ -1,6 +1,7 @@
<?php <?php
namespace yiiunit\data\ar; namespace yiiunit\data\ar;
use yii\db\ar\ActiveQuery;
class Customer extends ActiveRecord class Customer extends ActiveRecord
{ {
@ -21,6 +22,15 @@ class Customer extends ActiveRecord
); );
} }
public function orders()
{
return $this->hasMany('Order', array('id' => 'customer_id'));
}
/**
* @param ActiveQuery $query
* @return ActiveQuery
*/
public function active($query) public function active($query)
{ {
return $query->andWhere('@.`status` = ' . self::STATUS_ACTIVE); return $query->andWhere('@.`status` = ' . self::STATUS_ACTIVE);

24
tests/unit/data/ar/Order.php

@ -40,4 +40,28 @@ class Order extends ActiveRecord
), ),
); );
} }
public function customer()
{
return $this->hasOne('Customer', array('id' => 'customer_id'));
}
public function orderItems()
{
return $this->hasMany('OrderItem', array('order_id' => 'id'));
}
public function items()
{
return $this->hasMany('Item')
->via('orderItems', array('item_id' => 'id'))
->order('@.id');
}
public function books()
{
return $this->hasMany('Item')
->pivot('tbl_order_item', array('order_id' => 'id'), array('item_id' => 'id'))
->on('@.category_id = 1');
}
} }
Loading…
Cancel
Save