統計
| ブランチ: | リビジョン:

pictcode_admin / lib / Cake / Controller / Controller.php @ 5ad38a95

履歴 | 表示 | アノテート | ダウンロード (36.624 KB)

1 5ad38a95 spyder1211
<?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', 'Flash');
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|array|null $status HTTP status code (eg: 301). Defaults to 302 when null is passed.
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 === null) {
789
                        $status = 302;
790
                }
791
                $this->response->statusCode($status);
792
793
                if ($exit) {
794
                        $this->response->send();
795
                        $this->_stop();
796
                }
797
        }
798
799
/**
800
 * Parse beforeRedirect Response
801
 *
802
 * @param mixed $response Response from beforeRedirect callback
803
 * @param string|array $url The same value of beforeRedirect
804
 * @param int $status The same value of beforeRedirect
805
 * @param bool $exit The same value of beforeRedirect
806
 * @return array Array with keys url, status and exit
807
 */
808
        protected function _parseBeforeRedirect($response, $url, $status, $exit) {
809
                if (is_array($response) && array_key_exists(0, $response)) {
810
                        foreach ($response as $resp) {
811
                                if (is_array($resp) && isset($resp['url'])) {
812
                                        extract($resp, EXTR_OVERWRITE);
813
                                } elseif ($resp !== null) {
814
                                        $url = $resp;
815
                                }
816
                        }
817
                } elseif (is_array($response)) {
818
                        extract($response, EXTR_OVERWRITE);
819
                }
820
                return compact('url', 'status', 'exit');
821
        }
822
823
/**
824
 * Convenience and object wrapper method for CakeResponse::header().
825
 *
826
 * @param string $status The header message that is being set.
827
 * @return void
828
 * @deprecated 3.0.0 Will be removed in 3.0. Use CakeResponse::header().
829
 */
830
        public function header($status) {
831
                $this->response->header($status);
832
        }
833
834
/**
835
 * Saves a variable for use inside a view template.
836
 *
837
 * @param string|array $one A string or an array of data.
838
 * @param string|array $two Value in case $one is a string (which then works as the key).
839
 *   Unused if $one is an associative array, otherwise serves as the values to $one's keys.
840
 * @return void
841
 * @link http://book.cakephp.org/2.0/en/controllers.html#interacting-with-views
842
 */
843
        public function set($one, $two = null) {
844
                if (is_array($one)) {
845
                        if (is_array($two)) {
846
                                $data = array_combine($one, $two);
847
                        } else {
848
                                $data = $one;
849
                        }
850
                } else {
851
                        $data = array($one => $two);
852
                }
853
                $this->viewVars = $data + $this->viewVars;
854
        }
855
856
/**
857
 * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
858
 *
859
 * Examples:
860
 *
861
 * ```
862
 * setAction('another_action');
863
 * setAction('action_with_parameters', $parameter1);
864
 * ```
865
 *
866
 * @param string $action The new action to be 'redirected' to.
867
 *   Any other parameters passed to this method will be passed as parameters to the new action.
868
 * @return mixed Returns the return value of the called action
869
 */
870
        public function setAction($action) {
871
                $this->request->params['action'] = $action;
872
                $this->view = $action;
873
                $args = func_get_args();
874
                unset($args[0]);
875
                return call_user_func_array(array(&$this, $action), $args);
876
        }
877
878
/**
879
 * Returns number of errors in a submitted FORM.
880
 *
881
 * @return int Number of errors
882
 * @deprecated 3.0.0 This method will be removed in 3.0
883
 */
884
        public function validate() {
885
                $args = func_get_args();
886
                $errors = call_user_func_array(array(&$this, 'validateErrors'), $args);
887
888
                if ($errors === false) {
889
                        return 0;
890
                }
891
                return count($errors);
892
        }
893
894
/**
895
 * Validates models passed by parameters. Takes a list of models as a variable argument.
896
 * Example:
897
 *
898
 * `$errors = $this->validateErrors($this->Article, $this->User);`
899
 *
900
 * @return array Validation errors, or false if none
901
 * @deprecated 3.0.0 This method will be removed in 3.0
902
 */
