File: Request.php

package info (click to toggle)
matomo 5.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 95,068 kB
  • sloc: php: 289,425; xml: 127,249; javascript: 112,130; python: 202; sh: 178; makefile: 20; sql: 10
file content (319 lines) | stat: -rw-r--r-- 10,169 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
<?php

/**
 * Matomo - free/libre analytics platform
 *
 * @link    https://matomo.org
 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik;

use InvalidArgumentException;

/**
 * Provides (type safe) access methods for request parameters.
 *
 * Ensure to handle parameters received with this class with care.
 * Especially parameters received as string, array or json might contain malicious content. Those should never be used
 * raw in templates or other output.
 *
 * Note: For security reasons this class will automatically remove null byte sequences from string values.
 *
 * @api
 */
class Request
{
    /**
     * @var array
     */
    protected $requestParameters;

    private static $exceptionMsg = "The parameter '%s' isn't set in the Request and a default value wasn't provided.";

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

    /**
     * Creates a request object using GET and POST parameters of the current request
     *
     * @return static
     */
    public static function fromRequest(): self
    {
        return new self($_GET + $_POST);
    }

    /**
     * Creates a request object using only GET parameters of the current request
     *
     * @return static
     */
    public static function fromGet(): self
    {
        return new self($_GET);
    }

    /**
     * Creates a request object using only POST parameters of the current request
     *
     * @return static
     */
    public static function fromPost(): self
    {
        return new self($_POST);
    }

    /**
     * Creates a request object using the parameters that can be extracted from the provided query string
     *
     * @return static
     */
    public static function fromQueryString(string $queryString): self
    {
        $requestParameters = [];
        parse_str($queryString, $requestParameters);

        // If a querystring is provided urlencode'd parse_str will not be able to parse it correctly.
        // A querystring like `method%3dVisitsSummary.get%26idSite%3d1` would result in
        // an array like `['method=VisitsSummary.get&idSite=1' => '']`
        // In this case we try to parse the urldecode'd string to get proper results
        // Note: We can't always perform a urldecode, as this might otherwise destroy urlencoded values containing a &
        if (1 === count($requestParameters) && '' === end($requestParameters)) {
            $requestParameters = [];
            parse_str(urldecode($queryString), $requestParameters);
        }

        return new self($requestParameters);
    }

    /**
     * Returns the requested parameter from the request object.
     * If the requested parameter can't be found and no default is provided an exception will be thrown
     *
     * Note: It's recommend to use one of type-safe methods instead, if a certain type is expected:
     * @see getIntegerParameter
     * @see getFloatParameter
     * @see getStringParameter
     * @see getArrayParameter
     * @see getJSONParameter
     *
     * @param mixed $default
     * @return mixed
     * @throws InvalidArgumentException
     */
    public function getParameter(string $name, $default = null)
    {
        if (!strlen($name)) {
            throw new InvalidArgumentException('Invalid request parameter. Parameter name required.');
        }

        if (
            array_key_exists($name, $this->requestParameters)
            && $this->requestParameters[$name] !== null
        ) {
            return $this->filterNullBytes($this->requestParameters[$name]);
        }

        if (null !== $default) {
            return $default;
        }

        throw new InvalidArgumentException(sprintf(self::$exceptionMsg, $name));
    }

    /**
     * Returns the requested parameter from the request object.
     * If no default is provided and the requested parameter either can't be found or is not of type integer an
     * exception will be thrown
     *
     * @throws InvalidArgumentException
     */
    public function getIntegerParameter(string $name, ?int $default = null): int
    {
        $parameter = $this->getParameter($name, $default);

        if ((is_string($parameter) || is_numeric($parameter)) && (string)$parameter === (string)(int)$parameter) {
            return (int)$parameter;
        }

        if (null !== $default) {
            return $default;
        }

        throw new InvalidArgumentException(sprintf(self::$exceptionMsg, $name));
    }

