getServer()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 7

Duplication

Lines 7
Ratio 100 %

Importance

Changes 0
Metric Value
dl 7
loc 7
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
/**
4
 * Nexcess.net Turpentine Extension for Magento
5
 * Copyright (C) 2012  Nexcess.net L.L.C.
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 2 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License along
18
 * with this program; if not, write to the Free Software Foundation, Inc.,
19
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
 */
21
22
class Nexcessnet_Turpentine_Model_Dummy_Request extends
23
    Mage_Core_Controller_Request_Http {
24
25
    public $GET         = null;
26
    public $POST        = null;
27
    public $SERVER      = null;
28
    public $ENV         = null;
29
30
    /**
31
     * Constructor
32
     *
33
     * If a $uri is passed, the object will attempt to populate itself using
34
     * that information.
35
     *
36
     * @param string|Zend_Uri $uri
37
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
38
     * @throws Zend_Controller_Request_Exception when invalid URI passed
39
     */
40
    public function __construct($uri = null) {
41
        $this->_initFakeSuperGlobals();
42
        $this->_fixupFakeSuperGlobals($uri);
43
        try {
44
            parent::__construct($uri);
45
        } catch (Exception $e) {
46
            Mage::helper('turpentine/debug')
47
                ->logError('Bad URI given to dummy request: '.$uri);
48
            Mage::helper('turpentine/debug')
49
                ->logBackTrace();
50
            Mage::logException($e);
51
            if (Mage::helper('turpentine/esi')->getEsiDebugEnabled()) {
52
                throw $e;
53
            }
54
        }
55
    }
56
57
    /**
58
     * Access values contained in the superglobals as public members
59
     * Order of precedence: 1. GET, 2. POST, 3. COOKIE, 4. SERVER, 5. ENV
60
     *
61
     * @see http://msdn.microsoft.com/en-us/library/system.web.httprequest.item.aspx
62
     * @param string $key
63
     * @return mixed
64
     */
65
    public function __get($key) {
66
        switch (true) {
67
            case isset($this->_params[$key]):
68
                return $this->_params[$key];
69
            case isset($this->GET[$key]):
70
                return $this->GET[$key];
71
            case isset($this->POST[$key]):
72
                return $this->POST[$key];
73
            case isset($_COOKIE[$key]):
74
                return $_COOKIE[$key];
75
            case ($key == 'REQUEST_URI'):
76
                return $this->getRequestUri();
77
            case ($key == 'PATH_INFO'):
78
                return $this->getPathInfo();
79
            case isset($this->SERVER[$key]):
80
                return $this->SERVER[$key];
81
            case isset($this->ENV[$key]):
82
                return $this->ENV[$key];
83
            default:
84
                return null;
85
        }
86
    }
87
88
    /**
89
     * Check to see if a property is set
90
     *
91
     * @param string $key
92
     * @return boolean
93
     */
94
    public function __isset($key) {
95
        switch (true) {
96
            case isset($this->_params[$key]):
97
                return true;
98
            case isset($this->GET[$key]):
99
                return true;
100
            case isset($this->POST[$key]):
101
                return true;
102
            case isset($_COOKIE[$key]):
103
                return true;
104
            case isset($this->SERVER[$key]):
105
                return true;
106
            case isset($this->ENV[$key]):
107
                return true;
108
            default:
109
                return false;
110
        }
111
    }
112
113
    /**
114
     * Set GET values
115
     *
116
     * @param  string|array $spec
117
     * @param  null|mixed $value
118
     * @return Zend_Controller_Request_Http
119
     */
120
    public function setQuery($spec, $value = null) {
121
        if ((null === $value) && ! is_array($spec)) {
122
            #require_once 'Zend/Controller/Exception.php';
123
            throw new Zend_Controller_Exception('Invalid value passed to setQuery(); must be either array of values or key/value pair');
124
        }
125
        if ((null === $value) && is_array($spec)) {
126
            foreach ($spec as $key => $value) {
127
                $this->setQuery($key, $value);
128
            }
129
            return $this;
130
        }
131
        $this->GET[(string) $spec] = $value;
132
        return $this;
133
    }
134
135
    /**
136
     * Retrieve a member of the $_GET superglobal
137
     *
138
     * If no $key is passed, returns the entire $_GET array.
139
     *
140
     * @todo How to retrieve from nested arrays
141
     * @param string $key
142
     * @param mixed $default Default value to use if key not found
143
     * @return mixed Returns null if key does not exist
144
     */
145
    public function getQuery($key = null, $default = null) {
146
        if (null === $key) {
147
            return $this->GET;
148
        }
149
        return (isset($this->GET[$key])) ? $this->GET[$key] : $default;
150
    }
151
152
    /**
153
     * Retrieve a member of the $_POST superglobal
154
     *
155
     * If no $key is passed, returns the entire $_POST array.
156
     *
157
     * @todo How to retrieve from nested arrays
158
     * @param string $key
159
     * @param mixed $default Default value to use if key not found
160
     * @return mixed Returns null if key does not exist
161
     */
162 View Code Duplication
    public function getPost($key = null, $default = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
163
        if (null === $key) {
164
            return $this->POST;
165
        }
166
167
        return (isset($this->POST[$key])) ? $this->POST[$key] : $default;
168
    }
169
170
    /**
171
     * Retrieve a member of the $_SERVER superglobal
172
     *
173
     * If no $key is passed, returns the entire $_SERVER array.
174
     *
175
     * @param string $key
176
     * @param mixed $default Default value to use if key not found
177
     * @return mixed Returns null if key does not exist
178
     */
179 View Code Duplication
    public function getServer($key = null, $default = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180
        if (null === $key) {
181
            return $this->SERVER;
182
        }
183
184
        return (isset($this->SERVER[$key])) ? $this->SERVER[$key] : $default;
185
    }
186
187
    /**
188
     * Retrieve a member of the $_ENV superglobal
189
     *
190
     * If no $key is passed, returns the entire $_ENV array.
191
     *
192
     * @param string $key
193
     * @param mixed $default Default value to use if key not found
194
     * @return mixed Returns null if key does not exist
195
     */
196 View Code Duplication
    public function getEnv($key = null, $default = null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
197
        if (null === $key) {
198
            return $this->ENV;
199
        }
200
201
        return (isset($this->ENV[$key])) ? $this->ENV[$key] : $default;
202
    }
203
204
    /**
205
     * Return the value of the given HTTP header. Pass the header name as the
206
     * plain, HTTP-specified header name. Ex.: Ask for 'Accept' to get the
207
     * Accept header, 'Accept-Encoding' to get the Accept-Encoding header.
208
     *
209
     * @param string $header HTTP header name
210
     * @return string|false HTTP header value, or false if not found
211
     * @throws Zend_Controller_Request_Exception
212
     */
213
    public function getHeader($header) {
214
        if (empty($header)) {
215
            #require_once 'Zend/Controller/Request/Exception.php';
216
            throw new Zend_Controller_Request_Exception('An HTTP header name is required');
217
        }
218
219
        // Try to get it from the $_SERVER array first
220
        $temp = 'HTTP_'.strtoupper(str_replace('-', '_', $header));
221
        if (isset($this->SERVER[$temp])) {
222
            return $this->SERVER[$temp];
223
        }
224
225
        // This seems to be the only way to get the Authorization header on
226
        // Apache
227
        if (function_exists('apache_request_headers')) {
228
            $headers = apache_request_headers();
229
            if (isset($headers[$header])) {
230
                return $headers[$header];
231
            }
232
            $header = strtolower($header);
233
            foreach ($headers as $key => $value) {
234
                if (strtolower($key) == $header) {
235
                    return $value;
236
                }
237
            }
238
        }
239
240
        return false;
241
    }
242
243
    /**
244
     * Set the REQUEST_URI on which the instance operates
245
     *
246
     * If no request URI is passed, uses the value in $_SERVER['REQUEST_URI'],
247
     * $_SERVER['HTTP_X_REWRITE_URL'], or $_SERVER['ORIG_PATH_INFO'] + $_SERVER['QUERY_STRING'].
248
     *
249
     * @param string $requestUri
250
     * @return Zend_Controller_Request_Http
251
     */
252
    public function setRequestUri($requestUri = null) {
253
        if ($requestUri === null) {
254
            if (isset($this->SERVER['HTTP_X_REWRITE_URL'])) { // check this first so IIS will catch
255
                $requestUri = $this->SERVER['HTTP_X_REWRITE_URL'];
256
            } elseif (
257
                // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
258
                isset($this->SERVER['IIS_WasUrlRewritten'])
259
                && $this->SERVER['IIS_WasUrlRewritten'] == '1'
260
                && isset($this->SERVER['UNENCODED_URL'])
261
                && $this->SERVER['UNENCODED_URL'] != ''
262
                ) {
263
                $requestUri = $this->SERVER['UNENCODED_URL'];
264
            } elseif (isset($this->SERVER['REQUEST_URI'])) {
265
                $requestUri = $this->SERVER['REQUEST_URI'];
266
                // Http proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
267
                $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
268
                if (strpos($requestUri, $schemeAndHttpHost) === 0) {
269
                    $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
270
                }
271
            } elseif (isset($this->SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI
272
                $requestUri = $this->SERVER['ORIG_PATH_INFO'];
273
                if ( ! empty($this->SERVER['QUERY_STRING'])) {
274
                    $requestUri .= '?'.$this->SERVER['QUERY_STRING'];
275
                }
276
            } else {
277
                return $this;
278
            }
279
        } elseif ( ! is_string($requestUri)) {
280
            return $this;
281
        } else {
282
            // Set GET items, if available
283
            if (false !== ($pos = strpos($requestUri, '?'))) {
284
                // Get key => value pairs and set $_GET
285
                $query = substr($requestUri, $pos + 1);
286
                parse_str($query, $vars);
287
                $this->setQuery($vars);
288
            }
289
        }
290
291
        $this->_requestUri = $requestUri;
292
        return $this;
293
    }
294
295
    /**
296
     * Set the base URL of the request; i.e., the segment leading to the script name
297
     *
298
     * E.g.:
299
     * - /admin
300
     * - /myapp
301
     * - /subdir/index.php
302
     *
303
     * Do not use the full URI when providing the base. The following are
304
     * examples of what not to use:
305
     * - http://example.com/admin (should be just /admin)
306
     * - http://example.com/subdir/index.php (should be just /subdir/index.php)
307
     *
308
     * If no $baseUrl is provided, attempts to determine the base URL from the
309
     * environment, using SCRIPT_FILENAME, SCRIPT_NAME, PHP_SELF, and
310
     * ORIG_SCRIPT_NAME in its determination.
311
     *
312
     * @param mixed $baseUrl
313
     * @return Zend_Controller_Request_Http
314
     */
315
    public function setBaseUrl($baseUrl = null) {
316
        if ((null !== $baseUrl) && ! is_string($baseUrl)) {
317
            return $this;
318
        }
319
320
        if ($baseUrl === null) {
321
            $filename = (isset($this->SERVER['SCRIPT_FILENAME'])) ? basename($this->SERVER['SCRIPT_FILENAME']) : '';
322
323
            if (isset($this->SERVER['SCRIPT_NAME']) && basename($this->SERVER['SCRIPT_NAME']) === $filename) {
324
                $baseUrl = $this->SERVER['SCRIPT_NAME'];
325
            } elseif (isset($this->SERVER['PHP_SELF']) && basename($this->SERVER['PHP_SELF']) === $filename) {
326
                $baseUrl = $this->SERVER['PHP_SELF'];
327
            } elseif (isset($this->SERVER['ORIG_SCRIPT_NAME']) && basename($this->SERVER['ORIG_SCRIPT_NAME']) === $filename) {
328
                $baseUrl = $this->SERVER['ORIG_SCRIPT_NAME']; // 1and1 shared hosting compatibility
329
            } else {
330
                // Backtrack up the script_filename to find the portion matching
331
                // php_self
332
                $path    = isset($this->SERVER['PHP_SELF']) ? $this->SERVER['PHP_SELF'] : '';
333
                $file    = isset($this->SERVER['SCRIPT_FILENAME']) ? $this->SERVER['SCRIPT_FILENAME'] : '';
334
                $segs    = explode('/', trim($file, '/'));
335
                $segs    = array_reverse($segs);
336
                $index   = 0;
337
                $last    = count($segs);
338
                $baseUrl = '';
339
                do {
340
                    $seg     = $segs[$index];
341
                    $baseUrl = '/'.$seg.$baseUrl;
342
                    ++$index;
343
                } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
344
            }
345
346
            // Does the baseUrl have anything in common with the request_uri?
347
            $requestUri = $this->getRequestUri();
348
349
            if (0 === strpos($requestUri, $baseUrl)) {
350
                // full $baseUrl matches
351
                $this->_baseUrl = $baseUrl;
352
                return $this;
353
            }
354
355
            if (0 === strpos($requestUri, dirname($baseUrl))) {
356
                // directory portion of $baseUrl matches
357
                $this->_baseUrl = rtrim(dirname($baseUrl), '/');
358
                return $this;
359
            }
360
361
            $truncatedRequestUri = $requestUri;
362
            if (($pos = strpos($requestUri, '?')) !== false) {
363
                $truncatedRequestUri = substr($requestUri, 0, $pos);
364
            }
365
366
            $basename = basename($baseUrl);
367
            if (empty($basename) || ! strpos($truncatedRequestUri, $basename)) {
368
                // no match whatsoever; set it blank
369
                $this->_baseUrl = '';
370
                return $this;
371
            }
372
373
            // If using mod_rewrite or ISAPI_Rewrite strip the script filename
374
            // out of baseUrl. $pos !== 0 makes sure it is not matching a value
375
            // from PATH_INFO or QUERY_STRING
376
            if ((strlen($requestUri) >= strlen($baseUrl))
377
                && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0)))
378
            {
379
                $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
380
            }
381
        }
382
383
        $this->_baseUrl = rtrim($baseUrl, '/');
384
        return $this;
385
    }