903
        public function validateErrors() {
904
                $objects = func_get_args();
905
906
                if (empty($objects)) {
907
                        return false;
908
                }
909
910
                $errors = array();
911
                foreach ($objects as $object) {
912
                        if (isset($this->{$object->alias})) {
913
                                $object = $this->{$object->alias};
914
                        }
915
                        $object->set($object->data);
916
                        $errors = array_merge($errors, $object->invalidFields());
917
                }
918
919
                return $this->validationErrors = (!empty($errors) ? $errors : false);
920
        }
921
922
/**
923
 * Instantiates the correct view class, hands it its data, and uses it to render the view output.
924
 *
925
 * @param string $view View to use for rendering
926
 * @param string $layout Layout to use
927
 * @return CakeResponse A response object containing the rendered view.
928
 * @triggers Controller.beforeRender $this
929
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render
930
 */
931
        public function render($view = null, $layout = null) {
932
                $event = new CakeEvent('Controller.beforeRender', $this);
933
                $this->getEventManager()->dispatch($event);
934
                if ($event->isStopped()) {
935
                        $this->autoRender = false;
936
                        return $this->response;
937
                }
938
939
                if (!empty($this->uses) && is_array($this->uses)) {
940
                        foreach ($this->uses as $model) {
941
                                list($plugin, $className) = pluginSplit($model);
942
                                $this->request->params['models'][$className] = compact('plugin', 'className');
943
                        }
944
                }
945
946
                $this->View = $this->_getViewObject();
947
948
                $models = ClassRegistry::keys();
949
                foreach ($models as $currentModel) {
950
                        $currentObject = ClassRegistry::getObject($currentModel);
951
                        if ($currentObject instanceof Model) {
952
                                $className = get_class($currentObject);
953
                                list($plugin) = pluginSplit(App::location($className));
954
                                $this->request->params['models'][$currentObject->alias] = compact('plugin', 'className');
955
                                $this->View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors;
956
                        }
957
                }
958
959
                $this->autoRender = false;
960
                $this->response->body($this->View->render($view, $layout));
961
                return $this->response;
962
        }
963
964
/**
965
 * Returns the referring URL for this request.
966
 *
967
 * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
968
 * @param bool $local If true, restrict referring URLs to local server
969
 * @return string Referring URL
970
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::referer
971
 */
972
        public function referer($default = null, $local = false) {
973
                if (!$this->request) {
974
                        return '/';
975
                }
976
977
                $referer = $this->request->referer($local);
978
                if ($referer === '/' && $default && $default !== $referer) {
979
                        return Router::url($default, !$local);
980
                }
981
                return $referer;
982
        }
983
984
/**
985
 * Forces the user's browser not to cache the results of the current request.
986
 *
987
 * @return void
988
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::disableCache
989
 * @deprecated 3.0.0 Will be removed in 3.0. Use CakeResponse::disableCache().
990
 */
991
        public function disableCache() {
992
                $this->response->disableCache();
993
        }
994
995
/**
996
 * Shows a message to the user for $pause seconds, then redirects to $url.
997
 * Uses flash.ctp as the default layout for the message.
998
 * Does not work if the current debug level is higher than 0.
999
 *
1000
 * @param string $message Message to display to the user
1001
 * @param string|array $url Relative string or array-based URL to redirect to after the time expires
1002
 * @param int $pause Time to show the message
1003
 * @param string $layout Layout you want to use, defaults to 'flash'
1004
 * @return void
1005
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::flash
1006
 * @deprecated 3.0.0 Will be removed in 3.0. Use Session::setFlash().
1007
 */
1008
        public function flash($message, $url, $pause = 1, $layout = 'flash') {
1009
                $this->autoRender = false;
1010
                $this->set('url', Router::url($url));
1011
                $this->set('message', $message);
1012
                $this->set('pause', $pause);
1013
                $this->set('pageTitle', $message);
1014
                $this->render(false, $layout);
1015
        }