    /**
     * Returns the requested parameter from the request object.
     * If no default is provided and the requested parameter either can't be found or is not of type float an
     * exception will be thrown
     *
     * @throws InvalidArgumentException
     */
    public function getFloatParameter(string $name, ?float $default = null): float
    {
        $parameter = $this->getParameter($name, $default);

        if (is_float($parameter) || is_int($parameter)) {
            return (float)$parameter;
        }

        // Regex for all supported float notations in PHP (see https://www.php.net/manual/en/language.types.float.php)
        $floatRegex = "/^[-+]?((([0-9]+(_[0-9]+)*)|(([0-9]+(_[0-9]+)*)?\.([0-9]+(_[0-9]+)*))|(([0-9]+(_[0-9]+)*)\.([0-9]+(_[0-9]+)*)?))([eE][+-]?([0-9]+(_[0-9]+)*))?)$/";

        if (is_string($parameter) && preg_match($floatRegex, $parameter)) {
            // underscores would break numbers if not removed before
            return (float) str_replace('_', '', $parameter);
        }

        if (null !== $default) {
            return $default;
        }

        throw new InvalidArgumentException(sprintf(self::$exceptionMsg, $name));
    }

    /**
     * Returns the requested parameter from the request object.
     * If no default is provided and the requested parameter either can't be found or is not of type string an
     * exception will be thrown
     *
     * @throws InvalidArgumentException
     */
    public function getStringParameter(string $name, ?string $default = null): string
    {
        $parameter = $this->getParameter($name, $default);

        if (is_string($parameter) || is_numeric($parameter)) {
            return $this->filterNullBytes((string)$parameter);
        }

        if (null !== $default) {
            return $default;
        }

        throw new InvalidArgumentException(sprintf(self::$exceptionMsg, $name));
    }

    /**
     * Returns the requested parameter from the request object.
     * If no default is provided and the requested parameter either can't be found or can't be converted to boolean
     * exception will be thrown
     *
     * Values accepted as bool-ish:
     * true: true, 'true', '1', 1
     * false: false, 'false', '0', 0
     *
     * @throws InvalidArgumentException
     */
    public function getBoolParameter(string $name, ?bool $default = null): bool
    {
        $parameter = $this->getParameter($name, $default);

        if ($parameter === false || $parameter === true) {
            return $parameter;
        }

        if ((\is_string($parameter) && \strtolower($parameter) === 'false') || $parameter === '0' || $parameter === 0) {
            return false;
        }

        if ((\is_string($parameter) && \strtolower($parameter) === 'true') || $parameter === '1' || $parameter === 1) {
            return true;
        }

        if (null !== $default) {
            return $default;
        }

        throw new InvalidArgumentException(sprintf(self::$exceptionMsg, $name));
    }

    /**
     * Returns the requested parameter from the request object.
     * If no default is provided and the requested parameter either can't be found or is not of type array an
     * exception will be thrown
     *
     * @param array|null $default
     * @return array
     * @throws InvalidArgumentException
     */
    public function getArrayParameter(string $name, ?array $default = null): array
    {
        $parameter = $this->getParameter($name, $default);

        if (is_array($parameter)) {
            return $this->filterNullBytes($parameter);
        }

        if (null !== $default) {
            return $default;
        }

        throw new InvalidArgumentException(sprintf(self::$exceptionMsg, $name));
    }

    /**
     * Returns the requested parameter from the request object.
     * If no default is provided and the requested parameter either can't be found or can't be json_decode'd an
     * exception will be thrown
     *
     * @param mixed $default
     * @return mixed
     * @throws InvalidArgumentException
     */
    public function getJsonParameter(string $name, $default = null)
    {
        try {
            // Note we can't simply pass the default to getParameter here, in case the default would be string
            // we would otherwise try to parse it as json below, which might result in unexpected behavior
            $parameter = $this->getParameter($name);
        } catch (InvalidArgumentException $e) {
            $parameter = null;

            if ($default !== null) {
                return $default;
            }
        }

        if (is_string($parameter)) {
            $decodedValue = \json_decode($parameter, true);

            if ($decodedValue !== null && $decodedValue !== '') {
                return $this->filterNullBytes($decodedValue);
            }
        }

        if (null !== $default) {
            return $default;
        }

        throw new InvalidArgumentException(sprintf(self::$exceptionMsg, $name));
    }

    private function filterNullBytes($value)
    {
        if (is_array($value)) {
            $result = [];
            foreach ($value as $key => $arrayValue) {
                $result[$key] = $this->filterNullBytes($arrayValue);
            }
            return $result;
        } else {
            return is_string($value) ? Common::sanitizeNullBytes($value) : $value;
        }
    }

    /**
     * Returns an array containing all parameters of the request object
     *
     * @return array
     */
    public function getParameters(): array
    {
        return $this->requestParameters;
    }
}