1 <?php defined('SYSPATH') OR die('No direct access allowed.');
3 * Provides Kohana-specific helper functions. This is where the magic happens!
5 * $Id: Kohana.php 4372 2009-05-28 17:00:34Z ixmatus $
9 * @copyright (c) 2007-2008 Kohana Team
10 * @license http://kohanaphp.com/license.html
14 // The singleton instance of the controller
15 public static $instance;
17 // Output buffering level
18 private static $buffer_level;
20 // Will be set to TRUE when an exception is caught
21 public static $has_error = FALSE;
23 // The final output that will displayed by Kohana
24 public static $output = '';
26 // The current user agent
27 public static $user_agent;
30 public static $locale;
33 private static $configuration;
36 private static $include_paths;
42 private static $cache_lifetime;
45 private static $log_levels = array
53 // Internal caches and write status
54 private static $internal_cache = array();
55 private static $write_cache;
56 private static $internal_cache_path;
57 private static $internal_cache_key;
58 private static $internal_cache_encrypt;
61 * Sets up the PHP environment. Adds error/exception handling, output
62 * buffering, and adds an auto-loading method for loading classes.
64 * This method is run immediately when this file is loaded, and is
65 * benchmarked as environment_setup.
67 * For security, this function also destroys the $_REQUEST global variable.
68 * Using the proper global (GET, POST, COOKIE, etc) is inherently more secure.
69 * The recommended way to fetch a global variable is using the Input library.
70 * @see http://www.php.net/globals
74 public static function setup()
78 // This function can only be run once
82 // Start the environment setup benchmark
83 Benchmark::start(SYSTEM_BENCHMARK.'_environment_setup');
85 // Define Kohana error constant
86 define('E_KOHANA', 42);
88 // Define 404 error constant
89 define('E_PAGE_NOT_FOUND', 43);
91 // Define database error constant
92 define('E_DATABASE_ERROR', 44);
94 if (self::$cache_lifetime = self::config('core.internal_cache'))
96 // Are we using encryption for caches?
97 self::$internal_cache_encrypt = self::config('core.internal_cache_encrypt');
99 if(self::$internal_cache_encrypt===TRUE)
101 self::$internal_cache_key = self::config('core.internal_cache_key');
103 // Be sure the key is of acceptable length for the mcrypt algorithm used
104 self::$internal_cache_key = substr(self::$internal_cache_key, 0, 24);
107 // Set the directory to be used for the internal cache
108 if ( ! self::$internal_cache_path = self::config('core.internal_cache_path'))
110 self::$internal_cache_path = APPPATH.'cache/';
113 // Load cached configuration and language files
114 self::$internal_cache['configuration'] = self::cache('configuration', self::$cache_lifetime);
115 self::$internal_cache['language'] = self::cache('language', self::$cache_lifetime);
117 // Load cached file paths
118 self::$internal_cache['find_file_paths'] = self::cache('find_file_paths', self::$cache_lifetime);
120 // Enable cache saving
121 Event::add('system.shutdown', array(__CLASS__, 'internal_cache_save'));
124 // Disable notices and "strict" errors
125 $ER = error_reporting(~E_NOTICE & ~E_STRICT);
127 // Set the user agent
128 self::$user_agent = ( ! empty($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : '');
130 if (function_exists('date_default_timezone_set'))
132 $timezone = self::config('locale.timezone');
134 // Set default timezone, due to increased validation of date settings
135 // which cause massive amounts of E_NOTICEs to be generated in PHP 5.2+
136 date_default_timezone_set(empty($timezone) ? date_default_timezone_get() : $timezone);
139 // Restore error reporting
140 error_reporting($ER);
142 // Start output buffering
143 ob_start(array(__CLASS__, 'output_buffer'));
145 // Save buffering level
146 self::$buffer_level = ob_get_level();
149 spl_autoload_register(array('Kohana', 'auto_load'));
152 set_error_handler(array('Kohana', 'exception_handler'));
154 // Set exception handler
155 set_exception_handler(array('Kohana', 'exception_handler'));
157 // Send default text/html UTF-8 header
158 header('Content-Type: text/html; charset=UTF-8');
161 $locales = self::config('locale.language');
163 // Make first locale UTF-8
164 $locales[0] .= '.UTF-8';
166 // Set locale information
167 self::$locale = setlocale(LC_ALL, $locales);
169 if (self::$configuration['core']['log_threshold'] > 0)
171 // Set the log directory
172 self::log_directory(self::$configuration['core']['log_directory']);
174 // Enable log writing at shutdown
175 register_shutdown_function(array(__CLASS__, 'log_save'));
178 // Enable Kohana routing
179 Event::add('system.routing', array('Router', 'find_uri'));
180 Event::add('system.routing', array('Router', 'setup'));
182 // Enable Kohana controller initialization
183 Event::add('system.execute', array('Kohana', 'instance'));
185 // Enable Kohana 404 pages
186 Event::add('system.404', array('Kohana', 'show_404'));
188 // Enable Kohana output handling
189 Event::add('system.shutdown', array('Kohana', 'shutdown'));
191 if (self::config('core.enable_hooks') === TRUE)
193 // Find all the hook files
194 $hooks = self::list_files('hooks', TRUE);
196 foreach ($hooks as $file)
203 // Setup is complete, prevent it from being run again
206 // Stop the environment setup routine
207 Benchmark::stop(SYSTEM_BENCHMARK.'_environment_setup');
211 * Loads the controller and initializes it. Runs the pre_controller,
212 * post_controller_constructor, and post_controller events. Triggers
213 * a system.404 event when the route cannot be mapped to a controller.
215 * This method is benchmarked as controller_setup and controller_execution.
217 * @return object instance of controller
219 public static function & instance()
221 if (self::$instance === NULL)
223 Benchmark::start(SYSTEM_BENCHMARK.'_controller_setup');
225 // Include the Controller file
226 require Router::$controller_path;
230 // Start validation of the controller
231 $class = new ReflectionClass(ucfirst(Router::$controller).'_Controller');
233 catch (ReflectionException $e)
235 // Controller does not exist
236 Event::run('system.404');
239 if ($class->isAbstract() OR (IN_PRODUCTION AND $class->getConstant('ALLOW_PRODUCTION') == FALSE))
241 // Controller is not allowed to run in production
242 Event::run('system.404');
245 // Run system.pre_controller
246 Event::run('system.pre_controller');
248 // Create a new controller instance
249 $controller = $class->newInstance();
251 // Controller constructor has been executed
252 Event::run('system.post_controller_constructor');
256 // Load the controller method
257 $method = $class->getMethod(Router::$method);
260 if (Router::$method[0] === '_')
262 // Do not allow access to hidden methods
263 Event::run('system.404');
266 if ($method->isProtected() or $method->isPrivate())
268 // Do not attempt to invoke protected methods
269 throw new ReflectionException('protected controller method');
273 $arguments = Router::$arguments;
275 catch (ReflectionException $e)
277 // Use __call instead
278 $method = $class->getMethod('__call');
280 // Use arguments in __call format
281 $arguments = array(Router::$method, Router::$arguments);
284 // Stop the controller setup benchmark
285 Benchmark::stop(SYSTEM_BENCHMARK.'_controller_setup');
287 // Start the controller execution benchmark
288 Benchmark::start(SYSTEM_BENCHMARK.'_controller_execution');
290 // Execute the controller method
291 $method->invokeArgs($controller, $arguments);
293 // Controller method has been executed
294 Event::run('system.post_controller');
296 // Stop the controller execution benchmark
297 Benchmark::stop(SYSTEM_BENCHMARK.'_controller_execution');
300 return self::$instance;
304 * Get all include paths. APPPATH is the first path, followed by module
305 * paths in the order they are configured, follow by the SYSPATH.
307 * @param boolean re-process the include paths
310 public static function include_paths($process = FALSE)
312 if ($process === TRUE)
314 // Add APPPATH as the first path
315 self::$include_paths = array(APPPATH);
317 foreach (self::$configuration['core']['modules'] as $path)
319 if ($path = str_replace('\\', '/', realpath($path)))
322 self::$include_paths[] = $path.'/';
326 // Add SYSPATH as the last path
327 self::$include_paths[] = SYSPATH;
330 return self::$include_paths;
334 * Get a config item or group.
336 * @param string item name
337 * @param boolean force a forward slash (/) at the end of the item
338 * @param boolean is the item required?
341 public static function config($key, $slash = FALSE, $required = TRUE)
343 if (self::$configuration === NULL)
345 // Load core configuration
346 self::$configuration['core'] = self::config_load('core');
348 // Re-parse the include paths
349 self::include_paths(TRUE);
352 // Get the group name from the key
353 $group = explode('.', $key, 2);
356 if ( ! isset(self::$configuration[$group]))
358 // Load the configuration group
359 self::$configuration[$group] = self::config_load($group, $required);
362 // Get the value of the key string
363 $value = self::key_string(self::$configuration, $key);
365 if ($slash === TRUE AND is_string($value) AND $value !== '')
367 // Force the value to end with "/"
368 $value = rtrim($value, '/').'/';
375 * Sets a configuration item, if allowed.
377 * @param string config key string
378 * @param string config value
381 public static function config_set($key, $value)
383 // Do this to make sure that the config array is already loaded
386 if (substr($key, 0, 7) === 'routes.')
388 // Routes cannot contain sub keys due to possible dots in regex
389 $keys = explode('.', $key, 2);
393 // Convert dot-noted key string to an array
394 $keys = explode('.', $key);
397 // Used for recursion
398 $conf =& self::$configuration;
399 $last = count($keys) - 1;
401 foreach ($keys as $i => $k)
413 if ($key === 'core.modules')
415 // Reprocess the include paths
416 self::include_paths(TRUE);
423 * Load a config file.
425 * @param string config filename, without extension
426 * @param boolean is the file required?
429 public static function config_load($name, $required = TRUE)
431 if ($name === 'core')
433 // Load the application configuration file
434 require APPPATH.'config/config'.EXT;
436 if ( ! isset($config['site_domain']))
438 // Invalid config file
439 die('Your Kohana application configuration file is not valid.');
445 if (isset(self::$internal_cache['configuration'][$name]))
446 return self::$internal_cache['configuration'][$name];
448 // Load matching configs
449 $configuration = array();
451 if ($files = self::find_file('config', $name, $required))
453 foreach ($files as $file)
457 if (isset($config) AND is_array($config))
459 // Merge in configuration
460 $configuration = array_merge($configuration, $config);
465 if ( ! isset(self::$write_cache['configuration']))
468 self::$write_cache['configuration'] = TRUE;
471 return self::$internal_cache['configuration'][$name] = $configuration;
475 * Clears a config group from the cached configuration.
477 * @param string config group
480 public static function config_clear($group)
482 // Remove the group from config
483 unset(self::$configuration[$group], self::$internal_cache['configuration'][$group]);
485 if ( ! isset(self::$write_cache['configuration']))
488 self::$write_cache['configuration'] = TRUE;
493 * Add a new message to the log.
495 * @param string type of message
496 * @param string message text
499 public static function log($type, $message)
501 if (self::$log_levels[$type] <= self::$configuration['core']['log_threshold'])
503 $message = array(date('Y-m-d H:i:s P'), $type, $message);
505 // Run the system.log event
506 Event::run('system.log', $message);
508 self::$log[] = $message;
513 * Save all currently logged messages.
517 public static function log_save()
519 if (empty(self::$log) OR self::$configuration['core']['log_threshold'] < 1)
522 // Filename of the log
523 $filename = self::log_directory().date('Y-m-d').'.log'.EXT;
525 if ( ! is_file($filename))
527 // Write the SYSPATH checking header
528 file_put_contents($filename,
529 '<?php defined(\'SYSPATH\') or die(\'No direct script access.\'); ?>'.PHP_EOL.PHP_EOL);
531 // Prevent external writes
532 chmod($filename, 0644);
540 // Load the next mess
541 list ($date, $type, $text) = array_shift(self::$log);
543 // Add a new message line
544 $messages[] = $date.' --- '.$type.': '.$text;
546 while ( ! empty(self::$log));
548 // Write messages to log file
549 file_put_contents($filename, implode(PHP_EOL, $messages).PHP_EOL, FILE_APPEND);
553 * Get or set the logging directory.
555 * @param string new log directory
558 public static function log_directory($dir = NULL)
564 // Get the directory path
565 $dir = realpath($dir);
567 if (is_dir($dir) AND is_writable($dir))
569 // Change the log directory
570 $directory = str_replace('\\', '/', $dir).'/';
574 // Log directory is invalid
575 throw new Kohana_Exception('core.log_dir_unwritable', $dir);
583 * Load data from a simple cache file. This should only be used internally,
584 * and is NOT a replacement for the Cache library.
586 * @param string unique name of cache
587 * @param integer expiration in seconds
590 public static function cache($name, $lifetime)
594 $path = self::$internal_cache_path.'kohana_'.$name;
598 // Check the file modification time
599 if ((time() - filemtime($path)) < $lifetime)
601 // Cache is valid! Now, do we need to decrypt it?
602 if(self::$internal_cache_encrypt===TRUE)
604 $data = file_get_contents($path);
606 $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
607 $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
609 $decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::$internal_cache_key, $data, MCRYPT_MODE_ECB, $iv);
611 $cache = unserialize($decrypted_text);
613 // If the key changed, delete the cache file
617 // If cache is false (as above) return NULL, otherwise, return the cache
618 return ($cache ? $cache : NULL);
622 return unserialize(file_get_contents($path));
627 // Cache is invalid, delete it
638 * Save data to a simple cache file. This should only be used internally, and
639 * is NOT a replacement for the Cache library.
641 * @param string cache name
642 * @param mixed data to cache
643 * @param integer expiration in seconds
646 public static function cache_save($name, $data, $lifetime)
651 $path = self::$internal_cache_path.'kohana_'.$name;
656 return (is_file($path) and unlink($path));
660 // Using encryption? Encrypt the data when we write it
661 if(self::$internal_cache_encrypt===TRUE)
663 // Encrypt and write data to cache file
664 $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
665 $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
667 // Serialize and encrypt!
668 $encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::$internal_cache_key, serialize($data), MCRYPT_MODE_ECB, $iv);
670 return (bool) file_put_contents($path, $encrypted_text);
674 // Write data to cache file
675 return (bool) file_put_contents($path, serialize($data));
681 * Kohana output handler. Called during ob_clean, ob_flush, and their variants.
683 * @param string current output buffer
686 public static function output_buffer($output)
688 // Could be flushing, so send headers first
689 if ( ! Event::has_run('system.send_headers'))
691 // Run the send_headers event
692 Event::run('system.send_headers');
695 self::$output = $output;
697 // Set and return the final output
698 return self::$output;
702 * Closes all open output buffers, either by flushing or cleaning, and stores the Kohana
703 * output buffer for display during shutdown.
705 * @param boolean disable to clear buffers, rather than flushing
708 public static function close_buffers($flush = TRUE)
710 if (ob_get_level() >= self::$buffer_level)
712 // Set the close function
713 $close = ($flush === TRUE) ? 'ob_end_flush' : 'ob_end_clean';
715 while (ob_get_level() > self::$buffer_level)
717 // Flush or clean the buffer
721 // Store the Kohana output buffer
727 * Triggers the shutdown of Kohana by closing the output buffer, runs the system.display event.
731 public static function shutdown()
733 // Close output buffers
734 self::close_buffers(TRUE);
736 // Run the output event
737 Event::run('system.display', self::$output);
739 // Render the final output
740 self::render(self::$output);
744 * Inserts global Kohana variables into the generated output and prints it.
746 * @param string final output that will displayed
749 public static function render($output)
751 if (self::config('core.render_stats') === TRUE)
753 // Fetch memory usage in MB
754 $memory = function_exists('memory_get_usage') ? (memory_get_usage() / 1024 / 1024) : 0;
756 // Fetch benchmark for page execution time
757 $benchmark = Benchmark::get(SYSTEM_BENCHMARK.'_total_execution');
759 // Replace the global template variables
760 $output = str_replace(
774 number_format($memory, 2).'MB',
775 count(get_included_files()),
781 if ($level = self::config('core.output_compression') AND ini_get('output_handler') !== 'ob_gzhandler' AND (int) ini_get('zlib.output_compression') === 0)
783 if ($level < 1 OR $level > 9)
785 // Normalize the level to be an integer between 1 and 9. This
786 // step must be done to prevent gzencode from triggering an error
787 $level = max(1, min($level, 9));
790 if (stripos(@$_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
794 elseif (stripos(@$_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') !== FALSE)
796 $compress = 'deflate';
800 if (isset($compress) AND $level > 0)
805 // Compress output using gzip
806 $output = gzencode($output, $level);
809 // Compress output using zlib (HTTP deflate)
810 $output = gzdeflate($output, $level);
814 // This header must be sent with compressed content to prevent
815 // browser caches from breaking
816 header('Vary: Accept-Encoding');
818 // Send the content encoding header
819 header('Content-Encoding: '.$compress);
821 // Sending Content-Length in CGI can result in unexpected behavior
822 if (stripos(PHP_SAPI, 'cgi') === FALSE)
824 header('Content-Length: '.strlen($output));
832 * Displays a 404 page.
834 * @throws Kohana_404_Exception
835 * @param string URI of page
836 * @param string custom template
839 public static function show_404($page = FALSE, $template = FALSE)
841 throw new Kohana_404_Exception($page, $template);
845 * Dual-purpose PHP error and exception handler. Uses the kohana_error_page
846 * view to display the message.
848 * @param integer|object exception object or error code
849 * @param string error message
850 * @param string filename
851 * @param integer line number
854 public static function exception_handler($exception, $message = NULL, $file = NULL, $line = NULL)
858 // PHP errors have 5 args, always
859 $PHP_ERROR = (func_num_args() === 5);
861 // Test to see if errors should be displayed
862 if ($PHP_ERROR AND (error_reporting() & $exception) === 0)
865 // This is useful for hooks to determine if a page has an error
866 self::$has_error = TRUE;
868 // Error handling will use exactly 5 args, every time
873 $template = 'kohana_error_page';
877 $code = $exception->getCode();
878 $type = get_class($exception);
879 $message = $exception->getMessage();
880 $file = $exception->getFile();
881 $line = $exception->getLine();
882 $template = ($exception instanceof Kohana_Exception) ? $exception->getTemplate() : 'kohana_error_page';
885 if (is_numeric($code))
887 $codes = self::lang('errors');
889 if ( ! empty($codes[$code]))
891 list($level, $error, $description) = $codes[$code];
896 $error = $PHP_ERROR ? 'Unknown Error' : get_class($exception);
902 // Custom error message, this will never be logged
908 // Remove the DOCROOT from the path, as a security precaution
909 $file = str_replace('\\', '/', realpath($file));
910 $file = preg_replace('|^'.preg_quote(DOCROOT).'|', '', $file);
912 if ($level <= self::$configuration['core']['log_threshold'])
915 self::log('error', self::lang('core.uncaught_exception', $type, $message, $file, $line));
920 $description = self::lang('errors.'.E_RECOVERABLE_ERROR);
921 $description = is_array($description) ? $description[2] : '';
923 if ( ! headers_sent())
925 // Send the 500 header
926 header('HTTP/1.1 500 Internal Server Error');
931 if (method_exists($exception, 'sendHeaders') AND ! headers_sent())
933 // Send the headers if they have not already been sent
934 $exception->sendHeaders();
938 // Close all output buffers except for Kohana
939 while (ob_get_level() > self::$buffer_level)
944 // Test if display_errors is on
945 if (self::$configuration['core']['display_errors'] === TRUE)
947 if ( ! IN_PRODUCTION AND $line != FALSE)
949 // Remove the first entry of debug_backtrace(), it is the exception_handler call
950 $trace = $PHP_ERROR ? array_slice(debug_backtrace(), 1) : $exception->getTrace();
952 // Beautify backtrace
953 $trace = self::backtrace($trace);
957 require self::find_file('views', empty($template) ? 'kohana_error_page' : $template);
961 // Get the i18n messages
962 $error = self::lang('core.generic_error');
963 $message = self::lang('core.errors_disabled', url::site(), url::site(Router::$current_uri));
965 // Load the errors_disabled view
966 require self::find_file('views', 'kohana_error_disabled');
969 if ( ! Event::has_run('system.shutdown'))
971 // Run the shutdown even to ensure a clean exit
972 Event::run('system.shutdown');
975 // Turn off error reporting
987 die('Fatal Error: '.$e->getMessage().' File: '.$e->getFile().' Line: '.$e->getLine());
993 * Provides class auto-loading.
995 * @throws Kohana_Exception
996 * @param string name of class
999 public static function auto_load($class)
1001 if (class_exists($class, FALSE))
1004 if (($suffix = strrpos($class, '_')) > 0)
1006 // Find the class suffix
1007 $suffix = substr($class, $suffix + 1);
1015 if ($suffix === 'Core')
1017 $type = 'libraries';
1018 $file = substr($class, 0, -5);
1020 elseif ($suffix === 'Controller')
1022 $type = 'controllers';
1023 // Lowercase filename
1024 $file = strtolower(substr($class, 0, -11));
1026 elseif ($suffix === 'Model')
1029 // Lowercase filename
1030 $file = strtolower(substr($class, 0, -6));
1032 elseif ($suffix === 'Driver')
1034 $type = 'libraries/drivers';
1035 $file = str_replace('_', '/', substr($class, 0, -7));
1039 // This could be either a library or a helper, but libraries must
1040 // always be capitalized, so we check if the first character is
1041 // uppercase. If it is, we are loading a library, not a helper.
1042 $type = ($class[0] < 'a') ? 'libraries' : 'helpers';
1046 if ($filename = self::find_file($type, $file))
1053 // The class could not be found
1057 if ($filename = self::find_file($type, self::$configuration['core']['extension_prefix'].$class))
1059 // Load the class extension
1062 elseif ($suffix !== 'Core' AND class_exists($class.'_Core', FALSE))
1064 // Class extension to be evaluated
1065 $extension = 'class '.$class.' extends '.$class.'_Core { }';
1067 // Start class analysis
1068 $core = new ReflectionClass($class.'_Core');
1070 if ($core->isAbstract())
1072 // Make the extension abstract
1073 $extension = 'abstract '.$extension;
1076 // Transparent class extensions are handled using eval. This is
1077 // a disgusting hack, but it gets the job done.
1085 * Find a resource file in a given directory. Files will be located according
1086 * to the order of the include paths. Configuration and i18n files will be
1087 * returned in reverse order.
1089 * @throws Kohana_Exception if file is required and not found
1090 * @param string directory to search in
1091 * @param string filename to look for (without extension)
1092 * @param boolean file required
1093 * @param string file extension
1094 * @return array if the type is config, i18n or l10n
1095 * @return string if the file is found
1096 * @return FALSE if the file is not found
1098 public static function find_file($directory, $filename, $required = FALSE, $ext = FALSE)
1100 // NOTE: This test MUST be not be a strict comparison (===), or empty
1101 // extensions will be allowed!
1104 // Use the default extension
1109 // Add a period before the extension
1114 $search = $directory.'/'.$filename.$ext;
1116 if (isset(self::$internal_cache['find_file_paths'][$search]))
1117 return self::$internal_cache['find_file_paths'][$search];
1119 // Load include paths
1120 $paths = self::$include_paths;
1122 // Nothing found, yet
1125 if ($directory === 'config' OR $directory === 'i18n')
1127 // Search in reverse, for merging
1128 $paths = array_reverse($paths);
1130 foreach ($paths as $path)
1132 if (is_file($path.$search))
1134 // A matching file has been found
1135 $found[] = $path.$search;
1141 foreach ($paths as $path)
1143 if (is_file($path.$search))
1145 // A matching file has been found
1146 $found = $path.$search;
1154 if ($found === NULL)
1156 if ($required === TRUE)
1158 // Directory i18n key
1159 $directory = 'core.'.inflector::singular($directory);
1161 // If the file is required, throw an exception
1162 throw new Kohana_Exception('core.resource_not_found', self::lang($directory), $filename);
1166 // Nothing was found, return FALSE
1171 if ( ! isset(self::$write_cache['find_file_paths']))
1173 // Write cache at shutdown
1174 self::$write_cache['find_file_paths'] = TRUE;
1177 return self::$internal_cache['find_file_paths'][$search] = $found;
1181 * Lists all files and directories in a resource path.
1183 * @param string directory to search
1184 * @param boolean list all files to the maximum depth?
1185 * @param string full path to search (used for recursion, *never* set this manually)
1186 * @return array filenames and directories
1188 public static function list_files($directory, $recursive = FALSE, $path = FALSE)
1192 if ($path === FALSE)
1194 $paths = array_reverse(self::include_paths());
1196 foreach ($paths as $path)
1198 // Recursively get and merge all files
1199 $files = array_merge($files, self::list_files($directory, $recursive, $path.$directory));
1204 $path = rtrim($path, '/').'/';
1206 if (is_readable($path))
1208 $items = (array) glob($path.'*');
1210 if ( ! empty($items))
1212 foreach ($items as $index => $item)
1214 $files[] = $item = str_replace('\\', '/', $item);
1217 if (is_dir($item) AND $recursive == TRUE)
1219 // Filename should only be the basename
1220 $item = pathinfo($item, PATHINFO_BASENAME);
1222 // Append sub-directory search
1223 $files = array_merge($files, self::list_files($directory, TRUE, $path.$item));
1234 * Fetch an i18n language item.
1236 * @param string language key to fetch
1237 * @param array additional information to insert into the line
1238 * @return string i18n language string, or the requested key if the i18n item is not found
1240 public static function lang($key, $args = array())
1242 // Extract the main group from the key
1243 $group = explode('.', $key, 2);
1247 $locale = self::config('locale.language.0');
1249 if ( ! isset(self::$internal_cache['language'][$locale][$group]))
1251 // Messages for this group
1252 $messages = array();
1254 if ($files = self::find_file('i18n', $locale.'/'.$group))
1256 foreach ($files as $file)
1260 // Merge in configuration
1261 if ( ! empty($lang) AND is_array($lang))
1263 foreach ($lang as $k => $v)
1271 if ( ! isset(self::$write_cache['language']))
1273 // Write language cache
1274 self::$write_cache['language'] = TRUE;
1277 self::$internal_cache['language'][$locale][$group] = $messages;
1280 // Get the line from cache
1281 $line = self::key_string(self::$internal_cache['language'][$locale], $key);
1285 self::log('error', 'Missing i18n entry '.$key.' for language '.$locale);
1287 // Return the key string as fallback
1291 if (is_string($line) AND func_num_args() > 1)
1293 $args = array_slice(func_get_args(), 1);
1295 // Add the arguments into the line
1296 $line = vsprintf($line, is_array($args[0]) ? $args[0] : $args);
1303 * Returns the value of a key, defined by a 'dot-noted' string, from an array.
1305 * @param array array to search
1306 * @param string dot-noted string: foo.bar.baz
1307 * @return string if the key is found
1308 * @return void if the key is not found
1310 public static function key_string($array, $keys)
1316 $keys = explode('.', $keys);
1321 $key = array_shift($keys);
1323 if (isset($array[$key]))
1325 if (is_array($array[$key]) AND ! empty($keys))
1327 // Dig down to prepare the next loop
1328 $array = $array[$key];
1332 // Requested key was found
1333 return $array[$key];
1338 // Requested key is not set
1342 while ( ! empty($keys));
1348 * Sets values in an array by using a 'dot-noted' string.
1350 * @param array array to set keys in (reference)
1351 * @param string dot-noted string: foo.bar.baz
1352 * @return mixed fill value for the key
1355 public static function key_string_set( & $array, $keys, $fill = NULL)
1357 if (is_object($array) AND ($array instanceof ArrayObject))
1360 $array_copy = $array->getArrayCopy();
1363 $array_object = TRUE;
1367 if ( ! is_array($array))
1369 // Must always be an array
1370 $array = (array) $array;
1373 // Copy is a reference to the array
1374 $array_copy =& $array;
1381 $keys = explode('.', $keys);
1383 // Create reference to the array
1384 $row =& $array_copy;
1386 for ($i = 0, $end = count($keys) - 1; $i <= $end; $i++)
1388 // Get the current key
1391 if ( ! isset($row[$key]))
1393 if (isset($keys[$i + 1]))
1395 // Make the value an array
1396 $row[$key] = array();
1404 elseif (isset($keys[$i + 1]))
1406 // Make the value an array
1407 $row[$key] = (array) $row[$key];
1410 // Go down a level, creating a new row reference
1414 if (isset($array_object))
1416 // Swap the array back in
1417 $array->exchangeArray($array_copy);
1422 * Retrieves current user agent information:
1423 * keys: browser, version, platform, mobile, robot, referrer, languages, charsets
1424 * tests: is_browser, is_mobile, is_robot, accept_lang, accept_charset
1426 * @param string key or test name
1427 * @param string used with "accept" tests: user_agent(accept_lang, en)
1428 * @return array languages and charsets
1429 * @return string all other keys
1430 * @return boolean all tests
1432 public static function user_agent($key = 'agent', $compare = NULL)
1436 // Return the raw string
1437 if ($key === 'agent')
1438 return self::$user_agent;
1442 // Parse the user agent and extract basic information
1443 $agents = self::config('user_agents');
1445 foreach ($agents as $type => $data)
1447 foreach ($data as $agent => $name)
1449 if (stripos(self::$user_agent, $agent) !== FALSE)
1451 if ($type === 'browser' AND preg_match('|'.preg_quote($agent).'[^0-9.]*+([0-9.][0-9.a-z]*)|i', self::$user_agent, $match))
1453 // Set the browser version
1454 $info['version'] = $match[1];
1457 // Set the agent name
1458 $info[$type] = $name;
1465 if (empty($info[$key]))
1473 $return = ! empty($info[substr($key, 3)]);
1477 if ( ! empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
1479 if (preg_match_all('/[-a-z]{2,}/', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])), $matches))
1482 $return = $matches[0];
1488 if ( ! empty($_SERVER['HTTP_ACCEPT_CHARSET']))
1490 if (preg_match_all('/[-a-z0-9]{2,}/', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET'])), $matches))
1493 $return = $matches[0];
1498 if ( ! empty($_SERVER['HTTP_REFERER']))
1501 $return = trim($_SERVER['HTTP_REFERER']);
1506 // Cache the return value
1507 isset($return) and $info[$key] = $return;
1510 if ( ! empty($compare))
1512 // The comparison must always be lowercase
1513 $compare = strtolower($compare);
1518 // Check if the lange is accepted
1519 return in_array($compare, self::user_agent('languages'));
1521 case 'accept_charset':
1522 // Check if the charset is accepted
1523 return in_array($compare, self::user_agent('charsets'));
1526 // Invalid comparison
1532 // Return the key, if set
1533 return isset($info[$key]) ? $info[$key] : NULL;
1537 * Quick debugging of any variable. Any number of parameters can be set.
1541 public static function debug()
1543 if (func_num_args() === 0)
1547 $params = func_get_args();
1550 foreach ($params as $var)
1552 $output[] = '<pre>('.gettype($var).') '.html::specialchars(print_r($var, TRUE)).'</pre>';
1555 return implode("\n", $output);
1559 * Displays nice backtrace information.
1560 * @see http://php.net/debug_backtrace
1562 * @param array backtrace generated by an exception or debug_backtrace
1565 public static function backtrace($trace)
1567 if ( ! is_array($trace))
1573 foreach ($trace as $entry)
1577 if (isset($entry['file']))
1579 $temp .= self::lang('core.error_file_line', preg_replace('!^'.preg_quote(DOCROOT).'!', '', $entry['file']), $entry['line']);
1584 if (isset($entry['class']))
1586 // Add class and call type
1587 $temp .= $entry['class'].$entry['type'];
1591 $temp .= $entry['function'].'( ';
1593 // Add function args
1594 if (isset($entry['args']) AND is_array($entry['args']))
1596 // Separator starts as nothing
1599 while ($arg = array_shift($entry['args']))
1601 if (is_string($arg) AND is_file($arg))
1603 // Remove docroot from filename
1604 $arg = preg_replace('!^'.preg_quote(DOCROOT).'!', '', $arg);
1607 $temp .= $sep.html::specialchars(print_r($arg, TRUE));
1609 // Change separator to a comma
1614 $temp .= ' )</pre></li>';
1619 return '<ul class="backtrace">'.implode("\n", $output).'</ul>';
1623 * Saves the internal caches: configuration, include paths, etc.
1627 public static function internal_cache_save()
1629 if ( ! is_array(self::$write_cache))
1632 // Get internal cache names
1633 $caches = array_keys(self::$write_cache);
1638 foreach ($caches as $cache)
1640 if (isset(self::$internal_cache[$cache]))
1642 // Write the cache file
1643 self::cache_save($cache, self::$internal_cache[$cache], self::$configuration['core']['internal_cache']);
1645 // A cache has been written
1656 * Creates a generic i18n exception.
1658 class Kohana_Exception extends Exception {
1661 protected $template = 'kohana_error_page';
1664 protected $header = FALSE;
1667 protected $code = E_KOHANA;
1670 * Set exception message.
1672 * @param string i18n language key for the message
1673 * @param array addition line parameters
1675 public function __construct($error)
1677 $args = array_slice(func_get_args(), 1);
1679 // Fetch the error message
1680 $message = Kohana::lang($error, $args);
1682 if ($message === $error OR empty($message))
1684 // Unable to locate the message for the error
1685 $message = 'Unknown Exception: '.$error;
1688 // Sets $this->message the proper way
1689 parent::__construct($message);
1693 * Magic method for converting an object to a string.
1695 * @return string i18n message
1697 public function __toString()
1699 return (string) $this->message;
1703 * Fetch the template name.
1707 public function getTemplate()
1709 return $this->template;
1713 * Sends an Internal Server Error header.
1717 public function sendHeaders()
1719 // Send the 500 header
1720 header('HTTP/1.1 500 Internal Server Error');
1723 } // End Kohana Exception
1726 * Creates a custom exception.
1728 class Kohana_User_Exception extends Kohana_Exception {
1731 * Set exception title and message.
1733 * @param string exception title string
1734 * @param string exception message string
1735 * @param string custom error template
1737 public function __construct($title, $message, $template = FALSE)
1739 Exception::__construct($message);
1741 $this->code = $title;
1743 if ($template !== FALSE)
1745 $this->template = $template;
1749 } // End Kohana PHP Exception
1752 * Creates a Page Not Found exception.
1754 class Kohana_404_Exception extends Kohana_Exception {
1756 protected $code = E_PAGE_NOT_FOUND;
1759 * Set internal properties.
1761 * @param string URL of page
1762 * @param string custom error template
1764 public function __construct($page = FALSE, $template = FALSE)
1766 if ($page === FALSE)
1768 // Construct the page URI using Router properties
1769 $page = Router::$current_uri.Router::$url_suffix.Router::$query_string;
1772 Exception::__construct(Kohana::lang('core.page_not_found', $page));
1774 $this->template = $template;
1778 * Sends "File Not Found" headers, to emulate server behavior.
1782 public function sendHeaders()
1784 // Send the 404 header
1785 header('HTTP/1.1 404 File Not Found');
1788 } // End Kohana 404 Exception