PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/yii/framework/web/CController.php

https://bitbucket.org/ddonthula/zurmotest
PHP | 1231 lines | 494 code | 80 blank | 657 comment | 80 complexity | c1dd791271d14a519ba9fa967f694cda MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, LGPL-3.0, LGPL-2.1, BSD-2-Clause, GPL-2.0
  1. <?php
  2. /**
  3. * CController class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CController manages a set of actions which deal with the corresponding user requests.
  12. *
  13. * Through the actions, CController coordinates the data flow between models and views.
  14. *
  15. * When a user requests an action 'XYZ', CController will do one of the following:
  16. * 1. Method-based action: call method 'actionXYZ' if it exists;
  17. * 2. Class-based action: create an instance of class 'XYZ' if the class is found in the action class map
  18. * (specified via {@link actions()}, and execute the action;
  19. * 3. Call {@link missingAction()}, which by default will raise a 404 HTTP exception.
  20. *
  21. * If the user does not specify an action, CController will run the action specified by
  22. * {@link defaultAction}, instead.
  23. *
  24. * CController may be configured to execute filters before and after running actions.
  25. * Filters preprocess/postprocess the user request/response and may quit executing actions
  26. * if needed. They are executed in the order they are specified. If during the execution,
  27. * any of the filters returns true, the rest filters and the action will no longer get executed.
  28. *
  29. * Filters can be individual objects, or methods defined in the controller class.
  30. * They are specified by overriding {@link filters()} method. The following is an example
  31. * of the filter specification:
  32. * <pre>
  33. * array(
  34. * 'accessControl - login',
  35. * 'ajaxOnly + search',
  36. * array(
  37. * 'COutputCache + list',
  38. * 'duration'=>300,
  39. * ),
  40. * )
  41. * </pre>
  42. * The above example declares three filters: accessControl, ajaxOnly, COutputCache. The first two
  43. * are method-based filters (defined in CController), which refer to filtering methods in the controller class;
  44. * while the last refers to an object-based filter whose class is 'system.web.widgets.COutputCache' and
  45. * the 'duration' property is initialized as 300 (s).
  46. *
  47. * For method-based filters, a method named 'filterXYZ($filterChain)' in the controller class
  48. * will be executed, where 'XYZ' stands for the filter name as specified in {@link filters()}.
  49. * Note, inside the filter method, you must call <code>$filterChain->run()</code> if the action should
  50. * be executed. Otherwise, the filtering process would stop at this filter.
  51. *
  52. * Filters can be specified so that they are executed only when running certain actions.
  53. * For method-based filters, this is done by using '+' and '-' operators in the filter specification.
  54. * The '+' operator means the filter runs only when the specified actions are requested;
  55. * while the '-' operator means the filter runs only when the requested action is not among those actions.
  56. * For object-based filters, the '+' and '-' operators are following the class name.
  57. *
  58. * @property array $actionParams The request parameters to be used for action parameter binding.
  59. * @property CAction $action The action currently being executed, null if no active action.
  60. * @property string $id ID of the controller.
  61. * @property string $uniqueId The controller ID that is prefixed with the module ID (if any).
  62. * @property string $route The route (module ID, controller ID and action ID) of the current request.
  63. * @property CWebModule $module The module that this controller belongs to. It returns null
  64. * if the controller does not belong to any module.
  65. * @property string $viewPath The directory containing the view files for this controller. Defaults to 'protected/views/ControllerID'.
  66. * @property CMap $clips The list of clips.
  67. * @property string $pageTitle The page title. Defaults to the controller name and the action name.
  68. * @property CStack $cachingStack Stack of {@link COutputCache} objects.
  69. *
  70. * @author Qiang Xue <qiang.xue@gmail.com>
  71. * @package system.web
  72. * @since 1.0
  73. */
  74. class CController extends CBaseController
  75. {
  76. /**
  77. * Name of the hidden field storing persistent page states.
  78. */
  79. const STATE_INPUT_NAME='YII_PAGE_STATE';
  80. /**
  81. * @var mixed the name of the layout to be applied to this controller's views.
  82. * Defaults to null, meaning the {@link CWebApplication::layout application layout}
  83. * is used. If it is false, no layout will be applied.
  84. * The {@link CWebModule::layout module layout} will be used
  85. * if the controller belongs to a module and this layout property is null.
  86. */
  87. public $layout;
  88. /**
  89. * @var string the name of the default action. Defaults to 'index'.
  90. */
  91. public $defaultAction='index';
  92. private $_id;
  93. private $_action;
  94. private $_pageTitle;
  95. private $_cachingStack;
  96. private $_clips;
  97. private $_dynamicOutput;
  98. private $_pageStates;
  99. private $_module;
  100. /**
  101. * @param string $id id of this controller
  102. * @param CWebModule $module the module that this controller belongs to.
  103. */
  104. public function __construct($id,$module=null)
  105. {
  106. $this->_id=$id;
  107. $this->_module=$module;
  108. $this->attachBehaviors($this->behaviors());
  109. }
  110. /**
  111. * Initializes the controller.
  112. * This method is called by the application before the controller starts to execute.
  113. * You may override this method to perform the needed initialization for the controller.
  114. */
  115. public function init()
  116. {
  117. }
  118. /**
  119. * Returns the filter configurations.
  120. *
  121. * By overriding this method, child classes can specify filters to be applied to actions.
  122. *
  123. * This method returns an array of filter specifications. Each array element specify a single filter.
  124. *
  125. * For a method-based filter (called inline filter), it is specified as 'FilterName[ +|- Action1, Action2, ...]',
  126. * where the '+' ('-') operators describe which actions should be (should not be) applied with the filter.
  127. *
  128. * For a class-based filter, it is specified as an array like the following:
  129. * <pre>
  130. * array(
  131. * 'FilterClass[ +|- Action1, Action2, ...]',
  132. * 'name1'=>'value1',
  133. * 'name2'=>'value2',
  134. * ...
  135. * )
  136. * </pre>
  137. * where the name-value pairs will be used to initialize the properties of the filter.
  138. *
  139. * Note, in order to inherit filters defined in the parent class, a child class needs to
  140. * merge the parent filters with child filters using functions like array_merge().
  141. *
  142. * @return array a list of filter configurations.
  143. * @see CFilter
  144. */
  145. public function filters()
  146. {
  147. return array();
  148. }
  149. /**
  150. * Returns a list of external action classes.
  151. * Array keys are action IDs, and array values are the corresponding
  152. * action class in dot syntax (e.g. 'edit'=>'application.controllers.article.EditArticle')
  153. * or arrays representing the configuration of the actions, such as the following,
  154. * <pre>
  155. * return array(
  156. * 'action1'=>'path.to.Action1Class',
  157. * 'action2'=>array(
  158. * 'class'=>'path.to.Action2Class',
  159. * 'property1'=>'value1',
  160. * 'property2'=>'value2',
  161. * ),
  162. * );
  163. * </pre>
  164. * Derived classes may override this method to declare external actions.
  165. *
  166. * Note, in order to inherit actions defined in the parent class, a child class needs to
  167. * merge the parent actions with child actions using functions like array_merge().
  168. *
  169. * You may import actions from an action provider
  170. * (such as a widget, see {@link CWidget::actions}), like the following:
  171. * <pre>
  172. * return array(
  173. * ...other actions...
  174. * // import actions declared in ProviderClass::actions()
  175. * // the action IDs will be prefixed with 'pro.'
  176. * 'pro.'=>'path.to.ProviderClass',
  177. * // similar as above except that the imported actions are
  178. * // configured with the specified initial property values
  179. * 'pro2.'=>array(
  180. * 'class'=>'path.to.ProviderClass',
  181. * 'action1'=>array(
  182. * 'property1'=>'value1',
  183. * ),
  184. * 'action2'=>array(
  185. * 'property2'=>'value2',
  186. * ),
  187. * ),
  188. * )
  189. * </pre>
  190. *
  191. * In the above, we differentiate action providers from other action
  192. * declarations by the array keys. For action providers, the array keys
  193. * must contain a dot. As a result, an action ID 'pro2.action1' will
  194. * be resolved as the 'action1' action declared in the 'ProviderClass'.
  195. *
  196. * @return array list of external action classes
  197. * @see createAction
  198. */
  199. public function actions()
  200. {
  201. return array();
  202. }
  203. /**
  204. * Returns a list of behaviors that this controller should behave as.
  205. * The return value should be an array of behavior configurations indexed by
  206. * behavior names. Each behavior configuration can be either a string specifying
  207. * the behavior class or an array of the following structure:
  208. * <pre>
  209. * 'behaviorName'=>array(
  210. * 'class'=>'path.to.BehaviorClass',
  211. * 'property1'=>'value1',
  212. * 'property2'=>'value2',
  213. * )
  214. * </pre>
  215. *
  216. * Note, the behavior classes must implement {@link IBehavior} or extend from
  217. * {@link CBehavior}. Behaviors declared in this method will be attached
  218. * to the controller when it is instantiated.
  219. *
  220. * For more details about behaviors, see {@link CComponent}.
  221. * @return array the behavior configurations (behavior name=>behavior configuration)
  222. */
  223. public function behaviors()
  224. {
  225. return array();
  226. }
  227. /**
  228. * Returns the access rules for this controller.
  229. * Override this method if you use the {@link filterAccessControl accessControl} filter.
  230. * @return array list of access rules. See {@link CAccessControlFilter} for details about rule specification.
  231. */
  232. public function accessRules()
  233. {
  234. return array();
  235. }
  236. /**
  237. * Runs the named action.
  238. * Filters specified via {@link filters()} will be applied.
  239. * @param string $actionID action ID
  240. * @throws CHttpException if the action does not exist or the action name is not proper.
  241. * @see filters
  242. * @see createAction
  243. * @see runAction
  244. */
  245. public function run($actionID)
  246. {
  247. if(($action=$this->createAction($actionID))!==null)
  248. {
  249. if(($parent=$this->getModule())===null)
  250. $parent=Yii::app();
  251. if($parent->beforeControllerAction($this,$action))
  252. {
  253. $this->runActionWithFilters($action,$this->filters());
  254. $parent->afterControllerAction($this,$action);
  255. }
  256. }
  257. else
  258. $this->missingAction($actionID);
  259. }
  260. /**
  261. * Runs an action with the specified filters.
  262. * A filter chain will be created based on the specified filters
  263. * and the action will be executed then.
  264. * @param CAction $action the action to be executed.
  265. * @param array $filters list of filters to be applied to the action.
  266. * @see filters
  267. * @see createAction
  268. * @see runAction
  269. */
  270. public function runActionWithFilters($action,$filters)
  271. {
  272. if(empty($filters))
  273. $this->runAction($action);
  274. else
  275. {
  276. $priorAction=$this->_action;
  277. $this->_action=$action;
  278. CFilterChain::create($this,$action,$filters)->run();
  279. $this->_action=$priorAction;
  280. }
  281. }
  282. /**
  283. * Runs the action after passing through all filters.
  284. * This method is invoked by {@link runActionWithFilters} after all possible filters have been executed
  285. * and the action starts to run.
  286. * @param CAction $action action to run
  287. */
  288. public function runAction($action)
  289. {
  290. $priorAction=$this->_action;
  291. $this->_action=$action;
  292. if($this->beforeAction($action))
  293. {
  294. if($action->runWithParams($this->getActionParams())===false)
  295. $this->invalidActionParams($action);
  296. else
  297. $this->afterAction($action);
  298. }
  299. $this->_action=$priorAction;
  300. }
  301. /**
  302. * Returns the request parameters that will be used for action parameter binding.
  303. * By default, this method will return $_GET. You may override this method if you
  304. * want to use other request parameters (e.g. $_GET+$_POST).
  305. * @return array the request parameters to be used for action parameter binding
  306. * @since 1.1.7
  307. */
  308. public function getActionParams()
  309. {
  310. return $_GET;
  311. }
  312. /**
  313. * This method is invoked when the request parameters do not satisfy the requirement of the specified action.
  314. * The default implementation will throw a 400 HTTP exception.
  315. * @param CAction $action the action being executed
  316. * @since 1.1.7
  317. */
  318. public function invalidActionParams($action)
  319. {
  320. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  321. }
  322. /**
  323. * Postprocesses the output generated by {@link render()}.
  324. * This method is invoked at the end of {@link render()} and {@link renderText()}.
  325. * If there are registered client scripts, this method will insert them into the output
  326. * at appropriate places. If there are dynamic contents, they will also be inserted.
  327. * This method may also save the persistent page states in hidden fields of
  328. * stateful forms in the page.
  329. * @param string $output the output generated by the current action
  330. * @return string the output that has been processed.
  331. */
  332. public function processOutput($output)
  333. {
  334. Yii::app()->getClientScript()->render($output);
  335. // if using page caching, we should delay dynamic output replacement
  336. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  337. {
  338. $output=$this->processDynamicOutput($output);
  339. $this->_dynamicOutput=null;
  340. }
  341. if($this->_pageStates===null)
  342. $this->_pageStates=$this->loadPageStates();
  343. if(!empty($this->_pageStates))
  344. $this->savePageStates($this->_pageStates,$output);
  345. return $output;
  346. }
  347. /**
  348. * Postprocesses the dynamic output.
  349. * This method is internally used. Do not call this method directly.
  350. * @param string $output output to be processed
  351. * @return string the processed output
  352. */
  353. public function processDynamicOutput($output)
  354. {
  355. if($this->_dynamicOutput)
  356. {
  357. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  358. }
  359. return $output;
  360. }
  361. /**
  362. * Replaces the dynamic content placeholders with actual content.
  363. * This is a callback function used internally.
  364. * @param array $matches matches
  365. * @return string the replacement
  366. * @see processOutput
  367. */
  368. protected function replaceDynamicOutput($matches)
  369. {
  370. $content=$matches[0];
  371. if(isset($this->_dynamicOutput[$matches[1]]))
  372. {
  373. $content=$this->_dynamicOutput[$matches[1]];
  374. $this->_dynamicOutput[$matches[1]]=null;
  375. }
  376. return $content;
  377. }
  378. /**
  379. * Creates the action instance based on the action name.
  380. * The action can be either an inline action or an object.
  381. * The latter is created by looking up the action map specified in {@link actions}.
  382. * @param string $actionID ID of the action. If empty, the {@link defaultAction default action} will be used.
  383. * @return CAction the action instance, null if the action does not exist.
  384. * @see actions
  385. */
  386. public function createAction($actionID)
  387. {
  388. if($actionID==='')
  389. $actionID=$this->defaultAction;
  390. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  391. return new CInlineAction($this,$actionID);
  392. else
  393. {
  394. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  395. if($action!==null && !method_exists($action,'run'))
  396. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  397. return $action;
  398. }
  399. }
  400. /**
  401. * Creates the action instance based on the action map.
  402. * This method will check to see if the action ID appears in the given
  403. * action map. If so, the corresponding configuration will be used to
  404. * create the action instance.
  405. * @param array $actionMap the action map
  406. * @param string $actionID the action ID that has its prefix stripped off
  407. * @param string $requestActionID the originally requested action ID
  408. * @param array $config the action configuration that should be applied on top of the configuration specified in the map
  409. * @return CAction the action instance, null if the action does not exist.
  410. */
  411. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  412. {
  413. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  414. {
  415. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  416. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  417. }
  418. elseif($pos===false)
  419. return null;
  420. // the action is defined in a provider
  421. $prefix=substr($actionID,0,$pos+1);
  422. if(!isset($actionMap[$prefix]))
  423. return null;
  424. $actionID=(string)substr($actionID,$pos+1);
  425. $provider=$actionMap[$prefix];
  426. if(is_string($provider))
  427. $providerType=$provider;
  428. elseif(is_array($provider) && isset($provider['class']))
  429. {
  430. $providerType=$provider['class'];
  431. if(isset($provider[$actionID]))
  432. {
  433. if(is_string($provider[$actionID]))
  434. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  435. else
  436. $config=array_merge($provider[$actionID],$config);
  437. }
  438. }
  439. else
  440. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  441. $class=Yii::import($providerType,true);
  442. $map=call_user_func(array($class,'actions'));
  443. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  444. }
  445. /**
  446. * Handles the request whose action is not recognized.
  447. * This method is invoked when the controller cannot find the requested action.
  448. * The default implementation simply throws an exception.
  449. * @param string $actionID the missing action name
  450. * @throws CHttpException whenever this method is invoked
  451. */
  452. public function missingAction($actionID)
  453. {
  454. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  455. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  456. }
  457. /**
  458. * @return CAction the action currently being executed, null if no active action.
  459. */
  460. public function getAction()
  461. {
  462. return $this->_action;
  463. }
  464. /**
  465. * @param CAction $value the action currently being executed.
  466. */
  467. public function setAction($value)
  468. {
  469. $this->_action=$value;
  470. }
  471. /**
  472. * @return string ID of the controller
  473. */
  474. public function getId()
  475. {
  476. return $this->_id;
  477. }
  478. /**
  479. * @return string the controller ID that is prefixed with the module ID (if any).
  480. */
  481. public function getUniqueId()
  482. {
  483. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  484. }
  485. /**
  486. * @return string the route (module ID, controller ID and action ID) of the current request.
  487. * @since 1.1.0
  488. */
  489. public function getRoute()
  490. {
  491. if(($action=$this->getAction())!==null)
  492. return $this->getUniqueId().'/'.$action->getId();
  493. else
  494. return $this->getUniqueId();
  495. }
  496. /**
  497. * @return CWebModule the module that this controller belongs to. It returns null
  498. * if the controller does not belong to any module
  499. */
  500. public function getModule()
  501. {
  502. return $this->_module;
  503. }
  504. /**
  505. * Returns the directory containing view files for this controller.
  506. * The default implementation returns 'protected/views/ControllerID'.
  507. * Child classes may override this method to use customized view path.
  508. * If the controller belongs to a module, the default view path
  509. * is the {@link CWebModule::getViewPath module view path} appended with the controller ID.
  510. * @return string the directory containing the view files for this controller. Defaults to 'protected/views/ControllerID'.
  511. */
  512. public function getViewPath()
  513. {
  514. if(($module=$this->getModule())===null)
  515. $module=Yii::app();
  516. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  517. }
  518. /**
  519. * Looks for the view file according to the given view name.
  520. *
  521. * When a theme is currently active, this method will call {@link CTheme::getViewFile} to determine
  522. * which view file should be returned.
  523. *
  524. * Otherwise, this method will return the corresponding view file based on the following criteria:
  525. * <ul>
  526. * <li>absolute view within a module: the view name starts with a single slash '/'.
  527. * In this case, the view will be searched for under the currently active module's view path.
  528. * If there is no active module, the view will be searched for under the application's view path.</li>
  529. * <li>absolute view within the application: the view name starts with double slashes '//'.
  530. * In this case, the view will be searched for under the application's view path.
  531. * This syntax has been available since version 1.1.3.</li>
  532. * <li>aliased view: the view name contains dots and refers to a path alias.
  533. * The view file is determined by calling {@link YiiBase::getPathOfAlias()}. Note that aliased views
  534. * cannot be themed because they can refer to a view file located at arbitrary places.</li>
  535. * <li>relative view: otherwise. Relative views will be searched for under the currently active
  536. * controller's view path.</li>
  537. * </ul>
  538. *
  539. * After the view file is identified, this method may further call {@link CApplication::findLocalizedFile}
  540. * to find its localized version if internationalization is needed.
  541. *
  542. * @param string $viewName view name
  543. * @return string the view file path, false if the view file does not exist
  544. * @see resolveViewFile
  545. * @see CApplication::findLocalizedFile
  546. */
  547. public function getViewFile($viewName)
  548. {
  549. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  550. return $viewFile;
  551. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  552. if(($module=$this->getModule())!==null)
  553. $moduleViewPath=$module->getViewPath();
  554. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  555. }
  556. /**
  557. * Looks for the layout view script based on the layout name.
  558. *
  559. * The layout name can be specified in one of the following ways:
  560. *
  561. * <ul>
  562. * <li>layout is false: returns false, meaning no layout.</li>
  563. * <li>layout is null: the currently active module's layout will be used. If there is no active module,
  564. * the application's layout will be used.</li>
  565. * <li>a regular view name.</li>
  566. * </ul>
  567. *
  568. * The resolution of the view file based on the layout view is similar to that in {@link getViewFile}.
  569. * In particular, the following rules are followed:
  570. *
  571. * Otherwise, this method will return the corresponding view file based on the following criteria:
  572. * <ul>
  573. * <li>When a theme is currently active, this method will call {@link CTheme::getLayoutFile} to determine
  574. * which view file should be returned.</li>
  575. * <li>absolute view within a module: the view name starts with a single slash '/'.
  576. * In this case, the view will be searched for under the currently active module's view path.
  577. * If there is no active module, the view will be searched for under the application's view path.</li>
  578. * <li>absolute view within the application: the view name starts with double slashes '//'.
  579. * In this case, the view will be searched for under the application's view path.
  580. * This syntax has been available since version 1.1.3.</li>
  581. * <li>aliased view: the view name contains dots and refers to a path alias.
  582. * The view file is determined by calling {@link YiiBase::getPathOfAlias()}. Note that aliased views
  583. * cannot be themed because they can refer to a view file located at arbitrary places.</li>
  584. * <li>relative view: otherwise. Relative views will be searched for under the currently active
  585. * module's layout path. In case when there is no active module, the view will be searched for
  586. * under the application's layout path.</li>
  587. * </ul>
  588. *
  589. * After the view file is identified, this method may further call {@link CApplication::findLocalizedFile}
  590. * to find its localized version if internationalization is needed.
  591. *
  592. * @param mixed $layoutName layout name
  593. * @return string the view file for the layout. False if the view file cannot be found
  594. */
  595. public function getLayoutFile($layoutName)
  596. {
  597. if($layoutName===false)
  598. return false;
  599. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  600. return $layoutFile;
  601. if(empty($layoutName))
  602. {
  603. $module=$this->getModule();
  604. while($module!==null)
  605. {
  606. if($module->layout===false)
  607. return false;
  608. if(!empty($module->layout))
  609. break;
  610. $module=$module->getParentModule();
  611. }
  612. if($module===null)
  613. $module=Yii::app();
  614. $layoutName=$module->layout;
  615. }
  616. elseif(($module=$this->getModule())===null)
  617. $module=Yii::app();
  618. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  619. }
  620. /**
  621. * Finds a view file based on its name.
  622. * The view name can be in one of the following formats:
  623. * <ul>
  624. * <li>absolute view within a module: the view name starts with a single slash '/'.
  625. * In this case, the view will be searched for under the currently active module's view path.
  626. * If there is no active module, the view will be searched for under the application's view path.</li>
  627. * <li>absolute view within the application: the view name starts with double slashes '//'.
  628. * In this case, the view will be searched for under the application's view path.
  629. * This syntax has been available since version 1.1.3.</li>
  630. * <li>aliased view: the view name contains dots and refers to a path alias.
  631. * The view file is determined by calling {@link YiiBase::getPathOfAlias()}. Note that aliased views
  632. * cannot be themed because they can refer to a view file located at arbitrary places.</li>
  633. * <li>relative view: otherwise. Relative views will be searched for under the currently active
  634. * controller's view path.</li>
  635. * </ul>
  636. * For absolute view and relative view, the corresponding view file is a PHP file
  637. * whose name is the same as the view name. The file is located under a specified directory.
  638. * This method will call {@link CApplication::findLocalizedFile} to search for a localized file, if any.
  639. * @param string $viewName the view name
  640. * @param string $viewPath the directory that is used to search for a relative view name
  641. * @param string $basePath the directory that is used to search for an absolute view name under the application
  642. * @param string $moduleViewPath the directory that is used to search for an absolute view name under the current module.
  643. * If this is not set, the application base view path will be used.
  644. * @return mixed the view file path. False if the view file does not exist.
  645. */
  646. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  647. {
  648. if(empty($viewName))
  649. return false;
  650. if($moduleViewPath===null)
  651. $moduleViewPath=$basePath;
  652. if(($renderer=Yii::app()->getViewRenderer())!==null)
  653. $extension=$renderer->fileExtension;
  654. else
  655. $extension='.php';
  656. if($viewName[0]==='/')
  657. {
  658. if(strncmp($viewName,'//',2)===0)
  659. $viewFile=$basePath.$viewName;
  660. else
  661. $viewFile=$moduleViewPath.$viewName;
  662. }
  663. elseif(strpos($viewName,'.'))
  664. $viewFile=Yii::getPathOfAlias($viewName);
  665. else
  666. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  667. if(is_file($viewFile.$extension))
  668. return Yii::app()->findLocalizedFile($viewFile.$extension);
  669. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  670. return Yii::app()->findLocalizedFile($viewFile.'.php');
  671. else
  672. return false;
  673. }
  674. /**
  675. * Returns the list of clips.
  676. * A clip is a named piece of rendering result that can be
  677. * inserted at different places.
  678. * @return CMap the list of clips
  679. * @see CClipWidget
  680. */
  681. public function getClips()
  682. {
  683. if($this->_clips!==null)
  684. return $this->_clips;
  685. else
  686. return $this->_clips=new CMap;
  687. }
  688. /**
  689. * Processes the request using another controller action.
  690. * This is like {@link redirect}, but the user browser's URL remains unchanged.
  691. * In most cases, you should call {@link redirect} instead of this method.
  692. * @param string $route the route of the new controller action. This can be an action ID, or a complete route
  693. * with module ID (optional in the current module), controller ID and action ID. If the former, the action is assumed
  694. * to be located within the current controller.
  695. * @param boolean $exit whether to end the application after this call. Defaults to true.
  696. * @since 1.1.0
  697. */
  698. public function forward($route,$exit=true)
  699. {
  700. if(strpos($route,'/')===false)
  701. $this->run($route);
  702. else
  703. {
  704. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  705. $route=$module->getId().'/'.$route;
  706. Yii::app()->runController($route);
  707. }
  708. if($exit)
  709. Yii::app()->end();
  710. }
  711. /**
  712. * Renders a view with a layout.
  713. *
  714. * This method first calls {@link renderPartial} to render the view (called content view).
  715. * It then renders the layout view which may embed the content view at appropriate place.
  716. * In the layout view, the content view rendering result can be accessed via variable
  717. * <code>$content</code>. At the end, it calls {@link processOutput} to insert scripts
  718. * and dynamic contents if they are available.
  719. *
  720. * By default, the layout view script is "protected/views/layouts/main.php".
  721. * This may be customized by changing {@link layout}.
  722. *
  723. * @param string $view name of the view to be rendered. See {@link getViewFile} for details
  724. * about how the view script is resolved.
  725. * @param array $data data to be extracted into PHP variables and made available to the view script
  726. * @param boolean $return whether the rendering result should be returned instead of being displayed to end users.
  727. * @return string the rendering result. Null if the rendering result is not required.
  728. * @see renderPartial
  729. * @see getLayoutFile
  730. */
  731. public function render($view,$data=null,$return=false)
  732. {
  733. if($this->beforeRender($view))
  734. {
  735. $output=$this->renderPartial($view,$data,true);
  736. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  737. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  738. $this->afterRender($view,$output);
  739. $output=$this->processOutput($output);
  740. if($return)
  741. return $output;
  742. else
  743. echo $output;
  744. }
  745. }
  746. /**
  747. * This method is invoked at the beginning of {@link render()}.
  748. * You may override this method to do some preprocessing when rendering a view.
  749. * @param string $view the view to be rendered
  750. * @return boolean whether the view should be rendered.
  751. * @since 1.1.5
  752. */
  753. protected function beforeRender($view)
  754. {
  755. return true;
  756. }
  757. /**
  758. * This method is invoked after the specified is rendered by calling {@link render()}.
  759. * Note that this method is invoked BEFORE {@link processOutput()}.
  760. * You may override this method to do some postprocessing for the view rendering.
  761. * @param string $view the view that has been rendered
  762. * @param string $output the rendering result of the view. Note that this parameter is passed
  763. * as a reference. That means you can modify it within this method.
  764. * @since 1.1.5
  765. */
  766. protected function afterRender($view, &$output)
  767. {
  768. }
  769. /**
  770. * Renders a static text string.
  771. * The string will be inserted in the current controller layout and returned back.
  772. * @param string $text the static text string
  773. * @param boolean $return whether the rendering result should be returned instead of being displayed to end users.
  774. * @return string the rendering result. Null if the rendering result is not required.
  775. * @see getLayoutFile
  776. */
  777. public function renderText($text,$return=false)
  778. {
  779. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  780. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  781. $text=$this->processOutput($text);
  782. if($return)
  783. return $text;
  784. else
  785. echo $text;
  786. }
  787. /**
  788. * Renders a view.
  789. *
  790. * The named view refers to a PHP script (resolved via {@link getViewFile})
  791. * that is included by this method. If $data is an associative array,
  792. * it will be extracted as PHP variables and made available to the script.
  793. *
  794. * This method differs from {@link render()} in that it does not
  795. * apply a layout to the rendered result. It is thus mostly used
  796. * in rendering a partial view, or an AJAX response.
  797. *
  798. * @param string $view name of the view to be rendered. See {@link getViewFile} for details
  799. * about how the view script is resolved.
  800. * @param array $data data to be extracted into PHP variables and made available to the view script
  801. * @param boolean $return whether the rendering result should be returned instead of being displayed to end users
  802. * @param boolean $processOutput whether the rendering result should be postprocessed using {@link processOutput}.
  803. * @return string the rendering result. Null if the rendering result is not required.
  804. * @throws CException if the view does not exist
  805. * @see getViewFile
  806. * @see processOutput
  807. * @see render
  808. */
  809. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  810. {
  811. if(($viewFile=$this->getViewFile($view))!==false)
  812. {
  813. $output=$this->renderFile($viewFile,$data,true);
  814. if($processOutput)
  815. $output=$this->processOutput($output);
  816. if($return)
  817. return $output;
  818. else
  819. echo $output;
  820. }
  821. else
  822. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  823. array('{controller}'=>get_class($this), '{view}'=>$view)));
  824. }
  825. /**
  826. * Renders a named clip with the supplied parameters.
  827. * This is similar to directly accessing the {@link clips} property.
  828. * The main difference is that it can take an array of named parameters
  829. * which will replace the corresponding placeholders in the clip.
  830. * @param string $name the name of the clip
  831. * @param array $params an array of named parameters (name=>value) that should replace
  832. * their corresponding placeholders in the clip
  833. * @param boolean $return whether to return the clip content or echo it.
  834. * @return mixed either the clip content or null
  835. * @since 1.1.8
  836. */
  837. public function renderClip($name,$params=array(),$return=false)
  838. {
  839. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  840. if($return)
  841. return $text;
  842. else
  843. echo $text;
  844. }
  845. /**
  846. * Renders dynamic content returned by the specified callback.
  847. * This method is used together with {@link COutputCache}. Dynamic contents
  848. * will always show as their latest state even if the content surrounding them is being cached.
  849. * This is especially useful when caching pages that are mostly static but contain some small
  850. * dynamic regions, such as username or current time.
  851. * We can use this method to render these dynamic regions to ensure they are always up-to-date.
  852. *
  853. * The first parameter to this method should be a valid PHP callback, while the rest parameters
  854. * will be passed to the callback.
  855. *
  856. * Note, the callback and its parameter values will be serialized and saved in cache.
  857. * Make sure they are serializable.
  858. *
  859. * @param callback $callback a PHP callback which returns the needed dynamic content.
  860. * When the callback is specified as a string, it will be first assumed to be a method of the current
  861. * controller class. If the method does not exist, it is assumed to be a global PHP function.
  862. * Note, the callback should return the dynamic content instead of echoing it.
  863. */
  864. public function renderDynamic($callback)
  865. {
  866. $n=count($this->_dynamicOutput);
  867. echo "<###dynamic-$n###>";
  868. $params=func_get_args();
  869. array_shift($params);
  870. $this->renderDynamicInternal($callback,$params);
  871. }
  872. /**
  873. * This method is internally used.
  874. * @param callback $callback a PHP callback which returns the needed dynamic content.
  875. * @param array $params parameters passed to the PHP callback
  876. * @see renderDynamic
  877. */
  878. public function renderDynamicInternal($callback,$params)
  879. {
  880. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  881. if(is_string($callback) && method_exists($this,$callback))
  882. $callback=array($this,$callback);
  883. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  884. }
  885. /**
  886. * Creates a relative URL for the specified action defined in this controller.
  887. * @param string $route the URL route. This should be in the format of 'ControllerID/ActionID'.
  888. * If the ControllerID is not present, the current controller ID will be prefixed to the route.
  889. * If the route is empty, it is assumed to be the current action.
  890. * If the controller belongs to a module, the {@link CWebModule::getId module ID}
  891. * will be prefixed to the route. (If you do not want the module ID prefix, the route should start with a slash '/'.)
  892. * @param array $params additional GET parameters (name=>value). Both the name and value will be URL-encoded.
  893. * If the name is '#', the corresponding value will be treated as an anchor
  894. * and will be appended at the end of the URL.
  895. * @param string $ampersand the token separating name-value pairs in the URL.
  896. * @return string the constructed URL
  897. */
  898. public function createUrl($route,$params=array(),$ampersand='&')
  899. {
  900. if($route==='')
  901. $route=$this->getId().'/'.$this->getAction()->getId();
  902. elseif(strpos($route,'/')===false)
  903. $route=$this->getId().'/'.$route;
  904. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  905. $route=$module->getId().'/'.$route;
  906. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  907. }
  908. /**
  909. * Creates an absolute URL for the specified action defined in this controller.
  910. * @param string $route the URL route. This should be in the format of 'ControllerID/ActionID'.
  911. * If the ControllerPath is not present, the current controller ID will be prefixed to the route.
  912. * If the route is empty, it is assumed to be the current action.
  913. * @param array $params additional GET parameters (name=>value). Both the name and value will be URL-encoded.
  914. * @param string $schema schema to use (e.g. http, https). If empty, the schema used for the current request will be used.
  915. * @param string $ampersand the token separating name-value pairs in the URL.
  916. * @return string the constructed URL
  917. */
  918. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  919. {
  920. $url=$this->createUrl($route,$params,$ampersand);
  921. if(strpos($url,'http')===0)
  922. return $url;
  923. else
  924. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  925. }
  926. /**
  927. * @return string the page title. Defaults to the controller name and the action name.
  928. */
  929. public function getPageTitle()
  930. {
  931. if($this->_pageTitle!==null)
  932. return $this->_pageTitle;
  933. else
  934. {
  935. $name=ucfirst(basename($this->getId()));
  936. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  937. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  938. else
  939. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  940. }
  941. }
  942. /**
  943. * @param string $value the page title.
  944. */
  945. public function setPageTitle($value)
  946. {
  947. $this->_pageTitle=$value;
  948. }
  949. /**
  950. * Redirects the browser to the specified URL or route (controller/action).
  951. * @param mixed $url the URL to be redirected to. If the parameter is an array,
  952. * the first element must be a route to a controller action and the rest
  953. * are GET parameters in name-value pairs.
  954. * @param boolean $terminate whether to terminate the current application after calling this method. Defaults to true.
  955. * @param integer $statusCode the HTTP status code. Defaults to 302. See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html}
  956. * for details about HTTP status code.
  957. */
  958. public function redirect($url,$terminate=true,$statusCode=302)
  959. {
  960. if(is_array($url))
  961. {
  962. $route=isset($url[0]) ? $url[0] : '';
  963. $url=$this->createUrl($route,array_splice($url,1));
  964. }
  965. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  966. }
  967. /**
  968. * Refreshes the current page.
  969. * The effect of this method call is the same as user pressing the
  970. * refresh button on the browser (without post data).
  971. * @param boolean $terminate whether to terminate the current application after calling this method
  972. * @param string $anchor the anchor that should be appended to the redirection URL.
  973. * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
  974. */
  975. public function refresh($terminate=true,$anchor='')
  976. {
  977. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  978. }
  979. /**
  980. * Records a method call when an output cache is in effect.
  981. * When the content is served from the output cache, the recorded
  982. * method will be re-invoked.
  983. * @param string $context a property name of the controller. It refers to an object
  984. * whose method is being called. If empty it means the controller itself.
  985. * @param string $method the method name
  986. * @param array $params parameters passed to the method
  987. * @see COutputCache
  988. */
  989. public function recordCachingAction($context,$method,$params)
  990. {
  991. if($this->_cachingStack) // record only when there is an active output cache
  992. {
  993. foreach($this->_cachingStack as $cache)
  994. $cache->recordAction($context,$method,$params);
  995. }
  996. }
  997. /**
  998. * @param boolean $createIfNull whether to create a stack if it does not exist yet. Defaults to true.
  999. * @return CStack stack of {@link COutputCache} objects
  1000. */
  1001. public function getCachingStack($createIfNull=true)
  1002. {
  1003. if(!$this->_cachingStack)
  1004. $this->_cachingStack=new CStack;
  1005. return $this->_cachingStack;
  1006. }
  1007. /**
  1008. * Returns whether the caching stack is empty.
  1009. * @return boolean whether the caching stack is empty. If not empty, it means currently there are
  1010. * some output cache in effect. Note, the return result of this method may change when it is
  1011. * called in different output regions, depending on the partition of output caches.
  1012. */
  1013. public function isCachingStackEmpty()
  1014. {
  1015. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  1016. }
  1017. /**
  1018. * This method is invoked right before an action is to be executed (after all possible filters.)
  1019. * You may override this method to do last-minute preparation for the action.
  1020. * @param CAction $action the action to be executed.
  1021. * @return boolean whether the action should be executed.
  1022. */
  1023. protected function beforeAction($action)
  1024. {
  1025. return true;
  1026. }
  1027. /**
  1028. * This method is invoked right after an action is executed.
  1029. * You may override this method to do some postprocessing for the action.
  1030. * @param CAction $action the action just executed.
  1031. */
  1032. protected function afterAction($action)
  1033. {
  1034. }
  1035. /**
  1036. * The filter method for 'postOnly' filter.
  1037. * This filter throws an exception (CHttpException with code 400) if the applied action is receiving a non-POST request.
  1038. * @param CFilterChain $filterChain the filter chain that the filter is on.
  1039. * @throws CHttpException if the current request is not a POST request
  1040. */
  1041. public function filterPostOnly($filterChain)
  1042. {
  1043. if(Yii::app()->getRequest()->getIsPostRequest())
  1044. $filterChain->run();
  1045. else
  1046. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  1047. }
  1048. /**
  1049. * The filter method for 'ajaxOnly' filter.
  1050. * This filter throws an exception (CHttpException with code 400) if the applied action is receiving a non-AJAX request.
  1051. * @param CFilterChain $filterChain the filter chain that the filter is on.
  1052. * @throws CHttpException if the current request is not an AJAX request.
  1053. */
  1054. public function filterAjaxOnly($filterChain)
  1055. {
  1056. if(Yii::app()->getRequest()->getIsAjaxRequest())
  1057. $filterChain->run();
  1058. else
  1059. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  1060. }
  1061. /**
  1062. * The filter method for 'accessControl' filter.
  1063. * This filter is a wrapper of {@link CAccessControlFilter}.
  1064. * To use this filter, you must override {@link accessRules} method.
  1065. * @param CFilterChain $filterChain the filter chain that the filter is on.
  1066. */
  1067. public function filterAccessControl($filterChain)
  1068. {
  1069. $filter=new CAccessControlFilter;
  1070. $filter->setRules($this->accessRules());
  1071. $filter->filter($filterChain);
  1072. }
  1073. /**
  1074. * Returns a persistent page state value.
  1075. * A page state is a variable that is persistent across POST requests of the same page.
  1076. * In order to use persistent page states, the form(s) must be stateful
  1077. * which are generated using {@link CHtml::statefulForm}.
  1078. * @param string $name the state name
  1079. * @param mixed $defaultValue the value to be returned if the named state is not found
  1080. * @return mixed the page state value
  1081. * @see setPageState
  1082. * @see CHtml::statefulForm
  1083. */
  1084. public function getPageState($name,$defaultValue=null)
  1085. {
  1086. if($this->_pageStates===null)
  1087. $this->_pageStates=$this->loadPageStates();
  1088. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  1089. }
  1090. /**
  1091. * Saves a persistent page state value.
  1092. * A page state is a variable that is persistent across POST requests of the same page.
  1093. * In order to use persistent page states, the form(s) must be stateful
  1094. * which are generated using {@link CHtml::statefulForm}.
  1095. * @param string $name the state name
  1096. * @param mixed $value the page state value
  1097. * @param mixed $defaultValue the default page state value. If this is the same as
  1098. * the given value, the state will be removed from persistent storage.
  1099. * @see getPageState
  1100. * @see CHtml::statefulForm
  1101. */
  1102. public function setPageState($name,$value,$defaultValue=null)
  1103. {
  1104. if($this->_pageStates===null)
  1105. $this->_pageStates=$this->loadPageStates();
  1106. if($value===$defaultValue)
  1107. unset($this->_pageStates[$name]);
  1108. else
  1109. $this->_pageStates[$name]=$value;
  1110. $params=func_get_args();
  1111. $this->recordCachingAction('','setPageState',$params);
  1112. }
  1113. /**
  1114. * Removes all page states.
  1115. */
  1116. public function clearPageStates()
  1117. {
  1118. $this->_pageStates=array();
  1119. }
  1120. /**
  1121. * Loads page states from a hidden input.
  1122. * @return array the loaded page states
  1123. */
  1124. protected function loadPageStates()
  1125. {
  1126. if(!empty($_POST[self::STATE_INPUT_NAME]))
  1127. {
  1128. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  1129. {
  1130. if(extension_loaded('zlib'))
  1131. $data=@gzuncompress($data);
  1132. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  1133. return unserialize($data);
  1134. }
  1135. }
  1136. return array();
  1137. }
  1138. /**
  1139. * Saves page states as a base64 string.
  1140. * @param array $states the states to be saved.
  1141. * @param string $output the output to be modified. Note, this is passed by reference.
  1142. */
  1143. protected function savePageStates($states,&$output)
  1144. {
  1145. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  1146. if(extension_loaded('zlib'))
  1147. $data=gzcompress($data);
  1148. $value=base64_encode($data);
  1149. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  1150. }
  1151. }