Controller.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 0.2.9
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Controller;
  16. use Cake\Controller\Exception\MissingActionException;
  17. use Cake\Datasource\ModelAwareTrait;
  18. use Cake\Event\Event;
  19. use Cake\Event\EventListenerInterface;
  20. use Cake\Event\EventManagerTrait;
  21. use Cake\Log\LogTrait;
  22. use Cake\Network\Request;
  23. use Cake\Network\Response;
  24. use Cake\Routing\RequestActionTrait;
  25. use Cake\Routing\Router;
  26. use Cake\Utility\MergeVariablesTrait;
  27. use Cake\View\ViewVarsTrait;
  28. use LogicException;
  29. use ReflectionException;
  30. use ReflectionMethod;
  31. use RuntimeException;
  32. /**
  33. * Application controller class for organization of business logic.
  34. * Provides basic functionality, such as rendering views inside layouts,
  35. * automatic model availability, redirection, callbacks, and more.
  36. *
  37. * Controllers should provide a number of 'action' methods. These are public
  38. * methods on a controller that are not inherited from `Controller`.
  39. * Each action serves as an endpoint for performing a specific action on a
  40. * resource or collection of resources. For example adding or editing a new
  41. * object, or listing a set of objects.
  42. *
  43. * You can access request parameters, using `$this->request`. The request object
  44. * contains all the POST, GET and FILES that were part of the request.
  45. *
  46. * After performing the required action, controllers are responsible for
  47. * creating a response. This usually takes the form of a generated `View`, or
  48. * possibly a redirection to another URL. In either case `$this->response`
  49. * allows you to manipulate all aspects of the response.
  50. *
  51. * Controllers are created by `Dispatcher` based on request parameters and
  52. * routing. By default controllers and actions use conventional names.
  53. * For example `/posts/index` maps to `PostsController::index()`. You can re-map
  54. * URLs using Router::connect() or RouterBuilder::connect().
  55. *
  56. * ### Life cycle callbacks
  57. *
  58. * CakePHP fires a number of life cycle callbacks during each request.
  59. * By implementing a method you can receive the related events. The available
  60. * callbacks are:
  61. *
  62. * - `beforeFilter(Event $event)`
  63. * Called before each action. This is a good place to do general logic that
  64. * applies to all actions.
  65. * - `beforeRender(Event $event)`
  66. * Called before the view is rendered.
  67. * - `beforeRedirect(Event $event, $url, Response $response)`
  68. * Called before a redirect is done.
  69. * - `afterFilter(Event $event)`
  70. * Called after each action is complete and after the view is rendered.
  71. *
  72. * @property \Cake\Controller\Component\AuthComponent $Auth
  73. * @property \Cake\Controller\Component\CookieComponent $Cookie
  74. * @property \Cake\Controller\Component\CsrfComponent $Csrf
  75. * @property \Cake\Controller\Component\FlashComponent $Flash
  76. * @property \Cake\Controller\Component\PaginatorComponent $Paginator
  77. * @property \Cake\Controller\Component\RequestHandlerComponent $RequestHandler
  78. * @property \Cake\Controller\Component\SecurityComponent $Security
  79. * @link http://book.cakephp.org/3.0/en/controllers.html
  80. */
  81. class Controller implements EventListenerInterface
  82. {
  83. use EventManagerTrait;
  84. use LogTrait;
  85. use MergeVariablesTrait;
  86. use ModelAwareTrait;
  87. use RequestActionTrait;
  88. use ViewVarsTrait;
  89. /**
  90. * The name of this controller. Controller names are plural, named after the model they manipulate.
  91. *
  92. * Set automatically using conventions in Controller::__construct().
  93. *
  94. * @var string
  95. */
  96. public $name = null;
  97. /**
  98. * An array containing the names of helpers this controller uses. The array elements should
  99. * not contain the "Helper" part of the class name.
  100. *
  101. * Example: `public $helpers = ['Form', 'Html', 'Time'];`
  102. *
  103. * @var mixed
  104. * @link http://book.cakephp.org/3.0/en/controllers.html#configuring-helpers-to-load
  105. */
  106. public $helpers = [];
  107. /**
  108. * An instance of a Cake\Network\Request object that contains information about the current request.
  109. * This object contains all the information about a request and several methods for reading
  110. * additional information about the request.
  111. *
  112. * @var \Cake\Network\Request
  113. * @link http://book.cakephp.org/3.0/en/controllers/request-response.html#request
  114. */
  115. public $request;
  116. /**
  117. * An instance of a Response object that contains information about the impending response
  118. *
  119. * @var \Cake\Network\Response
  120. * @link http://book.cakephp.org/3.0/en/controllers/request-response.html#response
  121. */
  122. public $response;
  123. /**
  124. * The class name to use for creating the response object.
  125. *
  126. * @var string
  127. */
  128. protected $_responseClass = 'Cake\Network\Response';
  129. /**
  130. * Settings for pagination.
  131. *
  132. * Used to pre-configure pagination preferences for the various
  133. * tables your controller will be paginating.
  134. *
  135. * @var array
  136. * @see \Cake\Controller\Component\PaginatorComponent
  137. */
  138. public $paginate = [];
  139. /**
  140. * Set to true to automatically render the view
  141. * after action logic.
  142. *
  143. * @var bool
  144. */
  145. public $autoRender = true;
  146. /**
  147. * Instance of ComponentRegistry used to create Components
  148. *
  149. * @var \Cake\Controller\ComponentRegistry
  150. */
  151. protected $_components = null;
  152. /**
  153. * Array containing the names of components this controller uses. Component names
  154. * should not contain the "Component" portion of the class name.
  155. *
  156. * Example: `public $components = ['Session', 'RequestHandler', 'Acl'];`
  157. *
  158. * @var array
  159. * @link http://book.cakephp.org/3.0/en/controllers/components.html
  160. */
  161. public $components = [];
  162. /**
  163. * The name of the View class this controller sends output to.
  164. *
  165. * @var string
  166. */
  167. public $viewClass = null;
  168. /**
  169. * The path to this controllers view templates.
  170. * Example `Articles`
  171. *
  172. * Set automatically using conventions in Controller::__construct().
  173. *
  174. * @var string
  175. */
  176. public $viewPath;
  177. /**
  178. * The name of the view file to render. The name specified
  179. * is the filename in /app/Template/<SubFolder> without the .ctp extension.
  180. *
  181. * @var string
  182. */
  183. public $view = null;
  184. /**
  185. * Instance of the View created during rendering. Won't be set until after
  186. * Controller::render() is called.
  187. *
  188. * @var \Cake\View\View
  189. */
  190. public $View;
  191. /**
  192. * These Controller properties will be passed from the Controller to the View as options.
  193. *
  194. * @var array
  195. * @see \Cake\View\View
  196. */
  197. protected $_validViewOptions = [
  198. 'viewVars', 'autoLayout', 'helpers', 'view', 'layout', 'name', 'theme', 'layoutPath',
  199. 'viewPath', 'plugin', 'passedArgs'
  200. ];
  201. /**
  202. * Automatically set to the name of a plugin.
  203. *
  204. * @var string
  205. */
  206. public $plugin = null;
  207. /**
  208. * Holds all passed params.
  209. *
  210. * @var mixed
  211. */
  212. public $passedArgs = [];
  213. /**
  214. * Constructor.
  215. *
  216. * Sets a number of properties based on conventions if they are empty. To override the
  217. * conventions CakePHP uses you can define properties in your class declaration.
  218. *
  219. * @param \Cake\Network\Request|null $request Request object for this controller. Can be null for testing,
  220. * but expect that features that use the request parameters will not work.
  221. * @param \Cake\Network\Response|null $response Response object for this controller.
  222. * @param string|null $name Override the name useful in testing when using mocks.
  223. * @param \Cake\Event\EventManager|null $eventManager The event manager. Defaults to a new instance.
  224. */
  225. public function __construct(Request $request = null, Response $response = null, $name = null, $eventManager = null)
  226. {
  227. if ($this->name === null && $name === null) {
  228. list(, $name) = namespaceSplit(get_class($this));
  229. $name = substr($name, 0, -10);
  230. }
  231. if ($name !== null) {
  232. $this->name = $name;
  233. }
  234. if (!$this->viewPath) {
  235. $viewPath = $this->name;
  236. if (isset($request->params['prefix'])) {
  237. $prefixes = array_map(
  238. 'Cake\Utility\Inflector::camelize',
  239. explode('/', $request->params['prefix'])
  240. );
  241. $viewPath = implode(DS, $prefixes) . DS . $viewPath;
  242. }
  243. $this->viewPath = $viewPath;
  244. }
  245. if (!($request instanceof Request)) {
  246. $request = new Request();
  247. }
  248. $this->setRequest($request);
  249. if (!($response instanceof Response)) {
  250. $response = new Response();
  251. }
  252. $this->response = $response;
  253. if ($eventManager) {
  254. $this->eventManager($eventManager);
  255. }
  256. $this->modelFactory('Table', ['Cake\ORM\TableRegistry', 'get']);
  257. $modelClass = ($this->plugin ? $this->plugin . '.' : '') . $this->name;
  258. $this->_setModelClass($modelClass);
  259. $this->initialize();
  260. $this->_mergeControllerVars();
  261. $this->_loadComponents();
  262. $this->eventManager()->on($this);
  263. }
  264. /**
  265. * Initialization hook method.
  266. *
  267. * Implement this method to avoid having to overwrite
  268. * the constructor and call parent.
  269. *
  270. * @return void
  271. */
  272. public function initialize()
  273. {
  274. }
  275. /**
  276. * Get the component registry for this controller.
  277. *
  278. * @return \Cake\Controller\ComponentRegistry
  279. */
  280. public function components()
  281. {
  282. if ($this->_components === null) {
  283. $this->_components = new ComponentRegistry($this);
  284. }
  285. return $this->_components;
  286. }
  287. /**
  288. * Add a component to the controller's registry.
  289. *
  290. * This method will also set the component to a property.
  291. * For example:
  292. *
  293. * `$this->loadComponent('Acl.Acl');`
  294. *
  295. * Will result in a `Toolbar` property being set.
  296. *
  297. * @param string $name The name of the component to load.
  298. * @param array $config The config for the component.
  299. * @return \Cake\Controller\Component
  300. */
  301. public function loadComponent($name, array $config = [])
  302. {
  303. list(, $prop) = pluginSplit($name);
  304. $this->{$prop} = $this->components()->load($name, $config);
  305. return $this->{$prop};
  306. }
  307. /**
  308. * Magic accessor for model autoloading.
  309. *
  310. * @param string $name Property name
  311. * @return bool|object The model instance or false
  312. */
  313. public function __get($name)
  314. {
  315. list($plugin, $class) = pluginSplit($this->modelClass, true);
  316. if ($class !== $name) {
  317. return false;
  318. }
  319. return $this->loadModel($plugin . $class);
  320. }
  321. /**
  322. * Sets the request objects and configures a number of controller properties
  323. * based on the contents of the request. Controller acts as a proxy for certain View variables
  324. * which must also be updated here. The properties that get set are:
  325. *
  326. * - $this->request - To the $request parameter
  327. * - $this->plugin - To the $request->params['plugin']
  328. * - $this->autoRender - To false if $request->params['return'] == 1
  329. * - $this->passedArgs - The combined results of params['named'] and params['pass]
  330. * - View::$passedArgs - $this->passedArgs
  331. * - View::$plugin - $this->plugin
  332. * - View::$view - To the $request->params['action']
  333. * - View::$autoLayout - To the false if $request->params['bare']; is set.
  334. *
  335. * @param \Cake\Network\Request $request Request instance.
  336. * @return void
  337. */
  338. public function setRequest(Request $request)
  339. {
  340. $this->request = $request;
  341. $this->plugin = isset($request->params['plugin']) ? $request->params['plugin'] : null;
  342. $this->view = isset($request->params['action']) ? $request->params['action'] : null;
  343. if (isset($request->params['pass'])) {
  344. $this->passedArgs = $request->params['pass'];
  345. }
  346. }
  347. /**
  348. * Dispatches the controller action. Checks that the action
  349. * exists and isn't private.
  350. *
  351. * @return mixed The resulting response.
  352. * @throws \LogicException When request is not set.
  353. * @throws \Cake\Controller\Exception\MissingActionException When actions are not defined or inaccessible.
  354. */
  355. public function invokeAction()
  356. {
  357. $request = $this->request;
  358. if (!isset($request)) {
  359. throw new LogicException('No Request object configured. Cannot invoke action');
  360. }
  361. if (!$this->isAction($request->params['action'])) {
  362. throw new MissingActionException([
  363. 'controller' => $this->name . "Controller",
  364. 'action' => $request->params['action'],
  365. 'prefix' => isset($request->params['prefix']) ? $request->params['prefix'] : '',
  366. 'plugin' => $request->params['plugin'],
  367. ]);
  368. }
  369. $callable = [$this, $request->params['action']];
  370. return call_user_func_array($callable, $request->params['pass']);
  371. }
  372. /**
  373. * Merge components, helpers vars from
  374. * parent classes.
  375. *
  376. * @return void
  377. */
  378. protected function _mergeControllerVars()
  379. {
  380. $this->_mergeVars(
  381. ['components', 'helpers'],
  382. ['associative' => ['components', 'helpers']]
  383. );
  384. }
  385. /**
  386. * Returns a list of all events that will fire in the controller during its lifecycle.
  387. * You can override this function to add you own listener callbacks
  388. *
  389. * @return array
  390. */
  391. public function implementedEvents()
  392. {
  393. return [
  394. 'Controller.initialize' => 'beforeFilter',
  395. 'Controller.beforeRender' => 'beforeRender',
  396. 'Controller.beforeRedirect' => 'beforeRedirect',
  397. 'Controller.shutdown' => 'afterFilter',
  398. ];
  399. }
  400. /**
  401. * Loads the defined components using the Component factory.
  402. *
  403. * @return void
  404. */
  405. protected function _loadComponents()
  406. {
  407. if (empty($this->components)) {
  408. return;
  409. }
  410. $registry = $this->components();
  411. $components = $registry->normalizeArray($this->components);
  412. foreach ($components as $properties) {
  413. $this->loadComponent($properties['class'], $properties['config']);
  414. }
  415. }
  416. /**
  417. * Perform the startup process for this controller.
  418. * Fire the Components and Controller callbacks in the correct order.
  419. *
  420. * - Initializes components, which fires their `initialize` callback
  421. * - Calls the controller `beforeFilter`.
  422. * - triggers Component `startup` methods.
  423. *
  424. * @return void|\Cake\Network\Response
  425. */
  426. public function startupProcess()
  427. {
  428. $event = $this->dispatchEvent('Controller.initialize');
  429. if ($event->result instanceof Response) {
  430. return $event->result;
  431. }
  432. $event = $this->dispatchEvent('Controller.startup');
  433. if ($event->result instanceof Response) {
  434. return $event->result;
  435. }
  436. }
  437. /**
  438. * Perform the various shutdown processes for this controller.
  439. * Fire the Components and Controller callbacks in the correct order.
  440. *
  441. * - triggers the component `shutdown` callback.
  442. * - calls the Controller's `afterFilter` method.
  443. *
  444. * @return void|\Cake\Network\Response
  445. */
  446. public function shutdownProcess()
  447. {
  448. $event = $this->dispatchEvent('Controller.shutdown');
  449. if ($event->result instanceof Response) {
  450. return $event->result;
  451. }
  452. }
  453. /**
  454. * Redirects to given $url, after turning off $this->autoRender.
  455. * Script execution is halted after the redirect.
  456. *
  457. * @param string|array $url A string or array-based URL pointing to another location within the app,
  458. * or an absolute URL
  459. * @param int $status HTTP status code (eg: 301)
  460. * @return void|\Cake\Network\Response
  461. * @link http://book.cakephp.org/3.0/en/controllers.html#Controller::redirect
  462. */
  463. public function redirect($url, $status = 302)
  464. {
  465. $this->autoRender = false;
  466. $response = $this->response;
  467. if ($status) {
  468. $response->statusCode($status);
  469. }
  470. $event = $this->dispatchEvent('Controller.beforeRedirect', [$url, $response]);
  471. if ($event->result instanceof Response) {
  472. return $event->result;
  473. }
  474. if ($event->isStopped()) {
  475. return;
  476. }
  477. if ($url !== null && !$response->location()) {
  478. $response->location(Router::url($url, true));
  479. }
  480. return $response;
  481. }
  482. /**
  483. * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
  484. *
  485. * Examples:
  486. *
  487. * ```
  488. * setAction('another_action');
  489. * setAction('action_with_parameters', $parameter1);
  490. * ```
  491. *
  492. * @param string $action The new action to be 'redirected' to.
  493. * Any other parameters passed to this method will be passed as parameters to the new action.
  494. * @return mixed Returns the return value of the called action
  495. */
  496. public function setAction($action)
  497. {
  498. $this->request->params['action'] = $action;
  499. $this->view = $action;
  500. $args = func_get_args();
  501. unset($args[0]);
  502. return call_user_func_array([&$this, $action], $args);
  503. }
  504. /**
  505. * Instantiates the correct view class, hands it its data, and uses it to render the view output.
  506. *
  507. * @param string $view View to use for rendering
  508. * @param string $layout Layout to use
  509. * @return \Cake\Network\Response A response object containing the rendered view.
  510. * @link http://book.cakephp.org/3.0/en/controllers.html#rendering-a-view
  511. */
  512. public function render($view = null, $layout = null)
  513. {
  514. if (!empty($this->request->params['bare'])) {
  515. $this->getView()->autoLayout = false;
  516. }
  517. $event = $this->dispatchEvent('Controller.beforeRender');
  518. if ($event->result instanceof Response) {
  519. $this->autoRender = false;
  520. return $event->result;
  521. }
  522. if ($event->isStopped()) {
  523. $this->autoRender = false;
  524. return $this->response;
  525. }
  526. $this->autoRender = false;
  527. $this->response->body($this->getView()->render($view, $layout));
  528. return $this->response;
  529. }
  530. /**
  531. * Returns the referring URL for this request.
  532. *
  533. * @param string|null $default Default URL to use if HTTP_REFERER cannot be read from headers
  534. * @param bool $local If true, restrict referring URLs to local server
  535. * @return string Referring URL
  536. */
  537. public function referer($default = null, $local = false)
  538. {
  539. if (!$this->request) {
  540. return Router::url($default, !$local);
  541. }
  542. $referer = $this->request->referer($local);
  543. if ($referer === '/' && $default && $default !== $referer) {
  544. return Router::url($default, !$local);
  545. }
  546. return $referer;
  547. }
  548. /**
  549. * Handles pagination of records in Table objects.
  550. *
  551. * Will load the referenced Table object, and have the PaginatorComponent
  552. * paginate the query using the request date and settings defined in `$this->paginate`.
  553. *
  554. * This method will also make the PaginatorHelper available in the view.
  555. *
  556. * @param \Cake\ORM\Table|string|\Cake\ORM\Query|null $object Table to paginate
  557. * (e.g: Table instance, 'TableName' or a Query object)
  558. * @return \Cake\ORM\ResultSet Query results
  559. * @link http://book.cakephp.org/3.0/en/controllers.html#Controller::paginate
  560. * @throws \RuntimeException When no compatible table object can be found.
  561. */
  562. public function paginate($object = null)
  563. {
  564. if (is_object($object)) {
  565. $table = $object;
  566. }
  567. if (is_string($object) || $object === null) {
  568. $try = [$object, $this->modelClass];
  569. foreach ($try as $tableName) {
  570. if (empty($tableName)) {
  571. continue;
  572. }
  573. $table = $this->loadModel($tableName);
  574. break;
  575. }
  576. }
  577. $this->loadComponent('Paginator');
  578. if (empty($table)) {
  579. throw new RuntimeException('Unable to locate an object compatible with paginate.');
  580. }
  581. return $this->Paginator->paginate($table, $this->paginate);
  582. }
  583. /**
  584. * Method to check that an action is accessible from a URL.
  585. *
  586. * Override this method to change which controller methods can be reached.
  587. * The default implementation disallows access to all methods defined on Cake\Controller\Controller,
  588. * and allows all public methods on all subclasses of this class.
  589. *
  590. * @param string $action The action to check.
  591. * @return bool Whether or not the method is accessible from a URL.
  592. */
  593. public function isAction($action)
  594. {
  595. try {
  596. $method = new ReflectionMethod($this, $action);
  597. } catch (ReflectionException $e) {
  598. return false;
  599. }
  600. if (!$method->isPublic()) {
  601. return false;
  602. }
  603. if ($method->getDeclaringClass()->name === 'Cake\Controller\Controller') {
  604. return false;
  605. }
  606. return true;
  607. }
  608. /**
  609. * Called before the controller action. You can use this method to configure and customize components
  610. * or perform logic that needs to happen before each controller action.
  611. *
  612. * @param Event $event An Event instance
  613. * @return void
  614. * @link http://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks
  615. */
  616. public function beforeFilter(Event $event)
  617. {
  618. }
  619. /**
  620. * Called after the controller action is run, but before the view is rendered. You can use this method
  621. * to perform logic or set view variables that are required on every request.
  622. *
  623. * @param Event $event An Event instance
  624. * @return void
  625. * @link http://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks
  626. */
  627. public function beforeRender(Event $event)
  628. {
  629. }
  630. /**
  631. * The beforeRedirect method is invoked when the controller's redirect method is called but before any
  632. * further action.
  633. *
  634. * If the event is stopped the controller will not continue on to redirect the request.
  635. * The $url and $status variables have same meaning as for the controller's method.
  636. * You can set the event result to response instance or modify the redirect location
  637. * using controller's response instance.
  638. *
  639. * @param Event $event An Event instance
  640. * @param string|array $url A string or array-based URL pointing to another location within the app,
  641. * or an absolute URL
  642. * @param \Cake\Network\Response $response The response object.
  643. * @return void
  644. * @link http://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks
  645. */
  646. public function beforeRedirect(Event $event, $url, Response $response)
  647. {
  648. }
  649. /**
  650. * Called after the controller action is run and rendered.
  651. *
  652. * @param Event $event An Event instance
  653. * @return void
  654. * @link http://book.cakephp.org/3.0/en/controllers.html#request-life-cycle-callbacks
  655. */
  656. public function afterFilter(Event $event)
  657. {
  658. }
  659. }