summaryrefslogtreecommitdiffstats
path: root/library/vendor/Zend/Controller/Action/Helper/Redirector.php
blob: 8ff7c3e35d5ba81936e588e459658636f96768c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */

/**
 * @see Zend_Controller_Action_Helper_Abstract
 */

/**
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Action_Helper_Redirector extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * HTTP status code for redirects
     * @var int
     */
    protected $_code = 302;

    /**
     * Whether or not calls to _redirect() should exit script execution
     * @var boolean
     */
    protected $_exit = true;

    /**
     * Whether or not _redirect() should attempt to prepend the base URL to the
     * passed URL (if it's a relative URL)
     * @var boolean
     */
    protected $_prependBase = true;

    /**
     * Url to which to redirect
     * @var string
     */
    protected $_redirectUrl = null;

    /**
     * Whether or not to use an absolute URI when redirecting
     * @var boolean
     */
    protected $_useAbsoluteUri = false;

    /**
     * Whether or not to close the session before exiting
     * @var boolean
     */
    protected $_closeSessionOnExit = true;

    /**
     * Retrieve HTTP status code to emit on {@link _redirect()} call
     *
     * @return int
     */
    public function getCode()
    {
        return $this->_code;
    }

    /**
     * Validate HTTP status redirect code
     *
     * @param  int $code
     * @throws Zend_Controller_Action_Exception on invalid HTTP status code
     * @return true
     */
    protected function _checkCode($code)
    {
        $code = (int)$code;
        if ((300 > $code) || (307 < $code) || (304 == $code) || (306 == $code)) {
            throw new Zend_Controller_Action_Exception('Invalid redirect HTTP status code (' . $code  . ')');
        }

        return true;
    }

    /**
     * Set HTTP status code for {@link _redirect()} behaviour
     *
     * @param  int $code
     * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface
     */
    public function setCode($code)
    {
        $this->_checkCode($code);
        $this->_code = $code;
        return $this;
    }

    /**
     * Retrieve flag for whether or not {@link _redirect()} will exit when finished.
     *
     * @return boolean
     */
    public function getExit()
    {
        return $this->_exit;
    }

    /**
     * Set exit flag for {@link _redirect()} behaviour
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface
     */
    public function setExit($flag)
    {
        $this->_exit = ($flag) ? true : false;
        return $this;
    }

    /**
     * Retrieve flag for whether or not {@link _redirect()} will prepend the
     * base URL on relative URLs
     *
     * @return boolean
     */
    public function getPrependBase()
    {
        return $this->_prependBase;
    }

    /**
     * Set 'prepend base' flag for {@link _redirect()} behaviour
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface
     */
    public function setPrependBase($flag)
    {
        $this->_prependBase = ($flag) ? true : false;
        return $this;
    }

    /**
     * Retrieve flag for whether or not {@link redirectAndExit()} shall close the session before
     * exiting.
     *
     * @return boolean
     */
    public function getCloseSessionOnExit()
    {
        return $this->_closeSessionOnExit;
    }

    /**
     * Set flag for whether or not {@link redirectAndExit()} shall close the session before exiting.
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface
     */
    public function setCloseSessionOnExit($flag)
    {
        $this->_closeSessionOnExit = ($flag) ? true : false;
        return $this;
    }

    /**
     * Return use absolute URI flag
     *
     * @return boolean
     */
    public function getUseAbsoluteUri()
    {
        return $this->_useAbsoluteUri;
    }

    /**
     * Set use absolute URI flag
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface
     */
    public function setUseAbsoluteUri($flag = true)
    {
        $this->_useAbsoluteUri = ($flag) ? true : false;
        return $this;
    }

    /**
     * Set redirect in response object
     *
     * @return void
     */
    protected function _redirect($url)
    {
        if ($this->getUseAbsoluteUri() && !preg_match('#^(https?|ftp)://#', $url)) {
            $host  = (isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:'');
            $proto = (isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=="off") ? 'https' : 'http';
            $port  = (isset($_SERVER['SERVER_PORT'])?$_SERVER['SERVER_PORT']:80);
            $uri   = $proto . '://' . $host;
            if ((('http' == $proto) && (80 != $port)) || (('https' == $proto) && (443 != $port))) {
                // do not append if HTTP_HOST already contains port
                if (strrchr($host, ':') === false) {
                    $uri .= ':' . $port;
                }
            }
            $url = $uri . '/' . ltrim($url, '/');
        }
        $this->_redirectUrl = $url;
        $this->getResponse()->setRedirect($url, $this->getCode());
    }

    /**
     * Retrieve currently set URL for redirect
     *
     * @return string
     */
    public function getRedirectUrl()
    {
        return $this->_redirectUrl;
    }

    /**
     * Determine if the baseUrl should be prepended, and prepend if necessary
     *
     * @param  string $url
     * @return string
     */
    protected function _prependBase($url)
    {
        if ($this->getPrependBase()) {
            $request = $this->getRequest();
            if ($request instanceof Zend_Controller_Request_Http) {
                $base = rtrim($request->getBaseUrl(), '/');
                if (!empty($base) && ('/' != $base)) {
                    $url = $base . '/' . ltrim($url, '/');
                } else {
                    $url = '/' . ltrim($url, '/');
                }
            }
        }

        return $url;
    }

    /**
     * Set a redirect URL of the form /module/controller/action/params
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module
     * @param  array  $params
     * @return void
     */
    public function setGotoSimple($action, $controller = null, $module = null, array $params = array())
    {
        $dispatcher = $this->getFrontController()->getDispatcher();
        $request    = $this->getRequest();
        $curModule  = $request->getModuleName();
        $useDefaultController = false;

        if (null === $controller && null !== $module) {
            $useDefaultController = true;
        }

        if (null === $module) {
            $module = $curModule;
        }

        if ($module == $dispatcher->getDefaultModule()) {
            $module = '';
        }

        if (null === $controller && !$useDefaultController) {
            $controller = $request->getControllerName();
            if (empty($controller)) {
                $controller = $dispatcher->getDefaultControllerName();
            }
        }

        $params[$request->getModuleKey()]     = $module;
        $params[$request->getControllerKey()] = $controller;
        $params[$request->getActionKey()]     = $action;

        $router = $this->getFrontController()->getRouter();
        $url    = $router->assemble($params, 'default', true);

        $this->_redirect($url);
    }

    /**
     * Build a URL based on a route
     *
     * @param  array   $urlOptions
     * @param  string  $name Route name
     * @param  boolean $reset
     * @param  boolean $encode
     * @return void
     */
    public function setGotoRoute(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
    {
        $router = $this->getFrontController()->getRouter();
        $url    = $router->assemble($urlOptions, $name, $reset, $encode);

        $this->_redirect($url);
    }

    /**
     * Set a redirect URL string
     *
     * By default, emits a 302 HTTP status header, prepends base URL as defined
     * in request object if url is relative, and halts script execution by
     * calling exit().
     *
     * $options is an optional associative array that can be used to control
     * redirect behaviour. The available option keys are:
     * - exit: boolean flag indicating whether or not to halt script execution when done
     * - prependBase: boolean flag indicating whether or not to prepend the base URL when a relative URL is provided
     * - code: integer HTTP status code to use with redirect. Should be between 300 and 307.
     *
     * _redirect() sets the Location header in the response object. If you set
     * the exit flag to false, you can override this header later in code
     * execution.
     *
     * If the exit flag is true (true by default), _redirect() will write and
     * close the current session, if any.
     *
     * @param  string $url
     * @param  array  $options
     * @return void
     */
    public function setGotoUrl($url, array $options = array())
    {
        // prevent header injections
        $url = str_replace(array("\n", "\r"), '', $url);

        if (null !== $options) {
            if (isset($options['exit'])) {
                $this->setExit(($options['exit']) ? true : false);
            }
            if (isset($options['prependBase'])) {
                $this->setPrependBase(($options['prependBase']) ? true : false);
            }
            if (isset($options['code'])) {
                $this->setCode($options['code']);
            }
        }

        // If relative URL, decide if we should prepend base URL
        if (!preg_match('|^[a-z]+://|', $url)) {
            $url = $this->_prependBase($url);
        }

        $this->_redirect($url);
    }

    /**
     * Perform a redirect to an action/controller/module with params
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module
     * @param  array  $params
     * @return void
     */
    public function gotoSimple($action, $controller = null, $module = null, array $params = array())
    {
        $this->setGotoSimple($action, $controller, $module, $params);

        if ($this->getExit()) {
            $this->redirectAndExit();
        }
    }

    /**
     * Perform a redirect to an action/controller/module with params, forcing an immdiate exit
     *
     * @param  mixed $action
     * @param  mixed $controller
     * @param  mixed $module
     * @param  array $params
     * @return void
     */
    public function gotoSimpleAndExit($action, $controller = null, $module = null, array $params = array())
    {
        $this->setGotoSimple($action, $controller, $module, $params);
        $this->redirectAndExit();
    }

    /**
     * Redirect to a route-based URL
     *
     * Uses route's assemble method to build the URL; route is specified by $name;
     * default route is used if none provided.
     *
     * @param  array   $urlOptions Array of key/value pairs used to assemble URL
     * @param  string  $name
     * @param  boolean $reset
     * @param  boolean $encode
     * @return void
     */
    public function gotoRoute(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
    {
        $this->setGotoRoute($urlOptions, $name, $reset, $encode);

        if ($this->getExit()) {
            $this->redirectAndExit();
        }
    }

    /**
     * Redirect to a route-based URL, and immediately exit
     *
     * Uses route's assemble method to build the URL; route is specified by $name;
     * default route is used if none provided.
     *
     * @param  array   $urlOptions Array of key/value pairs used to assemble URL
     * @param  string  $name
     * @param  boolean $reset
     * @return void
     */
    public function gotoRouteAndExit(array $urlOptions = array(), $name = null, $reset = false)
    {
        $this->setGotoRoute($urlOptions, $name, $reset);
        $this->redirectAndExit();
    }

    /**
     * Perform a redirect to a url
     *
     * @param  string $url
     * @param  array  $options
     * @return void
     */
    public function gotoUrl($url, array $options = array())
    {
        $this->setGotoUrl($url, $options);

        if ($this->getExit()) {
            $this->redirectAndExit();
        }
    }

    /**
     * Set a URL string for a redirect, perform redirect, and immediately exit
     *
     * @param  string $url
     * @param  array  $options
     * @return void
     */
    public function gotoUrlAndExit($url, array $options = array())
    {
        $this->setGotoUrl($url, $options);
        $this->redirectAndExit();
    }

    /**
     * exit(): Perform exit for redirector
     *
     * @return void
     */
    public function redirectAndExit()
    {
        if ($this->getCloseSessionOnExit()) {
            // Close session, if started
            if (class_exists('Zend_Session', false) && Zend_Session::isStarted()) {
                Zend_Session::writeClose();
            } elseif (isset($_SESSION)) {
                session_write_close();
            }
        }

        $this->getResponse()->sendHeaders();
        exit();
    }

    /**
     * direct(): Perform helper when called as
     * $this->_helper->redirector($action, $controller, $module, $params)
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module
     * @param  array  $params
     * @return void
     */
    public function direct($action, $controller = null, $module = null, array $params = array())
    {
        $this->gotoSimple($action, $controller, $module, $params);
    }

    /**
     * Overloading
     *
     * Overloading for old 'goto', 'setGoto', and 'gotoAndExit' methods
     *
     * @param  string $method
     * @param  array $args
     * @return mixed
     * @throws Zend_Controller_Action_Exception for invalid methods
     */
    public function __call($method, $args)
    {
        $method = strtolower($method);
        if ('goto' == $method) {
            return call_user_func_array(array($this, 'gotoSimple'), $args);
        }
        if ('setgoto' == $method) {
            return call_user_func_array(array($this, 'setGotoSimple'), $args);
        }
        if ('gotoandexit' == $method) {
            return call_user_func_array(array($this, 'gotoSimpleAndExit'), $args);
        }

        throw new Zend_Controller_Action_Exception(sprintf('Invalid method "%s" called on redirector', $method));
    }
}