Completed
Push — master ( 186d9b...7aa9e4 )
by Richard
14s
created

Request::getVar()   C

Complexity

Conditions 11
Paths 42

Size

Total Lines 47
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 16.4042

Importance

Changes 0
Metric Value
cc 11
eloc 34
nc 42
nop 5
dl 0
loc 47
rs 5.2653
c 0
b 0
f 0
ccs 20
cts 31
cp 0.6452
crap 16.4042

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 */
11
12
namespace Xmf;
13
14
use Xoops\Core\Locale\Time;
15
16
/**
17
 * Request Class
18
 *
19
 * This class serves to provide a common interface to access
20
 * request variables.  This includes $_POST, $_GET, and naturally $_REQUEST.  Variables
21
 * can be passed through an input filter to avoid injection or returned raw.
22
 *
23
 * @category  Xmf\Request
24
 * @package   Xmf
25
 * @author    Richard Griffith <[email protected]>
26
 * @author    trabis <[email protected]>
27
 * @author    Joomla!
28
 * @copyright 2011-2016 XOOPS Project (http://xoops.org)
29
 * @license   GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
30
 * @link      http://xoops.org
31
 */
32
class Request
33
{
34
    /**
35
     * Available masks for cleaning variables
36
     */
37
    const MASK_NO_TRIM    = 1;
38
    const MASK_ALLOW_RAW  = 2;
39
    const MASK_ALLOW_HTML = 4;
40
41
    /**
42
     * Gets the request method
43
     *
44
     * @return string
45
     */
46 2
    public static function getMethod()
47
    {
48 2
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
49
50 2
        return $method;
51
    }
52
53
    /**
54
     * Fetches and returns a given variable.
55
     *
56
     * The default behaviour is fetching variables depending on the
57
     * current request method: GET and HEAD will result in returning
58
     * an entry from $_GET, POST and PUT will result in returning an
59
     * entry from $_POST.
60
     *
61
     * You can force the source by setting the $hash parameter:
62
     *
63
     *  - post       $_POST
64
     *  - get        $_GET
65
     *  - files      $_FILES
66
     *  - cookie     $_COOKIE
67
     *  - env        $_ENV
68
     *  - server     $_SERVER
69
     *  - method     via current $_SERVER['REQUEST_METHOD']
70
     *  - default    $_REQUEST
71
     *
72
     * @param string $name    Variable name
73
     * @param mixed  $default Default value if the variable does not exist
74
     * @param string $hash    Source of variable value (POST, GET, FILES, COOKIE, METHOD)
75
     * @param string $type    Return type for the variable (INT, FLOAT, BOOLEAN, WORD,
76
     *                         ALPHANUM, CMD, BASE64, STRING, ARRAY, PATH, NONE) For more
77
     *                         information see FilterInput::clean().
78
     * @param int    $mask    Filter mask for the variable
79
     *
80
     * @return mixed Requested variable
81
     */
82 28
    public static function getVar($name, $default = null, $hash = 'default', $type = 'none', $mask = 0)
83
    {
84
        // Ensure hash and type are uppercase
85 28
        $hash = strtoupper($hash);
86 28
        if ($hash === 'METHOD') {
87
            $hash = static::getMethod();
88
        }
89 28
        $type = strtoupper($type);
90
91
        // Get the input hash
92
        switch ($hash) {
93 28
            case 'GET':
94
                $input = &$_GET;
95
                break;
96 28
            case 'POST':
97 4
                $input = &$_POST;
98 4
                break;
99 24
            case 'FILES':
100
                $input = &$_FILES;
101
                break;
102 24
            case 'COOKIE':
103
                $input = &$_COOKIE;
104
                break;
105 24
            case 'ENV':
106
                $input = &$_ENV;
107
                break;
108 24
            case 'SERVER':
109
                $input = &$_SERVER;
110
                break;
111
            default:
112 24
                $input = &$_REQUEST;
113 24
                break;
114
        }
115
116 28
        if (isset($input[$name]) && $input[$name] !== null) {
117
            // Get the variable from the input hash and clean it
118 28
            $var = static::cleanVar($input[$name], $mask, $type);
119
        } else {
120 7
            if ($default !== null) {
121
                // Clean the default value
122 5
                $var = static::cleanVar($default, $mask, $type);
123
            } else {
124 2
                $var = $default;
125
            }
126
        }
127
128 28
        return $var;
129
    }
130
131
    /**
132
     * Fetches and returns a given filtered variable. The integer
133
     * filter will allow only digits to be returned. This is currently
134
     * only a proxy function for getVar().
135
     *
136
     * See getVar() for more in-depth documentation on the parameters.
137
     *
138
     * @param string $name    Variable name
139
     * @param int    $default Default value if the variable does not exist
140
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
141
     *
142
     * @return int Requested variable
143
     */
144 2
    public static function getInt($name, $default = 0, $hash = 'default')
145
    {
146 2
        return static::getVar($name, $default, $hash, 'int');
0 ignored issues
show
Bug Best Practice introduced by
The expression return static::getVar($n...$default, $hash, 'int') returns the type string which is incompatible with the documented return type integer.
Loading history...
147
    }
148
149
    /**
150
     * Fetches and returns a given filtered variable.  The float
151
     * filter only allows digits and periods.  This is currently
152
     * only a proxy function for getVar().
153
     *
154
     * See getVar() for more in-depth documentation on the parameters.
155
     *
156
     * @param string $name    Variable name
157
     * @param float  $default Default value if the variable does not exist
158
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
159
     *
160
     * @return float Requested variable
161
     */
162 2
    public static function getFloat($name, $default = 0.0, $hash = 'default')
163
    {
164 2
        return static::getVar($name, $default, $hash, 'float');
0 ignored issues
show
Bug Best Practice introduced by
The expression return static::getVar($n...efault, $hash, 'float') returns the type string which is incompatible with the documented return type double.
Loading history...
165
    }
166
167
    /**
168
     * Fetches and returns a given filtered variable. The bool
169
     * filter will only return true/false bool values. This is
170
     * currently only a proxy function for getVar().
171
     *
172
     * See getVar() for more in-depth documentation on the parameters.
173
     *
174
     * @param string $name    Variable name
175
     * @param bool   $default Default value if the variable does not exist
176
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
177
     *
178
     * @return bool Requested variable
179
     */
180 2
    public static function getBool($name, $default = false, $hash = 'default')
181
    {
182 2
        return static::getVar($name, $default, $hash, 'bool');
0 ignored issues
show
Bug Best Practice introduced by
The expression return static::getVar($n...default, $hash, 'bool') returns the type string which is incompatible with the documented return type boolean.
Loading history...
183
    }
184
185
    /**
186
     * Fetches and returns a given filtered variable. The word
187
     * filter only allows the characters [A-Za-z_]. This is currently
188
     * only a proxy function for getVar().
189
     *
190
     * See getVar() for more in-depth documentation on the parameters.
191
     *
192
     * @param string $name    Variable name
193
     * @param string $default Default value if the variable does not exist
194
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
195
     *
196
     * @return string Requested variable
197
     */
198 2
    public static function getWord($name, $default = '', $hash = 'default')
199
    {
200 2
        return static::getVar($name, $default, $hash, 'word');
201
    }
202
203
    /**
204
     * Fetches and returns a given filtered variable. The cmd filter only allows the characters
205
     * [A-Za-z0-9.-_] and returns in lower case. This is currently a proxy function for getVar().
206
     *
207
     * See getVar() for more in-depth documentation on the parameters.
208
     *
209
     * @param string $name    Variable name
210
     * @param string $default Default value if the variable does not exist
211
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
212
     *
213
     * @return string Requested variable
214
     */
215 2
    public static function getCmd($name, $default = '', $hash = 'default')
216
    {
217 2
        return static::getVar($name, $default, $hash, 'cmd');
218
    }
219
220
    /**
221
     * Fetches and returns a given filtered variable. The string
222
     * filter deletes 'bad' HTML code, if not overridden by the mask.
223
     * This is currently only a proxy function for getVar().
224
     *
225
     * See getVar() for more in-depth documentation on the parameters.
226
     *
227
     * @param string $name    Variable name
228
     * @param string $default Default value if the variable does not exist
229
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
230
     * @param int    $mask    Filter mask for the variable
231
     *
232
     * @return string Requested variable
233
     */
234 6
    public static function getString($name, $default = '', $hash = 'default', $mask = 0)
235
    {
236
        // Cast to string, in case static::MASK_ALLOW_RAW was specified for mask
237 6
        return (string) static::getVar($name, $default, $hash, 'string', $mask);
238
    }
239
240
    /**
241
     * Fetches and returns an array
242
     *
243
     * @param string $name    Variable name
244
     * @param mixed  $default Default value if the variable does not exist
245
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
246
     *
247
     * @return array
248
     */
249 2
    public static function getArray($name, $default = array(), $hash = 'default')
250
    {
251 2
        return static::getVar($name, $default, $hash, 'array');
0 ignored issues
show
Bug Best Practice introduced by
The expression return static::getVar($n...efault, $hash, 'array') also could return the type string which is incompatible with the documented return type array.
Loading history...
252
    }
253
254
    /**
255
     * Fetches and returns raw text
256
     *
257
     * @param string $name    Variable name
258
     * @param string $default Default value if the variable does not exist
259
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
260
     *
261
     * @return string Requested variable
262
     */
263 2
    public static function getText($name, $default = '', $hash = 'default')
264
    {
265 2
        return (string) static::getVar($name, $default, $hash, 'string', static::MASK_ALLOW_RAW);
266
    }
267
268
    /**
269
     * Fetches and returns a web url
270
     *
271
     * @param string $name    Variable name
272
     * @param string $default Default value if the variable does not exist
273
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
274
     *
275
     * @return string Requested variable
276
     */
277 1
    public static function getUrl($name, $default = '', $hash = 'default')
278
    {
279 1
        return (string) static::getVar($name, $default, $hash, 'weburl');
280
    }
281
282
    /**
283
     * Fetches and returns a file (or web) path
284
     *
285
     * @param string $name    Variable name
286
     * @param string $default Default value if the variable does not exist
287
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
288
     *
289
     * @return string Requested variable
290
     */
291 1
    public static function getPath($name, $default = '', $hash = 'default')
292
    {
293 1
        return (string) static::getVar($name, $default, $hash, 'path');
294
    }
295
296
    /**
297
     * Fetches and returns an email address
298
     *
299
     * @param string $name    Variable name
300
     * @param string $default Default value if the variable does not exist
301
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
302
     *
303
     * @return string email address or default if invalid
304
     */
305 1
    public static function getEmail($name, $default = '', $hash = 'default')
306
    {
307 1
        $ret = (string) static::getVar($name, $default, $hash, 'email');
308 1
        return empty($ret) ? $default : $ret;
309
    }
310
311
    /**
312
     * Fetches and returns an IP address
313
     *
314
     * @param string $name    Variable name
315
     * @param string $default Default value if the variable does not exist
316
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
317
     *
318
     * @return string IP address or default if invalid
319
     */
320 2
    public static function getIP($name, $default = '', $hash = 'default')
321
    {
322 2
        $ret = (string) static::getVar($name, $default, $hash, 'ip');
323 2
        return empty($ret) ? $default : $ret;
324
    }
325
326
    /**
327
     * Return a DateTime object from a Xoops\Form\DateSelect or Xoops\Form\DateTimeSelect field
328
     *
329
     * @param string $name    Variable name
330
     * @param mixed  $default Default value if the variable does not exist
331
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
332
     *
333
     * @return \DateTime object
334
     */
335 1
    public static function getDateTime($name, $default = null, $hash = 'default')
336
    {
337 1
        $values = self::getVar($name, [], $hash, 'array');
338 1
        $count = count($values);
0 ignored issues
show
Bug introduced by
$values of type string is incompatible with the type Countable|array expected by parameter $var of count(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

338
        $count = count(/** @scrutinizer ignore-type */ $values);
Loading history...
339 1
        if ($count === 1) {
340 1
            $date = reset($values);
0 ignored issues
show
Bug introduced by
$values of type string is incompatible with the type array expected by parameter $array of reset(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

340
            $date = reset(/** @scrutinizer ignore-type */ $values);
Loading history...
341 1
            $ret = (empty($date)) ? $default : Time::inputToDateTime($date);
342 1
        } elseif (isset($values['date']) && isset($values['time'])) {
343 1
            $ret = (empty($values['date'])) ? $default : Time::inputToDateTime($values);
344
        } else {
345
            $ret = $default;
346
        }
347 1
        return $ret;
348
    }
349
350
    /**
351
     * get request header
352
     *
353
     * @param string      $headerName name of header to retrieve, case insensitive
354
     * @param string|null $default    default to return if named header is not found
355
     *
356
     * @return string header value or default if header was not found
357
     */
358
    public static function getHeader($headerName, $default = '')
359
    {
360
        static $headers = null;
361
362
        if (null === $headers) {
363
            $headers = array();
364
            if (function_exists('apache_request_headers')) {
365
                $rawHeaders = apache_request_headers();
366
                foreach ($rawHeaders as $name => $value) {
367
                    $headers[strtolower($name)] = $value;
368
                }
369
            } else {
370
                // From joyview - http://php.net/manual/en/function.getallheaders.php
371
                foreach ($_SERVER as $name => $value) {
372
                    if (substr($name, 0, 5) === 'HTTP_') {
373
                        $translatedName = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($name, 5))));
374
                        $headers[$translatedName] = $value;
375
                    }
376
                }
377
            }
378
        }
379
380
        $name = strtolower($headerName);
381
        if (isset($headers[$name])) {
382
            return static::cleanVar($headers[$name]);
383
        }
384
        return $default;
385
    }
