<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Author: Remy Sharp (http://remysharp.com)
 *
 * Based on CodeIgniter Router.php 1.6.1
 * 
 * Description: Reroutes 404s to our bespoke controller (missing) which
 * will check $this->uri->segment(1) (the requested URL) against the 
 * database, and if nothing is found, will call show_404();
 * 
 * VERSION: 1.0 (2008-03-25)
 * 
 **/

class MY_Router extends CI_Router {
    /**
     * Constructor 
     *
     */    
    function MY_Router() {   
        parent::CI_Router(); 
        
        log_message('debug', "Custom Router Class Initialized");
    }
    
    function missing_controller($segments) {
        // this controller will lookup the URI segment in the database, and if nothing is
        // found, it will run the show_404()
        $this->set_class('missing');
        $this->set_method('index');
        return array('missing'); // note that we return the class name here too.
    }
    
    /**
     * Taken directly from Router.php (1.6.1) - to 'overload' the 404 method
     *
     * If CodeIgniter is updated, this function should be updated too.
     * 
     * Validates the supplied segments.  Attempts to determine the path to
     * the controller.
     *
     * @access  private
     * @param   array
     * @return  array
     */ 
    function _validate_request($segments)
    {
        // Does the requested controller exist in the root folder?
        if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
        {
            return $segments;
        }

        // Is the controller in a sub-folder?
        if (is_dir(APPPATH.'controllers/'.$segments[0]))
        {       
            // Set the directory and remove it from the segment array
            $this->set_directory($segments[0]);
            $segments = array_slice($segments, 1);
            
            if (count($segments) > 0)
            {
                // Does the requested controller exist in the sub-folder?
                if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
                {
                    return $this->missing_controller($segments);
                }
            }
            else
            {
                $this->set_class($this->default_controller);
                $this->set_method('index');
            
                // Does the default controller exist in the sub-folder?
                if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
                {
                    $this->directory = '';
                    return array();
                }
            
            }
                
            return $segments;
        }
    
        // Can't find the requested controller...
        return $this->missing_controller($segments);
    }
    
}
// END Router Class
?>