blob: e2a14800dbc422e486e9b7e509f743f6ed11683f [file] [log] [blame]
Derek Allarda72b60d2007-01-31 23:56:11 +00001<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
2/**
Derek Allardd2df9bc2007-04-15 17:41:17 +00003 * CodeIgniter
Derek Allarda72b60d2007-01-31 23:56:11 +00004 *
5 * An open source application development framework for PHP 4.3.2 or newer
6 *
7 * @package CodeIgniter
8 * @author Rick Ellis
Derek Allardd2df9bc2007-04-15 17:41:17 +00009 * @copyright Copyright (c) 2006, EllisLab, Inc.
Derek Allarda72b60d2007-01-31 23:56:11 +000010 * @license http://www.codeignitor.com/user_guide/license.html
11 * @link http://www.codeigniter.com
12 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * Router Class
20 *
21 * Parses URIs and determines routing
22 *
23 * @package CodeIgniter
24 * @subpackage Libraries
25 * @author Rick Ellis
26 * @category Libraries
27 * @link http://www.codeigniter.com/user_guide/general/routing.html
28 */
29class CI_Router {
30
31 var $config;
32 var $uri_string = '';
33 var $segments = array();
34 var $rsegments = array();
35 var $routes = array();
36 var $error_routes = array();
37 var $class = '';
38 var $method = 'index';
39 var $directory = '';
40 var $uri_protocol = 'auto';
41 var $default_controller;
42 var $scaffolding_request = FALSE; // Must be set to FALSE
43
44 /**
45 * Constructor
46 *
47 * Runs the route mapping function.
48 */
49 function CI_Router()
50 {
51 $this->config =& load_class('Config');
paulburdick35413132007-06-27 23:25:19 +000052 $this->input =& load_class('Input');
Derek Allarda72b60d2007-01-31 23:56:11 +000053 $this->_set_route_mapping();
54 log_message('debug', "Router Class Initialized");
55 }
56
57 // --------------------------------------------------------------------
58
59 /**
60 * Set the route mapping
61 *
62 * This function determines what should be served based on the URI request,
63 * as well as any "routes" that have been set in the routing config file.
64 *
65 * @access private
66 * @return void
67 */
68 function _set_route_mapping()
69 {
70 // Are query strings enabled in the config file?
71 // If so, we're done since segment based URIs are not used with query strings.
72 if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('controller_trigger')]))
73 {
74 $this->set_class($_GET[$this->config->item('controller_trigger')]);
75
76 if (isset($_GET[$this->config->item('function_trigger')]))
77 {
78 $this->set_method($_GET[$this->config->item('function_trigger')]);
79 }
80
81 return;
82 }
83
84 // Load the routes.php file.
85 @include(APPPATH.'config/routes'.EXT);
86 $this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route;
87 unset($route);
88
89 // Set the default controller so we can display it in the event
90 // the URI doesn't correlated to a valid controller.
91 $this->default_controller = ( ! isset($this->routes['default_controller']) OR $this->routes['default_controller'] == '') ? FALSE : strtolower($this->routes['default_controller']);
92
93 // Fetch the complete URI string
94 $this->uri_string = $this->_get_uri_string();
95
96 // If the URI contains only a slash we'll kill it
97 if ($this->uri_string == '/')
98 {
99 $this->uri_string = '';
100 }
101
102 // Is there a URI string? If not, the default controller specified in the "routes" file will be shown.
103 if ($this->uri_string == '')
104 {
105 if ($this->default_controller === FALSE)
106 {
107 show_error("Unable to determine what should be displayed. A default route has not been specified in the routing file.");
108 }
109
110 $this->set_class($this->default_controller);
111 $this->set_method('index');
112
113 log_message('debug', "No URI present. Default controller set.");
114 return;
115 }
116 unset($this->routes['default_controller']);
117
118 // Do we need to remove the suffix specified in the config file?
119 if ($this->config->item('url_suffix') != "")
120 {
121 $this->uri_string = preg_replace("|".preg_quote($this->config->item('url_suffix'))."$|", "", $this->uri_string);
122 }
123
124 // Explode the URI Segments. The individual segments will
125 // be stored in the $this->segments array.
126 foreach(explode("/", preg_replace("|/*(.+?)/*$|", "\\1", $this->uri_string)) as $val)
127 {
128 // Filter segments for security
129 $val = trim($this->_filter_uri($val));
130
131 if ($val != '')
132 $this->segments[] = $val;
133 }
134
135 // Parse any custom routing that may exist
136 $this->_parse_routes();
137
138 // Re-index the segment array so that it starts with 1 rather than 0
139 $this->_reindex_segments();
140 }
141
142 // --------------------------------------------------------------------
143
144 /**
145 * Compile Segments
146 *
147 * This function takes an array of URI segments as
148 * input, and puts it into the $this->segments array.
149 * It also sets the current class/method
150 *
151 * @access private
152 * @param array
153 * @param bool
154 * @return void
155 */
156 function _compile_segments($segments = array())
157 {
158 $segments = $this->_validate_segments($segments);
159
160 if (count($segments) == 0)
161 {
162 return;
163 }
164
165 $this->set_class($segments[0]);
166
167 if (isset($segments[1]))
168 {
169 // A scaffolding request. No funny business with the URL
170 if ($this->routes['scaffolding_trigger'] == $segments[1] AND $segments[1] != '_ci_scaffolding')
171 {
172 $this->scaffolding_request = TRUE;
173 unset($this->routes['scaffolding_trigger']);
174 }
175 else
176 {
177 // A standard method request
178 $this->set_method($segments[1]);
179 }
180 }
181
182 // Update our "routed" segment array to contain the segments.
183 // Note: If there is no custom routing, this array will be
184 // identical to $this->segments
185 $this->rsegments = $segments;
186 }
187
188 // --------------------------------------------------------------------
189
190 /**
191 * Validates the supplied segments. Attempts to determine the path to
192 * the controller.
193 *
194 * @access private
195 * @param array
196 * @return array
197 */
198 function _validate_segments($segments)
199 {
200 // Does the requested controller exist in the root folder?
201 if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
202 {
203 return $segments;
204 }
205
206 // Is the controller in a sub-folder?
207 if (is_dir(APPPATH.'controllers/'.$segments[0]))
208 {
209 // Set the directory and remove it from the segment array
210 $this->set_directory($segments[0]);
211 $segments = array_slice($segments, 1);
212
213 if (count($segments) > 0)
214 {
215 // Does the requested controller exist in the sub-folder?
216 if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
217 {
218 show_404();
219 }
220 }
221 else
222 {
223 $this->set_class($this->default_controller);
224 $this->set_method('index');
225
226 // Does the default controller exist in the sub-folder?
227 if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
228 {
229 $this->directory = '';
230 return array();
231 }
232
233 }
234
235 return $segments;
236 }
237
238 // Can't find the requested controller...
239 show_404();
240 }
241
242 // --------------------------------------------------------------------
243 /**
244 * Re-index Segments
245 *
246 * This function re-indexes the $this->segment array so that it
247 * starts at 1 rather then 0. Doing so makes it simpler to
248 * use functions like $this->uri->segment(n) since there is
249 * a 1:1 relationship between the segment array and the actual segments.
250 *
251 * @access private
252 * @return void
253 */
254 function _reindex_segments()
255 {
256 // Is the routed segment array different then the main segment array?
257 $diff = (count(array_diff($this->rsegments, $this->segments)) == 0) ? FALSE : TRUE;
258
259 $i = 1;
260 foreach ($this->segments as $val)
261 {
262 $this->segments[$i++] = $val;
263 }
264 unset($this->segments[0]);
265
266 if ($diff == FALSE)
267 {
268 $this->rsegments = $this->segments;
269 }
270 else
271 {
272 $i = 1;
273 foreach ($this->rsegments as $val)
274 {
275 $this->rsegments[$i++] = $val;
276 }
277 unset($this->rsegments[0]);
278 }
279 }
280
281 // --------------------------------------------------------------------
282
283 /**
284 * Get the URI String
285 *
286 * @access private
287 * @return string
288 */
289 function _get_uri_string()
290 {
291 if (strtoupper($this->config->item('uri_protocol')) == 'AUTO')
292 {
293 // If the URL has a question mark then it's simplest to just
294 // build the URI string from the zero index of the $_GET array.
295 // This avoids having to deal with $_SERVER variables, which
296 // can be unreliable in some environments
297 if (is_array($_GET) AND count($_GET) == 1)
298 {
299 // Note: Due to a bug in current() that affects some versions
300 // of PHP we can not pass function call directly into it
301 $keys = array_keys($_GET);
302 return current($keys);
303 }
304
305 // Is there a PATH_INFO variable?
306 // Note: some servers seem to have trouble with getenv() so we'll test it two ways
Rick Ellisf6603152007-06-09 01:16:00 +0000307 $path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO');
Derek Allarda72b60d2007-01-31 23:56:11 +0000308 if ($path != '' AND $path != "/".SELF)
309 {
310 return $path;
311 }
312
313 // No PATH_INFO?... What about QUERY_STRING?
314 $path = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING');
315 if ($path != '')
316 {
317 return $path;
318 }
319
320 // No QUERY_STRING?... Maybe the ORIG_PATH_INFO variable exists?
321 $path = (isset($_SERVER['ORIG_PATH_INFO'])) ? $_SERVER['ORIG_PATH_INFO'] : @getenv('ORIG_PATH_INFO');
322 if ($path != '' AND $path != "/".SELF)
323 {
324 return $path;
325 }
326
327 // We've exhausted all our options...
328 return '';
329 }
330 else
331 {
332 $uri = strtoupper($this->config->item('uri_protocol'));
333
334 if ($uri == 'REQUEST_URI')
335 {
336 return $this->_parse_request_uri();
337 }
338
339 return (isset($_SERVER[$uri])) ? $_SERVER[$uri] : @getenv($uri);
340 }
341 }
342
343 // --------------------------------------------------------------------
344
345 /**
346 * Parse the REQUEST_URI
347 *
348 * Due to the way REQUEST_URI works it usually contains path info
349 * that makes it unusable as URI data. We'll trim off the unnecessary
350 * data, hopefully arriving at a valid URI that we can use.
351 *
352 * @access private
353 * @return string
354 */
355 function _parse_request_uri()
356 {
357 if ( ! isset($_SERVER['REQUEST_URI']) OR $_SERVER['REQUEST_URI'] == '')
358 {
359 return '';
360 }
361
362 $request_uri = preg_replace("|/(.*)|", "\\1", str_replace("\\", "/", $_SERVER['REQUEST_URI']));
363
364 if ($request_uri == '' OR $request_uri == SELF)
365 {
366 return '';
367 }
368
369 $fc_path = FCPATH;
370 if (strpos($request_uri, '?') !== FALSE)
371 {
372 $fc_path .= '?';
373 }
374
375 $parsed_uri = explode("/", $request_uri);
376
377 $i = 0;
378 foreach(explode("/", $fc_path) as $segment)
379 {
380 if (isset($parsed_uri[$i]) AND $segment == $parsed_uri[$i])
381 {
382 $i++;
383 }
384 }
385
386 $parsed_uri = implode("/", array_slice($parsed_uri, $i));
387
388 if ($parsed_uri != '')
389 {
390 $parsed_uri = '/'.$parsed_uri;
391 }
392
393 return $parsed_uri;
394 }
395
396 // --------------------------------------------------------------------
397
398 /**
399 * Filter segments for malicious characters
400 *
401 * @access private
402 * @param string
403 * @return string
404 */
405 function _filter_uri($str)
406 {
407 if ($this->config->item('permitted_uri_chars') != '')
408 {
409 if ( ! preg_match("|^[".preg_quote($this->config->item('permitted_uri_chars'))."]+$|i", $str))
410 {
411 exit('The URI you submitted has disallowed characters.');
412 }
413 }
414 return $str;
415 }
416
417 // --------------------------------------------------------------------
418
419 /**
420 * Parse Routes
421 *
422 * This function matches any routes that may exist in
423 * the config/routes.php file against the URI to
424 * determine if the class/method need to be remapped.
425 *
426 * @access private
427 * @return void
428 */
429 function _parse_routes()
430 {
431 // Do we even have any custom routing to deal with?
Derek Allard445b24d2007-04-24 12:48:19 +0000432 // There is a default scaffolding trigger, so we'll look just for 1
433 if (count($this->routes) == 1)
Derek Allarda72b60d2007-01-31 23:56:11 +0000434 {
435 $this->_compile_segments($this->segments);
436 return;
437 }
Derek Allard445b24d2007-04-24 12:48:19 +0000438
Derek Allarda72b60d2007-01-31 23:56:11 +0000439 // Turn the segment array into a URI string
440 $uri = implode('/', $this->segments);
441 $num = count($this->segments);
442
443 // Is there a literal match? If so we're done
444 if (isset($this->routes[$uri]))
445 {
446 $this->_compile_segments(explode('/', $this->routes[$uri]));
447 return;
448 }
449
450 // Loop through the route array looking for wild-cards
451 foreach (array_slice($this->routes, 1) as $key => $val)
452 {
453 // Convert wild-cards to RegEx
454 $key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));
455
456 // Does the RegEx match?
457 if (preg_match('#^'.$key.'$#', $uri))
458 {
459 // Do we have a back-reference?
460 if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE)
461 {
462 $val = preg_replace('#^'.$key.'$#', $val, $uri);
463 }
464
465 $this->_compile_segments(explode('/', $val));
466 return;
467 }
468 }
469
470 // If we got this far it means we didn't encounter a
471 // matching route so we'll set the site default route
472 $this->_compile_segments($this->segments);
473 }
474
475 // --------------------------------------------------------------------
476
477 /**
478 * Set the class name
479 *
480 * @access public
481 * @param string
482 * @return void
483 */
484 function set_class($class)
485 {
paulburdick35413132007-06-27 23:25:19 +0000486 $this->class = $this->input->filename_security($class);
Derek Allarda72b60d2007-01-31 23:56:11 +0000487 }
488
489 // --------------------------------------------------------------------
490
491 /**
492 * Fetch the current class
493 *
494 * @access public
495 * @return string
496 */
497 function fetch_class()
498 {
499 return $this->class;
500 }
501
502 // --------------------------------------------------------------------
503
504 /**
505 * Set the method name
506 *
507 * @access public
508 * @param string
509 * @return void
510 */
511 function set_method($method)
512 {
paulburdick35413132007-06-27 23:25:19 +0000513 $this->method = $this->input->filename_security($method);
Derek Allarda72b60d2007-01-31 23:56:11 +0000514 }
515
516 // --------------------------------------------------------------------
517
518 /**
519 * Fetch the current method
520 *
521 * @access public
522 * @return string
523 */
524 function fetch_method()
525 {
526 if ($this->method == $this->fetch_class())
527 {
528 return 'index';
529 }
530
531 return $this->method;
532 }
533
534 // --------------------------------------------------------------------
535
536 /**
537 * Set the directory name
538 *
539 * @access public
540 * @param string
541 * @return void
542 */
543 function set_directory($dir)
544 {
paulburdick35413132007-06-27 23:25:19 +0000545 $this->directory = $this->input->filename_security($dir).'/';
Derek Allarda72b60d2007-01-31 23:56:11 +0000546 }
547
548 // --------------------------------------------------------------------
549
550 /**
551 * Fetch the sub-directory (if any) that contains the requested controller class
552 *
553 * @access public
554 * @return string
555 */
556 function fetch_directory()
557 {
558 return $this->directory;
559 }
560
561}
562// END Router Class
adminb0dd10f2006-08-25 17:25:49 +0000563?>