386
387
    /**
388
     * Set the base path for the URL
389
     *
390
     * @param string|null $basePath
391
     * @return Zend_Controller_Request_Http
392
     */
393
    public function setBasePath($basePath = null) {
394
        if ($basePath === null) {
395
            $filename = (isset($this->SERVER['SCRIPT_FILENAME']))
396
                      ? basename($this->SERVER['SCRIPT_FILENAME'])
397
                      : '';
398
399
            $baseUrl = $this->getBaseUrl();
400
            if (empty($baseUrl)) {
401
                $this->_basePath = '';
402
                return $this;
403
            }
404
405
            if (basename($baseUrl) === $filename) {
406
                $basePath = dirname($baseUrl);
407
            } else {
408
                $basePath = $baseUrl;
409
            }
410
        }
411
412
        if (substr(PHP_OS, 0, 3) === 'WIN') {
413
            $basePath = str_replace('\\', '/', $basePath);
414
        }
415
416
        $this->_basePath = rtrim($basePath, '/');
417
        return $this;
418
    }
419
420
    /**
421
     * Retrieve a parameter
422
     *
423
     * Retrieves a parameter from the instance. Priority is in the order of
424
     * userland parameters (see {@link setParam()}), $_GET, $_POST. If a
425
     * parameter matching the $key is not found, null is returned.
426
     *
427
     * If the $key is an alias, the actual key aliased will be used.
428
     *
429
     * @param mixed $key
430
     * @param mixed $default Default value to use if key not found
431
     * @return mixed
432
     */