1016
1017
/**
1018
 * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
1019
 *
1020
 * @param array $data POST'ed data organized by model and field
1021
 * @param string|array $op A string containing an SQL comparison operator, or an array matching operators
1022
 *        to fields
1023
 * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
1024
 * @param bool $exclusive If true, and $op is an array, fields not included in $op will not be
1025
 *        included in the returned conditions
1026
 * @return array|null An array of model conditions
1027
 * @deprecated 3.0.0 Will be removed in 3.0.
1028
 */
1029
        public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
1030
                if (!is_array($data) || empty($data)) {
1031
                        if (!empty($this->request->data)) {
1032
                                $data = $this->request->data;
1033
                        } else {
1034
                                return null;
1035
                        }
1036
                }
1037
                $cond = array();
1038
1039
                if ($op === null) {
1040
                        $op = '';
1041
                }
1042
1043
                $arrayOp = is_array($op);
1044
                foreach ($data as $model => $fields) {
1045
                        foreach ($fields as $field => $value) {
1046
                                $key = $model . '.' . $field;
1047
                                $fieldOp = $op;
1048
                                if ($arrayOp) {
1049
                                        if (array_key_exists($key, $op)) {
1050
                                                $fieldOp = $op[$key];
1051
                                        } elseif (array_key_exists($field, $op)) {
1052
                                                $fieldOp = $op[$field];
1053
                                        } else {
1054
                                                $fieldOp = false;
1055
                                        }
1056
                                }
1057
                                if ($exclusive && $fieldOp === false) {
1058
                                        continue;
1059
                                }
1060
                                $fieldOp = strtoupper(trim($fieldOp));
1061
                                if ($fieldOp === 'LIKE') {
1062
                                        $key = $key . ' LIKE';
1063
                                        $value = '%' . $value . '%';
1064
                                } elseif ($fieldOp && $fieldOp !== '=') {
1065
                                        $key = $key . ' ' . $fieldOp;
1066
                                }
1067
                                $cond[$key] = $value;
1068
                        }
1069
                }
1070
                if ($bool && strtoupper($bool) !== 'AND') {
1071
                        $cond = array($bool => $cond);
1072
                }
1073
                return $cond;
1074
        }
1075
1076
/**
1077
 * Handles automatic pagination of model records.
1078
 *
1079
 * @param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
1080
 * @param string|array $scope Conditions to use while paginating
1081
 * @param array $whitelist List of allowed options for paging
1082
 * @return array Model query results
1083
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::paginate
1084
 */
1085
        public function paginate($object = null, $scope = array(), $whitelist = array()) {
1086
                return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist);
1087
        }
1088
1089
/**
1090
 * Called before the controller action. You can use this method to configure and customize components
1091
 * or perform logic that needs to happen before each controller action.
1092
 *
1093
 * @return void
1094
 * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1095
 */
1096
        public function beforeFilter() {
1097
        }
1098
1099
/**
1100
 * Called after the controller action is run, but before the view is rendered. You can use this method
1101
 * to perform logic or set view variables that are required on every request.
1102
 *
1103
 * @return void
1104
 * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1105
 */
1106
        public function beforeRender() {
1107
        }
1108
1109
/**
1110
 * The beforeRedirect method is invoked when the controller's redirect method is called but before any
1111
 * further action.
1112
 *
1113
 * If this method returns false the controller will not continue on to redirect the request.
1114
 * The $url, $status and $exit variables have same meaning as for the controller's method. You can also
1115
 * return a string which will be interpreted as the URL to redirect to or return associative array with
1116
 * key 'url' and optionally 'status' and 'exit'.
1117
 *
1118
 * @param string|array $url A string or array-based URL pointing to another location within the app,
1119
 *     or an absolute URL
1120
 * @param int $status Optional HTTP status code (eg: 404)
1121
 * @param bool $exit If true, exit() will be called after the redirect
1122
 * @return mixed
1123
 *   false to stop redirection event,
1124
 *   string controllers a new redirection URL or
1125
 *   array with the keys url, status and exit to be used by the redirect method.
1126
 * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1127
 */
