1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 4.3.2 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2009, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
21 * Loads views and files
23 * @package CodeIgniter
24 * @subpackage Libraries
25 * @author ExpressionEngine Dev Team
27 * @link http://codeigniter.com/user_guide/libraries/loader.html
31 // All these are set automatically. Don't mess with them.
33 var $_ci_view_path = '';
34 var $_ci_is_php5 = FALSE;
35 var $_ci_is_instance = FALSE; // Whether we should use $this or $CI =& get_instance()
36 var $_ci_cached_vars = array();
37 var $_ci_classes = array();
38 var $_ci_loaded_files = array();
39 var $_ci_models = array();
40 var $_ci_helpers = array();
41 var $_ci_plugins = array();
42 var $_ci_varmap = array('unit_test' => 'unit', 'user_agent' => 'agent');
48 * Sets the path to the view files and gets the initial output buffering level
54 $this->_ci_is_php5 = (floor(phpversion()) >= 5) ? TRUE : FALSE;
55 $this->_ci_view_path = APPPATH.'views/';
56 $this->_ci_ob_level = ob_get_level();
58 log_message('debug', "Loader Class Initialized");
61 // --------------------------------------------------------------------
66 * This function lets users load and instantiate classes.
67 * It is designed to be called from a user's app controllers.
70 * @param string the name of the class
71 * @param mixed the optional parameters
72 * @param string an optional object name
75 function library($library = '', $params = NULL, $object_name = NULL)
82 if ( ! is_null($params) AND ! is_array($params))
87 if (is_array($library))
89 foreach ($library as $class)
91 $this->_ci_load_class($class, $params, $object_name);
96 $this->_ci_load_class($library, $params, $object_name);
99 $this->_ci_assign_to_models();
102 // --------------------------------------------------------------------
107 * This function lets users load and instantiate models.
110 * @param string the name of the class
111 * @param string name for the model
112 * @param bool database connection
115 function model($model, $name = '', $db_conn = FALSE)
117 if (is_array($model))
119 foreach($model as $babe)
131 // Is the model in a sub-folder? If so, parse out the filename and path.
132 if (strpos($model, '/') === FALSE)
138 $x = explode('/', $model);
140 unset($x[count($x)-1]);
141 $path = implode('/', $x).'/';
149 if (in_array($name, $this->_ci_models, TRUE))
154 $CI =& get_instance();
155 if (isset($CI->$name))
157 show_error('The model name you are loading is the name of a resource that is already being used: '.$name);
160 $model = strtolower($model);
162 if ( ! file_exists(APPPATH.'models/'.$path.$model.EXT))
164 show_error('Unable to locate the model you have specified: '.$model);
167 if ($db_conn !== FALSE AND ! class_exists('CI_DB'))
169 if ($db_conn === TRUE)
172 $CI->load->database($db_conn, FALSE, TRUE);
175 if ( ! class_exists('Model'))
177 load_class('Model', FALSE);
180 require_once(APPPATH.'models/'.$path.$model.EXT);
182 $model = ucfirst($model);
184 $CI->$name = new $model();
185 $CI->$name->_assign_libraries();
187 $this->_ci_models[] = $name;
190 // --------------------------------------------------------------------
196 * @param string the DB credentials
197 * @param bool whether to return the DB object
198 * @param bool whether to enable active record (this allows us to override the config setting)
201 function database($params = '', $return = FALSE, $active_record = FALSE)
203 // Grab the super object
204 $CI =& get_instance();
206 // Do we even need to load the database class?
207 if (class_exists('CI_DB') AND $return == FALSE AND $active_record == FALSE AND isset($CI->db) AND is_object($CI->db))
212 require_once(BASEPATH.'database/DB'.EXT);
214 if ($return === TRUE)
216 return DB($params, $active_record);
219 // Initialize the db variable. Needed to prevent
220 // reference errors with some configurations
224 $CI->db =& DB($params, $active_record);
226 // Assign the DB object to any existing models
227 $this->_ci_assign_to_models();
230 // --------------------------------------------------------------------
233 * Load the Utilities Class
240 if ( ! class_exists('CI_DB'))
245 $CI =& get_instance();
247 // for backwards compatibility, load dbforge so we can extend dbutils off it
248 // this use is deprecated and strongly discouraged
249 $CI->load->dbforge();
251 require_once(BASEPATH.'database/DB_utility'.EXT);
252 require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_utility'.EXT);
253 $class = 'CI_DB_'.$CI->db->dbdriver.'_utility';
255 $CI->dbutil =& instantiate_class(new $class());
257 $CI->load->_ci_assign_to_models();
260 // --------------------------------------------------------------------
263 * Load the Database Forge Class
270 if ( ! class_exists('CI_DB'))
275 $CI =& get_instance();
277 require_once(BASEPATH.'database/DB_forge'.EXT);
278 require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_forge'.EXT);
279 $class = 'CI_DB_'.$CI->db->dbdriver.'_forge';
281 $CI->dbforge = new $class();
283 $CI->load->_ci_assign_to_models();
286 // --------------------------------------------------------------------
291 * This function is used to load a "view" file. It has three parameters:
293 * 1. The name of the "view" file to be included.
294 * 2. An associative array of data to be extracted for use in the view.
295 * 3. TRUE/FALSE - whether to return the data or load it. In
296 * some cases it's advantageous to be able to return data so that
297 * a developer can process it in some way.
305 function view($view, $vars = array(), $return = FALSE)
307 return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
310 // --------------------------------------------------------------------
315 * This is a generic file loader
322 function file($path, $return = FALSE)
324 return $this->_ci_load(array('_ci_path' => $path, '_ci_return' => $return));
327 // --------------------------------------------------------------------
332 * Once variables are set they become available within
333 * the controller class and its "view" files.
339 function vars($vars = array(), $val = '')
341 if ($val != '' AND is_string($vars))
343 $vars = array($vars => $val);
346 $vars = $this->_ci_object_to_array($vars);
348 if (is_array($vars) AND count($vars) > 0)
350 foreach ($vars as $key => $val)
352 $this->_ci_cached_vars[$key] = $val;
357 // --------------------------------------------------------------------
362 * This function loads the specified helper file.
368 function helper($helpers = array())
370 if ( ! is_array($helpers))
372 $helpers = array($helpers);
375 foreach ($helpers as $helper)
377 $helper = strtolower(str_replace(EXT, '', str_replace('_helper', '', $helper)).'_helper');
379 if (isset($this->_ci_helpers[$helper]))
384 $ext_helper = APPPATH.'helpers/'.config_item('subclass_prefix').$helper.EXT;
386 // Is this a helper extension request?
387 if (file_exists($ext_helper))
389 $base_helper = BASEPATH.'helpers/'.$helper.EXT;
391 if ( ! file_exists($base_helper))
393 show_error('Unable to load the requested file: helpers/'.$helper.EXT);
396 include_once($ext_helper);
397 include_once($base_helper);
399 elseif (file_exists(APPPATH.'helpers/'.$helper.EXT))
401 include_once(APPPATH.'helpers/'.$helper.EXT);
405 if (file_exists(BASEPATH.'helpers/'.$helper.EXT))
407 include_once(BASEPATH.'helpers/'.$helper.EXT);
411 show_error('Unable to load the requested file: helpers/'.$helper.EXT);
415 $this->_ci_helpers[$helper] = TRUE;
416 log_message('debug', 'Helper loaded: '.$helper);
420 // --------------------------------------------------------------------
425 * This is simply an alias to the above function in case the
426 * user has written the plural form of this function.
432 function helpers($helpers = array())
434 $this->helper($helpers);
437 // --------------------------------------------------------------------
442 * This function loads the specified plugin.
448 function plugin($plugins = array())
450 if ( ! is_array($plugins))
452 $plugins = array($plugins);
455 foreach ($plugins as $plugin)
457 $plugin = strtolower(str_replace(EXT, '', str_replace('_pi', '', $plugin)).'_pi');
459 if (isset($this->_ci_plugins[$plugin]))
464 if (file_exists(APPPATH.'plugins/'.$plugin.EXT))
466 include_once(APPPATH.'plugins/'.$plugin.EXT);
470 if (file_exists(BASEPATH.'plugins/'.$plugin.EXT))
472 include_once(BASEPATH.'plugins/'.$plugin.EXT);
476 show_error('Unable to load the requested file: plugins/'.$plugin.EXT);
480 $this->_ci_plugins[$plugin] = TRUE;
481 log_message('debug', 'Plugin loaded: '.$plugin);
485 // --------------------------------------------------------------------
490 * This is simply an alias to the above function in case the
491 * user has written the plural form of this function.
497 function plugins($plugins = array())
499 $this->plugin($plugins);
502 // --------------------------------------------------------------------
505 * Loads a language file
512 function language($file = array(), $lang = '')
514 $CI =& get_instance();
516 if ( ! is_array($file))
518 $file = array($file);
521 foreach ($file as $langfile)
523 $CI->lang->load($langfile, $lang);
528 * Loads language files for scaffolding
534 function scaffold_language($file = '', $lang = '', $return = FALSE)
536 $CI =& get_instance();
537 return $CI->lang->load($file, $lang, $return);
540 // --------------------------------------------------------------------
543 * Loads a config file
549 function config($file = '', $use_sections = FALSE, $fail_gracefully = FALSE)
551 $CI =& get_instance();
552 $CI->config->load($file, $use_sections, $fail_gracefully);
555 // --------------------------------------------------------------------
560 * This initializing function works a bit different than the
561 * others. It doesn't load the class. Instead, it simply
562 * sets a flag indicating that scaffolding is allowed to be
563 * used. The actual scaffolding function below is
564 * called by the front controller based on whether the
565 * second segment of the URL matches the "secret" scaffolding
566 * word stored in the application/config/routes.php
572 function scaffolding($table = '')
574 if ($table === FALSE)
576 show_error('You must include the name of the table you would like to access when you initialize scaffolding');
579 $CI =& get_instance();
580 $CI->_ci_scaffolding = TRUE;
581 $CI->_ci_scaff_table = $table;
584 // --------------------------------------------------------------------
589 * This function is used to load views and files.
590 * Variables are prefixed with _ci_ to avoid symbol collision with
591 * variables made available to view files
597 function _ci_load($_ci_data)
599 // Set the default data variables
600 foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val)
602 $$_ci_val = ( ! isset($_ci_data[$_ci_val])) ? FALSE : $_ci_data[$_ci_val];
605 // Set the path to the requested file
608 $_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION);
609 $_ci_file = ($_ci_ext == '') ? $_ci_view.EXT : $_ci_view;
610 $_ci_path = $this->_ci_view_path.$_ci_file;
614 $_ci_x = explode('/', $_ci_path);
615 $_ci_file = end($_ci_x);
618 if ( ! file_exists($_ci_path))
620 show_error('Unable to load the requested file: '.$_ci_file);
623 // This allows anything loaded using $this->load (views, files, etc.)
624 // to become accessible from within the Controller and Model functions.
625 // Only needed when running PHP 5
627 if ($this->_ci_is_instance())
629 $_ci_CI =& get_instance();
630 foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var)
632 if ( ! isset($this->$_ci_key))
634 $this->$_ci_key =& $_ci_CI->$_ci_key;
640 * Extract and cache variables
642 * You can either set variables using the dedicated $this->load_vars()
643 * function or via the second parameter of this function. We'll merge
644 * the two types and cache them so that views that are embedded within
645 * other views can have access to these variables.
647 if (is_array($_ci_vars))
649 $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars);
651 extract($this->_ci_cached_vars);
656 * We buffer the output for two reasons:
657 * 1. Speed. You get a significant speed boost.
658 * 2. So that the final rendered template can be
659 * post-processed by the output class. Why do we
660 * need post processing? For one thing, in order to
661 * show the elapsed page load time. Unless we
662 * can intercept the content right before it's sent to
663 * the browser and then stop the timer it won't be accurate.
667 // If the PHP installation does not support short tags we'll
668 // do a little string replacement, changing the short tags
669 // to standard PHP echo statements.
671 if ((bool) @ini_get('short_open_tag') === FALSE AND config_item('rewrite_short_tags') == TRUE)
673 echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($_ci_path))));
677 include($_ci_path); // include() vs include_once() allows for multiple views with the same name
680 log_message('debug', 'File loaded: '.$_ci_path);
682 // Return the file data if requested
683 if ($_ci_return === TRUE)
685 $buffer = ob_get_contents();
691 * Flush the buffer... or buff the flusher?
693 * In order to permit views to be nested within
694 * other views, we need to flush the content back out whenever
695 * we are beyond the first level of output buffering so that
696 * it can be seen and included properly by the first included
697 * template and any subsequent ones. Oy!
700 if (ob_get_level() > $this->_ci_ob_level + 1)
706 // PHP 4 requires that we use a global
708 $OUT->append_output(ob_get_contents());
713 // --------------------------------------------------------------------
718 * This function loads the requested class.
721 * @param string the item that is being loaded
722 * @param mixed any additional parameters
723 * @param string an optional object name
726 function _ci_load_class($class, $params = NULL, $object_name = NULL)
728 // Get the class name, and while we're at it trim any slashes.
729 // The directory path can be included as part of the class name,
730 // but we don't want a leading slash
731 $class = str_replace(EXT, '', trim($class, '/'));
733 // Was the path included with the class name?
734 // We look for a slash to determine this
736 if (strpos($class, '/') !== FALSE)
738 // explode the path so we can separate the filename from the path
739 $x = explode('/', $class);
741 // Reset the $class variable now that we know the actual filename
744 // Kill the filename from the array
745 unset($x[count($x)-1]);
747 // Glue the path back together, sans filename
748 $subdir = implode($x, '/').'/';
751 // We'll test for both lowercase and capitalized versions of the file name
752 foreach (array(ucfirst($class), strtolower($class)) as $class)
754 $subclass = APPPATH.'libraries/'.$subdir.config_item('subclass_prefix').$class.EXT;
756 // Is this a class extension request?
757 if (file_exists($subclass))
759 $baseclass = BASEPATH.'libraries/'.ucfirst($class).EXT;
761 if ( ! file_exists($baseclass))
763 log_message('error', "Unable to load the requested class: ".$class);
764 show_error("Unable to load the requested class: ".$class);
767 // Safety: Was the class already loaded by a previous call?
768 if (in_array($subclass, $this->_ci_loaded_files))
770 // Before we deem this to be a duplicate request, let's see
771 // if a custom object name is being supplied. If so, we'll
772 // return a new instance of the object
773 if ( ! is_null($object_name))
775 $CI =& get_instance();
776 if ( ! isset($CI->$object_name))
778 return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name);
782 $is_duplicate = TRUE;
783 log_message('debug', $class." class already loaded. Second attempt ignored.");
787 include_once($baseclass);
788 include_once($subclass);
789 $this->_ci_loaded_files[] = $subclass;
791 return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name);
794 // Lets search for the requested library file and load it.
795 $is_duplicate = FALSE;
796 for ($i = 1; $i < 3; $i++)
798 $path = ($i % 2) ? APPPATH : BASEPATH;
799 $filepath = $path.'libraries/'.$subdir.$class.EXT;
801 // Does the file exist? No? Bummer...
802 if ( ! file_exists($filepath))
807 // Safety: Was the class already loaded by a previous call?
808 if (in_array($filepath, $this->_ci_loaded_files))
810 // Before we deem this to be a duplicate request, let's see
811 // if a custom object name is being supplied. If so, we'll
812 // return a new instance of the object
813 if ( ! is_null($object_name))
815 $CI =& get_instance();
816 if ( ! isset($CI->$object_name))
818 return $this->_ci_init_class($class, '', $params, $object_name);
822 $is_duplicate = TRUE;
823 log_message('debug', $class." class already loaded. Second attempt ignored.");
827 include_once($filepath);
828 $this->_ci_loaded_files[] = $filepath;
829 return $this->_ci_init_class($class, '', $params, $object_name);
833 // One last attempt. Maybe the library is in a subdirectory, but it wasn't specified?
836 $path = strtolower($class).'/'.$class;
837 return $this->_ci_load_class($path, $params);
840 // If we got this far we were unable to find the requested class.
841 // We do not issue errors if the load call failed due to a duplicate request
842 if ($is_duplicate == FALSE)
844 log_message('error', "Unable to load the requested class: ".$class);
845 show_error("Unable to load the requested class: ".$class);
849 // --------------------------------------------------------------------
852 * Instantiates a class
857 * @param string an optional object name
860 function _ci_init_class($class, $prefix = '', $config = FALSE, $object_name = NULL)
862 // Is there an associated config file for this class?
863 if ($config === NULL)
865 // We test for both uppercase and lowercase, for servers that
866 // are case-sensitive with regard to file names
867 if (file_exists(APPPATH.'config/'.strtolower($class).EXT))
869 include_once(APPPATH.'config/'.strtolower($class).EXT);
871 elseif (file_exists(APPPATH.'config/'.ucfirst(strtolower($class)).EXT))
873 include_once(APPPATH.'config/'.ucfirst(strtolower($class)).EXT);
879 if (class_exists('CI_'.$class))
881 $name = 'CI_'.$class;
883 elseif (class_exists(config_item('subclass_prefix').$class))
885 $name = config_item('subclass_prefix').$class;
894 $name = $prefix.$class;
897 // Is the class name valid?
898 if ( ! class_exists($name))
900 log_message('error', "Non-existent class: ".$name);
901 show_error("Non-existent class: ".$class);
904 // Set the variable name we will assign the class to
905 // Was a custom class name supplied? If so we'll use it
906 $class = strtolower($class);
908 if (is_null($object_name))
910 $classvar = ( ! isset($this->_ci_varmap[$class])) ? $class : $this->_ci_varmap[$class];
914 $classvar = $object_name;
917 // Save the class name and object name
918 $this->_ci_classes[$class] = $classvar;
920 // Instantiate the class
921 $CI =& get_instance();
922 if ($config !== NULL)
924 $CI->$classvar = new $name($config);
928 $CI->$classvar = new $name;
932 // --------------------------------------------------------------------
937 * The config/autoload.php file contains an array that permits sub-systems,
938 * libraries, plugins, and helpers to be loaded automatically.
944 function _ci_autoloader()
946 include_once(APPPATH.'config/autoload'.EXT);
948 if ( ! isset($autoload))
953 // Load any custom config file
954 if (count($autoload['config']) > 0)
956 $CI =& get_instance();
957 foreach ($autoload['config'] as $key => $val)
959 $CI->config->load($val);
963 // Autoload plugins, helpers and languages
964 foreach (array('helper', 'plugin', 'language') as $type)
966 if (isset($autoload[$type]) AND count($autoload[$type]) > 0)
968 $this->$type($autoload[$type]);
972 // A little tweak to remain backward compatible
973 // The $autoload['core'] item was deprecated
974 if ( ! isset($autoload['libraries']))
976 $autoload['libraries'] = $autoload['core'];
980 if (isset($autoload['libraries']) AND count($autoload['libraries']) > 0)
982 // Load the database driver.
983 if (in_array('database', $autoload['libraries']))
986 $autoload['libraries'] = array_diff($autoload['libraries'], array('database'));
990 if (in_array('scaffolding', $autoload['libraries']))
992 $this->scaffolding();
993 $autoload['libraries'] = array_diff($autoload['libraries'], array('scaffolding'));
996 // Load all other libraries
997 foreach ($autoload['libraries'] as $item)
999 $this->library($item);
1004 if (isset($autoload['model']))
1006 $this->model($autoload['model']);
1011 // --------------------------------------------------------------------
1016 * Makes sure that anything loaded by the loader class (libraries, plugins, etc.)
1017 * will be available to models, if any exist.
1023 function _ci_assign_to_models()
1025 if (count($this->_ci_models) == 0)
1030 if ($this->_ci_is_instance())
1032 $CI =& get_instance();
1033 foreach ($this->_ci_models as $model)
1035 $CI->$model->_assign_libraries();
1040 foreach ($this->_ci_models as $model)
1042 $this->$model->_assign_libraries();
1047 // --------------------------------------------------------------------
1052 * Takes an object as input and converts the class variables to array key/vals
1058 function _ci_object_to_array($object)
1060 return (is_object($object)) ? get_object_vars($object) : $object;
1063 // --------------------------------------------------------------------
1066 * Determines whether we should use the CI instance or $this
1071 function _ci_is_instance()
1073 if ($this->_ci_is_php5 == TRUE)
1079 return (is_object($CI)) ? TRUE : FALSE;
1084 /* End of file Loader.php */
1085 /* Location: ./system/libraries/Loader.php */