433
    public function getParam($key, $default = null) {
434
        $keyName = (null !== ($alias = $this->getAlias($key))) ? $alias : $key;
435
436
        $paramSources = $this->getParamSources();
437
        if (isset($this->_params[$keyName])) {
438
            return $this->_params[$keyName];
439
        } elseif (in_array('_GET', $paramSources) && (isset($this->GET[$keyName]))) {
440
            return $this->GET[$keyName];
441
        } elseif (in_array('_POST', $paramSources) && (isset($this->POST[$keyName]))) {
442
            return $this->POST[$keyName];
443
        }
444
445
        return $default;
446
    }
447
448
    /**
449
     * Retrieve an array of parameters
450
     *
451
     * Retrieves a merged array of parameters, with precedence of userland
452
     * params (see {@link setParam()}), $_GET, $_POST (i.e., values in the
453
     * userland params will take precedence over all others).
454
     *
455
     * @return array
456
     */
457
    public function getParams() {
458
        $return       = $this->_params;
459
        $paramSources = $this->getParamSources();
460 View Code Duplication
        if (in_array('_GET', $paramSources)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
461
            && isset($this->GET)
462
            && is_array($this->GET)
463
        ) {
464
            $return += $this->GET;
465
        }
466 View Code Duplication
        if (in_array('_POST', $paramSources)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
467
            && isset($this->POST)
468
            && is_array($this->POST)
469
        ) {
470
            $return += $this->POST;
471
        }
472
        return $return;
473
    }
