Loader.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  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/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 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. elseif ( ! is_subclass_of($model, 'CI_Model'))
  310. {
  311. throw new RuntimeException("Class ".$model." already exists and 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. // If the PHP installation does not support short tags we'll
  836. // do a little string replacement, changing the short tags
  837. // to standard PHP echo statements.
  838. if ( ! is_php('5.4') && ! ini_get('short_open_tag') && config_item('rewrite_short_tags') === TRUE)
  839. {
  840. echo eval('?>'.preg_replace('/;*\s*\?>/', '; ?>', str_replace('<?=', '<?php echo ', file_get_contents($_ci_path))));
  841. }
  842. else
  843. {
  844. include($_ci_path); // include() vs include_once() allows for multiple views with the same name
  845. }
  846. log_message('info', 'File loaded: '.$_ci_path);
  847. // Return the file data if requested
  848. if ($_ci_return === TRUE)
  849. {
  850. $buffer = ob_get_contents();
  851. @ob_end_clean();
  852. return $buffer;
  853. }
  854. /*
  855. * Flush the buffer... or buff the flusher?
  856. *
  857. * In order to permit views to be nested within
  858. * other views, we need to flush the content back out whenever
  859. * we are beyond the first level of output buffering so that
  860. * it can be seen and included properly by the first included
  861. * template and any subsequent ones. Oy!
  862. */
  863. if (ob_get_level() > $this->_ci_ob_level + 1)
  864. {
  865. ob_end_flush();
  866. }
  867. else
  868. {
  869. $_ci_CI->output->append_output(ob_get_contents());
  870. @ob_end_clean();
  871. }
  872. return $this;
  873. }
  874. // --------------------------------------------------------------------
  875. /**
  876. * Internal CI Library Loader
  877. *
  878. * @used-by CI_Loader::library()
  879. * @uses CI_Loader::_ci_init_library()
  880. *
  881. * @param string $class Class name to load
  882. * @param mixed $params Optional parameters to pass to the class constructor
  883. * @param string $object_name Optional object name to assign to
  884. * @return void
  885. */
  886. protected function _ci_load_library($class, $params = NULL, $object_name = NULL)
  887. {
  888. // Get the class name, and while we're at it trim any slashes.
  889. // The directory path can be included as part of the class name,
  890. // but we don't want a leading slash
  891. $class = str_replace('.php', '', trim($class, '/'));
  892. // Was the path included with the class name?
  893. // We look for a slash to determine this
  894. if (($last_slash = strrpos($class, '/')) !== FALSE)
  895. {
  896. // Extract the path
  897. $subdir = substr($class, 0, ++$last_slash);
  898. // Get the filename from the path
  899. $class = substr($class, $last_slash);
  900. }
  901. else
  902. {
  903. $subdir = '';
  904. }
  905. $class = ucfirst($class);
  906. // Is this a stock library? There are a few special conditions if so ...
  907. if (file_exists(BASEPATH.'libraries/'.$subdir.$class.'.php'))
  908. {
  909. return $this->_ci_load_stock_library($class, $subdir, $params, $object_name);
  910. }
  911. // Safety: Was the class already loaded by a previous call?
  912. if (class_exists($class, FALSE))
  913. {
  914. $property = $object_name;
  915. if (empty($property))
  916. {
  917. $property = strtolower($class);
  918. isset($this->_ci_varmap[$property]) && $property = $this->_ci_varmap[$property];
  919. }
  920. $CI =& get_instance();
  921. if (isset($CI->$property))
  922. {
  923. log_message('debug', $class.' class already loaded. Second attempt ignored.');
  924. return;
  925. }
  926. return $this->_ci_init_library($class, '', $params, $object_name);
  927. }
  928. // Let's search for the requested library file and load it.
  929. foreach ($this->_ci_library_paths as $path)
  930. {
  931. // BASEPATH has already been checked for
  932. if ($path === BASEPATH)
  933. {
  934. continue;
  935. }
  936. $filepath = $path.'libraries/'.$subdir.$class.'.php';
  937. // Does the file exist? No? Bummer...
  938. if ( ! file_exists($filepath))
  939. {
  940. continue;
  941. }
  942. include_once($filepath);
  943. return $this->_ci_init_library($class, '', $params, $object_name);
  944. }
  945. // One last attempt. Maybe the library is in a subdirectory, but it wasn't specified?
  946. if ($subdir === '')
  947. {
  948. return $this->_ci_load_library($class.'/'.$class, $params, $object_name);
  949. }
  950. // If we got this far we were unable to find the requested class.
  951. log_message('error', 'Unable to load the requested class: '.$class);
  952. show_error('Unable to load the requested class: '.$class);
  953. }
  954. // --------------------------------------------------------------------
  955. /**
  956. * Internal CI Stock Library Loader
  957. *
  958. * @used-by CI_Loader::_ci_load_library()
  959. * @uses CI_Loader::_ci_init_library()
  960. *
  961. * @param string $library_name Library name to load
  962. * @param string $file_path Path to the library filename, relative to libraries/
  963. * @param mixed $params Optional parameters to pass to the class constructor
  964. * @param string $object_name Optional object name to assign to
  965. * @return void
  966. */
  967. protected function _ci_load_stock_library($library_name, $file_path, $params, $object_name)
  968. {
  969. $prefix = 'CI_';
  970. if (class_exists($prefix.$library_name, FALSE))
  971. {
  972. if (class_exists(config_item('subclass_prefix').$library_name, FALSE))
  973. {
  974. $prefix = config_item('subclass_prefix');
  975. }
  976. $property = $object_name;
  977. if (empty($property))
  978. {
  979. $property = strtolower($library_name);
  980. isset($this->_ci_varmap[$property]) && $property = $this->_ci_varmap[$property];
  981. }
  982. $CI =& get_instance();
  983. if ( ! isset($CI->$property))
  984. {
  985. return $this->_ci_init_library($library_name, $prefix, $params, $object_name);
  986. }
  987. log_message('debug', $library_name.' class already loaded. Second attempt ignored.');
  988. return;
  989. }
  990. $paths = $this->_ci_library_paths;
  991. array_pop($paths); // BASEPATH
  992. array_pop($paths); // APPPATH (needs to be the first path checked)
  993. array_unshift($paths, APPPATH);
  994. foreach ($paths as $path)
  995. {
  996. if (file_exists($path = $path.'libraries/'.$file_path.$library_name.'.php'))
  997. {
  998. // Override
  999. include_once($path);
  1000. if (class_exists($prefix.$library_name, FALSE))
  1001. {
  1002. return $this->_ci_init_library($library_name, $prefix, $params, $object_name);
  1003. }
  1004. log_message('debug', $path.' exists, but does not declare '.$prefix.$library_name);
  1005. }
  1006. }
  1007. include_once(BASEPATH.'libraries/'.$file_path.$library_name.'.php');
  1008. // Check for extensions
  1009. $subclass = config_item('subclass_prefix').$library_name;
  1010. foreach ($paths as $path)
  1011. {
  1012. if (file_exists($path = $path.'libraries/'.$file_path.$subclass.'.php'))
  1013. {
  1014. include_once($path);
  1015. if (class_exists($subclass, FALSE))
  1016. {
  1017. $prefix = config_item('subclass_prefix');
  1018. break;
  1019. }
  1020. log_message('debug', $path.' exists, but does not declare '.$subclass);
  1021. }
  1022. }
  1023. return $this->_ci_init_library($library_name, $prefix, $params, $object_name);
  1024. }
  1025. // --------------------------------------------------------------------
  1026. /**
  1027. * Internal CI Library Instantiator
  1028. *
  1029. * @used-by CI_Loader::_ci_load_stock_library()
  1030. * @used-by CI_Loader::_ci_load_library()
  1031. *
  1032. * @param string $class Class name
  1033. * @param string $prefix Class name prefix
  1034. * @param array|null|bool $config Optional configuration to pass to the class constructor:
  1035. * FALSE to skip;
  1036. * NULL to search in config paths;
  1037. * array containing configuration data
  1038. * @param string $object_name Optional object name to assign to
  1039. * @return void
  1040. */
  1041. protected function _ci_init_library($class, $prefix, $config = FALSE, $object_name = NULL)
  1042. {
  1043. // Is there an associated config file for this class? Note: these should always be lowercase
  1044. if ($config === NULL)
  1045. {
  1046. // Fetch the config paths containing any package paths
  1047. $config_component = $this->_ci_get_component('config');
  1048. if (is_array($config_component->_config_paths))
  1049. {
  1050. $found = FALSE;
  1051. foreach ($config_component->_config_paths as $path)
  1052. {
  1053. // We test for both uppercase and lowercase, for servers that
  1054. // are case-sensitive with regard to file names. Load global first,
  1055. // override with environment next
  1056. if (file_exists($path.'config/'.strtolower($class).'.php'))
  1057. {
  1058. include($path.'config/'.strtolower($class).'.php');
  1059. $found = TRUE;
  1060. }
  1061. elseif (file_exists($path.'config/'.ucfirst(strtolower($class)).'.php'))
  1062. {
  1063. include($path.'config/'.ucfirst(strtolower($class)).'.php');
  1064. $found = TRUE;
  1065. }
  1066. if (file_exists($path.'config/'.ENVIRONMENT.'/'.strtolower($class).'.php'))
  1067. {
  1068. include($path.'config/'.ENVIRONMENT.'/'.strtolower($class).'.php');
  1069. $found = TRUE;
  1070. }
  1071. elseif (file_exists($path.'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php'))
  1072. {
  1073. include($path.'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php');
  1074. $found = TRUE;
  1075. }
  1076. // Break on the first found configuration, thus package
  1077. // files are not overridden by default paths
  1078. if ($found === TRUE)
  1079. {
  1080. break;
  1081. }
  1082. }
  1083. }
  1084. }
  1085. $class_name = $prefix.$class;
  1086. // Is the class name valid?
  1087. if ( ! class_exists($class_name, FALSE))
  1088. {
  1089. log_message('error', 'Non-existent class: '.$class_name);
  1090. show_error('Non-existent class: '.$class_name);
  1091. }
  1092. // Set the variable name we will assign the class to
  1093. // Was a custom class name supplied? If so we'll use it
  1094. if (empty($object_name))
  1095. {
  1096. $object_name = strtolower($class);
  1097. if (isset($this->_ci_varmap[$object_name]))
  1098. {
  1099. $object_name = $this->_ci_varmap[$object_name];
  1100. }
  1101. }
  1102. // Don't overwrite existing properties
  1103. $CI =& get_instance();
  1104. if (isset($CI->$object_name))
  1105. {
  1106. if ($CI->$object_name instanceof $class_name)
  1107. {
  1108. log_message('debug', $class_name." has already been instantiated as '".$object_name."'. Second attempt aborted.");
  1109. return;
  1110. }
  1111. show_error("Resource '".$object_name."' already exists and is not a ".$class_name." instance.");
  1112. }
  1113. // Save the class name and object name
  1114. $this->_ci_classes[$object_name] = $class;
  1115. // Instantiate the class
  1116. $CI->$object_name = isset($config)
  1117. ? new $class_name($config)
  1118. : new $class_name();
  1119. }
  1120. // --------------------------------------------------------------------
  1121. /**
  1122. * CI Autoloader
  1123. *
  1124. * Loads component listed in the config/autoload.php file.
  1125. *
  1126. * @used-by CI_Loader::initialize()
  1127. * @return void
  1128. */
  1129. protected function _ci_autoloader()
  1130. {
  1131. if (file_exists(APPPATH.'config/autoload.php'))
  1132. {
  1133. include(APPPATH.'config/autoload.php');
  1134. }
  1135. if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/autoload.php'))
  1136. {
  1137. include(APPPATH.'config/'.ENVIRONMENT.'/autoload.php');
  1138. }
  1139. if ( ! isset($autoload))
  1140. {
  1141. return;
  1142. }
  1143. // Autoload packages
  1144. if (isset($autoload['packages']))
  1145. {
  1146. foreach ($autoload['packages'] as $package_path)
  1147. {
  1148. $this->add_package_path($package_path);
  1149. }
  1150. }
  1151. // Load any custom config file
  1152. if (count($autoload['config']) > 0)
  1153. {
  1154. foreach ($autoload['config'] as $val)
  1155. {
  1156. $this->config($val);
  1157. }
  1158. }
  1159. // Autoload helpers and languages
  1160. foreach (array('helper', 'language') as $type)
  1161. {
  1162. if (isset($autoload[$type]) && count($autoload[$type]) > 0)
  1163. {
  1164. $this->$type($autoload[$type]);
  1165. }
  1166. }
  1167. // Autoload drivers
  1168. if (isset($autoload['drivers']))
  1169. {
  1170. $this->driver($autoload['drivers']);
  1171. }
  1172. // Load libraries
  1173. if (isset($autoload['libraries']) && count($autoload['libraries']) > 0)
  1174. {
  1175. // Load the database driver.
  1176. if (in_array('database', $autoload['libraries']))
  1177. {
  1178. $this->database();
  1179. $autoload['libraries'] = array_diff($autoload['libraries'], array('database'));
  1180. }
  1181. // Load all other libraries
  1182. $this->library($autoload['libraries']);
  1183. }
  1184. // Autoload models
  1185. if (isset($autoload['model']))
  1186. {
  1187. $this->model($autoload['model']);
  1188. }
  1189. }
  1190. // --------------------------------------------------------------------
  1191. /**
  1192. * Prepare variables for _ci_vars, to be later extract()-ed inside views
  1193. *
  1194. * Converts objects to associative arrays and filters-out internal
  1195. * variable names (i.e. keys prefixed with '_ci_').
  1196. *
  1197. * @param mixed $vars
  1198. * @return array
  1199. */
  1200. protected function _ci_prepare_view_vars($vars)
  1201. {
  1202. if ( ! is_array($vars))
  1203. {
  1204. $vars = is_object($vars)
  1205. ? get_object_vars($vars)
  1206. : array();
  1207. }
  1208. foreach (array_keys($vars) as $key)
  1209. {
  1210. if (strncmp($key, '_ci_', 4) === 0)
  1211. {
  1212. unset($vars[$key]);
  1213. }
  1214. }
  1215. return $vars;
  1216. }
  1217. // --------------------------------------------------------------------
  1218. /**
  1219. * CI Component getter
  1220. *
  1221. * Get a reference to a specific library or model.
  1222. *
  1223. * @param string $component Component name
  1224. * @return bool
  1225. */
  1226. protected function &_ci_get_component($component)
  1227. {
  1228. $CI =& get_instance();
  1229. return $CI->$component;
  1230. }
  1231. }