blob: ff5ffbfe4194a9441c50c77a68a5d2bfca0b0e59 [file] [log] [blame]
Derek Allard29eff532007-02-05 23:55:06 +00001<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
2/**
Derek Allardd2df9bc2007-04-15 17:41:17 +00003 * CodeIgniter
Derek Allard29eff532007-02-05 23:55:06 +00004 *
5 * An open source application development framework for PHP 4.3.2 or newer
6 *
7 * @package CodeIgniter
8 * @author Rick Ellis
Derek Allardd2df9bc2007-04-15 17:41:17 +00009 * @copyright Copyright (c) 2006, EllisLab, Inc.
Derek Allard29eff532007-02-05 23:55:06 +000010 * @license http://www.codeignitor.com/user_guide/license.html
11 * @link http://www.codeigniter.com
12 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * Loader Class
20 *
21 * Loads views and files
22 *
23 * @package CodeIgniter
24 * @subpackage Libraries
25 * @author Rick Ellis
26 * @category Loader
27 * @link http://www.codeigniter.com/user_guide/libraries/loader.html
28 */
29class CI_Loader {
30
31 // All these are set automatically. Don't mess with them.
32 var $_ci_ob_level;
33 var $_ci_view_path = '';
34 var $_ci_is_php5 = FALSE;
35 var $_ci_is_instance = FALSE; // Whether we should use $this or $CI =& get_instance()
36 var $_ci_cached_vars = array();
37 var $_ci_classes = array();
38 var $_ci_models = array();
39 var $_ci_helpers = array();
40 var $_ci_plugins = array();
41 var $_ci_scripts = array();
42 var $_ci_varmap = array('unit_test' => 'unit', 'user_agent' => 'agent');
43
44
45 /**
46 * Constructor
47 *
48 * Sets the path to the view files and gets the initial output buffering level
49 *
50 * @access public
51 */
52 function CI_Loader()
53 {
54 $this->_ci_is_php5 = (floor(phpversion()) >= 5) ? TRUE : FALSE;
55 $this->_ci_view_path = APPPATH.'views/';
56 $this->_ci_ob_level = ob_get_level();
57
58 log_message('debug', "Loader Class Initialized");
59 }
60
61 // --------------------------------------------------------------------
62
63 /**
64 * Class Loader
65 *
66 * This function lets users load and instantiate classes.
67 * It is designed to be called from a user's app controllers.
68 *
69 * @access public
70 * @param string the name of the class
71 * @param mixed the optional parameters
72 * @return void
73 */
74 function library($library = '', $params = NULL)
75 {
76 if ($library == '')
77 {
78 return FALSE;
79 }
80
81 if (is_array($library))
82 {
83 foreach ($library as $class)
84 {
85 $this->_ci_load_class($class, $params);
86 }
87 }
88 else
89 {
90 $this->_ci_load_class($library, $params);
91 }
92
93 $this->_ci_assign_to_models();
94 }
95
96 // --------------------------------------------------------------------
97
98 /**
99 * Model Loader
100 *
101 * This function lets users load and instantiate models.
102 *
103 * @access public
104 * @param string the name of the class
105 * @param mixed any initialization parameters
106 * @return void
107 */
108 function model($model, $name = '', $db_conn = FALSE)
109 {
110 if ($model == '')
111 return;
112
113 // Is the model in a sub-folder? If so, parse out the filename and path.
114 if (strpos($model, '/') === FALSE)
115 {
116 $path = '';
117 }
118 else
119 {
120 $x = explode('/', $model);
121 $model = end($x);
122 unset($x[count($x)-1]);
123 $path = implode('/', $x).'/';
124 }
125
126 if ($name == '')
127 {
128 $name = $model;
129 }
130
131 if (in_array($name, $this->_ci_models, TRUE))
132 {
133 return;
134 }
135
136 $CI =& get_instance();
137 if (isset($CI->$name))
138 {
139 show_error('The model name you are loading is the name of a resource that is already being used: '.$name);
140 }
141
142 $model = strtolower($model);
143
144 if ( ! file_exists(APPPATH.'models/'.$path.$model.EXT))
145 {
146 show_error('Unable to locate the model you have specified: '.$model);
147 }
148
149 if ($db_conn !== FALSE AND ! class_exists('CI_DB'))
150 {
151 if ($db_conn === TRUE)
152 $db_conn = '';
153
154 $CI->load->database($db_conn, FALSE, TRUE);
155 }
156
Derek Allardac0eb452007-02-15 18:42:22 +0000157 if ( ! class_exists('Model'))
158 {
159 require_once(BASEPATH.'libraries/Model'.EXT);
160 }
Derek Allard29eff532007-02-05 23:55:06 +0000161
162 require_once(APPPATH.'models/'.$path.$model.EXT);
163
164 $model = ucfirst($model);
165
166 $CI->$name = new $model();
167 $CI->$name->_assign_libraries();
168
169 $this->_ci_models[] = $name;
170 }
171
172 // --------------------------------------------------------------------
173
174 /**
175 * Database Loader
176 *
177 * @access public
178 * @param string the DB credentials
179 * @param bool whether to return the DB object
180 * @param bool whether to enable active record (this allows us to override the config setting)
181 * @return object
182 */
183 function database($params = '', $return = FALSE, $active_record = FALSE)
184 {
185 // Do we even need to load the database class?
186 if (class_exists('CI_DB') AND $return == FALSE AND $active_record == FALSE)
187 {
188 return FALSE;
189 }
190
191 require_once(BASEPATH.'database/DB'.EXT);
192
193 if ($return === TRUE)
194 {
195 return DB($params, $active_record);
196 }
197
198 // Grab the super object
199 $CI =& get_instance();
200
201 // Initialize the db variable. Needed to prevent
202 // reference errors with some configurations
203 $CI->db = '';
204
205 // Load the DB class
206 $CI->db =& DB($params, $active_record);
207
208 // Assign the DB object to any existing models
209 $this->_ci_assign_to_models();
210 }
211
212 // --------------------------------------------------------------------
213
214 /**
215 * Load the Utilities Class
216 *
217 * @access public
218 * @return string
219 */
220 function dbutil()
221 {
222 if ( ! class_exists('CI_DB'))
223 {
224 $this->database();
225 }
226
227 $CI =& get_instance();
228
229 require_once(BASEPATH.'database/DB_utility'.EXT);
230 require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_utility'.EXT);
231 $class = 'CI_DB_'.$CI->db->dbdriver.'_utility';
232
233 $CI->dbutil = new $class();
234 $CI->load->_ci_assign_to_models();
235 }
236
237 // --------------------------------------------------------------------
238
239 /**
240 * Load View
241 *
242 * This function is used to load a "view" file. It has three parameters:
243 *
244 * 1. The name of the "view" file to be included.
245 * 2. An associative array of data to be extracted for use in the view.
246 * 3. TRUE/FALSE - whether to return the data or load it. In
247 * some cases it's advantageous to be able to return data so that
248 * a developer can process it in some way.
249 *
250 * @access public
251 * @param string
252 * @param array
253 * @param bool
254 * @return void
255 */
256 function view($view, $vars = array(), $return = FALSE)
257 {
258 return $this->_ci_load(array('view' => $view, 'vars' => $this->_ci_object_to_array($vars), 'return' => $return));
259 }
260
261 // --------------------------------------------------------------------
262
263 /**
264 * Load File
265 *
266 * This is a generic file loader
267 *
268 * @access public
269 * @param string
270 * @param bool
271 * @return string
272 */
273 function file($path, $return = FALSE)
274 {
275 return $this->_ci_load(array('path' => $path, 'return' => $return));
276 }
277
278 // --------------------------------------------------------------------
279
280 /**
281 * Set Variables
282 *
283 * Once variables are set they become available within
284 * the controller class and its "view" files.
285 *
286 * @access public
287 * @param array
288 * @return void
289 */
290 function vars($vars = array())
291 {
292 $vars = $this->_ci_object_to_array($vars);
293
294 if (is_array($vars) AND count($vars) > 0)
295 {
296 foreach ($vars as $key => $val)
297 {
298 $this->_ci_cached_vars[$key] = $val;
299 }
300 }
301 }
302
303 // --------------------------------------------------------------------
304
305 /**
306 * Load Helper
307 *
308 * This function loads the specified helper file.
309 *
310 * @access public
311 * @param mixed
312 * @return void
313 */
314 function helper($helpers = array())
315 {
316 if ( ! is_array($helpers))
317 {
318 $helpers = array($helpers);
319 }
320
321 foreach ($helpers as $helper)
322 {
323 $helper = strtolower(str_replace(EXT, '', str_replace('_helper', '', $helper)).'_helper');
324
325 if (isset($this->_ci_helpers[$helper]))
326 {
327 continue;
328 }
329
330 if (file_exists(APPPATH.'helpers/'.$helper.EXT))
331 {
332 include_once(APPPATH.'helpers/'.$helper.EXT);
333 }
334 else
335 {
336 if (file_exists(BASEPATH.'helpers/'.$helper.EXT))
337 {
338 include(BASEPATH.'helpers/'.$helper.EXT);
339 }
340 else
341 {
342 show_error('Unable to load the requested file: helpers/'.$helper.EXT);
343 }
344 }
345
346 $this->_ci_helpers[$helper] = TRUE;
347
348 }
349
350 log_message('debug', 'Helpers loaded: '.implode(', ', $helpers));
351 }
352
353 // --------------------------------------------------------------------
354
355 /**
356 * Load Helpers
357 *
358 * This is simply an alias to the above function in case the
359 * user has written the plural form of this function.
360 *
361 * @access public
362 * @param array
363 * @return void
364 */
365 function helpers($helpers = array())
366 {
367 $this->helper($helpers);
368 }
369
370 // --------------------------------------------------------------------
371
372 /**
373 * Load Plugin
374 *
375 * This function loads the specified plugin.
376 *
377 * @access public
378 * @param array
379 * @return void
380 */
381 function plugin($plugins = array())
382 {
383 if ( ! is_array($plugins))
384 {
385 $plugins = array($plugins);
386 }
387
388 foreach ($plugins as $plugin)
389 {
390 $plugin = strtolower(str_replace(EXT, '', str_replace('_plugin.', '', $plugin)).'_pi');
391
392 if (isset($this->_ci_plugins[$plugin]))
393 {
394 continue;
395 }
396
397 if (file_exists(APPPATH.'plugins/'.$plugin.EXT))
398 {
399 include(APPPATH.'plugins/'.$plugin.EXT);
400 }
401 else
402 {
403 if (file_exists(BASEPATH.'plugins/'.$plugin.EXT))
404 {
405 include(BASEPATH.'plugins/'.$plugin.EXT);
406 }
407 else
408 {
409 show_error('Unable to load the requested file: plugins/'.$plugin.EXT);
410 }
411 }
412
413 $this->_ci_plugins[$plugin] = TRUE;
414 }
415
416 log_message('debug', 'Plugins loaded: '.implode(', ', $plugins));
417 }
418
419 // --------------------------------------------------------------------
420
421 /**
422 * Load Plugins
423 *
424 * This is simply an alias to the above function in case the
425 * user has written the plural form of this function.
426 *
427 * @access public
428 * @param array
429 * @return void
430 */
431 function plugins($plugins = array())
432 {
433 $this->plugin($plugins);
434 }
435
436 // --------------------------------------------------------------------
437
438 /**
439 * Load Script
440 *
441 * This function loads the specified include file from the
442 * application/scripts/ folder.
443 *
444 * NOTE: This feature has been deprecated but it will remain available
445 * for legacy users.
446 *
447 * @access public
448 * @param array
449 * @return void
450 */
451 function script($scripts = array())
452 {
453 if ( ! is_array($scripts))
454 {
455 $scripts = array($scripts);
456 }
457
458 foreach ($scripts as $script)
459 {
460 $script = strtolower(str_replace(EXT, '', $script));
461
462 if (isset($this->_ci_scripts[$script]))
463 {
464 continue;
465 }
466
467 if ( ! file_exists(APPPATH.'scripts/'.$script.EXT))
468 {
469 show_error('Unable to load the requested script: scripts/'.$script.EXT);
470 }
471
472 include(APPPATH.'scripts/'.$script.EXT);
473 }
474
475 log_message('debug', 'Scripts loaded: '.implode(', ', $scripts));
476 }
477
478 // --------------------------------------------------------------------
479
480 /**
481 * Loads a language file
482 *
483 * @access public
484 * @param string
485 * @return void
486 */
487 function language($file = '', $lang = '', $return = FALSE)
488 {
489 $CI =& get_instance();
490 return $CI->lang->load($file, $lang, $return);
491 }
492
493 // --------------------------------------------------------------------
494
495 /**
496 * Loads a config file
497 *
498 * @access public
499 * @param string
500 * @return void
501 */
502 function config($file = '', $use_sections = FALSE, $fail_gracefully = FALSE)
503 {
504 $CI =& get_instance();
505 $CI->config->load($file, $use_sections, $fail_gracefully);
506 }
507
508 // --------------------------------------------------------------------
509
510 /**
511 * Scaffolding Loader
512 *
513 * This initializing function works a bit different than the
514 * others. It doesn't load the class. Instead, it simply
515 * sets a flag indicating that scaffolding is allowed to be
516 * used. The actual scaffolding function below is
517 * called by the front controller based on whether the
518 * second segment of the URL matches the "secret" scaffolding
519 * word stored in the application/config/routes.php
520 *
521 * @access public
522 * @param string
523 * @return void
524 */
525 function scaffolding($table = '')
526 {
527 if ($table === FALSE)
528 {
Derek Allard655bc022007-02-06 23:45:33 +0000529 show_error('You must include the name of the table you would like to access when you initialize scaffolding');
Derek Allard29eff532007-02-05 23:55:06 +0000530 }
531
532 $CI =& get_instance();
533 $CI->_ci_scaffolding = TRUE;
534 $CI->_ci_scaff_table = $table;
535 }
536
537 // --------------------------------------------------------------------
538
539 /**
540 * Loader
541 *
542 * This function is used to load views and files.
543 *
544 * @access private
545 * @param array
546 * @return void
547 */
548 function _ci_load($data)
549 {
550 // Set the default data variables
551 foreach (array('view', 'vars', 'path', 'return') as $val)
552 {
553 $$val = ( ! isset($data[$val])) ? FALSE : $data[$val];
554 }
555
556 // Set the path to the requested file
557 if ($path == '')
558 {
559 $ext = pathinfo($view, PATHINFO_EXTENSION);
560 $file = ($ext == '') ? $view.EXT : $view;
561 $path = $this->_ci_view_path.$file;
562 }
563 else
564 {
565 $x = explode('/', $path);
566 $file = end($x);
567 }
568
569 if ( ! file_exists($path))
570 {
571 show_error('Unable to load the requested file: '.$file);
572 }
573
574 // This allows anything loaded using $this->load (views, files, etc.)
575 // to become accessible from within the Controller and Model functions.
576 // Only needed when running PHP 5
577
578 if ($this->_ci_is_instance())
579 {
580 $CI =& get_instance();
581 foreach (get_object_vars($CI) as $key => $var)
582 {
583 if ( ! isset($this->$key))
584 {
585 $this->$key =& $CI->$key;
586 }
587 }
588 }
589
590 /*
591 * Extract and cache variables
592 *
593 * You can either set variables using the dedicated $this->load_vars()
594 * function or via the second parameter of this function. We'll merge
595 * the two types and cache them so that views that are embedded within
596 * other views can have access to these variables.
597 */
598 if (is_array($vars))
599 {
600 $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $vars);
601 }
602 extract($this->_ci_cached_vars);
603
604 /*
605 * Buffer the output
606 *
607 * We buffer the output for two reasons:
608 * 1. Speed. You get a significant speed boost.
609 * 2. So that the final rendered template can be
610 * post-processed by the output class. Why do we
611 * need post processing? For one thing, in order to
612 * show the elapsed page load time. Unless we
613 * can intercept the content right before it's sent to
614 * the browser and then stop the timer it won't be accurate.
615 */
616 ob_start();
617
618 // If the PHP installation does not support short tags we'll
619 // do a little string replacement, changing the short tags
620 // to standard PHP echo statements.
621
622 if ((bool) @ini_get('short_open_tag') === FALSE AND config_item('rewrite_short_tags') == TRUE)
623 {
624 echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($path))).'<?php ');
625 }
626 else
627 {
628 include($path);
629 }
630
631 log_message('debug', 'File loaded: '.$path);
632
633 // Return the file data if requested
634 if ($return === TRUE)
635 {
636 $buffer = ob_get_contents();
637 @ob_end_clean();
638 return $buffer;
639 }
640
641 /*
642 * Flush the buffer... or buff the flusher?
643 *
644 * In order to permit views to be nested within
645 * other views, we need to flush the content back out whenever
646 * we are beyond the first level of output buffering so that
647 * it can be seen and included properly by the first included
648 * template and any subsequent ones. Oy!
649 *
650 */
651 if (ob_get_level() > $this->_ci_ob_level + 1)
652 {
653 ob_end_flush();
654 }
655 else
656 {
657 // PHP 4 requires that we use a global
658 global $OUT;
659 $OUT->set_output(ob_get_contents());
660 @ob_end_clean();
661 }
662 }
663
664 // --------------------------------------------------------------------
665
666 /**
667 * Load class
668 *
669 * This function loads the requested class.
670 *
671 * @access private
672 * @param string the item that is being loaded
673 * @param mixed any additional parameters
674 * @return void
675 */
676 function _ci_load_class($class, $params = NULL)
677 {
678 // Get the class name
679 $class = str_replace(EXT, '', $class);
680
681 // We'll test for both lowercase and capitalized versions of the file name
682 foreach (array(ucfirst($class), strtolower($class)) as $class)
683 {
684 // Is this a class extension request?
685 if (file_exists(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT))
686 {
687 if ( ! file_exists(BASEPATH.'libraries/'.ucfirst($class).EXT))
688 {
689 log_message('error', "Unable to load the requested class: ".$class);
690 show_error("Unable to load the requested class: ".$class);
691 }
692
693 include(BASEPATH.'libraries/'.ucfirst($class).EXT);
694 include(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT);
695
696 return $this->_ci_init_class($class, config_item('subclass_prefix'), $params);
697 }
698
699 // Lets search for the requested library file and load it.
Derek Allard4dde0de2007-02-14 22:44:36 +0000700 $is_duplicate = FALSE;
Derek Allard29eff532007-02-05 23:55:06 +0000701 for ($i = 1; $i < 3; $i++)
702 {
703 $path = ($i % 2) ? APPPATH : BASEPATH;
704 $fp = $path.'libraries/'.$class.EXT;
705
706 // Does the file exist? No? Bummer...
707 if ( ! file_exists($fp))
708 {
709 continue;
710 }
711
712 // Safety: Was the class already loaded by a previous call?
713 if (in_array($fp, $this->_ci_classes))
714 {
Derek Allard4dde0de2007-02-14 22:44:36 +0000715 $is_duplicate = TRUE;
Derek Allard29eff532007-02-05 23:55:06 +0000716 log_message('debug', $class." class already loaded. Second attempt ignored.");
717 return;
718 }
719
720 include($fp);
721 $this->_ci_classes[] = $fp;
722 return $this->_ci_init_class($class, '', $params);
723 }
724 } // END FOREACH
725
726 // If we got this far we were unable to find the requested class.
727 // We do not issue errors if the load call failed due to a duplicate request
728 if ($is_duplicate == FALSE)
729 {
730 log_message('error', "Unable to load the requested class: ".$class);
731 show_error("Unable to load the requested class: ".$class);
732 }
733 }
734
735 // --------------------------------------------------------------------
736
737 /**
738 * Instantiates a class
739 *
740 * @access private
741 * @param string
742 * @param string
743 * @return null
744 */
745 function _ci_init_class($class, $prefix = '', $config = FALSE)
746 {
747 // Is there an associated config file for this class?
748 if ($config === NULL)
749 {
750 $config = NULL;
751 if (file_exists(APPPATH.'config/'.$class.EXT))
752 {
753 include(APPPATH.'config/'.$class.EXT);
754 }
755 }
756
757 if ($prefix == '')
758 {
759 $name = (class_exists('CI_'.$class)) ? 'CI_'.$class : $class;
760 }
761 else
762 {
763 $name = $prefix.$class;
764 }
765
766 // Set the variable name we will assign the class to
767 $class = strtolower($class);
768 $classvar = ( ! isset($this->_ci_varmap[$class])) ? $class : $this->_ci_varmap[$class];
769
770 // Instantiate the class
771 $CI =& get_instance();
772 if ($config !== NULL)
773 {
774 $CI->$classvar = new $name($config);
775 }
776 else
777 {
778 $CI->$classvar = new $name;
779 }
780 }
781
782 // --------------------------------------------------------------------
783
784 /**
785 * Autoloader
786 *
787 * The config/autoload.php file contains an array that permits sub-systems,
788 * libraries, plugins, and helpers to be loaded automatically.
789 *
790 * @access private
791 * @param array
792 * @return void
793 */
794 function _ci_autoloader()
795 {
796 include(APPPATH.'config/autoload'.EXT);
797
798 if ( ! isset($autoload))
799 {
800 return FALSE;
801 }
802
803 // Load any custome config file
804 if (count($autoload['config']) > 0)
805 {
806 $CI =& get_instance();
807 foreach ($autoload['config'] as $key => $val)
808 {
809 $CI->config->load($val);
810 }
811 }
812
813 // Load plugins, helpers, and scripts
814 foreach (array('helper', 'plugin', 'script') as $type)
815 {
816 if (isset($autoload[$type]) AND count($autoload[$type]) > 0)
817 {
818 $this->$type($autoload[$type]);
819 }
820 }
821
822 // A little tweak to remain backward compatible
823 // The $autoload['core'] item was deprecated
824 if ( ! isset($autoload['libraries']))
825 {
826 $autoload['libraries'] = $autoload['core'];
827 }
828
829 // Load libraries
830 if (isset($autoload['libraries']) AND count($autoload['libraries']) > 0)
831 {
832 // Load the database driver.
833 if (in_array('database', $autoload['libraries']))
834 {
835 $this->database();
836 $autoload['libraries'] = array_diff($autoload['libraries'], array('database'));
837 }
838
839 // Load the model class.
840 if (in_array('model', $autoload['libraries']))
841 {
842 $this->model();
843 $autoload['libraries'] = array_diff($autoload['libraries'], array('model'));
844 }
845
846 // Load scaffolding
847 if (in_array('scaffolding', $autoload['libraries']))
848 {
849 $this->scaffolding();
850 $autoload['libraries'] = array_diff($autoload['libraries'], array('scaffolding'));
851 }
852
853 // Load all other libraries
854 foreach ($autoload['libraries'] as $item)
855 {
856 $this->library($item);
857 }
858 }
859 }
860
861 // --------------------------------------------------------------------
862
863 /**
864 * Assign to Models
865 *
866 * Makes sure that anything loaded by the loader class (libraries, plugins, etc.)
867 * will be available to models, if any exist.
868 *
869 * @access private
870 * @param object
871 * @return array
872 */
873 function _ci_assign_to_models()
874 {
875 if (count($this->_ci_models) == 0)
876 {
877 return;
878 }
879
880 if ($this->_ci_is_instance())
881 {
882 $CI =& get_instance();
883 foreach ($this->_ci_models as $model)
884 {
885 $CI->$model->_assign_libraries();
886 }
887 }
888 else
889 {
890 foreach ($this->_ci_models as $model)
891 {
892 $this->$model->_assign_libraries();
893 }
894 }
895 }
896
897 // --------------------------------------------------------------------
898
899 /**
900 * Object to Array
901 *
902 * Takes an object as input and converts the class variables to array key/vals
903 *
904 * @access private
905 * @param object
906 * @return array
907 */
908 function _ci_object_to_array($object)
909 {
910 return (is_object($object)) ? get_object_vars($object) : $object;
911 }
912
913 // --------------------------------------------------------------------
914
915 /**
916 * Determines whether we should use the CI instance or $this
917 *
918 * @access private
919 * @return bool
920 */
921 function _ci_is_instance()
922 {
923 if ($this->_ci_is_php5 == TRUE)
924 {
925 return TRUE;
926 }
927
928 global $CI;
929 return (is_object($CI)) ? TRUE : FALSE;
930 }
931
932}
adminb0dd10f2006-08-25 17:25:49 +0000933?>