474
475
    /**
476
     * Retrieve HTTP HOST
477
     *
478
     * @param bool $trimPort
479
     * @return string
480
     */
481
    public function getHttpHost($trimPort = true) {
482
        if ( ! isset($this->SERVER['HTTP_HOST'])) {
483
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Nexcessnet_Turpentine_Mo...my_Request::getHttpHost of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
484
        }
485
        if ($trimPort) {
486
            $host = explode(':', $this->SERVER['HTTP_HOST']);
487
            return $host[0];
488
        }
489
        return $this->SERVER['HTTP_HOST'];
490
    }
491
492
    /**
493
     * Set a member of the $_POST superglobal
494
     *
495
     * @param string|array $key
496
     * @param mixed $value
497
     *
498
     * @return Mage_Core_Controller_Request_Http
499
     */
500
    public function setPost($key, $value = null) {
501
        if (is_array($key)) {
502
            $this->POST = $key;
503
        } else {
504
            $this->POST[$key] = $value;
505
        }
506
        return $this;
507
    }
508
509
    /**
510
     * Init the fake superglobal vars
511
     *
512
     * @return null
513
     */
514
    protected function _initFakeSuperGlobals() {
515
        $this->GET = array();
516
        $this->POST = $_POST;
517
        $this->SERVER = $_SERVER;
518
        $this->ENV = $_ENV;
519
    }