386
387
    /**
388
     * See if a variable exists in one of the request hashes
389
     *
390
     * @param string $name variable to look for
391
     * @param string $hash hash to check
392
     *
393
     * @return boolean True if hash has an element 'name', otherwise false
394
     */
395 1
    public static function hasVar($name, $hash = 'method')
396
    {
397 1
        $hash = strtoupper($hash);
398 1
        if ($hash === 'METHOD') {
399
            $hash = strtoupper($_SERVER['REQUEST_METHOD']);
400
        }
401
402
        // Get the requested hash and determine existing value
403 1
        $original = static::get($hash, static::MASK_ALLOW_RAW);
404 1
        if (isset($original[$name])) {
405 1
            return true;
406
        }
407 1
        return false;
408
    }
409
410
    /**
411
     * Set a variable in one of the request variables
412
     *
413
     * @param string  $name      Name
414
     * @param string  $value     Value
415
     * @param string  $hash      Hash
416
     * @param boolean $overwrite Boolean
417
     *
418
     * @return string Previous value
419
     */
420 5
    public static function setVar($name, $value = null, $hash = 'method', $overwrite = true)
421
    {
422 5
        $hash = strtoupper($hash);
423 5
        if ($hash === 'METHOD') {
424
            $hash = strtoupper($_SERVER['REQUEST_METHOD']);
425
        }
426
427
        // Get the requested hash and determine existing value
428 5
        $original = static::get($hash, static::MASK_ALLOW_RAW);
429 5
        if (isset($original[$name])) {
430 3
            $previous = $original[$name];
431
            // don't overwrite value unless asked
432 3
            if (!$overwrite) {
433 3
                return $previous;
434
            }
435
        } else {
436 2
            $previous = null;
437
        }
438
439
        // set the value
440
        switch ($hash) {
441 5
            case 'GET':
442 5
                $_GET[$name] = $value;
443 5
                $_REQUEST[$name] = $value;
444 5
                break;
445
            case 'POST':
446
                $_POST[$name] = $value;
447
                $_REQUEST[$name] = $value;
448
                break;
449
            case 'REQUEST':
450
                $_REQUEST[$name] = $value;
451
                break;
452
            case 'COOKIE':
453
                $_COOKIE[$name] = $value;
454
                $_REQUEST[$name] = $value;
455
                break;
456
            case 'FILES':
457
                $_FILES[$name] = $value;
458
                break;
459
            case 'ENV':
460
                $_ENV['name'] = $value;
461
                break;
462
            case 'SERVER':
463
                $_SERVER['name'] = $value;
464
                break;
465
        }
466
467 5
        return $previous;
468
    }
