joomla-2.5 /libraries/koowa/request/request.php

Language PHP Lines 712
MD5 Hash f80fe5079b35ce06f8864d54f526ca60 Estimated Cost $9,431 (why?)
Repository https://bitbucket.org/organicdevelopment/joomla-2.5.git View Raw File View Project SPDX
  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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
<?php
/**
 * @version    	$Id: request.php 4477 2012-02-10 01:06:38Z johanjanssens $
 * @category	Koowa
 * @package    	Koowa_Request
 * @copyright  	Copyright (C) 2007 - 2012 Johan Janssens. All rights reserved.
 * @license    	GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link 		http://www.nooku.org
 */

//Instantiate the request singleton
KRequest::getInstance();

/**
 * Request class
 *
 * @author      Johan Janssens <johan@nooku.org>
 * @category    Koowa
 * @package     Koowa_Request
 * @uses        KFilter
 * @uses        KInflector
 * @uses        KService
 * @static
 */
class KRequest
{
    /**
     * URL of the request regardless of the server
     *
     * @var KHttpUrl
     */
    protected static $_url = null;

    /**
     * Base path of the request.
     *
     * @var KHttpUrl
     */
    protected static $_base = null;

    /**
     * Root path of the request.
     *
     * @var KHttpUrl
     */
    protected static $_root = null;

    /**
     * Referrer of the request
     *
     * @var KHttpUrl
     */
    protected static $_referrer = null;

    /**
     * The raw post or put content information
     *
     * @var array
     */
    protected static $_content = null;

    /**
     * The request accepts information
     *
     * @var array
     */
    protected static $_accept = null;


    /**
     * Constructor
     *
     * Prevent creating instances of this class by making the contructor private
     */
    final private function __construct(KConfig $config)
    {
        $content = self::content();

        if(self::type() == 'HTTP')
        {
            if(strpos(PHP_SAPI, 'cgi') !== false) {
                $authorization = KRequest::get('server.REDIRECT_HTTP_AUTHORIZATION', 'string');
            } else {
                $authorization = KRequest::get('server.HTTP_AUTHORIZATION', 'url');
            }
            
	        if (strstr($authorization,"Basic"))
	        {
	            $parts = explode(':',base64_decode(substr($authorization, 6)));

	            if (count($parts) == 2)
			    {
				    KRequest::set('server.PHP_AUTH_USER', $parts[0]);
				    KRequest::set('server.PHP_AUTH_PW'  , $parts[1]);
			    }
		    }
        }

        if(!empty($content['data']))
        {
            if($content['type'] == 'application/x-www-form-urlencoded')
            {
                if (in_array(self::method(), array('PUT', 'DELETE')))
                {
                    parse_str($content['data'], $GLOBALS['_'.self::method()]);
                    $GLOBALS['_REQUEST'] = array_merge($GLOBALS['_REQUEST'],  $GLOBALS['_'.self::method()]);
                }
            }

            if($content['type'] == 'application/json')
            {
                if(in_array(self::method(), array('POST', 'PUT', 'DELETE')))
                {
                    $GLOBALS['_'.self::method()] = json_decode($content['data'], true);
                    $GLOBALS['_REQUEST'] = array_merge($GLOBALS['_REQUEST'],  $GLOBALS['_'.self::method()]);
                }
            }
        }
     }

    /**
     * Clone
     *
     * Prevent creating clones of this class
     */
    final private function __clone() { }

    /**
     * Force creation of a singleton
     *
     * @return void
     */
    public static function getInstance($config = array())
    {
        static $instance;

        if ($instance === NULL)
        {
            if(!$config instanceof KConfig) {
                $config = new KConfig($config);
            }

            $instance = new self($config);
        }

        return $instance;
    }


    /**
     * Get sanitized data from the request.
     *
     * @param   string              Variable identifier, prefixed by hash name eg post.foo.bar
     * @param   mixed               Filter(s), can be a KFilter object, a filter name, an array of filter names or a filter identifier
     * @param   mixed               Default value when the variable doesn't exist
     * @throws  KRequestException   When an invalid filter was passed
     * @return  mixed               The sanitized data
     */
    public static function get($identifier, $filter, $default = null)
    {
        list($hash, $keys) = self::_parseIdentifier($identifier);

        $result = null;
        if(isset($GLOBALS['_'.$hash]))
        {
            $result = $GLOBALS['_'.$hash];
            foreach($keys as $key)
            {
                if(array_key_exists($key, $result)) {
                    $result = $result[$key];
                } else {
                    $result = null;
                    break;
                }
            }
        }


        // If the value is null return the default
        if(is_null($result)) {
            return $default;
        }

        // Handle magic quotes compatability
        if (get_magic_quotes_gpc() && !in_array($hash, array('FILES', 'SESSION'))) {
            $result = self::_stripSlashes( $result );
        }

        if(!($filter instanceof KFilterInterface)) {
            $filter = KService::get('koowa:filter.factory')->instantiate($filter);
        }

        return $filter->sanitize($result);
    }