520
521
    /**
522
     * Fix up the fake superglobal vars
523
     *
524
     * @param  string $uri
525
     * @return null
526
     */
527
    protected function _fixupFakeSuperGlobals($uri) {
528
        $uri = str_replace('|', urlencode('|'), $uri);
529
        $parsedUrl = parse_url($uri);
530
531
        if (isset($parsedUrl['path'])) {
532
            $this->SERVER['REQUEST_URI'] = $parsedUrl['path'];
533
        }
534
        if (isset($parsedUrl['query']) && $parsedUrl['query']) {
535
            $this->SERVER['QUERY_STRING'] = $parsedUrl['query'];
536
            $this->SERVER['REQUEST_URI'] .= '?'.$this->SERVER['QUERY_STRING'];
537
        } else {
538
            $this->SERVER['QUERY_STRING'] = null;
539
        }
540
        parse_str($this->SERVER['QUERY_STRING'], $this->GET);
541
        if (isset($this->SERVER['SCRIPT_URI'])) {
542
            $start = strpos($this->SERVER['SCRIPT_URI'], '/', 9);
543
            $sub = substr($this->SERVER['SCRIPT_URI'], $start);
544
            $this->SERVER['SCRIPT_URI'] = substr(
545
                    $this->SERVER['SCRIPT_URI'], 0, $start ).
546
                @str_replace(
547
                    $this->SERVER['SCRIPT_URL'], $parsedUrl['path'],
548
                    $sub, $c = 1 );
0 ignored issues
show
Bug introduced by
$c = 1 cannot be passed to str_replace() as the parameter $count expects a reference.
Loading history...
549
        }
550
        if (isset($this->SERVER['SCRIPT_URL'])) {
551
            $this->SERVER['SCRIPT_URL'] = $parsedUrl['path'];
552
        }
553
    }
554
555
    /**
556
     * Check this request against the cms, standard, and default routers to fill
557
     * the module/controller/action/route fields.
558
     *
559
     * TODO: This whole thing is a gigantic hack. Would be nice to have a
560
     * better solution.
561
     *
562
     * @return null
563
     */
