PageRenderTime 29ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/system/core/Loader.php

http://github.com/EllisLab/CodeIgniter
PHP | 1405 lines | 722 code | 179 blank | 504 comment | 95 complexity | f582f107e7cac87fb524a60b76e6cc3e MD5 | raw file
Possible License(s): CC-BY-SA-3.0
  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 - 2019, 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 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  33. * @license https://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. * Loader Class
  41. *
  42. * Loads framework components.
  43. *
  44. * @package CodeIgniter
  45. * @subpackage Libraries
  46. * @category Loader
  47. * @author EllisLab Dev Team
  48. * @link https://codeigniter.com/userguide3/libraries/loader.html
  49. */
  50. class CI_Loader {
  51. // All these are set automatically. Don't mess with them.
  52. /**
  53. * Nesting level of the output buffering mechanism
  54. *
  55. * @var int
  56. */
  57. protected $_ci_ob_level;
  58. /**
  59. * List of paths to load views from
  60. *
  61. * @var array
  62. */
  63. protected $_ci_view_paths = array(VIEWPATH => TRUE);
  64. /**
  65. * List of paths to load libraries from
  66. *
  67. * @var array
  68. */
  69. protected $_ci_library_paths = array(APPPATH, BASEPATH);
  70. /**
  71. * List of paths to load models from
  72. *
  73. * @var array
  74. */
  75. protected $_ci_model_paths = array(APPPATH);
  76. /**
  77. * List of paths to load helpers from
  78. *
  79. * @var array
  80. */
  81. protected $_ci_helper_paths = array(APPPATH, BASEPATH);
  82. /**
  83. * List of cached variables
  84. *
  85. * @var array
  86. */
  87. protected $_ci_cached_vars = array();
  88. /**
  89. * List of loaded classes
  90. *
  91. * @var array
  92. */
  93. protected $_ci_classes = array();
  94. /**
  95. * List of loaded models
  96. *
  97. * @var array
  98. */
  99. protected $_ci_models = array();
  100. /**
  101. * List of loaded helpers
  102. *
  103. * @var array
  104. */
  105. protected $_ci_helpers = array();
  106. /**
  107. * List of class name mappings
  108. *
  109. * @var array
  110. */
  111. protected $_ci_varmap = array(
  112. 'unit_test' => 'unit',
  113. 'user_agent' => 'agent'
  114. );
  115. // --------------------------------------------------------------------
  116. /**
  117. * Class constructor
  118. *
  119. * Sets component load paths, gets the initial output buffering level.
  120. *
  121. * @return void
  122. */
  123. public function __construct()
  124. {
  125. $this->_ci_ob_level = ob_get_level();
  126. $this->_ci_classes =& is_loaded();
  127. log_message('info', 'Loader Class Initialized');
  128. }
  129. // --------------------------------------------------------------------
  130. /**
  131. * Initializer
  132. *
  133. * @todo Figure out a way to move this to the constructor
  134. * without breaking *package_path*() methods.
  135. * @uses CI_Loader::_ci_autoloader()
  136. * @used-by CI_Controller::__construct()
  137. * @return void
  138. */
  139. public function initialize()
  140. {
  141. $this->_ci_autoloader();
  142. }
  143. // --------------------------------------------------------------------
  144. /**
  145. * Is Loaded
  146. *
  147. * A utility method to test if a class is in the self::$_ci_classes array.
  148. *
  149. * @used-by Mainly used by Form Helper function _get_validation_object().
  150. *
  151. * @param string $class Class name to check for
  152. * @return string|bool Class object name if loaded or FALSE
  153. */
  154. public function is_loaded($class)
  155. {
  156. return array_search(ucfirst($class), $this->_ci_classes, TRUE);
  157. }
  158. // --------------------------------------------------------------------
  159. /**
  160. * Library Loader
  161. *
  162. * Loads and instantiates libraries.
  163. * Designed to be called from application controllers.
  164. *
  165. * @param mixed $library Library name
  166. * @param array $params Optional parameters to pass to the library class constructor
  167. * @param string $object_name An optional object name to assign to
  168. * @return object
  169. */
  170. public function library($library, $params = NULL, $object_name = NULL)
  171. {
  172. if (empty($library))
  173. {
  174. return $this;
  175. }
  176. elseif (is_array($library))
  177. {
  178. foreach ($library as $key => $value)
  179. {
  180. if (is_int($key))
  181. {
  182. $this->library($value, $params);
  183. }
  184. else
  185. {
  186. $this->library($key, $params, $value);
  187. }
  188. }
  189. return $this;
  190. }
  191. if ($params !== NULL && ! is_array($params))
  192. {
  193. $params = NULL;
  194. }
  195. $this->_ci_load_library($library, $params, $object_name);
  196. return $this;
  197. }
  198. // --------------------------------------------------------------------
  199. /**
  200. * Model Loader
  201. *
  202. * Loads and instantiates models.
  203. *
  204. * @param mixed $model Model name
  205. * @param string $name An optional object name to assign to
  206. * @param bool $db_conn An optional database connection configuration to initialize
  207. * @return object
  208. */
  209. public function model($model, $name = '', $db_conn = FALSE)
  210. {
  211. if (empty($model))
  212. {
  213. return $this;
  214. }
  215. elseif (is_array($model))
  216. {
  217. foreach ($model as $key => $value)
  218. {
  219. is_int($key) ? $this->model($value, '', $db_conn) : $this->model($key, $value, $db_conn);
  220. }
  221. return $this;
  222. }
  223. $path = '';
  224. // Is the model in a sub-folder? If so, parse out the filename and path.
  225. if (($last_slash = strrpos($model, '/')) !== FALSE)
  226. {
  227. // The path is in front of the last slash
  228. $path = substr($model, 0, ++$last_slash);
  229. // And the model name behind it
  230. $model = substr($model, $last_slash);
  231. }
  232. if (empty($name))
  233. {
  234. $name = $model;
  235. }
  236. if (in_array($name, $this->_ci_models, TRUE))
  237. {
  238. return $this;
  239. }
  240. $CI =& get_instance();
  241. if (isset($CI->$name))
  242. {
  243. throw new RuntimeException('The model name you are loading is the name of a resource that is already being used: '.$name);
  244. }
  245. if ($db_conn !== FALSE && ! class_exists('CI_DB', FALSE))
  246. {
  247. if ($db_conn === TRUE)
  248. {
  249. $db_conn = '';
  250. }
  251. $this->database($db_conn, FALSE, TRUE);
  252. }
  253. // Note: All of the code under this condition used to be just:
  254. //
  255. // load_class('Model', 'core');
  256. //
  257. // However, load_class() instantiates classes
  258. // to cache them for later use and that prevents
  259. // MY_Model from being an abstract class and is
  260. // sub-optimal otherwise anyway.
  261. if ( ! class_exists('CI_Model', FALSE))
  262. {
  263. $app_path = APPPATH.'core'.DIRECTORY_SEPARATOR;
  264. if (file_exists($app_path.'Model.php'))
  265. {
  266. require_once($app_path.'Model.php');
  267. if ( ! class_exists('CI_Model', FALSE))
  268. {
  269. throw new RuntimeException($app_path."Model.php exists, but doesn't declare class CI_Model");
  270. }
  271. log_message('info', 'CI_Model class loaded');
  272. }
  273. elseif ( ! class_exists('CI_Model', FALSE))
  274. {
  275. require_once(BASEPATH.'core'.DIRECTORY_SEPARATOR.'Model.php');
  276. }
  277. $class = config_item('subclass_prefix').'Model';
  278. if (file_exists($app_path.$class.'.php'))
  279. {
  280. require_once($app_path.$class.'.php');
  281. if ( ! class_exists($class, FALSE))
  282. {
  283. throw new RuntimeException($app_path.$class.".php exists, but doesn't declare class ".$class);
  284. }
  285. log_message('info', config_item('subclass_prefix').'Model class loaded');
  286. }
  287. }
  288. $model = ucfirst($model);
  289. if ( ! class_exists($model, FALSE))
  290. {
  291. foreach ($this->_ci_model_paths as $mod_path)
  292. {
  293. if ( ! file_exists($mod_path.'models/'.$path.$model.'.php'))
  294. {
  295. continue;
  296. }
  297. require_once($mod_path.'models/'.$path.$model.'.php');
  298. if ( ! class_exists($model, FALSE))
  299. {
  300. throw new RuntimeException($mod_path."models/".$path.$model.".php exists, but doesn't declare class ".$model);
  301. }
  302. break;
  303. }
  304. if ( ! class_exists($model, FALSE))
  305. {
  306. throw new RuntimeException('Unable to locate the model you have specified: '.$model);
  307. }
  308. }
  309. if ( ! is_subclass_of($model, 'CI_Model'))
  310. {
  311. throw new RuntimeException("Class ".$model." doesn't extend CI_Model");
  312. }
  313. $this->_ci_models[] = $name;
  314. $model = new $model();
  315. $CI->$name = $model;
  316. log_message('info', 'Model "'.get_class($model).'" initialized');
  317. return $this;
  318. }
  319. // --------------------------------------------------------------------
  320. /**
  321. * Database Loader
  322. *
  323. * @param mixed $params Database configuration options
  324. * @param bool $return Whether to return the database object
  325. * @param bool $query_builder Whether to enable Query Builder
  326. * (overrides the configuration setting)
  327. *
  328. * @return object|bool Database object if $return is set to TRUE,
  329. * FALSE on failure, CI_Loader instance in any other case
  330. */
  331. public function database($params = '', $return = FALSE, $query_builder = NULL)
  332. {
  333. // Grab the super object
  334. $CI =& get_instance();
  335. // Do we even need to load the database class?
  336. if ($return === FALSE && $query_builder === NULL && isset($CI->db) && is_object($CI->db) && ! empty($CI->db->conn_id))
  337. {
  338. return FALSE;
  339. }
  340. require_once(BASEPATH.'database/DB.php');
  341. if ($return === TRUE)
  342. {
  343. return DB($params, $query_builder);
  344. }
  345. // Initialize the db variable. Needed to prevent
  346. // reference errors with some configurations
  347. $CI->db = '';
  348. // Load the DB class
  349. $CI->db =& DB($params, $query_builder);
  350. return $this;
  351. }
  352. // --------------------------------------------------------------------
  353. /**
  354. * Load the Database Utilities Class
  355. *
  356. * @param object $db Database object
  357. * @param bool $return Whether to return the DB Utilities class object or not
  358. * @return object
  359. */
  360. public function dbutil($db = NULL, $return = FALSE)
  361. {
  362. $CI =& get_instance();
  363. if ( ! is_object($db) OR ! ($db instanceof CI_DB))
  364. {
  365. class_exists('CI_DB', FALSE) OR $this->database();
  366. $db =& $CI->db;
  367. }
  368. require_once(BASEPATH.'database/DB_utility.php');
  369. require_once(BASEPATH.'database/drivers/'.$db->dbdriver.'/'.$db->dbdriver.'_utility.php');
  370. $class = 'CI_DB_'.$db->dbdriver.'_utility';
  371. if ($return === TRUE)
  372. {
  373. return new $class($db);
  374. }
  375. $CI->dbutil = new $class($db);
  376. return $this;
  377. }
  378. // --------------------------------------------------------------------
  379. /**
  380. * Load the Database Forge Class
  381. *
  382. * @param object $db Database object
  383. * @param bool $return Whether to return the DB Forge class object or not
  384. * @return object
  385. */
  386. public function dbforge($db = NULL, $return = FALSE)
  387. {
  388. $CI =& get_instance();
  389. if ( ! is_object($db) OR ! ($db instanceof CI_DB))
  390. {
  391. class_exists('CI_DB', FALSE) OR $this->database();
  392. $db =& $CI->db;
  393. }
  394. require_once(BASEPATH.'database/DB_forge.php');
  395. require_once(BASEPATH.'database/drivers/'.$db->dbdriver.'/'.$db->dbdriver.'_forge.php');
  396. if ( ! empty($db->subdriver))
  397. {
  398. $driver_path = BASEPATH.'database/drivers/'.$db->dbdriver.'/subdrivers/'.$db->dbdriver.'_'.$db->subdriver.'_forge.php';
  399. if (file_exists($driver_path))
  400. {
  401. require_once($driver_path);
  402. $class = 'CI_DB_'.$db->dbdriver.'_'.$db->subdriver.'_forge';
  403. }
  404. }
  405. else
  406. {
  407. $class = 'CI_DB_'.$db->dbdriver.'_forge';
  408. }
  409. if ($return === TRUE)
  410. {
  411. return new $class($db);
  412. }
  413. $CI->dbforge = new $class($db);
  414. return $this;
  415. }
  416. // --------------------------------------------------------------------
  417. /**
  418. * View Loader
  419. *
  420. * Loads "view" files.
  421. *
  422. * @param string $view View name
  423. * @param array $vars An associative array of data
  424. * to be extracted for use in the view
  425. * @param bool $return Whether to return the view output
  426. * or leave it to the Output class
  427. * @return object|string
  428. */
  429. public function view($view, $vars = array(), $return = FALSE)
  430. {
  431. return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return));
  432. }
  433. // --------------------------------------------------------------------
  434. /**
  435. * Generic File Loader
  436. *
  437. * @param string $path File path
  438. * @param bool $return Whether to return the file output
  439. * @return object|string
  440. */
  441. public function file($path, $return = FALSE)
  442. {
  443. return $this->_ci_load(array('_ci_path' => $path, '_ci_return' => $return));
  444. }
  445. // --------------------------------------------------------------------
  446. /**
  447. * Set Variables
  448. *
  449. * Once variables are set they become available within
  450. * the controller class and its "view" files.
  451. *
  452. * @param array|object|string $vars
  453. * An associative array or object containing values
  454. * to be set, or a value's name if string
  455. * @param string $val Value to set, only used if $vars is a string
  456. * @return object
  457. */
  458. public function vars($vars, $val = '')
  459. {
  460. $vars = is_string($vars)
  461. ? array($vars => $val)
  462. : $this->_ci_prepare_view_vars($vars);
  463. foreach ($vars as $key => $val)
  464. {
  465. $this->_ci_cached_vars[$key] = $val;
  466. }
  467. return $this;
  468. }
  469. // --------------------------------------------------------------------
  470. /**
  471. * Clear Cached Variables
  472. *
  473. * Clears the cached variables.
  474. *
  475. * @return CI_Loader
  476. */
  477. public function clear_vars()
  478. {
  479. $this->_ci_cached_vars = array();
  480. return $this;
  481. }
  482. // --------------------------------------------------------------------
  483. /**
  484. * Get Variable
  485. *
  486. * Check if a variable is set and retrieve it.
  487. *
  488. * @param string $key Variable name
  489. * @return mixed The variable or NULL if not found
  490. */
  491. public function get_var($key)
  492. {
  493. return isset($this->_ci_cached_vars[$key]) ? $this->_ci_cached_vars[$key] : NULL;
  494. }
  495. // --------------------------------------------------------------------
  496. /**
  497. * Get Variables
  498. *
  499. * Retrieves all loaded variables.
  500. *
  501. * @return array
  502. */
  503. public function get_vars()
  504. {
  505. return $this->_ci_cached_vars;
  506. }
  507. // --------------------------------------------------------------------
  508. /**
  509. * Helper Loader
  510. *
  511. * @param string|string[] $helpers Helper name(s)
  512. * @return object
  513. */
  514. public function helper($helpers = array())
  515. {
  516. is_array($helpers) OR $helpers = array($helpers);
  517. foreach ($helpers as &$helper)
  518. {
  519. $filename = basename($helper);
  520. $filepath = ($filename === $helper) ? '' : substr($helper, 0, strlen($helper) - strlen($filename));
  521. $filename = strtolower(preg_replace('#(_helper)?(\.php)?$#i', '', $filename)).'_helper';
  522. $helper = $filepath.$filename;
  523. if (isset($this->_ci_helpers[$helper]))
  524. {
  525. continue;
  526. }
  527. // Is this a helper extension request?
  528. $ext_helper = config_item('subclass_prefix').$filename;
  529. $ext_loaded = FALSE;
  530. foreach ($this->_ci_helper_paths as $path)
  531. {
  532. if (file_exists($path.'helpers/'.$ext_helper.'.php'))
  533. {
  534. include_once($path.'helpers/'.$ext_helper.'.php');
  535. $ext_loaded = TRUE;
  536. }
  537. }
  538. // If we have loaded extensions - check if the base one is here
  539. if ($ext_loaded === TRUE)
  540. {
  541. $base_helper = BASEPATH.'helpers/'.$helper.'.php';
  542. if ( ! file_exists($base_helper))
  543. {
  544. show_error('Unable to load the requested file: helpers/'.$helper.'.php');
  545. }
  546. include_once($base_helper);
  547. $this->_ci_helpers[$helper] = TRUE;
  548. log_message('info', 'Helper loaded: '.$helper);
  549. continue;
  550. }
  551. // No extensions found ... try loading regular helpers and/or overrides
  552. foreach ($this->_ci_helper_paths as $path)
  553. {
  554. if (file_exists($path.'helpers/'.$helper.'.php'))
  555. {
  556. include_once($path.'helpers/'.$helper.'.php');
  557. $this->_ci_helpers[$helper] = TRUE;
  558. log_message('info', 'Helper loaded: '.$helper);
  559. break;
  560. }
  561. }
  562. // unable to load the helper
  563. if ( ! isset($this->_ci_helpers[$helper]))
  564. {
  565. show_error('Unable to load the requested file: helpers/'.$helper.'.php');
  566. }
  567. }
  568. return $this;
  569. }
  570. // --------------------------------------------------------------------
  571. /**
  572. * Load Helpers
  573. *
  574. * An alias for the helper() method in case the developer has
  575. * written the plural form of it.
  576. *
  577. * @uses CI_Loader::helper()
  578. * @param string|string[] $helpers Helper name(s)
  579. * @return object
  580. */
  581. public function helpers($helpers = array())
  582. {
  583. return $this->helper($helpers);
  584. }
  585. // --------------------------------------------------------------------
  586. /**
  587. * Language Loader
  588. *
  589. * Loads language files.
  590. *
  591. * @param string|string[] $files List of language file names to load
  592. * @param string Language name
  593. * @return object
  594. */
  595. public function language($files, $lang = '')
  596. {
  597. get_instance()->lang->load($files, $lang);
  598. return $this;
  599. }
  600. // --------------------------------------------------------------------
  601. /**
  602. * Config Loader
  603. *
  604. * Loads a config file (an alias for CI_Config::load()).
  605. *
  606. * @uses CI_Config::load()
  607. * @param string $file Configuration file name
  608. * @param bool $use_sections Whether configuration values should be loaded into their own section
  609. * @param bool $fail_gracefully Whether to just return FALSE or display an error message
  610. * @return bool TRUE if the file was loaded correctly or FALSE on failure
  611. */
  612. public function config($file, $use_sections = FALSE, $fail_gracefully = FALSE)
  613. {
  614. return get_instance()->config->load($file, $use_sections, $fail_gracefully);
  615. }
  616. // --------------------------------------------------------------------
  617. /**
  618. * Driver Loader
  619. *
  620. * Loads a driver library.
  621. *
  622. * @param string|string[] $library Driver name(s)
  623. * @param array $params Optional parameters to pass to the driver
  624. * @param string $object_name An optional object name to assign to
  625. *
  626. * @return object|bool Object or FALSE on failure if $library is a string
  627. * and $object_name is set. CI_Loader instance otherwise.
  628. */
  629. public function driver($library, $params = NULL, $object_name = NULL)
  630. {
  631. if (is_array($library))
  632. {
  633. foreach ($library as $key => $value)
  634. {
  635. if (is_int($key))
  636. {
  637. $this->driver($value, $params);
  638. }
  639. else
  640. {
  641. $this->driver($key, $params, $value);
  642. }
  643. }
  644. return $this;
  645. }
  646. elseif (empty($library))
  647. {
  648. return FALSE;
  649. }
  650. if ( ! class_exists('CI_Driver_Library', FALSE))
  651. {
  652. // We aren't instantiating an object here, just making the base class available
  653. require BASEPATH.'libraries/Driver.php';
  654. }
  655. // We can save the loader some time since Drivers will *always* be in a subfolder,
  656. // and typically identically named to the library
  657. if ( ! strpos($library, '/'))
  658. {
  659. $library = ucfirst($library).'/'.$library;
  660. }
  661. return $this->library($library, $params, $object_name);
  662. }
  663. // --------------------------------------------------------------------
  664. /**
  665. * Add Package Path
  666. *
  667. * Prepends a parent path to the library, model, helper and config
  668. * path arrays.
  669. *
  670. * @see CI_Loader::$_ci_library_paths
  671. * @see CI_Loader::$_ci_model_paths
  672. * @see CI_Loader::$_ci_helper_paths
  673. * @see CI_Config::$_config_paths
  674. *
  675. * @param string $path Path to add
  676. * @param bool $view_cascade (default: TRUE)
  677. * @return object
  678. */
  679. public function add_package_path($path, $view_cascade = TRUE)
  680. {
  681. $path = rtrim($path, '/').'/';
  682. array_unshift($this->_ci_library_paths, $path);
  683. array_unshift($this->_ci_model_paths, $path);
  684. array_unshift($this->_ci_helper_paths, $path);
  685. $this->_ci_view_paths = array($path.'views/' => $view_cascade) + $this->_ci_view_paths;
  686. // Add config file path
  687. $config =& $this->_ci_get_component('config');
  688. $config->_config_paths[] = $path;
  689. return $this;
  690. }
  691. // --------------------------------------------------------------------
  692. /**
  693. * Get Package Paths
  694. *
  695. * Return a list of all package paths.
  696. *
  697. * @param bool $include_base Whether to include BASEPATH (default: FALSE)
  698. * @return array
  699. */
  700. public function get_package_paths($include_base = FALSE)
  701. {
  702. return ($include_base === TRUE) ? $this->_ci_library_paths : $this->_ci_model_paths;
  703. }
  704. // --------------------------------------------------------------------
  705. /**
  706. * Remove Package Path
  707. *
  708. * Remove a path from the library, model, helper and/or config
  709. * path arrays if it exists. If no path is provided, the most recently
  710. * added path will be removed removed.
  711. *
  712. * @param string $path Path to remove
  713. * @return object
  714. */
  715. public function remove_package_path($path = '')
  716. {
  717. $config =& $this->_ci_get_component('config');
  718. if ($path === '')
  719. {
  720. array_shift($this->_ci_library_paths);
  721. array_shift($this->_ci_model_paths);
  722. array_shift($this->_ci_helper_paths);
  723. array_shift($this->_ci_view_paths);
  724. array_pop($config->_config_paths);
  725. }
  726. else
  727. {
  728. $path = rtrim($path, '/').'/';
  729. foreach (array('_ci_library_paths', '_ci_model_paths', '_ci_helper_paths') as $var)
  730. {
  731. if (($key = array_search($path, $this->{$var})) !== FALSE)
  732. {
  733. unset($this->{$var}[$key]);
  734. }
  735. }
  736. if (isset($this->_ci_view_paths[$path.'views/']))
  737. {
  738. unset($this->_ci_view_paths[$path.'views/']);
  739. }
  740. if (($key = array_search($path, $config->_config_paths)) !== FALSE)
  741. {
  742. unset($config->_config_paths[$key]);
  743. }
  744. }
  745. // make sure the application default paths are still in the array
  746. $this->_ci_library_paths = array_unique(array_merge($this->_ci_library_paths, array(APPPATH, BASEPATH)));
  747. $this->_ci_helper_paths = array_unique(array_merge($this->_ci_helper_paths, array(APPPATH, BASEPATH)));
  748. $this->_ci_model_paths = array_unique(array_merge($this->_ci_model_paths, array(APPPATH)));
  749. $this->_ci_view_paths = array_merge($this->_ci_view_paths, array(APPPATH.'views/' => TRUE));
  750. $config->_config_paths = array_unique(array_merge($config->_config_paths, array(APPPATH)));
  751. return $this;
  752. }
  753. // --------------------------------------------------------------------
  754. /**
  755. * Internal CI Data Loader
  756. *
  757. * Used to load views and files.
  758. *
  759. * Variables are prefixed with _ci_ to avoid symbol collision with
  760. * variables made available to view files.
  761. *
  762. * @used-by CI_Loader::view()
  763. * @used-by CI_Loader::file()
  764. * @param array $_ci_data Data to load
  765. * @return object
  766. */
  767. protected function _ci_load($_ci_data)
  768. {
  769. // Set the default data variables
  770. foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val)
  771. {
  772. $$_ci_val = isset($_ci_data[$_ci_val]) ? $_ci_data[$_ci_val] : FALSE;
  773. }
  774. $file_exists = FALSE;
  775. // Set the path to the requested file
  776. if (is_string($_ci_path) && $_ci_path !== '')
  777. {
  778. $_ci_x = explode('/', $_ci_path);
  779. $_ci_file = end($_ci_x);
  780. }
  781. else
  782. {
  783. $_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION);
  784. $_ci_file = ($_ci_ext === '') ? $_ci_view.'.php' : $_ci_view;
  785. foreach ($this->_ci_view_paths as $_ci_view_file => $cascade)
  786. {
  787. if (file_exists($_ci_view_file.$_ci_file))
  788. {
  789. $_ci_path = $_ci_view_file.$_ci_file;
  790. $file_exists = TRUE;
  791. break;
  792. }
  793. if ( ! $cascade)
  794. {
  795. break;
  796. }
  797. }
  798. }
  799. if ( ! $file_exists && ! file_exists($_ci_path))
  800. {
  801. show_error('Unable to load the requested file: '.$_ci_file);
  802. }
  803. // This allows anything loaded using $this->load (views, files, etc.)
  804. // to become accessible from within the Controller and Model functions.
  805. $_ci_CI =& get_instance();
  806. foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var)
  807. {
  808. if ( ! isset($this->$_ci_key))
  809. {
  810. $this->$_ci_key =& $_ci_CI->$_ci_key;
  811. }
  812. }
  813. /*
  814. * Extract and cache variables
  815. *
  816. * You can either set variables using the dedicated $this->load->vars()
  817. * function or via the second parameter of this function. We'll merge
  818. * the two types and cache them so that views that are embedded within
  819. * other views can have access to these variables.
  820. */
  821. empty($_ci_vars) OR $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars);
  822. extract($this->_ci_cached_vars);
  823. /**
  824. * Buffer the output
  825. *
  826. * We buffer the output for two reasons:
  827. * 1. Speed. You get a significant speed boost.
  828. * 2. So that the final rendered template can be post-processed by
  829. * the output class. Why do we need post processing? For one thing,
  830. * in order to show the elapsed page load time. Unless we can
  831. * intercept the content right before it's sent to the browser and
  832. * then stop the timer it won't be accurate.
  833. */
  834. ob_start();
  835. include($_ci_path); // include() vs include_once() allows for multiple views with the same name
  836. log_message('info', 'File loaded: '.$_ci_path);
  837. // Return the file data if requested
  838. if ($_ci_return === TRUE)
  839. {
  840. $buffer = ob_get_contents();
  841. @ob_end_clean();
  842. return $buffer;
  843. }
  844. /*
  845. * Flush the buffer... or buff the flusher?
  846. *
  847. * In order to permit views to be nested within
  848. * other views, we need to flush the content back out whenever
  849. * we are beyond the first level of output buffering so that
  850. * it can be seen and included properly by the first included
  851. * template and any subsequent ones. Oy!
  852. */
  853. if (ob_get_level() > $this->_ci_ob_level + 1)
  854. {
  855. ob_end_flush();
  856. }
  857. else
  858. {
  859. $_ci_CI->output->append_output(ob_get_contents());
  860. @ob_end_clean();
  861. }
  862. return $this;
  863. }
  864. // --------------------------------------------------------------------
  865. /**
  866. * Internal CI Library Loader
  867. *
  868. * @used-by CI_Loader::library()
  869. * @uses CI_Loader::_ci_init_library()
  870. *
  871. * @param string $class Class name to load
  872. * @param mixed $params Optional parameters to pass to the class constructor
  873. * @param string $object_name Optional object name to assign to
  874. * @return void
  875. */
  876. protected function _ci_load_library($class, $params = NULL, $object_name = NULL)
  877. {
  878. // Get the class name, and while we're at it trim any slashes.
  879. // The directory path can be included as part of the class name,
  880. // but we don't want a leading slash
  881. $class = str_replace('.php', '', trim($class, '/'));
  882. // Was the path included with the class name?
  883. // We look for a slash to determine this
  884. if (($last_slash = strrpos($class, '/')) !== FALSE)
  885. {
  886. // Extract the path
  887. $subdir = substr($class, 0, ++$last_slash);
  888. // Get the filename from the path
  889. $class = substr($class, $last_slash);
  890. }
  891. else
  892. {
  893. $subdir = '';
  894. }
  895. $class = ucfirst($class);
  896. // Is this a stock library? There are a few special conditions if so ...
  897. if (file_exists(BASEPATH.'libraries/'.$subdir.$class.'.php'))
  898. {
  899. return $this->_ci_load_stock_library($class, $subdir, $params, $object_name);
  900. }
  901. // Safety: Was the class already loaded by a previous call?
  902. if (class_exists($class, FALSE))
  903. {
  904. $property = $object_name;
  905. if (empty($property))
  906. {
  907. $property = strtolower($class);
  908. isset($this->_ci_varmap[$property]) && $property = $this->_ci_varmap[$property];
  909. }
  910. $CI =& get_instance();
  911. if (isset($CI->$property))
  912. {
  913. log_message('debug', $class.' class already loaded. Second attempt ignored.');
  914. return;
  915. }
  916. return $this->_ci_init_library($class, '', $params, $object_name);
  917. }
  918. // Let's search for the requested library file and load it.
  919. foreach ($this->_ci_library_paths as $path)
  920. {
  921. // BASEPATH has already been checked for
  922. if ($path === BASEPATH)
  923. {
  924. continue;
  925. }
  926. $filepath = $path.'libraries/'.$subdir.$class.'.php';
  927. // Does the file exist? No? Bummer...
  928. if ( ! file_exists($filepath))
  929. {
  930. continue;
  931. }
  932. include_once($filepath);
  933. return $this->_ci_init_library($class, '', $params, $object_name);
  934. }
  935. // One last attempt. Maybe the library is in a subdirectory, but it wasn't specified?
  936. if ($subdir === '')
  937. {
  938. return $this->_ci_load_library($class.'/'.$class, $params, $object_name);
  939. }
  940. // If we got this far we were unable to find the requested class.
  941. log_message('error', 'Unable to load the requested class: '.$class);
  942. show_error('Unable to load the requested class: '.$class);
  943. }
  944. // --------------------------------------------------------------------
  945. /**
  946. * Internal CI Stock Library Loader
  947. *
  948. * @used-by CI_Loader::_ci_load_library()
  949. * @uses CI_Loader::_ci_init_library()
  950. *
  951. * @param string $library_name Library name to load
  952. * @param string $file_path Path to the library filename, relative to libraries/
  953. * @param mixed $params Optional parameters to pass to the class constructor
  954. * @param string $object_name Optional object name to assign to
  955. * @return void
  956. */
  957. protected function _ci_load_stock_library($library_name, $file_path, $params, $object_name)
  958. {
  959. $prefix = 'CI_';
  960. if (class_exists($prefix.$library_name, FALSE))
  961. {
  962. if (class_exists(config_item('subclass_prefix').$library_name, FALSE))
  963. {
  964. $prefix = config_item('subclass_prefix');
  965. }
  966. $property = $object_name;
  967. if (empty($property))
  968. {
  969. $property = strtolower($library_name);
  970. isset($this->_ci_varmap[$property]) && $property = $this->_ci_varmap[$property];
  971. }
  972. $CI =& get_instance();
  973. if ( ! isset($CI->$property))
  974. {
  975. return $this->_ci_init_library($library_name, $prefix, $params, $object_name);
  976. }
  977. log_message('debug', $library_name.' class already loaded. Second attempt ignored.');
  978. return;
  979. }
  980. $paths = $this->_ci_library_paths;
  981. array_pop($paths); // BASEPATH
  982. array_pop($paths); // APPPATH (needs to be the first path checked)
  983. array_unshift($paths, APPPATH);
  984. foreach ($paths as $path)
  985. {
  986. if (file_exists($path = $path.'libraries/'.$file_path.$library_name.'.php'))
  987. {
  988. // Override
  989. include_once($path);
  990. if (class_exists($prefix.$library_name, FALSE))
  991. {
  992. return $this->_ci_init_library($library_name, $prefix, $params, $object_name);
  993. }
  994. log_message('debug', $path.' exists, but does not declare '.$prefix.$library_name);
  995. }
  996. }
  997. include_once(BASEPATH.'libraries/'.$file_path.$library_name.'.php');
  998. // Check for extensions
  999. $subclass = config_item('subclass_prefix').$library_name;
  1000. foreach ($paths as $path)
  1001. {
  1002. if (file_exists($path = $path.'libraries/'.$file_path.$subclass.'.php'))
  1003. {
  1004. include_once($path);
  1005. if (class_exists($subclass, FALSE))
  1006. {
  1007. $prefix = config_item('subclass_prefix');
  1008. break;
  1009. }
  1010. log_message('debug', $path.' exists, but does not declare '.$subclass);
  1011. }
  1012. }
  1013. return $this->_ci_init_library($library_name, $prefix, $params, $object_name);
  1014. }
  1015. // --------------------------------------------------------------------
  1016. /**
  1017. * Internal CI Library Instantiator
  1018. *
  1019. * @used-by CI_Loader::_ci_load_stock_library()
  1020. * @used-by CI_Loader::_ci_load_library()
  1021. *
  1022. * @param string $class Class name
  1023. * @param string $prefix Class name prefix
  1024. * @param array|null|bool $config Optional configuration to pass to the class constructor:
  1025. * FALSE to skip;
  1026. * NULL to search in config paths;
  1027. * array containing configuration data
  1028. * @param string $object_name Optional object name to assign to
  1029. * @return void
  1030. */
  1031. protected function _ci_init_library($class, $prefix, $config = FALSE, $object_name = NULL)
  1032. {
  1033. // Is there an associated config file for this class? Note: these should always be lowercase
  1034. if ($config === NULL)
  1035. {
  1036. // Fetch the config paths containing any package paths
  1037. $config_component = $this->_ci_get_component('config');
  1038. if (is_array($config_component->_config_paths))
  1039. {
  1040. $found = FALSE;
  1041. foreach ($config_component->_config_paths as $path)
  1042. {
  1043. // We test for both uppercase and lowercase, for servers that
  1044. // are case-sensitive with regard to file names. Load global first,
  1045. // override with environment next
  1046. if (file_exists($path.'config/'.strtolower($class).'.php'))
  1047. {
  1048. include($path.'config/'.strtolower($class).'.php');
  1049. $found = TRUE;
  1050. }
  1051. elseif (file_exists($path.'config/'.ucfirst(strtolower($class)).'.php'))
  1052. {
  1053. include($path.'config/'.ucfirst(strtolower($class)).'.php');
  1054. $found = TRUE;
  1055. }
  1056. if (file_exists($path.'config/'.ENVIRONMENT.'/'.strtolower($class).'.php'))
  1057. {
  1058. include($path.'config/'.ENVIRONMENT.'/'.strtolower($class).'.php');
  1059. $found = TRUE;
  1060. }
  1061. elseif (file_exists($path.'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php'))
  1062. {
  1063. include($path.'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php');
  1064. $found = TRUE;
  1065. }
  1066. // Break on the first found configuration, thus package
  1067. // files are not overridden by default paths
  1068. if ($found === TRUE)
  1069. {
  1070. break;
  1071. }
  1072. }
  1073. }
  1074. }
  1075. $class_name = $prefix.$class;
  1076. // Is the class name valid?
  1077. if ( ! class_exists($class_name, FALSE))
  1078. {
  1079. log_message('error', 'Non-existent class: '.$class_name);
  1080. show_error('Non-existent class: '.$class_name);
  1081. }
  1082. // Set the variable name we will assign the class to
  1083. // Was a custom class name supplied? If so we'll use it
  1084. if (empty($object_name))
  1085. {
  1086. $object_name = strtolower($class);
  1087. if (isset($this->_ci_varmap[$object_name]))
  1088. {
  1089. $object_name = $this->_ci_varmap[$object_name];
  1090. }
  1091. }
  1092. // Don't overwrite existing properties
  1093. $CI =& get_instance();
  1094. if (isset($CI->$object_name))
  1095. {
  1096. if ($CI->$object_name instanceof $class_name)
  1097. {
  1098. log_message('debug', $class_name." has already been instantiated as '".$object_name."'. Second attempt aborted.");
  1099. return;
  1100. }
  1101. show_error("Resource '".$object_name."' already exists and is not a ".$class_name." instance.");
  1102. }
  1103. // Save the class name and object name
  1104. $this->_ci_classes[$object_name] = $class;
  1105. // Instantiate the class
  1106. $CI->$object_name = isset($config)
  1107. ? new $class_name($config)
  1108. : new $class_name();
  1109. }
  1110. // --------------------------------------------------------------------
  1111. /**
  1112. * CI Autoloader
  1113. *
  1114. * Loads component listed in the config/autoload.php file.
  1115. *
  1116. * @used-by CI_Loader::initialize()
  1117. * @return void
  1118. */
  1119. protected function _ci_autoloader()
  1120. {
  1121. if (file_exists(APPPATH.'config/autoload.php'))
  1122. {
  1123. include(APPPATH.'config/autoload.php');
  1124. }
  1125. if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/autoload.php'))
  1126. {
  1127. include(APPPATH.'config/'.ENVIRONMENT.'/autoload.php');
  1128. }
  1129. if ( ! isset($autoload))
  1130. {
  1131. return;
  1132. }
  1133. // Autoload packages
  1134. if (isset($autoload['packages']))
  1135. {
  1136. foreach ($autoload['packages'] as $package_path)
  1137. {
  1138. $this->add_package_path($package_path);
  1139. }
  1140. }
  1141. // Load any custom config file
  1142. if (count($autoload['config']) > 0)
  1143. {
  1144. foreach ($autoload['config'] as $val)
  1145. {
  1146. $this->config($val);
  1147. }
  1148. }
  1149. // Autoload helpers and languages
  1150. foreach (array('helper', 'language') as $type)
  1151. {
  1152. if (isset($autoload[$type]) && count($autoload[$type]) > 0)
  1153. {
  1154. $this->$type($autoload[$type]);
  1155. }
  1156. }
  1157. // Autoload drivers
  1158. if (isset($autoload['drivers']))
  1159. {
  1160. $this->driver($autoload['drivers']);
  1161. }
  1162. // Load libraries
  1163. if (isset($autoload['libraries']) && count($autoload['libraries']) > 0)
  1164. {
  1165. // Load the database driver.
  1166. if (in_array('database', $autoload['libraries']))
  1167. {
  1168. $this->database();
  1169. $autoload['libraries'] = array_diff($autoload['libraries'], array('database'));
  1170. }
  1171. // Load all other libraries
  1172. $this->library($autoload['libraries']);
  1173. }
  1174. // Autoload models
  1175. if (isset($autoload['model']))
  1176. {
  1177. $this->model($autoload['model']);
  1178. }
  1179. }
  1180. // --------------------------------------------------------------------
  1181. /**
  1182. * Prepare variables for _ci_vars, to be later extract()-ed inside views
  1183. *
  1184. * Converts objects to associative arrays and filters-out internal
  1185. * variable names (i.e. keys prefixed with '_ci_').
  1186. *
  1187. * @param mixed $vars
  1188. * @return array
  1189. */
  1190. protected function _ci_prepare_view_vars($vars)
  1191. {
  1192. if ( ! is_array($vars))
  1193. {
  1194. $vars = is_object($vars)
  1195. ? get_object_vars($vars)
  1196. : array();
  1197. }
  1198. foreach (array_keys($vars) as $key)
  1199. {
  1200. if (strncmp($key, '_ci_', 4) === 0)
  1201. {
  1202. unset($vars[$key]);
  1203. }
  1204. }
  1205. return $vars;
  1206. }
  1207. // --------------------------------------------------------------------
  1208. /**
  1209. * CI Component getter
  1210. *
  1211. * Get a reference to a specific library or model.
  1212. *
  1213. * @param string $component Component name
  1214. * @return bool
  1215. */
  1216. protected function &_ci_get_component($component)
  1217. {
  1218. $CI =& get_instance();
  1219. return $CI->$component;
  1220. }
  1221. }