forked from snytkine/LampCMS
/
Request.php
476 lines (389 loc) · 11.7 KB
/
Request.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
<?php
/**
*
* License, TERMS and CONDITIONS
*
* This software is lisensed under the GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
* Please read the license here : http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* ATTRIBUTION REQUIRED
* 4. All web pages generated by the use of this software, or at least
* the page that lists the recent questions (usually home page) must include
* a link to the http://www.lampcms.com and text of the link must indicate that
* the website's Questions/Answers functionality is powered by lampcms.com
* An example of acceptable link would be "Powered by <a href="http://www.lampcms.com">LampCMS</a>"
* The location of the link is not important, it can be in the footer of the page
* but it must not be hidden by style attibutes
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This product includes GeoLite data created by MaxMind,
* available from http://www.maxmind.com/
*
*
* @author Dmitri Snytkine <cms@lampcms.com>
* @copyright 2005-2011 (or current year) ExamNotes.net inc.
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
* @link http://www.lampcms.com Lampcms.com project
* @version Release: @package_version@
*
*
*/
namespace Lampcms;
/**
* Class for handling OUR Incoming HTTP Request
* including headers and query string
*
* @todo this class looks a little confused and
* unsure about itself.
* Why not just extend ArrayDefaults and use default value of 1?
*
* Why do we even need getParam if it just delegates
* to getFiltered()?
*
* @author Dmitri Snytkine
*
*/
class Request extends LampcmsArray implements Interfaces\LampcmsObject
{
/**
* Array of required query string params
*
* @var array
*/
protected $aRequired = array();
/**
* Array of filtered params
* @var array but initially set to null
*/
protected $aFiltered = null;
protected static $ajax = null;
public function __construct(array $array){
parent::__construct($array);
}
/**
*
* Emulates the HttpQueryString::get() method
*
* @param string $name
* @param string $type 's' for string, 'i' for 'int', 'b' for bool
* @param string $default default value to return in
* case param $name is not found
*/
public function get($name, $type = 's', $default = null){
if(!$this->offsetExists($name)){
$val = $default;
} else {
$val = $this->getFiltered($name);
}
switch(true){
case ('s' === $type):
$val = (string)$val;
break;
case ('b' === $type):
$val = (bool)$val;
break;
case ('i' === $type):
$val = (int)$val;
break;
}
return $val;
}
/**
* Singleton method
*
* @param array $aRequired
*
* @return object of this class
* @throws BadFunctionCallException if any of required
* params are missing
*/
public static function factory(array $aRequired = array()){
$a = null;
$req = self::getRequestMethod();
if('POST' === $req){
$a = $_POST;
} elseif ('GET' === $req){
$a = $_GET;
}
$o = new self($a);
$o->setRequired($aRequired);
$o->checkRequired();
return $o;
}
/**
* Set array of params that are required
* to be in request
*
* @param array $aRequired array of param names
*/
public function setRequired(array $aRequired = array()){
$this->aRequired = $aRequired;
return $this;
}
/**
*
* Getter for $this->aRequired
*
* @return array
*/
public function getRequired(){
return $this->aRequired;
}
/**
* Return array of query params
* values run through filter first
* and result is also memoized
*
* @return array $this->aFiltered
*/
public function getArray(){
if(null === $this->aFiltered){
$a = $this->getArrayCopy();
foreach($a as $key => $val) {
$this->aFiltered[$key] = $this->getFiltered($key);
}
}
return $this->aFiltered;
}
/**
* Initial check to see if request contains
* all required parameterns
*
* @throws BadFunctionCallException if at least
* one required param is missing
*
* @return object $this
*/
public function checkRequired(){
if(!empty($this->aRequired)){
foreach($this->aRequired as $var){
if(!$this->offsetExists($var)){
throw new \BadFunctionCallException('Missing required query param: '.$var);
}
}
}
return $this;
}
/**
* Changing offsetGet does not affect get()
*
* @param string $offset
*/
public function offsetGet($offset){
/**
* For 'a' and 'pageID' return
* default values and don't go through
* getFiltered() if values don't exist
*
*/
if(!$this->offsetExists($offset)){
if('a' === $offset){
return 'viewquestions';
} elseif('pageID' === $offset){
return 1;
} else {
throw new DevException('Request param '.$offset.' does not exist');
}
}
return $this->getFiltered($offset);
}
/**
*
* @param $key
* @param $val
*/
public function offsetSet($key, $val){
$this->aFiltered = null;
parent::offsetSet($key, $val);
}
/**
* Get value of query string param
* if it exists or return $default
* if it does not exist
*
* @param string $var name of query string
* param
*
* @todo remove this and use get() or normal offsetGet() instead!
*
* @return mixed string|bool|int filtered value of param
* or value of supplied $default
*
*
*/
/*public function getParam($var, $default = 1){
if(!$this->offsetExists($var)){
$this->offsetSet($var, $default);
return $default;
}
return $this->getFiltered($var);
}*/
/**
* @todo remove this soon
*
*/
/*public function __get($param){
e('trying to get '.$param.' via __get');
return $this->offsetGet($param);
}*/
/**
* Get filtered value of query string
* param
*
* @param string $name name of query string param
*
* @return mixed string|bool|int depending on param type
*
*/
protected function getFiltered($name){
$val = parent::offsetGet($name);
if('a' === $name && !empty($val)){
$expression = '/^[[:alpha:]\-]{1,20}$/';
if(!filter_var($val, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => $expression)))){
throw new \InvalidArgumentException('Invalid value of "a" it can only contain letters and a hyphen and be limited to 20 characters in total was: '.$val);
}
$ret = $val;
} elseif(
('i_' === substr(strtolower($name), 0, 2)) ||
('id' === substr(strtolower($name), -2, 2))){
/**
* FILTER_VALIDATE_INT
* does not seem to accept 0 as a valid int!
* this sucks, so instead going to use is_numeric
*/
if(!is_numeric($val) || ($val < 0) || ($val > 99999999999)){
throw new \InvalidArgumentException('Invalid value of "'.$name.'". It can only be a number between 0 and 99999999999 was: '.$val);
}
$ret = (int)$val;
} elseif('_hex' === substr(strtolower($name), -4, 4)){
$expression = '/^[0-9A-F]{6}$/';
if(!filter_var($val, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => $expression)))){
throw new \InvalidArgumentException('Invalid value of '.$name.' it can only be a hex number. Was: '.$val);
}
$ret = $val;
} elseif('flag' === substr(strtolower($name), -4, 4)){
/**
* FILTER_VALIDATE_BOOLEAN will not work here
* because it does not accept 0 as valid option,
* only 1, true, on, yes
* it just does not accept any values for 'false'
*/
if(!is_numeric($val) || $val > 1){
throw new \InvalidArgumentException('Invalid value of '.$name.' It can only be an integer and not greater than 1, it was: '.gettype($val).' val: '.$val);
}
$ret = (bool)$val;
}elseif('token' === $name){
$ret = filter_var($val, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
}
else {
//$ret = filter_var($val, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$ret = $val;
}
return $ret;
}
/**
* @return request method like "GET" or "POST"
* and always in UPPER CASE
*
*/
public static function getRequestMethod(){
return strtoupper($_SERVER['REQUEST_METHOD']);
}
/**
* Get value of specific request header
*
* @param string $strHeader
* @return mixed string value of header or false
* if header not found
*/
public final static function getHttpHeader($strHeader)
{
$strKey = 'HTTP_'.strtoupper(str_replace('-', '_', $strHeader));
if (!empty($_SERVER[$strKey])) {
return $_SERVER[$strKey];
}
/**
* Fix case of request header, this way the
* param $strHeader is NOT case sensitive
*
*/
if (function_exists('apache_request_headers')) {
$strHeader = (str_replace(" ", "-", (ucwords(str_replace("-", " ", strtolower($strHeader))))));
$arrHeaders = apache_request_headers();
if (!empty($arrHeaders[$strHeader])) {
return $arrHeaders[$strHeader];
}
}
return false;
}
/**
*
* @return bool true if request is via Ajax, false otherwise
*
*/
public static final function isAjax()
{
d('isAjax? '.print_r($_GET, 1));
if(null !== self::$ajax){
return self::$ajax;
}
if((isset($_GET) && !empty($_GET['ajaxid'])) ||
(isset($_POST) && !empty($_POST['ajaxid']))){
self::$ajax = true;
d('ajaxid true');
return true;
}
self::$ajax = (strtoupper((string)self::getHttpHeader('X-REQUESTED-WITH')) === 'XMLHTTPREQUEST');
return self::$ajax;
}
/**
* Check to see if iframeid param exists in query string
*
* @return bool true if iframeid is one of the params
*/
public static function isIframe(){
return !empty($_REQUEST['iframeid']);
}
/**
* Returns ip address of client
* and falls back to localhost address
*
*
* @return string ip address
*/
public static function getIP()
{
return (isset($_SERVER) && !empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.2';
}
/**
* Get useragent of user making a request
*
* @return mixed string useragent | null if user agent not present
*
*/
public static function getUserAgent()
{
$sUserAgent = (isset($_SERVER) && isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT'] : null;
return $sUserAgent;
}
}