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: * @package Cake.Controller
13: * @since CakePHP(tm) v 0.2.9
14: * @license http://www.opensource.org/licenses/mit-license.php MIT License
15: */
16:
17: App::uses('CakeResponse', 'Network');
18: App::uses('ClassRegistry', 'Utility');
19: App::uses('ComponentCollection', 'Controller');
20: App::uses('View', 'View');
21: App::uses('CakeEvent', 'Event');
22: App::uses('CakeEventListener', 'Event');
23: App::uses('CakeEventManager', 'Event');
24:
25: /**
26: * Application controller class for organization of business logic.
27: * Provides basic functionality, such as rendering views inside layouts,
28: * automatic model availability, redirection, callbacks, and more.
29: *
30: * Controllers should provide a number of 'action' methods. These are public methods on the controller
31: * that are not prefixed with a '_' and not part of Controller. Each action serves as an endpoint for
32: * performing a specific action on a resource or collection of resources. For example: adding or editing a new
33: * object, or listing a set of objects.
34: *
35: * You can access request parameters, using `$this->request`. The request object contains all the POST, GET and FILES
36: * that were part of the request.
37: *
38: * After performing the required actions, controllers are responsible for creating a response. This usually
39: * takes the form of a generated View, or possibly a redirection to another controller action. In either case
40: * `$this->response` allows you to manipulate all aspects of the response.
41: *
42: * Controllers are created by Dispatcher based on request parameters and routing. By default controllers and actions
43: * use conventional names. For example `/posts/index` maps to `PostsController::index()`. You can re-map URLs
44: * using Router::connect().
45: *
46: * @package Cake.Controller
47: * @property AclComponent $Acl
48: * @property AuthComponent $Auth
49: * @property CookieComponent $Cookie
50: * @property EmailComponent $Email
51: * @property PaginatorComponent $Paginator
52: * @property RequestHandlerComponent $RequestHandler
53: * @property SecurityComponent $Security
54: * @property SessionComponent $Session
55: * @link http://book.cakephp.org/2.0/en/controllers.html
56: */
57: class Controller extends Object implements CakeEventListener {
58:
59: /**
60: * The name of this controller. Controller names are plural, named after the model they manipulate.
61: *
62: * @var string
63: * @link http://book.cakephp.org/2.0/en/controllers.html#controller-attributes
64: */
65: public $name = null;
66:
67: /**
68: * An array containing the class names of models this controller uses.
69: *
70: * Example: `public $uses = array('Product', 'Post', 'Comment');`
71: *
72: * Can be set to several values to express different options:
73: *
74: * - `true` Use the default inflected model name.
75: * - `array()` Use only models defined in the parent class.
76: * - `false` Use no models at all, do not merge with parent class either.
77: * - `array('Post', 'Comment')` Use only the Post and Comment models. Models
78: * Will also be merged with the parent class.
79: *
80: * The default value is `true`.
81: *
82: * @var mixed
83: * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses
84: */
85: public $uses = true;
86:
87: /**
88: * An array containing the names of helpers this controller uses. The array elements should
89: * not contain the "Helper" part of the class name.
90: *
91: * Example: `public $helpers = array('Html', 'Js', 'Time', 'Ajax');`
92: *
93: * @var mixed
94: * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses
95: */
96: public $helpers = array();
97:
98: /**
99: * An instance of a CakeRequest object that contains information about the current request.
100: * This object contains all the information about a request and several methods for reading
101: * additional information about the request.
102: *
103: * @var CakeRequest
104: * @link http://book.cakephp.org/2.0/en/controllers/request-response.html#cakerequest
105: */
106: public $request;
107:
108: /**
109: * An instance of a CakeResponse object that contains information about the impending response
110: *
111: * @var CakeResponse
112: * @link http://book.cakephp.org/2.0/en/controllers/request-response.html#cakeresponse
113: */
114: public $response;
115:
116: /**
117: * The class name to use for creating the response object.
118: *
119: * @var string
120: */
121: protected $_responseClass = 'CakeResponse';
122:
123: /**
124: * The name of the views subfolder containing views for this controller.
125: *
126: * @var string
127: */
128: public $viewPath = null;
129:
130: /**
131: * The name of the layouts subfolder containing layouts for this controller.
132: *
133: * @var string
134: */
135: public $layoutPath = null;
136:
137: /**
138: * Contains variables to be handed to the view.
139: *
140: * @var array
141: */
142: public $viewVars = array();
143:
144: /**
145: * The name of the view file to render. The name specified
146: * is the filename in /app/View/<SubFolder> without the .ctp extension.
147: *
148: * @var string
149: */
150: public $view = null;
151:
152: /**
153: * The name of the layout file to render the view inside of. The name specified
154: * is the filename of the layout in /app/View/Layouts without the .ctp
155: * extension.
156: *
157: * @var string
158: */
159: public $layout = 'default';
160:
161: /**
162: * Set to true to automatically render the view
163: * after action logic.
164: *
165: * @var bool
166: */
167: public $autoRender = true;
168:
169: /**
170: * Set to true to automatically render the layout around views.
171: *
172: * @var bool
173: */
174: public $autoLayout = true;
175:
176: /**
177: * Instance of ComponentCollection used to handle callbacks.
178: *
179: * @var ComponentCollection
180: */
181: public $Components = null;
182:
183: /**
184: * Array containing the names of components this controller uses. Component names
185: * should not contain the "Component" portion of the class name.
186: *
187: * Example: `public $components = array('Session', 'RequestHandler', 'Acl');`
188: *
189: * @var array
190: * @link http://book.cakephp.org/2.0/en/controllers/components.html
191: */
192: public $components = array('Session');
193:
194: /**
195: * The name of the View class this controller sends output to.
196: *
197: * @var string
198: */
199: public $viewClass = 'View';
200:
201: /**
202: * Instance of the View created during rendering. Won't be set until after
203: * Controller::render() is called.
204: *
205: * @var View
206: */
207: public $View;
208:
209: /**
210: * File extension for view templates. Defaults to CakePHP's conventional ".ctp".
211: *
212: * @var string
213: */
214: public $ext = '.ctp';
215:
216: /**
217: * Automatically set to the name of a plugin.
218: *
219: * @var string
220: */
221: public $plugin = null;
222:
223: /**
224: * Used to define methods a controller that will be cached. To cache a
225: * single action, the value is set to an array containing keys that match
226: * action names and values that denote cache expiration times (in seconds).
227: *
228: * Example:
229: *
230: * {{{
231: * public $cacheAction = array(
232: * 'view/23/' => 21600,
233: * 'recalled/' => 86400
234: * );
235: * }}}
236: *
237: * $cacheAction can also be set to a strtotime() compatible string. This
238: * marks all the actions in the controller for view caching.
239: *
240: * @var mixed
241: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html#additional-configuration-options
242: */
243: public $cacheAction = false;
244:
245: /**
246: * Holds all params passed and named.
247: *
248: * @var mixed
249: */
250: public $passedArgs = array();
251:
252: /**
253: * Triggers Scaffolding
254: *
255: * @var mixed
256: * @link http://book.cakephp.org/2.0/en/controllers/scaffolding.html
257: */
258: public $scaffold = false;
259:
260: /**
261: * Holds current methods of the controller. This is a list of all the methods reachable
262: * via URL. Modifying this array will allow you to change which methods can be reached.
263: *
264: * @var array
265: */
266: public $methods = array();
267:
268: /**
269: * This controller's primary model class name, the Inflector::singularize()'ed version of
270: * the controller's $name property.
271: *
272: * Example: For a controller named 'Comments', the modelClass would be 'Comment'
273: *
274: * @var string
275: */
276: public $modelClass = null;
277:
278: /**
279: * This controller's model key name, an underscored version of the controller's $modelClass property.
280: *
281: * Example: For a controller named 'ArticleComments', the modelKey would be 'article_comment'
282: *
283: * @var string
284: */
285: public $modelKey = null;
286:
287: /**
288: * Holds any validation errors produced by the last call of the validateErrors() method.
289: *
290: * @var array
291: */
292: public $validationErrors = null;
293:
294: /**
295: * The class name of the parent class you wish to merge with.
296: * Typically this is AppController, but you may wish to merge vars with a different
297: * parent class.
298: *
299: * @var string
300: */
301: protected $_mergeParent = 'AppController';
302:
303: /**
304: * Instance of the CakeEventManager this controller is using
305: * to dispatch inner events.
306: *
307: * @var CakeEventManager
308: */
309: protected $_eventManager = null;
310:
311: /**
312: * Constructor.
313: *
314: * @param CakeRequest $request Request object for this controller. Can be null for testing,
315: * but expect that features that use the request parameters will not work.
316: * @param CakeResponse $response Response object for this controller.
317: */
318: public function __construct($request = null, $response = null) {
319: if ($this->name === null) {
320: $this->name = substr(get_class($this), 0, -10);
321: }
322:
323: if (!$this->viewPath) {
324: $this->viewPath = $this->name;
325: }
326:
327: $this->modelClass = Inflector::singularize($this->name);
328: $this->modelKey = Inflector::underscore($this->modelClass);
329: $this->Components = new ComponentCollection();
330:
331: $childMethods = get_class_methods($this);
332: $parentMethods = get_class_methods('Controller');
333:
334: $this->methods = array_diff($childMethods, $parentMethods);
335:
336: if ($request instanceof CakeRequest) {
337: $this->setRequest($request);
338: }
339: if ($response instanceof CakeResponse) {
340: $this->response = $response;
341: }
342: parent::__construct();
343: }
344:
345: /**
346: * Provides backwards compatibility to avoid problems with empty and isset to alias properties.
347: * Lazy loads models using the loadModel() method if declared in $uses
348: *
349: * @param string $name Property name to check.
350: * @return bool
351: */
352: public function __isset($name) {
353: switch ($name) {
354: case 'base':
355: case 'here':
356: case 'webroot':
357: case 'data':
358: case 'action':
359: case 'params':
360: return true;
361: }
362:
363: if (is_array($this->uses)) {
364: foreach ($this->uses as $modelClass) {
365: list($plugin, $class) = pluginSplit($modelClass, true);
366: if ($name === $class) {
367: return $this->loadModel($modelClass);
368: }
369: }
370: }
371:
372: if ($name === $this->modelClass) {
373: list($plugin, $class) = pluginSplit($name, true);
374: if (!$plugin) {
375: $plugin = $this->plugin ? $this->plugin . '.' : null;
376: }
377: return $this->loadModel($plugin . $this->modelClass);
378: }
379:
380: return false;
381: }
382:
383: /**
384: * Provides backwards compatibility access to the request object properties.
385: * Also provides the params alias.
386: *
387: * @param string $name The name of the requested value
388: * @return mixed The requested value for valid variables/aliases else null
389: */
390: public function __get($name) {
391: switch ($name) {
392: case 'base':
393: case 'here':
394: case 'webroot':
395: case 'data':
396: return $this->request->{$name};
397: case 'action':
398: return isset($this->request->params['action']) ? $this->request->params['action'] : '';
399: case 'params':
400: return $this->request;
401: case 'paginate':
402: return $this->Components->load('Paginator')->settings;
403: }
404:
405: if (isset($this->{$name})) {
406: return $this->{$name};
407: }
408:
409: return null;
410: }
411:
412: /**
413: * Provides backwards compatibility access for setting values to the request object.
414: *
415: * @param string $name Property name to set.
416: * @param mixed $value Value to set.
417: * @return void
418: */
419: public function __set($name, $value) {
420: switch ($name) {
421: case 'base':
422: case 'here':
423: case 'webroot':
424: case 'data':
425: $this->request->{$name} = $value;
426: return;
427: case 'action':
428: $this->request->params['action'] = $value;
429: return;
430: case 'params':
431: $this->request->params = $value;
432: return;
433: case 'paginate':
434: $this->Components->load('Paginator')->settings = $value;
435: return;
436: }
437: $this->{$name} = $value;
438: }
439:
440: /**
441: * Sets the request objects and configures a number of controller properties
442: * based on the contents of the request. The properties that get set are
443: *
444: * - $this->request - To the $request parameter
445: * - $this->plugin - To the $request->params['plugin']
446: * - $this->view - To the $request->params['action']
447: * - $this->autoLayout - To the false if $request->params['bare']; is set.
448: * - $this->autoRender - To false if $request->params['return'] == 1
449: * - $this->passedArgs - The the combined results of params['named'] and params['pass]
450: *
451: * @param CakeRequest $request Request instance.
452: * @return void
453: */
454: public function setRequest(CakeRequest $request) {
455: $this->request = $request;
456: $this->plugin = isset($request->params['plugin']) ? Inflector::camelize($request->params['plugin']) : null;
457: $this->view = isset($request->params['action']) ? $request->params['action'] : null;
458: if (isset($request->params['pass']) && isset($request->params['named'])) {
459: $this->passedArgs = array_merge($request->params['pass'], $request->params['named']);
460: }
461:
462: if (!empty($request->params['return']) && $request->params['return'] == 1) {
463: $this->autoRender = false;
464: }
465: if (!empty($request->params['bare'])) {
466: $this->autoLayout = false;
467: }
468: }
469:
470: /**
471: * Dispatches the controller action. Checks that the action
472: * exists and isn't private.
473: *
474: * @param CakeRequest $request Request instance.
475: * @return mixed The resulting response.
476: * @throws PrivateActionException When actions are not public or prefixed by _
477: * @throws MissingActionException When actions are not defined and scaffolding is
478: * not enabled.
479: */
480: public function invokeAction(CakeRequest $request) {
481: try {
482: $method = new ReflectionMethod($this, $request->params['action']);
483:
484: if ($this->_isPrivateAction($method, $request)) {
485: throw new PrivateActionException(array(
486: 'controller' => $this->name . "Controller",
487: 'action' => $request->params['action']
488: ));
489: }
490: return $method->invokeArgs($this, $request->params['pass']);
491:
492: } catch (ReflectionException $e) {
493: if ($this->scaffold !== false) {
494: return $this->_getScaffold($request);
495: }
496: throw new MissingActionException(array(
497: 'controller' => $this->name . "Controller",
498: 'action' => $request->params['action']
499: ));
500: }
501: }
502:
503: /**
504: * Check if the request's action is marked as private, with an underscore,
505: * or if the request is attempting to directly accessing a prefixed action.
506: *
507: * @param ReflectionMethod $method The method to be invoked.
508: * @param CakeRequest $request The request to check.
509: * @return bool
510: */
511: protected function _isPrivateAction(ReflectionMethod $method, CakeRequest $request) {
512: $privateAction = (
513: $method->name[0] === '_' ||
514: !$method->isPublic() ||
515: !in_array($method->name, $this->methods)
516: );
517: $prefixes = array_map('strtolower', Router::prefixes());
518:
519: if (!$privateAction && !empty($prefixes)) {
520: if (empty($request->params['prefix']) && strpos($request->params['action'], '_') > 0) {
521: list($prefix) = explode('_', $request->params['action']);
522: $privateAction = in_array(strtolower($prefix), $prefixes);
523: }
524: }
525: return $privateAction;
526: }
527:
528: /**
529: * Returns a scaffold object to use for dynamically scaffolded controllers.
530: *
531: * @param CakeRequest $request Request instance.
532: * @return Scaffold
533: */
534: protected function _getScaffold(CakeRequest $request) {
535: return new Scaffold($this, $request);
536: }
537:
538: /**
539: * Merge components, helpers, and uses vars from
540: * Controller::$_mergeParent and PluginAppController.
541: *
542: * @return void
543: */
544: protected function _mergeControllerVars() {
545: $pluginController = $pluginDot = null;
546: $mergeParent = is_subclass_of($this, $this->_mergeParent);
547: $pluginVars = array();
548: $appVars = array();
549:
550: if (!empty($this->plugin)) {
551: $pluginController = $this->plugin . 'AppController';
552: if (!is_subclass_of($this, $pluginController)) {
553: $pluginController = null;
554: }
555: $pluginDot = $this->plugin . '.';
556: }
557:
558: if ($pluginController) {
559: $merge = array('components', 'helpers');
560: $this->_mergeVars($merge, $pluginController);
561: }
562:
563: if ($mergeParent || !empty($pluginController)) {
564: $appVars = get_class_vars($this->_mergeParent);
565: $merge = array('components', 'helpers');
566: $this->_mergeVars($merge, $this->_mergeParent, true);
567: }
568:
569: if ($this->uses === null) {
570: $this->uses = false;
571: }
572: if ($this->uses === true) {
573: $this->uses = array($pluginDot . $this->modelClass);
574: }
575: if (isset($appVars['uses']) && $appVars['uses'] === $this->uses) {
576: array_unshift($this->uses, $pluginDot . $this->modelClass);
577: }
578: if ($pluginController) {
579: $pluginVars = get_class_vars($pluginController);
580: }
581: if ($this->uses !== false) {
582: $this->_mergeUses($pluginVars);
583: $this->_mergeUses($appVars);
584: } else {
585: $this->uses = array();
586: $this->modelClass = '';
587: }
588: }
589:
590: /**
591: * Helper method for merging the $uses property together.
592: *
593: * Merges the elements not already in $this->uses into
594: * $this->uses.
595: *
596: * @param array $merge The data to merge in.
597: * @return void
598: */
599: protected function _mergeUses($merge) {
600: if (!isset($merge['uses'])) {
601: return;
602: }
603: if ($merge['uses'] === true) {
604: return;
605: }
606: $this->uses = array_merge(
607: $this->uses,
608: array_diff($merge['uses'], $this->uses)
609: );
610: }
611:
612: /**
613: * Returns a list of all events that will fire in the controller during its lifecycle.
614: * You can override this function to add your own listener callbacks
615: *
616: * @return array
617: */
618: public function implementedEvents() {
619: return array(
620: 'Controller.initialize' => 'beforeFilter',
621: 'Controller.beforeRender' => 'beforeRender',
622: 'Controller.beforeRedirect' => array('callable' => 'beforeRedirect', 'passParams' => true),
623: 'Controller.shutdown' => 'afterFilter'
624: );
625: }
626:
627: /**
628: * Loads Model classes based on the uses property
629: * see Controller::loadModel(); for more info.
630: * Loads Components and prepares them for initialization.
631: *
632: * @return mixed true if models found and instance created.
633: * @see Controller::loadModel()
634: * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::constructClasses
635: * @throws MissingModelException
636: */
637: public function constructClasses() {
638: $this->_mergeControllerVars();
639: if ($this->uses) {
640: $this->uses = (array)$this->uses;
641: list(, $this->modelClass) = pluginSplit(reset($this->uses));
642: }
643: $this->Components->init($this);
644: return true;
645: }
646:
647: /**
648: * Returns the CakeEventManager manager instance that is handling any callbacks.
649: * You can use this instance to register any new listeners or callbacks to the
650: * controller events, or create your own events and trigger them at will.
651: *
652: * @return CakeEventManager
653: */
654: public function getEventManager() {
655: if (empty($this->_eventManager)) {
656: $this->_eventManager = new CakeEventManager();
657: $this->_eventManager->attach($this->Components);
658: $this->_eventManager->attach($this);
659: }
660: return $this->_eventManager;
661: }
662:
663: /**
664: * Perform the startup process for this controller.
665: * Fire the Components and Controller callbacks in the correct order.
666: *
667: * - Initializes components, which fires their `initialize` callback
668: * - Calls the controller `beforeFilter`.
669: * - triggers Component `startup` methods.
670: *
671: * @return void
672: * @triggers Controller.initialize $this
673: * @triggers Controller.startup $this
674: */
675: public function startupProcess() {
676: $this->getEventManager()->dispatch(new CakeEvent('Controller.initialize', $this));
677: $this->getEventManager()->dispatch(new CakeEvent('Controller.startup', $this));
678: }
679:
680: /**
681: * Perform the various shutdown processes for this controller.
682: * Fire the Components and Controller callbacks in the correct order.
683: *
684: * - triggers the component `shutdown` callback.
685: * - calls the Controller's `afterFilter` method.
686: *
687: * @return void
688: * @triggers Controller.shutdown $this
689: */
690: public function shutdownProcess() {
691: $this->getEventManager()->dispatch(new CakeEvent('Controller.shutdown', $this));
692: }
693:
694: /**
695: * Queries & sets valid HTTP response codes & messages.
696: *
697: * @param int|array $code If $code is an integer, then the corresponding code/message is
698: * returned if it exists, null if it does not exist. If $code is an array,
699: * then the 'code' and 'message' keys of each nested array are added to the default
700: * HTTP codes. Example:
701: *
702: * httpCodes(404); // returns array(404 => 'Not Found')
703: *
704: * httpCodes(array(
705: * 701 => 'Unicorn Moved',
706: * 800 => 'Unexpected Minotaur'
707: * )); // sets these new values, and returns true
708: *
709: * @return array Associative array of the HTTP codes as keys, and the message
710: * strings as values, or null of the given $code does not exist.
711: * @deprecated 3.0.0 Since 2.4. Will be removed in 3.0. Use CakeResponse::httpCodes().
712: */
713: public function httpCodes($code = null) {
714: return $this->response->httpCodes($code);
715: }
716:
717: /**
718: * Loads and instantiates models required by this controller.
719: * If the model is non existent, it will throw a missing database table error, as CakePHP generates
720: * dynamic models for the time being.
721: *
722: * @param string $modelClass Name of model class to load
723: * @param int|string $id Initial ID the instanced model class should have
724: * @return bool True if the model was found
725: * @throws MissingModelException if the model class cannot be found.
726: */
727: public function loadModel($modelClass = null, $id = null) {
728: if ($modelClass === null) {
729: $modelClass = $this->modelClass;
730: }
731:
732: $this->uses = ($this->uses) ? (array)$this->uses : array();
733: if (!in_array($modelClass, $this->uses, true)) {
734: $this->uses[] = $modelClass;
735: }
736:
737: list($plugin, $modelClass) = pluginSplit($modelClass, true);
738:
739: $this->{$modelClass} = ClassRegistry::init(array(
740: 'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
741: ));
742: if (!$this->{$modelClass}) {
743: throw new MissingModelException($modelClass);
744: }
745: return true;
746: }
747:
748: /**
749: * Redirects to given $url, after turning off $this->autoRender.
750: * Script execution is halted after the redirect.
751: *
752: * @param string|array $url A string or array-based URL pointing to another location within the app,
753: * or an absolute URL
754: * @param int $status Optional HTTP status code (eg: 404)
755: * @param bool $exit If true, exit() will be called after the redirect
756: * @return void
757: * @triggers Controller.beforeRedirect $this, array($url, $status, $exit)
758: * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect
759: */
760: public function redirect($url, $status = null, $exit = true) {
761: $this->autoRender = false;
762:
763: if (is_array($status)) {
764: extract($status, EXTR_OVERWRITE);
765: }
766: $event = new CakeEvent('Controller.beforeRedirect', $this, array($url, $status, $exit));
767:
768: list($event->break, $event->breakOn, $event->collectReturn) = array(true, false, true);
769: $this->getEventManager()->dispatch($event);
770:
771: if ($event->isStopped()) {
772: return;
773: }
774: $response = $event->result;
775: extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
776:
777: if ($url !== null) {
778: $this->response->header('Location', Router::url($url, true));
779: }
780:
781: if (is_string($status)) {
782: $codes = array_flip($this->response->httpCodes());
783: if (isset($codes[$status])) {
784: $status = $codes[$status];
785: }
786: }
787:
788: if ($status) {
789: $this->response->statusCode($status);
790: }
791:
792: if ($exit) {
793: $this->response->send();
794: $this->_stop();
795: }
796: }
797:
798: /**
799: * Parse beforeRedirect Response
800: *
801: * @param mixed $response Response from beforeRedirect callback
802: * @param string|array $url The same value of beforeRedirect
803: * @param int $status The same value of beforeRedirect
804: * @param bool $exit The same value of beforeRedirect
805: * @return array Array with keys url, status and exit
806: */
807: protected function _parseBeforeRedirect($response, $url, $status, $exit) {
808: if (is_array($response) && array_key_exists(0, $response)) {
809: foreach ($response as $resp) {
810: if (is_array($resp) && isset($resp['url'])) {
811: extract($resp, EXTR_OVERWRITE);
812: } elseif ($resp !== null) {
813: $url = $resp;
814: }
815: }
816: } elseif (is_array($response)) {
817: extract($response, EXTR_OVERWRITE);
818: }
819: return compact('url', 'status', 'exit');
820: }
821:
822: /**
823: * Convenience and object wrapper method for CakeResponse::header().
824: *
825: * @param string $status The header message that is being set.
826: * @return void
827: * @deprecated 3.0.0 Will be removed in 3.0. Use CakeResponse::header().
828: */
829: public function header($status) {
830: $this->response->header($status);
831: }
832:
833: /**
834: * Saves a variable for use inside a view template.
835: *
836: * @param string|array $one A string or an array of data.
837: * @param string|array $two Value in case $one is a string (which then works as the key).
838: * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
839: * @return void
840: * @link http://book.cakephp.org/2.0/en/controllers.html#interacting-with-views
841: */
842: public function set($one, $two = null) {
843: if (is_array($one)) {
844: if (is_array($two)) {
845: $data = array_combine($one, $two);
846: } else {
847: $data = $one;
848: }
849: } else {
850: $data = array($one => $two);
851: }
852: $this->viewVars = $data + $this->viewVars;
853: }
854:
855: /**
856: * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
857: *
858: * Examples:
859: *
860: * {{{
861: * setAction('another_action');
862: * setAction('action_with_parameters', $parameter1);
863: * }}}
864: *
865: * @param string $action The new action to be 'redirected' to.
866: * Any other parameters passed to this method will be passed as parameters to the new action.
867: * @return mixed Returns the return value of the called action
868: */
869: public function setAction($action) {
870: $this->request->params['action'] = $action;
871: $this->view = $action;
872: $args = func_get_args();
873: unset($args[0]);
874: return call_user_func_array(array(&$this, $action), $args);
875: }
876:
877: /**
878: * Returns number of errors in a submitted FORM.
879: *
880: * @return int Number of errors
881: * @deprecated 3.0.0 This method will be removed in 3.0
882: */
883: public function validate() {
884: $args = func_get_args();
885: $errors = call_user_func_array(array(&$this, 'validateErrors'), $args);
886:
887: if ($errors === false) {
888: return 0;
889: }
890: return count($errors);
891: }
892:
893: /**
894: * Validates models passed by parameters. Takes a list of models as a variable argument.
895: * Example:
896: *
897: * `$errors = $this->validateErrors($this->Article, $this->User);`
898: *
899: * @return array Validation errors, or false if none
900: * @deprecated 3.0.0 This method will be removed in 3.0
901: */
902: public function validateErrors() {
903: $objects = func_get_args();
904:
905: if (empty($objects)) {
906: return false;
907: }
908:
909: $errors = array();
910: foreach ($objects as $object) {
911: if (isset($this->{$object->alias})) {
912: $object = $this->{$object->alias};
913: }
914: $object->set($object->data);
915: $errors = array_merge($errors, $object->invalidFields());
916: }
917:
918: return $this->validationErrors = (!empty($errors) ? $errors : false);
919: }
920:
921: /**
922: * Instantiates the correct view class, hands it its data, and uses it to render the view output.
923: *
924: * @param string $view View to use for rendering
925: * @param string $layout Layout to use
926: * @return CakeResponse A response object containing the rendered view.
927: * @triggers Controller.beforeRender $this
928: * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render
929: */
930: public function render($view = null, $layout = null) {
931: $event = new CakeEvent('Controller.beforeRender', $this);
932: $this->getEventManager()->dispatch($event);
933: if ($event->isStopped()) {
934: $this->autoRender = false;
935: return $this->response;
936: }
937:
938: if (!empty($this->uses) && is_array($this->uses)) {
939: foreach ($this->uses as $model) {
940: list($plugin, $className) = pluginSplit($model);
941: $this->request->params['models'][$className] = compact('plugin', 'className');
942: }
943: }
944:
945: $this->View = $this->_getViewObject();
946:
947: $models = ClassRegistry::keys();
948: foreach ($models as $currentModel) {
949: $currentObject = ClassRegistry::getObject($currentModel);
950: if ($currentObject instanceof Model) {
951: $className = get_class($currentObject);
952: list($plugin) = pluginSplit(App::location($className));
953: $this->request->params['models'][$currentObject->alias] = compact('plugin', 'className');
954: $this->View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors;
955: }
956: }
957:
958: $this->autoRender = false;
959: $this->response->body($this->View->render($view, $layout));
960: return $this->response;
961: }
962:
963: /**
964: * Returns the referring URL for this request.
965: *
966: * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
967: * @param bool $local If true, restrict referring URLs to local server
968: * @return string Referring URL
969: * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::referer
970: */
971: public function referer($default = null, $local = false) {
972: if (!$this->request) {
973: return '/';
974: }
975:
976: $referer = $this->request->referer($local);
977: if ($referer === '/' && $default) {
978: return Router::url($default, !$local);
979: }
980: return $referer;
981: }
982:
983: /**
984: * Forces the user's browser not to cache the results of the current request.
985: *
986: * @return void
987: * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::disableCache
988: * @deprecated 3.0.0 Will be removed in 3.0. Use CakeResponse::disableCache().
989: */
990: public function disableCache() {
991: $this->response->disableCache();
992: }
993:
994: /**
995: * Shows a message to the user for $pause seconds, then redirects to $url.
996: * Uses flash.ctp as the default layout for the message.
997: * Does not work if the current debug level is higher than 0.
998: *
999: * @param string $message Message to display to the user
1000: * @param string|array $url Relative string or array-based URL to redirect to after the time expires
1001: * @param int $pause Time to show the message
1002: * @param string $layout Layout you want to use, defaults to 'flash'
1003: * @return void
1004: * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::flash
1005: * @deprecated 3.0.0 Will be removed in 3.0. Use Session::setFlash().
1006: */
1007: public function flash($message, $url, $pause = 1, $layout = 'flash') {
1008: $this->autoRender = false;
1009: $this->set('url', Router::url($url));
1010: $this->set('message', $message);
1011: $this->set('pause', $pause);
1012: $this->set('pageTitle', $message);
1013: $this->render(false, $layout);
1014: }
1015:
1016: /**
1017: * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
1018: *
1019: * @param array $data POST'ed data organized by model and field
1020: * @param string|array $op A string containing an SQL comparison operator, or an array matching operators
1021: * to fields
1022: * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
1023: * @param bool $exclusive If true, and $op is an array, fields not included in $op will not be
1024: * included in the returned conditions
1025: * @return array|null An array of model conditions
1026: * @deprecated 3.0.0 Will be removed in 3.0.
1027: */
1028: public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
1029: if (!is_array($data) || empty($data)) {
1030: if (!empty($this->request->data)) {
1031: $data = $this->request->data;
1032: } else {
1033: return null;
1034: }
1035: }
1036: $cond = array();
1037:
1038: if ($op === null) {
1039: $op = '';
1040: }
1041:
1042: $arrayOp = is_array($op);
1043: foreach ($data as $model => $fields) {
1044: foreach ($fields as $field => $value) {
1045: $key = $model . '.' . $field;
1046: $fieldOp = $op;
1047: if ($arrayOp) {
1048: if (array_key_exists($key, $op)) {
1049: $fieldOp = $op[$key];
1050: } elseif (array_key_exists($field, $op)) {
1051: $fieldOp = $op[$field];
1052: } else {
1053: $fieldOp = false;
1054: }
1055: }
1056: if ($exclusive && $fieldOp === false) {
1057: continue;
1058: }
1059: $fieldOp = strtoupper(trim($fieldOp));
1060: if ($fieldOp === 'LIKE') {
1061: $key = $key . ' LIKE';
1062: $value = '%' . $value . '%';
1063: } elseif ($fieldOp && $fieldOp !== '=') {
1064: $key = $key . ' ' . $fieldOp;
1065: }
1066: $cond[$key] = $value;
1067: }
1068: }
1069: if ($bool && strtoupper($bool) !== 'AND') {
1070: $cond = array($bool => $cond);
1071: }
1072: return $cond;
1073: }
1074:
1075: /**
1076: * Handles automatic pagination of model records.
1077: *
1078: * @param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
1079: * @param string|array $scope Conditions to use while paginating
1080: * @param array $whitelist List of allowed options for paging
1081: * @return array Model query results
1082: * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::paginate
1083: */
1084: public function paginate($object = null, $scope = array(), $whitelist = array()) {
1085: return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist);
1086: }
1087:
1088: /**
1089: * Called before the controller action. You can use this method to configure and customize components
1090: * or perform logic that needs to happen before each controller action.
1091: *
1092: * @return void
1093: * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1094: */
1095: public function beforeFilter() {
1096: }
1097:
1098: /**
1099: * Called after the controller action is run, but before the view is rendered. You can use this method
1100: * to perform logic or set view variables that are required on every request.
1101: *
1102: * @return void
1103: * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1104: */
1105: public function beforeRender() {
1106: }
1107:
1108: /**
1109: * The beforeRedirect method is invoked when the controller's redirect method is called but before any
1110: * further action.
1111: *
1112: * If this method returns false the controller will not continue on to redirect the request.
1113: * The $url, $status and $exit variables have same meaning as for the controller's method. You can also
1114: * return a string which will be interpreted as the URL to redirect to or return associative array with
1115: * key 'url' and optionally 'status' and 'exit'.
1116: *
1117: * @param string|array $url A string or array-based URL pointing to another location within the app,
1118: * or an absolute URL
1119: * @param int $status Optional HTTP status code (eg: 404)
1120: * @param bool $exit If true, exit() will be called after the redirect
1121: * @return mixed
1122: * false to stop redirection event,
1123: * string controllers a new redirection URL or
1124: * array with the keys url, status and exit to be used by the redirect method.
1125: * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1126: */
1127: public function beforeRedirect($url, $status = null, $exit = true) {
1128: }
1129:
1130: /**
1131: * Called after the controller action is run and rendered.
1132: *
1133: * @return void
1134: * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1135: */
1136: public function afterFilter() {
1137: }
1138:
1139: /**
1140: * This method should be overridden in child classes.
1141: *
1142: * @param string $method name of method called example index, edit, etc.
1143: * @return bool Success
1144: * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1145: */
1146: public function beforeScaffold($method) {
1147: return true;
1148: }
1149:
1150: /**
1151: * Alias to beforeScaffold()
1152: *
1153: * @param string $method Method name.
1154: * @return bool
1155: * @see Controller::beforeScaffold()
1156: * @deprecated 3.0.0 Will be removed in 3.0.
1157: */
1158: protected function _beforeScaffold($method) {
1159: return $this->beforeScaffold($method);
1160: }
1161:
1162: /**
1163: * This method should be overridden in child classes.
1164: *
1165: * @param string $method name of method called either edit or update.
1166: * @return bool Success
1167: * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1168: */
1169: public function afterScaffoldSave($method) {
1170: return true;
1171: }
1172:
1173: /**
1174: * Alias to afterScaffoldSave()
1175: *
1176: * @param string $method Method name.
1177: * @return bool
1178: * @see Controller::afterScaffoldSave()
1179: * @deprecated 3.0.0 Will be removed in 3.0.
1180: */
1181: protected function _afterScaffoldSave($method) {
1182: return $this->afterScaffoldSave($method);
1183: }
1184:
1185: /**
1186: * This method should be overridden in child classes.
1187: *
1188: * @param string $method name of method called either edit or update.
1189: * @return bool Success
1190: * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1191: */
1192: public function afterScaffoldSaveError($method) {
1193: return true;
1194: }
1195:
1196: /**
1197: * Alias to afterScaffoldSaveError()
1198: *
1199: * @param string $method Method name.
1200: * @return bool
1201: * @see Controller::afterScaffoldSaveError()
1202: * @deprecated 3.0.0 Will be removed in 3.0.
1203: */
1204: protected function _afterScaffoldSaveError($method) {
1205: return $this->afterScaffoldSaveError($method);
1206: }
1207:
1208: /**
1209: * This method should be overridden in child classes.
1210: * If not it will render a scaffold error.
1211: * Method MUST return true in child classes
1212: *
1213: * @param string $method name of method called example index, edit, etc.
1214: * @return bool Success
1215: * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1216: */
1217: public function scaffoldError($method) {
1218: return false;
1219: }
1220:
1221: /**
1222: * Alias to scaffoldError()
1223: *
1224: * @param string $method Method name.
1225: * @return bool
1226: * @see Controller::scaffoldError()
1227: * @deprecated 3.0.0 Will be removed in 3.0.
1228: */
1229: protected function _scaffoldError($method) {
1230: return $this->scaffoldError($method);
1231: }
1232:
1233: /**
1234: * Constructs the view class instance based on the controller property
1235: *
1236: * @return View
1237: */
1238: protected function _getViewObject() {
1239: $viewClass = $this->viewClass;
1240: if ($this->viewClass !== 'View') {
1241: list($plugin, $viewClass) = pluginSplit($viewClass, true);
1242: $viewClass = $viewClass . 'View';
1243: App::uses($viewClass, $plugin . 'View');
1244: }
1245:
1246: return new $viewClass($this);
1247: }
1248:
1249: }
1250: