Commit 105e277f authored by Antonio Ramirez's avatar Antonio Ramirez

Merge branch 'master' into bootstrap

* master: (84 commits)
  remove from master (update track)
  minor fixes
  updated the README file of the bootstrap app.
  Inflector class
  readjusting files for the framework package.
  renamed files.
  Added punycode as part of the framework.
  Renamed core asset bundles.
  fixed wrong dependency name.
  Added bootstrap bundles.
  Reorganized the bootstrap app to prepare it as a separate composer package.
  Update Pagination.php
  "ManagerTestBase::testExecuteBizRule()" has been fixed to not produce side effects on other tests.
  changed back to "create_time".
  Always enable profiling for DB queries.
  Fixed SiteController about Yii.
  changed to insert_time.
  Minor doc fix.
  refactored AutoTimestamp.
  Added UrlRule::host.
  ...

Conflicts:
	yii/assets.php
parents 25512733 ab695d11
...@@ -13,4 +13,7 @@ nbproject ...@@ -13,4 +13,7 @@ nbproject
Thumbs.db Thumbs.db
# composer vendor dir # composer vendor dir
/yii/vendor /yii/vendor
\ No newline at end of file
# composer itself is not needed
composer.phar
The Yii framework is free software. It is released under the terms of The Yii framework is free software. It is released under the terms of
the following BSD License. the following BSD License.
Copyright © 2008-2012 by Yii Software LLC (http://www.yiisoft.com) Copyright © 2008-2013 by Yii Software LLC (http://www.yiisoft.com)
All rights reserved. All rights reserved.
Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without
......
The Yii framework is free software. It is released under the terms of
the following BSD License.
Copyright © 2008-2013 by Yii Software LLC (http://www.yiisoft.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Yii Software LLC nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
Yii 2 Bootstrap Application
===========================
**NOTE** Yii 2 and the relevant applications and extensions are still under heavy
development. We may make significant changes without prior notices. Please do not
use them for production. Please consider using [Yii v1.1](https://github.com/yiisoft/yii)
if you have a project to be deployed for production soon.
Thank you for choosing Yii 2 - the new generation of high-performance PHP framework.
The Yii 2 Bootstrap Application is a Web application template that you can easily customize
to fit for your needs. It is particularly suitable for small Websites which mainly contain
a few informational pages.
DIRECTORY STRUCTURE
-------------------
commands/ contains console commands (controllers)
config/ contains application configurations
controllers/ contains Web controller classes
models/ contains model classes
runtime/ contains files generated during runtime
vendor/ contains dependent 3rd-party packages
views/ contains view files for the Web application
www/ contains the entry script and Web resources
REQUIREMENTS
------------
The minimum requirement by Yii is that your Web server supports PHP 5.3.?.
INSTALLATION
------------
### Install via Composer
If you do not have [Composer](http://getcomposer.org/), you may download it from
[http://getcomposer.org/](http://getcomposer.org/) or run the following command on Linux/Unix/MacOS:
~~~
curl -s http://getcomposer.org/installer | php
~~~
You can then install the Bootstrap Application using the following command:
~~~
php composer.phar create-project --stability=dev yiisoft/yii2-bootstrap bootstrap
~~~
Now you should be able to access the Bootstrap Application using the URL `http://localhost/bootstrap/www/`,
assuming `bootstrap` is directly under the document root of your Web server.
### Install from an Archive File
This is not currently available. We will provide it when Yii 2 is formally released.
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace app\commands;
use yii\console\Controller;
/**
* This command echos what the first argument that you have entered.
*
* This command is provided as an example for you to learn how to create console commands.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class HelloController extends Controller
{
/**
* This command echos what you have entered as the message.
* @param string $message the message to be echoed.
*/
public function actionIndex($message = 'hello world')
{
echo $message;
}
}
\ No newline at end of file
{
"name": "yiisoft/yii2-bootstrap",
"description": "Yii 2 Bootstrap Application",
"keywords": ["yii", "framework", "bootstrap"],
"homepage": "http://www.yiiframework.com/",
"type": "project",
"license": "BSD-3-Clause",
"support": {
"issues": "https://github.com/yiisoft/yii2/issues?state=open",
"forum": "http://www.yiiframework.com/forum/",
"wiki": "http://www.yiiframework.com/wiki/",
"irc": "irc://irc.freenode.net/yii",
"source": "https://github.com/yiisoft/yii2"
},
"config": {
"vendor-dir": "vendor"
},
"minimum-stability": "dev",
"require": {
"php": ">=5.3.0",
"yiisoft/yii2": "dev-master"
}
}
...@@ -5,8 +5,6 @@ return array( ...@@ -5,8 +5,6 @@ return array(
'basePath' => '@wwwroot', 'basePath' => '@wwwroot',
'baseUrl' => '@www', 'baseUrl' => '@www',
'css' => array( 'css' => array(
'css/bootstrap.min.css',
'css/bootstrap-responsive.min.css',
'css/site.css', 'css/site.css',
), ),
'js' => array( 'js' => array(
...@@ -14,6 +12,7 @@ return array( ...@@ -14,6 +12,7 @@ return array(
), ),
'depends' => array( 'depends' => array(
'yii', 'yii',
'yii/bootstrap-responsive',
), ),
), ),
); );
<?php
return array(
'id' => 'bootstrap-console',
'basePath' => dirname(__DIR__),
'preload' => array('log'),
'controllerPath' => dirname(__DIR__) . '/commands',
'controllerNamespace' => 'app\commands',
'modules' => array(
),
'components' => array(
'cache' => array(
'class' => 'yii\caching\FileCache',
),
'log' => array(
'class' => 'yii\logging\Router',
'targets' => array(
array(
'class' => 'yii\logging\FileTarget',
'levels' => array('error', 'warning'),
),
),
),
),
'params' => require(__DIR__ . '/params.php'),
);
<?php <?php
return array( return array(
'id' => 'hello', 'id' => 'bootstrap',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'preload' => array('log'), 'preload' => array('log'),
'controllerNamespace' => 'app\controllers',
'modules' => array( 'modules' => array(
'debug' => array( // 'debug' => array(
'class' => 'yii\debug\Module', // 'class' => 'yii\debug\Module',
) // )
), ),
'components' => array( 'components' => array(
'cache' => array( 'cache' => array(
...@@ -23,14 +24,15 @@ return array( ...@@ -23,14 +24,15 @@ return array(
'log' => array( 'log' => array(
'class' => 'yii\logging\Router', 'class' => 'yii\logging\Router',
'targets' => array( 'targets' => array(
'file' => array( array(
'class' => 'yii\logging\FileTarget', 'class' => 'yii\logging\FileTarget',
'levels' => array('error', 'warning'), 'levels' => array('error', 'warning'),
), ),
// array(
// 'class' => 'yii\logging\DebugTarget',
// )
), ),
), ),
), ),
'params' => array( 'params' => require(__DIR__ . '/params.php'),
'adminEmail' => 'admin@example.com',
),
); );
<?php
return array(
'adminEmail' => 'admin@example.com',
);
\ No newline at end of file
<?php <?php
namespace app\controllers;
use Yii;
use yii\web\Controller; use yii\web\Controller;
use app\models\LoginForm; use app\models\LoginForm;
use app\models\ContactForm; use app\models\ContactForm;
......
/*!
* Bootstrap Responsive v2.3.1
*
* Copyright 2012 Twitter, Inc
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world @twitter by @mdo and @fat.
*/.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}@-ms-viewport{width:device-width}.hidden{display:none;visibility:hidden}.visible-phone{display:none!important}.visible-tablet{display:none!important}.hidden-desktop{display:none!important}.visible-desktop{display:inherit!important}@media(min-width:768px) and (max-width:979px){.hidden-desktop{display:inherit!important}.visible-desktop{display:none!important}.visible-tablet{display:inherit!important}.hidden-tablet{display:none!important}}@media(max-width:767px){.hidden-desktop{display:inherit!important}.visible-desktop{display:none!important}.visible-phone{display:inherit!important}.hidden-phone{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:inherit!important}.hidden-print{display:none!important}}@media(min-width:1200px){.row{margin-left:-30px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:30px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:1170px}.span12{width:1170px}.span11{width:1070px}.span10{width:970px}.span9{width:870px}.span8{width:770px}.span7{width:670px}.span6{width:570px}.span5{width:470px}.span4{width:370px}.span3{width:270px}.span2{width:170px}.span1{width:70px}.offset12{margin-left:1230px}.offset11{margin-left:1130px}.offset10{margin-left:1030px}.offset9{margin-left:930px}.offset8{margin-left:830px}.offset7{margin-left:730px}.offset6{margin-left:630px}.offset5{margin-left:530px}.offset4{margin-left:430px}.offset3{margin-left:330px}.offset2{margin-left:230px}.offset1{margin-left:130px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.564102564102564%;*margin-left:2.5109110747408616%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.564102564102564%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.45299145299145%;*width:91.39979996362975%}.row-fluid .span10{width:82.90598290598291%;*width:82.8527914166212%}.row-fluid .span9{width:74.35897435897436%;*width:74.30578286961266%}.row-fluid .span8{width:65.81196581196582%;*width:65.75877432260411%}.row-fluid .span7{width:57.26495726495726%;*width:57.21176577559556%}.row-fluid .span6{width:48.717948717948715%;*width:48.664757228587014%}.row-fluid .span5{width:40.17094017094017%;*width:40.11774868157847%}.row-fluid .span4{width:31.623931623931625%;*width:31.570740134569924%}.row-fluid .span3{width:23.076923076923077%;*width:23.023731587561375%}.row-fluid .span2{width:14.52991452991453%;*width:14.476723040552828%}.row-fluid .span1{width:5.982905982905983%;*width:5.929714493544281%}.row-fluid .offset12{margin-left:105.12820512820512%;*margin-left:105.02182214948171%}.row-fluid .offset12:first-child{margin-left:102.56410256410257%;*margin-left:102.45771958537915%}.row-fluid .offset11{margin-left:96.58119658119658%;*margin-left:96.47481360247316%}.row-fluid .offset11:first-child{margin-left:94.01709401709402%;*margin-left:93.91071103837061%}.row-fluid .offset10{margin-left:88.03418803418803%;*margin-left:87.92780505546462%}.row-fluid .offset10:first-child{margin-left:85.47008547008548%;*margin-left:85.36370249136206%}.row-fluid .offset9{margin-left:79.48717948717949%;*margin-left:79.38079650845607%}.row-fluid .offset9:first-child{margin-left:76.92307692307693%;*margin-left:76.81669394435352%}.row-fluid .offset8{margin-left:70.94017094017094%;*margin-left:70.83378796144753%}.row-fluid .offset8:first-child{margin-left:68.37606837606839%;*margin-left:68.26968539734497%}.row-fluid .offset7{margin-left:62.393162393162385%;*margin-left:62.28677941443899%}.row-fluid .offset7:first-child{margin-left:59.82905982905982%;*margin-left:59.72267685033642%}.row-fluid .offset6{margin-left:53.84615384615384%;*margin-left:53.739770867430444%}.row-fluid .offset6:first-child{margin-left:51.28205128205128%;*margin-left:51.175668303327875%}.row-fluid .offset5{margin-left:45.299145299145295%;*margin-left:45.1927623204219%}.row-fluid .offset5:first-child{margin-left:42.73504273504273%;*margin-left:42.62865975631933%}.row-fluid .offset4{margin-left:36.75213675213675%;*margin-left:36.645753773413354%}.row-fluid .offset4:first-child{margin-left:34.18803418803419%;*margin-left:34.081651209310785%}.row-fluid .offset3{margin-left:28.205128205128204%;*margin-left:28.0987452264048%}.row-fluid .offset3:first-child{margin-left:25.641025641025642%;*margin-left:25.53464266230224%}.row-fluid .offset2{margin-left:19.65811965811966%;*margin-left:19.551736679396257%}.row-fluid .offset2:first-child{margin-left:17.094017094017094%;*margin-left:16.98763411529369%}.row-fluid .offset1{margin-left:11.11111111111111%;*margin-left:11.004728132387708%}.row-fluid .offset1:first-child{margin-left:8.547008547008547%;*margin-left:8.440625568285142%}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:30px}input.span12,textarea.span12,.uneditable-input.span12{width:1156px}input.span11,textarea.span11,.uneditable-input.span11{width:1056px}input.span10,textarea.span10,.uneditable-input.span10{width:956px}input.span9,textarea.span9,.uneditable-input.span9{width:856px}input.span8,textarea.span8,.uneditable-input.span8{width:756px}input.span7,textarea.span7,.uneditable-input.span7{width:656px}input.span6,textarea.span6,.uneditable-input.span6{width:556px}input.span5,textarea.span5,.uneditable-input.span5{width:456px}input.span4,textarea.span4,.uneditable-input.span4{width:356px}input.span3,textarea.span3,.uneditable-input.span3{width:256px}input.span2,textarea.span2,.uneditable-input.span2{width:156px}input.span1,textarea.span1,.uneditable-input.span1{width:56px}.thumbnails{margin-left:-30px}.thumbnails>li{margin-left:30px}.row-fluid .thumbnails{margin-left:0}}@media(min-width:768px) and (max-width:979px){.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:724px}.span12{width:724px}.span11{width:662px}.span10{width:600px}.span9{width:538px}.span8{width:476px}.span7{width:414px}.span6{width:352px}.span5{width:290px}.span4{width:228px}.span3{width:166px}.span2{width:104px}.span1{width:42px}.offset12{margin-left:764px}.offset11{margin-left:702px}.offset10{margin-left:640px}.offset9{margin-left:578px}.offset8{margin-left:516px}.offset7{margin-left:454px}.offset6{margin-left:392px}.offset5{margin-left:330px}.offset4{margin-left:268px}.offset3{margin-left:206px}.offset2{margin-left:144px}.offset1{margin-left:82px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.7624309392265194%;*margin-left:2.709239449864817%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.7624309392265194%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.43646408839778%;*width:91.38327259903608%}.row-fluid .span10{width:82.87292817679558%;*width:82.81973668743387%}.row-fluid .span9{width:74.30939226519337%;*width:74.25620077583166%}.row-fluid .span8{width:65.74585635359117%;*width:65.69266486422946%}.row-fluid .span7{width:57.18232044198895%;*width:57.12912895262725%}.row-fluid .span6{width:48.61878453038674%;*width:48.56559304102504%}.row-fluid .span5{width:40.05524861878453%;*width:40.00205712942283%}.row-fluid .span4{width:31.491712707182323%;*width:31.43852121782062%}.row-fluid .span3{width:22.92817679558011%;*width:22.87498530621841%}.row-fluid .span2{width:14.3646408839779%;*width:14.311449394616199%}.row-fluid .span1{width:5.801104972375691%;*width:5.747913483013988%}.row-fluid .offset12{margin-left:105.52486187845304%;*margin-left:105.41847889972962%}.row-fluid .offset12:first-child{margin-left:102.76243093922652%;*margin-left:102.6560479605031%}.row-fluid .offset11{margin-left:96.96132596685082%;*margin-left:96.8549429881274%}.row-fluid .offset11:first-child{margin-left:94.1988950276243%;*margin-left:94.09251204890089%}.row-fluid .offset10{margin-left:88.39779005524862%;*margin-left:88.2914070765252%}.row-fluid .offset10:first-child{margin-left:85.6353591160221%;*margin-left:85.52897613729868%}.row-fluid .offset9{margin-left:79.8342541436464%;*margin-left:79.72787116492299%}.row-fluid .offset9:first-child{margin-left:77.07182320441989%;*margin-left:76.96544022569647%}.row-fluid .offset8{margin-left:71.2707182320442%;*margin-left:71.16433525332079%}.row-fluid .offset8:first-child{margin-left:68.50828729281768%;*margin-left:68.40190431409427%}.row-fluid .offset7{margin-left:62.70718232044199%;*margin-left:62.600799341718584%}.row-fluid .offset7:first-child{margin-left:59.94475138121547%;*margin-left:59.838368402492065%}.row-fluid .offset6{margin-left:54.14364640883978%;*margin-left:54.037263430116376%}.row-fluid .offset6:first-child{margin-left:51.38121546961326%;*margin-left:51.27483249088986%}.row-fluid .offset5{margin-left:45.58011049723757%;*margin-left:45.47372751851417%}.row-fluid .offset5:first-child{margin-left:42.81767955801105%;*margin-left:42.71129657928765%}.row-fluid .offset4{margin-left:37.01657458563536%;*margin-left:36.91019160691196%}.row-fluid .offset4:first-child{margin-left:34.25414364640884%;*margin-left:34.14776066768544%}.row-fluid .offset3{margin-left:28.45303867403315%;*margin-left:28.346655695309746%}.row-fluid .offset3:first-child{margin-left:25.69060773480663%;*margin-left:25.584224756083227%}.row-fluid .offset2{margin-left:19.88950276243094%;*margin-left:19.783119783707537%}.row-fluid .offset2:first-child{margin-left:17.12707182320442%;*margin-left:17.02068884448102%}.row-fluid .offset1{margin-left:11.32596685082873%;*margin-left:11.219583872105325%}.row-fluid .offset1:first-child{margin-left:8.56353591160221%;*margin-left:8.457152932878806%}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:20px}input.span12,textarea.span12,.uneditable-input.span12{width:710px}input.span11,textarea.span11,.uneditable-input.span11{width:648px}input.span10,textarea.span10,.uneditable-input.span10{width:586px}input.span9,textarea.span9,.uneditable-input.span9{width:524px}input.span8,textarea.span8,.uneditable-input.span8{width:462px}input.span7,textarea.span7,.uneditable-input.span7{width:400px}input.span6,textarea.span6,.uneditable-input.span6{width:338px}input.span5,textarea.span5,.uneditable-input.span5{width:276px}input.span4,textarea.span4,.uneditable-input.span4{width:214px}input.span3,textarea.span3,.uneditable-input.span3{width:152px}input.span2,textarea.span2,.uneditable-input.span2{width:90px}input.span1,textarea.span1,.uneditable-input.span1{width:28px}}@media(max-width:767px){body{padding-right:20px;padding-left:20px}.navbar-fixed-top,.navbar-fixed-bottom,.navbar-static-top{margin-right:-20px;margin-left:-20px}.container-fluid{padding:0}.dl-horizontal dt{float:none;width:auto;clear:none;text-align:left}.dl-horizontal dd{margin-left:0}.container{width:auto}.row-fluid{width:100%}.row,.thumbnails{margin-left:0}.thumbnails>li{float:none;margin-left:0}[class*="span"],.uneditable-input[class*="span"],.row-fluid [class*="span"]{display:block;float:none;width:100%;margin-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.span12,.row-fluid .span12{width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="offset"]:first-child{margin-left:0}.input-large,.input-xlarge,.input-xxlarge,input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.input-prepend input,.input-append input,.input-prepend input[class*="span"],.input-append input[class*="span"]{display:inline-block;width:auto}.controls-row [class*="span"]+[class*="span"]{margin-left:0}.modal{position:fixed;top:20px;right:20px;left:20px;width:auto;margin:0}.modal.fade{top:-100px}.modal.fade.in{top:20px}}@media(max-width:480px){.nav-collapse{-webkit-transform:translate3d(0,0,0)}.page-header h1 small{display:block;line-height:20px}input[type="checkbox"],input[type="radio"]{border:1px solid #ccc}.form-horizontal .control-label{float:none;width:auto;padding-top:0;text-align:left}.form-horizontal .controls{margin-left:0}.form-horizontal .control-list{padding-top:0}.form-horizontal .form-actions{padding-right:10px;padding-left:10px}.media .pull-left,.media .pull-right{display:block;float:none;margin-bottom:10px}.media-object{margin-right:0;margin-left:0}.modal{top:10px;right:10px;left:10px}.modal-header .close{padding:10px;margin:-10px}.carousel-caption{position:static}}@media(max-width:979px){body{padding-top:0}.navbar-fixed-top,.navbar-fixed-bottom{position:static}.navbar-fixed-top{margin-bottom:20px}.navbar-fixed-bottom{margin-top:20px}.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding:5px}.navbar .container{width:auto;padding:0}.navbar .brand{padding-right:10px;padding-left:10px;margin:0 0 0 -5px}.nav-collapse{clear:both}.nav-collapse .nav{float:none;margin:0 0 10px}.nav-collapse .nav>li{float:none}.nav-collapse .nav>li>a{margin-bottom:2px}.nav-collapse .nav>.divider-vertical{display:none}.nav-collapse .nav .nav-header{color:#777;text-shadow:none}.nav-collapse .nav>li>a,.nav-collapse .dropdown-menu a{padding:9px 15px;font-weight:bold;color:#777;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.nav-collapse .btn{padding:4px 10px 4px;font-weight:normal;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.nav-collapse .dropdown-menu li+li a{margin-bottom:2px}.nav-collapse .nav>li>a:hover,.nav-collapse .nav>li>a:focus,.nav-collapse .dropdown-menu a:hover,.nav-collapse .dropdown-menu a:focus{background-color:#f2f2f2}.navbar-inverse .nav-collapse .nav>li>a,.navbar-inverse .nav-collapse .dropdown-menu a{color:#999}.navbar-inverse .nav-collapse .nav>li>a:hover,.navbar-inverse .nav-collapse .nav>li>a:focus,.navbar-inverse .nav-collapse .dropdown-menu a:hover,.navbar-inverse .nav-collapse .dropdown-menu a:focus{background-color:#111}.nav-collapse.in .btn-group{padding:0;margin-top:5px}.nav-collapse .dropdown-menu{position:static;top:auto;left:auto;display:none;float:none;max-width:none;padding:0;margin:0 15px;background-color:transparent;border:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.nav-collapse .open>.dropdown-menu{display:block}.nav-collapse .dropdown-menu:before,.nav-collapse .dropdown-menu:after{display:none}.nav-collapse .dropdown-menu .divider{display:none}.nav-collapse .nav>li>.dropdown-menu:before,.nav-collapse .nav>li>.dropdown-menu:after{display:none}.nav-collapse .navbar-form,.nav-collapse .navbar-search{float:none;padding:10px 15px;margin:10px 0;border-top:1px solid #f2f2f2;border-bottom:1px solid #f2f2f2;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1)}.navbar-inverse .nav-collapse .navbar-form,.navbar-inverse .nav-collapse .navbar-search{border-top-color:#111;border-bottom-color:#111}.navbar .nav-collapse .nav.pull-right{float:none;margin-left:0}.nav-collapse,.nav-collapse.collapse{height:0;overflow:hidden}.navbar .btn-navbar{display:block}.navbar-static .navbar-inner{padding-right:10px;padding-left:10px}}@media(min-width:980px){.nav-collapse.collapse{height:auto!important;overflow:visible!important}}
This source diff could not be displayed because it is too large. You can view the blob instead.
/*!
* Bootstrap.js by @fat & @mdo
* Copyright 2012 Twitter, Inc.
* http://www.apache.org/licenses/LICENSE-2.0.txt
*/
!function(e){"use strict";e(function(){e.support.transition=function(){var e=function(){var e=document.createElement("bootstrap"),t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},n;for(n in t)if(e.style[n]!==undefined)return t[n]}();return e&&{end:e}}()})}(window.jQuery),!function(e){"use strict";var t='[data-dismiss="alert"]',n=function(n){e(n).on("click",t,this.close)};n.prototype.close=function(t){function s(){i.trigger("closed").remove()}var n=e(this),r=n.attr("data-target"),i;r||(r=n.attr("href"),r=r&&r.replace(/.*(?=#[^\s]*$)/,"")),i=e(r),t&&t.preventDefault(),i.length||(i=n.hasClass("alert")?n:n.parent()),i.trigger(t=e.Event("close"));if(t.isDefaultPrevented())return;i.removeClass("in"),e.support.transition&&i.hasClass("fade")?i.on(e.support.transition.end,s):s()};var r=e.fn.alert;e.fn.alert=function(t){return this.each(function(){var r=e(this),i=r.data("alert");i||r.data("alert",i=new n(this)),typeof t=="string"&&i[t].call(r)})},e.fn.alert.Constructor=n,e.fn.alert.noConflict=function(){return e.fn.alert=r,this},e(document).on("click.alert.data-api",t,n.prototype.close)}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.button.defaults,n)};t.prototype.setState=function(e){var t="disabled",n=this.$element,r=n.data(),i=n.is("input")?"val":"html";e+="Text",r.resetText||n.data("resetText",n[i]()),n[i](r[e]||this.options[e]),setTimeout(function(){e=="loadingText"?n.addClass(t).attr(t,t):n.removeClass(t).removeAttr(t)},0)},t.prototype.toggle=function(){var e=this.$element.closest('[data-toggle="buttons-radio"]');e&&e.find(".active").removeClass("active"),this.$element.toggleClass("active")};var n=e.fn.button;e.fn.button=function(n){return this.each(function(){var r=e(this),i=r.data("button"),s=typeof n=="object"&&n;i||r.data("button",i=new t(this,s)),n=="toggle"?i.toggle():n&&i.setState(n)})},e.fn.button.defaults={loadingText:"loading..."},e.fn.button.Constructor=t,e.fn.button.noConflict=function(){return e.fn.button=n,this},e(document).on("click.button.data-api","[data-toggle^=button]",function(t){var n=e(t.target);n.hasClass("btn")||(n=n.closest(".btn")),n.button("toggle")})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.$indicators=this.$element.find(".carousel-indicators"),this.options=n,this.options.pause=="hover"&&this.$element.on("mouseenter",e.proxy(this.pause,this)).on("mouseleave",e.proxy(this.cycle,this))};t.prototype={cycle:function(t){return t||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(e.proxy(this.next,this),this.options.interval)),this},getActiveIndex:function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},to:function(t){var n=this.getActiveIndex(),r=this;if(t>this.$items.length-1||t<0)return;return this.sliding?this.$element.one("slid",function(){r.to(t)}):n==t?this.pause().cycle():this.slide(t>n?"next":"prev",e(this.$items[t]))},pause:function(t){return t||(this.paused=!0),this.$element.find(".next, .prev").length&&e.support.transition.end&&(this.$element.trigger(e.support.transition.end),this.cycle(!0)),clearInterval(this.interval),this.interval=null,this},next:function(){if(this.sliding)return;return this.slide("next")},prev:function(){if(this.sliding)return;return this.slide("prev")},slide:function(t,n){var r=this.$element.find(".item.active"),i=n||r[t](),s=this.interval,o=t=="next"?"left":"right",u=t=="next"?"first":"last",a=this,f;this.sliding=!0,s&&this.pause(),i=i.length?i:this.$element.find(".item")[u](),f=e.Event("slide",{relatedTarget:i[0],direction:o});if(i.hasClass("active"))return;this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid",function(){var t=e(a.$indicators.children()[a.getActiveIndex()]);t&&t.addClass("active")}));if(e.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(f);if(f.isDefaultPrevented())return;i.addClass(t),i[0].offsetWidth,r.addClass(o),i.addClass(o),this.$element.one(e.support.transition.end,function(){i.removeClass([t,o].join(" ")).addClass("active"),r.removeClass(["active",o].join(" ")),a.sliding=!1,setTimeout(function(){a.$element.trigger("slid")},0)})}else{this.$element.trigger(f);if(f.isDefaultPrevented())return;r.removeClass("active"),i.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return s&&this.cycle(),this}};var n=e.fn.carousel;e.fn.carousel=function(n){return this.each(function(){var r=e(this),i=r.data("carousel"),s=e.extend({},e.fn.carousel.defaults,typeof n=="object"&&n),o=typeof n=="string"?n:s.slide;i||r.data("carousel",i=new t(this,s)),typeof n=="number"?i.to(n):o?i[o]():s.interval&&i.pause().cycle()})},e.fn.carousel.defaults={interval:5e3,pause:"hover"},e.fn.carousel.Constructor=t,e.fn.carousel.noConflict=function(){return e.fn.carousel=n,this},e(document).on("click.carousel.data-api","[data-slide], [data-slide-to]",function(t){var n=e(this),r,i=e(n.attr("data-target")||(r=n.attr("href"))&&r.replace(/.*(?=#[^\s]+$)/,"")),s=e.extend({},i.data(),n.data()),o;i.carousel(s),(o=n.attr("data-slide-to"))&&i.data("carousel").pause().to(o).cycle(),t.preventDefault()})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.collapse.defaults,n),this.options.parent&&(this.$parent=e(this.options.parent)),this.options.toggle&&this.toggle()};t.prototype={constructor:t,dimension:function(){var e=this.$element.hasClass("width");return e?"width":"height"},show:function(){var t,n,r,i;if(this.transitioning||this.$element.hasClass("in"))return;t=this.dimension(),n=e.camelCase(["scroll",t].join("-")),r=this.$parent&&this.$parent.find("> .accordion-group > .in");if(r&&r.length){i=r.data("collapse");if(i&&i.transitioning)return;r.collapse("hide"),i||r.data("collapse",null)}this.$element[t](0),this.transition("addClass",e.Event("show"),"shown"),e.support.transition&&this.$element[t](this.$element[0][n])},hide:function(){var t;if(this.transitioning||!this.$element.hasClass("in"))return;t=this.dimension(),this.reset(this.$element[t]()),this.transition("removeClass",e.Event("hide"),"hidden"),this.$element[t](0)},reset:function(e){var t=this.dimension();return this.$element.removeClass("collapse")[t](e||"auto")[0].offsetWidth,this.$element[e!==null?"addClass":"removeClass"]("collapse"),this},transition:function(t,n,r){var i=this,s=function(){n.type=="show"&&i.reset(),i.transitioning=0,i.$element.trigger(r)};this.$element.trigger(n);if(n.isDefaultPrevented())return;this.transitioning=1,this.$element[t]("in"),e.support.transition&&this.$element.hasClass("collapse")?this.$element.one(e.support.transition.end,s):s()},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}};var n=e.fn.collapse;e.fn.collapse=function(n){return this.each(function(){var r=e(this),i=r.data("collapse"),s=e.extend({},e.fn.collapse.defaults,r.data(),typeof n=="object"&&n);i||r.data("collapse",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.collapse.defaults={toggle:!0},e.fn.collapse.Constructor=t,e.fn.collapse.noConflict=function(){return e.fn.collapse=n,this},e(document).on("click.collapse.data-api","[data-toggle=collapse]",function(t){var n=e(this),r,i=n.attr("data-target")||t.preventDefault()||(r=n.attr("href"))&&r.replace(/.*(?=#[^\s]+$)/,""),s=e(i).data("collapse")?"toggle":n.data();n[e(i).hasClass("in")?"addClass":"removeClass"]("collapsed"),e(i).collapse(s)})}(window.jQuery),!function(e){"use strict";function r(){e(t).each(function(){i(e(this)).removeClass("open")})}function i(t){var n=t.attr("data-target"),r;n||(n=t.attr("href"),n=n&&/#/.test(n)&&n.replace(/.*(?=#[^\s]*$)/,"")),r=n&&e(n);if(!r||!r.length)r=t.parent();return r}var t="[data-toggle=dropdown]",n=function(t){var n=e(t).on("click.dropdown.data-api",this.toggle);e("html").on("click.dropdown.data-api",function(){n.parent().removeClass("open")})};n.prototype={constructor:n,toggle:function(t){var n=e(this),s,o;if(n.is(".disabled, :disabled"))return;return s=i(n),o=s.hasClass("open"),r(),o||s.toggleClass("open"),n.focus(),!1},keydown:function(n){var r,s,o,u,a,f;if(!/(38|40|27)/.test(n.keyCode))return;r=e(this),n.preventDefault(),n.stopPropagation();if(r.is(".disabled, :disabled"))return;u=i(r),a=u.hasClass("open");if(!a||a&&n.keyCode==27)return n.which==27&&u.find(t).focus(),r.click();s=e("[role=menu] li:not(.divider):visible a",u);if(!s.length)return;f=s.index(s.filter(":focus")),n.keyCode==38&&f>0&&f--,n.keyCode==40&&f<s.length-1&&f++,~f||(f=0),s.eq(f).focus()}};var s=e.fn.dropdown;e.fn.dropdown=function(t){return this.each(function(){var r=e(this),i=r.data("dropdown");i||r.data("dropdown",i=new n(this)),typeof t=="string"&&i[t].call(r)})},e.fn.dropdown.Constructor=n,e.fn.dropdown.noConflict=function(){return e.fn.dropdown=s,this},e(document).on("click.dropdown.data-api",r).on("click.dropdown.data-api",".dropdown form",function(e){e.stopPropagation()}).on("click.dropdown-menu",function(e){e.stopPropagation()}).on("click.dropdown.data-api",t,n.prototype.toggle).on("keydown.dropdown.data-api",t+", [role=menu]",n.prototype.keydown)}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.options=n,this.$element=e(t).delegate('[data-dismiss="modal"]',"click.dismiss.modal",e.proxy(this.hide,this)),this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};t.prototype={constructor:t,toggle:function(){return this[this.isShown?"hide":"show"]()},show:function(){var t=this,n=e.Event("show");this.$element.trigger(n);if(this.isShown||n.isDefaultPrevented())return;this.isShown=!0,this.escape(),this.backdrop(function(){var n=e.support.transition&&t.$element.hasClass("fade");t.$element.parent().length||t.$element.appendTo(document.body),t.$element.show(),n&&t.$element[0].offsetWidth,t.$element.addClass("in").attr("aria-hidden",!1),t.enforceFocus(),n?t.$element.one(e.support.transition.end,function(){t.$element.focus().trigger("shown")}):t.$element.focus().trigger("shown")})},hide:function(t){t&&t.preventDefault();var n=this;t=e.Event("hide"),this.$element.trigger(t);if(!this.isShown||t.isDefaultPrevented())return;this.isShown=!1,this.escape(),e(document).off("focusin.modal"),this.$element.removeClass("in").attr("aria-hidden",!0),e.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal()},enforceFocus:function(){var t=this;e(document).on("focusin.modal",function(e){t.$element[0]!==e.target&&!t.$element.has(e.target).length&&t.$element.focus()})},escape:function(){var e=this;this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.modal",function(t){t.which==27&&e.hide()}):this.isShown||this.$element.off("keyup.dismiss.modal")},hideWithTransition:function(){var t=this,n=setTimeout(function(){t.$element.off(e.support.transition.end),t.hideModal()},500);this.$element.one(e.support.transition.end,function(){clearTimeout(n),t.hideModal()})},hideModal:function(){var e=this;this.$element.hide(),this.backdrop(function(){e.removeBackdrop(),e.$element.trigger("hidden")})},removeBackdrop:function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},backdrop:function(t){var n=this,r=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var i=e.support.transition&&r;this.$backdrop=e('<div class="modal-backdrop '+r+'" />').appendTo(document.body),this.$backdrop.click(this.options.backdrop=="static"?e.proxy(this.$element[0].focus,this.$element[0]):e.proxy(this.hide,this)),i&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in");if(!t)return;i?this.$backdrop.one(e.support.transition.end,t):t()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),e.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(e.support.transition.end,t):t()):t&&t()}};var n=e.fn.modal;e.fn.modal=function(n){return this.each(function(){var r=e(this),i=r.data("modal"),s=e.extend({},e.fn.modal.defaults,r.data(),typeof n=="object"&&n);i||r.data("modal",i=new t(this,s)),typeof n=="string"?i[n]():s.show&&i.show()})},e.fn.modal.defaults={backdrop:!0,keyboard:!0,show:!0},e.fn.modal.Constructor=t,e.fn.modal.noConflict=function(){return e.fn.modal=n,this},e(document).on("click.modal.data-api",'[data-toggle="modal"]',function(t){var n=e(this),r=n.attr("href"),i=e(n.attr("data-target")||r&&r.replace(/.*(?=#[^\s]+$)/,"")),s=i.data("modal")?"toggle":e.extend({remote:!/#/.test(r)&&r},i.data(),n.data());t.preventDefault(),i.modal(s).one("hide",function(){n.focus()})})}(window.jQuery),!function(e){"use strict";var t=function(e,t){this.init("tooltip",e,t)};t.prototype={constructor:t,init:function(t,n,r){var i,s,o,u,a;this.type=t,this.$element=e(n),this.options=this.getOptions(r),this.enabled=!0,o=this.options.trigger.split(" ");for(a=o.length;a--;)u=o[a],u=="click"?this.$element.on("click."+this.type,this.options.selector,e.proxy(this.toggle,this)):u!="manual"&&(i=u=="hover"?"mouseenter":"focus",s=u=="hover"?"mouseleave":"blur",this.$element.on(i+"."+this.type,this.options.selector,e.proxy(this.enter,this)),this.$element.on(s+"."+this.type,this.options.selector,e.proxy(this.leave,this)));this.options.selector?this._options=e.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},getOptions:function(t){return t=e.extend({},e.fn[this.type].defaults,this.$element.data(),t),t.delay&&typeof t.delay=="number"&&(t.delay={show:t.delay,hide:t.delay}),t},enter:function(t){var n=e.fn[this.type].defaults,r={},i;this._options&&e.each(this._options,function(e,t){n[e]!=t&&(r[e]=t)},this),i=e(t.currentTarget)[this.type](r).data(this.type);if(!i.options.delay||!i.options.delay.show)return i.show();clearTimeout(this.timeout),i.hoverState="in",this.timeout=setTimeout(function(){i.hoverState=="in"&&i.show()},i.options.delay.show)},leave:function(t){var n=e(t.currentTarget)[this.type](this._options).data(this.type);this.timeout&&clearTimeout(this.timeout);if(!n.options.delay||!n.options.delay.hide)return n.hide();n.hoverState="out",this.timeout=setTimeout(function(){n.hoverState=="out"&&n.hide()},n.options.delay.hide)},show:function(){var t,n,r,i,s,o,u=e.Event("show");if(this.hasContent()&&this.enabled){this.$element.trigger(u);if(u.isDefaultPrevented())return;t=this.tip(),this.setContent(),this.options.animation&&t.addClass("fade"),s=typeof this.options.placement=="function"?this.options.placement.call(this,t[0],this.$element[0]):this.options.placement,t.detach().css({top:0,left:0,display:"block"}),this.options.container?t.appendTo(this.options.container):t.insertAfter(this.$element),n=this.getPosition(),r=t[0].offsetWidth,i=t[0].offsetHeight;switch(s){case"bottom":o={top:n.top+n.height,left:n.left+n.width/2-r/2};break;case"top":o={top:n.top-i,left:n.left+n.width/2-r/2};break;case"left":o={top:n.top+n.height/2-i/2,left:n.left-r};break;case"right":o={top:n.top+n.height/2-i/2,left:n.left+n.width}}this.applyPlacement(o,s),this.$element.trigger("shown")}},applyPlacement:function(e,t){var n=this.tip(),r=n[0].offsetWidth,i=n[0].offsetHeight,s,o,u,a;n.offset(e).addClass(t).addClass("in"),s=n[0].offsetWidth,o=n[0].offsetHeight,t=="top"&&o!=i&&(e.top=e.top+i-o,a=!0),t=="bottom"||t=="top"?(u=0,e.left<0&&(u=e.left*-2,e.left=0,n.offset(e),s=n[0].offsetWidth,o=n[0].offsetHeight),this.replaceArrow(u-r+s,s,"left")):this.replaceArrow(o-i,o,"top"),a&&n.offset(e)},replaceArrow:function(e,t,n){this.arrow().css(n,e?50*(1-e/t)+"%":"")},setContent:function(){var e=this.tip(),t=this.getTitle();e.find(".tooltip-inner")[this.options.html?"html":"text"](t),e.removeClass("fade in top bottom left right")},hide:function(){function i(){var t=setTimeout(function(){n.off(e.support.transition.end).detach()},500);n.one(e.support.transition.end,function(){clearTimeout(t),n.detach()})}var t=this,n=this.tip(),r=e.Event("hide");this.$element.trigger(r);if(r.isDefaultPrevented())return;return n.removeClass("in"),e.support.transition&&this.$tip.hasClass("fade")?i():n.detach(),this.$element.trigger("hidden"),this},fixTitle:function(){var e=this.$element;(e.attr("title")||typeof e.attr("data-original-title")!="string")&&e.attr("data-original-title",e.attr("title")||"").attr("title","")},hasContent:function(){return this.getTitle()},getPosition:function(){var t=this.$element[0];return e.extend({},typeof t.getBoundingClientRect=="function"?t.getBoundingClientRect():{width:t.offsetWidth,height:t.offsetHeight},this.$element.offset())},getTitle:function(){var e,t=this.$element,n=this.options;return e=t.attr("data-original-title")||(typeof n.title=="function"?n.title.call(t[0]):n.title),e},tip:function(){return this.$tip=this.$tip||e(this.options.template)},arrow:function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},validate:function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(t){var n=t?e(t.currentTarget)[this.type](this._options).data(this.type):this;n.tip().hasClass("in")?n.hide():n.show()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}};var n=e.fn.tooltip;e.fn.tooltip=function(n){return this.each(function(){var r=e(this),i=r.data("tooltip"),s=typeof n=="object"&&n;i||r.data("tooltip",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.tooltip.Constructor=t,e.fn.tooltip.defaults={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1},e.fn.tooltip.noConflict=function(){return e.fn.tooltip=n,this}}(window.jQuery),!function(e){"use strict";var t=function(e,t){this.init("popover",e,t)};t.prototype=e.extend({},e.fn.tooltip.Constructor.prototype,{constructor:t,setContent:function(){var e=this.tip(),t=this.getTitle(),n=this.getContent();e.find(".popover-title")[this.options.html?"html":"text"](t),e.find(".popover-content")[this.options.html?"html":"text"](n),e.removeClass("fade top bottom left right in")},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var e,t=this.$element,n=this.options;return e=(typeof n.content=="function"?n.content.call(t[0]):n.content)||t.attr("data-content"),e},tip:function(){return this.$tip||(this.$tip=e(this.options.template)),this.$tip},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}});var n=e.fn.popover;e.fn.popover=function(n){return this.each(function(){var r=e(this),i=r.data("popover"),s=typeof n=="object"&&n;i||r.data("popover",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.popover.Constructor=t,e.fn.popover.defaults=e.extend({},e.fn.tooltip.defaults,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),e.fn.popover.noConflict=function(){return e.fn.popover=n,this}}(window.jQuery),!function(e){"use strict";function t(t,n){var r=e.proxy(this.process,this),i=e(t).is("body")?e(window):e(t),s;this.options=e.extend({},e.fn.scrollspy.defaults,n),this.$scrollElement=i.on("scroll.scroll-spy.data-api",r),this.selector=(this.options.target||(s=e(t).attr("href"))&&s.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.$body=e("body"),this.refresh(),this.process()}t.prototype={constructor:t,refresh:function(){var t=this,n;this.offsets=e([]),this.targets=e([]),n=this.$body.find(this.selector).map(function(){var n=e(this),r=n.data("target")||n.attr("href"),i=/^#\w/.test(r)&&e(r);return i&&i.length&&[[i.position().top+(!e.isWindow(t.$scrollElement.get(0))&&t.$scrollElement.scrollTop()),r]]||null}).sort(function(e,t){return e[0]-t[0]}).each(function(){t.offsets.push(this[0]),t.targets.push(this[1])})},process:function(){var e=this.$scrollElement.scrollTop()+this.options.offset,t=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,n=t-this.$scrollElement.height(),r=this.offsets,i=this.targets,s=this.activeTarget,o;if(e>=n)return s!=(o=i.last()[0])&&this.activate(o);for(o=r.length;o--;)s!=i[o]&&e>=r[o]&&(!r[o+1]||e<=r[o+1])&&this.activate(i[o])},activate:function(t){var n,r;this.activeTarget=t,e(this.selector).parent(".active").removeClass("active"),r=this.selector+'[data-target="'+t+'"],'+this.selector+'[href="'+t+'"]',n=e(r).parent("li").addClass("active"),n.parent(".dropdown-menu").length&&(n=n.closest("li.dropdown").addClass("active")),n.trigger("activate")}};var n=e.fn.scrollspy;e.fn.scrollspy=function(n){return this.each(function(){var r=e(this),i=r.data("scrollspy"),s=typeof n=="object"&&n;i||r.data("scrollspy",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.scrollspy.Constructor=t,e.fn.scrollspy.defaults={offset:10},e.fn.scrollspy.noConflict=function(){return e.fn.scrollspy=n,this},e(window).on("load",function(){e('[data-spy="scroll"]').each(function(){var t=e(this);t.scrollspy(t.data())})})}(window.jQuery),!function(e){"use strict";var t=function(t){this.element=e(t)};t.prototype={constructor:t,show:function(){var t=this.element,n=t.closest("ul:not(.dropdown-menu)"),r=t.attr("data-target"),i,s,o;r||(r=t.attr("href"),r=r&&r.replace(/.*(?=#[^\s]*$)/,""));if(t.parent("li").hasClass("active"))return;i=n.find(".active:last a")[0],o=e.Event("show",{relatedTarget:i}),t.trigger(o);if(o.isDefaultPrevented())return;s=e(r),this.activate(t.parent("li"),n),this.activate(s,s.parent(),function(){t.trigger({type:"shown",relatedTarget:i})})},activate:function(t,n,r){function o(){i.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),t.addClass("active"),s?(t[0].offsetWidth,t.addClass("in")):t.removeClass("fade"),t.parent(".dropdown-menu")&&t.closest("li.dropdown").addClass("active"),r&&r()}var i=n.find("> .active"),s=r&&e.support.transition&&i.hasClass("fade");s?i.one(e.support.transition.end,o):o(),i.removeClass("in")}};var n=e.fn.tab;e.fn.tab=function(n){return this.each(function(){var r=e(this),i=r.data("tab");i||r.data("tab",i=new t(this)),typeof n=="string"&&i[n]()})},e.fn.tab.Constructor=t,e.fn.tab.noConflict=function(){return e.fn.tab=n,this},e(document).on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(t){t.preventDefault(),e(this).tab("show")})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.typeahead.defaults,n),this.matcher=this.options.matcher||this.matcher,this.sorter=this.options.sorter||this.sorter,this.highlighter=this.options.highlighter||this.highlighter,this.updater=this.options.updater||this.updater,this.source=this.options.source,this.$menu=e(this.options.menu),this.shown=!1,this.listen()};t.prototype={constructor:t,select:function(){var e=this.$menu.find(".active").attr("data-value");return this.$element.val(this.updater(e)).change(),this.hide()},updater:function(e){return e},show:function(){var t=e.extend({},this.$element.position(),{height:this.$element[0].offsetHeight});return this.$menu.insertAfter(this.$element).css({top:t.top+t.height,left:t.left}).show(),this.shown=!0,this},hide:function(){return this.$menu.hide(),this.shown=!1,this},lookup:function(t){var n;return this.query=this.$element.val(),!this.query||this.query.length<this.options.minLength?this.shown?this.hide():this:(n=e.isFunction(this.source)?this.source(this.query,e.proxy(this.process,this)):this.source,n?this.process(n):this)},process:function(t){var n=this;return t=e.grep(t,function(e){return n.matcher(e)}),t=this.sorter(t),t.length?this.render(t.slice(0,this.options.items)).show():this.shown?this.hide():this},matcher:function(e){return~e.toLowerCase().indexOf(this.query.toLowerCase())},sorter:function(e){var t=[],n=[],r=[],i;while(i=e.shift())i.toLowerCase().indexOf(this.query.toLowerCase())?~i.indexOf(this.query)?n.push(i):r.push(i):t.push(i);return t.concat(n,r)},highlighter:function(e){var t=this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");return e.replace(new RegExp("("+t+")","ig"),function(e,t){return"<strong>"+t+"</strong>"})},render:function(t){var n=this;return t=e(t).map(function(t,r){return t=e(n.options.item).attr("data-value",r),t.find("a").html(n.highlighter(r)),t[0]}),t.first().addClass("active"),this.$menu.html(t),this},next:function(t){var n=this.$menu.find(".active").removeClass("active"),r=n.next();r.length||(r=e(this.$menu.find("li")[0])),r.addClass("active")},prev:function(e){var t=this.$menu.find(".active").removeClass("active"),n=t.prev();n.length||(n=this.$menu.find("li").last()),n.addClass("active")},listen:function(){this.$element.on("focus",e.proxy(this.focus,this)).on("blur",e.proxy(this.blur,this)).on("keypress",e.proxy(this.keypress,this)).on("keyup",e.proxy(this.keyup,this)),this.eventSupported("keydown")&&this.$element.on("keydown",e.proxy(this.keydown,this)),this.$menu.on("click",e.proxy(this.click,this)).on("mouseenter","li",e.proxy(this.mouseenter,this)).on("mouseleave","li",e.proxy(this.mouseleave,this))},eventSupported:function(e){var t=e in this.$element;return t||(this.$element.setAttribute(e,"return;"),t=typeof this.$element[e]=="function"),t},move:function(e){if(!this.shown)return;switch(e.keyCode){case 9:case 13:case 27:e.preventDefault();break;case 38:e.preventDefault(),this.prev();break;case 40:e.preventDefault(),this.next()}e.stopPropagation()},keydown:function(t){this.suppressKeyPressRepeat=~e.inArray(t.keyCode,[40,38,9,13,27]),this.move(t)},keypress:function(e){if(this.suppressKeyPressRepeat)return;this.move(e)},keyup:function(e){switch(e.keyCode){case 40:case 38:case 16:case 17:case 18:break;case 9:case 13:if(!this.shown)return;this.select();break;case 27:if(!this.shown)return;this.hide();break;default:this.lookup()}e.stopPropagation(),e.preventDefault()},focus:function(e){this.focused=!0},blur:function(e){this.focused=!1,!this.mousedover&&this.shown&&this.hide()},click:function(e){e.stopPropagation(),e.preventDefault(),this.select(),this.$element.focus()},mouseenter:function(t){this.mousedover=!0,this.$menu.find(".active").removeClass("active"),e(t.currentTarget).addClass("active")},mouseleave:function(e){this.mousedover=!1,!this.focused&&this.shown&&this.hide()}};var n=e.fn.typeahead;e.fn.typeahead=function(n){return this.each(function(){var r=e(this),i=r.data("typeahead"),s=typeof n=="object"&&n;i||r.data("typeahead",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.typeahead.defaults={source:[],items:8,menu:'<ul class="typeahead dropdown-menu"></ul>',item:'<li><a href="#"></a></li>',minLength:1},e.fn.typeahead.Constructor=t,e.fn.typeahead.noConflict=function(){return e.fn.typeahead=n,this},e(document).on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(t){var n=e(this);if(n.data("typeahead"))return;n.typeahead(n.data())})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.options=e.extend({},e.fn.affix.defaults,n),this.$window=e(window).on("scroll.affix.data-api",e.proxy(this.checkPosition,this)).on("click.affix.data-api",e.proxy(function(){setTimeout(e.proxy(this.checkPosition,this),1)},this)),this.$element=e(t),this.checkPosition()};t.prototype.checkPosition=function(){if(!this.$element.is(":visible"))return;var t=e(document).height(),n=this.$window.scrollTop(),r=this.$element.offset(),i=this.options.offset,s=i.bottom,o=i.top,u="affix affix-top affix-bottom",a;typeof i!="object"&&(s=o=i),typeof o=="function"&&(o=i.top()),typeof s=="function"&&(s=i.bottom()),a=this.unpin!=null&&n+this.unpin<=r.top?!1:s!=null&&r.top+this.$element.height()>=t-s?"bottom":o!=null&&n<=o?"top":!1;if(this.affixed===a)return;this.affixed=a,this.unpin=a=="bottom"?r.top-n:null,this.$element.removeClass(u).addClass("affix"+(a?"-"+a:""))};var n=e.fn.affix;e.fn.affix=function(n){return this.each(function(){var r=e(this),i=r.data("affix"),s=typeof n=="object"&&n;i||r.data("affix",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.affix.Constructor=t,e.fn.affix.defaults={offset:0},e.fn.affix.noConflict=function(){return e.fn.affix=n,this},e(window).on("load",function(){e('[data-spy="affix"]').each(function(){var t=e(this),n=t.data();n.offset=n.offset||{},n.offsetBottom&&(n.offset.bottom=n.offsetBottom),n.offsetTop&&(n.offset.top=n.offsetTop),t.affix(n)})})}(window.jQuery);
\ No newline at end of file
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
*/ */
// you may need to adjust this path to the correct Yii framework path // you may need to adjust this path to the correct Yii framework path
$frameworkPath = dirname(__FILE__) . '/../../../yii'; $frameworkPath = dirname(__FILE__) . '/../../yii';
require_once($frameworkPath . '/requirements/YiiRequirementChecker.php'); require_once($frameworkPath . '/requirements/YiiRequirementChecker.php');
$requirementsChecker = new YiiRequirementChecker(); $requirementsChecker = new YiiRequirementChecker();
...@@ -93,4 +93,4 @@ $requirements = array( ...@@ -93,4 +93,4 @@ $requirements = array(
'memo' => 'PHP mail SMTP server required', 'memo' => 'PHP mail SMTP server required',
), ),
); );
$requirementsChecker->checkYii()->check($requirements)->render(); $requirementsChecker->checkYii()->check($requirements)->render();
\ No newline at end of file
...@@ -27,7 +27,7 @@ $this->registerAssetBundle('app'); ...@@ -27,7 +27,7 @@ $this->registerAssetBundle('app');
<div class="navbar"> <div class="navbar">
<div class="navbar-inner"> <div class="navbar-inner">
<div class="container"> <div class="container">
<?php echo Menu::widget($this, array( <?php echo Menu::widget(array(
'options' => array('class' => 'nav'), 'options' => array('class' => 'nav'),
'items' => array( 'items' => array(
array('label' => 'Home', 'url' => array('/site/index')), array('label' => 'Home', 'url' => array('/site/index')),
...@@ -44,7 +44,7 @@ $this->registerAssetBundle('app'); ...@@ -44,7 +44,7 @@ $this->registerAssetBundle('app');
<!-- /.navbar --> <!-- /.navbar -->
</div> </div>
<?php echo Breadcrumbs::widget($this, array( <?php echo Breadcrumbs::widget(array(
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : array(), 'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : array(),
)); ?> )); ?>
<?php echo $content; ?> <?php echo $content; ?>
...@@ -60,7 +60,7 @@ $this->registerAssetBundle('app'); ...@@ -60,7 +60,7 @@ $this->registerAssetBundle('app');
</div> </div>
<?php $this->endBody(); ?> <?php $this->endBody(); ?>
</div> </div>
<?php echo Toolbar::widget($this); ?> <?php echo Toolbar::widget(); ?>
</body> </body>
</html> </html>
<?php $this->endPage(); ?> <?php $this->endPage(); ?>
...@@ -23,7 +23,7 @@ $this->params['breadcrumbs'][] = $this->title; ...@@ -23,7 +23,7 @@ $this->params['breadcrumbs'][] = $this->title;
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you. If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p> </p>
<?php $form = ActiveForm::begin($this, array( <?php $form = ActiveForm::begin(array(
'options' => array('class' => 'form-horizontal'), 'options' => array('class' => 'form-horizontal'),
'fieldConfig' => array('inputOptions' => array('class' => 'input-xlarge')), 'fieldConfig' => array('inputOptions' => array('class' => 'input-xlarge')),
)); ?> )); ?>
...@@ -35,7 +35,7 @@ $this->params['breadcrumbs'][] = $this->title; ...@@ -35,7 +35,7 @@ $this->params['breadcrumbs'][] = $this->title;
$field = $form->field($model, 'verifyCode'); $field = $form->field($model, 'verifyCode');
echo $field->begin() echo $field->begin()
. $field->label() . $field->label()
. Captcha::widget($this) . Captcha::widget()
. Html::activeTextInput($model, 'verifyCode', array('class' => 'input-medium')) . Html::activeTextInput($model, 'verifyCode', array('class' => 'input-medium'))
. $field->error() . $field->error()
. $field->end(); . $field->end();
......
...@@ -14,7 +14,7 @@ $this->params['breadcrumbs'][] = $this->title; ...@@ -14,7 +14,7 @@ $this->params['breadcrumbs'][] = $this->title;
<p>Please fill out the following fields to login:</p> <p>Please fill out the following fields to login:</p>
<?php $form = ActiveForm::begin($this, array('options' => array('class' => 'form-horizontal'))); ?> <?php $form = ActiveForm::begin(array('options' => array('class' => 'form-horizontal'))); ?>
<?php echo $form->field($model, 'username')->textInput(); ?> <?php echo $form->field($model, 'username')->textInput(); ?>
<?php echo $form->field($model, 'password')->passwordInput(); ?> <?php echo $form->field($model, 'password')->passwordInput(); ?>
<?php echo $form->field($model, 'rememberMe')->checkbox(); ?> <?php echo $form->field($model, 'rememberMe')->checkbox(); ?>
......
...@@ -3,12 +3,10 @@ ...@@ -3,12 +3,10 @@
// comment out the following line to disable debug mode // comment out the following line to disable debug mode
defined('YII_DEBUG') or define('YII_DEBUG', true); defined('YII_DEBUG') or define('YII_DEBUG', true);
$frameworkPath = __DIR__ . '/../../yii'; require(__DIR__ . '/../vendor/yiisoft/yii2/yii.php');
require(__DIR__ . '/../vendor/autoload.php');
require($frameworkPath . '/Yii.php'); $config = require(__DIR__ . '/../config/main.php');
// Register Composer autoloader
@include($frameworkPath . '/vendor/autoload.php');
$config = require(__DIR__ . '/protected/config/main.php');
$application = new yii\web\Application($config); $application = new yii\web\Application($config);
$application->run(); $application->run();
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/** /**
* Yii command line script for Unix/Linux. * Yii console bootstrap file.
*
* This is the bootstrap script for running yiic on Unix/Linux.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
require_once(__DIR__ . '/yiic.php'); defined('YII_DEBUG') or define('YII_DEBUG', true);
// fcgi doesn't have STDIN defined by default
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
$frameworkPath = __DIR__ . '/../../yii';
require($frameworkPath . '/Yii.php');
$config = require(__DIR__ . '/config/console.php');
$application = new yii\console\Application($config);
$application->run();
@echo off @echo off
rem ------------------------------------------------------------- rem -------------------------------------------------------------
rem Yii command line script for Windows. rem Yii command line bootstrap script for Windows.
rem
rem This is the bootstrap script for running yiic on Windows.
rem rem
rem @author Qiang Xue <qiang.xue@gmail.com> rem @author Qiang Xue <qiang.xue@gmail.com>
rem @link http://www.yiiframework.com/ rem @link http://www.yiiframework.com/
...@@ -17,6 +15,6 @@ set YII_PATH=%~dp0 ...@@ -17,6 +15,6 @@ set YII_PATH=%~dp0
if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe
"%PHP_COMMAND%" "%YII_PATH%yiic" %* "%PHP_COMMAND%" "%YII_PATH%yii" %*
@endlocal @endlocal
\ No newline at end of file
...@@ -13,7 +13,7 @@ defined('STDIN') or define('STDIN', fopen('php://stdin', 'r')); ...@@ -13,7 +13,7 @@ defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
require(__DIR__ . '/../yii/Yii.php'); require(__DIR__ . '/../yii/Yii.php');
$id = 'yiic-build'; $id = 'yii-build';
$basePath = __DIR__; $basePath = __DIR__;
$application = new yii\console\Application(array('id' => $id, 'basePath' => $basePath)); $application = new yii\console\Application(array('id' => $id, 'basePath' => $basePath));
......
...@@ -94,7 +94,7 @@ ...@@ -94,7 +94,7 @@
</fileset> </fileset>
<fileset dir="." id="executables"> <fileset dir="." id="executables">
<include name="${build.src.dir}/**/yiic" /> <include name="${build.src.dir}/**/yii" />
</fileset> </fileset>
<target name="src" depends="sync"> <target name="src" depends="sync">
......
...@@ -93,7 +93,7 @@ class LocaleController extends Controller ...@@ -93,7 +93,7 @@ class LocaleController extends Controller
/** /**
* Plural rules. * Plural rules.
* *
* This file is automatically generated by the "yiic locale/plural" command under the "build" folder. * This file is automatically generated by the "yii locale/plural" command under the "build" folder.
* Do not modify it directly. * Do not modify it directly.
* *
* The original plural rule data used for generating this file has the following copyright terms: * The original plural rule data used for generating this file has the following copyright terms:
......
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file"
],
"hash": "7d46ce9c4d8d5f4ecae1611ea8f0b49c",
"packages": [
{
"name": "ezyang/htmlpurifier",
"version": "v4.5.0",
"source": {
"type": "git",
"url": "https://github.com/ezyang/htmlpurifier.git",
"reference": "v4.5.0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/ezyang/htmlpurifier/zipball/v4.5.0",
"reference": "v4.5.0",
"shasum": ""
},
"require": {
"php": ">=5.2"
},
"type": "library",
"autoload": {
"psr-0": {
"HTMLPurifier": "library/"
},
"files": [
"library/HTMLPurifier.composer.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL"
],
"authors": [
{
"name": "Edward Z. Yang",
"email": "admin@htmlpurifier.org",
"homepage": "http://ezyang.com"
}
],
"description": "Standards compliant HTML filter written in PHP",
"homepage": "http://htmlpurifier.org/",
"keywords": [
"html"
],
"time": "2013-02-18 00:04:08"
},
{
"name": "michelf/php-markdown",
"version": "1.3",
"source": {
"type": "git",
"url": "https://github.com/michelf/php-markdown.git",
"reference": "1.3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/michelf/php-markdown/zipball/1.3",
"reference": "1.3",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-lib": "1.3.x-dev"
}
},
"autoload": {
"psr-0": {
"Michelf": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Michel Fortin",
"email": "michel.fortin@michelf.ca",
"homepage": "http://michelf.ca/",
"role": "Developer"
},
{
"name": "John Gruber",
"homepage": "http://daringfireball.net/"
}
],
"description": "PHP Markdown",
"homepage": "http://michelf.ca/projects/php-markdown/",
"keywords": [
"markdown"
],
"time": "2013-04-11 18:53:11"
},
{
"name": "smarty/smarty",
"version": "v3.1.13",
"source": {
"type": "svn",
"url": "http://smarty-php.googlecode.com/svn",
"reference": "/tags/v3.1.13/@4699"
},
"require": {
"php": ">=5.2"
},
"type": "library",
"autoload": {
"classmap": [
"distribution/libs/Smarty.class.php",
"distribution/libs/SmartyBC.class.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-3.0"
],
"authors": [
{
"name": "Monte Ohrt",
"email": "monte@ohrt.com"
},
{
"name": "Uwe Tews",
"email": "uwe.tews@googlemail.com"
},
{
"name": "Rodney Rehm",
"email": "rodney.rehm@medialize.de"
}
],
"description": "Smarty - the compiling PHP template engine",
"homepage": "http://www.smarty.net",
"keywords": [
"templating"
],
"time": "2013-01-26 12:03:52"
},
{
"name": "twig/twig",
"version": "v1.12.3",
"source": {
"type": "git",
"url": "https://github.com/fabpot/Twig.git",
"reference": "v1.12.3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/fabpot/Twig/zipball/v1.12.3",
"reference": "v1.12.3",
"shasum": ""
},
"require": {
"php": ">=5.2.4"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.12-dev"
}
},
"autoload": {
"psr-0": {
"Twig_": "lib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Armin Ronacher",
"email": "armin.ronacher@active-4.com"
}
],
"description": "Twig, the flexible, fast, and secure template language for PHP",
"homepage": "http://twig.sensiolabs.org",
"keywords": [
"templating"
],
"time": "2013-04-08 12:40:11"
}
],
"packages-dev": [
],
"aliases": [
],
"minimum-stability": "stable",
"stability-flags": [
],
"platform": {
"php": ">=5.3.0"
},
"platform-dev": [
]
}
...@@ -446,3 +446,7 @@ $customers = Customer::find()->olderThan(50)->all(); ...@@ -446,3 +446,7 @@ $customers = Customer::find()->olderThan(50)->all();
The parameters should follow after the `$query` parameter when defining the scope method, and they The parameters should follow after the `$query` parameter when defining the scope method, and they
can take default values like shown above. can take default values like shown above.
### Atomic operations and scenarios
TBD
...@@ -28,10 +28,9 @@ app/ ...@@ -28,10 +28,9 @@ app/
img/ containing image files img/ containing image files
themes/ containing application themes themes/ containing application themes
protected/ containing protected application files protected/ containing protected application files
yiic yiic command line script for Unix/Linux yii yii command line script for Unix/Linux
yiic.bat yiic command line script for Windows yii.bat yii command line script for Windows
yiic.php yiic command line PHP script commands/ containing customized yii console commands
commands/ containing customized 'yiic' commands
components/ containing reusable user components components/ containing reusable user components
config/ containing configuration files config/ containing configuration files
console.php the console application configuration console.php the console application configuration
...@@ -60,4 +59,4 @@ app/ ...@@ -60,4 +59,4 @@ app/
~~~ ~~~
TBD TBD
\ No newline at end of file
...@@ -19,7 +19,7 @@ The following steps show how we can use database migration during development: ...@@ -19,7 +19,7 @@ The following steps show how we can use database migration during development:
4. Doug applies the migration to his local development database 4. Doug applies the migration to his local development database
Yii supports database migration via the `yiic migrate` command line tool. This Yii supports database migration via the `yii migrate` command line tool. This
tool supports creating new migrations, applying/reverting/redoing migrations, and tool supports creating new migrations, applying/reverting/redoing migrations, and
showing migration history and new migrations. showing migration history and new migrations.
...@@ -29,7 +29,7 @@ Creating Migrations ...@@ -29,7 +29,7 @@ Creating Migrations
To create a new migration (e.g. create a news table), we run the following command: To create a new migration (e.g. create a news table), we run the following command:
~~~ ~~~
yiic migrate/create <name> yii migrate/create <name>
~~~ ~~~
The required `name` parameter specifies a very brief description of the migration The required `name` parameter specifies a very brief description of the migration
...@@ -38,7 +38,7 @@ is used as part of a PHP class name. Therefore, it should only contain letters, ...@@ -38,7 +38,7 @@ is used as part of a PHP class name. Therefore, it should only contain letters,
digits and/or underscore characters. digits and/or underscore characters.
~~~ ~~~
yiic migrate/create create_news_table yii migrate/create create_news_table
~~~ ~~~
The above command will create under the `protected/migrations` directory a new The above command will create under the `protected/migrations` directory a new
...@@ -153,7 +153,7 @@ To apply all available new migrations (i.e., make the local database up-to-date) ...@@ -153,7 +153,7 @@ To apply all available new migrations (i.e., make the local database up-to-date)
run the following command: run the following command:
~~~ ~~~
yiic migrate yii migrate
~~~ ~~~
The command will show the list of all new migrations. If you confirm to apply The command will show the list of all new migrations. If you confirm to apply
...@@ -170,7 +170,7 @@ Sometimes, we may only want to apply one or a few new migrations. We can use the ...@@ -170,7 +170,7 @@ Sometimes, we may only want to apply one or a few new migrations. We can use the
following command: following command:
~~~ ~~~
yiic migrate/up 3 yii migrate/up 3
~~~ ~~~
This command will apply the 3 new migrations. Changing the value 3 will allow This command will apply the 3 new migrations. Changing the value 3 will allow
...@@ -179,7 +179,7 @@ us to change the number of migrations to be applied. ...@@ -179,7 +179,7 @@ us to change the number of migrations to be applied.
We can also migrate the database to a specific version with the following command: We can also migrate the database to a specific version with the following command:
~~~ ~~~
yiic migrate/to 101129_185401 yii migrate/to 101129_185401
~~~ ~~~
That is, we use the timestamp part of a migration name to specify the version That is, we use the timestamp part of a migration name to specify the version
...@@ -196,7 +196,7 @@ To revert the last one or several applied migrations, we can use the following ...@@ -196,7 +196,7 @@ To revert the last one or several applied migrations, we can use the following
command: command:
~~~ ~~~
yiic migrate/down [step] yii migrate/down [step]
~~~ ~~~
where the optional `step` parameter specifies how many migrations to be reverted where the optional `step` parameter specifies how many migrations to be reverted
...@@ -213,7 +213,7 @@ Redoing migrations means first reverting and then applying the specified migrati ...@@ -213,7 +213,7 @@ Redoing migrations means first reverting and then applying the specified migrati
This can be done with the following command: This can be done with the following command:
~~~ ~~~
yiic migrate/redo [step] yii migrate/redo [step]
~~~ ~~~
where the optional `step` parameter specifies how many migrations to be redone. where the optional `step` parameter specifies how many migrations to be redone.
...@@ -227,8 +227,8 @@ Besides applying and reverting migrations, the migration tool can also display ...@@ -227,8 +227,8 @@ Besides applying and reverting migrations, the migration tool can also display
the migration history and the new migrations to be applied. the migration history and the new migrations to be applied.
~~~ ~~~
yiic migrate/history [limit] yii migrate/history [limit]
yiic migrate/new [limit] yii migrate/new [limit]
~~~ ~~~
where the optional parameter `limit` specifies the number of migrations to be where the optional parameter `limit` specifies the number of migrations to be
...@@ -247,10 +247,10 @@ often happens when developing a new migration. We can use the following command ...@@ -247,10 +247,10 @@ often happens when developing a new migration. We can use the following command
to achieve this goal. to achieve this goal.
~~~ ~~~
yiic migrate/mark 101129_185401 yii migrate/mark 101129_185401
~~~ ~~~
This command is very similar to `yiic migrate/to` command, except that it only This command is very similar to `yii migrate/to` command, except that it only
modifies the migration history table to the specified version without applying modifies the migration history table to the specified version without applying
or reverting the migrations. or reverting the migrations.
...@@ -291,7 +291,7 @@ line: ...@@ -291,7 +291,7 @@ line:
To specify these options, execute the migrate command using the following format To specify these options, execute the migrate command using the following format
~~~ ~~~
yiic migrate/up --option1=value1 --option2=value2 ... yii migrate/up --option1=value1 --option2=value2 ...
~~~ ~~~
For example, if we want to migrate for a `forum` module whose migration files For example, if we want to migrate for a `forum` module whose migration files
...@@ -299,7 +299,7 @@ are located within the module's `migrations` directory, we can use the following ...@@ -299,7 +299,7 @@ are located within the module's `migrations` directory, we can use the following
command: command:
~~~ ~~~
yiic migrate/up --migrationPath=ext.forum.migrations yii migrate/up --migrationPath=ext.forum.migrations
~~~ ~~~
......
...@@ -152,7 +152,7 @@ with significant improvements. For more details, please see the "assets" subsect ...@@ -152,7 +152,7 @@ with significant improvements. For more details, please see the "assets" subsect
While Yii 2.0 continues to use PHP as its main template language, it comes with built-in While Yii 2.0 continues to use PHP as its main template language, it comes with built-in
support for two popular template engines: Smarty and Twig. The Prado template engine is support for two popular template engines: Smarty and Twig. The Prado template engine is
no longer supported. To use these template engines, you just need to use `tpl` as the file no longer supported. To use these template engines, you just need to use `tpl` as the file
extension for your Smarty views, or `twig` for Twig views. You may also configure the extension for your Smarty views, or `twig` for Twig views. You may also configure the
`View::renderers` property to use other template engines. `View::renderers` property to use other template engines.
...@@ -218,7 +218,7 @@ methods of the `Widget` class. For example, ...@@ -218,7 +218,7 @@ methods of the `Widget` class. For example,
```php ```php
// $this refers to the View object // $this refers to the View object
// Note that you have to "echo" the result to display it // Note that you have to "echo" the result to display it
echo \yii\widgets\Menu::widget($this, array('items' => $items)); echo \yii\widgets\Menu::widget(array('items' => $items));
// $this refers to the View object // $this refers to the View object
$form = \yii\widgets\ActiveForm::begin($this); $form = \yii\widgets\ActiveForm::begin($this);
...@@ -252,7 +252,7 @@ Console applications are now composed by controllers, too, like Web applications ...@@ -252,7 +252,7 @@ Console applications are now composed by controllers, too, like Web applications
console controllers and Web controllers share the same base controller class. console controllers and Web controllers share the same base controller class.
Each console controller is like `CConsoleCommand` in 1.1. It consists of one or several Each console controller is like `CConsoleCommand` in 1.1. It consists of one or several
actions. You use the `yiic <route>` command to execute a console command, where `<route>` actions. You use the `yii <route>` command to execute a console command, where `<route>`
stands for a controller route (e.g. `sitemap/index`). Additional anonymous arguments stands for a controller route (e.g. `sitemap/index`). Additional anonymous arguments
are passed as the parameters to the corresponding controller action method, and named arguments are passed as the parameters to the corresponding controller action method, and named arguments
are treated as global options declared in `globalOptions()`. are treated as global options declared in `globalOptions()`.
...@@ -269,10 +269,6 @@ Message translation is still supported, but managed via the "i18n" application c ...@@ -269,10 +269,6 @@ Message translation is still supported, but managed via the "i18n" application c
The component manages a set of message sources, which allows you to use different message The component manages a set of message sources, which allows you to use different message
sources based on message categories. For more information, see the class documentation for `I18N`. sources based on message categories. For more information, see the class documentation for `I18N`.
The message translation method is changed by merging the message category into the message being
translated. For example, `Yii::t('yii|message to be translated')`.
Action Filters Action Filters
-------------- --------------
......
ActiveRecord ActiveRecord
============ ============
Scenarios
---------
Possible scenario formats supported by ActiveRecord:
```php
public function scenarios()
{
return array(
// attributes array, all operations won't be wrapped with transaction
'scenario1' => array('attribute1', 'attribute2'),
// insert and update operations will be wrapped with transaction, delete won't be wrapped
'scenario2' => array(
'attributes' => array('attribute1', 'attribute2'),
'atomic' => array(self::OP_INSERT, self::OP_UPDATE),
),
);
}
```
Query Query
----- -----
### Basic Queries ### Basic Queries
### Relational Queries ### Relational Queries
### Scopes ### Scopes
...@@ -45,6 +45,9 @@ class YiiBaseTest extends TestCase ...@@ -45,6 +45,9 @@ class YiiBaseTest extends TestCase
Yii::setAlias('@yii', null); Yii::setAlias('@yii', null);
$this->assertFalse(Yii::getAlias('@yii', false)); $this->assertFalse(Yii::getAlias('@yii', false));
$this->assertEquals('/yii/gii/file', Yii::getAlias('@yii/gii/file')); $this->assertEquals('/yii/gii/file', Yii::getAlias('@yii/gii/file'));
Yii::setAlias('@some/alias', '/www');
$this->assertEquals('/www', Yii::getAlias('@some/alias'));
} }
public function testGetVersion() public function testGetVersion()
......
<?php
namespace yiiunit\framework\base;
use yii\base\Dictionary;
class MapItem
{
public $data='data';
}
class DictionaryTest extends \yiiunit\TestCase
{
/**
* @var \yii\base\Dictionary
*/
protected $dictionary;
protected $item1;
protected $item2;
protected $item3;
protected function setUp()
{
parent::setUp();
$this->dictionary = new Dictionary;
$this->item1 = new MapItem;
$this->item2 = new MapItem;
$this->item3 = new MapItem;
$this->dictionary->add('key1', $this->item1);
$this->dictionary->add('key2', $this->item2);
}
protected function tearDown()
{
parent::tearDown();
$this->dictionary = null;
$this->item1 = null;
$this->item2 = null;
$this->item3 = null;
}
public function testConstruct()
{
$a = array(1, 2, 'key3' => 3);
$dictionary = new Dictionary($a);
$this->assertEquals(3, $dictionary->getCount());
$dictionary2=new Dictionary($this->dictionary);
$this->assertEquals(2, $dictionary2->getCount());
}
public function testGetCount()
{
$this->assertEquals(2, $this->dictionary->getCount());
}
public function testGetKeys()
{
$keys = $this->dictionary->getKeys();
$this->assertEquals(2, count($keys));
$this->assertEquals('key1', $keys[0]);
$this->assertEquals('key2', $keys[1]);
}
public function testAdd()
{
$this->dictionary->add('key3', $this->item3);
$this->assertEquals(3, $this->dictionary->getCount());
$this->assertTrue($this->dictionary->has('key3'));
$this->dictionary[] = 'test';
}
public function testRemove()
{
$this->dictionary->remove('key1');
$this->assertEquals(1, $this->dictionary->getCount());
$this->assertTrue(!$this->dictionary->has('key1'));
$this->assertTrue($this->dictionary->remove('unknown key') === null);
}
public function testRemoveAll()
{
$this->dictionary->add('key3', $this->item3);
$this->dictionary->removeAll();
$this->assertEquals(0, $this->dictionary->getCount());
$this->assertTrue(!$this->dictionary->has('key1') && !$this->dictionary->has('key2'));
$this->dictionary->add('key3', $this->item3);
$this->dictionary->removeAll(true);
$this->assertEquals(0, $this->dictionary->getCount());
$this->assertTrue(!$this->dictionary->has('key1') && !$this->dictionary->has('key2'));
}
public function testHas()
{
$this->assertTrue($this->dictionary->has('key1'));
$this->assertTrue($this->dictionary->has('key2'));
$this->assertFalse($this->dictionary->has('key3'));
}
public function testFromArray()
{
$array = array('key3' => $this->item3, 'key4' => $this->item1);
$this->dictionary->copyFrom($array);
$this->assertEquals(2, $this->dictionary->getCount());
$this->assertEquals($this->item3, $this->dictionary['key3']);
$this->assertEquals($this->item1, $this->dictionary['key4']);
$this->setExpectedException('yii\base\InvalidParamException');
$this->dictionary->copyFrom($this);
}
public function testMergeWith()
{
$a = array('a' => 'v1', 'v2', array('2'), 'c' => array('3', 'c' => 'a'));
$b = array('v22', 'a' => 'v11', array('2'), 'c' => array('c' => '3', 'a'));
$c = array('a' => 'v11', 'v2', array('2'), 'c' => array('3', 'c' => '3', 'a'), 'v22', array('2'));
$dictionary = new Dictionary($a);
$dictionary2 = new Dictionary($b);
$dictionary->mergeWith($dictionary2);
$this->assertTrue($dictionary->toArray() === $c);
$array = array('key2' => $this->item1, 'key3' => $this->item3);
$this->dictionary->mergeWith($array, false);
$this->assertEquals(3, $this->dictionary->getCount());
$this->assertEquals($this->item1, $this->dictionary['key2']);
$this->assertEquals($this->item3, $this->dictionary['key3']);
$this->setExpectedException('yii\base\InvalidParamException');
$this->dictionary->mergeWith($this, false);
}
public function testRecursiveMergeWithTraversable(){
$dictionary = new Dictionary();
$obj = new \ArrayObject(array(
'k1' => $this->item1,
'k2' => $this->item2,
'k3' => new \ArrayObject(array(
'k4' => $this->item3,
))
));
$dictionary->mergeWith($obj, true);
$this->assertEquals(3, $dictionary->getCount());
$this->assertEquals($this->item1, $dictionary['k1']);
$this->assertEquals($this->item2, $dictionary['k2']);
$this->assertEquals($this->item3, $dictionary['k3']['k4']);
}
public function testArrayRead()
{
$this->assertEquals($this->item1, $this->dictionary['key1']);
$this->assertEquals($this->item2, $this->dictionary['key2']);
$this->assertEquals(null, $this->dictionary['key3']);
}
public function testArrayWrite()
{
$this->dictionary['key3'] = $this->item3;
$this->assertEquals(3, $this->dictionary->getCount());
$this->assertEquals($this->item3, $this->dictionary['key3']);
$this->dictionary['key1'] = $this->item3;
$this->assertEquals(3, $this->dictionary->getCount());
$this->assertEquals($this->item3, $this->dictionary['key1']);
unset($this->dictionary['key2']);
$this->assertEquals(2, $this->dictionary->getCount());
$this->assertTrue(!$this->dictionary->has('key2'));
unset($this->dictionary['unknown key']);
}
public function testArrayForeach()
{
$n = 0;
$found = 0;
foreach ($this->dictionary as $index => $item) {
$n++;
if ($index === 'key1' && $item === $this->item1) {
$found++;
}
if ($index === 'key2' && $item === $this->item2) {
$found++;
}
}
$this->assertTrue($n == 2 && $found == 2);
}
public function testArrayMisc()
{
$this->assertEquals($this->dictionary->Count, count($this->dictionary));
$this->assertTrue(isset($this->dictionary['key1']));
$this->assertFalse(isset($this->dictionary['unknown key']));
}
public function testToArray()
{
$dictionary = new Dictionary(array('key' => 'value'));
$this->assertEquals(array('key' => 'value'), $dictionary->toArray());
}
public function testIteratorCurrent()
{
$dictionary = new Dictionary(array('key1' => 'value1', 'key2' => 'value2'));
$val = $dictionary->getIterator()->current();
$this->assertEquals('value1', $val);
}
}
...@@ -12,7 +12,7 @@ use yiiunit\data\base\InvalidRulesModel; ...@@ -12,7 +12,7 @@ use yiiunit\data\base\InvalidRulesModel;
*/ */
class ModelTest extends TestCase class ModelTest extends TestCase
{ {
public function testGetAttributeLalel() public function testGetAttributeLabel()
{ {
$speaker = new Speaker(); $speaker = new Speaker();
$this->assertEquals('First Name', $speaker->getAttributeLabel('firstName')); $this->assertEquals('First Name', $speaker->getAttributeLabel('firstName'));
......
<?php
namespace yiiunit\framework\base;
use yii\base\Vector;
class ListItem
{
public $data='data';
}
class VectorTest extends \yiiunit\TestCase
{
/**
* @var Vector
*/
protected $vector;
protected $item1;
protected $item2;
protected $item3;
protected function setUp()
{
parent::setUp();
$this->vector = new Vector;
$this->item1 = new ListItem;
$this->item2 = new ListItem;
$this->item3 = new ListItem;
$this->vector->add($this->item1);
$this->vector->add($this->item2);
}
protected function tearDown()
{
parent::tearDown();
$this->vector = null;
$this->item1 = null;
$this->item2 = null;
$this->item3 = null;
}
public function testConstruct()
{
$a = array(1, 2, 3);
$vector = new Vector($a);
$this->assertEquals(3, $vector->getCount());
$vector2 = new Vector($this->vector);
$this->assertEquals(2, $vector2->getCount());
}
public function testItemAt()
{
$a = array(1, 2, null, 4);
$vector = new Vector($a);
$this->assertEquals(1, $vector->itemAt(0));
$this->assertEquals(2, $vector->itemAt(1));
$this->assertNull($vector->itemAt(2));
$this->assertEquals(4, $vector->itemAt(3));
}
public function testGetCount()
{
$this->assertEquals(2, $this->vector->getCount());
$this->assertEquals(2, $this->vector->Count);
}
public function testAdd()
{
$this->vector->add(null);
$this->vector->add($this->item3);
$this->assertEquals(4, $this->vector->getCount());
$this->assertEquals(3, $this->vector->indexOf($this->item3));
}
public function testInsertAt()
{
$this->vector->insertAt(0, $this->item3);
$this->assertEquals(3, $this->vector->getCount());
$this->assertEquals(2, $this->vector->indexOf($this->item2));
$this->assertEquals(0, $this->vector->indexOf($this->item3));
$this->assertEquals(1, $this->vector->indexOf($this->item1));
$this->setExpectedException('yii\base\InvalidParamException');
$this->vector->insertAt(4, $this->item3);
}
public function testRemove()
{
$this->vector->remove($this->item1);
$this->assertEquals(1, $this->vector->getCount());
$this->assertEquals(-1, $this->vector->indexOf($this->item1));
$this->assertEquals(0, $this->vector->indexOf($this->item2));
$this->assertEquals(false, $this->vector->remove($this->item1));
}
public function testRemoveAt()
{
$this->vector->add($this->item3);
$this->vector->removeAt(1);
$this->assertEquals(-1, $this->vector->indexOf($this->item2));
$this->assertEquals(1, $this->vector->indexOf($this->item3));
$this->assertEquals(0, $this->vector->indexOf($this->item1));
$this->setExpectedException('yii\base\InvalidParamException');
$this->vector->removeAt(2);
}
public function testRemoveAll()
{
$this->vector->add($this->item3);
$this->vector->removeAll();
$this->assertEquals(0, $this->vector->getCount());
$this->assertEquals(-1, $this->vector->indexOf($this->item1));
$this->assertEquals(-1, $this->vector->indexOf($this->item2));
$this->vector->add($this->item3);
$this->vector->removeAll(true);
$this->assertEquals(0, $this->vector->getCount());
$this->assertEquals(-1, $this->vector->indexOf($this->item1));
$this->assertEquals(-1, $this->vector->indexOf($this->item2));
}
public function testHas()
{
$this->assertTrue($this->vector->has($this->item1));
$this->assertTrue($this->vector->has($this->item2));
$this->assertFalse($this->vector->has($this->item3));
}
public function testIndexOf()
{
$this->assertEquals(0, $this->vector->indexOf($this->item1));
$this->assertEquals(1, $this->vector->indexOf($this->item2));
$this->assertEquals(-1, $this->vector->indexOf($this->item3));
}
public function testFromArray()
{
$array = array($this->item3, $this->item1);
$this->vector->copyFrom($array);
$this->assertTrue(count($array) == 2 && $this->vector[0] === $this->item3 && $this->vector[1] === $this->item1);
$this->setExpectedException('yii\base\InvalidParamException');
$this->vector->copyFrom($this);
}
public function testMergeWith()
{
$array = array($this->item3, $this->item1);
$this->vector->mergeWith($array);
$this->assertTrue($this->vector->getCount() == 4 && $this->vector[0] === $this->item1 &&
$this->vector[3] === $this->item1);
$a = array(1);
$vector = new Vector($a);
$this->vector->mergeWith($vector);
$this->assertTrue($this->vector->getCount() == 5 && $this->vector[0] === $this->item1 &&
$this->vector[3] === $this->item1 && $this->vector[4] === 1);
$this->setExpectedException('yii\base\InvalidParamException');
$this->vector->mergeWith($this);
}
public function testToArray()
{
$array = $this->vector->toArray();
$this->assertTrue(count($array) == 2 && $array[0] === $this->item1 && $array[1] === $this->item2);
}
public function testArrayRead()
{
$this->assertTrue($this->vector[0] === $this->item1);
$this->assertTrue($this->vector[1] === $this->item2);
$this->setExpectedException('yii\base\InvalidParamException');
$a = $this->vector[2];
}
public function testGetIterator()
{
$n = 0;
$found = 0;
foreach ($this->vector as $index => $item) {
foreach ($this->vector as $a => $b) {
// test of iterator
}
$n++;
if ($index === 0 && $item === $this->item1) {
$found++;
}
if ($index === 1 && $item === $this->item2) {
$found++;
}
}
$this->assertTrue($n == 2 && $found == 2);
}
public function testArrayMisc()
{
$this->assertEquals($this->vector->Count, count($this->vector));
$this->assertTrue(isset($this->vector[1]));
$this->assertFalse(isset($this->vector[2]));
}
public function testOffsetSetAdd()
{
$vector = new Vector(array(1, 2, 3));
$vector->offsetSet(null, 4);
$this->assertEquals(array(1, 2, 3, 4), $vector->toArray());
}
public function testOffsetSetReplace()
{
$vector = new Vector(array(1, 2, 3));
$vector->offsetSet(1, 4);
$this->assertEquals(array(1, 4, 3), $vector->toArray());
}
public function testOffsetUnset()
{
$vector = new Vector(array(1, 2, 3));
$vector->offsetUnset(1);
$this->assertEquals(array(1, 3), $vector->toArray());
}
public function testIteratorCurrent()
{
$vector = new Vector(array('value1', 'value2'));
$val = $vector->getIterator()->current();
$this->assertEquals('value1', $val);
}
}
<?php
use yiiunit\TestCase;
use yii\console\controllers\AssetController;
/**
* Unit test for [[\yii\console\controllers\AssetController]].
* @see AssetController
*/
class AssetControllerTest extends TestCase
{
/**
* @var string path for the test files.
*/
protected $testFilePath = '';
/**
* @var string test assets path.
*/
protected $testAssetsBasePath = '';
public function setUp()
{
$this->testFilePath = Yii::getAlias('@yiiunit/runtime') . DIRECTORY_SEPARATOR . get_class($this);
$this->createDir($this->testFilePath);
$this->testAssetsBasePath = $this->testFilePath . DIRECTORY_SEPARATOR . 'assets';
$this->createDir($this->testAssetsBasePath);
}
public function tearDown()
{
$this->removeDir($this->testFilePath);
}
/**
* Creates directory.
* @param $dirName directory full name.
*/
protected function createDir($dirName)
{
if (!file_exists($dirName)) {
mkdir($dirName, 0777, true);
}
}
/**
* Removes directory.
* @param $dirName directory full name
*/
protected function removeDir($dirName)
{
if (!empty($dirName) && file_exists($dirName)) {
exec("rm -rf {$dirName}");
}
}
/**
* Creates test asset controller instance.
* @return AssetController
*/
protected function createAssetController()
{
$module = $this->getMock('yii\\base\\Module', array('fake'), array('console'));
$assetController = new AssetController('asset', $module);
$assetController->interactive = false;
$assetController->jsCompressor = 'cp {from} {to}';
$assetController->cssCompressor = 'cp {from} {to}';
return $assetController;
}
/**
* Emulates running of the asset controller action.
* @param string $actionId id of action to be run.
* @param array $args action arguments.
* @return string command output.
*/
protected function runAssetControllerAction($actionId, array $args=array())
{
$controller = $this->createAssetController();
ob_start();
ob_implicit_flush(false);
$params = array(
\yii\console\Request::ANONYMOUS_PARAMS => $args
);
$controller->run($actionId, $params);
return ob_get_clean();
}
/**
* Creates test compress config.
* @param array[] $bundles asset bundles config.
* @return array config array.
*/
protected function createCompressConfig(array $bundles)
{
$baseUrl = '/test';
$config = array(
'bundles' => $this->createBundleConfig($bundles),
'targets' => array(
'all' => array(
'basePath' => $this->testAssetsBasePath,
'baseUrl' => $baseUrl,
'js' => 'all.js',
'css' => 'all.css',
),
),
'assetManager' => array(
'basePath' => $this->testAssetsBasePath,
'baseUrl' => $baseUrl,
),
);
return $config;
}
/**
* Creates test bundle configuration.
* @param array[] $bundles asset bundles config.
* @return array bundle config.
*/
protected function createBundleConfig(array $bundles)
{
foreach ($bundles as $name => $config) {
if (!array_key_exists('basePath', $config)) {
$bundles[$name]['basePath'] = $this->testFilePath;
}
if (!array_key_exists('baseUrl', $config)) {
$bundles[$name]['baseUrl'] = '';
}
}
return $bundles;
}
/**
* Creates test compress config file.
* @param string $fileName output file name.
* @param array[] $bundles asset bundles config.
* @throws Exception on failure.
*/
protected function createCompressConfigFile($fileName, array $bundles)
{
$content = '<?php return '.var_export($this->createCompressConfig($bundles), true).';';
if (file_put_contents($fileName, $content) <= 0) {
throw new \Exception("Unable to create file '{$fileName}'!");
}
}
/**
* Creates test asset file.
* @param string $fileRelativeName file name relative to [[testFilePath]]
* @param string $content file content
* @throws Exception on failure.
*/
protected function createAssetSourceFile($fileRelativeName, $content)
{
$fileFullName = $this->testFilePath.DIRECTORY_SEPARATOR.$fileRelativeName;
$this->createDir(dirname($fileFullName));
if (file_put_contents($fileFullName, $content)<=0) {
throw new \Exception("Unable to create file '{$fileFullName}'!");
}
}
/**
* Creates a list of asset source files.
* @param array $files assert source files in format: file/relative/name => fileContent
*/
protected function createAssertSourceFiles(array $files)
{
foreach ($files as $name => $content) {
$this->createAssetSourceFile($name, $content);
}
}
// Tests :
public function testActionTemplate()
{
$configFileName = $this->testFilePath . DIRECTORY_SEPARATOR . 'config.php';
$this->runAssetControllerAction('template', array($configFileName));
$this->assertTrue(file_exists($configFileName), 'Unable to create config file template!');
}
public function testActionCompress()
{
// Given :
$cssFiles = array(
'css/test_body.css' => 'body {
padding-top: 20px;
padding-bottom: 60px;
}',
'css/test_footer.css' => '.footer {
margin: 20px;
display: block;
}',
);
$this->createAssertSourceFiles($cssFiles);
$jsFiles = array(
'js/test_alert.js' => "function test() {
alert('Test message');
}",
'js/test_sum_ab.js' => "function sumAB(a, b) {
return a + b;
}",
);
$this->createAssertSourceFiles($jsFiles);
$bundles = array(
'app' => array(
'css' => array_keys($cssFiles),
'js' => array_keys($jsFiles),
),
);;
$bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php';
$configFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'config.php';
$this->createCompressConfigFile($configFile, $bundles);
// When :
$this->runAssetControllerAction('compress', array($configFile, $bundleFile));
// Then :
$this->assertTrue(file_exists($bundleFile), 'Unable to create output bundle file!');
$compressedCssFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.css';
$this->assertTrue(file_exists($compressedCssFileName), 'Unable to compress CSS files!');
$compressedJsFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.js';
$this->assertTrue(file_exists($compressedJsFileName), 'Unable to compress JS files!');
$compressedCssFileContent = file_get_contents($compressedCssFileName);
foreach ($cssFiles as $name => $content) {
$this->assertContains($content, $compressedCssFileContent, "Source of '{$name}' is missing in combined file!");
}
$compressedJsFileContent = file_get_contents($compressedJsFileName);
foreach ($jsFiles as $name => $content) {
$this->assertContains($content, $compressedJsFileContent, "Source of '{$name}' is missing in combined file!");
}
}
}
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
namespace yiiunit\framework\helpers; namespace yiiunit\framework\helpers;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;
use yii\web\Sort;
class ArrayHelperTest extends \yii\test\TestCase class ArrayHelperTest extends \yii\test\TestCase
{ {
...@@ -54,16 +56,51 @@ class ArrayHelperTest extends \yii\test\TestCase ...@@ -54,16 +56,51 @@ class ArrayHelperTest extends \yii\test\TestCase
array('name' => 'A', 'age' => 1), array('name' => 'A', 'age' => 1),
); );
ArrayHelper::multisort($array, array('name', 'age'), SORT_ASC, array(SORT_STRING, SORT_REGULAR)); ArrayHelper::multisort($array, array('name', 'age'), false, array(SORT_STRING, SORT_REGULAR));
$this->assertEquals(array('name' => 'A', 'age' => 1), $array[0]); $this->assertEquals(array('name' => 'A', 'age' => 1), $array[0]);
$this->assertEquals(array('name' => 'B', 'age' => 4), $array[1]); $this->assertEquals(array('name' => 'B', 'age' => 4), $array[1]);
$this->assertEquals(array('name' => 'a', 'age' => 3), $array[2]); $this->assertEquals(array('name' => 'a', 'age' => 3), $array[2]);
$this->assertEquals(array('name' => 'b', 'age' => 2), $array[3]); $this->assertEquals(array('name' => 'b', 'age' => 2), $array[3]);
ArrayHelper::multisort($array, array('name', 'age'), SORT_ASC, array(SORT_STRING, SORT_REGULAR), false); ArrayHelper::multisort($array, array('name', 'age'), false, array(SORT_STRING, SORT_REGULAR), false);
$this->assertEquals(array('name' => 'A', 'age' => 1), $array[0]); $this->assertEquals(array('name' => 'A', 'age' => 1), $array[0]);
$this->assertEquals(array('name' => 'a', 'age' => 3), $array[1]); $this->assertEquals(array('name' => 'a', 'age' => 3), $array[1]);
$this->assertEquals(array('name' => 'b', 'age' => 2), $array[2]); $this->assertEquals(array('name' => 'b', 'age' => 2), $array[2]);
$this->assertEquals(array('name' => 'B', 'age' => 4), $array[3]); $this->assertEquals(array('name' => 'B', 'age' => 4), $array[3]);
} }
public function testMultisortUseSort()
{
// single key
$sort = new Sort();
$sort->attributes = array('name', 'age');
$sort->defaults = array('name' => Sort::ASC);
$orders = $sort->getOrders();
$array = array(
array('name' => 'b', 'age' => 3),
array('name' => 'a', 'age' => 1),
array('name' => 'c', 'age' => 2),
);
ArrayHelper::multisort($array, array_keys($orders), array_values($orders));
$this->assertEquals(array('name' => 'a', 'age' => 1), $array[0]);
$this->assertEquals(array('name' => 'b', 'age' => 3), $array[1]);
$this->assertEquals(array('name' => 'c', 'age' => 2), $array[2]);
// multiple keys
$sort = new Sort();
$sort->attributes = array('name', 'age');
$sort->defaults = array('name' => Sort::ASC, 'age' => Sort::DESC);
$orders = $sort->getOrders();
$array = array(
array('name' => 'b', 'age' => 3),
array('name' => 'a', 'age' => 2),
array('name' => 'a', 'age' => 1),
);
ArrayHelper::multisort($array, array_keys($orders), array_values($orders));
$this->assertEquals(array('name' => 'a', 'age' => 2), $array[0]);
$this->assertEquals(array('name' => 'a', 'age' => 1), $array[1]);
$this->assertEquals(array('name' => 'b', 'age' => 3), $array[2]);
}
} }
...@@ -167,7 +167,7 @@ abstract class ManagerTestBase extends TestCase ...@@ -167,7 +167,7 @@ abstract class ManagerTestBase extends TestCase
$this->assertTrue($this->auth->executeBizRule(null, array(), null)); $this->assertTrue($this->auth->executeBizRule(null, array(), null));
$this->assertTrue($this->auth->executeBizRule('return 1 == true;', array(), null)); $this->assertTrue($this->auth->executeBizRule('return 1 == true;', array(), null));
$this->assertTrue($this->auth->executeBizRule('return $params[0] == $params[1];', array(1, '1'), null)); $this->assertTrue($this->auth->executeBizRule('return $params[0] == $params[1];', array(1, '1'), null));
$this->assertFalse($this->auth->executeBizRule('invalid', array(), null)); $this->assertFalse($this->auth->executeBizRule('invalid;', array(), null));
} }
public function testCheckAccess() public function testCheckAccess()
......
<?php
namespace yii\web;
use yiiunit\framework\web\ResponseTest;
/**
* Mock PHP header function to check for sent headers
* @param string $string
* @param bool $replace
* @param int $httpResponseCode
*/
function header($string, $replace = true, $httpResponseCode = null) {
ResponseTest::$headers[] = $string;
// TODO implement replace
if ($httpResponseCode !== null) {
ResponseTest::$httpResponseCode = $httpResponseCode;
}
}
namespace yiiunit\framework\web;
use yii\helpers\StringHelper;
use yii\web\Response;
class ResponseTest extends \yiiunit\TestCase
{
public static $headers = array();
public static $httpResponseCode = 200;
protected function setUp()
{
parent::setUp();
$this->reset();
}
protected function reset()
{
static::$headers = array();
static::$httpResponseCode = 200;
}
public function ranges()
{
// TODO test more cases for range requests and check for rfc compatibility
// http://www.w3.org/Protocols/rfc2616/rfc2616.txt
return array(
array('0-5', '0-5', 6, '12ёж'),
array('2-', '2-66', 65, 'ёжик3456798áèabcdefghijklmnopqrstuvwxyz!"§$%&/(ёжик)=?'),
array('-12', '55-66', 12, '(ёжик)=?'),
);
}
/**
* @dataProvider ranges
*/
public function testSendFileRanges($rangeHeader, $expectedHeader, $length, $expectedFile)
{
$content = $this->generateTestFileContent();
$_SERVER['HTTP_RANGE'] = 'bytes=' . $rangeHeader;
$sent = $this->runSendFile('testFile.txt', $content, null);
$this->assertEquals($expectedFile, $sent);
$this->assertTrue(in_array('HTTP/1.1 206 Partial Content', static::$headers));
$this->assertTrue(in_array('Accept-Ranges: bytes', static::$headers));
$this->assertArrayHasKey('Content-Range: bytes ' . $expectedHeader . '/' . StringHelper::strlen($content), array_flip(static::$headers));
$this->assertTrue(in_array('Content-Type: text/plain', static::$headers));
$this->assertTrue(in_array('Content-Length: ' . $length, static::$headers));
}
protected function generateTestFileContent()
{
return '12ёжик3456798áèabcdefghijklmnopqrstuvwxyz!"§$%&/(ёжик)=?';
}
protected function runSendFile($fileName, $content, $mimeType)
{
ob_start();
ob_implicit_flush(false);
$response = new Response();
$response->sendFile($fileName, $content, $mimeType, false);
$file = ob_get_clean();
return $file;
}
}
\ No newline at end of file
...@@ -14,9 +14,9 @@ class UrlManagerTest extends \yiiunit\TestCase ...@@ -14,9 +14,9 @@ class UrlManagerTest extends \yiiunit\TestCase
'cache' => null, 'cache' => null,
)); ));
$url = $manager->createUrl('post/view'); $url = $manager->createUrl('post/view');
$this->assertEquals('/?r=post/view', $url); $this->assertEquals('?r=post/view', $url);
$url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post')); $url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post'));
$this->assertEquals('/?r=post/view&id=1&title=sample+post', $url); $this->assertEquals('?r=post/view&id=1&title=sample+post', $url);
// default setting with '/test/' as base url // default setting with '/test/' as base url
$manager = new UrlManager(array( $manager = new UrlManager(array(
...@@ -24,7 +24,7 @@ class UrlManagerTest extends \yiiunit\TestCase ...@@ -24,7 +24,7 @@ class UrlManagerTest extends \yiiunit\TestCase
'cache' => null, 'cache' => null,
)); ));
$url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post')); $url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post'));
$this->assertEquals('/test/?r=post/view&id=1&title=sample+post', $url); $this->assertEquals('/test?r=post/view&id=1&title=sample+post', $url);
// pretty URL without rules // pretty URL without rules
$manager = new UrlManager(array( $manager = new UrlManager(array(
...@@ -85,6 +85,24 @@ class UrlManagerTest extends \yiiunit\TestCase ...@@ -85,6 +85,24 @@ class UrlManagerTest extends \yiiunit\TestCase
$this->assertEquals('/post/1/sample+post.html', $url); $this->assertEquals('/post/1/sample+post.html', $url);
$url = $manager->createUrl('post/index', array('page' => 1)); $url = $manager->createUrl('post/index', array('page' => 1));
$this->assertEquals('/post/index.html?page=1', $url); $this->assertEquals('/post/index.html?page=1', $url);
// pretty URL with rules that have host info
$manager = new UrlManager(array(
'enablePrettyUrl' => true,
'cache' => null,
'rules' => array(
array(
'pattern' => 'post/<id>/<title>',
'route' => 'post/view',
'host' => 'http://<lang:en|fr>.example.com',
),
),
'baseUrl' => '/test',
));
$url = $manager->createUrl('post/view', array('id' => 1, 'title' => 'sample post', 'lang' => 'en'));
$this->assertEquals('http://en.example.com/test/post/1/sample+post', $url);
$url = $manager->createUrl('post/index', array('page' => 1));
$this->assertEquals('/test/post/index?page=1', $url);
} }
public function testCreateAbsoluteUrl() public function testCreateAbsoluteUrl()
...@@ -95,7 +113,7 @@ class UrlManagerTest extends \yiiunit\TestCase ...@@ -95,7 +113,7 @@ class UrlManagerTest extends \yiiunit\TestCase
'cache' => null, 'cache' => null,
)); ));
$url = $manager->createAbsoluteUrl('post/view', array('id' => 1, 'title' => 'sample post')); $url = $manager->createAbsoluteUrl('post/view', array('id' => 1, 'title' => 'sample post'));
$this->assertEquals('http://www.example.com/?r=post/view&id=1&title=sample+post', $url); $this->assertEquals('http://www.example.com?r=post/view&id=1&title=sample+post', $url);
} }
public function testParseRequest() public function testParseRequest()
......
...@@ -26,7 +26,7 @@ class UrlRuleTest extends \yiiunit\TestCase ...@@ -26,7 +26,7 @@ class UrlRuleTest extends \yiiunit\TestCase
public function testParseRequest() public function testParseRequest()
{ {
$manager = new UrlManager(array('cache' => null)); $manager = new UrlManager(array('cache' => null));
$request = new Request; $request = new Request(array('hostInfo' => 'http://en.example.com'));
$suites = $this->getTestsForParseRequest(); $suites = $this->getTestsForParseRequest();
foreach ($suites as $i => $suite) { foreach ($suites as $i => $suite) {
list ($name, $config, $tests) = $suite; list ($name, $config, $tests) = $suite;
...@@ -327,6 +327,19 @@ class UrlRuleTest extends \yiiunit\TestCase ...@@ -327,6 +327,19 @@ class UrlRuleTest extends \yiiunit\TestCase
array('post/index', array('page' => 1), 'posts/?page=1'), array('post/index', array('page' => 1), 'posts/?page=1'),
), ),
), ),
array(
'with host info',
array(
'pattern' => 'post/<page:\d+>/<tag>',
'route' => 'post/index',
'defaults' => array('page' => 1),
'host' => 'http://<lang:en|fr>.example.com',
),
array(
array('post/index', array('page' => 1, 'tag' => 'a'), false),
array('post/index', array('page' => 1, 'tag' => 'a', 'lang' => 'en'), 'http://en.example.com/post/a'),
),
),
); );
} }
...@@ -610,6 +623,19 @@ class UrlRuleTest extends \yiiunit\TestCase ...@@ -610,6 +623,19 @@ class UrlRuleTest extends \yiiunit\TestCase
array('a', false), array('a', false),
), ),
), ),
array(
'with host info',
array(
'pattern' => 'post/<page:\d+>',
'route' => 'post/index',
'host' => 'http://<lang:en|fr>.example.com',
),
array(
array('post/1', 'post/index', array('page' => '1', 'lang' => 'en')),
array('post/a', false),
array('post/1/a', false),
),
),
); );
} }
} }
Upgrading Instructions for Yii Framework v2
===========================================
!!!IMPORTANT!!!
The following upgrading instructions are cumulative. That is,
if you want to upgrade from version A to version C and there is
version B between A and C, you need to following the instructions
for both A and B.
General upgrade instructions
----------------------------
- Make a backup.
- Clean up your 'assets' folder.
- Replace 'framework' dir with the new one or point Git to a fresh
release tag and checkout.
- Check if everything is OK, if not — revert to previous stable version and post
issues to [Yii issue tracker](https://github.com/yiisoft/yii2/issues).
Upgrading from v1.1.x
---------------------
- All framework classes are now namespaced, and the name prefix `C` is removed.
- The format of path alias is changed to `@yii/base/Component`.
In 1.x, this would be `system.base.CComponent`. See guide for more details.
- The root alias `@yii` now represents the framework installation directory.
In 1.x, this is named as `system`. We also removed `zii` root alias.
- `Object` serves as the base class that supports properties. And `Component` extends
from `Object` and supports events and behaviors. Behaviors declared in
`Component::behaviors()` are attached on demand.
- `CList` is renamed to `Vector`, and `CMap` is renamed to `Dictionary`.
Other collection classes are dropped in favor of SPL classes.
- `CFormModel` is removed. Please use `yii\base\Model` instead.
- `CDbCriteria` is replaced by `yii\db\Query` which includes methods for
building a query. `CDbCommandBuilder` is replaced by `yii\db\QueryBuilder`
which has cleaner and more complete support of query building capabilities.
The Yii framework is free software. It is released under the terms of
the following BSD License.
Copyright © 2008-2013 by Yii Software LLC (http://www.yiisoft.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Yii Software LLC nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
Yii 2.0 Public Preview
======================
Thank you for choosing Yii - a high-performance component-based PHP framework.
If you are looking for a production-ready PHP framework, please use
[Yii v1.1](https://github.com/yiisoft/yii).
Yii 2.0 is still under heavy development. We may make significant changes
without prior notices. **Yii 2.0 is not ready for production use yet.**
[![Build Status](https://secure.travis-ci.org/yiisoft/yii2.png)](http://travis-ci.org/yiisoft/yii2)
REQUIREMENTS
------------
The minimum requirement by Yii is that your Web server supports PHP 5.3.?.
Upgrading Instructions for Yii Framework v2
===========================================
!!!IMPORTANT!!!
The following upgrading instructions are cumulative. That is,
if you want to upgrade from version A to version C and there is
version B between A and C, you need to following the instructions
for both A and B.
...@@ -287,7 +287,11 @@ class YiiBase ...@@ -287,7 +287,11 @@ class YiiBase
if ($path !== null) { if ($path !== null) {
$path = strncmp($path, '@', 1) ? rtrim($path, '\\/') : static::getAlias($path); $path = strncmp($path, '@', 1) ? rtrim($path, '\\/') : static::getAlias($path);
if (!isset(self::$aliases[$root])) { if (!isset(self::$aliases[$root])) {
self::$aliases[$root] = $path; if ($pos === false) {
self::$aliases[$root] = $path;
} else {
self::$aliases[$root] = array($alias => $path);
}
} elseif (is_string(self::$aliases[$root])) { } elseif (is_string(self::$aliases[$root])) {
if ($pos === false) { if ($pos === false) {
self::$aliases[$root] = $path; self::$aliases[$root] = $path;
...@@ -579,10 +583,9 @@ class YiiBase ...@@ -579,10 +583,9 @@ class YiiBase
/** /**
* Translates a message to the specified language. * Translates a message to the specified language.
* *
* The translation will be conducted according to the message category and the target language. * This is a shortcut method of [[\yii\i18n\I18N::translate()]].
* To specify the category of the message, prefix the message with the category name and separate it *
* with "|". For example, "app|hello world". If the category is not specified, the default category "app" * The translation will be conducted according to the message category and the target language will be used.
* will be used. The actual message translation is done by a [[\yii\i18n\MessageSource|message source]].
* *
* In case when a translated message has different plural forms (separated by "|"), this method * In case when a translated message has different plural forms (separated by "|"), this method
* will also attempt to choose an appropriate one according to a given numeric value which is * will also attempt to choose an appropriate one according to a given numeric value which is
...@@ -595,20 +598,18 @@ class YiiBase ...@@ -595,20 +598,18 @@ class YiiBase
* For more details on how plural rules are applied, please refer to: * For more details on how plural rules are applied, please refer to:
* [[http://www.unicode.org/cldr/charts/supplemental/language_plural_rules.html]] * [[http://www.unicode.org/cldr/charts/supplemental/language_plural_rules.html]]
* *
* @param string $category the message category.
* @param string $message the message to be translated. * @param string $message the message to be translated.
* @param array $params the parameters that will be used to replace the corresponding placeholders in the message. * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
* @param string $language the language code (e.g. `en_US`, `en`). If this is null, the current * @param string $language the language code (e.g. `en_US`, `en`). If this is null, the current
* [[\yii\base\Application::language|application language]] will be used. * [[\yii\base\Application::language|application language]] will be used.
* @return string the translated message. * @return string the translated message.
*/ */
public static function t($message, $params = array(), $language = null) public static function t($category, $message, $params = array(), $language = null)
{ {
if (self::$app !== null) { if (self::$app !== null) {
return self::$app->getI18N()->translate($message, $params, $language); return self::$app->getI18N()->translate($category, $message, $params, $language);
} else { } else {
if (strpos($message, '|') !== false && preg_match('/^([\w\-\\/\.\\\\]+)\|(.*)/', $message, $matches)) {
$message = $matches[2];
}
return is_array($params) ? strtr($message, $params) : $message; return is_array($params) ? strtr($message, $params) : $message;
} }
} }
......
<?php <?php
return array( return array(
'jquery' => array( 'yii' => array(
'sourcePath' => __DIR__ . '/assets', 'sourcePath' => __DIR__ . '/assets',
'js' => array( 'js' => array(
'jquery.min.js', 'yii.js',
), ),
'depends' => array('yii/jquery'),
), ),
'yii' => array( 'yii/jquery' => array(
'sourcePath' => __DIR__ . '/assets', 'sourcePath' => __DIR__ . '/assets',
'js' => array( 'js' => array(
'yii.js', 'jquery.min.js',
), ),
'depends' => array('jquery'),
), ),
'yii/validation' => array( 'yii/validation' => array(
'sourcePath' => __DIR__ . '/assets', 'sourcePath' => __DIR__ . '/assets',
...@@ -26,7 +26,7 @@ return array( ...@@ -26,7 +26,7 @@ return array(
'js' => array( 'js' => array(
'yii.activeForm.js', 'yii.activeForm.js',
), ),
'depends' => array('yii', 'yii/validation'), 'depends' => array('yii'),
), ),
'yii/captcha' => array( 'yii/captcha' => array(
'sourcePath' => __DIR__ . '/assets', 'sourcePath' => __DIR__ . '/assets',
...@@ -43,20 +43,26 @@ return array( ...@@ -43,20 +43,26 @@ return array(
'depends' => array('yii'), 'depends' => array('yii'),
), ),
'yii/bootstrap' => array( 'yii/bootstrap' => array(
'sourcePath' => __DIR__ . '/assets/bootstrap', 'sourcePath' => __DIR__ . '/assets',
'js' => array(
'/js/bootstrap.min.js',
),
'css' => array( 'css' => array(
'css/bootstrap.css' 'bootstrap/css/bootstrap.css',
), ),
'depends' => array('yii'), 'js' => array(
'bootstrap/js/bootstrap.js',
),
'depends' => array('yii/jquery'),
), ),
'yii/bootstrap-responsive' => array( 'yii/bootstrap-responsive' => array(
'sourcePath' => __DIR__ . '/assets/bootstrap', 'sourcePath' => __DIR__ . '/assets',
'css' => array( 'css' => array(
'css/bootstrap-responsive.css' 'bootstrap/css/bootstrap-responsive.css',
), ),
'depends' => array('yii/bootstrap'), 'depends' => array('yii/bootstrap'),
) ),
'yii/punycode' => array(
'sourcePath' => __DIR__ . '/assets',
'js' => array(
'punycode/punycode.min.js',
),
),
); );
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
Copyright Mathias Bynens <http://mathiasbynens.be/>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/*! http://mths.be/punycode v1.2.1 by @mathias */
(function(o){function e(o){throw RangeError(L[o])}function n(o,e){for(var n=o.length;n--;)o[n]=e(o[n]);return o}function t(o,e){return n(o.split(S),e).join(".")}function r(o){for(var e,n,t=[],r=0,u=o.length;u>r;)e=o.charCodeAt(r++),55296==(63488&e)&&u>r?(n=o.charCodeAt(r++),56320==(64512&n)?t.push(((1023&e)<<10)+(1023&n)+65536):t.push(e,n)):t.push(e);return t}function u(o){return n(o,function(o){var e="";return o>65535&&(o-=65536,e+=R(55296|1023&o>>>10),o=56320|1023&o),e+=R(o)}).join("")}function i(o){return 10>o-48?o-22:26>o-65?o-65:26>o-97?o-97:x}function f(o,e){return o+22+75*(26>o)-((0!=e)<<5)}function c(o,e,n){var t=0;for(o=n?P(o/m):o>>1,o+=P(o/e);o>M*y>>1;t+=x)o=P(o/M);return P(t+(M+1)*o/(o+j))}function l(o){var n,t,r,f,l,d,s,a,p,h,v=[],g=o.length,w=0,j=I,m=A;for(t=o.lastIndexOf(F),0>t&&(t=0),r=0;t>r;++r)o.charCodeAt(r)>=128&&e("not-basic"),v.push(o.charCodeAt(r));for(f=t>0?t+1:0;g>f;){for(l=w,d=1,s=x;f>=g&&e("invalid-input"),a=i(o.charCodeAt(f++)),(a>=x||a>P((b-w)/d))&&e("overflow"),w+=a*d,p=m>=s?C:s>=m+y?y:s-m,!(p>a);s+=x)h=x-p,d>P(b/h)&&e("overflow"),d*=h;n=v.length+1,m=c(w-l,n,0==l),P(w/n)>b-j&&e("overflow"),j+=P(w/n),w%=n,v.splice(w++,0,j)}return u(v)}function d(o){var n,t,u,i,l,d,s,a,p,h,v,g,w,j,m,E=[];for(o=r(o),g=o.length,n=I,t=0,l=A,d=0;g>d;++d)v=o[d],128>v&&E.push(R(v));for(u=i=E.length,i&&E.push(F);g>u;){for(s=b,d=0;g>d;++d)v=o[d],v>=n&&s>v&&(s=v);for(w=u+1,s-n>P((b-t)/w)&&e("overflow"),t+=(s-n)*w,n=s,d=0;g>d;++d)if(v=o[d],n>v&&++t>b&&e("overflow"),v==n){for(a=t,p=x;h=l>=p?C:p>=l+y?y:p-l,!(h>a);p+=x)m=a-h,j=x-h,E.push(R(f(h+m%j,0))),a=P(m/j);E.push(R(f(a,0))),l=c(t,w,u==i),t=0,++u}++t,++n}return E.join("")}function s(o){return t(o,function(o){return E.test(o)?l(o.slice(4).toLowerCase()):o})}function a(o){return t(o,function(o){return O.test(o)?"xn--"+d(o):o})}var p="object"==typeof exports&&exports,h="object"==typeof module&&module&&module.exports==p&&module,v="object"==typeof global&&global;(v.global===v||v.window===v)&&(o=v);var g,w,b=2147483647,x=36,C=1,y=26,j=38,m=700,A=72,I=128,F="-",E=/^xn--/,O=/[^ -~]/,S=/\x2E|\u3002|\uFF0E|\uFF61/g,L={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},M=x-C,P=Math.floor,R=String.fromCharCode;if(g={version:"1.2.1",ucs2:{decode:r,encode:u},decode:l,encode:d,toASCII:a,toUnicode:s},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define(function(){return g});else if(p&&!p.nodeType)if(h)h.exports=g;else for(w in g)g.hasOwnProperty(w)&&(p[w]=g[w]);else o.punycode=g})(this);
\ No newline at end of file
...@@ -57,7 +57,7 @@ ...@@ -57,7 +57,7 @@
// whether to perform validation when a change is detected on the input // whether to perform validation when a change is detected on the input
validateOnChange: false, validateOnChange: false,
// whether to perform validation when the user is typing. // whether to perform validation when the user is typing.
validateOnType: false, validateOnType: false,
// number of milliseconds that the validation should be delayed when a user is typing in the input field. // number of milliseconds that the validation should be delayed when a user is typing in the input field.
validationDelay: 200, validationDelay: 200,
// whether to enable AJAX-based validation. // whether to enable AJAX-based validation.
......
...@@ -51,8 +51,8 @@ ...@@ -51,8 +51,8 @@
dataType: 'json', dataType: 'json',
cache: false, cache: false,
success: function(data) { success: function(data) {
$e.attr('src', data['url']); $e.attr('src', data.url);
$('body').data(settings.hashKey, [data['hash1'], data['hash2']]); $('body').data(settings.hashKey, [data.hash1, data.hash2]);
} }
}); });
}, },
......
...@@ -18,7 +18,7 @@ yii.debug = (function ($) { ...@@ -18,7 +18,7 @@ yii.debug = (function ($) {
//dataType: 'json', //dataType: 'json',
success: function(data) { success: function(data) {
var $e = $('#' + id); var $e = $('#' + id);
$e.html(data); $e.html(data).show();
} }
}); });
} }
......
...@@ -110,9 +110,19 @@ yii.validation = (function ($) { ...@@ -110,9 +110,19 @@ yii.validation = (function ($) {
return; return;
} }
var valid = value.match(options.pattern) && (!options.allowName || value.match(options.fullPattern)); var valid = true;
if (options.enableIDN) {
var regexp = /^(.*)@(.*)$/,
matches = regexp.exec(value);
if (matches === null) {
valid = false;
} else {
value = punycode.toASCII(matches[1]) + '@' + punycode.toASCII(matches[2]);
}
}
if (!valid) { if (!valid || !(value.match(options.pattern) && (!options.allowName || value.match(options.fullPattern)))) {
messages.push(options.message); messages.push(options.message);
} }
}, },
...@@ -126,7 +136,19 @@ yii.validation = (function ($) { ...@@ -126,7 +136,19 @@ yii.validation = (function ($) {
value = options.defaultScheme + '://' + value; value = options.defaultScheme + '://' + value;
} }
if (!value.match(options.pattern)) { var valid = true;
if (options.enableIDN) {
var regexp = /^([^:]+):\/\/([^\/]+)(.*)$/,
matches = regexp.exec(value);
if (matches === null) {
valid = false;
} else {
value = matches[1] + '://' + punycode.toASCII(matches[2]) + matches[3];
}
}
if (!valid || !value.match(options.pattern)) {
messages.push(options.message); messages.push(options.message);
} }
}, },
......
...@@ -183,7 +183,7 @@ class Controller extends Component ...@@ -183,7 +183,7 @@ class Controller extends Component
} }
if (!empty($missing)) { if (!empty($missing)) {
throw new InvalidRequestException(Yii::t('yii|Missing required parameters: {params}', array( throw new InvalidRequestException(Yii::t('yii', 'Missing required parameters: {params}', array(
'{params}' => implode(', ', $missing), '{params}' => implode(', ', $missing),
))); )));
} }
...@@ -410,6 +410,7 @@ class Controller extends Component ...@@ -410,6 +410,7 @@ class Controller extends Component
* Returns the view object that can be used to render views or view files. * Returns the view object that can be used to render views or view files.
* The [[render()]], [[renderPartial()]] and [[renderFile()]] methods will use * The [[render()]], [[renderPartial()]] and [[renderFile()]] methods will use
* this view object to implement the actual view rendering. * this view object to implement the actual view rendering.
* If not set, it will default to the "view" application component.
* @return View the view object that can be used to render views or view files. * @return View the view object that can be used to render views or view files.
*/ */
public function getView() public function getView()
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
use yii\helpers\ArrayHelper;
/**
* 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 Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Countable
{
/**
* @var array internal data storage
*/
private $_d = array();
/**
* Constructor.
* Initializes the dictionary with an array or an iterable object.
* @param mixed $data 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
* @throws Exception if data is not well formed (neither an array nor an iterable object)
*/
public function __construct($data = array(), $config = array())
{
if (!empty($data)) {
$this->copyFrom($data);
}
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->_d);
}
/**
* 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->_d);
}
/**
* Returns the keys stored in the dictionary.
* @return array the key list
*/
public function getKeys()
{
return array_keys($this->_d);
}
/**
* Returns the item with the specified key.
* @param mixed $key the key
* @return mixed the element with the specified key.
* Null if the key cannot be found in the dictionary.
*/
public function itemAt($key)
{
return isset($this->_d[$key]) ? $this->_d[$key] : null;
}
/**
* Adds an item into the dictionary.
* Note, if the specified key already exists, the old value will be overwritten.
* @param mixed $key key
* @param mixed $value value
* @throws Exception if the dictionary is read-only
*/
public function add($key, $value)
{
if ($key === null) {
$this->_d[] = $value;
} else {
$this->_d[$key] = $value;
}
}
/**
* 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($key)
{
if (isset($this->_d[$key])) {
$value = $this->_d[$key];
unset($this->_d[$key]);
return $value;
} else { // the value is null
unset($this->_d[$key]);
return null;
}
}
/**
* 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 removeAll($safeClear = false)
{
if ($safeClear) {
foreach (array_keys($this->_d) as $key) {
$this->remove($key);
}
} else {
$this->_d = array();
}
}
/**
* Returns a value indicating whether the dictionary contains the specified key.
* @param mixed $key the key
* @return boolean whether the dictionary contains an item with the specified key
*/
public function has($key)
{
return isset($this->_d[$key]) || array_key_exists($key, $this->_d);
}
/**
* Returns the dictionary as a PHP array.
* @return array the list of items in array
*/
public function toArray()
{
return $this->_d;
}
/**
* Copies iterable data into the dictionary.
* Note, existing data in the dictionary will be cleared first.
* @param mixed $data the data to be copied from, must be an array or an object implementing `Traversable`
* @throws InvalidParamException if data is neither an array nor an iterator.
*/
public function copyFrom($data)
{
if (is_array($data) || $data instanceof \Traversable) {
if (!empty($this->_d)) {
$this->removeAll();
}
if ($data instanceof self) {
$data = $data->_d;
}
foreach ($data as $key => $value) {
$this->add($key, $value);
}
} else {
throw new InvalidParamException('Data must be either an array or an object implementing Traversable.');
}
}
/**
* Merges iterable data into the dictionary.
*
* Existing elements in the dictionary will be overwritten if their keys are the same as those in the source.
* If the merge is recursive, the following algorithm is performed:
*
* - the dictionary data is saved as $a, and the source data is saved as $b;
* - if $a and $b both have an array indexed at the same string key, the arrays will be merged using this algorithm;
* - any integer-indexed elements in $b will be appended to $a;
* - any string-indexed elements in $b will overwrite elements in $a with the same index;
*
* @param array|\Traversable $data the data to be merged with. It must be an array or object implementing Traversable
* @param boolean $recursive whether the merging should be recursive.
* @throws InvalidParamException if data is neither an array nor an object implementing `Traversable`.
*/
public function mergeWith($data, $recursive = true)
{
if (is_array($data) || $data instanceof \Traversable) {
if ($data instanceof self) {
$data = $data->_d;
}
if ($recursive) {
if ($data instanceof \Traversable) {
$d = array();
foreach ($data as $key => $value) {
$d[$key] = $value;
}
$this->_d = ArrayHelper::merge($this->_d, $d);
} else {
$this->_d = ArrayHelper::merge($this->_d, $data);
}
} else {
foreach ($data as $key => $value) {
$this->add($key, $value);
}
}
} else {
throw new InvalidParamException('The data to be merged with must be an array or an object implementing Traversable.');
}
}
/**
* 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 $this->has($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->itemAt($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($offset, $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)
{
$this->remove($offset);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* DictionaryIterator implements the SPL `Iterator` interface for [[Dictionary]].
*
* It allows [[Dictionary]] to return a new iterator for data traversing purpose.
* You normally do not use this class directly.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class DictionaryIterator implements \Iterator
{
/**
* @var array the data to be iterated through
*/
private $_d;
/**
* @var array list of keys in the map
*/
private $_keys;
/**
* @var mixed current key
*/
private $_key;
/**
* Constructor.
* @param array $data the data to be iterated through
*/
public function __construct(&$data)
{
$this->_d = &$data;
$this->_keys = array_keys($data);
$this->_key = reset($this->_keys);
}
/**
* Rewinds the index of the current item.
* This method is required by the SPL interface `Iterator`.
*/
public function rewind()
{
$this->_key = reset($this->_keys);
}
/**
* Returns the key of the current array element.
* This method is required by the SPL interface `Iterator`.
* @return mixed the key of the current array element
*/
public function key()
{
return $this->_key;
}
/**
* Returns the current array element.
* This method is required by the SPL interface `Iterator`.
* @return mixed the current array element
*/
public function current()
{
return $this->_d[$this->_key];
}
/**
* Moves the internal pointer to the next element.
* This method is required by the SPL interface `Iterator`.
*/
public function next()
{
$this->_key = next($this->_keys);
}
/**
* Returns whether there is an element at current position.
* This method is required by the SPL interface `Iterator`.
* @return boolean whether there is an item at current position.
*/
public function valid()
{
return $this->_key !== false;
}
}
...@@ -90,20 +90,20 @@ class ErrorException extends Exception ...@@ -90,20 +90,20 @@ class ErrorException extends Exception
public function getName() public function getName()
{ {
$names = array( $names = array(
E_ERROR => Yii::t('yii|Fatal Error'), E_ERROR => Yii::t('yii', 'Fatal Error'),
E_PARSE => Yii::t('yii|Parse Error'), E_PARSE => Yii::t('yii', 'Parse Error'),
E_CORE_ERROR => Yii::t('yii|Core Error'), E_CORE_ERROR => Yii::t('yii', 'Core Error'),
E_COMPILE_ERROR => Yii::t('yii|Compile Error'), E_COMPILE_ERROR => Yii::t('yii', 'Compile Error'),
E_USER_ERROR => Yii::t('yii|User Error'), E_USER_ERROR => Yii::t('yii', 'User Error'),
E_WARNING => Yii::t('yii|Warning'), E_WARNING => Yii::t('yii', 'Warning'),
E_CORE_WARNING => Yii::t('yii|Core Warning'), E_CORE_WARNING => Yii::t('yii', 'Core Warning'),
E_COMPILE_WARNING => Yii::t('yii|Compile Warning'), E_COMPILE_WARNING => Yii::t('yii', 'Compile Warning'),
E_USER_WARNING => Yii::t('yii|User Warning'), E_USER_WARNING => Yii::t('yii', 'User Warning'),
E_STRICT => Yii::t('yii|Strict'), E_STRICT => Yii::t('yii', 'Strict'),
E_NOTICE => Yii::t('yii|Notice'), E_NOTICE => Yii::t('yii', 'Notice'),
E_RECOVERABLE_ERROR => Yii::t('yii|Recoverable Error'), E_RECOVERABLE_ERROR => Yii::t('yii', 'Recoverable Error'),
E_DEPRECATED => Yii::t('yii|Deprecated'), E_DEPRECATED => Yii::t('yii', 'Deprecated'),
); );
return isset($names[$this->getCode()]) ? $names[$this->getCode()] : Yii::t('yii|Error'); return isset($names[$this->getCode()]) ? $names[$this->getCode()] : Yii::t('yii', 'Error');
} }
} }
...@@ -75,8 +75,11 @@ class ErrorHandler extends Component ...@@ -75,8 +75,11 @@ class ErrorHandler extends Component
\Yii::$app->runAction($this->errorAction); \Yii::$app->runAction($this->errorAction);
} elseif (\Yii::$app instanceof \yii\web\Application) { } elseif (\Yii::$app instanceof \yii\web\Application) {
if (!headers_sent()) { if (!headers_sent()) {
$errorCode = $exception instanceof HttpException ? $exception->statusCode : 500; if ($exception instanceof HttpException) {
header("HTTP/1.0 $errorCode " . get_class($exception)); header('HTTP/1.0 ' . $exception->statusCode . ' ' . $exception->getName());
} else {
header('HTTP/1.0 500 ' . get_class($exception));
}
} }
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') { if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
\Yii::$app->renderException($exception); \Yii::$app->renderException($exception);
......
...@@ -20,6 +20,6 @@ class Exception extends \Exception ...@@ -20,6 +20,6 @@ class Exception extends \Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Exception'); return \Yii::t('yii', 'Exception');
} }
} }
...@@ -103,7 +103,7 @@ class HttpException extends UserException ...@@ -103,7 +103,7 @@ class HttpException extends UserException
if (isset($httpCodes[$this->statusCode])) { if (isset($httpCodes[$this->statusCode])) {
return $httpCodes[$this->statusCode]; return $httpCodes[$this->statusCode];
} else { } else {
return \Yii::t('yii|Error'); return \Yii::t('yii', 'Error');
} }
} }
} }
...@@ -20,7 +20,7 @@ class InvalidCallException extends Exception ...@@ -20,7 +20,7 @@ class InvalidCallException extends Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Invalid Call'); return \Yii::t('yii', 'Invalid Call');
} }
} }
...@@ -20,7 +20,7 @@ class InvalidConfigException extends Exception ...@@ -20,7 +20,7 @@ class InvalidConfigException extends Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Invalid Configuration'); return \Yii::t('yii', 'Invalid Configuration');
} }
} }
...@@ -20,7 +20,7 @@ class InvalidParamException extends Exception ...@@ -20,7 +20,7 @@ class InvalidParamException extends Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Invalid Parameter'); return \Yii::t('yii', 'Invalid Parameter');
} }
} }
...@@ -20,7 +20,7 @@ class InvalidRequestException extends UserException ...@@ -20,7 +20,7 @@ class InvalidRequestException extends UserException
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Invalid Request'); return \Yii::t('yii', 'Invalid Request');
} }
} }
...@@ -20,7 +20,7 @@ class InvalidRouteException extends UserException ...@@ -20,7 +20,7 @@ class InvalidRouteException extends UserException
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Invalid Route'); return \Yii::t('yii', 'Invalid Route');
} }
} }
...@@ -7,6 +7,8 @@ ...@@ -7,6 +7,8 @@
namespace yii\base; namespace yii\base;
use ArrayObject;
use ArrayIterator;
use yii\helpers\StringHelper; use yii\helpers\StringHelper;
use yii\validators\RequiredValidator; use yii\validators\RequiredValidator;
use yii\validators\Validator; use yii\validators\Validator;
...@@ -30,7 +32,7 @@ use yii\validators\Validator; ...@@ -30,7 +32,7 @@ use yii\validators\Validator;
* You may directly use Model to store model data, or extend it with customization. * You may directly use Model to store model data, or extend it with customization.
* You may also customize Model by attaching [[ModelBehavior|model behaviors]]. * You may also customize Model by attaching [[ModelBehavior|model behaviors]].
* *
* @property Vector $validators All the validators declared in the model. * @property ArrayObject $validators All the validators declared in the model.
* @property array $activeValidators The validators applicable to the current [[scenario]]. * @property array $activeValidators The validators applicable to the current [[scenario]].
* @property array $errors Errors for all attributes or the specified attribute. Empty array is returned if no error. * @property array $errors Errors for all attributes or the specified attribute. Empty array is returned if no error.
* @property array $attributes Attribute values (name => value). * @property array $attributes Attribute values (name => value).
...@@ -56,7 +58,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -56,7 +58,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
*/ */
private $_errors; private $_errors;
/** /**
* @var Vector vector of validators * @var ArrayObject list of validators
*/ */
private $_validators; private $_validators;
/** /**
...@@ -300,15 +302,15 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -300,15 +302,15 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
* This method differs from [[getActiveValidators()]] in that the latter * This method differs from [[getActiveValidators()]] in that the latter
* only returns the validators applicable to the current [[scenario]]. * only returns the validators applicable to the current [[scenario]].
* *
* Because this method returns a [[Vector]] object, you may * Because this method returns an ArrayObject object, you may
* manipulate it by inserting or removing validators (useful in model behaviors). * manipulate it by inserting or removing validators (useful in model behaviors).
* For example, * For example,
* *
* ~~~ * ~~~
* $model->validators->add($newValidator); * $model->validators[] = $newValidator;
* ~~~ * ~~~
* *
* @return Vector all the validators declared in the model. * @return ArrayObject all the validators declared in the model.
*/ */
public function getValidators() public function getValidators()
{ {
...@@ -340,18 +342,18 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -340,18 +342,18 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
/** /**
* Creates validator objects based on the validation rules specified in [[rules()]]. * Creates validator objects based on the validation rules specified in [[rules()]].
* Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned. * Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned.
* @return Vector validators * @return ArrayObject validators
* @throws InvalidConfigException if any validation rule configuration is invalid * @throws InvalidConfigException if any validation rule configuration is invalid
*/ */
public function createValidators() public function createValidators()
{ {
$validators = new Vector; $validators = new ArrayObject;
foreach ($this->rules() as $rule) { foreach ($this->rules() as $rule) {
if ($rule instanceof Validator) { if ($rule instanceof Validator) {
$validators->add($rule); $validators->append($rule);
} elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
$validator = Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2)); $validator = Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2));
$validators->add($validator); $validators->append($validator);
} else { } else {
throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.'); throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
} }
...@@ -590,18 +592,22 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -590,18 +592,22 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
/** /**
* Returns the attribute names that are safe to be massively assigned in the current scenario. * Returns the attribute names that are safe to be massively assigned in the current scenario.
* @return array safe attribute names * @return string[] safe attribute names
*/ */
public function safeAttributes() public function safeAttributes()
{ {
$scenario = $this->getScenario(); $scenario = $this->getScenario();
$scenarios = $this->scenarios(); $scenarios = $this->scenarios();
if (!isset($scenarios[$scenario])) {
return array();
}
$attributes = array(); $attributes = array();
if (isset($scenarios[$scenario])) { if (isset($scenarios[$scenario]['attributes']) && is_array($scenarios[$scenario]['attributes'])) {
foreach ($scenarios[$scenario] as $attribute) { $scenarios[$scenario] = $scenarios[$scenario]['attributes'];
if ($attribute[0] !== '!') { }
$attributes[] = $attribute; foreach ($scenarios[$scenario] as $attribute) {
} if ($attribute[0] !== '!') {
$attributes[] = $attribute;
} }
} }
return $attributes; return $attributes;
...@@ -609,34 +615,37 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -609,34 +615,37 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
/** /**
* Returns the attribute names that are subject to validation in the current scenario. * Returns the attribute names that are subject to validation in the current scenario.
* @return array safe attribute names * @return string[] safe attribute names
*/ */
public function activeAttributes() public function activeAttributes()
{ {
$scenario = $this->getScenario(); $scenario = $this->getScenario();
$scenarios = $this->scenarios(); $scenarios = $this->scenarios();
if (isset($scenarios[$scenario])) { if (!isset($scenarios[$scenario])) {
$attributes = $scenarios[$this->getScenario()];
foreach ($attributes as $i => $attribute) {
if ($attribute[0] === '!') {
$attributes[$i] = substr($attribute, 1);
}
}
return $attributes;
} else {
return array(); return array();
} }
if (isset($scenarios[$scenario]['attributes']) && is_array($scenarios[$scenario]['attributes'])) {
$attributes = $scenarios[$scenario]['attributes'];
} else {
$attributes = $scenarios[$scenario];
}
foreach ($attributes as $i => $attribute) {
if ($attribute[0] === '!') {
$attributes[$i] = substr($attribute, 1);
}
}
return $attributes;
} }
/** /**
* Returns an iterator for traversing the attributes in the model. * Returns an iterator for traversing the attributes in the model.
* This method is required by the interface IteratorAggregate. * This method is required by the interface IteratorAggregate.
* @return DictionaryIterator an iterator for traversing the items in the list. * @return ArrayIterator an iterator for traversing the items in the list.
*/ */
public function getIterator() public function getIterator()
{ {
$attributes = $this->getAttributes(); $attributes = $this->getAttributes();
return new DictionaryIterator($attributes); return new ArrayIterator($attributes);
} }
/** /**
......
...@@ -449,7 +449,7 @@ abstract class Module extends Component ...@@ -449,7 +449,7 @@ abstract class Module extends Component
public function getComponent($id, $load = true) public function getComponent($id, $load = true)
{ {
if (isset($this->_components[$id])) { if (isset($this->_components[$id])) {
if ($this->_components[$id] instanceof Component) { if ($this->_components[$id] instanceof Object) {
return $this->_components[$id]; return $this->_components[$id];
} elseif ($load) { } elseif ($load) {
Yii::trace("Loading component: $id", __METHOD__); Yii::trace("Loading component: $id", __METHOD__);
......
...@@ -20,7 +20,7 @@ class NotSupportedException extends Exception ...@@ -20,7 +20,7 @@ class NotSupportedException extends Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Not Supported'); return \Yii::t('yii', 'Not Supported');
} }
} }
...@@ -20,7 +20,7 @@ class UnknownClassException extends Exception ...@@ -20,7 +20,7 @@ class UnknownClassException extends Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Unknown Class'); return \Yii::t('yii', 'Unknown Class');
} }
} }
...@@ -20,7 +20,7 @@ class UnknownMethodException extends Exception ...@@ -20,7 +20,7 @@ class UnknownMethodException extends Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Unknown Method'); return \Yii::t('yii', 'Unknown Method');
} }
} }
...@@ -20,7 +20,7 @@ class UnknownPropertyException extends Exception ...@@ -20,7 +20,7 @@ class UnknownPropertyException extends Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Unknown Property'); return \Yii::t('yii', 'Unknown Property');
} }
} }
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* Vector implements an integer-indexed collection class.
*
* You can access, append, insert, remove an item from the vector
* by calling methods such as [[itemAt()]], [[add()]], [[insertAt()]],
* [[remove()]] and [[removeAt()]].
*
* To get the number of the items in the vector, use [[getCount()]].
*
* Because Vector implements a set of SPL interfaces, it can be used
* like a regular PHP array as follows,
*
* ~~~
* $vector[] = $item; // append new item at the end
* $vector[$index] = $item; // set new item at $index
* unset($vector[$index]); // remove the item at $index
* if (isset($vector[$index])) // if the vector has an item at $index
* foreach ($vector as $index => $item) // traverse each item in the vector
* $n = count($vector); // count the number of items
* ~~~
*
* Note that if you plan to extend Vector by performing additional operations
* with each addition or removal of an item (e.g. performing type check),
* please make sure you override [[insertAt()]] and [[removeAt()]].
*
* @property integer $count the number of items in the vector
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Countable
{
/**
* @var array internal data storage
*/
private $_d = array();
/**
* @var integer number of items
*/
private $_c = 0;
/**
* Constructor.
* Initializes the vector with an array or an iterable object.
* @param mixed $data the initial data to be populated into the vector.
* This can be an array or an iterable object.
* @param array $config name-value pairs that will be used to initialize the object properties
* @throws Exception if data is not well formed (neither an array nor an iterable object)
*/
public function __construct($data = array(), $config = array())
{
if (!empty($data)) {
$this->copyFrom($data);
}
parent::__construct($config);
}
/**
* Returns an iterator for traversing the items in the vector.
* This method is required by the SPL interface `IteratorAggregate`.
* It will be implicitly called when you use `foreach` to traverse the vector.
* @return VectorIterator an iterator for traversing the items in the vector.
*/
public function getIterator()
{
return new VectorIterator($this->_d);
}
/**
* Returns the number of items in the vector.
* This method is required by the SPL `Countable` interface.
* It will be implicitly called when you use `count($vector)`.
* @return integer number of items in the vector.
*/
public function count()
{
return $this->getCount();
}
/**
* Returns the number of items in the vector.
* @return integer the number of items in the vector
*/
public function getCount()
{
return $this->_c;
}
/**
* Returns the item at the specified index.
* @param integer $index the index of the item
* @return mixed the item at the index
* @throws InvalidParamException if the index is out of range
*/
public function itemAt($index)
{
if (isset($this->_d[$index])) {
return $this->_d[$index];
} elseif ($index >= 0 && $index < $this->_c) { // in case the value is null
return $this->_d[$index];
} else {
throw new InvalidParamException('Index out of range: ' . $index);
}
}
/**
* Appends an item at the end of the vector.
* @param mixed $item new item
* @return integer the zero-based index at which the item is added
* @throws Exception if the vector is read-only.
*/
public function add($item)
{
$this->insertAt($this->_c, $item);
return $this->_c - 1;
}
/**
* Inserts an item at the specified position.
* Original item at the position and the following items will be moved
* one step towards the end.
* @param integer $index the specified position.
* @param mixed $item new item to be inserted into the vector
* @throws InvalidParamException if the index specified is out of range, or the vector is read-only.
*/
public function insertAt($index, $item)
{
if ($index === $this->_c) {
$this->_d[$this->_c++] = $item;
} elseif ($index >= 0 && $index < $this->_c) {
array_splice($this->_d, $index, 0, array($item));
$this->_c++;
} else {
throw new InvalidParamException('Index out of range: ' . $index);
}
}
/**
* Removes an item from the vector.
* The vector will search for the item, and the first item found
* will be removed from the vector.
* @param mixed $item the item to be removed.
* @return mixed the index at which the item is being removed, or false
* if the item cannot be found in the vector.
* @throws Exception if the vector is read only.
*/
public function remove($item)
{
if (($index = $this->indexOf($item)) >= 0) {
$this->removeAt($index);
return $index;
} else {
return false;
}
}
/**
* Removes an item at the specified position.
* @param integer $index the index of the item to be removed.
* @return mixed the removed item.
* @throws InvalidParamException if the index is out of range, or the vector is read only.
*/
public function removeAt($index)
{
if ($index >= 0 && $index < $this->_c) {
$this->_c--;
if ($index === $this->_c) {
return array_pop($this->_d);
} else {
$item = $this->_d[$index];
array_splice($this->_d, $index, 1);
return $item;
}
} else {
throw new InvalidParamException('Index out of range: ' . $index);
}
}
/**
* Removes all items from the vector.
* @param boolean $safeClear whether to clear every item by calling [[removeAt]].
* Defaults to false, meaning all items in the vector will be cleared directly
* without calling [[removeAt]].
*/
public function removeAll($safeClear = false)
{
if ($safeClear) {
for ($i = $this->_c - 1; $i >= 0; --$i) {
$this->removeAt($i);
}
} else {
$this->_d = array();
$this->_c = 0;
}
}
/**
* Returns a value indicating whether the vector contains the specified item.
* Note that the search is based on strict PHP comparison.
* @param mixed $item the item
* @return boolean whether the vector contains the item
*/
public function has($item)
{
return $this->indexOf($item) >= 0;
}
/**
* Returns the index of the specified item in the vector.
* The index is zero-based. If the item is not found in the vector, -1 will be returned.
* Note that the search is based on strict PHP comparison.
* @param mixed $item the item
* @return integer the index of the item in the vector (0 based), -1 if not found.
*/
public function indexOf($item)
{
$index = array_search($item, $this->_d, true);
return $index === false ? -1 : $index;
}
/**
* Returns the vector as a PHP array.
* @return array the items in the vector.
*/
public function toArray()
{
return $this->_d;
}
/**
* Copies iterable data into the vector.
* Note, existing data in the vector will be cleared first.
* @param mixed $data the data to be copied from, must be an array or an object implementing `Traversable`
* @throws InvalidParamException if data is neither an array nor an object implementing `Traversable`.
*/
public function copyFrom($data)
{
if (is_array($data) || $data instanceof \Traversable) {
if ($this->_c > 0) {
$this->removeAll();
}
if ($data instanceof self) {
$data = $data->_d;
}
foreach ($data as $item) {
$this->add($item);
}
} else {
throw new InvalidParamException('Data must be either an array or an object implementing Traversable.');
}
}
/**
* Merges iterable data into the vector.
* New items will be appended to the end of the existing items.
* @param array|\Traversable $data the data to be merged with. It must be an array or object implementing Traversable
* @throws InvalidParamException if data is neither an array nor an object implementing `Traversable`.
*/
public function mergeWith($data)
{
if (is_array($data) || ($data instanceof \Traversable)) {
if ($data instanceof Vector) {
$data = $data->_d;
}
foreach ($data as $item) {
$this->add($item);
}
} else {
throw new InvalidParamException('The data to be merged with must be an array or an object implementing Traversable.');
}
}
/**
* Returns a value indicating whether there is an item at the specified offset.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `isset($vector[$offset])`.
* @param integer $offset the offset to be checked
* @return boolean whether there is an item at the specified offset.
*/
public function offsetExists($offset)
{
return $offset >= 0 && $offset < $this->_c;
}
/**
* Returns the item at the specified offset.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `$value = $vector[$offset];`.
* This is equivalent to [[itemAt]].
* @param integer $offset the offset to retrieve item.
* @return mixed the item at the offset
* @throws Exception if the offset is out of range
*/
public function offsetGet($offset)
{
return $this->itemAt($offset);
}
/**
* Sets the item at the specified offset.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `$vector[$offset] = $item;`.
* If the offset is null or equal to the number of the existing items,
* the new item will be appended to the vector.
* Otherwise, the existing item at the offset will be replaced with the new item.
* @param integer $offset the offset to set item
* @param mixed $item the item value
* @throws Exception if the offset is out of range, or the vector is read only.
*/
public function offsetSet($offset, $item)
{
if ($offset === null || $offset === $this->_c) {
$this->insertAt($this->_c, $item);
} else {
$this->removeAt($offset);
$this->insertAt($offset, $item);
}
}
/**
* Unsets the item at the specified offset.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `unset($vector[$offset])`.
* This is equivalent to [[removeAt]].
* @param integer $offset the offset to unset item
* @throws Exception if the offset is out of range, or the vector is read only.
*/
public function offsetUnset($offset)
{
$this->removeAt($offset);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* VectorIterator implements the SPL `Iterator` interface for [[Vector]].
*
* It allows [[Vector]] to return a new iterator for data traversing purpose.
* You normally do not use this class directly.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class VectorIterator implements \Iterator
{
/**
* @var array the data to be iterated through
*/
private $_d;
/**
* @var integer index of the current item
*/
private $_i;
/**
* @var integer count of the data items
*/
private $_c;
/**
* Constructor.
* @param array $data the data to be iterated through
*/
public function __construct(&$data)
{
$this->_d = &$data;
$this->_i = 0;
$this->_c = count($this->_d);
}
/**
* Rewinds the index of the current item.
* This method is required by the SPL interface `Iterator`.
*/
public function rewind()
{
$this->_i = 0;
}
/**
* Returns the key of the current item.
* This method is required by the SPL interface `Iterator`.
* @return integer the key of the current item
*/
public function key()
{
return $this->_i;
}
/**
* Returns the current item.
* This method is required by the SPL interface `Iterator`.
* @return mixed the current item
*/
public function current()
{
return $this->_d[$this->_i];
}
/**
* Moves the internal pointer to the next item.
* This method is required by the SPL interface `Iterator`.
*/
public function next()
{
$this->_i++;
}
/**
* Returns a value indicating whether there is an item at current position.
* This method is required by the SPL interface `Iterator`.
* @return boolean whether there is an item at current position.
*/
public function valid()
{
return $this->_i < $this->_c;
}
}
...@@ -373,9 +373,10 @@ class View extends Component ...@@ -373,9 +373,10 @@ class View extends Component
*/ */
public function beginBlock($id, $renderInPlace = false) public function beginBlock($id, $renderInPlace = false)
{ {
return Block::begin($this, array( return Block::begin(array(
'id' => $id, 'id' => $id,
'renderInPlace' => $renderInPlace, 'renderInPlace' => $renderInPlace,
'view' => $this,
)); ));
} }
...@@ -390,10 +391,10 @@ class View extends Component ...@@ -390,10 +391,10 @@ class View extends Component
/** /**
* Begins the rendering of content that is to be decorated by the specified view. * Begins the rendering of content that is to be decorated by the specified view.
* This method can be used to implement nested layout. For example, a layout can be embedded * This method can be used to implement nested layout. For example, a layout can be embedded
* in another layout file specified as '@app/view/layouts/base' like the following: * in another layout file specified as '@app/view/layouts/base.php' like the following:
* *
* ~~~ * ~~~
* <?php $this->beginContent('@app/view/layouts/base'); ?> * <?php $this->beginContent('@app/view/layouts/base.php'); ?>
* ...layout content here... * ...layout content here...
* <?php $this->endContent(); ?> * <?php $this->endContent(); ?>
* ~~~ * ~~~
...@@ -406,9 +407,10 @@ class View extends Component ...@@ -406,9 +407,10 @@ class View extends Component
*/ */
public function beginContent($viewFile, $params = array()) public function beginContent($viewFile, $params = array())
{ {
return ContentDecorator::begin($this, array( return ContentDecorator::begin(array(
'viewFile' => $viewFile, 'viewFile' => $viewFile,
'params' => $params, 'params' => $params,
'view' => $this,
)); ));
} }
...@@ -442,8 +444,9 @@ class View extends Component ...@@ -442,8 +444,9 @@ class View extends Component
public function beginCache($id, $properties = array()) public function beginCache($id, $properties = array())
{ {
$properties['id'] = $id; $properties['id'] = $id;
$properties['view'] = $this;
/** @var $cache FragmentCache */ /** @var $cache FragmentCache */
$cache = FragmentCache::begin($this, $properties); $cache = FragmentCache::begin($properties);
if ($cache->getCachedContent() !== false) { if ($cache->getCachedContent() !== false) {
$this->endCache(); $this->endCache();
return false; return false;
......
...@@ -17,16 +17,6 @@ use Yii; ...@@ -17,16 +17,6 @@ use Yii;
*/ */
class Widget extends Component class Widget extends Component
{ {
/**
* @var View the view object that this widget is associated with.
* The widget will use this view object to register any needed assets.
* This property is also required by [[render()]] and [[renderFile()]].
*/
public $view;
/**
* @var string id of the widget.
*/
private $_id;
/** /**
* @var integer a counter used to generate [[id]] for widgets. * @var integer a counter used to generate [[id]] for widgets.
* @internal * @internal
...@@ -39,32 +29,19 @@ class Widget extends Component ...@@ -39,32 +29,19 @@ class Widget extends Component
*/ */
public static $_stack = array(); public static $_stack = array();
/**
* Constructor.
* @param View $view the view object that this widget is associated with.
* The widget will use this view object to register any needed assets.
* It is also required by [[render()]] and [[renderFile()]].
* @param array $config name-value pairs that will be used to initialize the object properties
*/
public function __construct($view, $config = array())
{
$this->view = $view;
parent::__construct($config);
}
/** /**
* Begins a widget. * Begins a widget.
* This method creates an instance of the calling class. It will apply the configuration * This method creates an instance of the calling class. It will apply the configuration
* to the created instance. A matching [[end()]] call should be called later. * to the created instance. A matching [[end()]] call should be called later.
* @param View $view the view object that the newly created widget is associated with.
* @param array $config name-value pairs that will be used to initialize the object properties * @param array $config name-value pairs that will be used to initialize the object properties
* @return Widget the newly created widget instance * @return Widget the newly created widget instance
*/ */
public static function begin($view, $config = array()) public static function begin($config = array())
{ {
$config['class'] = get_called_class(); $config['class'] = get_called_class();
/** @var Widget $widget */ /** @var Widget $widget */
$widget = Yii::createObject($config, $view); $widget = Yii::createObject($config);
self::$_stack[] = $widget; self::$_stack[] = $widget;
return $widget; return $widget;
} }
...@@ -93,21 +70,22 @@ class Widget extends Component ...@@ -93,21 +70,22 @@ class Widget extends Component
/** /**
* Creates a widget instance and runs it. * Creates a widget instance and runs it.
* The widget rendering result is returned by this method. * The widget rendering result is returned by this method.
* @param View $view the view object that the newly created widget is associated with.
* @param array $config name-value pairs that will be used to initialize the object properties * @param array $config name-value pairs that will be used to initialize the object properties
* @return string the rendering result of the widget. * @return string the rendering result of the widget.
*/ */
public static function widget($view, $config = array()) public static function widget($config = array())
{ {
ob_start(); ob_start();
ob_implicit_flush(false); ob_implicit_flush(false);
/** @var Widget $widget */ /** @var Widget $widget */
$config['class'] = get_called_class(); $config['class'] = get_called_class();
$widget = Yii::createObject($config, $view); $widget = Yii::createObject($config);
$widget->run(); $widget->run();
return ob_get_clean(); return ob_get_clean();
} }
private $_id;
/** /**
* Returns the ID of the widget. * Returns the ID of the widget.
* @param boolean $autoGenerate whether to generate an ID if it is not set previously * @param boolean $autoGenerate whether to generate an ID if it is not set previously
...@@ -130,6 +108,32 @@ class Widget extends Component ...@@ -130,6 +108,32 @@ class Widget extends Component
$this->_id = $value; $this->_id = $value;
} }
private $_view;
/**
* Returns the view object that can be used to render views or view files.
* The [[render()]] and [[renderFile()]] methods will use
* this view object to implement the actual view rendering.
* If not set, it will default to the "view" application component.
* @return View the view object that can be used to render views or view files.
*/
public function getView()
{
if ($this->_view === null) {
$this->_view = Yii::$app->getView();
}
return $this->_view;
}
/**
* Sets the view object to be used by this widget.
* @param View $view the view object that can be used to render views or view files.
*/
public function setView($view)
{
$this->_view = $view;
}
/** /**
* Executes the widget. * Executes the widget.
*/ */
...@@ -159,7 +163,7 @@ class Widget extends Component ...@@ -159,7 +163,7 @@ class Widget extends Component
public function render($view, $params = array()) public function render($view, $params = array())
{ {
$viewFile = $this->findViewFile($view); $viewFile = $this->findViewFile($view);
return $this->view->renderFile($viewFile, $params, $this); return $this->getView()->renderFile($viewFile, $params, $this);
} }
/** /**
...@@ -171,7 +175,7 @@ class Widget extends Component ...@@ -171,7 +175,7 @@ class Widget extends Component
*/ */
public function renderFile($file, $params = array()) public function renderFile($file, $params = array())
{ {
return $this->view->renderFile($file, $params, $this); return $this->getView()->renderFile($file, $params, $this);
} }
/** /**
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\behaviors;
use yii\base\Behavior;
use yii\db\Expression;
use yii\db\ActiveRecord;
/**
* AutoTimestamp will automatically fill the attributes about creation time and updating time.
*
* AutoTimestamp fills the attributes when the associated AR model is being inserted or updated.
* You may specify an AR to use this behavior like the following:
*
* ~~~
* public function behaviors()
* {
* return array(
* 'timestamp' => array(
* 'class' => 'yii\behaviors\AutoTimestamp',
* ),
* );
* }
* ~~~
*
* By default, AutoTimestamp will fill the `create_time` attribute with the current timestamp
* when the associated AR object is being inserted; it will fill the `update_time` attribute
* with the timestamp when the AR object is being updated.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class AutoTimestamp extends Behavior
{
/**
* @var array list of attributes that are to be automatically filled with timestamps.
* The array keys are the ActiveRecord events upon which the attributes are to be filled with timestamps,
* and the array values are the corresponding attribute to be updated. You can use a string to represent
* a single attribute, or an array to represent a list of attributes.
* The default setting is to update the `create_time` attribute upon AR insertion,
* and update the `update_time` attribute upon AR updating.
*/
public $attributes = array(
ActiveRecord::EVENT_BEFORE_INSERT => 'create_time',
ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time',
);
/**
* @var \Closure|Expression The expression that will be used for generating the timestamp.
* This can be either an anonymous function that returns the timestamp value,
* or an [[Expression]] object representing a DB expression (e.g. `new Expression('NOW()')`).
* If not set, it will use the value of `time()` to fill the attributes.
*/
public $timestamp;
/**
* Declares event handlers for the [[owner]]'s events.
* @return array events (array keys) and the corresponding event handler methods (array values).
*/
public function events()
{
$events = array();
$behavior = $this;
foreach ($this->attributes as $event => $attributes) {
if (!is_array($attributes)) {
$attributes = array($attributes);
}
$events[$event] = function () use ($behavior, $attributes) {
$behavior->updateTimestamp($attributes);
};
}
return $events;
}
/**
* Updates the attributes with the current timestamp.
* @param array $attributes list of attributes to be updated.
*/
public function updateTimestamp($attributes)
{
foreach ($attributes as $attribute) {
$this->owner->$attribute = $this->evaluateTimestamp($attribute);
}
}
/**
* Gets the appropriate timestamp for the specified attribute.
* @param string $attribute attribute name
* @return mixed the timestamp value
*/
protected function evaluateTimestamp($attribute)
{
if ($this->timestamp instanceof Expression) {
return $this->timestamp;
} elseif ($this->timestamp !== null) {
return call_user_func($this->timestamp);
} else {
return time();
}
}
}
...@@ -63,12 +63,6 @@ ...@@ -63,12 +63,6 @@
"irc": "irc://irc.freenode.net/yii", "irc": "irc://irc.freenode.net/yii",
"source": "https://github.com/yiisoft/yii2" "source": "https://github.com/yiisoft/yii2"
}, },
"config": {
"vendor-dir": "yii/vendor"
},
"bin": [
"yii/yiic"
],
"require": { "require": {
"php": ">=5.3.0", "php": ">=5.3.0",
"michelf/php-markdown": "1.3", "michelf/php-markdown": "1.3",
......
...@@ -30,7 +30,7 @@ use yii\base\InvalidRouteException; ...@@ -30,7 +30,7 @@ use yii\base\InvalidRouteException;
* To run the console application, enter the following on the command line: * To run the console application, enter the following on the command line:
* *
* ~~~ * ~~~
* yiic <route> [--param1=value1 --param2 ...] * yii <route> [--param1=value1 --param2 ...]
* ~~~ * ~~~
* *
* where `<route>` refers to a controller route in the form of `ModuleID/ControllerID/ActionID` * where `<route>` refers to a controller route in the form of `ModuleID/ControllerID/ActionID`
...@@ -42,7 +42,7 @@ use yii\base\InvalidRouteException; ...@@ -42,7 +42,7 @@ use yii\base\InvalidRouteException;
* To use this command, simply type: * To use this command, simply type:
* *
* ~~~ * ~~~
* yiic help * yii help
* ~~~ * ~~~
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
...@@ -94,7 +94,7 @@ class Application extends \yii\base\Application ...@@ -94,7 +94,7 @@ class Application extends \yii\base\Application
list ($route, $params) = $request->resolve(); list ($route, $params) = $request->resolve();
return $this->runAction($route, $params); return $this->runAction($route, $params);
} else { } else {
throw new Exception(\Yii::t('yii|This script must be run from the command line.')); throw new Exception(\Yii::t('yii', 'This script must be run from the command line.'));
} }
} }
...@@ -113,7 +113,7 @@ class Application extends \yii\base\Application ...@@ -113,7 +113,7 @@ class Application extends \yii\base\Application
try { try {
return parent::runAction($route, $params); return parent::runAction($route, $params);
} catch (InvalidRouteException $e) { } catch (InvalidRouteException $e) {
throw new Exception(\Yii::t('yii|Unknown command "{command}".', array('{command}' => $route))); throw new Exception(\Yii::t('yii', 'Unknown command "{command}".', array('{command}' => $route)));
} }
} }
......
...@@ -18,10 +18,10 @@ use yii\helpers\Console; ...@@ -18,10 +18,10 @@ use yii\helpers\Console;
* *
* A controller consists of one or several actions known as sub-commands. * A controller consists of one or several actions known as sub-commands.
* Users call a console command by specifying the corresponding route which identifies a controller action. * Users call a console command by specifying the corresponding route which identifies a controller action.
* The `yiic` program is used when calling a console command, like the following: * The `yii` program is used when calling a console command, like the following:
* *
* ~~~ * ~~~
* yiic <route> [--param1=value1 --param2 ...] * yii <route> [--param1=value1 --param2 ...]
* ~~~ * ~~~
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
...@@ -91,7 +91,7 @@ class Controller extends \yii\base\Controller ...@@ -91,7 +91,7 @@ class Controller extends \yii\base\Controller
$args = isset($params[Request::ANONYMOUS_PARAMS]) ? $params[Request::ANONYMOUS_PARAMS] : array(); $args = isset($params[Request::ANONYMOUS_PARAMS]) ? $params[Request::ANONYMOUS_PARAMS] : array();
unset($params[Request::ANONYMOUS_PARAMS]); unset($params[Request::ANONYMOUS_PARAMS]);
if (!empty($params)) { if (!empty($params)) {
throw new Exception(Yii::t('yii|Unknown options: {params}', array( throw new Exception(Yii::t('yii', 'Unknown options: {params}', array(
'{params}' => implode(', ', array_keys($params)), '{params}' => implode(', ', array_keys($params)),
))); )));
} }
...@@ -115,7 +115,7 @@ class Controller extends \yii\base\Controller ...@@ -115,7 +115,7 @@ class Controller extends \yii\base\Controller
} }
if (!empty($missing)) { if (!empty($missing)) {
throw new Exception(Yii::t('yii|Missing required arguments: {params}', array( throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', array(
'{params}' => implode(', ', $missing), '{params}' => implode(', ', $missing),
))); )));
} }
......
...@@ -22,7 +22,7 @@ class Exception extends UserException ...@@ -22,7 +22,7 @@ class Exception extends UserException
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Error'); return \Yii::t('yii', 'Error');
} }
} }
...@@ -27,7 +27,7 @@ class Request extends \yii\base\Request ...@@ -27,7 +27,7 @@ class Request extends \yii\base\Request
public function resolve() public function resolve()
{ {
$rawParams = $this->getRawParams(); $rawParams = $this->getRawParams();
array_shift($rawParams); // the 1st argument is the yiic script name array_shift($rawParams); // the 1st argument is the yii script name
if (isset($rawParams[0])) { if (isset($rawParams[0])) {
$route = $rawParams[0]; $route = $rawParams[0];
......
...@@ -12,17 +12,32 @@ use yii\console\Exception; ...@@ -12,17 +12,32 @@ use yii\console\Exception;
use yii\console\Controller; use yii\console\Controller;
/** /**
* This command allows you to combine and compress your JavaScript and CSS files.
*
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class AssetController extends Controller class AssetController extends Controller
{ {
/**
* @var string controller default action ID.
*/
public $defaultAction = 'compress'; public $defaultAction = 'compress';
/**
* @var array list of asset bundles to be compressed.
* The keys are the bundle names, and the values are the configuration
* arrays for creating the [[yii\web\AssetBundle]] objects.
*/
public $bundles = array(); public $bundles = array();
/**
* @var array list of paths to the extensions, which assets should be also compressed.
* Each path should contain asset manifest file named "assets.php".
*/
public $extensions = array(); public $extensions = array();
/** /**
* @var array * @var array list of asset bundles, which represents output compressed files.
* You can specify the name of the output compressed file using 'css' and 'js' keys:
* For example:
* ~~~ * ~~~
* 'all' => array( * 'all' => array(
* 'css' => 'all.css', * 'css' => 'all.css',
...@@ -30,34 +45,74 @@ class AssetController extends Controller ...@@ -30,34 +45,74 @@ class AssetController extends Controller
* 'depends' => array( ... ), * 'depends' => array( ... ),
* ) * )
* ~~~ * ~~~
* File names can contain placeholder "{ts}", which will be filled by current timestamp, while
* file creation.
*/ */
public $targets = array(); public $targets = array();
/**
* @var array configuration for [[yii\web\AssetManager]] instance, which will be used
* for assets publishing.
*/
public $assetManager = array(); public $assetManager = array();
/**
* @var string|callback Java Script file compressor.
* If a string, it is treated as shell command template, which should contain
* placeholders {from} - source file name - and {to} - output file name.
* If an array, it is treated as PHP callback, which should perform the compression.
*
* Default value relies on usage of "Closure Compiler"
* @see https://developers.google.com/closure/compiler/
*/
public $jsCompressor = 'java -jar compiler.jar --js {from} --js_output_file {to}'; public $jsCompressor = 'java -jar compiler.jar --js {from} --js_output_file {to}';
/**
* @var string|callback CSS file compressor.
* If a string, it is treated as shell command template, which should contain
* placeholders {from} - source file name - and {to} - output file name.
* If an array, it is treated as PHP callback, which should perform the compression.
*
* Default value relies on usage of "YUI Compressor"
* @see https://github.com/yui/yuicompressor/
*/
public $cssCompressor = 'java -jar yuicompressor.jar {from} -o {to}'; public $cssCompressor = 'java -jar yuicompressor.jar {from} -o {to}';
/**
* Combines and compresses the asset files according to the given configuration.
* During the process new asset bundle configuration file will be created.
* You should replace your original asset bundle configuration with this file in order to use compressed files.
* @param string $configFile configuration file name.
* @param string $bundleFile output asset bundles configuration file name.
*/
public function actionCompress($configFile, $bundleFile) public function actionCompress($configFile, $bundleFile)
{ {
$this->loadConfiguration($configFile); $this->loadConfiguration($configFile);
$bundles = $this->loadBundles($this->bundles, $this->extensions); $bundles = $this->loadBundles($this->bundles, $this->extensions);
$targets = $this->loadTargets($this->targets, $bundles); $targets = $this->loadTargets($this->targets, $bundles);
$this->publishBundles($bundles, $this->publishOptions); $this->publishBundles($bundles, $this->assetManager);
$timestamp = time(); $timestamp = time();
foreach ($targets as $target) { foreach ($targets as $name => $target) {
echo "Creating output bundle '{$name}':\n";
if (!empty($target->js)) { if (!empty($target->js)) {
$this->buildTarget($target, 'js', $bundles, $timestamp); $this->buildTarget($target, 'js', $bundles, $timestamp);
} }
if (!empty($target->css)) { if (!empty($target->css)) {
$this->buildTarget($target, 'css', $bundles, $timestamp); $this->buildTarget($target, 'css', $bundles, $timestamp);
} }
echo "\n";
} }
$targets = $this->adjustDependency($targets, $bundles); $targets = $this->adjustDependency($targets, $bundles);
$this->saveTargets($targets, $bundleFile); $this->saveTargets($targets, $bundleFile);
} }
/**
* Applies configuration from the given file to self instance.
* @param string $configFile configuration file name.
* @throws \yii\console\Exception on failure.
*/
protected function loadConfiguration($configFile) protected function loadConfiguration($configFile)
{ {
echo "Loading configuration from '{$configFile}'...\n";
foreach (require($configFile) as $name => $value) { foreach (require($configFile) as $name => $value) {
if (property_exists($this, $name)) { if (property_exists($this, $name)) {
$this->$name = $value; $this->$name = $value;
...@@ -74,8 +129,15 @@ class AssetController extends Controller ...@@ -74,8 +129,15 @@ class AssetController extends Controller
} }
} }
/**
* Creates full list of source asset bundles.
* @param array[] $bundles list of asset bundle configurations.
* @param array $extensions list of the extension paths.
* @return \yii\web\AssetBundle[] list of source asset bundles.
*/
protected function loadBundles($bundles, $extensions) protected function loadBundles($bundles, $extensions)
{ {
echo "Collecting source bundles information...\n";
$result = array(); $result = array();
foreach ($bundles as $name => $bundle) { foreach ($bundles as $name => $bundle) {
$bundle['class'] = 'yii\\web\\AssetBundle'; $bundle['class'] = 'yii\\web\\AssetBundle';
...@@ -96,6 +158,13 @@ class AssetController extends Controller ...@@ -96,6 +158,13 @@ class AssetController extends Controller
return $result; return $result;
} }
/**
* Creates full list of output asset bundles.
* @param array $targets output asset bundles configuration.
* @param \yii\web\AssetBundle[] $bundles list of source asset bundles.
* @return \yii\web\AssetBundle[] list of output asset bundles.
* @throws \yii\console\Exception on failure.
*/
protected function loadTargets($targets, $bundles) protected function loadTargets($targets, $bundles)
{ {
// build the dependency order of bundles // build the dependency order of bundles
...@@ -151,26 +220,31 @@ class AssetController extends Controller ...@@ -151,26 +220,31 @@ class AssetController extends Controller
} }
/** /**
* @param \yii\web\AssetBundle[] $bundles * Publishes given asset bundles.
* @param array $options * @param \yii\web\AssetBundle[] $bundles asset bundles to be published.
* @param array $options assert manager instance configuration.
*/ */
protected function publishBundles($bundles, $options) protected function publishBundles($bundles, $options)
{ {
echo "\nPublishing bundles:\n";
if (!isset($options['class'])) { if (!isset($options['class'])) {
$options['class'] = 'yii\\web\\AssetManager'; $options['class'] = 'yii\\web\\AssetManager';
} }
$am = Yii::createObject($options); $am = Yii::createObject($options);
foreach ($bundles as $bundle) { foreach ($bundles as $name => $bundle) {
$bundle->publish($am); $bundle->publish($am);
echo " '".$name."' published.\n";
} }
echo "\n";
} }
/** /**
* @param \yii\web\AssetBundle $target * Builds output asset bundle.
* @param string $type either "js" or "css" * @param \yii\web\AssetBundle $target output asset bundle
* @param \yii\web\AssetBundle[] $bundles * @param string $type either "js" or "css".
* @param integer $timestamp * @param \yii\web\AssetBundle[] $bundles source asset bundles.
* @throws Exception * @param integer $timestamp current timestamp.
* @throws Exception on failure.
*/ */
protected function buildTarget($target, $type, $bundles, $timestamp) protected function buildTarget($target, $type, $bundles, $timestamp)
{ {
...@@ -182,7 +256,7 @@ class AssetController extends Controller ...@@ -182,7 +256,7 @@ class AssetController extends Controller
foreach ($target->depends as $name) { foreach ($target->depends as $name) {
if (isset($bundles[$name])) { if (isset($bundles[$name])) {
foreach ($bundles[$name]->$type as $file) { foreach ($bundles[$name]->$type as $file) {
$inputFiles[] = $bundles[$name]->basePath . '/' . $file; $inputFiles[] = $bundles[$name]->basePath . $file;
} }
} else { } else {
throw new Exception("Unknown bundle: $name"); throw new Exception("Unknown bundle: $name");
...@@ -196,8 +270,16 @@ class AssetController extends Controller ...@@ -196,8 +270,16 @@ class AssetController extends Controller
$target->$type = array($outputFile); $target->$type = array($outputFile);
} }
/**
* Adjust dependencies between asset bundles in the way source bundles begin to depend on output ones.
* @param \yii\web\AssetBundle[] $targets output asset bundles.
* @param \yii\web\AssetBundle[] $bundles source asset bundles.
* @return \yii\web\AssetBundle[] output asset bundles.
*/
protected function adjustDependency($targets, $bundles) protected function adjustDependency($targets, $bundles)
{ {
echo "Creating new bundle configuration...\n";
$map = array(); $map = array();
foreach ($targets as $name => $target) { foreach ($targets as $name => $target) {
foreach ($target->depends as $bundle) { foreach ($target->depends as $bundle) {
...@@ -231,6 +313,13 @@ class AssetController extends Controller ...@@ -231,6 +313,13 @@ class AssetController extends Controller
return $targets; return $targets;
} }
/**
* Registers asset bundles including their dependencies.
* @param \yii\web\AssetBundle[] $bundles asset bundles list.
* @param string $name bundle name.
* @param array $registered stores already registered names.
* @throws \yii\console\Exception if circular dependency is detected.
*/
protected function registerBundle($bundles, $name, &$registered) protected function registerBundle($bundles, $name, &$registered)
{ {
if (!isset($registered[$name])) { if (!isset($registered[$name])) {
...@@ -246,6 +335,11 @@ class AssetController extends Controller ...@@ -246,6 +335,11 @@ class AssetController extends Controller
} }
} }
/**
* Saves new asset bundles configuration.
* @param \yii\web\AssetBundle[] $targets list of asset bundles to be saved.
* @param string $bundleFile output file name.
*/
protected function saveTargets($targets, $bundleFile) protected function saveTargets($targets, $bundleFile)
{ {
$array = array(); $array = array();
...@@ -258,70 +352,117 @@ class AssetController extends Controller ...@@ -258,70 +352,117 @@ class AssetController extends Controller
} }
$array = var_export($array, true); $array = var_export($array, true);
$version = date('Y-m-d H:i:s', time()); $version = date('Y-m-d H:i:s', time());
file_put_contents($bundleFile, <<<EOD $bytesWritten = file_put_contents($bundleFile, <<<EOD
<?php <?php
/** /**
* This file is generated by the "yiic script" command. * This file is generated by the "yii script" command.
* DO NOT MODIFY THIS FILE DIRECTLY. * DO NOT MODIFY THIS FILE DIRECTLY.
* @version $version * @version $version
*/ */
return $array; return $array;
EOD EOD
); );
if ($bytesWritten <= 0) {
throw new Exception("Unable to write output bundle configuration at '{$bundleFile}'.");
}
echo "Output bundle configuration created at '{$bundleFile}'.\n";
} }
/**
* Compresses given Java Script files and combines them into the single one.
* @param array $inputFiles list of source file names.
* @param string $outputFile output file name.
* @throws \yii\console\Exception on failure
*/
protected function compressJsFiles($inputFiles, $outputFile) protected function compressJsFiles($inputFiles, $outputFile)
{ {
if (empty($inputFiles)) {
return;
}
echo " Compressing JavaScript files...\n";
if (is_string($this->jsCompressor)) { if (is_string($this->jsCompressor)) {
$tmpFile = $outputFile . '.tmp'; $tmpFile = $outputFile . '.tmp';
$this->combineJsFiles($inputFiles, $tmpFile); $this->combineJsFiles($inputFiles, $tmpFile);
$log = shell_exec(strtr($this->jsCompressor, array( $log = shell_exec(strtr($this->jsCompressor, array(
'{from}' => $tmpFile, '{from}' => escapeshellarg($tmpFile),
'{to}' => $outputFile, '{to}' => escapeshellarg($outputFile),
))); )));
@unlink($tmpFile); @unlink($tmpFile);
} else { } else {
$log = call_user_func($this->jsCompressor, $this, $inputFiles, $outputFile); $log = call_user_func($this->jsCompressor, $this, $inputFiles, $outputFile);
} }
if (!file_exists($outputFile)) {
throw new Exception("Unable to compress JavaScript files into '{$outputFile}'.");
}
echo " JavaScript files compressed into '{$outputFile}'.\n";
} }
/**
* Compresses given CSS files and combines them into the single one.
* @param array $inputFiles list of source file names.
* @param string $outputFile output file name.
* @throws \yii\console\Exception on failure
*/
protected function compressCssFiles($inputFiles, $outputFile) protected function compressCssFiles($inputFiles, $outputFile)
{ {
if (empty($inputFiles)) {
return;
}
echo " Compressing CSS files...\n";
if (is_string($this->cssCompressor)) { if (is_string($this->cssCompressor)) {
$tmpFile = $outputFile . '.tmp'; $tmpFile = $outputFile . '.tmp';
$this->combineCssFiles($inputFiles, $tmpFile); $this->combineCssFiles($inputFiles, $tmpFile);
$log = shell_exec(strtr($this->cssCompressor, array( $log = shell_exec(strtr($this->cssCompressor, array(
'{from}' => $inputFiles, '{from}' => escapeshellarg($tmpFile),
'{to}' => $outputFile, '{to}' => escapeshellarg($outputFile),
))); )));
@unlink($tmpFile);
} else { } else {
$log = call_user_func($this->cssCompressor, $this, $inputFiles, $outputFile); $log = call_user_func($this->cssCompressor, $this, $inputFiles, $outputFile);
} }
if (!file_exists($outputFile)) {
throw new Exception("Unable to compress CSS files into '{$outputFile}'.");
}
echo " CSS files compressed into '{$outputFile}'.\n";
} }
public function combineJsFiles($files, $tmpFile) /**
* Combines Java Script files into a single one.
* @param array $inputFiles source file names.
* @param string $outputFile output file name.
*/
public function combineJsFiles($inputFiles, $outputFile)
{ {
$content = ''; $content = '';
foreach ($files as $file) { foreach ($inputFiles as $file) {
$content .= "/*** BEGIN FILE: $file ***/\n" $content .= "/*** BEGIN FILE: $file ***/\n"
. file_get_contents($file) . file_get_contents($file)
. "/*** END FILE: $file ***/\n"; . "/*** END FILE: $file ***/\n";
} }
file_put_contents($tmpFile, $content); file_put_contents($outputFile, $content);
} }
public function combineCssFiles($files, $tmpFile) /**
* Combines CSS files into a single one.
* @param array $inputFiles source file names.
* @param string $outputFile output file name.
*/
public function combineCssFiles($inputFiles, $outputFile)
{ {
// todo: adjust url() references in CSS files // todo: adjust url() references in CSS files
$content = ''; $content = '';
foreach ($files as $file) { foreach ($inputFiles as $file) {
$content .= "/*** BEGIN FILE: $file ***/\n" $content .= "/*** BEGIN FILE: $file ***/\n"
. file_get_contents($file) . file_get_contents($file)
. "/*** END FILE: $file ***/\n"; . "/*** END FILE: $file ***/\n";
} }
file_put_contents($tmpFile, $content); file_put_contents($outputFile, $content);
} }
/**
* Creates template of configuration file for [[actionCompress]].
* @param string $configFile output file name.
*/
public function actionTemplate($configFile) public function actionTemplate($configFile)
{ {
$template = <<<EOD $template = <<<EOD
...@@ -348,6 +489,16 @@ return array( ...@@ -348,6 +489,16 @@ return array(
), ),
); );
EOD; EOD;
file_put_contents($configFile, $template); if (file_exists($configFile)) {
if (!$this->confirm("File '{$configFile}' already exists. Do you wish to overwrite it?")) {
return;
}
}
$bytesWritten = file_put_contents($configFile, $template);
if ($bytesWritten<=0) {
echo "Error: unable to write file '{$configFile}'!\n\n";
} else {
echo "Configuration file template created at '{$configFile}'.\n\n";
}
} }
} }
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
namespace yii\console\controllers; namespace yii\console\controllers;
use Yii;
use yii\console\Controller; use yii\console\Controller;
use yii\console\Exception; use yii\console\Exception;
use yii\caching\Cache; use yii\caching\Cache;
...@@ -19,9 +20,28 @@ use yii\caching\Cache; ...@@ -19,9 +20,28 @@ use yii\caching\Cache;
*/ */
class CacheController extends Controller class CacheController extends Controller
{ {
/**
* Lists the caches that can be flushed.
*/
public function actionIndex() public function actionIndex()
{ {
$this->forward('help/index', array('-args' => array('cache/flush'))); $caches = array();
$components = Yii::$app->getComponents();
foreach ($components as $name => $component) {
if ($component instanceof Cache) {
$caches[$name] = get_class($component);
} elseif (is_array($component) && isset($component['class']) && strpos($component['class'], 'Cache') !== false) {
$caches[$name] = $component['class'];
}
}
if (!empty($caches)) {
echo "The following caches can be flushed:\n\n";
foreach ($caches as $name => $class) {
echo " * $name: $class\n";
}
} else {
echo "No cache is used.\n";
}
} }
/** /**
...@@ -33,7 +53,7 @@ class CacheController extends Controller ...@@ -33,7 +53,7 @@ class CacheController extends Controller
public function actionFlush($component = 'cache') public function actionFlush($component = 'cache')
{ {
/** @var $cache Cache */ /** @var $cache Cache */
$cache = \Yii::$app->getComponent($component); $cache = Yii::$app->getComponent($component);
if (!$cache || !$cache instanceof Cache) { if (!$cache || !$cache instanceof Cache) {
throw new Exception('Application component "'.$component.'" is not defined or not a cache.'); throw new Exception('Application component "'.$component.'" is not defined or not a cache.');
} }
......
...@@ -25,7 +25,7 @@ use yii\helpers\StringHelper; ...@@ -25,7 +25,7 @@ use yii\helpers\StringHelper;
* This command can be used as follows on command line: * This command can be used as follows on command line:
* *
* ~~~ * ~~~
* yiic help [command name] * yii help [command name]
* ~~~ * ~~~
* *
* In the above, if the command name is not provided, all * In the above, if the command name is not provided, all
...@@ -41,8 +41,8 @@ class HelpController extends Controller ...@@ -41,8 +41,8 @@ class HelpController extends Controller
* about a particular command. For example, * about a particular command. For example,
* *
* ~~~ * ~~~
* yiic help # list available commands * yii help # list available commands
* yiic help message # display help info about "message" * yii help message # display help info about "message"
* ~~~ * ~~~
* *
* @param string $command The name of the command to show help about. * @param string $command The name of the command to show help about.
...@@ -55,7 +55,7 @@ class HelpController extends Controller ...@@ -55,7 +55,7 @@ class HelpController extends Controller
if ($command !== null) { if ($command !== null) {
$result = Yii::$app->createController($command); $result = Yii::$app->createController($command);
if ($result === false) { if ($result === false) {
throw new Exception(Yii::t('yii|No help for unknown command "{command}".', array( throw new Exception(Yii::t('yii', 'No help for unknown command "{command}".', array(
'{command}' => $command, '{command}' => $command,
))); )));
} }
...@@ -148,7 +148,7 @@ class HelpController extends Controller ...@@ -148,7 +148,7 @@ class HelpController extends Controller
echo "* $command\n"; echo "* $command\n";
} }
echo "\nTo see the help of each command, enter:\n"; echo "\nTo see the help of each command, enter:\n";
echo "\n yiic help <command-name>\n\n"; echo "\n yii help <command-name>\n\n";
} else { } else {
echo "\nNo commands are found.\n"; echo "\nNo commands are found.\n";
} }
...@@ -188,7 +188,7 @@ class HelpController extends Controller ...@@ -188,7 +188,7 @@ class HelpController extends Controller
echo "\n"; echo "\n";
} }
echo "\n\nTo see the detailed information about individual sub-commands, enter:\n"; echo "\n\nTo see the detailed information about individual sub-commands, enter:\n";
echo "\n yiic help <sub-command>\n\n"; echo "\n yii help <sub-command>\n\n";
} }
} }
...@@ -239,7 +239,7 @@ class HelpController extends Controller ...@@ -239,7 +239,7 @@ class HelpController extends Controller
{ {
$action = $controller->createAction($actionID); $action = $controller->createAction($actionID);
if ($action === null) { if ($action === null) {
throw new Exception(Yii::t('yii|No help for unknown sub-command "{command}".', array( throw new Exception(Yii::t('yii', 'No help for unknown sub-command "{command}".', array(
'{command}' => rtrim($controller->getUniqueId() . '/' . $actionID, '/'), '{command}' => rtrim($controller->getUniqueId() . '/' . $actionID, '/'),
))); )));
} }
...@@ -259,9 +259,9 @@ class HelpController extends Controller ...@@ -259,9 +259,9 @@ class HelpController extends Controller
echo "\nUSAGE\n\n"; echo "\nUSAGE\n\n";
if ($action->id === $controller->defaultAction) { if ($action->id === $controller->defaultAction) {
echo 'yiic ' . $controller->getUniqueId(); echo 'yii ' . $controller->getUniqueId();
} else { } else {
echo "yiic " . $action->getUniqueId(); echo "yii " . $action->getUniqueId();
} }
list ($required, $optional) = $this->getArgHelps($method, isset($tags['param']) ? $tags['param'] : array()); list ($required, $optional) = $this->getArgHelps($method, isset($tags['param']) ? $tags['param'] : array());
if (!empty($required)) { if (!empty($required)) {
......
...@@ -194,7 +194,7 @@ class MessageController extends Controller ...@@ -194,7 +194,7 @@ class MessageController extends Controller
/** /**
* Message translations. * Message translations.
* *
* This file is automatically generated by 'yiic message' command. * This file is automatically generated by 'yii message' command.
* It contains the localizable messages extracted from source code. * It contains the localizable messages extracted from source code.
* You may modify this file by translating the extracted messages. * You may modify this file by translating the extracted messages.
* *
......
...@@ -42,13 +42,13 @@ use yii\helpers\ArrayHelper; ...@@ -42,13 +42,13 @@ use yii\helpers\ArrayHelper;
* *
* ~~~ * ~~~
* # creates a new migration named 'create_user_table' * # creates a new migration named 'create_user_table'
* yiic migrate/create create_user_table * yii migrate/create create_user_table
* *
* # applies ALL new migrations * # applies ALL new migrations
* yiic migrate * yii migrate
* *
* # reverts the last applied migration * # reverts the last applied migration
* yiic migrate/down * yii migrate/down
* ~~~ * ~~~
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
...@@ -135,8 +135,8 @@ class MigrateController extends Controller ...@@ -135,8 +135,8 @@ class MigrateController extends Controller
* For example, * For example,
* *
* ~~~ * ~~~
* yiic migrate # apply all new migrations * yii migrate # apply all new migrations
* yiic migrate 3 # apply the first 3 new migrations * yii migrate 3 # apply the first 3 new migrations
* ~~~ * ~~~
* *
* @param integer $limit the number of new migrations to be applied. If 0, it means * @param integer $limit the number of new migrations to be applied. If 0, it means
...@@ -184,8 +184,8 @@ class MigrateController extends Controller ...@@ -184,8 +184,8 @@ class MigrateController extends Controller
* For example, * For example,
* *
* ~~~ * ~~~
* yiic migrate/down # revert the last migration * yii migrate/down # revert the last migration
* yiic migrate/down 3 # revert the last 3 migrations * yii migrate/down 3 # revert the last 3 migrations
* ~~~ * ~~~
* *
* @param integer $limit the number of migrations to be reverted. Defaults to 1, * @param integer $limit the number of migrations to be reverted. Defaults to 1,
...@@ -231,8 +231,8 @@ class MigrateController extends Controller ...@@ -231,8 +231,8 @@ class MigrateController extends Controller
* them again. For example, * them again. For example,
* *
* ~~~ * ~~~
* yiic migrate/redo # redo the last applied migration * yii migrate/redo # redo the last applied migration
* yiic migrate/redo 3 # redo the last 3 applied migrations * yii migrate/redo 3 # redo the last 3 applied migrations
* ~~~ * ~~~
* *
* @param integer $limit the number of migrations to be redone. Defaults to 1, * @param integer $limit the number of migrations to be redone. Defaults to 1,
...@@ -284,8 +284,8 @@ class MigrateController extends Controller ...@@ -284,8 +284,8 @@ class MigrateController extends Controller
* them again. For example, * them again. For example,
* *
* ~~~ * ~~~
* yiic migrate/to 101129_185401 # using timestamp * yii migrate/to 101129_185401 # using timestamp
* yiic migrate/to m101129_185401_create_user_table # using full name * yii migrate/to m101129_185401_create_user_table # using full name
* ~~~ * ~~~
* *
* @param string $version the version name that the application should be migrated to. * @param string $version the version name that the application should be migrated to.
...@@ -332,8 +332,8 @@ class MigrateController extends Controller ...@@ -332,8 +332,8 @@ class MigrateController extends Controller
* No actual migration will be performed. * No actual migration will be performed.
* *
* ~~~ * ~~~
* yiic migrate/mark 101129_185401 # using timestamp * yii migrate/mark 101129_185401 # using timestamp
* yiic migrate/mark m101129_185401_create_user_table # using full name * yii migrate/mark m101129_185401_create_user_table # using full name
* ~~~ * ~~~
* *
* @param string $version the version at which the migration history should be marked. * @param string $version the version at which the migration history should be marked.
...@@ -398,9 +398,9 @@ class MigrateController extends Controller ...@@ -398,9 +398,9 @@ class MigrateController extends Controller
* so far. For example, * so far. For example,
* *
* ~~~ * ~~~
* yiic migrate/history # showing the last 10 migrations * yii migrate/history # showing the last 10 migrations
* yiic migrate/history 5 # showing the last 5 migrations * yii migrate/history 5 # showing the last 5 migrations
* yiic migrate/history 0 # showing the whole history * yii migrate/history 0 # showing the whole history
* ~~~ * ~~~
* *
* @param integer $limit the maximum number of migrations to be displayed. * @param integer $limit the maximum number of migrations to be displayed.
...@@ -432,9 +432,9 @@ class MigrateController extends Controller ...@@ -432,9 +432,9 @@ class MigrateController extends Controller
* For example, * For example,
* *
* ~~~ * ~~~
* yiic migrate/new # showing the first 10 new migrations * yii migrate/new # showing the first 10 new migrations
* yiic migrate/new 5 # showing the first 5 new migrations * yii migrate/new 5 # showing the first 5 new migrations
* yiic migrate/new 0 # showing all new migrations * yii migrate/new 0 # showing all new migrations
* ~~~ * ~~~
* *
* @param integer $limit the maximum number of new migrations to be displayed. * @param integer $limit the maximum number of new migrations to be displayed.
...@@ -469,7 +469,7 @@ class MigrateController extends Controller ...@@ -469,7 +469,7 @@ class MigrateController extends Controller
* skeleton by filling up the actual migration logic. * skeleton by filling up the actual migration logic.
* *
* ~~~ * ~~~
* yiic migrate/create create_user_table * yii migrate/create create_user_table
* ~~~ * ~~~
* *
* @param string $name the name of the new migration. This should only contain * @param string $name the name of the new migration. This should only contain
......
...@@ -73,6 +73,22 @@ class ActiveRecord extends Model ...@@ -73,6 +73,22 @@ class ActiveRecord extends Model
*/ */
const EVENT_AFTER_DELETE = 'afterDelete'; const EVENT_AFTER_DELETE = 'afterDelete';
/**
* Represents insert ActiveRecord operation. This constant is used for specifying set of atomic operations
* for particular scenario in the [[scenarios()]] method.
*/
const OP_INSERT = 'insert';
/**
* Represents update ActiveRecord operation. This constant is used for specifying set of atomic operations
* for particular scenario in the [[scenarios()]] method.
*/
const OP_UPDATE = 'update';
/**
* Represents delete ActiveRecord operation. This constant is used for specifying set of atomic operations
* for particular scenario in the [[scenarios()]] method.
*/
const OP_DELETE = 'delete';
/** /**
* @var array attribute values indexed by attribute names * @var array attribute values indexed by attribute names
*/ */
...@@ -664,10 +680,39 @@ class ActiveRecord extends Model ...@@ -664,10 +680,39 @@ class ActiveRecord extends Model
* @param array $attributes list of attributes that need to be saved. Defaults to null, * @param array $attributes list of attributes that need to be saved. Defaults to null,
* meaning all attributes that are loaded from DB will be saved. * meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the attributes are valid and the record is inserted successfully. * @return boolean whether the attributes are valid and the record is inserted successfully.
* @throws \Exception in case insert failed.
*/ */
public function insert($runValidation = true, $attributes = null) public function insert($runValidation = true, $attributes = null)
{ {
if ($runValidation && !$this->validate($attributes) || !$this->beforeSave(true)) { if ($runValidation && !$this->validate($attributes)) {
return false;
}
$db = static::getDb();
$transaction = $this->isOperationAtomic(self::OP_INSERT) && $db->getTransaction() === null ? $db->beginTransaction() : null;
try {
$result = $this->insertInternal($attributes);
if ($transaction !== null) {
if ($result === false) {
$transaction->rollback();
} else {
$transaction->commit();
}
}
} catch (\Exception $e) {
if ($transaction !== null) {
$transaction->rollback();
}
throw $e;
}
return $result;
}
/**
* @see ActiveRecord::insert()
*/
private function insertInternal($attributes = null)
{
if (!$this->beforeSave(true)) {
return false; return false;
} }
$values = $this->getDirtyAttributes($attributes); $values = $this->getDirtyAttributes($attributes);
...@@ -678,22 +723,23 @@ class ActiveRecord extends Model ...@@ -678,22 +723,23 @@ class ActiveRecord extends Model
} }
$db = static::getDb(); $db = static::getDb();
$command = $db->createCommand()->insert($this->tableName(), $values); $command = $db->createCommand()->insert($this->tableName(), $values);
if ($command->execute()) { if (!$command->execute()) {
$table = $this->getTableSchema(); return false;
if ($table->sequenceName !== null) { }
foreach ($table->primaryKey as $name) { $table = $this->getTableSchema();
if (!isset($this->_attributes[$name])) { if ($table->sequenceName !== null) {
$this->_oldAttributes[$name] = $this->_attributes[$name] = $db->getLastInsertID($table->sequenceName); foreach ($table->primaryKey as $name) {
break; if (!isset($this->_attributes[$name])) {
} $this->_oldAttributes[$name] = $this->_attributes[$name] = $db->getLastInsertID($table->sequenceName);
break;
} }
} }
foreach ($values as $name => $value) {
$this->_oldAttributes[$name] = $value;
}
$this->afterSave(true);
return true;
} }
foreach ($values as $name => $value) {
$this->_oldAttributes[$name] = $value;
}
$this->afterSave(true);
return true;
} }
/** /**
...@@ -744,39 +790,67 @@ class ActiveRecord extends Model ...@@ -744,39 +790,67 @@ class ActiveRecord extends Model
* or [[beforeSave()]] stops the updating process. * or [[beforeSave()]] stops the updating process.
* @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
* being updated is outdated. * being updated is outdated.
* @throws \Exception in case update failed.
*/ */
public function update($runValidation = true, $attributes = null) public function update($runValidation = true, $attributes = null)
{ {
if ($runValidation && !$this->validate($attributes) || !$this->beforeSave(false)) { if ($runValidation && !$this->validate($attributes)) {
return false; return false;
} }
$values = $this->getDirtyAttributes($attributes); $db = static::getDb();
if (!empty($values)) { $transaction = $this->isOperationAtomic(self::OP_UPDATE) && $db->getTransaction() === null ? $db->beginTransaction() : null;
$condition = $this->getOldPrimaryKey(true); try {
$lock = $this->optimisticLock(); $result = $this->updateInternal($attributes);
if ($lock !== null) { if ($transaction !== null) {
if (!isset($values[$lock])) { if ($result === false) {
$values[$lock] = $this->$lock + 1; $transaction->rollback();
} else {
$transaction->commit();
} }
$condition[$lock] = $this->$lock;
} }
// We do not check the return value of updateAll() because it's possible } catch (\Exception $e) {
// that the UPDATE statement doesn't change anything and thus returns 0. if ($transaction !== null) {
$rows = $this->updateAll($values, $condition); $transaction->rollback();
if ($lock !== null && !$rows) {
throw new StaleObjectException('The object being updated is outdated.');
} }
throw $e;
}
return $result;
}
foreach ($values as $name => $value) { /**
$this->_oldAttributes[$name] = $this->_attributes[$name]; * @see CActiveRecord::update()
* @throws StaleObjectException
*/
private function updateInternal($attributes = null)
{
if (!$this->beforeSave(false)) {
return false;
}
$values = $this->getDirtyAttributes($attributes);
if (empty($values)) {
return 0;
}
$condition = $this->getOldPrimaryKey(true);
$lock = $this->optimisticLock();
if ($lock !== null) {
if (!isset($values[$lock])) {
$values[$lock] = $this->$lock + 1;
} }
$condition[$lock] = $this->$lock;
}
// We do not check the return value of updateAll() because it's possible
// that the UPDATE statement doesn't change anything and thus returns 0.
$rows = $this->updateAll($values, $condition);
$this->afterSave(false); if ($lock !== null && !$rows) {
return $rows; throw new StaleObjectException('The object being updated is outdated.');
} else { }
return 0;
foreach ($values as $name => $value) {
$this->_oldAttributes[$name] = $this->_attributes[$name];
} }
$this->afterSave(false);
return $rows;
} }
/** /**
...@@ -826,27 +900,43 @@ class ActiveRecord extends Model ...@@ -826,27 +900,43 @@ class ActiveRecord extends Model
* Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful. * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
* @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
* being deleted is outdated. * being deleted is outdated.
* @throws \Exception in case delete failed.
*/ */
public function delete() public function delete()
{ {
if ($this->beforeDelete()) { $db = static::getDb();
// we do not check the return value of deleteAll() because it's possible $transaction = $this->isOperationAtomic(self::OP_DELETE) && $db->getTransaction() === null ? $db->beginTransaction() : null;
// the record is already deleted in the database and thus the method will return 0 try {
$condition = $this->getOldPrimaryKey(true); $result = false;
$lock = $this->optimisticLock(); if ($this->beforeDelete()) {
if ($lock !== null) { // we do not check the return value of deleteAll() because it's possible
$condition[$lock] = $this->$lock; // the record is already deleted in the database and thus the method will return 0
$condition = $this->getOldPrimaryKey(true);
$lock = $this->optimisticLock();
if ($lock !== null) {
$condition[$lock] = $this->$lock;
}
$result = $this->deleteAll($condition);
if ($lock !== null && !$result) {
throw new StaleObjectException('The object being deleted is outdated.');
}
$this->_oldAttributes = null;
$this->afterDelete();
} }
$rows = $this->deleteAll($condition); if ($transaction !== null) {
if ($lock !== null && !$rows) { if ($result === false) {
throw new StaleObjectException('The object being deleted is outdated.'); $transaction->rollback();
} else {
$transaction->commit();
}
} }
$this->_oldAttributes = null; } catch (\Exception $e) {
$this->afterDelete(); if ($transaction !== null) {
return $rows; $transaction->rollback();
} else { }
return false; throw $e;
} }
return $result;
} }
/** /**
...@@ -1336,4 +1426,19 @@ class ActiveRecord extends Model ...@@ -1336,4 +1426,19 @@ class ActiveRecord extends Model
} }
return true; return true;
} }
/**
* @param string $operation possible values are ActiveRecord::INSERT, ActiveRecord::UPDATE and ActiveRecord::DELETE.
* @return boolean whether given operation is atomic. Currently active scenario is taken into account.
*/
private function isOperationAtomic($operation)
{
$scenario = $this->getScenario();
$scenarios = $this->scenarios();
if (isset($scenarios[$scenario], $scenario[$scenario]['atomic']) && is_array($scenarios[$scenario]['atomic'])) {
return in_array($operation, $scenarios[$scenario]['atomic']);
} else {
return false;
}
}
} }
...@@ -283,22 +283,16 @@ class Command extends \yii\base\Component ...@@ -283,22 +283,16 @@ class Command extends \yii\base\Component
try { try {
$token = "SQL: $sql"; $token = "SQL: $sql";
if ($this->db->enableProfiling) { Yii::beginProfile($token, __METHOD__);
Yii::beginProfile($token, __METHOD__);
}
$this->prepare(); $this->prepare();
$this->pdoStatement->execute(); $this->pdoStatement->execute();
$n = $this->pdoStatement->rowCount(); $n = $this->pdoStatement->rowCount();
if ($this->db->enableProfiling) { Yii::endProfile($token, __METHOD__);
Yii::endProfile($token, __METHOD__);
}
return $n; return $n;
} catch (\Exception $e) { } catch (\Exception $e) {
if ($this->db->enableProfiling) { Yii::endProfile($token, __METHOD__);
Yii::endProfile($token, __METHOD__);
}
$message = $e->getMessage(); $message = $e->getMessage();
Yii::error("$message\nFailed to execute SQL: $rawSql", __METHOD__); Yii::error("$message\nFailed to execute SQL: $rawSql", __METHOD__);
...@@ -411,9 +405,7 @@ class Command extends \yii\base\Component ...@@ -411,9 +405,7 @@ class Command extends \yii\base\Component
try { try {
$token = "SQL: $sql"; $token = "SQL: $sql";
if ($db->enableProfiling) { Yii::beginProfile($token, __METHOD__);
Yii::beginProfile($token, __METHOD__);
}
$this->prepare(); $this->prepare();
$this->pdoStatement->execute(); $this->pdoStatement->execute();
...@@ -428,9 +420,7 @@ class Command extends \yii\base\Component ...@@ -428,9 +420,7 @@ class Command extends \yii\base\Component
$this->pdoStatement->closeCursor(); $this->pdoStatement->closeCursor();
} }
if ($db->enableProfiling) { Yii::endProfile($token, __METHOD__);
Yii::endProfile($token, __METHOD__);
}
if (isset($cache, $cacheKey) && $cache instanceof Cache) { if (isset($cache, $cacheKey) && $cache instanceof Cache) {
$cache->set($cacheKey, $result, $db->queryCacheDuration, $db->queryCacheDependency); $cache->set($cacheKey, $result, $db->queryCacheDuration, $db->queryCacheDependency);
...@@ -439,9 +429,7 @@ class Command extends \yii\base\Component ...@@ -439,9 +429,7 @@ class Command extends \yii\base\Component
return $result; return $result;
} catch (\Exception $e) { } catch (\Exception $e) {
if ($db->enableProfiling) { Yii::endProfile($token, __METHOD__);
Yii::endProfile($token, __METHOD__);
}
$message = $e->getMessage(); $message = $e->getMessage();
Yii::error("$message\nCommand::$method() failed: $rawSql", __METHOD__); Yii::error("$message\nCommand::$method() failed: $rawSql", __METHOD__);
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null; $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
......
...@@ -7,6 +7,8 @@ ...@@ -7,6 +7,8 @@
namespace yii\db; namespace yii\db;
use PDO;
use Yii;
use yii\base\Component; use yii\base\Component;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\base\NotSupportedException; use yii\base\NotSupportedException;
...@@ -128,7 +130,7 @@ class Connection extends Component ...@@ -128,7 +130,7 @@ class Connection extends Component
*/ */
public $attributes; public $attributes;
/** /**
* @var \PDO the PHP PDO instance associated with this DB connection. * @var PDO the PHP PDO instance associated with this DB connection.
* This property is mainly managed by [[open()]] and [[close()]] methods. * This property is mainly managed by [[open()]] and [[close()]] methods.
* When a DB connection is active, this property will represent a PDO instance; * When a DB connection is active, this property will represent a PDO instance;
* otherwise, it will be null. * otherwise, it will be null.
...@@ -212,13 +214,6 @@ class Connection extends Component ...@@ -212,13 +214,6 @@ class Connection extends Component
* The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed. * The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
*/ */
public $emulatePrepare; public $emulatePrepare;
/**
* @var boolean whether to enable profiling for the SQL statements being executed.
* Defaults to false. This should be mainly enabled and used during development
* to find out the bottleneck of SQL executions.
* @see getStats
*/
public $enableProfiling = false;
/** /**
* @var string the common prefix or suffix for table names. If a table name is given * @var string the common prefix or suffix for table names. If a table name is given
* as `{{%TableName}}`, then the percentage character `%` will be replaced with this * as `{{%TableName}}`, then the percentage character `%` will be replaced with this
...@@ -229,7 +224,7 @@ class Connection extends Component ...@@ -229,7 +224,7 @@ class Connection extends Component
/** /**
* @var array mapping between PDO driver names and [[Schema]] classes. * @var array mapping between PDO driver names and [[Schema]] classes.
* The keys of the array are PDO driver names while the values the corresponding * The keys of the array are PDO driver names while the values the corresponding
* schema class name or configuration. Please refer to [[\Yii::createObject()]] for * schema class name or configuration. Please refer to [[Yii::createObject()]] for
* details on how to specify a configuration. * details on how to specify a configuration.
* *
* This property is mainly used by [[getSchema()]] when fetching the database schema information. * This property is mainly used by [[getSchema()]] when fetching the database schema information.
...@@ -312,13 +307,17 @@ class Connection extends Component ...@@ -312,13 +307,17 @@ class Connection extends Component
if (empty($this->dsn)) { if (empty($this->dsn)) {
throw new InvalidConfigException('Connection::dsn cannot be empty.'); throw new InvalidConfigException('Connection::dsn cannot be empty.');
} }
$token = 'Opening DB connection: ' . $this->dsn;
try { try {
\Yii::trace('Opening DB connection: ' . $this->dsn, __METHOD__); Yii::trace($token, __METHOD__);
Yii::beginProfile($token, __METHOD__);
$this->pdo = $this->createPdoInstance(); $this->pdo = $this->createPdoInstance();
$this->initConnection(); $this->initConnection();
Yii::endProfile($token, __METHOD__);
} }
catch (\PDOException $e) { catch (\PDOException $e) {
\Yii::error("Failed to open DB connection ({$this->dsn}): " . $e->getMessage(), __METHOD__); Yii::endProfile($token, __METHOD__);
Yii::error("Failed to open DB connection ({$this->dsn}): " . $e->getMessage(), __METHOD__);
$message = YII_DEBUG ? 'Failed to open DB connection: ' . $e->getMessage() : 'Failed to open DB connection.'; $message = YII_DEBUG ? 'Failed to open DB connection: ' . $e->getMessage() : 'Failed to open DB connection.';
throw new Exception($message, $e->errorInfo, (int)$e->getCode()); throw new Exception($message, $e->errorInfo, (int)$e->getCode());
} }
...@@ -332,7 +331,7 @@ class Connection extends Component ...@@ -332,7 +331,7 @@ class Connection extends Component
public function close() public function close()
{ {
if ($this->pdo !== null) { if ($this->pdo !== null) {
\Yii::trace('Closing DB connection: ' . $this->dsn, __METHOD__); Yii::trace('Closing DB connection: ' . $this->dsn, __METHOD__);
$this->pdo = null; $this->pdo = null;
$this->_schema = null; $this->_schema = null;
$this->_transaction = null; $this->_transaction = null;
...@@ -344,11 +343,11 @@ class Connection extends Component ...@@ -344,11 +343,11 @@ class Connection extends Component
* This method is called by [[open]] to establish a DB connection. * This method is called by [[open]] to establish a DB connection.
* The default implementation will create a PHP PDO instance. * The default implementation will create a PHP PDO instance.
* You may override this method if the default PDO needs to be adapted for certain DBMS. * You may override this method if the default PDO needs to be adapted for certain DBMS.
* @return \PDO the pdo instance * @return PDO the pdo instance
*/ */
protected function createPdoInstance() protected function createPdoInstance()
{ {
$pdoClass = '\PDO'; $pdoClass = 'PDO';
if (($pos = strpos($this->dsn, ':')) !== false) { if (($pos = strpos($this->dsn, ':')) !== false) {
$driver = strtolower(substr($this->dsn, 0, $pos)); $driver = strtolower(substr($this->dsn, 0, $pos));
if ($driver === 'mssql' || $driver === 'dblib' || $driver === 'sqlsrv') { if ($driver === 'mssql' || $driver === 'dblib' || $driver === 'sqlsrv') {
...@@ -367,9 +366,9 @@ class Connection extends Component ...@@ -367,9 +366,9 @@ class Connection extends Component
*/ */
protected function initConnection() protected function initConnection()
{ {
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($this->emulatePrepare !== null && constant('\PDO::ATTR_EMULATE_PREPARES')) { if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
$this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare); $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
} }
if ($this->charset !== null && in_array($this->getDriverName(), array('pgsql', 'mysql', 'mysqli'))) { if ($this->charset !== null && in_array($this->getDriverName(), array('pgsql', 'mysql', 'mysqli'))) {
$this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset)); $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
...@@ -428,7 +427,7 @@ class Connection extends Component ...@@ -428,7 +427,7 @@ class Connection extends Component
} else { } else {
$driver = $this->getDriverName(); $driver = $this->getDriverName();
if (isset($this->schemaMap[$driver])) { if (isset($this->schemaMap[$driver])) {
$this->_schema = \Yii::createObject($this->schemaMap[$driver]); $this->_schema = Yii::createObject($this->schemaMap[$driver]);
$this->_schema->db = $this; $this->_schema->db = $this;
return $this->_schema; return $this->_schema;
} else { } else {
...@@ -536,28 +535,7 @@ class Connection extends Component ...@@ -536,28 +535,7 @@ class Connection extends Component
if (($pos = strpos($this->dsn, ':')) !== false) { if (($pos = strpos($this->dsn, ':')) !== false) {
return strtolower(substr($this->dsn, 0, $pos)); return strtolower(substr($this->dsn, 0, $pos));
} else { } else {
return strtolower($this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME)); return strtolower($this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
}
}
/**
* Returns the statistical results of SQL queries.
* The results returned include the number of SQL statements executed and
* the total time spent.
* In order to use this method, [[enableProfiling]] has to be set true.
* @return array the first element indicates the number of SQL statements executed,
* and the second element the total time spent in SQL execution.
* @see \yii\logging\Logger::getProfiling()
*/
public function getQuerySummary()
{
$logger = \Yii::getLogger();
$timings = $logger->getProfiling(array('yii\db\Command::query', 'yii\db\Command::execute'));
$count = count($timings);
$time = 0;
foreach ($timings as $timing) {
$time += $timing[1];
} }
return array($count, $time);
} }
} }
...@@ -39,6 +39,6 @@ class Exception extends \yii\base\Exception ...@@ -39,6 +39,6 @@ class Exception extends \yii\base\Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Database Exception'); return \Yii::t('yii', 'Database Exception');
} }
} }
...@@ -10,14 +10,14 @@ namespace yii\db; ...@@ -10,14 +10,14 @@ namespace yii\db;
/** /**
* Migration is the base class for representing a database migration. * Migration is the base class for representing a database migration.
* *
* Migration is designed to be used together with the "yiic migrate" command. * Migration is designed to be used together with the "yii migrate" command.
* *
* Each child class of Migration represents an individual database migration which * Each child class of Migration represents an individual database migration which
* is identified by the child class name. * is identified by the child class name.
* *
* Within each migration, the [[up()]] method should be overwritten to contain the logic * Within each migration, the [[up()]] method should be overwritten to contain the logic
* for "upgrading" the database; while the [[down()]] method for the "downgrading" * for "upgrading" the database; while the [[down()]] method for the "downgrading"
* logic. The "yiic migrate" command manages all available migrations in an application. * logic. The "yii migrate" command manages all available migrations in an application.
* *
* If the database supports transactions, you may also overwrite [[safeUp()]] and * If the database supports transactions, you may also overwrite [[safeUp()]] and
* [[safeDown()]] so that if anything wrong happens during the upgrading or downgrading, * [[safeDown()]] so that if anything wrong happens during the upgrading or downgrading,
......
...@@ -18,6 +18,6 @@ class StaleObjectException extends Exception ...@@ -18,6 +18,6 @@ class StaleObjectException extends Exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii|Stale Object Exception'); return \Yii::t('yii', 'Stale Object Exception');
} }
} }
...@@ -17,18 +17,18 @@ use yii\helpers\Html; ...@@ -17,18 +17,18 @@ use yii\helpers\Html;
*/ */
class Toolbar extends Widget class Toolbar extends Widget
{ {
public $debugAction = 'debug'; public $debugAction = 'debug/default/toolbar';
public $enabled = YII_DEBUG;
public function run() public function run()
{ {
if ($this->enabled) { if (Yii::$app->hasModule('debug')) {
$id = 'yii-debug-toolbar'; $id = 'yii-debug-toolbar';
$url = Yii::$app->getUrlManager()->createUrl($this->debugAction, array( $url = Yii::$app->getUrlManager()->createUrl($this->debugAction, array(
'tag' => Yii::getLogger()->tag, 'tag' => Yii::getLogger()->tag,
)); ));
$this->view->registerJs("yii.debug.load('$id', '$url');"); $view = $this->getView();
$this->view->registerAssetBundle('yii/debug'); $view->registerJs("yii.debug.load('$id', '$url');");
$view->registerAssetBundle('yii/debug');
echo Html::tag('div', '', array( echo Html::tag('div', '', array(
'id' => $id, 'id' => $id,
'style' => 'display: none', 'style' => 'display: none',
......
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
namespace yii\debug\controllers; namespace yii\debug\controllers;
use Yii;
use yii\web\Controller; use yii\web\Controller;
/** /**
...@@ -19,4 +20,15 @@ class DefaultController extends Controller ...@@ -19,4 +20,15 @@ class DefaultController extends Controller
{ {
echo $tag; echo $tag;
} }
public function actionToolbar($tag)
{
$file = Yii::$app->getRuntimePath() . "/debug/$tag.log";
if (preg_match('/^[\w\-]+$/', $tag) && is_file($file)) {
$data = json_decode(file_get_contents($file), true);
echo $this->renderPartial('toolbar', $data);
} else {
echo "Unable to find debug data tagged with '$tag'.";
}
}
} }
\ No newline at end of file
<?php use yii\helpers\Html;
echo Html::style("
#yii-debug-toolbar {
position: fixed;
left: 0;
right: 0;
bottom: 0;
background-color: #eee;
border-top: 1px solid #ccc;
margin: 0;
padding: 5px 10px;
z-index: 1000000;
font: 11px Verdana, Arial, sans-serif;
text-align: left;
}
.yii-debug-toolbar-block {
float: left;
margin: 0 10px;
");
?>
<div class="yii-debug-toolbar-block">
</div>
<div class="yii-debug-toolbar-block">
Peak memory: <?php echo sprintf('%.2fMB', $memory / 1048576); ?>
</div>
<div class="yii-debug-toolbar-block">
Time spent: <?php echo sprintf('%.3fs', $time); ?>
</div>
<div class="yii-debug-toolbar-block">
</div>
<div class="yii-debug-toolbar-block">
</div>
...@@ -263,8 +263,8 @@ class ArrayHelper ...@@ -263,8 +263,8 @@ class ArrayHelper
* elements, a property name of the objects, or an anonymous function returning the values for comparison * elements, a property name of the objects, or an anonymous function returning the values for comparison
* purpose. The anonymous function signature should be: `function($item)`. * purpose. The anonymous function signature should be: `function($item)`.
* To sort by multiple keys, provide an array of keys here. * To sort by multiple keys, provide an array of keys here.
* @param boolean|array $ascending whether to sort in ascending or descending order. When * @param boolean|array $descending whether to sort in descending or ascending order. When
* sorting by multiple keys with different ascending orders, use an array of ascending flags. * sorting by multiple keys with different descending orders, use an array of descending flags.
* @param integer|array $sortFlag the PHP sort flag. Valid values include * @param integer|array $sortFlag the PHP sort flag. Valid values include
* `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING` and `SORT_LOCALE_STRING`. * `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING` and `SORT_LOCALE_STRING`.
* Please refer to [PHP manual](http://php.net/manual/en/function.sort.php) * Please refer to [PHP manual](http://php.net/manual/en/function.sort.php)
...@@ -272,20 +272,20 @@ class ArrayHelper ...@@ -272,20 +272,20 @@ class ArrayHelper
* @param boolean|array $caseSensitive whether to sort string in case-sensitive manner. This parameter * @param boolean|array $caseSensitive whether to sort string in case-sensitive manner. This parameter
* is used only when `$sortFlag` is `SORT_STRING`. * is used only when `$sortFlag` is `SORT_STRING`.
* When sorting by multiple keys with different case sensitivities, use an array of boolean values. * 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 * @throws InvalidParamException if the $descending or $sortFlag parameters do not have
* correct number of elements as that of $key. * correct number of elements as that of $key.
*/ */
public static function multisort(&$array, $key, $ascending = true, $sortFlag = SORT_REGULAR, $caseSensitive = true) public static function multisort(&$array, $key, $descending = false, $sortFlag = SORT_REGULAR, $caseSensitive = true)
{ {
$keys = is_array($key) ? $key : array($key); $keys = is_array($key) ? $key : array($key);
if (empty($keys) || empty($array)) { if (empty($keys) || empty($array)) {
return; return;
} }
$n = count($keys); $n = count($keys);
if (is_scalar($ascending)) { if (is_scalar($descending)) {
$ascending = array_fill(0, $n, $ascending); $descending = array_fill(0, $n, $descending);
} elseif (count($ascending) !== $n) { } elseif (count($descending) !== $n) {
throw new InvalidParamException('The length of $ascending parameter must be the same as that of $keys.'); throw new InvalidParamException('The length of $descending parameter must be the same as that of $keys.');
} }
if (is_scalar($sortFlag)) { if (is_scalar($sortFlag)) {
$sortFlag = array_fill(0, $n, $sortFlag); $sortFlag = array_fill(0, $n, $sortFlag);
...@@ -315,7 +315,7 @@ class ArrayHelper ...@@ -315,7 +315,7 @@ class ArrayHelper
} else { } else {
$args[] = static::getColumn($array, $key); $args[] = static::getColumn($array, $key);
} }
$args[] = $ascending[$i] ? SORT_ASC : SORT_DESC; $args[] = $descending[$i] ? SORT_DESC : SORT_ASC;
$args[] = $flag; $args[] = $flag;
} }
$args[] = &$array; $args[] = &$array;
......
...@@ -75,26 +75,19 @@ class I18N extends Component ...@@ -75,26 +75,19 @@ class I18N extends Component
* Translates a message to the specified language. * Translates a message to the specified language.
* If the first parameter in `$params` is a number and it is indexed by 0, appropriate plural rules * If the first parameter in `$params` is a number and it is indexed by 0, appropriate plural rules
* will be applied to the translated message. * will be applied to the translated message.
* @param string $category the message category.
* @param string $message the message to be translated. * @param string $message the message to be translated.
* @param array $params the parameters that will be used to replace the corresponding placeholders in the message. * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
* @param string $language the language code (e.g. `en_US`, `en`). If this is null, the current * @param string $language the language code (e.g. `en_US`, `en`). If this is null, the current
* [[\yii\base\Application::language|application language]] will be used. * [[\yii\base\Application::language|application language]] will be used.
* @return string the translated message. * @return string the translated message.
*/ */
public function translate($message, $params = array(), $language = null) public function translate($category, $message, $params = array(), $language = null)
{ {
if ($language === null) { if ($language === null) {
$language = Yii::$app->language; $language = Yii::$app->language;
} }
// allow chars for category: word chars, ".", "-", "/", "\"
if (strpos($message, '|') !== false && preg_match('/^([\w\-\\/\.\\\\]+)\|(.*)/', $message, $matches)) {
$category = $matches[1];
$message = $matches[2];
} else {
$category = 'app';
}
$message = $this->getMessageSource($category)->translate($category, $message, $language); $message = $this->getMessageSource($category)->translate($category, $message, $language);
if (!is_array($params)) { if (!is_array($params)) {
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
/** /**
* Plural rules. * Plural rules.
* *
* This file is automatically generated by the "yiic locale/plural" command under the "build" folder. * This file is automatically generated by the "yii locale/plural" command under the "build" folder.
* Do not modify it directly. * Do not modify it directly.
* *
* The original plural rule data used for generating this file has the following copyright terms: * The original plural rule data used for generating this file has the following copyright terms:
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
return array ( return array (
'ar' => 'ar' =>
array ( array (
0 => '$n==0', 0 => '$n==0',
1 => '$n==1', 1 => '$n==1',
...@@ -24,569 +24,569 @@ return array ( ...@@ -24,569 +24,569 @@ return array (
3 => 'in_array(fmod($n,100),range(3,10))', 3 => 'in_array(fmod($n,100),range(3,10))',
4 => 'in_array(fmod($n,100),range(11,99))', 4 => 'in_array(fmod($n,100),range(11,99))',
), ),
'asa' => 'asa' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'af' => 'af' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'bem' => 'bem' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'bez' => 'bez' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'bg' => 'bg' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'bn' => 'bn' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'brx' => 'brx' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ca' => 'ca' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'cgg' => 'cgg' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'chr' => 'chr' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'da' => 'da' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'de' => 'de' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'dv' => 'dv' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ee' => 'ee' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'el' => 'el' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'en' => 'en' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'eo' => 'eo' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'es' => 'es' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'et' => 'et' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'eu' => 'eu' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'fi' => 'fi' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'fo' => 'fo' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'fur' => 'fur' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'fy' => 'fy' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'gl' => 'gl' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'gsw' => 'gsw' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'gu' => 'gu' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ha' => 'ha' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'haw' => 'haw' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'he' => 'he' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'is' => 'is' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'it' => 'it' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'jmc' => 'jmc' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'kaj' => 'kaj' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'kcg' => 'kcg' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'kk' => 'kk' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'kl' => 'kl' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ksb' => 'ksb' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ku' => 'ku' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'lb' => 'lb' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'lg' => 'lg' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'mas' => 'mas' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ml' => 'ml' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'mn' => 'mn' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'mr' => 'mr' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'nah' => 'nah' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'nb' => 'nb' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'nd' => 'nd' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ne' => 'ne' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'nl' => 'nl' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'nn' => 'nn' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'no' => 'no' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'nr' => 'nr' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ny' => 'ny' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'nyn' => 'nyn' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'om' => 'om' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'or' => 'or' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'pa' => 'pa' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'pap' => 'pap' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ps' => 'ps' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'pt' => 'pt' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'rof' => 'rof' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'rm' => 'rm' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'rwk' => 'rwk' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'saq' => 'saq' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'seh' => 'seh' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'sn' => 'sn' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'so' => 'so' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'sq' => 'sq' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ss' => 'ss' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ssy' => 'ssy' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'st' => 'st' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'sv' => 'sv' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'sw' => 'sw' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'syr' => 'syr' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ta' => 'ta' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'te' => 'te' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'teo' => 'teo' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'tig' => 'tig' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'tk' => 'tk' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'tn' => 'tn' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ts' => 'ts' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ur' => 'ur' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'wae' => 'wae' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
've' => 've' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'vun' => 'vun' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'xh' => 'xh' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'xog' => 'xog' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'zu' => 'zu' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
), ),
'ak' => 'ak' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'am' => 'am' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'bh' => 'bh' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'fil' => 'fil' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'tl' => 'tl' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'guw' => 'guw' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'hi' => 'hi' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'ln' => 'ln' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'mg' => 'mg' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'nso' => 'nso' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'ti' => 'ti' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'wa' => 'wa' =>
array ( array (
0 => '($n==0||$n==1)', 0 => '($n==0||$n==1)',
), ),
'ff' => 'ff' =>
array ( array (
0 => '($n>=0&&$n<=2)&&$n!=2', 0 => '($n>=0&&$n<=2)&&$n!=2',
), ),
'fr' => 'fr' =>
array ( array (
0 => '($n>=0&&$n<=2)&&$n!=2', 0 => '($n>=0&&$n<=2)&&$n!=2',
), ),
'kab' => 'kab' =>
array ( array (
0 => '($n>=0&&$n<=2)&&$n!=2', 0 => '($n>=0&&$n<=2)&&$n!=2',
), ),
'lv' => 'lv' =>
array ( array (
0 => '$n==0', 0 => '$n==0',
1 => 'fmod($n,10)==1&&fmod($n,100)!=11', 1 => 'fmod($n,10)==1&&fmod($n,100)!=11',
), ),
'iu' => 'iu' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==2', 1 => '$n==2',
), ),
'kw' => 'kw' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==2', 1 => '$n==2',
), ),
'naq' => 'naq' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==2', 1 => '$n==2',
), ),
'se' => 'se' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==2', 1 => '$n==2',
), ),
'sma' => 'sma' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==2', 1 => '$n==2',
), ),
'smi' => 'smi' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==2', 1 => '$n==2',
), ),
'smj' => 'smj' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==2', 1 => '$n==2',
), ),
'smn' => 'smn' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==2', 1 => '$n==2',
), ),
'sms' => 'sms' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==2', 1 => '$n==2',
), ),
'ga' => 'ga' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==2', 1 => '$n==2',
2 => 'in_array($n,array(3,4,5,6))', 2 => 'in_array($n,array(3,4,5,6))',
3 => 'in_array($n,array(7,8,9,10))', 3 => 'in_array($n,array(7,8,9,10))',
), ),
'ro' => 'ro' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==0||$n!=1&&in_array(fmod($n,100),range(1,19))', 1 => '$n==0||$n!=1&&in_array(fmod($n,100),range(1,19))',
), ),
'mo' => 'mo' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==0||$n!=1&&in_array(fmod($n,100),range(1,19))', 1 => '$n==0||$n!=1&&in_array(fmod($n,100),range(1,19))',
), ),
'lt' => 'lt' =>
array ( array (
0 => 'fmod($n,10)==1&&!in_array(fmod($n,100),range(11,19))', 0 => 'fmod($n,10)==1&&!in_array(fmod($n,100),range(11,19))',
1 => 'in_array(fmod($n,10),range(2,9))&&!in_array(fmod($n,100),range(11,19))', 1 => 'in_array(fmod($n,10),range(2,9))&&!in_array(fmod($n,100),range(11,19))',
), ),
'be' => 'be' =>
array ( array (
0 => 'fmod($n,10)==1&&fmod($n,100)!=11', 0 => 'fmod($n,10)==1&&fmod($n,100)!=11',
1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))', 1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))',
2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))', 2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))',
), ),
'bs' => 'bs' =>
array ( array (
0 => 'fmod($n,10)==1&&fmod($n,100)!=11', 0 => 'fmod($n,10)==1&&fmod($n,100)!=11',
1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))', 1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))',
2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))', 2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))',
), ),
'hr' => 'hr' =>
array ( array (
0 => 'fmod($n,10)==1&&fmod($n,100)!=11', 0 => 'fmod($n,10)==1&&fmod($n,100)!=11',
1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))', 1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))',
2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))', 2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))',
), ),
'ru' => 'ru' =>
array ( array (
0 => 'fmod($n,10)==1&&fmod($n,100)!=11', 0 => 'fmod($n,10)==1&&fmod($n,100)!=11',
1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))', 1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))',
2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))', 2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))',
), ),
'sh' => 'sh' =>
array ( array (
0 => 'fmod($n,10)==1&&fmod($n,100)!=11', 0 => 'fmod($n,10)==1&&fmod($n,100)!=11',
1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))', 1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))',
2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))', 2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))',
), ),
'sr' => 'sr' =>
array ( array (
0 => 'fmod($n,10)==1&&fmod($n,100)!=11', 0 => 'fmod($n,10)==1&&fmod($n,100)!=11',
1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))', 1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))',
2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))', 2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))',
), ),
'uk' => 'uk' =>
array ( array (
0 => 'fmod($n,10)==1&&fmod($n,100)!=11', 0 => 'fmod($n,10)==1&&fmod($n,100)!=11',
1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))', 1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))',
2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))', 2 => 'fmod($n,10)==0||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(11,12,13,14))',
), ),
'cs' => 'cs' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => 'in_array($n,array(2,3,4))', 1 => 'in_array($n,array(2,3,4))',
), ),
'sk' => 'sk' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => 'in_array($n,array(2,3,4))', 1 => 'in_array($n,array(2,3,4))',
), ),
'pl' => 'pl' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))', 1 => 'in_array(fmod($n,10),array(2,3,4))&&!in_array(fmod($n,100),array(12,13,14))',
2 => '$n!=1&&in_array(fmod($n,10),array(0,1))||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(12,13,14))', 2 => '$n!=1&&in_array(fmod($n,10),array(0,1))||in_array(fmod($n,10),array(5,6,7,8,9))||in_array(fmod($n,100),array(12,13,14))',
), ),
'sl' => 'sl' =>
array ( array (
0 => 'fmod($n,100)==1', 0 => 'fmod($n,100)==1',
1 => 'fmod($n,100)==2', 1 => 'fmod($n,100)==2',
2 => 'in_array(fmod($n,100),array(3,4))', 2 => 'in_array(fmod($n,100),array(3,4))',
), ),
'mt' => 'mt' =>
array ( array (
0 => '$n==1', 0 => '$n==1',
1 => '$n==0||in_array(fmod($n,100),range(2,10))', 1 => '$n==0||in_array(fmod($n,100),range(2,10))',
2 => 'in_array(fmod($n,100),range(11,19))', 2 => 'in_array(fmod($n,100),range(11,19))',
), ),
'mk' => 'mk' =>
array ( array (
0 => 'fmod($n,10)==1&&$n!=11', 0 => 'fmod($n,10)==1&&$n!=11',
), ),
'cy' => 'cy' =>
array ( array (
0 => '$n==0', 0 => '$n==0',
1 => '$n==1', 1 => '$n==1',
...@@ -594,33 +594,33 @@ return array ( ...@@ -594,33 +594,33 @@ return array (
3 => '$n==3', 3 => '$n==3',
4 => '$n==6', 4 => '$n==6',
), ),
'lag' => 'lag' =>
array ( array (
0 => '$n==0', 0 => '$n==0',
1 => '($n>=0&&$n<=2)&&$n!=0&&$n!=2', 1 => '($n>=0&&$n<=2)&&$n!=0&&$n!=2',
), ),
'shi' => 'shi' =>
array ( array (
0 => '($n>=0&&$n<=1)', 0 => '($n>=0&&$n<=1)',
1 => 'in_array($n,range(2,10))', 1 => 'in_array($n,range(2,10))',
), ),
'br' => 'br' =>
array ( array (
0 => 'fmod($n,10)==1&&!in_array(fmod($n,100),array(11,71,91))', 0 => 'fmod($n,10)==1&&!in_array(fmod($n,100),array(11,71,91))',
1 => 'fmod($n,10)==2&&!in_array(fmod($n,100),array(12,72,92))', 1 => 'fmod($n,10)==2&&!in_array(fmod($n,100),array(12,72,92))',
2 => 'in_array(fmod($n,10),array(3,4,9))&&!in_array(fmod($n,100),array_merge(range(10,19),range(70,79),range(90,99)))', 2 => 'in_array(fmod($n,10),array(3,4,9))&&!in_array(fmod($n,100),array_merge(range(10,19),range(70,79),range(90,99)))',
3 => 'fmod($n,1000000)==0&&$n!=0', 3 => 'fmod($n,1000000)==0&&$n!=0',
), ),
'ksh' => 'ksh' =>
array ( array (
0 => '$n==0', 0 => '$n==0',
1 => '$n==1', 1 => '$n==1',
), ),
'tzm' => 'tzm' =>
array ( array (
0 => '($n==0||$n==1)||in_array($n,range(11,99))', 0 => '($n==0||$n==1)||in_array($n,range(11,99))',
), ),
'gv' => 'gv' =>
array ( array (
0 => 'in_array(fmod($n,10),array(1,2))||fmod($n,20)==0', 0 => 'in_array(fmod($n,10),array(1,2))||fmod($n,20)==0',
), ),
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\logging;
use Yii;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class DebugTarget extends Target
{
public $maxLogFiles = 20;
/**
* Exports log messages to a specific destination.
* Child classes must implement this method.
* @param array $messages the messages to be exported. See [[Logger::messages]] for the structure
* of each message.
*/
public function export($messages)
{
$path = Yii::$app->getRuntimePath() . '/debug';
if (!is_dir($path)) {
mkdir($path);
}
$file = $path . '/' . Yii::getLogger()->getTag() . '.log';
$data = array(
'messages' => $messages,
'_SERVER' => $_SERVER,
'_GET' => $_GET,
'_POST' => $_POST,
'_COOKIE' => $_COOKIE,
'_FILES' => empty($_FILES) ? array() : $_FILES,
'_SESSION' => empty($_SESSION) ? array() : $_SESSION,
'memory' => memory_get_peak_usage(),
'time' => microtime(true) - YII_BEGIN_TIME,
);
file_put_contents($file, json_encode($data));
}
/**
* Processes the given log messages.
* This method will filter the given messages with [[levels]] and [[categories]].
* And if requested, it will also export the filtering result to specific medium (e.g. email).
* @param array $messages log messages to be processed. See [[Logger::messages]] for the structure
* of each message.
* @param boolean $final whether this method is called at the end of the current application
*/
public function collect($messages, $final)
{
if (Yii::$app->getModule('debug', false) !== null) {
return;
}
$this->messages = array_merge($this->messages, $this->filterMessages($messages));
if ($final) {
$this->export($this->messages);
$this->gc();
}
}
protected function gc()
{
if (mt_rand(0, 10000) > 100) {
return;
}
$iterator = new \DirectoryIterator(Yii::$app->getRuntimePath() . '/debug');
$files = array();
foreach ($iterator as $file) {
if (preg_match('/^[\d\-]+\.log$/', $file->getFileName()) && $file->isFile()) {
$files[] = $file->getPathname();
}
}
sort($files);
if (count($files) > $this->maxLogFiles) {
$n = count($files) - $this->maxLogFiles;
foreach ($files as $i => $file) {
if ($i < $n) {
unlink($file);
} else {
break;
}
}
}
}
}
...@@ -48,7 +48,7 @@ class EmailTarget extends Target ...@@ -48,7 +48,7 @@ class EmailTarget extends Target
$body .= $this->formatMessage($message); $body .= $this->formatMessage($message);
} }
$body = wordwrap($body, 70); $body = wordwrap($body, 70);
$subject = $this->subject === null ? \Yii::t('yii|Application Log') : $this->subject; $subject = $this->subject === null ? \Yii::t('yii', 'Application Log') : $this->subject;
foreach ($this->emails as $email) { foreach ($this->emails as $email) {
$this->sendEmail($subject, $body, $email, $this->sentFrom, $this->headers); $this->sendEmail($subject, $body, $email, $this->sentFrom, $this->headers);
} }
......
...@@ -82,11 +82,13 @@ class Logger extends Component ...@@ -82,11 +82,13 @@ class Logger extends Component
* @var Router the log target router registered with this logger. * @var Router the log target router registered with this logger.
*/ */
public $router; public $router;
/** /**
* @var string a tag that uniquely identifies the current request. This can be used * @var string
* to differentiate the log messages for different requests.
*/ */
public $tag; private $_tag;
/** /**
* Initializes the logger by registering [[flush()]] as a shutdown function. * Initializes the logger by registering [[flush()]] as a shutdown function.
...@@ -94,7 +96,6 @@ class Logger extends Component ...@@ -94,7 +96,6 @@ class Logger extends Component
public function init() public function init()
{ {
parent::init(); parent::init();
$this->tag = date('Ymd-His', microtime(true));
register_shutdown_function(array($this, 'flush'), true); register_shutdown_function(array($this, 'flush'), true);
} }
...@@ -142,6 +143,25 @@ class Logger extends Component ...@@ -142,6 +143,25 @@ class Logger extends Component
$this->messages = array(); $this->messages = array();
} }
/**
* @return string a tag that uniquely identifies the current request.
*/
public function getTag()
{
if ($this->_tag === null) {
$this->_tag = date('Ymd-His', microtime(true));
}
return $this->_tag;
}
/**
* @param string $tag a tag that uniquely identifies the current request.
*/
public function setTag($tag)
{
$this->_tag = $tag;
}
/** /**
* Returns the total elapsed time since the start of the current request. * Returns the total elapsed time since the start of the current request.
* This method calculates the difference between now and the timestamp * This method calculates the difference between now and the timestamp
...@@ -205,6 +225,24 @@ class Logger extends Component ...@@ -205,6 +225,24 @@ class Logger extends Component
return array_values($timings); return array_values($timings);
} }
/**
* Returns the statistical results of DB queries.
* The results returned include the number of SQL statements executed and
* the total time spent.
* @return array the first element indicates the number of SQL statements executed,
* and the second element the total time spent in SQL execution.
*/
public function getDbProfiling()
{
$timings = $this->getProfiling(array('yii\db\Command::query', 'yii\db\Command::execute'));
$count = count($timings);
$time = 0;
foreach ($timings as $timing) {
$time += $timing[1];
}
return array($count, $time);
}
private function calculateTimings() private function calculateTimings()
{ {
$timings = array(); $timings = array();
......
...@@ -59,7 +59,7 @@ class CProfileLogRoute extends CWebLogRoute ...@@ -59,7 +59,7 @@ class CProfileLogRoute extends CWebLogRoute
if ($value === 'summary' || $value === 'callstack') if ($value === 'summary' || $value === 'callstack')
$this->_report = $value; $this->_report = $value;
else else
throw new CException(Yii::t('yii|CProfileLogRoute.report "{report}" is invalid. Valid values include "summary" and "callstack".', throw new CException(Yii::t('yii', 'CProfileLogRoute.report "{report}" is invalid. Valid values include "summary" and "callstack".',
array('{report}' => $value))); array('{report}' => $value)));
} }
...@@ -106,7 +106,7 @@ class CProfileLogRoute extends CWebLogRoute ...@@ -106,7 +106,7 @@ class CProfileLogRoute extends CWebLogRoute
$results[$last[4]] = array($token, $delta, count($stack)); $results[$last[4]] = array($token, $delta, count($stack));
} else } else
{ {
throw new CException(Yii::t('yii|CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.', throw new CException(Yii::t('yii', 'CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.',
array('{token}' => $token))); array('{token}' => $token)));
} }
} }
...@@ -149,7 +149,7 @@ class CProfileLogRoute extends CWebLogRoute ...@@ -149,7 +149,7 @@ class CProfileLogRoute extends CWebLogRoute
else else
$results[$token] = array($token, 1, $delta, $delta, $delta); $results[$token] = array($token, 1, $delta, $delta, $delta);
} else } else
throw new CException(Yii::t('yii|CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.', throw new CException(Yii::t('yii', 'CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.',
array('{token}' => $token))); array('{token}' => $token)));
} }
} }
......
...@@ -7,6 +7,8 @@ ...@@ -7,6 +7,8 @@
namespace yii\logging; namespace yii\logging;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
/** /**
...@@ -25,7 +27,7 @@ use yii\base\InvalidConfigException; ...@@ -25,7 +27,7 @@ use yii\base\InvalidConfigException;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
abstract class Target extends \yii\base\Component abstract class Target extends Component
{ {
/** /**
* @var boolean whether to enable this log target. Defaults to true. * @var boolean whether to enable this log target. Defaults to true.
...@@ -67,7 +69,7 @@ abstract class Target extends \yii\base\Component ...@@ -67,7 +69,7 @@ abstract class Target extends \yii\base\Component
/** /**
* @var array the messages that are retrieved from the logger so far by this log target. * @var array the messages that are retrieved from the logger so far by this log target.
*/ */
private $_messages = array(); public $messages = array();
private $_levels = 0; private $_levels = 0;
...@@ -89,14 +91,14 @@ abstract class Target extends \yii\base\Component ...@@ -89,14 +91,14 @@ abstract class Target extends \yii\base\Component
*/ */
public function collect($messages, $final) public function collect($messages, $final)
{ {
$this->_messages = array_merge($this->_messages, $this->filterMessages($messages)); $this->messages = array_merge($this->messages, $this->filterMessages($messages));
$count = count($this->_messages); $count = count($this->messages);
if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) { if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
if (($context = $this->getContextMessage()) !== '') { if (($context = $this->getContextMessage()) !== '') {
$this->_messages[] = array($context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME); $this->messages[] = array($context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME);
} }
$this->export($this->_messages); $this->export($this->messages);
$this->_messages = array(); $this->messages = array();
} }
} }
...@@ -108,8 +110,9 @@ abstract class Target extends \yii\base\Component ...@@ -108,8 +110,9 @@ abstract class Target extends \yii\base\Component
protected function getContextMessage() protected function getContextMessage()
{ {
$context = array(); $context = array();
if ($this->logUser && ($user = \Yii::$app->getComponent('user', false)) !== null) { if ($this->logUser && ($user = Yii::$app->getComponent('user', false)) !== null) {
$context[] = 'User: ' . $user->getName() . ' (ID: ' . $user->getId() . ')'; /** @var $user \yii\web\User */
$context[] = 'User: ' . $user->getId();
} }
foreach ($this->logVars as $name) { foreach ($this->logVars as $name) {
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2011 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* CWebLogRoute shows the log content in Web page.
*
* The log content can appear either at the end of the current Web page
* or in FireBug console window (if {@link showInFireBug} is set true).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class CWebLogRoute extends CLogRoute
{
/**
* @var boolean whether the log should be displayed in FireBug instead of browser window. Defaults to false.
*/
public $showInFireBug = false;
/**
* @var boolean whether the log should be ignored in FireBug for ajax calls. Defaults to true.
* This option should be used carefully, because an ajax call returns all output as a result data.
* For example if the ajax call expects a json type result any output from the logger will cause ajax call to fail.
*/
public $ignoreAjaxInFireBug = true;
/**
* Displays the log messages.
* @param array $logs list of log messages
*/
public function processLogs($logs)
{
$this->render('log', $logs);
}
/**
* Renders the view.
* @param string $view the view name (file name without extension). The file is assumed to be located under framework/data/views.
* @param array $data data to be passed to the view
*/
protected function render($view, $data)
{
$app = \Yii::$app;
$isAjax = $app->getRequest()->getIsAjaxRequest();
if ($this->showInFireBug)
{
if ($isAjax && $this->ignoreAjaxInFireBug)
return;
$view .= '-firebug';
} elseif (!($app instanceof CWebApplication) || $isAjax)
return;
$viewFile = YII_PATH . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view . '.php';
include($app->findLocalizedFile($viewFile, 'en'));
}
}
...@@ -7,9 +7,9 @@ return array( ...@@ -7,9 +7,9 @@ return array(
array( array(
'name' => 'PHP version', 'name' => 'PHP version',
'mandatory' => true, 'mandatory' => true,
'condition' => version_compare(PHP_VERSION, '5.3.0', '>='), 'condition' => version_compare(PHP_VERSION, '5.3.3', '>='),
'by' => '<a href="http://www.yiiframework.com">Yii Framework</a>', 'by' => '<a href="http://www.yiiframework.com">Yii Framework</a>',
'memo' => 'PHP 5.3.0 or higher is required.', 'memo' => 'PHP 5.3.3 or higher is required.',
), ),
array( array(
'name' => 'Reflection extension', 'name' => 'Reflection extension',
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -3,80 +3,68 @@ ...@@ -3,80 +3,68 @@
/* @var $summary array */ /* @var $summary array */
/* @var $requirements array[] */ /* @var $requirements array[] */
?> ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <html lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta charset="utf-8"/>
<meta http-equiv="content-language" content="en"/> <title>Yii Application Requirement Checker</title>
<style type="text/css"> <?php $this->renderViewFile(dirname(__FILE__).DIRECTORY_SEPARATOR.'css.php'); ?>
<?php $this->renderViewFile(dirname(__FILE__).DIRECTORY_SEPARATOR.'css.php'); ?>
</style>
<title>Yii Application Requirement Checker</title>
</head> </head>
<body> <body>
<div id="page"> <div class="container">
<div class="header">
<div id="header"> <h1>Yii Application Requirement Checker</h1>
<h1>Yii Application Requirement Checker</h1> </div>
</div><!-- header--> <hr>
<div id="content">
<h2>Description</h2>
<p>
This script checks if your server configuration meets the requirements
for running Yii application.
It checks if the server is running the right version of PHP,
if appropriate PHP extensions have been loaded, and if php.ini file settings are correct.
</p>
<h2>Conclusion</h2> <div class="content">
<p> <h3>Description</h3>
<?php if ($summary['errors']>0): ?> <p>
Unfortunately your server configuration does not satisfy the requirements by this application. This script checks if your server configuration meets the requirements
<?php elseif ($summary['warnings']>0): ?> for running Yii application.
Your server configuration satisfies the minimum requirements by this application. Please pay attention to the warnings listed below if your application will use the corresponding features. It checks if the server is running the right version of PHP,
<?php else: ?> if appropriate PHP extensions have been loaded, and if php.ini file settings are correct.
Congratulations! Your server configuration satisfies all requirements. </p>
<?php endif; ?>
</p>
<h2>Details</h2> <h3>Conclusion</h3>
<?php if ($summary['errors']>0): ?>
<strong class="text-error">Unfortunately your server configuration does not satisfy the requirements by this application.</strong>
<?php elseif ($summary['warnings']>0): ?>
<strong class="text-warning">Your server configuration satisfies the minimum requirements by this application. Please pay attention to the warnings listed below if your application will use the corresponding features.</strong>
<?php else: ?>
<strong class="text-success">Congratulations! Your server configuration satisfies all requirements.</strong>
<?php endif; ?>
<table class="result"> <h3>Details</h3>
<tr><th>Name</th><th>Result</th><th>Required By</th><th>Memo</th></tr>
<?php foreach($requirements as $requirement): ?>
<tr>
<td>
<?php echo $requirement['name']; ?>
</td>
<td class="<?php echo $requirement['condition'] ? 'passed' : ($requirement['mandatory'] ? 'failed' : 'warning'); ?>">
<?php echo $requirement['condition'] ? 'Passed' : ($requirement['mandatory'] ? 'Failed' : 'Warning'); ?>
</td>
<td>
<?php echo $requirement['by']; ?>
</td>
<td>
<?php echo $requirement['memo']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<table> <table class="table table-bordered">
<tr> <tr><th>Name</th><th>Result</th><th>Required By</th><th>Memo</th></tr>
<td class="passed">&nbsp;</td><td>passed</td> <?php foreach($requirements as $requirement): ?>
<td class="failed">&nbsp;</td><td>failed</td> <tr class="<?php echo $requirement['condition'] ? 'success' : ($requirement['mandatory'] ? 'error' : 'warning'); ?>">
<td class="warning">&nbsp;</td><td>warning</td> <td>
</tr> <?php echo $requirement['name']; ?>
</table> </td>
<td >
<?php echo $requirement['condition'] ? 'Passed' : ($requirement['mandatory'] ? 'Failed' : 'Warning'); ?>
</td>
<td>
<?php echo $requirement['by']; ?>
</td>
<td>
<?php echo $requirement['memo']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
</div><!-- content --> </div>
<div id="footer"> <hr>
<?php echo $this->getServerInfo().' '.$this->getNowDate(); ?>
</div><!-- footer -->
</div><!-- page --> <div class="footer">
<p>Server: <?php echo $this->getServerInfo().' '.$this->getNowDate(); ?></p>
<p>Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a></p>
</div>
</div>
</body> </body>
</html> </html>
\ No newline at end of file
...@@ -43,7 +43,7 @@ class BooleanValidator extends Validator ...@@ -43,7 +43,7 @@ class BooleanValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|{attribute} must be either "{true}" or "{false}".'); $this->message = Yii::t('yii', '{attribute} must be either "{true}" or "{false}".');
} }
} }
...@@ -79,9 +79,11 @@ class BooleanValidator extends Validator ...@@ -79,9 +79,11 @@ class BooleanValidator extends Validator
* Returns the JavaScript needed for performing client-side validation. * Returns the JavaScript needed for performing client-side validation.
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
$options = array( $options = array(
'trueValue' => $this->trueValue, 'trueValue' => $this->trueValue,
...@@ -100,6 +102,7 @@ class BooleanValidator extends Validator ...@@ -100,6 +102,7 @@ class BooleanValidator extends Validator
$options['strict'] = 1; $options['strict'] = 1;
} }
$view->registerAssetBundle('yii/validation');
return 'yii.validation.boolean(value, messages, ' . json_encode($options) . ');'; return 'yii.validation.boolean(value, messages, ' . json_encode($options) . ');';
} }
} }
...@@ -39,7 +39,7 @@ class CaptchaValidator extends Validator ...@@ -39,7 +39,7 @@ class CaptchaValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|The verification code is incorrect.'); $this->message = Yii::t('yii', 'The verification code is incorrect.');
} }
} }
...@@ -91,9 +91,11 @@ class CaptchaValidator extends Validator ...@@ -91,9 +91,11 @@ class CaptchaValidator extends Validator
* Returns the JavaScript needed for performing client-side validation. * Returns the JavaScript needed for performing client-side validation.
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
$captcha = $this->getCaptchaAction(); $captcha = $this->getCaptchaAction();
$code = $captcha->getVerifyCode(false); $code = $captcha->getVerifyCode(false);
...@@ -111,6 +113,7 @@ class CaptchaValidator extends Validator ...@@ -111,6 +113,7 @@ class CaptchaValidator extends Validator
$options['skipOnEmpty'] = 1; $options['skipOnEmpty'] = 1;
} }
$view->registerAssetBundle('yii/validation');
return 'yii.validation.captcha(value, messages, ' . json_encode($options) . ');'; return 'yii.validation.captcha(value, messages, ' . json_encode($options) . ');';
} }
} }
......
...@@ -79,28 +79,28 @@ class CompareValidator extends Validator ...@@ -79,28 +79,28 @@ class CompareValidator extends Validator
if ($this->message === null) { if ($this->message === null) {
switch ($this->operator) { switch ($this->operator) {
case '==': case '==':
$this->message = Yii::t('yii|{attribute} must be repeated exactly.'); $this->message = Yii::t('yii', '{attribute} must be repeated exactly.');
break; break;
case '===': case '===':
$this->message = Yii::t('yii|{attribute} must be repeated exactly.'); $this->message = Yii::t('yii', '{attribute} must be repeated exactly.');
break; break;
case '!=': case '!=':
$this->message = Yii::t('yii|{attribute} must not be equal to "{compareValue}".'); $this->message = Yii::t('yii', '{attribute} must not be equal to "{compareValue}".');
break; break;
case '!==': case '!==':
$this->message = Yii::t('yii|{attribute} must not be equal to "{compareValue}".'); $this->message = Yii::t('yii', '{attribute} must not be equal to "{compareValue}".');
break; break;
case '>': case '>':
$this->message = Yii::t('yii|{attribute} must be greater than "{compareValue}".'); $this->message = Yii::t('yii', '{attribute} must be greater than "{compareValue}".');
break; break;
case '>=': case '>=':
$this->message = Yii::t('yii|{attribute} must be greater than or equal to "{compareValue}".'); $this->message = Yii::t('yii', '{attribute} must be greater than or equal to "{compareValue}".');
break; break;
case '<': case '<':
$this->message = Yii::t('yii|{attribute} must be less than "{compareValue}".'); $this->message = Yii::t('yii', '{attribute} must be less than "{compareValue}".');
break; break;
case '<=': case '<=':
$this->message = Yii::t('yii|{attribute} must be less than or equal to "{compareValue}".'); $this->message = Yii::t('yii', '{attribute} must be less than or equal to "{compareValue}".');
break; break;
default: default:
throw new InvalidConfigException("Unknown operator: {$this->operator}"); throw new InvalidConfigException("Unknown operator: {$this->operator}");
...@@ -119,7 +119,7 @@ class CompareValidator extends Validator ...@@ -119,7 +119,7 @@ class CompareValidator extends Validator
{ {
$value = $object->$attribute; $value = $object->$attribute;
if (is_array($value)) { if (is_array($value)) {
$this->addError($object, $attribute, Yii::t('yii|{attribute} is invalid.')); $this->addError($object, $attribute, Yii::t('yii', '{attribute} is invalid.'));
return; return;
} }
if ($this->compareValue !== null) { if ($this->compareValue !== null) {
...@@ -178,9 +178,11 @@ class CompareValidator extends Validator ...@@ -178,9 +178,11 @@ class CompareValidator extends Validator
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated * @param string $attribute the name of the attribute to be validated
* @return string the client-side validation script * @return string the client-side validation script
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @throws InvalidConfigException if CompareValidator::operator is invalid * @throws InvalidConfigException if CompareValidator::operator is invalid
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
$options = array('operator' => $this->operator); $options = array('operator' => $this->operator);
...@@ -203,6 +205,7 @@ class CompareValidator extends Validator ...@@ -203,6 +205,7 @@ class CompareValidator extends Validator
'{compareValue}' => $compareValue, '{compareValue}' => $compareValue,
))); )));
$view->registerAssetBundle('yii/validation');
return 'yii.validation.compare(value, messages, ' . json_encode($options) . ');'; return 'yii.validation.compare(value, messages, ' . json_encode($options) . ');';
} }
} }
...@@ -38,7 +38,7 @@ class DateValidator extends Validator ...@@ -38,7 +38,7 @@ class DateValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|The format of {attribute} is invalid.'); $this->message = Yii::t('yii', 'The format of {attribute} is invalid.');
} }
} }
......
...@@ -47,6 +47,12 @@ class EmailValidator extends Validator ...@@ -47,6 +47,12 @@ class EmailValidator extends Validator
* Defaults to false. * Defaults to false.
*/ */
public $checkPort = false; public $checkPort = false;
/**
* @var boolean whether validation process should take into account IDN (internationalized domain
* names). Defaults to false meaning that validation of emails containing IDN will always fail.
*/
public $enableIDN = false;
/** /**
* Initializes the validator. * Initializes the validator.
...@@ -55,7 +61,7 @@ class EmailValidator extends Validator ...@@ -55,7 +61,7 @@ class EmailValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|{attribute} is not a valid email address.'); $this->message = Yii::t('yii', '{attribute} is not a valid email address.');
} }
} }
...@@ -81,10 +87,18 @@ class EmailValidator extends Validator ...@@ -81,10 +87,18 @@ class EmailValidator extends Validator
public function validateValue($value) public function validateValue($value)
{ {
// make sure string length is limited to avoid DOS attacks // make sure string length is limited to avoid DOS attacks
$valid = is_string($value) && strlen($value) <= 254 if (!is_string($value) || strlen($value) >= 255) {
&& (preg_match($this->pattern, $value) || $this->allowName && preg_match($this->fullPattern, $value)); return false;
}
if (($atPosition = strpos($value, '@')) === false) {
return false;
}
$domain = rtrim(substr($value, $atPosition + 1), '>');
if ($this->enableIDN) {
$value = idn_to_ascii(ltrim(substr($value, 0, $atPosition), '<')) . '@' . idn_to_ascii($domain);
}
$valid = preg_match($this->pattern, $value) || $this->allowName && preg_match($this->fullPattern, $value);
if ($valid) { if ($valid) {
$domain = rtrim(substr($value, strpos($value, '@') + 1), '>');
if ($this->checkMX && function_exists('checkdnsrr')) { if ($this->checkMX && function_exists('checkdnsrr')) {
$valid = checkdnsrr($domain, 'MX'); $valid = checkdnsrr($domain, 'MX');
} }
...@@ -99,9 +113,11 @@ class EmailValidator extends Validator ...@@ -99,9 +113,11 @@ class EmailValidator extends Validator
* Returns the JavaScript needed for performing client-side validation. * Returns the JavaScript needed for performing client-side validation.
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
$options = array( $options = array(
'pattern' => new JsExpression($this->pattern), 'pattern' => new JsExpression($this->pattern),
...@@ -111,11 +127,16 @@ class EmailValidator extends Validator ...@@ -111,11 +127,16 @@ class EmailValidator extends Validator
'{attribute}' => $object->getAttributeLabel($attribute), '{attribute}' => $object->getAttributeLabel($attribute),
'{value}' => $object->$attribute, '{value}' => $object->$attribute,
))), ))),
'enableIDN' => (boolean)$this->enableIDN,
); );
if ($this->skipOnEmpty) { if ($this->skipOnEmpty) {
$options['skipOnEmpty'] = 1; $options['skipOnEmpty'] = 1;
} }
$view->registerAssetBundle('yii/validation');
if ($this->enableIDN) {
$view->registerAssetBundle('yii/punycode');
}
return 'yii.validation.email(value, messages, ' . Json::encode($options) . ');'; return 'yii.validation.email(value, messages, ' . Json::encode($options) . ');';
} }
} }
...@@ -45,7 +45,7 @@ class ExistValidator extends Validator ...@@ -45,7 +45,7 @@ class ExistValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|{attribute} is invalid.'); $this->message = Yii::t('yii', '{attribute} is invalid.');
} }
} }
......
...@@ -97,22 +97,22 @@ class FileValidator extends Validator ...@@ -97,22 +97,22 @@ class FileValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|File upload failed.'); $this->message = Yii::t('yii', 'File upload failed.');
} }
if ($this->uploadRequired === null) { if ($this->uploadRequired === null) {
$this->uploadRequired = Yii::t('yii|Please upload a file.'); $this->uploadRequired = Yii::t('yii', 'Please upload a file.');
} }
if ($this->tooMany === null) { if ($this->tooMany === null) {
$this->tooMany = Yii::t('yii|You can upload at most {limit} files.'); $this->tooMany = Yii::t('yii', 'You can upload at most {limit} files.');
} }
if ($this->wrongType === null) { if ($this->wrongType === null) {
$this->wrongType = Yii::t('yii|Only files with these extensions are allowed: {extensions}.'); $this->wrongType = Yii::t('yii', 'Only files with these extensions are allowed: {extensions}.');
} }
if ($this->tooBig === null) { if ($this->tooBig === null) {
$this->tooBig = Yii::t('yii|The file "{file}" is too big. Its size cannot exceed {limit} bytes.'); $this->tooBig = Yii::t('yii', 'The file "{file}" is too big. Its size cannot exceed {limit} bytes.');
} }
if ($this->tooSmall === null) { if ($this->tooSmall === null) {
$this->tooSmall = Yii::t('yii|The file "{file}" is too small. Its size cannot be smaller than {limit} bytes.'); $this->tooSmall = Yii::t('yii', 'The file "{file}" is too small. Its size cannot be smaller than {limit} bytes.');
} }
if (!is_array($this->types)) { if (!is_array($this->types)) {
$this->types = preg_split('/[\s,]+/', strtolower($this->types), -1, PREG_SPLIT_NO_EMPTY); $this->types = preg_split('/[\s,]+/', strtolower($this->types), -1, PREG_SPLIT_NO_EMPTY);
......
...@@ -79,12 +79,14 @@ class InlineValidator extends Validator ...@@ -79,12 +79,14 @@ class InlineValidator extends Validator
* *
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. Null if the validator does not support * @return string the client-side validation script. Null if the validator does not support
* client-side validation. * client-side validation.
* @see enableClientValidation * @see enableClientValidation
* @see \yii\web\ActiveForm::enableClientValidation * @see \yii\web\ActiveForm::enableClientValidation
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
if ($this->clientValidate !== null) { if ($this->clientValidate !== null) {
$method = $this->clientValidate; $method = $this->clientValidate;
......
...@@ -62,14 +62,14 @@ class NumberValidator extends Validator ...@@ -62,14 +62,14 @@ class NumberValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === null) {
$this->message = $this->integerOnly ? Yii::t('yii|{attribute} must be an integer.') $this->message = $this->integerOnly ? Yii::t('yii', '{attribute} must be an integer.')
: Yii::t('yii|{attribute} must be a number.'); : Yii::t('yii', '{attribute} must be a number.');
} }
if ($this->min !== null && $this->tooSmall === null) { if ($this->min !== null && $this->tooSmall === null) {
$this->tooSmall = Yii::t('yii|{attribute} must be no less than {min}.'); $this->tooSmall = Yii::t('yii', '{attribute} must be no less than {min}.');
} }
if ($this->max !== null && $this->tooBig === null) { if ($this->max !== null && $this->tooBig === null) {
$this->tooBig = Yii::t('yii|{attribute} must be no greater than {max}.'); $this->tooBig = Yii::t('yii', '{attribute} must be no greater than {max}.');
} }
} }
...@@ -83,7 +83,7 @@ class NumberValidator extends Validator ...@@ -83,7 +83,7 @@ class NumberValidator extends Validator
{ {
$value = $object->$attribute; $value = $object->$attribute;
if (is_array($value)) { if (is_array($value)) {
$this->addError($object, $attribute, Yii::t('yii|{attribute} is invalid.')); $this->addError($object, $attribute, Yii::t('yii', '{attribute} is invalid.'));
return; return;
} }
$pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern; $pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
...@@ -114,9 +114,11 @@ class NumberValidator extends Validator ...@@ -114,9 +114,11 @@ class NumberValidator extends Validator
* Returns the JavaScript needed for performing client-side validation. * Returns the JavaScript needed for performing client-side validation.
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
$label = $object->getAttributeLabel($attribute); $label = $object->getAttributeLabel($attribute);
$value = $object->$attribute; $value = $object->$attribute;
...@@ -149,6 +151,7 @@ class NumberValidator extends Validator ...@@ -149,6 +151,7 @@ class NumberValidator extends Validator
$options['skipOnEmpty'] = 1; $options['skipOnEmpty'] = 1;
} }
$view->registerAssetBundle('yii/validation');
return 'yii.validation.number(value, messages, ' . Json::encode($options) . ');'; return 'yii.validation.number(value, messages, ' . Json::encode($options) . ');';
} }
} }
...@@ -48,7 +48,7 @@ class RangeValidator extends Validator ...@@ -48,7 +48,7 @@ class RangeValidator extends Validator
throw new InvalidConfigException('The "range" property must be set.'); throw new InvalidConfigException('The "range" property must be set.');
} }
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|{attribute} is invalid.'); $this->message = Yii::t('yii', '{attribute} is invalid.');
} }
} }
...@@ -81,9 +81,11 @@ class RangeValidator extends Validator ...@@ -81,9 +81,11 @@ class RangeValidator extends Validator
* Returns the JavaScript needed for performing client-side validation. * Returns the JavaScript needed for performing client-side validation.
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
$range = array(); $range = array();
foreach ($this->range as $value) { foreach ($this->range as $value) {
...@@ -101,6 +103,7 @@ class RangeValidator extends Validator ...@@ -101,6 +103,7 @@ class RangeValidator extends Validator
$options['skipOnEmpty'] = 1; $options['skipOnEmpty'] = 1;
} }
$view->registerAssetBundle('yii/validation');
return 'yii.validation.range(value, messages, ' . json_encode($options) . ');'; return 'yii.validation.range(value, messages, ' . json_encode($options) . ');';
} }
} }
...@@ -45,7 +45,7 @@ class RegularExpressionValidator extends Validator ...@@ -45,7 +45,7 @@ class RegularExpressionValidator extends Validator
throw new InvalidConfigException('The "pattern" property must be set.'); throw new InvalidConfigException('The "pattern" property must be set.');
} }
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|{attribute} is invalid.'); $this->message = Yii::t('yii', '{attribute} is invalid.');
} }
} }
...@@ -79,10 +79,12 @@ class RegularExpressionValidator extends Validator ...@@ -79,10 +79,12 @@ class RegularExpressionValidator extends Validator
* Returns the JavaScript needed for performing client-side validation. * Returns the JavaScript needed for performing client-side validation.
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
* @throws InvalidConfigException if the "pattern" is not a valid regular expression * @throws InvalidConfigException if the "pattern" is not a valid regular expression
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
$pattern = $this->pattern; $pattern = $this->pattern;
$pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $pattern); $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $pattern);
...@@ -110,6 +112,7 @@ class RegularExpressionValidator extends Validator ...@@ -110,6 +112,7 @@ class RegularExpressionValidator extends Validator
$options['skipOnEmpty'] = 1; $options['skipOnEmpty'] = 1;
} }
$view->registerAssetBundle('yii/validation');
return 'yii.validation.regularExpression(value, messages, ' . Json::encode($options) . ');'; return 'yii.validation.regularExpression(value, messages, ' . Json::encode($options) . ');';
} }
} }
...@@ -57,8 +57,8 @@ class RequiredValidator extends Validator ...@@ -57,8 +57,8 @@ class RequiredValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === null) {
$this->message = $this->requiredValue === null ? Yii::t('yii|{attribute} cannot be blank.') $this->message = $this->requiredValue === null ? Yii::t('yii', '{attribute} cannot be blank.')
: Yii::t('yii|{attribute} must be "{requiredValue}".'); : Yii::t('yii', '{attribute} must be "{requiredValue}".');
} }
} }
...@@ -102,9 +102,11 @@ class RequiredValidator extends Validator ...@@ -102,9 +102,11 @@ class RequiredValidator extends Validator
* Returns the JavaScript needed for performing client-side validation. * Returns the JavaScript needed for performing client-side validation.
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
$options = array(); $options = array();
if ($this->requiredValue !== null) { if ($this->requiredValue !== null) {
...@@ -124,6 +126,7 @@ class RequiredValidator extends Validator ...@@ -124,6 +126,7 @@ class RequiredValidator extends Validator
'{value}' => $object->$attribute, '{value}' => $object->$attribute,
))); )));
$view->registerAssetBundle('yii/validation');
return 'yii.validation.required(value, messages, ' . json_encode($options) . ');'; return 'yii.validation.required(value, messages, ' . json_encode($options) . ');';
} }
} }
...@@ -65,16 +65,16 @@ class StringValidator extends Validator ...@@ -65,16 +65,16 @@ class StringValidator extends Validator
$this->encoding = Yii::$app->charset; $this->encoding = Yii::$app->charset;
} }
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|{attribute} must be a string.'); $this->message = Yii::t('yii', '{attribute} must be a string.');
} }
if ($this->min !== null && $this->tooShort === null) { if ($this->min !== null && $this->tooShort === null) {
$this->tooShort = Yii::t('yii|{attribute} should contain at least {min} characters.'); $this->tooShort = Yii::t('yii', '{attribute} should contain at least {min} characters.');
} }
if ($this->max !== null && $this->tooLong === null) { if ($this->max !== null && $this->tooLong === null) {
$this->tooLong = Yii::t('yii|{attribute} should contain at most {max} characters.'); $this->tooLong = Yii::t('yii', '{attribute} should contain at most {max} characters.');
} }
if ($this->is !== null && $this->notEqual === null) { if ($this->is !== null && $this->notEqual === null) {
$this->notEqual = Yii::t('yii|{attribute} should contain {length} characters.'); $this->notEqual = Yii::t('yii', '{attribute} should contain {length} characters.');
} }
} }
...@@ -126,9 +126,11 @@ class StringValidator extends Validator ...@@ -126,9 +126,11 @@ class StringValidator extends Validator
* Returns the JavaScript needed for performing client-side validation. * Returns the JavaScript needed for performing client-side validation.
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
$label = $object->getAttributeLabel($attribute); $label = $object->getAttributeLabel($attribute);
$value = $object->$attribute; $value = $object->$attribute;
...@@ -168,6 +170,7 @@ class StringValidator extends Validator ...@@ -168,6 +170,7 @@ class StringValidator extends Validator
$options['skipOnEmpty'] = 1; $options['skipOnEmpty'] = 1;
} }
$view->registerAssetBundle('yii/validation');
return 'yii.validation.string(value, messages, ' . json_encode($options) . ');'; return 'yii.validation.string(value, messages, ' . json_encode($options) . ');';
} }
} }
......
...@@ -39,7 +39,7 @@ class UniqueValidator extends Validator ...@@ -39,7 +39,7 @@ class UniqueValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|{attribute} "{value}" has already been taken.'); $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
} }
} }
...@@ -55,7 +55,7 @@ class UniqueValidator extends Validator ...@@ -55,7 +55,7 @@ class UniqueValidator extends Validator
$value = $object->$attribute; $value = $object->$attribute;
if (is_array($value)) { if (is_array($value)) {
$this->addError($object, $attribute, Yii::t('yii|{attribute} is invalid.')); $this->addError($object, $attribute, Yii::t('yii', '{attribute} is invalid.'));
return; return;
} }
......
...@@ -37,6 +37,12 @@ class UrlValidator extends Validator ...@@ -37,6 +37,12 @@ class UrlValidator extends Validator
* contain the scheme part. * contain the scheme part.
**/ **/
public $defaultScheme; public $defaultScheme;
/**
* @var boolean whether validation process should take into account IDN (internationalized
* domain names). Defaults to false meaning that validation of URLs containing IDN will always
* fail.
*/
public $enableIDN = false;
/** /**
...@@ -46,7 +52,7 @@ class UrlValidator extends Validator ...@@ -46,7 +52,7 @@ class UrlValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii|{attribute} is not a valid URL.'); $this->message = Yii::t('yii', '{attribute} is not a valid URL.');
} }
} }
...@@ -87,6 +93,12 @@ class UrlValidator extends Validator ...@@ -87,6 +93,12 @@ class UrlValidator extends Validator
$pattern = $this->pattern; $pattern = $this->pattern;
} }
if ($this->enableIDN) {
$value = preg_replace_callback('/:\/\/([^\/]+)/', function($matches) {
return '://' . idn_to_ascii($matches[1]);
}, $value);
}
if (preg_match($pattern, $value)) { if (preg_match($pattern, $value)) {
return true; return true;
} }
...@@ -98,10 +110,12 @@ class UrlValidator extends Validator ...@@ -98,10 +110,12 @@ class UrlValidator extends Validator
* Returns the JavaScript needed for performing client-side validation. * Returns the JavaScript needed for performing client-side validation.
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
* @see \yii\Web\ActiveForm::enableClientValidation * @see \yii\Web\ActiveForm::enableClientValidation
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
if (strpos($this->pattern, '{schemes}') !== false) { if (strpos($this->pattern, '{schemes}') !== false) {
$pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern); $pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
...@@ -115,6 +129,7 @@ class UrlValidator extends Validator ...@@ -115,6 +129,7 @@ class UrlValidator extends Validator
'{attribute}' => $object->getAttributeLabel($attribute), '{attribute}' => $object->getAttributeLabel($attribute),
'{value}' => $object->$attribute, '{value}' => $object->$attribute,
))), ))),
'enableIDN' => (boolean)$this->enableIDN,
); );
if ($this->skipOnEmpty) { if ($this->skipOnEmpty) {
$options['skipOnEmpty'] = 1; $options['skipOnEmpty'] = 1;
...@@ -123,7 +138,10 @@ class UrlValidator extends Validator ...@@ -123,7 +138,10 @@ class UrlValidator extends Validator
$options['defaultScheme'] = $this->defaultScheme; $options['defaultScheme'] = $this->defaultScheme;
} }
$view->registerAssetBundle('yii/validation');
if ($this->enableIDN) {
$view->registerAssetBundle('yii/punycode');
}
return 'yii.validation.url(value, messages, ' . Json::encode($options) . ');'; return 'yii.validation.url(value, messages, ' . Json::encode($options) . ');';
} }
} }
...@@ -211,11 +211,13 @@ abstract class Validator extends Component ...@@ -211,11 +211,13 @@ abstract class Validator extends Component
* *
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script. Null if the validator does not support * @return string the client-side validation script. Null if the validator does not support
* client-side validation. * client-side validation.
* @see \yii\web\ActiveForm::enableClientValidation * @see \yii\web\ActiveForm::enableClientValidation
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute, $view)
{ {
return null; return null;
} }
......
...@@ -100,7 +100,7 @@ class AccessControl extends ActionFilter ...@@ -100,7 +100,7 @@ class AccessControl extends ActionFilter
if ($user->getIsGuest()) { if ($user->getIsGuest()) {
$user->loginRequired(); $user->loginRequired();
} else { } else {
throw new HttpException(403, Yii::t('yii|You are not allowed to perform this action.')); throw new HttpException(403, Yii::t('yii', 'You are not allowed to perform this action.'));
} }
} }
} }
...@@ -260,10 +260,6 @@ class CaptchaAction extends Action ...@@ -260,10 +260,6 @@ class CaptchaAction extends Action
(int)($this->foreColor % 0x10000 / 0x100), (int)($this->foreColor % 0x10000 / 0x100),
$this->foreColor % 0x100); $this->foreColor % 0x100);
if ($this->fontFile === null) {
$this->fontFile = dirname(__FILE__) . '/SpicyRice.ttf';
}
$length = strlen($code); $length = strlen($code);
$box = imagettfbbox(30, 0, $this->fontFile, $code); $box = imagettfbbox(30, 0, $this->fontFile, $code);
$w = $box[4] - $box[0] + $this->offset * ($length - 1); $w = $box[4] - $box[0] + $this->offset * ($length - 1);
...@@ -302,10 +298,6 @@ class CaptchaAction extends Action ...@@ -302,10 +298,6 @@ class CaptchaAction extends Action
$image = new \Imagick(); $image = new \Imagick();
$image->newImage($this->width, $this->height, $backColor); $image->newImage($this->width, $this->height, $backColor);
if ($this->fontFile === null) {
$this->fontFile = dirname(__FILE__) . '/SpicyRice.ttf';
}
$draw = new \ImagickDraw(); $draw = new \ImagickDraw();
$draw->setFont($this->fontFile); $draw->setFont($this->fontFile);
$draw->setFontSize(30); $draw->setFontSize(30);
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
namespace yii\web; namespace yii\web;
use Yii; use Yii;
use yii\base\DictionaryIterator; use ArrayIterator;
use yii\helpers\SecurityHelper; use yii\helpers\SecurityHelper;
/** /**
...@@ -50,11 +50,11 @@ class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \ ...@@ -50,11 +50,11 @@ class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \
* Returns an iterator for traversing the cookies in the collection. * Returns an iterator for traversing the cookies in the collection.
* This method is required by the SPL interface `IteratorAggregate`. * This method is required by the SPL interface `IteratorAggregate`.
* It will be implicitly called when you use `foreach` to traverse the collection. * It will be implicitly called when you use `foreach` to traverse the collection.
* @return DictionaryIterator an iterator for traversing the cookies in the collection. * @return ArrayIterator an iterator for traversing the cookies in the collection.
*/ */
public function getIterator() public function getIterator()
{ {
return new DictionaryIterator($this->_cookies); return new ArrayIterator($this->_cookies);
} }
/** /**
......
...@@ -47,8 +47,8 @@ use Yii; ...@@ -47,8 +47,8 @@ use Yii;
* } * }
* *
* // display pagination * // display pagination
* LinkPager::widget($this, array( * LinkPager::widget(array(
* 'pages' => $pages, * 'pagination' => $pages,
* )); * ));
* ~~~ * ~~~
* *
......
...@@ -72,7 +72,7 @@ class Request extends \yii\base\Request ...@@ -72,7 +72,7 @@ class Request extends \yii\base\Request
$_GET = array_merge($_GET, $params); $_GET = array_merge($_GET, $params);
return array($route, $_GET); return array($route, $_GET);
} else { } else {
throw new HttpException(404, Yii::t('yii|Page not found.')); throw new HttpException(404, Yii::t('yii', 'Page not found.'));
} }
} }
...@@ -786,7 +786,7 @@ class Request extends \yii\base\Request ...@@ -786,7 +786,7 @@ class Request extends \yii\base\Request
} }
if (empty($token) || $cookies->getValue($this->csrfTokenName) !== $token) { if (empty($token) || $cookies->getValue($this->csrfTokenName) !== $token) {
throw new HttpException(400, Yii::t('yii|Unable to verify your data submission.')); throw new HttpException(400, Yii::t('yii', 'Unable to verify your data submission.'));
} }
} }
} }
......
...@@ -8,8 +8,10 @@ ...@@ -8,8 +8,10 @@
namespace yii\web; namespace yii\web;
use Yii; use Yii;
use yii\base\HttpException;
use yii\helpers\FileHelper; use yii\helpers\FileHelper;
use yii\helpers\Html; use yii\helpers\Html;
use yii\helpers\StringHelper;
/** /**
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
...@@ -31,27 +33,76 @@ class Response extends \yii\base\Response ...@@ -31,27 +33,76 @@ class Response extends \yii\base\Response
* @param string $content content to be set. * @param string $content content to be set.
* @param string $mimeType mime type of the content. If null, it will be guessed automatically based on the given file name. * @param string $mimeType mime type of the content. If null, it will be guessed automatically based on the given file name.
* @param boolean $terminate whether to terminate the current application after calling this method * @param boolean $terminate whether to terminate the current application after calling this method
* @todo * @throws \yii\base\HttpException when range request is not satisfiable.
*/ */
public function sendFile($fileName, $content, $mimeType = null, $terminate = true) public function sendFile($fileName, $content, $mimeType = null, $terminate = true)
{ {
if ($mimeType === null && ($mimeType = FileHelper::getMimeType($fileName)) === null) { if ($mimeType === null && (($mimeType = FileHelper::getMimeTypeByExtension($fileName)) === null)) {
$mimeType = 'application/octet-stream'; $mimeType = 'application/octet-stream';
} }
$fileSize = StringHelper::strlen($content);
$contentStart = 0;
$contentEnd = $fileSize - 1;
// tell the client that we accept range requests
header('Accept-Ranges: bytes');
if (isset($_SERVER['HTTP_RANGE'])) {
// client sent us a multibyte range, can not hold this one for now
if (strpos(',', $_SERVER['HTTP_RANGE']) !== false) {
header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
throw new HttpException(416, 'Requested Range Not Satisfiable');
}
$range = str_replace('bytes=', '', $_SERVER['HTTP_RANGE']);
// range requests starts from "-", so it means that data must be dumped the end point.
if ($range[0] === '-') {
$contentStart = $fileSize - substr($range, 1);
} else {
$range = explode('-', $range);
$contentStart = $range[0];
$contentEnd = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $fileSize - 1;
}
/* Check the range and make sure it's treated according to the specs.
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
*/
// End bytes can not be larger than $end.
$contentEnd = ($contentEnd > $fileSize) ? $fileSize : $contentEnd;
// Validate the requested range and return an error if it's not correct.
$wrongContentStart = ($contentStart > $contentEnd || $contentStart > $fileSize - 1 || $contentStart < 0);
if ($wrongContentStart) {
header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
throw new HttpException(416, 'Requested Range Not Satisfiable');
}
header('HTTP/1.1 206 Partial Content');
header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
} else {
header('HTTP/1.1 200 OK');
}
$length = $contentEnd - $contentStart + 1; // Calculate new content length
header('Pragma: public'); header('Pragma: public');
header('Expires: 0'); header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-type: $mimeType"); header('Content-Type: ' . $mimeType);
if (ob_get_length() === false) { header('Content-Length: ' . $length);
header('Content-Length: ' . (function_exists('mb_strlen') ? mb_strlen($content, '8bit') : strlen($content))); header('Content-Disposition: attachment; filename="' . $fileName . '"');
}
header("Content-Disposition: attachment; filename=\"$fileName\"");
header('Content-Transfer-Encoding: binary'); header('Content-Transfer-Encoding: binary');
$content = StringHelper::substr($content, $contentStart, $length);
if ($terminate) { if ($terminate) {
// clean up the application first because the file downloading could take long time // clean up the application first because the file downloading could take long time
// which may cause timeout of some resources (such as DB connection) // which may cause timeout of some resources (such as DB connection)
Yii::app()->end(0, false); ob_start();
Yii::$app->end(0, false);
ob_end_clean();
echo $content; echo $content;
exit(0); exit(0);
} else { } else {
......
...@@ -183,7 +183,15 @@ class UrlManager extends Component ...@@ -183,7 +183,15 @@ class UrlManager extends Component
/** @var $rule UrlRule */ /** @var $rule UrlRule */
foreach ($this->rules as $rule) { foreach ($this->rules as $rule) {
if (($url = $rule->createUrl($this, $route, $params)) !== false) { if (($url = $rule->createUrl($this, $route, $params)) !== false) {
return rtrim($baseUrl, '/') . '/' . $url . $anchor; if ($rule->host !== null) {
if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
return substr($url, 0, $pos) . $baseUrl . substr($url, $pos);
} else {
return $url . $baseUrl . $anchor;
}
} else {
return "$baseUrl/{$url}{$anchor}";
}
} }
} }
...@@ -193,9 +201,9 @@ class UrlManager extends Component ...@@ -193,9 +201,9 @@ class UrlManager extends Component
if (!empty($params)) { if (!empty($params)) {
$route .= '?' . http_build_query($params); $route .= '?' . http_build_query($params);
} }
return rtrim($baseUrl, '/') . '/' . $route . $anchor; return "$baseUrl/{$route}{$anchor}";
} else { } else {
$url = $baseUrl . '?' . $this->routeVar . '=' . $route; $url = "$baseUrl?{$this->routeVar}=$route";
if (!empty($params)) { if (!empty($params)) {
$url .= '&' . http_build_query($params); $url .= '&' . http_build_query($params);
} }
...@@ -213,7 +221,12 @@ class UrlManager extends Component ...@@ -213,7 +221,12 @@ class UrlManager extends Component
*/ */
public function createAbsoluteUrl($route, $params = array()) public function createAbsoluteUrl($route, $params = array())
{ {
return $this->getHostInfo() . $this->createUrl($route, $params); $url = $this->createUrl($route, $params);
if (strpos($url, '://') !== false) {
return $url;
} else {
return $this->getHostInfo() . $url;
}
} }
/** /**
...@@ -238,7 +251,7 @@ class UrlManager extends Component ...@@ -238,7 +251,7 @@ class UrlManager extends Component
*/ */
public function setBaseUrl($value) public function setBaseUrl($value)
{ {
$this->_baseUrl = $value; $this->_baseUrl = rtrim($value, '/');
} }
/** /**
......
...@@ -28,9 +28,15 @@ class UrlRule extends Object ...@@ -28,9 +28,15 @@ class UrlRule extends Object
const CREATION_ONLY = 2; const CREATION_ONLY = 2;
/** /**
* @var string regular expression used to parse a URL * @var string the pattern used to parse and create the path info part of a URL.
* @see host
*/ */
public $pattern; public $pattern;
/**
* @var string the pattern used to parse and create the host info part of a URL.
* @see pattern
*/
public $host;
/** /**
* @var string the route to the controller action * @var string the route to the controller action
*/ */
...@@ -102,7 +108,10 @@ class UrlRule extends Object ...@@ -102,7 +108,10 @@ class UrlRule extends Object
} }
$this->pattern = trim($this->pattern, '/'); $this->pattern = trim($this->pattern, '/');
if ($this->pattern === '') {
if ($this->host !== null) {
$this->pattern = rtrim($this->host, '/') . rtrim('/' . $this->pattern, '/') . '/';
} elseif ($this->pattern === '') {
$this->_template = ''; $this->_template = '';
$this->pattern = '#^$#u'; $this->pattern = '#^$#u';
return; return;
...@@ -162,11 +171,11 @@ class UrlRule extends Object ...@@ -162,11 +171,11 @@ class UrlRule extends Object
return false; return false;
} }
if ($this->verb !== null && !in_array($request->verb, $this->verb, true)) { if ($this->verb !== null && !in_array($request->getRequestMethod(), $this->verb, true)) {
return false; return false;
} }
$pathInfo = $request->pathInfo; $pathInfo = $request->getPathInfo();
$suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix); $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix);
if ($suffix !== '' && $pathInfo !== '') { if ($suffix !== '' && $pathInfo !== '') {
$n = strlen($suffix); $n = strlen($suffix);
...@@ -182,6 +191,10 @@ class UrlRule extends Object ...@@ -182,6 +191,10 @@ class UrlRule extends Object
} }
} }
if ($this->host !== null) {
$pathInfo = strtolower($request->getHostInfo()) . '/' . $pathInfo;
}
if (!preg_match($this->pattern, $pathInfo, $matches)) { if (!preg_match($this->pattern, $pathInfo, $matches)) {
return false; return false;
} }
...@@ -267,7 +280,12 @@ class UrlRule extends Object ...@@ -267,7 +280,12 @@ class UrlRule extends Object
} }
$url = trim(strtr($this->_template, $tr), '/'); $url = trim(strtr($this->_template, $tr), '/');
if (strpos($url, '//') !== false) { if ($this->host !== null) {
$pos = strpos($url, '/', 8);
if ($pos !== false) {
$url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
}
} elseif (strpos($url, '//') !== false) {
$url = preg_replace('#/+#', '/', $url); $url = preg_replace('#/+#', '/', $url);
} }
......
...@@ -286,7 +286,7 @@ class User extends Component ...@@ -286,7 +286,7 @@ class User extends Component
if ($this->loginUrl !== null) { if ($this->loginUrl !== null) {
Yii::$app->getResponse()->redirect($this->loginUrl); Yii::$app->getResponse()->redirect($this->loginUrl);
} else { } else {
throw new HttpException(403, Yii::t('yii|Login Required')); throw new HttpException(403, Yii::t('yii', 'Login Required'));
} }
} }
......
...@@ -138,7 +138,7 @@ class ActiveField extends Component ...@@ -138,7 +138,7 @@ class ActiveField extends Component
$validators = array(); $validators = array();
foreach ($this->model->getActiveValidators($attribute) as $validator) { foreach ($this->model->getActiveValidators($attribute) as $validator) {
/** @var \yii\validators\Validator $validator */ /** @var \yii\validators\Validator $validator */
$js = $validator->clientValidateAttribute($this->model, $attribute); $js = $validator->clientValidateAttribute($this->model, $attribute, $this->form->getView());
if ($validator->enableClientValidation && $js != '') { if ($validator->enableClientValidation && $js != '') {
$validators[] = $js; $validators[] = $js;
} }
......
...@@ -187,7 +187,7 @@ class ActiveForm extends Widget ...@@ -187,7 +187,7 @@ class ActiveForm extends Widget
} }
} }
$header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii|Please fix the following errors:') . '</p>'; $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
$footer = isset($options['footer']) ? $options['footer'] : ''; $footer = isset($options['footer']) ? $options['footer'] : '';
unset($options['header'], $options['footer']); unset($options['header'], $options['footer']);
......
...@@ -23,7 +23,7 @@ use yii\helpers\Html; ...@@ -23,7 +23,7 @@ use yii\helpers\Html;
* *
* ~~~ * ~~~
* // $this is the view object currently being used * // $this is the view object currently being used
* echo Breadcrumbs::widget($this, array( * echo Breadcrumbs::widget(array(
* 'links' => array( * 'links' => array(
* array('label' => 'Sample Post', 'url' => array('post/edit', 'id' => 1)), * array('label' => 'Sample Post', 'url' => array('post/edit', 'id' => 1)),
* 'Edit', * 'Edit',
...@@ -37,7 +37,7 @@ use yii\helpers\Html; ...@@ -37,7 +37,7 @@ use yii\helpers\Html;
* *
* ~~~ * ~~~
* // $this is the view object currently being used * // $this is the view object currently being used
* echo Breadcrumbs::widget($this, array( * echo Breadcrumbs::widget(array(
* 'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : array(), * 'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : array(),
* )); * ));
* ~~~ * ~~~
...@@ -103,7 +103,7 @@ class Breadcrumbs extends Widget ...@@ -103,7 +103,7 @@ class Breadcrumbs extends Widget
$links = array(); $links = array();
if ($this->homeLink === null) { if ($this->homeLink === null) {
$links[] = $this->renderItem(array( $links[] = $this->renderItem(array(
'label' => Yii::t('yii|Home'), 'label' => Yii::t('yii', 'Home'),
'url' => Yii::$app->homeUrl, 'url' => Yii::$app->homeUrl,
), $this->itemTemplate); ), $this->itemTemplate);
} elseif ($this->homeLink !== false) { } elseif ($this->homeLink !== false) {
......
...@@ -122,7 +122,7 @@ class LinkPager extends Widget ...@@ -122,7 +122,7 @@ class LinkPager extends Widget
{ {
$buttons = array(); $buttons = array();
$pageCount = $this->pagination->pageCount; $pageCount = $this->pagination->getPageCount();
$currentPage = $this->pagination->getPage(); $currentPage = $this->pagination->getPage();
// first page // first page
......
...@@ -63,7 +63,7 @@ class ListPager extends Widget ...@@ -63,7 +63,7 @@ class ListPager extends Widget
*/ */
public function run() public function run()
{ {
$pageCount = $this->pagination->pageCount; $pageCount = $this->pagination->getPageCount();
$currentPage = $this->pagination->getPage(); $currentPage = $this->pagination->getPage();
$pages = array(); $pages = array();
......
...@@ -27,7 +27,7 @@ use yii\helpers\Html; ...@@ -27,7 +27,7 @@ use yii\helpers\Html;
* *
* ~~~ * ~~~
* // $this is the view object currently being used * // $this is the view object currently being used
* echo Menu::widget($this, array( * echo Menu::widget(array(
* 'items' => array( * 'items' => array(
* // Important: you need to specify url as 'controller/action', * // Important: you need to specify url as 'controller/action',
* // not just as 'controller' even if default action is used. * // not just as 'controller' even if default action is used.
......
#!/usr/bin/env php
<?php <?php
/** /**
* Yii console bootstrap file. * Yii console bootstrap file.
...@@ -15,8 +16,8 @@ defined('STDIN') or define('STDIN', fopen('php://stdin', 'r')); ...@@ -15,8 +16,8 @@ defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
require(__DIR__ . '/Yii.php'); require(__DIR__ . '/Yii.php');
$application = new yii\console\Application(array( $application = new yii\console\Application(array(
'id' => 'yiic', 'id' => 'yii-console',
'basePath' => __DIR__ . '/console', 'basePath' => __DIR__ . '/console',
'controllerPath' => '@yii/console/controllers', 'controllerPath' => '@yii/console/controllers',
)); ));
$application->run(); $application->run();
\ No newline at end of file
@echo off
rem -------------------------------------------------------------
rem Yii command line bootstrap script for Windows.
rem
rem @author Qiang Xue <qiang.xue@gmail.com>
rem @link http://www.yiiframework.com/
rem @copyright Copyright &copy; 2012 Yii Software LLC
rem @license http://www.yiiframework.com/license/
rem -------------------------------------------------------------
@setlocal
set YII_PATH=%~dp0
if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe
"%PHP_COMMAND%" "%YII_PATH%yii" %*
@endlocal
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