564
    public function fakeRouterDispatch() {
565
        if ($this->_cmsRouterMatch()) {
566
            Mage::helper('turpentine/debug')->logDebug('Matched router: cms');
567
        } elseif ($this->_standardRouterMatch()) {
568
            Mage::helper('turpentine/debug')->logDebug('Matched router: standard');
569
        } elseif ($this->_defaultRouterMatch()) {
570
            Mage::helper('turpentine/debug')->logDebug('Matched router: default');
571
        } else {
572
            Mage::helper('turpentine/debug')->logDebug('No router match');
573
        }
574
    }
575
576
    /**
577
     *
578
     *
579
     * @return boolean
580
     */
581
    protected function _defaultRouterMatch() {
582
        $noRoute        = explode('/', Mage::app()->getStore()->getConfig('web/default/no_route'));
583
        $moduleName     = isset($noRoute[0]) ? $noRoute[0] : 'core';
584
        $controllerName = isset($noRoute[1]) ? $noRoute[1] : 'index';
585
        $actionName     = isset($noRoute[2]) ? $noRoute[2] : 'index';
586
587
        if (Mage::app()->getStore()->isAdmin()) {
588
            $adminFrontName = (string) Mage::getConfig()->getNode('admin/routers/adminhtml/args/frontName');
589
            if ($adminFrontName != $moduleName) {
590
                $moduleName     = 'core';
591
                $controllerName = 'index';
592
                $actionName     = 'noRoute';
593
                Mage::app()->setCurrentStore(Mage::app()->getDefaultStoreView());
594
            }
595
        }
596
597
        $this->setModuleName($moduleName)
598
            ->setControllerName($controllerName)
599
            ->setActionName($actionName);
600
601
        return true;
602
    }
603
604
    /**
605
     *
606
     *
607
     * @return bool
608
     */
