Commit c4b04b78 by Qiang Xue

Merge branch 'master' of https://github.com/yiisoft/yii2

parents b19f640b 034d88e5
language: php
php:
- 5.3
- 5.4
- 5.5
env:
- DB=mysql
before_script:
- sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'create database IF NOT EXISTS yiitest;'; fi"
script: phpunit
\ No newline at end of file
......@@ -2,7 +2,7 @@
defined('YII_DEBUG') or define('YII_DEBUG', true);
require(__DIR__ . '/../framework/yii.php');
require(__DIR__ . '/../../framework/yii.php');
$config = require(__DIR__ . '/protected/config/main.php');
$application = new yii\web\Application($config);
......
......@@ -16,4 +16,4 @@ return array(
'yii',
),
),
);
\ No newline at end of file
);
......@@ -18,4 +18,4 @@ return array(
'params' => array(
'adminEmail' => 'admin@example.com',
),
);
\ No newline at end of file
);
......@@ -46,4 +46,4 @@ class SiteController extends Controller
{
echo $this->render('about');
}
}
\ No newline at end of file
}
......@@ -60,4 +60,4 @@ class ContactForm extends Model
return false;
}
}
}
\ No newline at end of file
}
......@@ -55,4 +55,4 @@ class LoginForm extends Model
return false;
}
}
}
\ No newline at end of file
}
......@@ -58,4 +58,4 @@ class User extends \yii\base\Object implements \yii\web\Identity
{
return $this->password === $password;
}
}
\ No newline at end of file
}
......@@ -54,4 +54,4 @@ $this->registerAssetBundle('app');
</div>
</body>
</html>
<?php $this->endPage(); ?>
\ No newline at end of file
<?php $this->endPage(); ?>
......@@ -30,4 +30,4 @@ $this->title = 'Contact';
<div class="form-actions">
<?php echo Html::submitButton('Submit', null, null, array('class' => 'btn btn-primary')); ?>
</div>
<?php $this->endWidget(); ?>
\ No newline at end of file
<?php $this->endWidget(); ?>
......@@ -18,4 +18,4 @@ $this->title = 'Login';
<div class="form-actions">
<?php echo Html::submitButton('Login', null, null, array('class' => 'btn btn-primary')); ?>
</div>
<?php $this->endWidget(); ?>
\ No newline at end of file
<?php $this->endWidget(); ?>
......@@ -16,5 +16,5 @@ require(__DIR__ . '/../framework/yii.php');
$id = 'yiic-build';
$basePath = __DIR__;
$application = new yii\console\Application($id, $basePath);
$application = new yii\console\Application(array('id' => $id, 'basePath' => $basePath));
$application->run();
......@@ -412,7 +412,7 @@ class Customer extends \yii\db\ActiveRecord
/**
* @param ActiveQuery $query
*/
public function active($query)
public static function active($query)
{
$query->andWhere('status = 1');
}
......@@ -435,7 +435,7 @@ class Customer extends \yii\db\ActiveRecord
* @param ActiveQuery $query
* @param integer $age
*/
public function olderThan($query, $age = 30)
public static function olderThan($query, $age = 30)
{
$query->andWhere('age > :age', array(':age' => $age));
}
......
......@@ -7,7 +7,7 @@ If you have installed Yii under a Web-accessible folder, you should be able to
access this application through the following URL:
~~~
http://localhost/yii/app/index.php
http://localhost/yii/apps/bootstrap/index.php
~~~
......
Error Handling
==============
......@@ -25,8 +25,8 @@ http://hostname/path/to/yii/requirements/index.php
~~~
Yii requires PHP 5.3, so the server must have PHP 5.3 or above installed and
available to the web server. Yii has been tested with [Apache HTTP server](http://httpd.apache.org/)
on Windows and Linux. It may also run on other Web servers and platforms,
available to the web server. Yii has been tested with [Apache HTTP server](http://httpd.apache.org/)
on Windows and Linux. It may also run on other Web servers and platforms,
provided PHP 5.3 is supported.
......@@ -34,7 +34,7 @@ Recommended Apache Configuration
--------------------------------
Yii is ready to work with a default Apache web server configuration.
The `.htaccess` files in Yii framework and application folders restrict
The `.htaccess` files in Yii framework and application folders deny
access to the restricted resources. To hide the bootstrap file (usually `index.php`)
in your URLs you can add `mod_rewrite` instructions to the `.htaccess` file
in your document root or to the virtual host configuration:
......@@ -63,7 +63,7 @@ server {
access_log /www/mysite/log/access.log main;
server_name mysite;
root $host_path/htdocs;
root $host_path/htdocs;
set $yii_bootstrap "index.php";
charset utf-8;
......@@ -108,4 +108,5 @@ server {
}
~~~
Using this configuration you can set `cgi.fix_pathinfo=0` in php.ini to avoid many unnecessary system stat() calls.
Using this configuration you can set `cgi.fix_pathinfo=0` in php.ini to avoid
many unnecessary system `stat()` calls.
......@@ -11,7 +11,7 @@ the communication between the model and the view.
Besides implementing MVC, Yii also introduces a front-controller, called
`Application`, which encapsulates the execution context for the processing
of a request. Application collects some information about a user request and
of a request. Application collects information about a user request and
then dispatches it to an appropriate controller for further handling.
The following diagram shows the static structure of a Yii application:
......@@ -21,6 +21,7 @@ The following diagram shows the static structure of a Yii application:
A Typical Workflow
------------------
The following diagram shows a typical workflow of a Yii application when
it is handling a user request:
......
Performance Tuning
==================
Application performance consists of two parts. First is the framework performance
and the second is the application itself. Yii has a pretty low performance impact
on your application out of the box and can be fine-tuned further for production
environment. As for the application, we'll provide some of the best practices
along with examples on how to apply them to Yii.
Preparing framework for production
----------------------------------
### Disabling Debug Mode
First thing you should do before deploying your application to production environment
is to disable debug mode. A Yii application runs in debug mode if the constant
`YII_DEBUG` is defined as `true` in `index.php` so to disable debug the following
should be in your `index.php`:
```php
defined('YII_DEBUG') or define('YII_DEBUG', false);
```
Debug mode is very useful during development stage, but it would impact performance
because some components cause extra burden in debug mode. For example, the message
logger may record additional debug information for every message being logged.
### Enabling PHP opcode cache
Enabling the PHP opcode cache improves any PHP application performance and lowers
memory usage significantly. Yii is no exception. It was tested with
[APC PHP extension](http://php.net/manual/en/book.apc.php) that caches
and optimizes PHP intermediate code and avoids the time spent in parsing PHP
scripts for every incoming request.
### Turning on ActiveRecord database schema caching
If the application is using Active Record, we should turn on the schema caching
to save the time of parsing database schema. This can be done by setting the
`Connection::enableSchemaCache` property to be `true` via application configuration
`protected/config/main.php`:
```php
return array(
// ...
'components' => array(
// ...
'db' => array(
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydatabase',
'username' => 'root',
'password' => '',
'enableSchemaCache' => true,
// Duration of schema cache.
// 'schemaCacheDuration' => 3600,
// Name of the cache component used. Default is 'cache'.
//'schemaCache' => 'cache',
),
'cache' => array(
'class' => 'yii\caching\FileCache',
),
),
);
```
Note that `cache` application component should be configured.
### Combining and Minimizing Assets
TBD
### Using better storage for sessions
By default PHP uses files to handle sessions. It is OK for development and
small projects but when it comes to handling concurrent requests it's better to
switch to another storage such as database. You can do so by configuring your
application via `protected/config/main.php`:
```php
return array(
// ...
'components' => array(
'session' => array(
'class' => 'yii\web\DbSession',
// Set the following if want to use DB component other than
// default 'db'.
// 'db' => 'mydb',
// To override default session table set the following
// 'sessionTable' => 'my_session',
),
),
);
```
You can use `CacheSession` to store sessions using cache. Note that some
cache storages such as memcached has no guaranteee that session data will not
be lost leading to unexpected logouts.
Improving application
---------------------
### Using Serverside Caching Techniques
As described in the Caching section, Yii provides several caching solutions that
may improve the performance of a Web application significantly. If the generation
of some data takes long time, we can use the data caching approach to reduce the
data generation frequency; If a portion of page remains relatively static, we
can use the fragment caching approach to reduce its rendering frequency;
If a whole page remains relative static, we can use the page caching approach to
save the rendering cost for the whole page.
### Leveraging HTTP to save procesing time and bandwidth
TBD
### Database Optimization
Fetching data from database is often the main performance bottleneck in
a Web application. Although using caching may alleviate the performance hit,
it does not fully solve the problem. When the database contains enormous data
and the cached data is invalid, fetching the latest data could be prohibitively
expensive without proper database and query design.
Design index wisely in a database. Indexing can make SELECT queries much faster,
but it may slow down INSERT, UPDATE or DELETE queries.
For complex queries, it is recommended to create a database view for it instead
of issuing the queries inside the PHP code and asking DBMS to parse them repetitively.
Do not overuse Active Record. Although Active Record is good at modelling data
in an OOP fashion, it actually degrades performance due to the fact that it needs
to create one or several objects to represent each row of query result. For data
intensive applications, using DAO or database APIs at lower level could be
a better choice.
Last but not least, use LIMIT in your SELECT queries. This avoids fetching
overwhelming data from database and exhausting the memory allocated to PHP.
### Using asArray
A good way to save memory and processing time on read-only pages is to use
ActiveRecord's `asArray` method.
```php
class PostController extends Controller
{
public function actionIndex()
{
$posts = Post::find()->orderBy('id DESC')->limit(100)->asArray()->all();
echo $this->render('index', array(
'posts' => $posts,
));
}
}
```
In the view you should access fields of each invidual record from `$posts` as array:
```php
foreach($posts as $post) {
echo $post['title']."<br>";
}
```
Note that you can use array notation even if `asArray` wasn't specified and you're
working with AR objects.
### Processing data in background
In order to respond to user requests faster you can process heavy parts of the
request later if there's no need for immediate response.
- Cron jobs + console.
- queues + handlers.
TBD
\ No newline at end of file
Template
========
URL Management
==============
......@@ -27,6 +27,9 @@ array(
)
```
Note that Smarty and Twig are not bundled with Yii and you have to download and
unpack these yourself and then specify `twigPath` and `smartyPath` respectively.
Twig
----
......
......@@ -600,6 +600,13 @@ class YiiBase
*/
public static function t($message, $params = array(), $language = null)
{
return self::$app->getI18N()->translate($message, $params, $language);
if (self::$app !== null) {
return self::$app->getI18N()->translate($message, $params, $language);
} else {
if (strpos($message, '|') !== false && preg_match('/^([\w\-\\/\.\\\\]+)\|(.*)/', $message, $matches)) {
$message = $matches[2];
}
return is_array($params) ? strtr($message, $params) : $message;
}
}
}
......@@ -28,4 +28,4 @@ return array(
),
'depends' => array('yii', 'yii/validation'),
),
);
\ No newline at end of file
);
......@@ -87,4 +87,4 @@ class ActionFilter extends Behavior
{
return !in_array($action->id, $this->except, true) && (empty($this->only) || in_array($action->id, $this->only, true));
}
}
\ No newline at end of file
}
......@@ -306,6 +306,15 @@ class Application extends Module
}
/**
* @return null|Component
* @todo
*/
public function getAuthManager()
{
return $this->getComponent('auth');
}
/**
* Registers the core application components.
* @see setComponents
*/
......
......@@ -496,6 +496,7 @@ class Component extends Object
*/
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
......@@ -511,6 +512,7 @@ class Component extends Object
*/
public function detachBehaviors()
{
$this->ensureBehaviors();
if ($this->_behaviors !== null) {
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
......
......@@ -22,4 +22,4 @@ class Exception extends \Exception
{
return \Yii::t('yii|Exception');
}
}
\ No newline at end of file
}
......@@ -744,10 +744,10 @@ class View extends Component
{
$lines = array();
if (!empty($this->metaTags)) {
$lines[] = implode("\n", $this->cssFiles);
$lines[] = implode("\n", $this->metaTags);
}
if (!empty($this->linkTags)) {
$lines[] = implode("\n", $this->cssFiles);
$lines[] = implode("\n", $this->linkTags);
}
if (!empty($this->cssFiles)) {
$lines[] = implode("\n", $this->cssFiles);
......@@ -797,4 +797,4 @@ class View extends Component
}
return implode("\n", $lines);
}
}
\ No newline at end of file
}
......@@ -41,4 +41,4 @@ class ViewEvent extends Event
$this->viewFile = $viewFile;
parent::__construct($config);
}
}
\ No newline at end of file
}
......@@ -83,7 +83,8 @@ class Widget extends Component
*/
public function render($view, $params = array())
{
return $this->view->render($view, $params, $this);
$viewFile = $this->findViewFile($view);
return $this->view->renderFile($viewFile, $params, $this);
}
/**
......@@ -133,4 +134,4 @@ class Widget extends Component
return pathinfo($file, PATHINFO_EXTENSION) === '' ? $file . '.php' : $file;
}
}
\ No newline at end of file
}
......@@ -349,4 +349,4 @@ abstract class Cache extends Component implements \ArrayAccess
{
$this->delete($key);
}
}
\ No newline at end of file
}
......@@ -49,4 +49,4 @@ abstract class Dependency extends \yii\base\Object
* @return mixed the data needed to determine if dependency has been changed.
*/
abstract protected function generateDependencyData();
}
\ No newline at end of file
}
......@@ -46,4 +46,4 @@ class MemCacheServer extends \yii\base\Object
* @var boolean if the server should be flagged as online upon a failure. This is used by memcache only.
*/
public $status = true;
}
\ No newline at end of file
}
......@@ -89,4 +89,4 @@ class WinCache extends Cache
{
return wincache_ucache_clear();
}
}
\ No newline at end of file
}
......@@ -147,4 +147,4 @@ class Controller extends \yii\base\Controller
{
return array();
}
}
\ No newline at end of file
}
......@@ -321,4 +321,4 @@ class AppController extends Controller
closedir($handle);
return $list;
}
}
\ No newline at end of file
}
......@@ -350,4 +350,4 @@ return array(
EOD;
file_put_contents($configFile, $template);
}
}
\ No newline at end of file
}
......@@ -418,4 +418,4 @@ class HelpController extends Controller
$name = $required ? "$name (required)" : $name;
return $doc === '' ? $name : "$name: $doc";
}
}
\ No newline at end of file
}
<?php
/** @var $controller \yii\console\controllers\AppController */
$controller = $this;
return array(
'default' => array(
'index.php' => array(
'handler' => function($source) use ($controller) {
return $controller->replaceRelativePath($source, realpath(YII_PATH.'/yii.php'), 'yii');
},
'permissions' => 0777,
),
'protected/runtime' => array(
'permissions' => 0755,
),
),
);
\ No newline at end of file
<?php
define('YII_DEBUG', true);
require __DIR__.'/../framework/yii.php';
$config = require dirname(__DIR__).'/protected/config/main.php';
$config['basePath'] = dirname(__DIR__).'/protected';
$app = new \yii\web\Application($config);
$app->run();
\ No newline at end of file
<?php
return array(
'id' => 'webapp',
'name' => 'My Web Application',
'components' => array(
// uncomment the following to use a MySQL database
/*
'db' => array(
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdrive',
'username' => 'root',
'password' => '',
),
*/
'cache' => array(
'class' => 'yii\caching\DummyCache',
),
),
);
\ No newline at end of file
<?php
use \yii\web\Controller;
/**
* SiteController
*/
class SiteController extends Controller
{
public function actionIndex()
{
echo $this->render('index', array(
'name' => 'Qiang',
));
}
}
\ No newline at end of file
<?php use yii\helpers\Html as Html; ?>
<!doctype html>
<html lang="<?php \Yii::$app->language?>">
<head>
<meta charset="utf-8" />
<title><?php echo Html::encode($this->title)?></title>
</head>
<body>
<h1><?php echo Html::encode($this->title)?></h1>
<div class="content">
<?php echo $content?>
</div>
<div class="footer">
<?php echo \Yii::powered()?>
</div>
</body>
</html>
\ No newline at end of file
Hello, <?php echo $name?>!
\ No newline at end of file
......@@ -88,7 +88,8 @@ class ActiveQuery extends Query
{
if (method_exists($this->modelClass, $name)) {
array_unshift($params, $this);
return call_user_func_array(array($this->modelClass, $name), $params);
call_user_func_array(array($this->modelClass, $name), $params);
return $this;
} else {
return parent::__call($name, $params);
}
......
......@@ -266,7 +266,7 @@ class ActiveRelation extends ActiveQuery
{
$attributes = array_keys($this->link);
$values = array();
if (count($attributes) ===1) {
if (count($attributes) === 1) {
// single key
$attribute = reset($this->link);
foreach ($models as $model) {
......
......@@ -66,7 +66,7 @@ use yii\caching\Cache;
* // ... executing other SQL statements ...
* $transaction->commit();
* } catch(Exception $e) {
* $transaction->rollBack();
* $transaction->rollback();
* }
* ~~~
*
......@@ -517,7 +517,7 @@ class Connection extends Component
public function quoteSql($sql)
{
$db = $this;
return preg_replace_callback('/(\\{\\{([\w\-\. ]+)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
return preg_replace_callback('/(\\{\\{([%\w\-\. ]+)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
function($matches) use($db) {
if (isset($matches[3])) {
return $db->quoteColumnName($matches[3]);
......
......@@ -41,4 +41,4 @@ class Exception extends \yii\base\Exception
{
return \Yii::t('yii|Database Exception');
}
}
\ No newline at end of file
}
......@@ -57,4 +57,4 @@ class Expression extends \yii\base\Object
{
return $this->expression;
}
}
\ No newline at end of file
}
......@@ -64,14 +64,14 @@ class Migration extends \yii\base\Component
$transaction = $this->db->beginTransaction();
try {
if ($this->safeUp() === false) {
$transaction->rollBack();
$transaction->rollback();
return false;
}
$transaction->commit();
} catch (\Exception $e) {
echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
echo $e->getTraceAsString() . "\n";
$transaction->rollBack();
$transaction->rollback();
return false;
}
return null;
......@@ -89,14 +89,14 @@ class Migration extends \yii\base\Component
$transaction = $this->db->beginTransaction();
try {
if ($this->safeDown() === false) {
$transaction->rollBack();
$transaction->rollback();
return false;
}
$transaction->commit();
} catch (\Exception $e) {
echo "Exception: " . $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ")\n";
echo $e->getTraceAsString() . "\n";
$transaction->rollBack();
$transaction->rollback();
return false;
}
return null;
......@@ -368,4 +368,4 @@ class Migration extends \yii\base\Component
$this->db->createCommand()->dropIndex($name, $table)->execute();
echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n";
}
}
\ No newline at end of file
}
......@@ -483,7 +483,7 @@ class Query extends \yii\base\Component
* Sets the ORDER BY part of the query.
* @param string|array $columns the columns (and the directions) to be ordered by.
* Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array
* (e.g. `array('id' => Query::SORT_ASC ASC, 'name' => Query::SORT_DESC)`).
* (e.g. `array('id' => Query::SORT_ASC, 'name' => Query::SORT_DESC)`).
* The method will automatically quote the column names unless a column contains some parenthesis
* (which means the column contains a DB expression).
* @return Query the query object itself
......@@ -499,7 +499,7 @@ class Query extends \yii\base\Component
* Adds additional ORDER BY columns to the query.
* @param string|array $columns the columns (and the directions) to be ordered by.
* Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array
* (e.g. `array('id' => Query::SORT_ASC ASC, 'name' => Query::SORT_DESC)`).
* (e.g. `array('id' => Query::SORT_ASC, 'name' => Query::SORT_DESC)`).
* The method will automatically quote the column names unless a column contains some parenthesis
* (which means the column contains a DB expression).
* @return Query the query object itself
......
......@@ -20,4 +20,4 @@ class StaleObjectException extends Exception
{
return \Yii::t('yii|Stale Object Exception');
}
}
\ No newline at end of file
}
......@@ -25,7 +25,7 @@ use yii\base\InvalidConfigException;
* //.... other SQL executions
* $transaction->commit();
* } catch(Exception $e) {
* $transaction->rollBack();
* $transaction->rollback();
* }
* ~~~
*
......@@ -42,14 +42,14 @@ class Transaction extends \yii\base\Object
public $db;
/**
* @var boolean whether this transaction is active. Only an active transaction
* can [[commit()]] or [[rollBack()]]. This property is set true when the transaction is started.
* can [[commit()]] or [[rollback()]]. This property is set true when the transaction is started.
*/
private $_active = false;
/**
* Returns a value indicating whether this transaction is active.
* @return boolean whether this transaction is active. Only an active transaction
* can [[commit()]] or [[rollBack()]].
* can [[commit()]] or [[rollback()]].
*/
public function getIsActive()
{
......
......@@ -16,4 +16,4 @@ namespace yii\helpers;
*/
class ArrayHelper extends base\ArrayHelper
{
}
\ No newline at end of file
}
......@@ -18,4 +18,4 @@ namespace yii\helpers;
*/
class FileHelper extends base\FileHelper
{
}
\ No newline at end of file
}
......@@ -42,4 +42,4 @@ class JsExpression extends Object
{
return $this->expression;
}
}
\ No newline at end of file
}
......@@ -15,4 +15,4 @@ namespace yii\helpers;
class Json extends base\Json
{
}
\ No newline at end of file
}
......@@ -26,4 +26,4 @@ namespace yii\helpers;
*/
class SecurityHelper extends base\SecurityHelper
{
}
\ No newline at end of file
}
......@@ -25,4 +25,4 @@ namespace yii\helpers;
*/
class VarDumper extends base\VarDumper
{
}
\ No newline at end of file
}
......@@ -236,15 +236,17 @@ class ArrayHelper
* To sort by multiple keys, provide an array of keys here.
* @param boolean|array $ascending whether to sort in ascending or descending order. When
* sorting by multiple keys with different ascending orders, use an array of ascending flags.
* @param integer|array $sortFlag the PHP sort flag. Valid values include:
* `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, and `SORT_STRING | SORT_FLAG_CASE`. The last
* value is for sorting strings in case-insensitive manner. Please refer to
* See [PHP manual](http://php.net/manual/en/function.sort.php) for more details.
* When sorting by multiple keys with different sort flags, use an array of sort flags.
* @param integer|array $sortFlag the PHP sort flag. Valid values include
* `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING` and `SORT_LOCALE_STRING`.
* Please refer to [PHP manual](http://php.net/manual/en/function.sort.php)
* for more details. When sorting by multiple keys with different sort flags, use an array of sort flags.
* @param boolean|array $caseSensitive whether to sort string in case-sensitive manner. This parameter
* is used only when `$sortFlag` is `SORT_STRING`.
* When sorting by multiple keys with different case sensitivities, use an array of boolean values.
* @throws InvalidParamException if the $ascending or $sortFlag parameters do not have
* correct number of elements as that of $key.
*/
public static function multisort(&$array, $key, $ascending = true, $sortFlag = SORT_REGULAR)
public static function multisort(&$array, $key, $ascending = true, $sortFlag = SORT_REGULAR, $caseSensitive = true)
{
$keys = is_array($key) ? $key : array($key);
if (empty($keys) || empty($array)) {
......@@ -259,20 +261,30 @@ class ArrayHelper
if (is_scalar($sortFlag)) {
$sortFlag = array_fill(0, $n, $sortFlag);
} elseif (count($sortFlag) !== $n) {
throw new InvalidParamException('The length of $ascending parameter must be the same as that of $keys.');
throw new InvalidParamException('The length of $sortFlag parameter must be the same as that of $keys.');
}
if (is_scalar($caseSensitive)) {
$caseSensitive = array_fill(0, $n, $caseSensitive);
} elseif (count($caseSensitive) !== $n) {
throw new InvalidParamException('The length of $caseSensitive parameter must be the same as that of $keys.');
}
$args = array();
foreach ($keys as $i => $key) {
$flag = $sortFlag[$i];
if ($flag == (SORT_STRING | SORT_FLAG_CASE)) {
$flag = SORT_STRING;
$column = array();
foreach (static::getColumn($array, $key) as $k => $value) {
$column[$k] = strtolower($value);
$cs = $caseSensitive[$i];
if (!$cs && ($flag === SORT_STRING)) {
if (defined('SORT_FLAG_CASE')) {
$flag = $flag | SORT_FLAG_CASE;
$args[] = static::getColumn($array, $key);
} else {
$column = array();
foreach (static::getColumn($array, $key) as $k => $value) {
$column[$k] = mb_strtolower($value);
}
$args[] = $column;
}
$args[] = $column;
} else {
$args[] = static::getColumn($array, $key);
$args[] = static::getColumn($array, $key);
}
$args[] = $ascending[$i] ? SORT_ASC : SORT_DESC;
$args[] = $flag;
......@@ -337,4 +349,4 @@ class ArrayHelper
}
return $d;
}
}
\ No newline at end of file
}
......@@ -169,4 +169,4 @@ class FileHelper
}
closedir($handle);
}
}
\ No newline at end of file
}
......@@ -95,9 +95,9 @@ class Html
public static $attributeOrder = array(
'type',
'id',
'class',
'name',
'value',
'class',
'href',
'src',
......@@ -127,13 +127,15 @@ class Html
* Encodes special characters into HTML entities.
* The [[yii\base\Application::charset|application charset]] will be used for encoding.
* @param string $content the content to be encoded
* @param boolean $doubleEncode whether to encode HTML entities in `$content`. If false,
* HTML entities in `$content` will not be further encoded.
* @return string the encoded content
* @see decode
* @see http://www.php.net/manual/en/function.htmlspecialchars.php
*/
public static function encode($content)
public static function encode($content, $doubleEncode = true)
{
return htmlspecialchars($content, ENT_QUOTES, Yii::$app->charset);
return htmlspecialchars($content, ENT_QUOTES, Yii::$app->charset, $doubleEncode);
}
/**
......@@ -375,7 +377,8 @@ class Html
*/
public static function mailto($text, $email = null, $options = array())
{
return static::a($text, 'mailto:' . ($email === null ? $text : $email), $options);
$options['href'] = 'mailto:' . ($email === null ? $text : $email);
return static::tag('a', $text, $options);
}
/**
......
......@@ -104,4 +104,4 @@ class Json
return $data;
}
}
}
\ No newline at end of file
}
......@@ -42,7 +42,8 @@ class SecurityHelper
public static function encrypt($data, $key)
{
$module = static::openCryptModule();
$key = StringHelper::substr($key, 0, mcrypt_enc_get_key_size($module));
// 192-bit (24 bytes) key size
$key = StringHelper::substr($key, 0, 24);
srand();
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
mcrypt_generic_init($module, $key, $iv);
......@@ -63,7 +64,8 @@ class SecurityHelper
public static function decrypt($data, $key)
{
$module = static::openCryptModule();
$key = StringHelper::substr($key, 0, mcrypt_enc_get_key_size($module));
// 192-bit (24 bytes) key size
$key = StringHelper::substr($key, 0, 24);
$ivSize = mcrypt_enc_get_iv_size($module);
$iv = StringHelper::substr($data, 0, $ivSize);
mcrypt_generic_init($module, $key, $iv);
......@@ -148,7 +150,8 @@ class SecurityHelper
if (!extension_loaded('mcrypt')) {
throw new InvalidConfigException('The mcrypt PHP extension is not installed.');
}
$module = @mcrypt_module_open('rijndael-256', '', MCRYPT_MODE_CBC, '');
// AES uses a 128-bit block size
$module = @mcrypt_module_open('rijndael-128', '', 'cbc', '');
if ($module === false) {
throw new Exception('Failed to initialize the mcrypt module.');
}
......@@ -164,11 +167,11 @@ class SecurityHelper
*
* ~~~
* // generates the hash (usually done during user registration or when the password is changed)
* $hash = SecurityHelper::hashPassword($password);
* $hash = SecurityHelper::generatePasswordHash($password);
* // ...save $hash in database...
*
* // during login, validate if the password entered is correct using $hash fetched from database
* if (PasswordHelper::verifyPassword($password, $hash) {
* if (SecurityHelper::verifyPassword($password, $hash) {
* // password is good
* } else {
* // password is bad
......@@ -214,7 +217,7 @@ class SecurityHelper
throw new InvalidParamException('Password must be a string and cannot be empty.');
}
if (!preg_match('/^\$2[axy]\$(\d\d)\$[\./0-9A-Za-z]{22}/', $hash, $matches) || $matches[1] < 4 || $matches[1] > 30) {
if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches) || $matches[1] < 4 || $matches[1] > 30) {
throw new InvalidParamException('Hash is invalid.');
}
......@@ -269,4 +272,4 @@ class SecurityHelper
$salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));
return $salt;
}
}
\ No newline at end of file
}
......@@ -39,7 +39,7 @@ class VarDumper
*/
public static function dump($var, $depth = 10, $highlight = false)
{
echo self::dumpAsString($var, $depth, $highlight);
echo static::dumpAsString($var, $depth, $highlight);
}
/**
......@@ -116,7 +116,7 @@ class VarDumper
} elseif (self::$_depth <= $level) {
self::$_output .= get_class($var) . '(...)';
} else {
$id = self::$_objects[] = $var;
$id = array_push(self::$_objects, $var);
$className = get_class($var);
$members = (array)$var;
$spaces = str_repeat(' ', $level * 4);
......@@ -131,4 +131,4 @@ class VarDumper
break;
}
}
}
\ No newline at end of file
}
......@@ -76,4 +76,4 @@ class PhpMessageSource extends MessageSource
return array();
}
}
}
\ No newline at end of file
}
......@@ -624,4 +624,4 @@ return array (
array (
0 => 'in_array(fmod($n,10),array(1,2))||fmod($n,20)==0',
),
);
\ No newline at end of file
);
......@@ -69,4 +69,4 @@ class EmailTarget extends Target
}
mail($sentTo, $subject, $body, implode("\r\n", $headers));
}
}
\ No newline at end of file
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment