Subversion-Projekte lars-tiefland.ci

Revision

Revision 2049 | Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
68 lars 1
<?php
2
/**
3
 * CodeIgniter
4
 *
5
 * An open source application development framework for PHP
6
 *
7
 * This content is released under the MIT License (MIT)
8
 *
9
 * Copyright (c) 2014 - 2016, British Columbia Institute of Technology
10
 *
11
 * Permission is hereby granted, free of charge, to any person obtaining a copy
12
 * of this software and associated documentation files (the "Software"), to deal
13
 * in the Software without restriction, including without limitation the rights
14
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
 * copies of the Software, and to permit persons to whom the Software is
16
 * furnished to do so, subject to the following conditions:
17
 *
18
 * The above copyright notice and this permission notice shall be included in
19
 * all copies or substantial portions of the Software.
20
 *
21
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27
 * THE SOFTWARE.
28
 *
29
 * @package	CodeIgniter
30
 * @author	EllisLab Dev Team
31
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
32
 * @copyright	Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
33
 * @license	http://opensource.org/licenses/MIT	MIT License
34
 * @link	https://codeigniter.com
35
 * @since	Version 1.0.0
36
 * @filesource
37
 */
38
defined('BASEPATH') OR exit('No direct script access allowed');
39
 
40
/**
41
 * URI Class
42
 *
43
 * Parses URIs and determines routing
44
 *
45
 * @package		CodeIgniter
46
 * @subpackage	Libraries
47
 * @category	URI
48
 * @author		EllisLab Dev Team
49
 * @link		https://codeigniter.com/user_guide/libraries/uri.html
50
 */
51
class CI_URI {
52
 
53
	/**
54
	 * List of cached URI segments
55
	 *
56
	 * @var	array
57
	 */
58
	public $keyval = array();
59
 
60
	/**
61
	 * Current URI string
62
	 *
63
	 * @var	string
64
	 */
65
	public $uri_string = '';
66
 
67
	/**
68
	 * List of URI segments
69
	 *
70
	 * Starts at 1 instead of 0.
71
	 *
72
	 * @var	array
73
	 */
74
	public $segments = array();
75
 
76
	/**
77
	 * List of routed URI segments
78
	 *
79
	 * Starts at 1 instead of 0.
80
	 *
81
	 * @var	array
82
	 */
83
	public $rsegments = array();
84
 
85
	/**
86
	 * Permitted URI chars
87
	 *
88
	 * PCRE character group allowed in URI segments
89
	 *
90
	 * @var	string
91
	 */
92
	protected $_permitted_uri_chars;
93
 
94
	/**
95
	 * Class constructor
96
	 *
97
	 * @return	void
98
	 */
99
	public function __construct()
100
	{
101
		$this->config =& load_class('Config', 'core');
102
 
103
		// If query strings are enabled, we don't need to parse any segments.
104
		// However, they don't make sense under CLI.
105
		if (is_cli() OR $this->config->item('enable_query_strings') !== TRUE)
106
		{
107
			$this->_permitted_uri_chars = $this->config->item('permitted_uri_chars');
108
 
109
			// If it's a CLI request, ignore the configuration
110
			if (is_cli())
111
			{
112
				$uri = $this->_parse_argv();
113
			}
114
			else
115
			{
116
				$protocol = $this->config->item('uri_protocol');
117
				empty($protocol) && $protocol = 'REQUEST_URI';
118
 
119
				switch ($protocol)
120
				{
121
					case 'AUTO': // For BC purposes only
122
					case 'REQUEST_URI':
123
						$uri = $this->_parse_request_uri();
124
						break;
125
					case 'QUERY_STRING':
126
						$uri = $this->_parse_query_string();
127
						break;
128
					case 'PATH_INFO':
129
					default:
130
						$uri = isset($_SERVER[$protocol])
131
							? $_SERVER[$protocol]
132
							: $this->_parse_request_uri();
133
						break;
134
				}
135
			}
136
 
137
			$this->_set_uri_string($uri);
138
		}
139
 
140
		log_message('info', 'URI Class Initialized');
141
	}
142
 
143
	// --------------------------------------------------------------------
144
 
145
	/**
146
	 * Set URI String
147
	 *
148
	 * @param 	string	$str
149
	 * @return	void
150
	 */
151
	protected function _set_uri_string($str)
152
	{
153
		// Filter out control characters and trim slashes
154
		$this->uri_string = trim(remove_invisible_characters($str, FALSE), '/');
155
 
156
		if ($this->uri_string !== '')
157
		{
158
			// Remove the URL suffix, if present
159
			if (($suffix = (string) $this->config->item('url_suffix')) !== '')
160
			{
161
				$slen = strlen($suffix);
162
 
163
				if (substr($this->uri_string, -$slen) === $suffix)
164
				{
165
					$this->uri_string = substr($this->uri_string, 0, -$slen);
166
				}
167
			}
168
 
169
			$this->segments[0] = NULL;
170
			// Populate the segments array
171
			foreach (explode('/', trim($this->uri_string, '/')) as $val)
172
			{
173
				$val = trim($val);
174
				// Filter segments for security
175
				$this->filter_uri($val);
176
 
177
				if ($val !== '')
178
				{
179
					$this->segments[] = $val;
180
				}
181
			}
182
 
183
			unset($this->segments[0]);
184
		}
185
	}
186
 
187
	// --------------------------------------------------------------------
188
 
189
	/**
190
	 * Parse REQUEST_URI
191
	 *
192
	 * Will parse REQUEST_URI and automatically detect the URI from it,
193
	 * while fixing the query string if necessary.
194
	 *
195
	 * @return	string
196
	 */
197
	protected function _parse_request_uri()
198
	{
199
		if ( ! isset($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME']))
200
		{
201
			return '';
202
		}
203
 
204
		// parse_url() returns false if no host is present, but the path or query string
205
		// contains a colon followed by a number
206
		$uri = parse_url('http://dummy'.$_SERVER['REQUEST_URI']);
207
		$query = isset($uri['query']) ? $uri['query'] : '';
208
		$uri = isset($uri['path']) ? $uri['path'] : '';
209
 
210
		if (isset($_SERVER['SCRIPT_NAME'][0]))
211
		{
212
			if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0)
213
			{
214
				$uri = (string) substr($uri, strlen($_SERVER['SCRIPT_NAME']));
215
			}
216
			elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0)
217
			{
218
				$uri = (string) substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME'])));
219
			}
220
		}
221
 
222
		// This section ensures that even on servers that require the URI to be in the query string (Nginx) a correct
223
		// URI is found, and also fixes the QUERY_STRING server var and $_GET array.
224
		if (trim($uri, '/') === '' && strncmp($query, '/', 1) === 0)
225
		{
226
			$query = explode('?', $query, 2);
227
			$uri = $query[0];
228
			$_SERVER['QUERY_STRING'] = isset($query[1]) ? $query[1] : '';
229
		}
230
		else
231
		{
232
			$_SERVER['QUERY_STRING'] = $query;
233
		}
234
 
235
		parse_str($_SERVER['QUERY_STRING'], $_GET);
236
 
237
		if ($uri === '/' OR $uri === '')
238
		{
239
			return '/';
240
		}
241
 
242
		// Do some final cleaning of the URI and return it
243
		return $this->_remove_relative_directory($uri);
244
	}
245
 
246
	// --------------------------------------------------------------------
247
 
248
	/**
249
	 * Parse QUERY_STRING
250
	 *
251
	 * Will parse QUERY_STRING and automatically detect the URI from it.
252
	 *
253
	 * @return	string
254
	 */
255
	protected function _parse_query_string()
256
	{
257
		$uri = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING');
258
 
259
		if (trim($uri, '/') === '')
260
		{
261
			return '';
262
		}
263
		elseif (strncmp($uri, '/', 1) === 0)
264
		{
265
			$uri = explode('?', $uri, 2);
266
			$_SERVER['QUERY_STRING'] = isset($uri[1]) ? $uri[1] : '';
267
			$uri = $uri[0];
268
		}
269
 
270
		parse_str($_SERVER['QUERY_STRING'], $_GET);
271
 
272
		return $this->_remove_relative_directory($uri);
273
	}
274
 
275
	// --------------------------------------------------------------------
276
 
277
	/**
278
	 * Parse CLI arguments
279
	 *
280
	 * Take each command line argument and assume it is a URI segment.
281
	 *
282
	 * @return	string
283
	 */
284
	protected function _parse_argv()
285
	{
286
		$args = array_slice($_SERVER['argv'], 1);
287
		return $args ? implode('/', $args) : '';
288
	}
289
 
290
	// --------------------------------------------------------------------
291
 
292
	/**
293
	 * Remove relative directory (../) and multi slashes (///)
294
	 *
295
	 * Do some final cleaning of the URI and return it, currently only used in self::_parse_request_uri()
296
	 *
297
	 * @param	string	$uri
298
	 * @return	string
299
	 */
300
	protected function _remove_relative_directory($uri)
301
	{
302
		$uris = array();
303
		$tok = strtok($uri, '/');
304
		while ($tok !== FALSE)
305
		{
306
			if (( ! empty($tok) OR $tok === '0') && $tok !== '..')
307
			{
308
				$uris[] = $tok;
309
			}
310
			$tok = strtok('/');
311
		}
312
 
313
		return implode('/', $uris);
314
	}
315
 
316
	// --------------------------------------------------------------------
317
 
318
	/**
319
	 * Filter URI
320
	 *
321
	 * Filters segments for malicious characters.
322
	 *
323
	 * @param	string	$str
324
	 * @return	void
325
	 */
326
	public function filter_uri(&$str)
327
	{
328
		if ( ! empty($str) && ! empty($this->_permitted_uri_chars) && ! preg_match('/^['.$this->_permitted_uri_chars.']+$/i'.(UTF8_ENABLED ? 'u' : ''), $str))
329
		{
330
			show_error('The URI you submitted has disallowed characters.', 400);
331
		}
332
	}
333
 
334
	// --------------------------------------------------------------------
335
 
336
	/**
337
	 * Fetch URI Segment
338
	 *
339
	 * @see		CI_URI::$segments
340
	 * @param	int		$n		Index
341
	 * @param	mixed		$no_result	What to return if the segment index is not found
342
	 * @return	mixed
343
	 */
344
	public function segment($n, $no_result = NULL)
345
	{
346
		return isset($this->segments[$n]) ? $this->segments[$n] : $no_result;
347
	}
348
 
349
	// --------------------------------------------------------------------
350
 
351
	/**
352
	 * Fetch URI "routed" Segment
353
	 *
354
	 * Returns the re-routed URI segment (assuming routing rules are used)
355
	 * based on the index provided. If there is no routing, will return
356
	 * the same result as CI_URI::segment().
357
	 *
358
	 * @see		CI_URI::$rsegments
359
	 * @see		CI_URI::segment()
360
	 * @param	int		$n		Index
361
	 * @param	mixed		$no_result	What to return if the segment index is not found
362
	 * @return	mixed
363
	 */
364
	public function rsegment($n, $no_result = NULL)
365
	{
366
		return isset($this->rsegments[$n]) ? $this->rsegments[$n] : $no_result;
367
	}
368
 
369
	// --------------------------------------------------------------------
370
 
371
	/**
372
	 * URI to assoc
373
	 *
374
	 * Generates an associative array of URI data starting at the supplied
375
	 * segment index. For example, if this is your URI:
376
	 *
377
	 *	example.com/user/search/name/joe/location/UK/gender/male
378
	 *
379
	 * You can use this method to generate an array with this prototype:
380
	 *
381
	 *	array (
382
	 *		name => joe
383
	 *		location => UK
384
	 *		gender => male
385
	 *	 )
386
	 *
387
	 * @param	int	$n		Index (default: 3)
388
	 * @param	array	$default	Default values
389
	 * @return	array
390
	 */
391
	public function uri_to_assoc($n = 3, $default = array())
392
	{
393
		return $this->_uri_to_assoc($n, $default, 'segment');
394
	}
395
 
396
	// --------------------------------------------------------------------
397
 
398
	/**
399
	 * Routed URI to assoc
400
	 *
401
	 * Identical to CI_URI::uri_to_assoc(), only it uses the re-routed
402
	 * segment array.
403
	 *
404
	 * @see		CI_URI::uri_to_assoc()
405
	 * @param 	int	$n		Index (default: 3)
406
	 * @param 	array	$default	Default values
407
	 * @return 	array
408
	 */
409
	public function ruri_to_assoc($n = 3, $default = array())
410
	{
411
		return $this->_uri_to_assoc($n, $default, 'rsegment');
412
	}
413
 
414
	// --------------------------------------------------------------------
415
 
416
	/**
417
	 * Internal URI-to-assoc
418
	 *
419
	 * Generates a key/value pair from the URI string or re-routed URI string.
420
	 *
421
	 * @used-by	CI_URI::uri_to_assoc()
422
	 * @used-by	CI_URI::ruri_to_assoc()
423
	 * @param	int	$n		Index (default: 3)
424
	 * @param	array	$default	Default values
425
	 * @param	string	$which		Array name ('segment' or 'rsegment')
426
	 * @return	array
427
	 */
428
	protected function _uri_to_assoc($n = 3, $default = array(), $which = 'segment')
429
	{
430
		if ( ! is_numeric($n))
431
		{
432
			return $default;
433
		}
434
 
435
		if (isset($this->keyval[$which], $this->keyval[$which][$n]))
436
		{
437
			return $this->keyval[$which][$n];
438
		}
439
 
440
		$total_segments = "total_{$which}s";
441
		$segment_array = "{$which}_array";
442
 
443
		if ($this->$total_segments() < $n)
444
		{
445
			return (count($default) === 0)
446
				? array()
447
				: array_fill_keys($default, NULL);
448
		}
449
 
450
		$segments = array_slice($this->$segment_array(), ($n - 1));
451
		$i = 0;
452
		$lastval = '';
453
		$retval = array();
454
		foreach ($segments as $seg)
455
		{
456
			if ($i % 2)
457
			{
458
				$retval[$lastval] = $seg;
459
			}
460
			else
461
			{
462
				$retval[$seg] = NULL;
463
				$lastval = $seg;
464
			}
465
 
466
			$i++;
467
		}
468
 
469
		if (count($default) > 0)
470
		{
471
			foreach ($default as $val)
472
			{
473
				if ( ! array_key_exists($val, $retval))
474
				{
475
					$retval[$val] = NULL;
476
				}
477
			}
478
		}
479
 
480
		// Cache the array for reuse
481
		isset($this->keyval[$which]) OR $this->keyval[$which] = array();
482
		$this->keyval[$which][$n] = $retval;
483
		return $retval;
484
	}
485
 
486
	// --------------------------------------------------------------------
487
 
488
	/**
489
	 * Assoc to URI
490
	 *
491
	 * Generates a URI string from an associative array.
492
	 *
493
	 * @param	array	$array	Input array of key/value pairs
494
	 * @return	string	URI string
495
	 */
496
	public function assoc_to_uri($array)
497
	{
498
		$temp = array();
499
		foreach ((array) $array as $key => $val)
500
		{
501
			$temp[] = $key;
502
			$temp[] = $val;
503
		}
504
 
505
		return implode('/', $temp);
506
	}
507
 
508
	// --------------------------------------------------------------------
509
 
510
	/**
511
	 * Slash segment
512
	 *
513
	 * Fetches an URI segment with a slash.
514
	 *
515
	 * @param	int	$n	Index
516
	 * @param	string	$where	Where to add the slash ('trailing' or 'leading')
517
	 * @return	string
518
	 */
519
	public function slash_segment($n, $where = 'trailing')
520
	{
521
		return $this->_slash_segment($n, $where, 'segment');
522
	}
523
 
524
	// --------------------------------------------------------------------
525
 
526
	/**
527
	 * Slash routed segment
528
	 *
529
	 * Fetches an URI routed segment with a slash.
530
	 *
531
	 * @param	int	$n	Index
532
	 * @param	string	$where	Where to add the slash ('trailing' or 'leading')
533
	 * @return	string
534
	 */
535
	public function slash_rsegment($n, $where = 'trailing')
536
	{
537
		return $this->_slash_segment($n, $where, 'rsegment');
538
	}
539
 
540
	// --------------------------------------------------------------------
541
 
542
	/**
543
	 * Internal Slash segment
544
	 *
545
	 * Fetches an URI Segment and adds a slash to it.
546
	 *
547
	 * @used-by	CI_URI::slash_segment()
548
	 * @used-by	CI_URI::slash_rsegment()
549
	 *
550
	 * @param	int	$n	Index
551
	 * @param	string	$where	Where to add the slash ('trailing' or 'leading')
552
	 * @param	string	$which	Array name ('segment' or 'rsegment')
553
	 * @return	string
554
	 */
555
	protected function _slash_segment($n, $where = 'trailing', $which = 'segment')
556
	{
557
		$leading = $trailing = '/';
558
 
559
		if ($where === 'trailing')
560
		{
561
			$leading	= '';
562
		}
563
		elseif ($where === 'leading')
564
		{
565
			$trailing	= '';
566
		}
567
 
568
		return $leading.$this->$which($n).$trailing;
569
	}
570
 
571
	// --------------------------------------------------------------------
572
 
573
	/**
574
	 * Segment Array
575
	 *
576
	 * @return	array	CI_URI::$segments
577
	 */
578
	public function segment_array()
579
	{
580
		return $this->segments;
581
	}
582
 
583
	// --------------------------------------------------------------------
584
 
585
	/**
586
	 * Routed Segment Array
587
	 *
588
	 * @return	array	CI_URI::$rsegments
589
	 */
590
	public function rsegment_array()
591
	{
592
		return $this->rsegments;
593
	}
594
 
595
	// --------------------------------------------------------------------
596
 
597
	/**
598
	 * Total number of segments
599
	 *
600
	 * @return	int
601
	 */
602
	public function total_segments()
603
	{
604
		return count($this->segments);
605
	}
606
 
607
	// --------------------------------------------------------------------
608
 
609
	/**
610
	 * Total number of routed segments
611
	 *
612
	 * @return	int
613
	 */
614
	public function total_rsegments()
615
	{
616
		return count($this->rsegments);
617
	}
618
 
619
	// --------------------------------------------------------------------
620
 
621
	/**
622
	 * Fetch URI string
623
	 *
624
	 * @return	string	CI_URI::$uri_string
625
	 */
626
	public function uri_string()
627
	{
628
		return $this->uri_string;
629
	}
630
 
631
	// --------------------------------------------------------------------
632
 
633
	/**
634
	 * Fetch Re-routed URI string
635
	 *
636
	 * @return	string
637
	 */
638
	public function ruri_string()
639
	{
640
		return ltrim(load_class('Router', 'core')->directory, '/').implode('/', $this->rsegments);
641
	}
642
 
643
}