    /**
     * Set a variable in the request. Cookies and session data are stored persistently.
     *
     * @param   mixed   Variable identifier, prefixed by hash name eg post.foo.bar
     * @param   mixed   Variable value
     */
    public static function set($identifier, $value)
    {
        list($hash, $keys) = self::_parseIdentifier($identifier);
        
        // Add to _REQUEST hash if original hash is get, post, or cookies
        if(in_array($hash, array('GET', 'POST', 'COOKIE'))) {
            self::set('request.'.implode('.', $keys), $value);
        }
        
        // Store cookies persistently
        if($hash == 'COOKIE' && strpos(KRequest::protocol(), 'http') !== false)
        {
            // rewrite the $keys as foo[bar][bar]
            $ckeys = $keys; // get a copy
            $name = array_shift($ckeys);
            foreach($ckeys as $ckey) {
                $name .= '['.$ckey.']';
            }
 
            if(!setcookie($name, $value)) {
                throw new KRequestException("Couldn't set cookie, headers already sent.");
            }
        }

        // Store in $GLOBALS
        foreach(array_reverse($keys, true) as $key) {
            $value = array($key => $value);
        }
        
        // Add the global if it's doesn't exist
        if(!isset($GLOBALS['_'.$hash])) { 
           $GLOBALS['_'.$hash] = array(); 
        } 
        
        $GLOBALS['_'.$hash] = KHelperArray::merge($GLOBALS['_'.$hash], $value);
    }

