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