Completed
Pull Request — master (#122)
by Richard
12:56
created

Request::get()   D

Complexity

Conditions 10
Paths 28

Size

Total Lines 41
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
cc 10
eloc 30
nc 28
nop 2
dl 0
loc 41
rs 4.8196
c 4
b 1
f 0

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
/**
15
 * Request Class
16
 *
17
 * This class serves to provide a common interface to access
18
 * request variables.  This includes $_POST, $_GET, and naturally $_REQUEST.  Variables
19
 * can be passed through an input filter to avoid injection or returned raw.
20
 *
21
 * @category  Xmf\Request
22
 * @package   Xmf
23
 * @author    Richard Griffith <[email protected]>
24
 * @author    trabis <[email protected]>
25
 * @author    Joomla!
26
 * @copyright 2011-2016 XOOPS Project (http://xoops.org)
27
 * @license   GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
28
 * @link      http://xoops.org
29
 * @since     1.0
30
 */
31
class Request
32
{
33
    /**
34
     * Available masks for cleaning variables
35
     */
36
    const MASK_NO_TRIM    = 1;
37
    const MASK_ALLOW_RAW  = 2;
38
    const MASK_ALLOW_HTML = 4;
39
40
    /**
41
     * Gets the request method
42
     *
43
     * @return string
44
     */
45
    public static function getMethod()
46
    {
47
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
48
49
        return $method;
50
    }
51
52
    /**
53
     * Fetches and returns a given variable.
54
     *
55
     * The default behaviour is fetching variables depending on the
56
     * current request method: GET and HEAD will result in returning
57
     * an entry from $_GET, POST and PUT will result in returning an
58
     * entry from $_POST.
59
     *
60
     * You can force the source by setting the $hash parameter:
61
     *
62
     *  - post       $_POST
63
     *  - get        $_GET
64
     *  - files      $_FILES
65
     *  - cookie     $_COOKIE
66
     *  - env        $_ENV
67
     *  - server     $_SERVER
68
     *  - method     via current $_SERVER['REQUEST_METHOD']
69
     *  - default    $_REQUEST
70
     *
71
     * @param string $name    Variable name
72
     * @param mixed  $default Default value if the variable does not exist
73
     * @param string $hash    Source of variable value (POST, GET, FILES, COOKIE, METHOD)
74
     * @param string $type    Return type for the variable (INT, FLOAT, BOOLEAN, WORD,
75
     *                         ALPHANUM, CMD, BASE64, STRING, ARRAY, PATH, NONE) For more
76
     *                         information see FilterInput::clean().
77
     * @param int    $mask    Filter mask for the variable
78
     *
79
     * @return mixed Requested variable
80
     */
81
    public static function getVar($name, $default = null, $hash = 'default', $type = 'none', $mask = 0)
82
    {
83
        // Ensure hash and type are uppercase
84
        $hash = strtoupper($hash);
85
        if ($hash === 'METHOD') {
86
            $hash = static::getMethod();
87
        }
88
        $type = strtoupper($type);
89
90
        // Get the input hash
91
        switch ($hash) {
92
            case 'GET':
93
                $input = &$_GET;
94
                break;
95
            case 'POST':
96
                $input = &$_POST;
97
                break;
98
            case 'FILES':
99
                $input = &$_FILES;
100
                break;
101
            case 'COOKIE':
102
                $input = &$_COOKIE;
103
                break;
104
            case 'ENV':
105
                $input = &$_ENV;
106
                break;
107
            case 'SERVER':
108
                $input = &$_SERVER;
109
                break;
110
            default:
111
                $input = &$_REQUEST;
112
                break;
113
        }
114
115
        if (isset($input[$name]) && $input[$name] !== null) {
116
            // Get the variable from the input hash and clean it
117
            $var = static::cleanVar($input[$name], $mask, $type);
118
119
            // Handle magic quotes compatibility
120
            if (get_magic_quotes_gpc() && ($var != $default) && ($hash !== 'FILES')) {
121
                $var = static::stripSlashesRecursive($var);
122
            }
123
        } else {
124
            if ($default !== null) {
125
                // Clean the default value
126
                $var = static::cleanVar($default, $mask, $type);
127
            } else {
128
                $var = $default;
129
            }
130
        }
131
132
        return $var;
133
    }
134
135
    /**
136
     * Fetches and returns a given filtered variable. The integer
137
     * filter will allow only digits to be returned. This is currently
138
     * only a proxy function for getVar().
139
     *
140
     * See getVar() for more in-depth documentation on the parameters.
141
     *
142
     * @param string $name    Variable name
143
     * @param int    $default Default value if the variable does not exist
144
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
145
     *
146
     * @return int Requested variable
0 ignored issues
show
Documentation introduced by
Should the return type not be array|string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
147
     */
148
    public static function getInt($name, $default = 0, $hash = 'default')
149
    {
150
        return static::getVar($name, $default, $hash, 'int');
151
    }
152
153
    /**
154
     * Fetches and returns a given filtered variable.  The float
155
     * filter only allows digits and periods.  This is currently
156
     * only a proxy function for getVar().
157
     *
158
     * See getVar() for more in-depth documentation on the parameters.
159
     *
160
     * @param string $name    Variable name
161
     * @param float  $default Default value if the variable does not exist
162
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
163
     *
164
     * @return float Requested variable
0 ignored issues
show
Documentation introduced by
Should the return type not be array|string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
165
     */
166
    public static function getFloat($name, $default = 0.0, $hash = 'default')
167
    {
168
        return static::getVar($name, $default, $hash, 'float');
169
    }
170
171
    /**
172
     * Fetches and returns a given filtered variable. The bool
173
     * filter will only return true/false bool values. This is
174
     * currently only a proxy function for getVar().
175
     *
176
     * See getVar() for more in-depth documentation on the parameters.
177
     *
178
     * @param string $name    Variable name
179
     * @param bool   $default Default value if the variable does not exist
180
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
181
     *
182
     * @return bool Requested variable
0 ignored issues
show
Documentation introduced by
Should the return type not be array|string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
183
     */
184
    public static function getBool($name, $default = false, $hash = 'default')
185
    {
186
        return static::getVar($name, $default, $hash, 'bool');
187
    }
188
189
    /**
190
     * Fetches and returns a given filtered variable. The word
191
     * filter only allows the characters [A-Za-z_]. This is currently
192
     * only a proxy function for getVar().
193
     *
194
     * See getVar() for more in-depth documentation on the parameters.
195
     *
196
     * @param string $name    Variable name
197
     * @param string $default Default value if the variable does not exist
198
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
199
     *
200
     * @return string Requested variable
0 ignored issues
show
Documentation introduced by
Should the return type not be array|string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
201
     */
202
    public static function getWord($name, $default = '', $hash = 'default')
203
    {
204
        return static::getVar($name, $default, $hash, 'word');
205
    }
206
207
    /**
208
     * Fetches and returns a given filtered variable. The cmd filter only allows the characters
209
     * [A-Za-z0-9.-_] and returns in lower case. This is currently a proxy function for getVar().
210
     *
211
     * See getVar() for more in-depth documentation on the parameters.
212
     *
213
     * @param string $name    Variable name
214
     * @param string $default Default value if the variable does not exist
215
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
216
     *
217
     * @return string Requested variable
0 ignored issues
show
Documentation introduced by
Should the return type not be array|string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
218
     */
219
    public static function getCmd($name, $default = '', $hash = 'default')
220
    {
221
        return static::getVar($name, $default, $hash, 'cmd');
222
    }
223
224
    /**
225
     * Fetches and returns a given filtered variable. The string
226
     * filter deletes 'bad' HTML code, if not overridden by the mask.
227
     * This is currently only a proxy function for getVar().
228
     *
229
     * See getVar() for more in-depth documentation on the parameters.
230
     *
231
     * @param string $name    Variable name
232
     * @param string $default Default value if the variable does not exist
233
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
234
     * @param int    $mask    Filter mask for the variable
235
     *
236
     * @return string Requested variable
237
     */
238
    public static function getString($name, $default = '', $hash = 'default', $mask = 0)
239
    {
240
        // Cast to string, in case static::MASK_ALLOW_RAW was specified for mask
241
        return (string) static::getVar($name, $default, $hash, 'string', $mask);
242
    }
243
244
    /**
245
     * Fetches and returns an array
246
     *
247
     * @param string $name    Variable name
248
     * @param mixed  $default Default value if the variable does not exist
249
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
250
     *
251
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
252
     */
253
    public static function getArray($name, $default = array(), $hash = 'default')
254
    {
255
        return static::getVar($name, $default, $hash, 'array');
256
    }
257
258
    /**
259
     * Fetches and returns raw text
260
     *
261
     * @param string $name    Variable name
262
     * @param string $default Default value if the variable does not exist
263
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
264
     *
265
     * @return string Requested variable
266
     */
267
    public static function getText($name, $default = '', $hash = 'default')
268
    {
269
        return (string) static::getVar($name, $default, $hash, 'string', static::MASK_ALLOW_RAW);
270
    }
271
272
    /**
273
     * Fetches and returns a web url
274
     *
275
     * @param string $name    Variable name
276
     * @param string $default Default value if the variable does not exist
277
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
278
     *
279
     * @return string Requested variable
280
     */
281
    public static function getUrl($name, $default = '', $hash = 'default')
282
    {
283
        return (string) static::getVar($name, $default, $hash, 'weburl');
284
    }
285
286
    /**
287
     * Fetches and returns a file (or web) path
288
     *
289
     * @param string $name    Variable name
290
     * @param string $default Default value if the variable does not exist
291
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
292
     *
293
     * @return string Requested variable
294
     */
295
    public static function getPath($name, $default = '', $hash = 'default')
296
    {
297
        return (string) static::getVar($name, $default, $hash, 'path');
298
    }
299
300
    /**
301
     * Fetches and returns an email address
302
     *
303
     * @param string $name    Variable name
304
     * @param string $default Default value if the variable does not exist
305
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
306
     *
307
     * @return string email address or default if invalid
308
     */
309
    public static function getEmail($name, $default = '', $hash = 'default')
310
    {
311
        $ret = (string) static::getVar($name, $default, $hash, 'email');
312
        return empty($ret) ? $default : $ret;
313
    }
314
315
    /**
316
     * Fetches and returns an IP address
317
     *
318
     * @param string $name    Variable name
319
     * @param string $default Default value if the variable does not exist
320
     * @param string $hash    Where the var should come from (POST, GET, FILES, COOKIE, METHOD)
321
     *
322
     * @return string IP address or default if invalid
323
     */
324
    public static function getIP($name, $default = '', $hash = 'default')
325
    {
326
        $ret = (string) static::getVar($name, $default, $hash, 'ip');
327
        return empty($ret) ? $default : $ret;
328
    }
329
330
    /**
331
     * get request header
332
     *
333
     * @param string      $headerName name of header to retrieve, case insensitive
334
     * @param string|null $default    default to return if named header is not found
335
     *
336
     * @return string header value or default if header was not found
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

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

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
592
     */
593
    protected static function cleanVars($var, $mask = 0, $type = null)
594
    {
595
        if (is_array($var)) {
596
            foreach ($var as $key => &$value) {
597
                $value = static::cleanVars($value, $mask, $type);
598
            }
599
        } else {
600
            $var = static::cleanVar($var, $mask, $type);
601
        }
602
603
        return $var;
604
    }
605
606
    /**
607
     * Strips slashes recursively on an array
608
     *
609
     * @param string|array $value string of Array of (nested arrays of) strings
610
     *
611
     * @return array The input array with stripslashes applied to it
0 ignored issues
show
Documentation introduced by
Should the return type not be array|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
612
     */
613
    protected static function stripSlashesRecursive($value)
614
    {
615
        $value = is_array($value)
616
            ? array_map(array('XoopsRequest', 'stripSlashesRecursive'), $value)
617
            : stripslashes($value);
618
619
        return $value;
620
    }
621
}
622