    /**
     * Check if a variable exists based on an identifier
     *
     * @param   string  Variable identifier, prefixed by hash name eg post.foo.bar
     * @return  boolean
     */
    public static function has($identifier)
    {
        list($hash, $keys) = self::_parseIdentifier($identifier);

        foreach($keys as $key)
        {
            if(isset($GLOBALS['_'.$hash]) && array_key_exists($key, $GLOBALS['_'.$hash])) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get the POST or PUT raw content information
     *
     * The raw post data is not available with enctype="multipart/form-data".
     *
     * @param   string  The content data to return. Can be 'type' or 'data'.
     *                  If not set, all the data will be returned.
     * @return  array   An associative array with the content data. Valid keys are
     *                  'type' and 'data'
     */
    public static function content($key = null)
    {
        $result = '';

        if (!isset(self::$_content) && isset($_SERVER['CONTENT_TYPE']))
        {
            $type = $_SERVER['CONTENT_TYPE'];

            // strip parameters from content-type like "; charset=UTF-8"
            if (is_string($type))
            {
                if (preg_match('/^([^,\;]*)/', $type, $matches)) {
                    $type = $matches[1];
                }
            }

            self::$_content['type'] = $type;


            $data = '';
            if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 0)
            {
                $input = fopen('php://input', 'r');
                while ($chunk = fread($input, 1024)) {
                    $data .= $chunk;
                }

                fclose($input);
            }

            self::$_content['data'] = $data;
        }

        return isset($key) ? self::$_content[$key] : self::$_content;
    }

    /**
     * Get the accept request information
     *
     * @param   string  The accept data to return. Can be 'format', 'encoding' or 'language'.
     *                  If not set, all the accept data will be returned.
     * @return  array   An associative array with the content data. Valid keys are
     *                  'format', 'encoding' and 'language'
     */
    public static function accept($type = null)
    {
        if (!isset(self::$_accept) && isset($_SERVER['HTTP_ACCEPT']))
        {
            $accept = KRequest::get('server.HTTP_ACCEPT', 'string');
            self::$_accept['format'] = self::_parseAccept($accept);

            if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
            {
                $accept = KRequest::get('server.HTTP_ACCEPT_ENCODING', 'string');
                self::$_accept['encoding'] = self::_parseAccept($accept);
            }

            if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
            {
                $accept = KRequest::get('server.HTTP_ACCEPT_LANGUAGE', 'string');
                self::$_accept['language'] = self::_parseAccept($accept);
            }
        }

        return $type ? self::$_accept[$type] : self::$_accept;
    }

    /**
     * Returns the client information doing the request
     *
     * @return string $_SERVER['HTTP_USER_AGENT'] or an empty string if it's not supplied in the request
     */
    public static function client()
    {
        return isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    }

    /**
     * Returns the HTTP referrer.
     *
     * 'referer' a commonly used misspelling word for 'referrer'
     * @see     http://en.wikipedia.org/wiki/HTTP_referrer
     *
     * @param   boolean     Only allow internal url's
     * @return  KHttpUrl    A KHttpUrl object
     */
    public static function referrer($isInternal = true)
    {
        if(!isset(self::$_referrer))
        {
            if($referrer = KRequest::get('server.HTTP_REFERER', 'url'))
            {
                self::$_referrer = KService::get('koowa:http.url', array('url' => $referrer));

                if($isInternal)
                {
                    if(!KService::get('koowa:filter.internalurl')->validate((string)self::$_referrer)) {
                        return null;
                    }
                }
            }
        }

        return self::$_referrer;
    }

    /**
     * Return the URI of the request regardless of the server
     *
     * @return  KHttpUrl    A KHttpUri object
     */
    public static function url()
    {
        if(!isset(self::$_url))
        {
            $url = self::protocol().'://';
            
            if (PHP_SAPI !== 'cli') 
        	{
        		/*
            	 * Since we are assigning the URI from the server variables, we first need
             	 * to determine if we are running on apache or IIS.  If PHP_SELF and REQUEST_URI
             	 * are present, we will assume we are running on apache.
             	 */
        	    if (!empty ($_SERVER['PHP_SELF']) && !empty ($_SERVER['REQUEST_URI']))
                {
                	/*
                 	 * To build the entire URI we need to prepend the protocol, and the http host
                 	 * to the URI string.
                 	 */
                    $url .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

                	/*
                 	 * Since we do not have REQUEST_URI to work with, we will assume we are
                 	 * running on IIS and will therefore need to work some magic with the SCRIPT_NAME and
                 	 * QUERY_STRING environment variables.
                 	 */
                }
                else
                {
                    // IIS uses the SCRIPT_NAME variable instead of a REQUEST_URI variable
                    $url .= $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];

                    // If the query string exists append it to the URI string
                    if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) {
                        $url .= '?' . $_SERVER['QUERY_STRING'];
                    }
                }
        	}
        	else $url .= 'koowa';
            
            // Sanitize the url since we can't trust the server var
            $url = KService::get('koowa:filter.url')->sanitize($url);

            // Create the URI object
            self::$_url = KService::get('koowa:http.url', array('url' => $url));

        }