469
470
    /**
471
     * Fetches and returns a request array.
472
     *
473
     * The default behaviour is fetching variables depending on the
474
     * current request method: GET and HEAD will result in returning
475
     * $_GET, POST and PUT will result in returning $_POST.
476
     *
477
     * You can force the source by setting the $hash parameter:
478
     *
479
     *  - post        $_POST
480
     *  - get         $_GET
481
     *  - files       $_FILES
482
     *  - cookie      $_COOKIE
483
     *  - env         $_ENV
484
     *  - server      $_SERVER
485
     *  - method      via current $_SERVER['REQUEST_METHOD']
486
     *  - default     $_REQUEST
487
     *
488
     * @param string $hash to get (POST, GET, FILES, METHOD)
489
     * @param int    $mask Filter mask for the variable
490
     *
491
     * @return mixed Request hash
492
     */
493 7
    public static function get($hash = 'default', $mask = 0)
494
    {
495 7
        $hash = strtoupper($hash);
496
497 7
        if ($hash === 'METHOD') {
498
            $hash = strtoupper($_SERVER['REQUEST_METHOD']);
499
        }
500
501
        switch ($hash) {
502 7
            case 'GET':
503 5
                $input = $_GET;
504 5
                break;
505 2
            case 'POST':
506
                $input = $_POST;
507
                break;
508 2
            case 'FILES':
509
                $input = $_FILES;
510
                break;
511 2
            case 'COOKIE':
512
                $input = $_COOKIE;
513
                break;
514 2
            case 'ENV':
515
                $input = &$_ENV;
516
                break;
517 2
            case 'SERVER':
518
                $input = &$_SERVER;
519
                break;
520
            default:
521 2
                $input = $_REQUEST;
522 2
                break;
523
        }
524
525 7
        $result = static::cleanVars($input, $mask);
526
527 7
        return $result;
528
    }
