UI design document updated.
[speedfreak] / Server / system / core / Kohana.php
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3  * Provides Kohana-specific helper functions. This is where the magic happens!
4  *
5  * $Id: Kohana.php 4372 2009-05-28 17:00:34Z ixmatus $
6  *
7  * @package    Core
8  * @author     Kohana Team
9  * @copyright  (c) 2007-2008 Kohana Team
10  * @license    http://kohanaphp.com/license.html
11  */
12 final class Kohana {
13
14         // The singleton instance of the controller
15         public static $instance;
16
17         // Output buffering level
18         private static $buffer_level;
19
20         // Will be set to TRUE when an exception is caught
21         public static $has_error = FALSE;
22
23         // The final output that will displayed by Kohana
24         public static $output = '';
25
26         // The current user agent
27         public static $user_agent;
28
29         // The current locale
30         public static $locale;
31
32         // Configuration
33         private static $configuration;
34
35         // Include paths
36         private static $include_paths;
37
38         // Logged messages
39         private static $log;
40
41         // Cache lifetime
42         private static $cache_lifetime;
43
44         // Log levels
45         private static $log_levels = array
46         (
47                 'error' => 1,
48                 'alert' => 2,
49                 'info'  => 3,
50                 'debug' => 4,
51         );
52
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;
59
60         /**
61          * Sets up the PHP environment. Adds error/exception handling, output
62          * buffering, and adds an auto-loading method for loading classes.
63          *
64          * This method is run immediately when this file is loaded, and is
65          * benchmarked as environment_setup.
66          *
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
71          *
72          * @return  void
73          */
74         public static function setup()
75         {
76                 static $run;
77
78                 // This function can only be run once
79                 if ($run === TRUE)
80                         return;
81
82                 // Start the environment setup benchmark
83                 Benchmark::start(SYSTEM_BENCHMARK.'_environment_setup');
84
85                 // Define Kohana error constant
86                 define('E_KOHANA', 42);
87
88                 // Define 404 error constant
89                 define('E_PAGE_NOT_FOUND', 43);
90
91                 // Define database error constant
92                 define('E_DATABASE_ERROR', 44);
93
94                 if (self::$cache_lifetime = self::config('core.internal_cache'))
95                 {
96                         // Are we using encryption for caches?
97                         self::$internal_cache_encrypt   = self::config('core.internal_cache_encrypt');
98                         
99                         if(self::$internal_cache_encrypt===TRUE)
100                         {
101                                 self::$internal_cache_key = self::config('core.internal_cache_key');
102                                 
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);
105                         }
106                         
107                         // Set the directory to be used for the internal cache
108                         if ( ! self::$internal_cache_path = self::config('core.internal_cache_path'))
109                         {
110                                 self::$internal_cache_path = APPPATH.'cache/';
111                         }
112
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);
116
117                         // Load cached file paths
118                         self::$internal_cache['find_file_paths'] = self::cache('find_file_paths', self::$cache_lifetime);
119
120                         // Enable cache saving
121                         Event::add('system.shutdown', array(__CLASS__, 'internal_cache_save'));
122                 }
123
124                 // Disable notices and "strict" errors
125                 $ER = error_reporting(~E_NOTICE & ~E_STRICT);
126
127                 // Set the user agent
128                 self::$user_agent = ( ! empty($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : '');
129
130                 if (function_exists('date_default_timezone_set'))
131                 {
132                         $timezone = self::config('locale.timezone');
133
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);
137                 }
138
139                 // Restore error reporting
140                 error_reporting($ER);
141
142                 // Start output buffering
143                 ob_start(array(__CLASS__, 'output_buffer'));
144
145                 // Save buffering level
146                 self::$buffer_level = ob_get_level();
147
148                 // Set autoloader
149                 spl_autoload_register(array('Kohana', 'auto_load'));
150
151                 // Set error handler
152                 set_error_handler(array('Kohana', 'exception_handler'));
153
154                 // Set exception handler
155                 set_exception_handler(array('Kohana', 'exception_handler'));
156
157                 // Send default text/html UTF-8 header
158                 header('Content-Type: text/html; charset=UTF-8');
159
160                 // Load locales
161                 $locales = self::config('locale.language');
162
163                 // Make first locale UTF-8
164                 $locales[0] .= '.UTF-8';
165
166                 // Set locale information
167                 self::$locale = setlocale(LC_ALL, $locales);
168
169                 if (self::$configuration['core']['log_threshold'] > 0)
170                 {
171                         // Set the log directory
172                         self::log_directory(self::$configuration['core']['log_directory']);
173
174                         // Enable log writing at shutdown
175                         register_shutdown_function(array(__CLASS__, 'log_save'));
176                 }
177
178                 // Enable Kohana routing
179                 Event::add('system.routing', array('Router', 'find_uri'));
180                 Event::add('system.routing', array('Router', 'setup'));
181
182                 // Enable Kohana controller initialization
183                 Event::add('system.execute', array('Kohana', 'instance'));
184
185                 // Enable Kohana 404 pages
186                 Event::add('system.404', array('Kohana', 'show_404'));
187
188                 // Enable Kohana output handling
189                 Event::add('system.shutdown', array('Kohana', 'shutdown'));
190
191                 if (self::config('core.enable_hooks') === TRUE)
192                 {
193                         // Find all the hook files
194                         $hooks = self::list_files('hooks', TRUE);
195
196                         foreach ($hooks as $file)
197                         {
198                                 // Load the hook
199                                 include $file;
200                         }
201                 }
202
203                 // Setup is complete, prevent it from being run again
204                 $run = TRUE;
205
206                 // Stop the environment setup routine
207                 Benchmark::stop(SYSTEM_BENCHMARK.'_environment_setup');
208         }
209
210         /**
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.
214          *
215          * This method is benchmarked as controller_setup and controller_execution.
216          *
217          * @return  object  instance of controller
218          */
219         public static function & instance()
220         {
221                 if (self::$instance === NULL)
222                 {
223                         Benchmark::start(SYSTEM_BENCHMARK.'_controller_setup');
224
225                         // Include the Controller file
226                         require Router::$controller_path;
227
228                         try
229                         {
230                                 // Start validation of the controller
231                                 $class = new ReflectionClass(ucfirst(Router::$controller).'_Controller');
232                         }
233                         catch (ReflectionException $e)
234                         {
235                                 // Controller does not exist
236                                 Event::run('system.404');
237                         }
238
239                         if ($class->isAbstract() OR (IN_PRODUCTION AND $class->getConstant('ALLOW_PRODUCTION') == FALSE))
240                         {
241                                 // Controller is not allowed to run in production
242                                 Event::run('system.404');
243                         }
244
245                         // Run system.pre_controller
246                         Event::run('system.pre_controller');
247
248                         // Create a new controller instance
249                         $controller = $class->newInstance();
250
251                         // Controller constructor has been executed
252                         Event::run('system.post_controller_constructor');
253
254                         try
255                         {
256                                 // Load the controller method
257                                 $method = $class->getMethod(Router::$method);
258
259                                 // Method exists
260                                 if (Router::$method[0] === '_')
261                                 {
262                                         // Do not allow access to hidden methods
263                                         Event::run('system.404');
264                                 }
265
266                                 if ($method->isProtected() or $method->isPrivate())
267                                 {
268                                         // Do not attempt to invoke protected methods
269                                         throw new ReflectionException('protected controller method');
270                                 }
271
272                                 // Default arguments
273                                 $arguments = Router::$arguments;
274                         }
275                         catch (ReflectionException $e)
276                         {
277                                 // Use __call instead
278                                 $method = $class->getMethod('__call');
279
280                                 // Use arguments in __call format
281                                 $arguments = array(Router::$method, Router::$arguments);
282                         }
283
284                         // Stop the controller setup benchmark
285                         Benchmark::stop(SYSTEM_BENCHMARK.'_controller_setup');
286
287                         // Start the controller execution benchmark
288                         Benchmark::start(SYSTEM_BENCHMARK.'_controller_execution');
289
290                         // Execute the controller method
291                         $method->invokeArgs($controller, $arguments);
292
293                         // Controller method has been executed
294                         Event::run('system.post_controller');
295
296                         // Stop the controller execution benchmark
297                         Benchmark::stop(SYSTEM_BENCHMARK.'_controller_execution');
298                 }
299
300                 return self::$instance;
301         }
302
303         /**
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.
306          *
307          * @param   boolean  re-process the include paths
308          * @return  array
309          */
310         public static function include_paths($process = FALSE)
311         {
312                 if ($process === TRUE)
313                 {
314                         // Add APPPATH as the first path
315                         self::$include_paths = array(APPPATH);
316
317                         foreach (self::$configuration['core']['modules'] as $path)
318                         {
319                                 if ($path = str_replace('\\', '/', realpath($path)))
320                                 {
321                                         // Add a valid path
322                                         self::$include_paths[] = $path.'/';
323                                 }
324                         }
325
326                         // Add SYSPATH as the last path
327                         self::$include_paths[] = SYSPATH;
328                 }
329
330                 return self::$include_paths;
331         }
332
333         /**
334          * Get a config item or group.
335          *
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?
339          * @return  mixed
340          */
341         public static function config($key, $slash = FALSE, $required = TRUE)
342         {
343                 if (self::$configuration === NULL)
344                 {
345                         // Load core configuration
346                         self::$configuration['core'] = self::config_load('core');
347
348                         // Re-parse the include paths
349                         self::include_paths(TRUE);
350                 }
351
352                 // Get the group name from the key
353                 $group = explode('.', $key, 2);
354                 $group = $group[0];
355
356                 if ( ! isset(self::$configuration[$group]))
357                 {
358                         // Load the configuration group
359                         self::$configuration[$group] = self::config_load($group, $required);
360                 }
361
362                 // Get the value of the key string
363                 $value = self::key_string(self::$configuration, $key);
364
365                 if ($slash === TRUE AND is_string($value) AND $value !== '')
366                 {
367                         // Force the value to end with "/"
368                         $value = rtrim($value, '/').'/';
369                 }
370
371                 return $value;
372         }
373
374         /**
375          * Sets a configuration item, if allowed.
376          *
377          * @param   string   config key string
378          * @param   string   config value
379          * @return  boolean
380          */
381         public static function config_set($key, $value)
382         {
383                 // Do this to make sure that the config array is already loaded
384                 self::config($key);
385
386                 if (substr($key, 0, 7) === 'routes.')
387                 {
388                         // Routes cannot contain sub keys due to possible dots in regex
389                         $keys = explode('.', $key, 2);
390                 }
391                 else
392                 {
393                         // Convert dot-noted key string to an array
394                         $keys = explode('.', $key);
395                 }
396
397                 // Used for recursion
398                 $conf =& self::$configuration;
399                 $last = count($keys) - 1;
400
401                 foreach ($keys as $i => $k)
402                 {
403                         if ($i === $last)
404                         {
405                                 $conf[$k] = $value;
406                         }
407                         else
408                         {
409                                 $conf =& $conf[$k];
410                         }
411                 }
412
413                 if ($key === 'core.modules')
414                 {
415                         // Reprocess the include paths
416                         self::include_paths(TRUE);
417                 }
418
419                 return TRUE;
420         }
421
422         /**
423          * Load a config file.
424          *
425          * @param   string   config filename, without extension
426          * @param   boolean  is the file required?
427          * @return  array
428          */
429         public static function config_load($name, $required = TRUE)
430         {
431                 if ($name === 'core')
432                 {
433                         // Load the application configuration file
434                         require APPPATH.'config/config'.EXT;
435
436                         if ( ! isset($config['site_domain']))
437                         {
438                                 // Invalid config file
439                                 die('Your Kohana application configuration file is not valid.');
440                         }
441
442                         return $config;
443                 }
444
445                 if (isset(self::$internal_cache['configuration'][$name]))
446                         return self::$internal_cache['configuration'][$name];
447
448                 // Load matching configs
449                 $configuration = array();
450
451                 if ($files = self::find_file('config', $name, $required))
452                 {
453                         foreach ($files as $file)
454                         {
455                                 require $file;
456
457                                 if (isset($config) AND is_array($config))
458                                 {
459                                         // Merge in configuration
460                                         $configuration = array_merge($configuration, $config);
461                                 }
462                         }
463                 }
464
465                 if ( ! isset(self::$write_cache['configuration']))
466                 {
467                         // Cache has changed
468                         self::$write_cache['configuration'] = TRUE;
469                 }
470
471                 return self::$internal_cache['configuration'][$name] = $configuration;
472         }
473
474         /**
475          * Clears a config group from the cached configuration.
476          *
477          * @param   string  config group
478          * @return  void
479          */
480         public static function config_clear($group)
481         {
482                 // Remove the group from config
483                 unset(self::$configuration[$group], self::$internal_cache['configuration'][$group]);
484
485                 if ( ! isset(self::$write_cache['configuration']))
486                 {
487                         // Cache has changed
488                         self::$write_cache['configuration'] = TRUE;
489                 }
490         }
491
492         /**
493          * Add a new message to the log.
494          *
495          * @param   string  type of message
496          * @param   string  message text
497          * @return  void
498          */
499         public static function log($type, $message)
500         {
501                 if (self::$log_levels[$type] <= self::$configuration['core']['log_threshold'])
502                 {
503                         $message = array(date('Y-m-d H:i:s P'), $type, $message);
504
505                         // Run the system.log event
506                         Event::run('system.log', $message);
507
508                         self::$log[] = $message;
509                 }
510         }
511
512         /**
513          * Save all currently logged messages.
514          *
515          * @return  void
516          */
517         public static function log_save()
518         {
519                 if (empty(self::$log) OR self::$configuration['core']['log_threshold'] < 1)
520                         return;
521
522                 // Filename of the log
523                 $filename = self::log_directory().date('Y-m-d').'.log'.EXT;
524
525                 if ( ! is_file($filename))
526                 {
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);
530
531                         // Prevent external writes
532                         chmod($filename, 0644);
533                 }
534
535                 // Messages to write
536                 $messages = array();
537
538                 do
539                 {
540                         // Load the next mess
541                         list ($date, $type, $text) = array_shift(self::$log);
542
543                         // Add a new message line
544                         $messages[] = $date.' --- '.$type.': '.$text;
545                 }
546                 while ( ! empty(self::$log));
547
548                 // Write messages to log file
549                 file_put_contents($filename, implode(PHP_EOL, $messages).PHP_EOL, FILE_APPEND);
550         }
551
552         /**
553          * Get or set the logging directory.
554          *
555          * @param   string  new log directory
556          * @return  string
557          */
558         public static function log_directory($dir = NULL)
559         {
560                 static $directory;
561
562                 if ( ! empty($dir))
563                 {
564                         // Get the directory path
565                         $dir = realpath($dir);
566
567                         if (is_dir($dir) AND is_writable($dir))
568                         {
569                                 // Change the log directory
570                                 $directory = str_replace('\\', '/', $dir).'/';
571                         }
572                         else
573                         {
574                                 // Log directory is invalid
575                                 throw new Kohana_Exception('core.log_dir_unwritable', $dir);
576                         }
577                 }
578
579                 return $directory;
580         }
581
582         /**
583          * Load data from a simple cache file. This should only be used internally,
584          * and is NOT a replacement for the Cache library.
585          *
586          * @param   string   unique name of cache
587          * @param   integer  expiration in seconds
588          * @return  mixed
589          */
590         public static function cache($name, $lifetime)
591         {
592                 if ($lifetime > 0)
593                 {
594                         $path = self::$internal_cache_path.'kohana_'.$name;
595
596                         if (is_file($path))
597                         {
598                                 // Check the file modification time
599                                 if ((time() - filemtime($path)) < $lifetime)
600                                 {
601                                         // Cache is valid! Now, do we need to decrypt it?
602                                         if(self::$internal_cache_encrypt===TRUE)
603                                         {
604                                                 $data           = file_get_contents($path);
605                                                 
606                                                 $iv_size        = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
607                                                 $iv                     = mcrypt_create_iv($iv_size, MCRYPT_RAND);
608                                                 
609                                                 $decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::$internal_cache_key, $data, MCRYPT_MODE_ECB, $iv);
610                                                 
611                                                 $cache  = unserialize($decrypted_text);
612                                                 
613                                                 // If the key changed, delete the cache file
614                                                 if(!$cache)
615                                                         unlink($path);
616
617                                                 // If cache is false (as above) return NULL, otherwise, return the cache
618                                                 return ($cache ? $cache : NULL);
619                                         }
620                                         else
621                                         {
622                                                 return unserialize(file_get_contents($path));
623                                         }
624                                 }
625                                 else
626                                 {
627                                         // Cache is invalid, delete it
628                                         unlink($path);
629                                 }
630                         }
631                 }
632
633                 // No cache found
634                 return NULL;
635         }
636
637         /**
638          * Save data to a simple cache file. This should only be used internally, and
639          * is NOT a replacement for the Cache library.
640          *
641          * @param   string   cache name
642          * @param   mixed    data to cache
643          * @param   integer  expiration in seconds
644          * @return  boolean
645          */
646         public static function cache_save($name, $data, $lifetime)
647         {
648                 if ($lifetime < 1)
649                         return FALSE;
650
651                 $path = self::$internal_cache_path.'kohana_'.$name;
652
653                 if ($data === NULL)
654                 {
655                         // Delete cache
656                         return (is_file($path) and unlink($path));
657                 }
658                 else
659                 {
660                         // Using encryption? Encrypt the data when we write it
661                         if(self::$internal_cache_encrypt===TRUE)
662                         {
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);
666                                 
667                                 // Serialize and encrypt!
668                                 $encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::$internal_cache_key, serialize($data), MCRYPT_MODE_ECB, $iv);
669                                 
670                                 return (bool) file_put_contents($path, $encrypted_text);
671                         }
672                         else
673                         {
674                                 // Write data to cache file
675                                 return (bool) file_put_contents($path, serialize($data));
676                         }
677                 }
678         }
679
680         /**
681          * Kohana output handler. Called during ob_clean, ob_flush, and their variants.
682          *
683          * @param   string  current output buffer
684          * @return  string
685          */
686         public static function output_buffer($output)
687         {
688                 // Could be flushing, so send headers first
689                 if ( ! Event::has_run('system.send_headers'))
690                 {
691                         // Run the send_headers event
692                         Event::run('system.send_headers');
693                 }
694                 
695                 self::$output   = $output;
696                 
697                 // Set and return the final output
698                 return self::$output;
699         }
700
701         /**
702          * Closes all open output buffers, either by flushing or cleaning, and stores the Kohana
703          * output buffer for display during shutdown.
704          *
705          * @param   boolean  disable to clear buffers, rather than flushing
706          * @return  void
707          */
708         public static function close_buffers($flush = TRUE)
709         {
710                 if (ob_get_level() >= self::$buffer_level)
711                 {
712                         // Set the close function
713                         $close = ($flush === TRUE) ? 'ob_end_flush' : 'ob_end_clean';
714
715                         while (ob_get_level() > self::$buffer_level)
716                         {
717                                 // Flush or clean the buffer
718                                 $close();
719                         }
720
721                         // Store the Kohana output buffer
722                         ob_end_clean();
723                 }
724         }
725
726         /**
727          * Triggers the shutdown of Kohana by closing the output buffer, runs the system.display event.
728          *
729          * @return  void
730          */
731         public static function shutdown()
732         {
733                 // Close output buffers
734                 self::close_buffers(TRUE);
735
736                 // Run the output event
737                 Event::run('system.display', self::$output);
738
739                 // Render the final output
740                 self::render(self::$output);
741         }
742
743         /**
744          * Inserts global Kohana variables into the generated output and prints it.
745          *
746          * @param   string  final output that will displayed
747          * @return  void
748          */
749         public static function render($output)
750         {
751                 if (self::config('core.render_stats') === TRUE)
752                 {
753                         // Fetch memory usage in MB
754                         $memory = function_exists('memory_get_usage') ? (memory_get_usage() / 1024 / 1024) : 0;
755
756                         // Fetch benchmark for page execution time
757                         $benchmark = Benchmark::get(SYSTEM_BENCHMARK.'_total_execution');
758
759                         // Replace the global template variables
760                         $output = str_replace(
761                                 array
762                                 (
763                                         '{kohana_version}',
764                                         '{kohana_codename}',
765                                         '{execution_time}',
766                                         '{memory_usage}',
767                                         '{included_files}',
768                                 ),
769                                 array
770                                 (
771                                         KOHANA_VERSION,
772                                         KOHANA_CODENAME,
773                                         $benchmark['time'],
774                                         number_format($memory, 2).'MB',
775                                         count(get_included_files()),
776                                 ),
777                                 $output
778                         );
779                 }
780
781                 if ($level = self::config('core.output_compression') AND ini_get('output_handler') !== 'ob_gzhandler' AND (int) ini_get('zlib.output_compression') === 0)
782                 {
783                         if ($level < 1 OR $level > 9)
784                         {
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));
788                         }
789
790                         if (stripos(@$_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
791                         {
792                                 $compress = 'gzip';
793                         }
794                         elseif (stripos(@$_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') !== FALSE)
795                         {
796                                 $compress = 'deflate';
797                         }
798                 }
799
800                 if (isset($compress) AND $level > 0)
801                 {
802                         switch ($compress)
803                         {
804                                 case 'gzip':
805                                         // Compress output using gzip
806                                         $output = gzencode($output, $level);
807                                 break;
808                                 case 'deflate':
809                                         // Compress output using zlib (HTTP deflate)
810                                         $output = gzdeflate($output, $level);
811                                 break;
812                         }
813
814                         // This header must be sent with compressed content to prevent
815                         // browser caches from breaking
816                         header('Vary: Accept-Encoding');
817
818                         // Send the content encoding header
819                         header('Content-Encoding: '.$compress);
820
821                         // Sending Content-Length in CGI can result in unexpected behavior
822                         if (stripos(PHP_SAPI, 'cgi') === FALSE)
823                         {
824                                 header('Content-Length: '.strlen($output));
825                         }
826                 }
827
828                 echo $output;
829         }
830
831         /**
832          * Displays a 404 page.
833          *
834          * @throws  Kohana_404_Exception
835          * @param   string  URI of page
836          * @param   string  custom template
837          * @return  void
838          */
839         public static function show_404($page = FALSE, $template = FALSE)
840         {
841                 throw new Kohana_404_Exception($page, $template);
842         }
843
844         /**
845          * Dual-purpose PHP error and exception handler. Uses the kohana_error_page
846          * view to display the message.
847          *
848          * @param   integer|object  exception object or error code
849          * @param   string          error message
850          * @param   string          filename
851          * @param   integer         line number
852          * @return  void
853          */
854         public static function exception_handler($exception, $message = NULL, $file = NULL, $line = NULL)
855         {
856                 try
857                 {
858                         // PHP errors have 5 args, always
859                         $PHP_ERROR = (func_num_args() === 5);
860         
861                         // Test to see if errors should be displayed
862                         if ($PHP_ERROR AND (error_reporting() & $exception) === 0)
863                                 return;
864         
865                         // This is useful for hooks to determine if a page has an error
866                         self::$has_error = TRUE;
867         
868                         // Error handling will use exactly 5 args, every time
869                         if ($PHP_ERROR)
870                         {
871                                 $code     = $exception;
872                                 $type     = 'PHP Error';
873                                 $template = 'kohana_error_page';
874                         }
875                         else
876                         {
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';
883                         }
884         
885                         if (is_numeric($code))
886                         {
887                                 $codes = self::lang('errors');
888         
889                                 if ( ! empty($codes[$code]))
890                                 {
891                                         list($level, $error, $description) = $codes[$code];
892                                 }
893                                 else
894                                 {
895                                         $level = 1;
896                                         $error = $PHP_ERROR ? 'Unknown Error' : get_class($exception);
897                                         $description = '';
898                                 }
899                         }
900                         else
901                         {
902                                 // Custom error message, this will never be logged
903                                 $level = 5;
904                                 $error = $code;
905                                 $description = '';
906                         }
907         
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);
911         
912                         if ($level <= self::$configuration['core']['log_threshold'])
913                         {
914                                 // Log the error
915                                 self::log('error', self::lang('core.uncaught_exception', $type, $message, $file, $line));
916                         }
917         
918                         if ($PHP_ERROR)
919                         {
920                                 $description = self::lang('errors.'.E_RECOVERABLE_ERROR);
921                                 $description = is_array($description) ? $description[2] : '';
922         
923                                 if ( ! headers_sent())
924                                 {
925                                         // Send the 500 header
926                                         header('HTTP/1.1 500 Internal Server Error');
927                                 }
928                         }
929                         else
930                         {
931                                 if (method_exists($exception, 'sendHeaders') AND ! headers_sent())
932                                 {
933                                         // Send the headers if they have not already been sent
934                                         $exception->sendHeaders();
935                                 }
936                         }
937         
938                         // Close all output buffers except for Kohana
939                         while (ob_get_level() > self::$buffer_level)
940                         {
941                                 ob_end_clean();
942                         }
943         
944                         // Test if display_errors is on
945                         if (self::$configuration['core']['display_errors'] === TRUE)
946                         {
947                                 if ( ! IN_PRODUCTION AND $line != FALSE)
948                                 {
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();
951         
952                                         // Beautify backtrace
953                                         $trace = self::backtrace($trace);
954                                 }
955         
956                                 // Load the error
957                                 require self::find_file('views', empty($template) ? 'kohana_error_page' : $template);
958                         }
959                         else
960                         {
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));
964         
965                                 // Load the errors_disabled view
966                                 require self::find_file('views', 'kohana_error_disabled');
967                         }
968         
969                         if ( ! Event::has_run('system.shutdown'))
970                         {
971                                 // Run the shutdown even to ensure a clean exit
972                                 Event::run('system.shutdown');
973                         }
974         
975                         // Turn off error reporting
976                         error_reporting(0);
977                         exit;
978                 }
979                 catch (Exception $e)
980                 {
981                         if (IN_PRODUCTION)
982                         {
983                                 die('Fatal Error');
984                         }
985                         else
986                         {
987                                 die('Fatal Error: '.$e->getMessage().' File: '.$e->getFile().' Line: '.$e->getLine());
988                         }
989                 }
990         }
991
992         /**
993          * Provides class auto-loading.
994          *
995          * @throws  Kohana_Exception
996          * @param   string  name of class
997          * @return  bool
998          */
999         public static function auto_load($class)
1000         {
1001                 if (class_exists($class, FALSE))
1002                         return TRUE;
1003
1004                 if (($suffix = strrpos($class, '_')) > 0)
1005                 {
1006                         // Find the class suffix
1007                         $suffix = substr($class, $suffix + 1);
1008                 }
1009                 else
1010                 {
1011                         // No suffix
1012                         $suffix = FALSE;
1013                 }
1014
1015                 if ($suffix === 'Core')
1016                 {
1017                         $type = 'libraries';
1018                         $file = substr($class, 0, -5);
1019                 }
1020                 elseif ($suffix === 'Controller')
1021                 {
1022                         $type = 'controllers';
1023                         // Lowercase filename
1024                         $file = strtolower(substr($class, 0, -11));
1025                 }
1026                 elseif ($suffix === 'Model')
1027                 {
1028                         $type = 'models';
1029                         // Lowercase filename
1030                         $file = strtolower(substr($class, 0, -6));
1031                 }
1032                 elseif ($suffix === 'Driver')
1033                 {
1034                         $type = 'libraries/drivers';
1035                         $file = str_replace('_', '/', substr($class, 0, -7));
1036                 }
1037                 else
1038                 {
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';
1043                         $file = $class;
1044                 }
1045
1046                 if ($filename = self::find_file($type, $file))
1047                 {
1048                         // Load the class
1049                         require $filename;
1050                 }
1051                 else
1052                 {
1053                         // The class could not be found
1054                         return FALSE;
1055                 }
1056
1057                 if ($filename = self::find_file($type, self::$configuration['core']['extension_prefix'].$class))
1058                 {
1059                         // Load the class extension
1060                         require $filename;
1061                 }
1062                 elseif ($suffix !== 'Core' AND class_exists($class.'_Core', FALSE))
1063                 {
1064                         // Class extension to be evaluated
1065                         $extension = 'class '.$class.' extends '.$class.'_Core { }';
1066
1067                         // Start class analysis
1068                         $core = new ReflectionClass($class.'_Core');
1069
1070                         if ($core->isAbstract())
1071                         {
1072                                 // Make the extension abstract
1073                                 $extension = 'abstract '.$extension;
1074                         }
1075
1076                         // Transparent class extensions are handled using eval. This is
1077                         // a disgusting hack, but it gets the job done.
1078                         eval($extension);
1079                 }
1080
1081                 return TRUE;
1082         }
1083
1084         /**
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.
1088          *
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
1097          */
1098         public static function find_file($directory, $filename, $required = FALSE, $ext = FALSE)
1099         {
1100                 // NOTE: This test MUST be not be a strict comparison (===), or empty
1101                 // extensions will be allowed!
1102                 if ($ext == '')
1103                 {
1104                         // Use the default extension
1105                         $ext = EXT;
1106                 }
1107                 else
1108                 {
1109                         // Add a period before the extension
1110                         $ext = '.'.$ext;
1111                 }
1112
1113                 // Search path
1114                 $search = $directory.'/'.$filename.$ext;
1115
1116                 if (isset(self::$internal_cache['find_file_paths'][$search]))
1117                         return self::$internal_cache['find_file_paths'][$search];
1118
1119                 // Load include paths
1120                 $paths = self::$include_paths;
1121
1122                 // Nothing found, yet
1123                 $found = NULL;
1124
1125                 if ($directory === 'config' OR $directory === 'i18n')
1126                 {
1127                         // Search in reverse, for merging
1128                         $paths = array_reverse($paths);
1129
1130                         foreach ($paths as $path)
1131                         {
1132                                 if (is_file($path.$search))
1133                                 {
1134                                         // A matching file has been found
1135                                         $found[] = $path.$search;
1136                                 }
1137                         }
1138                 }
1139                 else
1140                 {
1141                         foreach ($paths as $path)
1142                         {
1143                                 if (is_file($path.$search))
1144                                 {
1145                                         // A matching file has been found
1146                                         $found = $path.$search;
1147
1148                                         // Stop searching
1149                                         break;
1150                                 }
1151                         }
1152                 }
1153
1154                 if ($found === NULL)
1155                 {
1156                         if ($required === TRUE)
1157                         {
1158                                 // Directory i18n key
1159                                 $directory = 'core.'.inflector::singular($directory);
1160
1161                                 // If the file is required, throw an exception
1162                                 throw new Kohana_Exception('core.resource_not_found', self::lang($directory), $filename);
1163                         }
1164                         else
1165                         {
1166                                 // Nothing was found, return FALSE
1167                                 $found = FALSE;
1168                         }
1169                 }
1170
1171                 if ( ! isset(self::$write_cache['find_file_paths']))
1172                 {
1173                         // Write cache at shutdown
1174                         self::$write_cache['find_file_paths'] = TRUE;
1175                 }
1176
1177                 return self::$internal_cache['find_file_paths'][$search] = $found;
1178         }
1179
1180         /**
1181          * Lists all files and directories in a resource path.
1182          *
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
1187          */
1188         public static function list_files($directory, $recursive = FALSE, $path = FALSE)
1189         {
1190                 $files = array();
1191
1192                 if ($path === FALSE)
1193                 {
1194                         $paths = array_reverse(self::include_paths());
1195
1196                         foreach ($paths as $path)
1197                         {
1198                                 // Recursively get and merge all files
1199                                 $files = array_merge($files, self::list_files($directory, $recursive, $path.$directory));
1200                         }
1201                 }
1202                 else
1203                 {
1204                         $path = rtrim($path, '/').'/';
1205
1206                         if (is_readable($path))
1207                         {
1208                                 $items = (array) glob($path.'*');
1209
1210                                 if ( ! empty($items))
1211                                 {
1212                                         foreach ($items as $index => $item)
1213                                         {
1214                                                 $files[] = $item = str_replace('\\', '/', $item);
1215
1216                                                 // Handle recursion
1217                                                 if (is_dir($item) AND $recursive == TRUE)
1218                                                 {
1219                                                         // Filename should only be the basename
1220                                                         $item = pathinfo($item, PATHINFO_BASENAME);
1221
1222                                                         // Append sub-directory search
1223                                                         $files = array_merge($files, self::list_files($directory, TRUE, $path.$item));
1224                                                 }
1225                                         }
1226                                 }
1227                         }
1228                 }
1229
1230                 return $files;
1231         }
1232
1233         /**
1234          * Fetch an i18n language item.
1235          *
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
1239          */
1240         public static function lang($key, $args = array())
1241         {
1242                 // Extract the main group from the key
1243                 $group = explode('.', $key, 2);
1244                 $group = $group[0];
1245
1246                 // Get locale name
1247                 $locale = self::config('locale.language.0');
1248
1249                 if ( ! isset(self::$internal_cache['language'][$locale][$group]))
1250                 {
1251                         // Messages for this group
1252                         $messages = array();
1253
1254                         if ($files = self::find_file('i18n', $locale.'/'.$group))
1255                         {
1256                                 foreach ($files as $file)
1257                                 {
1258                                         include $file;
1259
1260                                         // Merge in configuration
1261                                         if ( ! empty($lang) AND is_array($lang))
1262                                         {
1263                                                 foreach ($lang as $k => $v)
1264                                                 {
1265                                                         $messages[$k] = $v;
1266                                                 }
1267                                         }
1268                                 }
1269                         }
1270
1271                         if ( ! isset(self::$write_cache['language']))
1272                         {
1273                                 // Write language cache
1274                                 self::$write_cache['language'] = TRUE;
1275                         }
1276
1277                         self::$internal_cache['language'][$locale][$group] = $messages;
1278                 }
1279
1280                 // Get the line from cache
1281                 $line = self::key_string(self::$internal_cache['language'][$locale], $key);
1282
1283                 if ($line === NULL)
1284                 {
1285                         self::log('error', 'Missing i18n entry '.$key.' for language '.$locale);
1286
1287                         // Return the key string as fallback
1288                         return $key;
1289                 }
1290
1291                 if (is_string($line) AND func_num_args() > 1)
1292                 {
1293                         $args = array_slice(func_get_args(), 1);
1294
1295                         // Add the arguments into the line
1296                         $line = vsprintf($line, is_array($args[0]) ? $args[0] : $args);
1297                 }
1298
1299                 return $line;
1300         }
1301
1302         /**
1303          * Returns the value of a key, defined by a 'dot-noted' string, from an array.
1304          *
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
1309          */
1310         public static function key_string($array, $keys)
1311         {
1312                 if (empty($array))
1313                         return NULL;
1314
1315                 // Prepare for loop
1316                 $keys = explode('.', $keys);
1317
1318                 do
1319                 {
1320                         // Get the next key
1321                         $key = array_shift($keys);
1322
1323                         if (isset($array[$key]))
1324                         {
1325                                 if (is_array($array[$key]) AND ! empty($keys))
1326                                 {
1327                                         // Dig down to prepare the next loop
1328                                         $array = $array[$key];
1329                                 }
1330                                 else
1331                                 {
1332                                         // Requested key was found
1333                                         return $array[$key];
1334                                 }
1335                         }
1336                         else
1337                         {
1338                                 // Requested key is not set
1339                                 break;
1340                         }
1341                 }
1342                 while ( ! empty($keys));
1343
1344                 return NULL;
1345         }
1346
1347         /**
1348          * Sets values in an array by using a 'dot-noted' string.
1349          *
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
1353          * @return  void
1354          */
1355         public static function key_string_set( & $array, $keys, $fill = NULL)
1356         {
1357                 if (is_object($array) AND ($array instanceof ArrayObject))
1358                 {
1359                         // Copy the array
1360                         $array_copy = $array->getArrayCopy();
1361
1362                         // Is an object
1363                         $array_object = TRUE;
1364                 }
1365                 else
1366                 {
1367                         if ( ! is_array($array))
1368                         {
1369                                 // Must always be an array
1370                                 $array = (array) $array;
1371                         }
1372
1373                         // Copy is a reference to the array
1374                         $array_copy =& $array;
1375                 }
1376
1377                 if (empty($keys))
1378                         return $array;
1379
1380                 // Create keys
1381                 $keys = explode('.', $keys);
1382
1383                 // Create reference to the array
1384                 $row =& $array_copy;
1385
1386                 for ($i = 0, $end = count($keys) - 1; $i <= $end; $i++)
1387                 {
1388                         // Get the current key
1389                         $key = $keys[$i];
1390
1391                         if ( ! isset($row[$key]))
1392                         {
1393                                 if (isset($keys[$i + 1]))
1394                                 {
1395                                         // Make the value an array
1396                                         $row[$key] = array();
1397                                 }
1398                                 else
1399                                 {
1400                                         // Add the fill key
1401                                         $row[$key] = $fill;
1402                                 }
1403                         }
1404                         elseif (isset($keys[$i + 1]))
1405                         {
1406                                 // Make the value an array
1407                                 $row[$key] = (array) $row[$key];
1408                         }
1409
1410                         // Go down a level, creating a new row reference
1411                         $row =& $row[$key];
1412                 }
1413
1414                 if (isset($array_object))
1415                 {
1416                         // Swap the array back in
1417                         $array->exchangeArray($array_copy);
1418                 }
1419         }
1420
1421         /**
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
1425          *
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
1431          */
1432         public static function user_agent($key = 'agent', $compare = NULL)
1433         {
1434                 static $info;
1435
1436                 // Return the raw string
1437                 if ($key === 'agent')
1438                         return self::$user_agent;
1439
1440                 if ($info === NULL)
1441                 {
1442                         // Parse the user agent and extract basic information
1443                         $agents = self::config('user_agents');
1444
1445                         foreach ($agents as $type => $data)
1446                         {
1447                                 foreach ($data as $agent => $name)
1448                                 {
1449                                         if (stripos(self::$user_agent, $agent) !== FALSE)
1450                                         {
1451                                                 if ($type === 'browser' AND preg_match('|'.preg_quote($agent).'[^0-9.]*+([0-9.][0-9.a-z]*)|i', self::$user_agent, $match))
1452                                                 {
1453                                                         // Set the browser version
1454                                                         $info['version'] = $match[1];
1455                                                 }
1456
1457                                                 // Set the agent name
1458                                                 $info[$type] = $name;
1459                                                 break;
1460                                         }
1461                                 }
1462                         }
1463                 }
1464
1465                 if (empty($info[$key]))
1466                 {
1467                         switch ($key)
1468                         {
1469                                 case 'is_robot':
1470                                 case 'is_browser':
1471                                 case 'is_mobile':
1472                                         // A boolean result
1473                                         $return = ! empty($info[substr($key, 3)]);
1474                                 break;
1475                                 case 'languages':
1476                                         $return = array();
1477                                         if ( ! empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
1478                                         {
1479                                                 if (preg_match_all('/[-a-z]{2,}/', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])), $matches))
1480                                                 {
1481                                                         // Found a result
1482                                                         $return = $matches[0];
1483                                                 }
1484                                         }
1485                                 break;
1486                                 case 'charsets':
1487                                         $return = array();
1488                                         if ( ! empty($_SERVER['HTTP_ACCEPT_CHARSET']))
1489                                         {
1490                                                 if (preg_match_all('/[-a-z0-9]{2,}/', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET'])), $matches))
1491                                                 {
1492                                                         // Found a result
1493                                                         $return = $matches[0];
1494                                                 }
1495                                         }
1496                                 break;
1497                                 case 'referrer':
1498                                         if ( ! empty($_SERVER['HTTP_REFERER']))
1499                                         {
1500                                                 // Found a result
1501                                                 $return = trim($_SERVER['HTTP_REFERER']);
1502                                         }
1503                                 break;
1504                         }
1505
1506                         // Cache the return value
1507                         isset($return) and $info[$key] = $return;
1508                 }
1509
1510                 if ( ! empty($compare))
1511                 {
1512                         // The comparison must always be lowercase
1513                         $compare = strtolower($compare);
1514
1515                         switch ($key)
1516                         {
1517                                 case 'accept_lang':
1518                                         // Check if the lange is accepted
1519                                         return in_array($compare, self::user_agent('languages'));
1520                                 break;
1521                                 case 'accept_charset':
1522                                         // Check if the charset is accepted
1523                                         return in_array($compare, self::user_agent('charsets'));
1524                                 break;
1525                                 default:
1526                                         // Invalid comparison
1527                                         return FALSE;
1528                                 break;
1529                         }
1530                 }
1531
1532                 // Return the key, if set
1533                 return isset($info[$key]) ? $info[$key] : NULL;
1534         }
1535
1536         /**
1537          * Quick debugging of any variable. Any number of parameters can be set.
1538          *
1539          * @return  string
1540          */
1541         public static function debug()
1542         {
1543                 if (func_num_args() === 0)
1544                         return;
1545
1546                 // Get params
1547                 $params = func_get_args();
1548                 $output = array();
1549
1550                 foreach ($params as $var)
1551                 {
1552                         $output[] = '<pre>('.gettype($var).') '.html::specialchars(print_r($var, TRUE)).'</pre>';
1553                 }
1554
1555                 return implode("\n", $output);
1556         }
1557
1558         /**
1559          * Displays nice backtrace information.
1560          * @see http://php.net/debug_backtrace
1561          *
1562          * @param   array   backtrace generated by an exception or debug_backtrace
1563          * @return  string
1564          */
1565         public static function backtrace($trace)
1566         {
1567                 if ( ! is_array($trace))
1568                         return;
1569
1570                 // Final output
1571                 $output = array();
1572
1573                 foreach ($trace as $entry)
1574                 {
1575                         $temp = '<li>';
1576
1577                         if (isset($entry['file']))
1578                         {
1579                                 $temp .= self::lang('core.error_file_line', preg_replace('!^'.preg_quote(DOCROOT).'!', '', $entry['file']), $entry['line']);
1580                         }
1581
1582                         $temp .= '<pre>';
1583
1584                         if (isset($entry['class']))
1585                         {
1586                                 // Add class and call type
1587                                 $temp .= $entry['class'].$entry['type'];
1588                         }
1589
1590                         // Add function
1591                         $temp .= $entry['function'].'( ';
1592
1593                         // Add function args
1594                         if (isset($entry['args']) AND is_array($entry['args']))
1595                         {
1596                                 // Separator starts as nothing
1597                                 $sep = '';
1598
1599                                 while ($arg = array_shift($entry['args']))
1600                                 {
1601                                         if (is_string($arg) AND is_file($arg))
1602                                         {
1603                                                 // Remove docroot from filename
1604                                                 $arg = preg_replace('!^'.preg_quote(DOCROOT).'!', '', $arg);
1605                                         }
1606
1607                                         $temp .= $sep.html::specialchars(print_r($arg, TRUE));
1608
1609                                         // Change separator to a comma
1610                                         $sep = ', ';
1611                                 }
1612                         }
1613
1614                         $temp .= ' )</pre></li>';
1615
1616                         $output[] = $temp;
1617                 }
1618
1619                 return '<ul class="backtrace">'.implode("\n", $output).'</ul>';
1620         }
1621
1622         /**
1623          * Saves the internal caches: configuration, include paths, etc.
1624          *
1625          * @return  boolean
1626          */
1627         public static function internal_cache_save()
1628         {
1629                 if ( ! is_array(self::$write_cache))
1630                         return FALSE;
1631
1632                 // Get internal cache names
1633                 $caches = array_keys(self::$write_cache);
1634
1635                 // Nothing written
1636                 $written = FALSE;
1637
1638                 foreach ($caches as $cache)
1639                 {
1640                         if (isset(self::$internal_cache[$cache]))
1641                         {
1642                                 // Write the cache file
1643                                 self::cache_save($cache, self::$internal_cache[$cache], self::$configuration['core']['internal_cache']);
1644
1645                                 // A cache has been written
1646                                 $written = TRUE;
1647                         }
1648                 }
1649
1650                 return $written;
1651         }
1652
1653 } // End Kohana
1654
1655 /**
1656  * Creates a generic i18n exception.
1657  */
1658 class Kohana_Exception extends Exception {
1659
1660         // Template file
1661         protected $template = 'kohana_error_page';
1662
1663         // Header
1664         protected $header = FALSE;
1665
1666         // Error code
1667         protected $code = E_KOHANA;
1668
1669         /**
1670          * Set exception message.
1671          *
1672          * @param  string  i18n language key for the message
1673          * @param  array   addition line parameters
1674          */
1675         public function __construct($error)
1676         {
1677                 $args = array_slice(func_get_args(), 1);
1678
1679                 // Fetch the error message
1680                 $message = Kohana::lang($error, $args);
1681
1682                 if ($message === $error OR empty($message))
1683                 {
1684                         // Unable to locate the message for the error
1685                         $message = 'Unknown Exception: '.$error;
1686                 }
1687
1688                 // Sets $this->message the proper way
1689                 parent::__construct($message);
1690         }
1691
1692         /**
1693          * Magic method for converting an object to a string.
1694          *
1695          * @return  string  i18n message
1696          */
1697         public function __toString()
1698         {
1699                 return (string) $this->message;
1700         }
1701
1702         /**
1703          * Fetch the template name.
1704          *
1705          * @return  string
1706          */
1707         public function getTemplate()
1708         {
1709                 return $this->template;
1710         }
1711
1712         /**
1713          * Sends an Internal Server Error header.
1714          *
1715          * @return  void
1716          */
1717         public function sendHeaders()
1718         {
1719                 // Send the 500 header
1720                 header('HTTP/1.1 500 Internal Server Error');
1721         }
1722
1723 } // End Kohana Exception
1724
1725 /**
1726  * Creates a custom exception.
1727  */
1728 class Kohana_User_Exception extends Kohana_Exception {
1729
1730         /**
1731          * Set exception title and message.
1732          *
1733          * @param   string  exception title string
1734          * @param   string  exception message string
1735          * @param   string  custom error template
1736          */
1737         public function __construct($title, $message, $template = FALSE)
1738         {
1739                 Exception::__construct($message);
1740
1741                 $this->code = $title;
1742
1743                 if ($template !== FALSE)
1744                 {
1745                         $this->template = $template;
1746                 }
1747         }
1748
1749 } // End Kohana PHP Exception
1750
1751 /**
1752  * Creates a Page Not Found exception.
1753  */
1754 class Kohana_404_Exception extends Kohana_Exception {
1755
1756         protected $code = E_PAGE_NOT_FOUND;
1757
1758         /**
1759          * Set internal properties.
1760          *
1761          * @param  string  URL of page
1762          * @param  string  custom error template
1763          */
1764         public function __construct($page = FALSE, $template = FALSE)
1765         {
1766                 if ($page === FALSE)
1767                 {
1768                         // Construct the page URI using Router properties
1769                         $page = Router::$current_uri.Router::$url_suffix.Router::$query_string;
1770                 }
1771
1772                 Exception::__construct(Kohana::lang('core.page_not_found', $page));
1773
1774                 $this->template = $template;
1775         }
1776
1777         /**
1778          * Sends "File Not Found" headers, to emulate server behavior.
1779          *
1780          * @return void
1781          */
1782         public function sendHeaders()
1783         {
1784                 // Send the 404 header
1785                 header('HTTP/1.1 404 File Not Found');
1786         }
1787
1788 } // End Kohana 404 Exception