609
    protected function _standardRouterMatch() {
610
        $router = Mage::app()->getFrontController()->getRouter('standard');
611
612
        // $router->fetchDefault();
613
614
        $front = $router->getFront();
615
        $path = trim($this->getPathInfo(), '/');
616
617
        if ($path) {
618
            $p = explode('/', $path);
619
        } else {
620
            // was $router->_getDefaultPath()
621
            $p = explode('/', Mage::getStoreConfig('web/default/front'));
622
        }
623
624
        // get module name
625 View Code Duplication
        if ($this->getModuleName()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
626
            $module = $this->getModuleName();
627
        } else {
628
            if ( ! empty($p[0])) {
629
                $module = $p[0];
630
            } else {
631
                $module = $router->getFront()->getDefault('module');
632
                $this->setAlias(Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS, '');
633
            }
634
        }
635
        if ( ! $module) {
636
            if (Mage::app()->getStore()->isAdmin()) {
637
                $module = 'admin';
638
            } else {
639
                return false;
640
            }
641
        }
642
643
        /**
644
         * Searching router args by module name from route using it as key
645
         */
646
        $modules = $router->getModuleByFrontName($module);
647
648
        if ($modules === false) {
649
            return false;
650
        }
651
652
        /**
653
         * Going through modules to find appropriate controller
654
         */
655
        $found = false;
656
        foreach ($modules as $realModule) {
657
            $this->setRouteName($router->getRouteByFrontName($module));
658
659
            // get controller name
660 View Code Duplication
            if ($this->getControllerName()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
661
                $controller = $this->getControllerName();
662
            } else {
663
                if ( ! empty($p[1])) {
664
                    $controller = $p[1];
665
                } else {
666
                    $controller = $front->getDefault('controller');
667
                    $this->setAlias(
668
                        Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,
669
                        ltrim($this->getOriginalPathInfo(), '/')
670
                    );
671
                }
672
            }
673
674
            // get action name
675
            if (empty($action)) {
676
                if ($this->getActionName()) {
677
                    $action = $this->getActionName();
678
                } else {
679
                    $action = ! empty($p[2]) ? $p[2] : $front->getDefault('action');
680
                }
681
            }
682
683
            //checking if this place should be secure
684
            // $router->_checkShouldBeSecure($this, '/'.$module.'/'.$controller.'/'.$action);
685
686
            // $controllerClassName = $router->_validateControllerClassName($realModule, $controller);
687
            $controllerClassName = $router->getControllerClassName($realModule, $controller);
688
            if ( ! $controllerClassName) {
689
                continue;
690
            } else {
691
                $controllerFileName = $router->getControllerFileName($realModule, $controller);
692
                if ( ! $router->validateControllerFileName($controllerFileName)) {
693
                    return false;
694
                }
695
                if ( ! class_exists($controllerClassName, false)) {
696
                    if ( ! file_exists($controllerFileName)) {
697
                        return false;
698
                    }
699
                    include_once $controllerFileName;
700
701
                    if ( ! class_exists($controllerClassName, false)) {
702
                        throw Mage::exception('Mage_Core', Mage::helper('core')->__('Controller file was loaded but class does not exist'));
703
                    }
704
                }
705
            }
706
707
            // instantiate controller class
708
            $controllerInstance = Mage::getControllerInstance($controllerClassName, $this, $front->getResponse());
709
710
            if ( ! $controllerInstance->hasAction($action)) {
711
                continue;
712
            }
713
714
            $found = true;
715
            break;
716
        }
717
718
        /**
719
         * if we did not found any suitable
720
         */
721
        if ( ! $found) {
722
            /*
723
            if ($router->_noRouteShouldBeApplied()) {
724
                $controller = 'index';
725
                $action = 'noroute';
726
727
                $controllerClassName = $router->_validateControllerClassName($realModule, $controller);
728
                if (!$controllerClassName) {
729
                    return false;
730
                }
731
732
                // instantiate controller class
733
                $controllerInstance = Mage::getControllerInstance($controllerClassName, $this,
734
                    $front->getResponse());
735
736
                if (!$controllerInstance->hasAction($action)) {
737
                    return false;
738
                }
739
            } else {
740
                return false;
741
            }
742
            */
743
            return false;
744
        }
745
746
        // set values only after all the checks are done
747
        $this->setModuleName($module);
748
        $this->setControllerName($controller);
0 ignored issues
show
Bug introduced by
The variable $controller does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
749
        $this->setActionName($action);
0 ignored issues
show
Bug introduced by
The variable $action does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
750
        $this->setControllerModule($realModule);
0 ignored issues
show
Bug introduced by
The variable $realModule seems to be defined by a foreach iteration on line 656. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
751
752
        // set parameters from pathinfo
753
        for ($i = 3, $l = sizeof($p); $i < $l; $i += 2) {
754
            $this->setParam($p[$i], isset($p[$i + 1]) ? urldecode($p[$i + 1]) : '');
755
        }
756
757
        // dispatch action
758
        $this->setDispatched(true);
759
        // $controllerInstance->dispatch($action);
760
761
        return true;
762
    }
763
764
    /**
765
     *
766
     *
767
     * @return bool
768
     */
769
    protected function _cmsRouterMatch() {
770
        $router = Mage::app()->getFrontController()->getRouter('cms');
771
772
        $identifier = trim($this->getPathInfo(), '/');
773
774
        $condition = new Varien_Object(array(
775
            'identifier' => $identifier,
776
            'continue'   => true
777
        ));
778
        Mage::dispatchEvent('cms_controller_router_match_before', array(
779
            'router'    => $router,
780
            'condition' => $condition
781
        ));
782
        $identifier = $condition->getIdentifier();
783
784
        if ($condition->getRedirectUrl()) {
785
            Mage::app()->getFrontController()->getResponse()
786
                ->setRedirect($condition->getRedirectUrl())
787
                ->sendResponse();
788
            $this->setDispatched(true);
789
            return true;
790
        }
791
792
        if ( ! $condition->getContinue()) {
793
            return false;
794
        }
795
796
        $page   = Mage::getModel('cms/page');
797
        $pageId = $page->checkIdentifier($identifier, Mage::app()->getStore()->getId());
798
        if ( ! $pageId) {
799
            return false;
800
        }
801
802
        $this->setModuleName('cms')
803
            ->setControllerName('page')
804
            ->setActionName('view')
805
            ->setParam('page_id', $pageId);
806
        $this->setAlias(
807
            Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,
808
            $identifier
809
        );
810
811
        return true;
812
    }
813
}
814