529
530
    /**
531
     * Sets a request variable
532
     *
533
     * @param array   $array     An associative array of key-value pairs
534
     * @param string  $hash      The request variable to set (POST, GET, FILES, METHOD)
535
     * @param boolean $overwrite If true and an existing key is found, the value is overwritten,
536
     *                            otherwise it is ignored
537
     *
538
     * @return void
539
     */
540 2
    public static function set($array, $hash = 'method', $overwrite = true)
541
    {
542 2
        foreach ($array as $key => $value) {
543 2
            static::setVar($key, $value, $hash, $overwrite);
544
        }
545 2
    }
546
547
    /**
548
     * Clean up an input variable.
549
     *
550
     * @param mixed  $var  The input variable.
551
     * @param int    $mask Filter bit mask.
552
     *                      - 1=no trim: If this flag is cleared and the input is a string,
553
     *                        the string will have leading and trailing whitespace trimmed.
554
     *                      - 2=allow_raw: If set, no more filtering is performed, higher bits are ignored.
555
     *                      - 4=allow_html: HTML is allowed, but passed through a safe HTML filter first.
556
     *                        If set, no more filtering is performed.
557
     *                      - If no bits other than the 1 bit is set, a strict filter is applied.
558
     * @param string $type The variable type. See {@link FilterInput::clean()}.
559
     *
560
     * @return string
561
     */