1128
        public function beforeRedirect($url, $status = null, $exit = true) {
1129
        }
1130
1131
/**
1132
 * Called after the controller action is run and rendered.
1133
 *
1134
 * @return void
1135
 * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1136
 */
1137
        public function afterFilter() {
1138
        }
1139
1140
/**
1141
 * This method should be overridden in child classes.
1142
 *
1143
 * @param string $method name of method called example index, edit, etc.
1144
 * @return bool Success
1145
 * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1146
 */
1147
        public function beforeScaffold($method) {
1148
                return true;
1149
        }
1150
1151
/**
1152
 * Alias to beforeScaffold()
1153
 *
1154
 * @param string $method Method name.
1155
 * @return bool
1156
 * @see Controller::beforeScaffold()
1157
 * @deprecated 3.0.0 Will be removed in 3.0.
1158
 */
1159
        protected function _beforeScaffold($method) {
1160
                return $this->beforeScaffold($method);
1161
        }
1162
1163
/**
1164
 * This method should be overridden in child classes.
1165
 *
1166
 * @param string $method name of method called either edit or update.
1167
 * @return bool Success
1168
 * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1169
 */
1170
        public function afterScaffoldSave($method) {
1171
                return true;
1172
        }
1173
1174
/**
1175
 * Alias to afterScaffoldSave()
1176
 *
1177
 * @param string $method Method name.
1178
 * @return bool
1179
 * @see Controller::afterScaffoldSave()
1180
 * @deprecated 3.0.0 Will be removed in 3.0.
1181
 */
1182
        protected function _afterScaffoldSave($method) {
1183
                return $this->afterScaffoldSave($method);
1184
        }
1185
1186
/**
1187
 * This method should be overridden in child classes.
1188
 *
1189
 * @param string $method name of method called either edit or update.
1190
 * @return bool Success
1191
 * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1192
 */
1193
        public function afterScaffoldSaveError($method) {
1194
                return true;
1195
        }
1196
1197
/**
1198
 * Alias to afterScaffoldSaveError()
1199
 *
1200
 * @param string $method Method name.
1201
 * @return bool
1202
 * @see Controller::afterScaffoldSaveError()
1203
 * @deprecated 3.0.0 Will be removed in 3.0.
1204
 */
1205
        protected function _afterScaffoldSaveError($method) {
1206
                return $this->afterScaffoldSaveError($method);
1207
        }
1208
1209
/**
1210
 * This method should be overridden in child classes.
1211
 * If not it will render a scaffold error.
1212
 * Method MUST return true in child classes
1213
 *
1214
 * @param string $method name of method called example index, edit, etc.
1215
 * @return bool Success
1216
 * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1217
 */
1218
        public function scaffoldError($method) {
1219
                return false;
1220
        }
1221
1222
/**
1223
 * Alias to scaffoldError()
1224
 *
1225
 * @param string $method Method name.
1226
 * @return bool
1227
 * @see Controller::scaffoldError()
1228
 * @deprecated 3.0.0 Will be removed in 3.0.
1229
 */
1230
        protected function _scaffoldError($method) {
1231
                return $this->scaffoldError($method);
1232
        }
1233
1234
/**
1235
 * Constructs the view class instance based on the controller property
1236
 *
1237
 * @return View
1238
 */
1239
        protected function _getViewObject() {
1240
                $viewClass = $this->viewClass;
1241
                if ($this->viewClass !== 'View') {
1242
                        list($plugin, $viewClass) = pluginSplit($viewClass, true);
1243
                        $viewClass = $viewClass . 'View';
1244
                        App::uses($viewClass, $plugin . 'View');
1245
                }
1246
1247
                return new $viewClass($this);
1248
        }
1249
1250
}