You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1411 lines
36 KiB

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