        return self::$_url;
    }

    /**
     * Returns the base path of the request.
     *
     * @return  object  A KHttpUrl object
     */
    public static function base()
    {
        if(!isset(self::$_base))
        {
            // Get the base request path
            if (strpos(PHP_SAPI, 'cgi') !== false && !ini_get('cgi.fix_pathinfo')  && !empty($_SERVER['REQUEST_URI'])) 
            {    
                // PHP-CGI on Apache with "cgi.fix_pathinfo = 0"
                // We don't have user-supplied PATH_INFO in PHP_SELF
                $path = $_SERVER['PHP_SELF'];
            } 
            else $path = $_SERVER['SCRIPT_NAME'];
            
            $path = rtrim(dirname($path), '/\\');
         
            // Sanitize the url since we can't trust the server var
            $path = KService::get('koowa:filter.url')->sanitize($path);

            self::$_base = KService::get('koowa:http.url', array('url' => $path));
        }

        return self::$_base;
    }

    /**
     * Returns the root path of the request.
     *
     * In most case this value will be the same as KRequest::base however it can be
     * changed by pushing in a different value
     *
     * @return  object  A KHttpUrl object
     */
    public static function root($path = null)
    {
        if(!is_null($path))
        {
            if(!$path instanceof KhttpUrl) {
                $path = KService::get('koowa:http.url', array('url' => $path));
            }

            self::$_root = $path;
        }

        if(is_null(self::$_root)) {
            self::$_root = self::$_base;
        }

        return self::$_root;
    }

    /**
     * Returns the current request protocol, based on $_SERVER['https']. In CLI
     * mode, 'cli' will be returned.
     *
     * @return  string
     */
    public static function protocol()
    {
        $protocol = 'cli';
        
        if (PHP_SAPI !== 'cli') 
        {
            $protocol = 'http';
            
            if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) {
                $protocol = 'https';
            }
        } 
     
        return $protocol;
    }

    /**
     * Returns current request method.
     *
     * @return  string
     */
    public static function method()
    {
        $method = '';

        if(PHP_SAPI != 'cli')
        {
            $method  =  strtoupper($_SERVER['REQUEST_METHOD']);

            if($method == 'POST')
            {
                if(isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
                    $method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
                }

                if(self::has('post._method')) {
                    $method = strtoupper(self::get('post._method', 'cmd'));
                }
            }
        }

        return $method;
    }

    /**
     * Return the current request transport type.
     *
     * @return  string
     */
    public static function type()
    {
        $type = 'HTTP';

        if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
            $type = 'AJAX';
        }

        if( isset($_SERVER['HTTP_X_FLASH_VERSION'])) {
            $type = 'FLASH';
        }

        if(preg_match('/^(Shockwave|Adobe) Flash/', KRequest::client()) == 1) {
             $type = 'FLASH';
        }

        return $type;
    }

    /**
     * Return the request token
     *
     * @return  string  The request token or NULL if no token could be found
     */
    public static function token()
    {
        $token = null;

        if(self::has('server.HTTP_X_TOKEN')) {
            $token = self::get('server.HTTP_X_TOKEN', 'md5');
        }

        if(self::has('request._token')) {
            $token = self::get('request._token', 'md5');
        }

        return $token;
    }

    /**
     * Return the request format
     *
     * This function tries to find the format by inspecting the accept header,
     * only if one accept type is specified the format will be parsed from it,
     * otherwise the path extension or the 'format' request variable is used.
     *
     * @return  string  The request format or NULL if no format could be found
     */
    public static function format()
    {
        $format = null;

        if(count(self::accept('format')) == 1)
        {
            $mime   = explode('/', key(self::accept('format')));
            $format = $mime[1];

            if($pos = strpos($format, '+')) {
                $format = substr($format, 0, $pos);
            }

            //Format cannot be *
            if($format == '*') {
                $format = null;
            }
        }

        if(self::has('request.format')) {
            $format = self::get('request.format', 'word');
        }

        return $format;
    }

    /**
     * Parse the variable identifier
     *
     * @param   string  Variable identifier
     * @return  array   0 => hash, 1 => parts
     */
    protected static function _parseIdentifier($identifier)
    {
        $parts = array();
        $hash  = $identifier;

        // Validate the variable format
        if(strpos($identifier, '.') !== false)
        {
            // Split the variable name into it's parts
            $parts = explode('.', $identifier);

            // Validate the hash name
            $hash   = array_shift($parts);
        }

        $hash = strtoupper($hash);

        return array($hash, $parts);
    }

    /**
     * Parses an accept header and returns an array (type => quality) of the
     * accepted types, ordered by quality.
     *
     * @param string    header to parse
     * @param array     default values
     * @return array
     */
    protected static function _parseAccept( $accept, array $defaults = NULL)
    {
        if (!empty($accept))
        {
            // Get all of the types
            $types = explode(',', $accept);

            foreach ($types as $type)
            {
                // Split the type into parts
                $parts = explode(';', $type);

                // Make the type only the MIME
                $type = trim(array_shift($parts));

                // Default quality is 1.0
                $quality = 1.0;

                foreach ($parts as $part)
                {
                    // Prevent undefined $value notice below
                    if (strpos($part, '=') === FALSE) {
                        continue;
                    }

                    // Separate the key and value
                    list ($key, $value) = explode('=', trim($part));

                    if ($key === 'q')
                    {
                        // There is a quality for this type
                        $quality = (float) trim($value);
                    }
                }

                // Add the accept type and quality
                $defaults[$type] = $quality;
            }
        }

        // Make sure that accepts is an array
        $accepts = (array) $defaults;

        // Order by quality
        arsort($accepts);

        return $accepts;
    }

    /**
     * Strips slashes recursively on an array
     *
     * @param   array   Array of (nested arrays of) strings
     * @return  array   The input array with stripshlashes applied to it
     */
    protected static function _stripSlashes( $value )
    {
        if(!is_object($value)) {
            $value = is_array( $value ) ? array_map( array( 'KRequest', '_stripSlashes' ), $value ) : stripslashes( $value );
        }

        return $value;
    }
}
Back to Top