562 35
    protected static function cleanVar($var, $mask = 0, $type = null)
563
    {
564
        // Static input filters for specific settings
565 35
        static $noHtmlFilter = null;
566 35
        static $safeHtmlFilter = null;
567
568
        // convert $var in array if $type is ARRAY
569 35
        if (strtolower($type) === 'array' && !is_array($var)) {
570 1
            $var = array($var);
571
        }
572
573
        // If the no trim flag is not set, trim the variable
574 35
        if (!($mask & static::MASK_NO_TRIM) && is_string($var)) {
575 32
            $var = trim($var);
576
        }
577
578
        // Now we handle input filtering
579
        // If the allow raw flag is set, do not modify the variable
580 35
        if (!($mask & static::MASK_ALLOW_RAW)) {
581 28
            if ($mask & static::MASK_ALLOW_HTML) {
582
                // If the allow html flag is set, apply a safe html filter to the variable
583 2
                if (null === $safeHtmlFilter) {
584 1
                    $safeHtmlFilter = FilterInput::getInstance(array(), array(), 1, 1);
585
                }
586 2
                $var = $safeHtmlFilter->cleanVar($var, $type);
587
            } else {
588
                // Since no allow flags were set, we will apply the most strict filter to the variable
589 26
                if (null === $noHtmlFilter) {
590
                    $noHtmlFilter = FilterInput::getInstance();
591
                }
592 26
                $var = $noHtmlFilter->clean($var, $type);
593
            }
594
        }
595
596 35
        return $var;
597
    }
598
599
    /**
600
     * Clean up an array of variables.
601
     *
602
     * @param mixed  $var  The input variable.
603
     * @param int    $mask Filter bit mask. See {@link Request::cleanVar()}
604
     * @param string $type The variable type. See {@link FilterInput::clean()}.
605
     *
606
     * @return string
607
     */
608 7
    protected static function cleanVars($var, $mask = 0, $type = null)
609
    {
610 7
        if (is_array($var)) {
611 7
            foreach ($var as $key => &$value) {
612 7
                $value = static::cleanVars($value, $mask, $type);
613
            }
614
        } else {
615 7
            $var = static::cleanVar($var, $mask, $type);
616
        }
617
618 7
        return $var;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $var also could return the type array which is incompatible with the documented return type string.
Loading history...
619
    }
620
}
621