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