PageRenderTime 54ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/system/classes/kohana/core.php

https://bitbucket.org/alvinpd/monsterninja
PHP | 1505 lines | 1352 code | 39 blank | 114 comment | 7 complexity | 4503eafec3779de0762dfde1f6adf7de MD5 | raw file
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. /**
  3. * Contains the most low-level helpers methods in Kohana:
  4. *
  5. * - Environment initialization
  6. * - Locating files within the cascading filesystem
  7. * - Auto-loading and transparent extension of classes
  8. * - Variable and path debugging
  9. *
  10. * @package Kohana
  11. * @category Base
  12. * @author Kohana Team
  13. * @copyright (c) 2008-2009 Kohana Team
  14. * @license http://kohanaphp.com/license
  15. */
  16. class Kohana_Core {
  17. // Release version and codename
  18. const VERSION = '3.0.6';
  19. const CODENAME = 'sumar hiti';
  20. // Log message types
  21. const ERROR = 'ERROR';
  22. const DEBUG = 'DEBUG';
  23. const INFO = 'INFO';
  24. // Common environment type constants for consistency and convenience
  25. const PRODUCTION = 'production';
  26. const STAGING = 'staging';
  27. const TESTING = 'testing';
  28. const DEVELOPMENT = 'development';
  29. // Security check that is added to all generated PHP files
  30. const FILE_SECURITY = '<?php defined(\'SYSPATH\') or die(\'No direct script access.\');';
  31. // Format of cache files: header, cache name, and data
  32. const FILE_CACHE = ":header \n\n// :name\n\n:data\n";
  33. /**
  34. * @var array PHP error code => human readable name
  35. */
  36. public static $php_errors = array(
  37. E_ERROR => 'Fatal Error',
  38. E_USER_ERROR => 'User Error',
  39. E_PARSE => 'Parse Error',
  40. E_WARNING => 'Warning',
  41. E_USER_WARNING => 'User Warning',
  42. E_STRICT => 'Strict',
  43. E_NOTICE => 'Notice',
  44. E_RECOVERABLE_ERROR => 'Recoverable Error',
  45. );
  46. /**
  47. * @var string current environment name
  48. */
  49. public static $environment = Kohana::DEVELOPMENT;
  50. /**
  51. * @var boolean command line environment?
  52. */
  53. public static $is_cli = FALSE;
  54. /**
  55. * @var boolean Windows environment?
  56. */
  57. public static $is_windows = FALSE;
  58. /**
  59. * @var boolean magic quotes enabled?
  60. */
  61. public static $magic_quotes = FALSE;
  62. /**
  63. * @var boolean log errors and exceptions?
  64. */
  65. public static $log_errors = FALSE;
  66. /**
  67. * @var string character set of input and output
  68. */
  69. public static $charset = 'utf-8';
  70. /**
  71. * @var string base URL to the application
  72. */
  73. public static $base_url = '/';
  74. /**
  75. * @var string application index file
  76. */
  77. public static $index_file = 'index.php';
  78. /**
  79. * @var string cache directory
  80. */
  81. public static $cache_dir;
  82. /**
  83. * @var boolean enabling internal caching?
  84. */
  85. public static $caching = FALSE;
  86. /**
  87. * @var boolean enable core profiling?
  88. */
  89. public static $profiling = TRUE;
  90. /**
  91. * @var boolean enable error handling?
  92. */
  93. public static $errors = TRUE;
  94. /**
  95. * @var array types of errors to display at shutdown
  96. */
  97. public static $shutdown_errors = array(E_PARSE, E_ERROR, E_USER_ERROR, E_COMPILE_ERROR);
  98. /**
  99. * @var object logging object
  100. */
  101. public static $log;
  102. /**
  103. * @var object config object
  104. */
  105. public static $config;
  106. // Is the environment initialized?
  107. protected static $_init = FALSE;
  108. // Currently active modules
  109. protected static $_modules = array();
  110. // Include paths that are used to find files
  111. protected static $_paths = array(APPPATH, SYSPATH);
  112. // File path cache
  113. protected static $_files = array();
  114. // Has the file cache changed?
  115. protected static $_files_changed = FALSE;
  116. /**
  117. * Initializes the environment:
  118. *
  119. * - Disables register_globals and magic_quotes_gpc
  120. * - Determines the current environment
  121. * - Set global settings
  122. * - Sanitizes GET, POST, and COOKIE variables
  123. * - Converts GET, POST, and COOKIE variables to the global character set
  124. *
  125. * Any of the global settings can be set here:
  126. *
  127. * Type | Setting | Description | Default Value
  128. * ----------|------------|------------------------------------------------|---------------
  129. * `boolean` | errors | use internal error and exception handling? | `TRUE`
  130. * `boolean` | profile | do internal benchmarking? | `TRUE`
  131. * `boolean` | caching | cache the location of files between requests? | `FALSE`
  132. * `string` | charset | character set used for all input and output | `"utf-8"`
  133. * `string` | base_url | set the base URL for the application | `"/"`
  134. * `string` | index_file | set the index.php file name | `"index.php"`
  135. * `string` | cache_dir | set the cache directory path | `APPPATH."cache"`
  136. *
  137. * @throws Kohana_Exception
  138. * @param array global settings
  139. * @return void
  140. * @uses Kohana::globals
  141. * @uses Kohana::sanitize
  142. * @uses Kohana::cache
  143. * @uses Profiler
  144. */
  145. public static function init(array $settings = NULL)
  146. {
  147. if (Kohana::$_init)
  148. {
  149. // Do not allow execution twice
  150. return;
  151. }
  152. // Kohana is now initialized
  153. Kohana::$_init = TRUE;
  154. if (isset($settings['profile']))
  155. {
  156. // Enable profiling
  157. Kohana::$profiling = (bool) $settings['profile'];
  158. }
  159. if (Kohana::$profiling === TRUE)
  160. {
  161. // Start a new benchmark
  162. $benchmark = Profiler::start('Kohana', __FUNCTION__);
  163. }
  164. // Start an output buffer
  165. ob_start();
  166. if (defined('E_DEPRECATED'))
  167. {
  168. // E_DEPRECATED only exists in PHP >= 5.3.0
  169. Kohana::$php_errors[E_DEPRECATED] = 'Deprecated';
  170. }
  171. if (isset($settings['errors']))
  172. {
  173. // Enable error handling
  174. Kohana::$errors = (bool) $settings['errors'];
  175. }
  176. if (Kohana::$errors === TRUE)
  177. {
  178. // Enable Kohana exception handling, adds stack traces and error source.
  179. set_exception_handler(array('Kohana', 'exception_handler'));
  180. // Enable Kohana error handling, converts all PHP errors to exceptions.
  181. set_error_handler(array('Kohana', 'error_handler'));
  182. }
  183. // Enable the Kohana shutdown handler, which catches E_FATAL errors.
  184. register_shutdown_function(array('Kohana', 'shutdown_handler'));
  185. if (ini_get('register_globals'))
  186. {
  187. // Reverse the effects of register_globals
  188. Kohana::globals();
  189. }
  190. // Determine if we are running in a command line environment
  191. Kohana::$is_cli = (PHP_SAPI === 'cli');
  192. // Determine if we are running in a Windows environment
  193. Kohana::$is_windows = (DIRECTORY_SEPARATOR === '\\');
  194. if (isset($settings['cache_dir']))
  195. {
  196. // Set the cache directory path
  197. Kohana::$cache_dir = realpath($settings['cache_dir']);
  198. }
  199. else
  200. {
  201. // Use the default cache directory
  202. Kohana::$cache_dir = APPPATH.'cache';
  203. }
  204. if ( ! is_writable(Kohana::$cache_dir))
  205. {
  206. throw new Kohana_Exception('Directory :dir must be writable',
  207. array(':dir' => Kohana::debug_path(Kohana::$cache_dir)));
  208. }
  209. if (isset($settings['caching']))
  210. {
  211. // Enable or disable internal caching
  212. Kohana::$caching = (bool) $settings['caching'];
  213. }
  214. if (Kohana::$caching === TRUE)
  215. {
  216. // Load the file path cache
  217. Kohana::$_files = Kohana::cache('Kohana::find_file()');
  218. }
  219. if (isset($settings['charset']))
  220. {
  221. // Set the system character set
  222. Kohana::$charset = strtolower($settings['charset']);
  223. }
  224. if (function_exists('mb_internal_encoding'))
  225. {
  226. // Set the MB extension encoding to the same character set
  227. mb_internal_encoding(Kohana::$charset);
  228. }
  229. if (isset($settings['base_url']))
  230. {
  231. // Set the base URL
  232. Kohana::$base_url = rtrim($settings['base_url'], '/').'/';
  233. }
  234. if (isset($settings['index_file']))
  235. {
  236. // Set the index file
  237. Kohana::$index_file = trim($settings['index_file'], '/');
  238. }
  239. // Determine if the extremely evil magic quotes are enabled
  240. Kohana::$magic_quotes = (bool) get_magic_quotes_gpc();
  241. // Sanitize all request variables
  242. $_GET = Kohana::sanitize($_GET);
  243. $_POST = Kohana::sanitize($_POST);
  244. $_COOKIE = Kohana::sanitize($_COOKIE);
  245. // Load the logger
  246. Kohana::$log = Kohana_Log::instance();
  247. // Load the config
  248. Kohana::$config = Kohana_Config::instance();
  249. if (isset($benchmark))
  250. {
  251. // Stop benchmarking
  252. Profiler::stop($benchmark);
  253. }
  254. }
  255. /**
  256. * Cleans up the environment:
  257. *
  258. * - Restore the previous error and exception handlers
  259. * - Destroy the Kohana::$log and Kohana::$config objects
  260. *
  261. * @return void
  262. */
  263. public static function deinit()
  264. {
  265. if (Kohana::$_init)
  266. {
  267. // Removed the autoloader
  268. spl_autoload_unregister(array('Kohana', 'auto_load'));
  269. if (Kohana::$errors)
  270. {
  271. // Go back to the previous error handler
  272. restore_error_handler();
  273. // Go back to the previous exception handler
  274. restore_exception_handler();
  275. }
  276. // Destroy objects created by init
  277. Kohana::$log = Kohana::$config = NULL;
  278. // Reset internal storage
  279. Kohana::$_modules = Kohana::$_files = array();
  280. Kohana::$_paths = array(APPPATH, SYSPATH);
  281. // Reset file cache status
  282. Kohana::$_files_changed = FALSE;
  283. // Kohana is no longer initialized
  284. Kohana::$_init = FALSE;
  285. }
  286. }
  287. /**
  288. * Reverts the effects of the `register_globals` PHP setting by unsetting
  289. * all global varibles except for the default super globals (GPCS, etc).
  290. *
  291. * if (ini_get('register_globals'))
  292. * {
  293. * Kohana::globals();
  294. * }
  295. *
  296. * @return void
  297. */
  298. public static function globals()
  299. {
  300. if (isset($_REQUEST['GLOBALS']) OR isset($_FILES['GLOBALS']))
  301. {
  302. // Prevent malicious GLOBALS overload attack
  303. echo "Global variable overload attack detected! Request aborted.\n";
  304. // Exit with an error status
  305. exit(1);
  306. }
  307. // Get the variable names of all globals
  308. $global_variables = array_keys($GLOBALS);
  309. // Remove the standard global variables from the list
  310. $global_variables = array_diff($global_variables,
  311. array('GLOBALS', '_REQUEST', '_GET', '_POST', '_FILES', '_COOKIE', '_SERVER', '_ENV', '_SESSION'));
  312. foreach ($global_variables as $name)
  313. {
  314. // Retrieve the global variable and make it null
  315. global $$name;
  316. $$name = NULL;
  317. // Unset the global variable, effectively disabling register_globals
  318. unset($GLOBALS[$name], $$name);
  319. }
  320. }
  321. /**
  322. * Recursively sanitizes an input variable:
  323. *
  324. * - Strips slashes if magic quotes are enabled
  325. * - Normalizes all newlines to LF
  326. *
  327. * @param mixed any variable
  328. * @return mixed sanitized variable
  329. */
  330. public static function sanitize($value)
  331. {
  332. if (is_array($value) OR is_object($value))
  333. {
  334. foreach ($value as $key => $val)
  335. {
  336. // Recursively clean each value
  337. $value[$key] = Kohana::sanitize($val);
  338. }
  339. }
  340. elseif (is_string($value))
  341. {
  342. if (Kohana::$magic_quotes === TRUE)
  343. {
  344. // Remove slashes added by magic quotes
  345. $value = stripslashes($value);
  346. }
  347. if (strpos($value, "\r") !== FALSE)
  348. {
  349. // Standardize newlines
  350. $value = str_replace(array("\r\n", "\r"), "\n", $value);
  351. }
  352. }
  353. return $value;
  354. }
  355. /**
  356. * Provides auto-loading support of Kohana classes, as well as transparent
  357. * extension of classes that have a _Core suffix.
  358. *
  359. * Class names are converted to file names by making the class name
  360. * lowercase and converting underscores to slashes:
  361. *
  362. * // Loads classes/my/class/name.php
  363. * Kohana::auto_load('My_Class_Name');
  364. *
  365. * @param string class name
  366. * @return boolean
  367. */
  368. public static function auto_load($class)
  369. {
  370. // Transform the class name into a path
  371. $file = str_replace('_', '/', strtolower($class));
  372. if ($path = Kohana::find_file('classes', $file))
  373. {
  374. // Load the class file
  375. require $path;
  376. // Class has been found
  377. return TRUE;
  378. }
  379. // Class is not in the filesystem
  380. return FALSE;
  381. }
  382. /**
  383. * Changes the currently enabled modules. Module paths may be relative
  384. * or absolute, but must point to a directory:
  385. *
  386. * Kohana::modules(array('modules/foo', MODPATH.'bar'));
  387. *
  388. * @param array list of module paths
  389. * @return array enabled modules
  390. */
  391. public static function modules(array $modules = NULL)
  392. {
  393. if ($modules === NULL)
  394. return Kohana::$_modules;
  395. if (Kohana::$profiling === TRUE)
  396. {
  397. // Start a new benchmark
  398. $benchmark = Profiler::start('Kohana', __FUNCTION__);
  399. }
  400. // Start a new list of include paths, APPPATH first
  401. $paths = array(APPPATH);
  402. foreach ($modules as $name => $path)
  403. {
  404. if (is_dir($path))
  405. {
  406. // Add the module to include paths
  407. $paths[] = $modules[$name] = realpath($path).DIRECTORY_SEPARATOR;
  408. }
  409. else
  410. {
  411. // This module is invalid, remove it
  412. unset($modules[$name]);
  413. }
  414. }
  415. // Finish the include paths by adding SYSPATH
  416. $paths[] = SYSPATH;
  417. // Set the new include paths
  418. Kohana::$_paths = $paths;
  419. // Set the current module list
  420. Kohana::$_modules = $modules;
  421. foreach (Kohana::$_modules as $path)
  422. {
  423. $init = $path.'init'.EXT;
  424. if (is_file($init))
  425. {
  426. // Include the module initialization file once
  427. require_once $init;
  428. }
  429. }
  430. if (isset($benchmark))
  431. {
  432. // Stop the benchmark
  433. Profiler::stop($benchmark);
  434. }
  435. return Kohana::$_modules;
  436. }
  437. /**
  438. * Returns the the currently active include paths, including the
  439. * application and system paths.
  440. *
  441. * @return array
  442. */
  443. public static function include_paths()
  444. {
  445. return Kohana::$_paths;
  446. }
  447. /**
  448. * Finds the path of a file by directory, filename, and extension.
  449. * If no extension is given, the default EXT extension will be used.
  450. *
  451. * When searching the "config" or "i18n" directories, or when the
  452. * $aggregate_files flag is set to true, an array of files
  453. * will be returned. These files will return arrays which must be
  454. * merged together.
  455. *
  456. * // Returns an absolute path to views/template.php
  457. * Kohana::find_file('views', 'template');
  458. *
  459. * // Returns an absolute path to media/css/style.css
  460. * Kohana::find_file('media', 'css/style', 'css');
  461. *
  462. * // Returns an array of all the "mimes" configuration file
  463. * Kohana::find_file('config', 'mimes');
  464. *
  465. * @param string directory name (views, i18n, classes, extensions, etc.)
  466. * @param string filename with subdirectory
  467. * @param string extension to search for
  468. * @param boolean return an array of files?
  469. * @return array a list of files when $array is TRUE
  470. * @return string single file path
  471. */
  472. public static function find_file($dir, $file, $ext = NULL, $array = FALSE)
  473. {
  474. // Use the defined extension by default
  475. $ext = ($ext === NULL) ? EXT : '.'.$ext;
  476. // Create a partial path of the filename
  477. $path = $dir.DIRECTORY_SEPARATOR.$file.$ext;
  478. if (Kohana::$caching === TRUE AND isset(Kohana::$_files[$path]))
  479. {
  480. // This path has been cached
  481. return Kohana::$_files[$path];
  482. }
  483. if (Kohana::$profiling === TRUE AND class_exists('Profiler', FALSE))
  484. {
  485. // Start a new benchmark
  486. $benchmark = Profiler::start('Kohana', __FUNCTION__);
  487. }
  488. if ($array OR $dir === 'config' OR $dir === 'i18n' OR $dir === 'messages')
  489. {
  490. // Include paths must be searched in reverse
  491. $paths = array_reverse(Kohana::$_paths);
  492. // Array of files that have been found
  493. $found = array();
  494. foreach ($paths as $dir)
  495. {
  496. if (is_file($dir.$path))
  497. {
  498. // This path has a file, add it to the list
  499. $found[] = $dir.$path;
  500. }
  501. }
  502. }
  503. else
  504. {
  505. // The file has not been found yet
  506. $found = FALSE;
  507. foreach (Kohana::$_paths as $dir)
  508. {
  509. if (is_file($dir.$path))
  510. {
  511. // A path has been found
  512. $found = $dir.$path;
  513. // Stop searching
  514. break;
  515. }
  516. }
  517. }
  518. if (Kohana::$caching === TRUE)
  519. {
  520. // Add the path to the cache
  521. Kohana::$_files[$path] = $found;
  522. // Files have been changed
  523. Kohana::$_files_changed = TRUE;
  524. }
  525. if (isset($benchmark))
  526. {
  527. // Stop the benchmark
  528. Profiler::stop($benchmark);
  529. }
  530. return $found;
  531. }
  532. /**
  533. * Recursively finds all of the files in the specified directory.
  534. *
  535. * $views = Kohana::list_files('views');
  536. *
  537. * @param string directory name
  538. * @param array list of paths to search
  539. * @return array
  540. */
  541. public static function list_files($directory = NULL, array $paths = NULL)
  542. {
  543. if ($directory !== NULL)
  544. {
  545. // Add the directory separator
  546. $directory .= DIRECTORY_SEPARATOR;
  547. }
  548. if ($paths === NULL)
  549. {
  550. // Use the default paths
  551. $paths = Kohana::$_paths;
  552. }
  553. // Create an array for the files
  554. $found = array();
  555. foreach ($paths as $path)
  556. {
  557. if (is_dir($path.$directory))
  558. {
  559. // Create a new directory iterator
  560. $dir = new DirectoryIterator($path.$directory);
  561. foreach ($dir as $file)
  562. {
  563. // Get the file name
  564. $filename = $file->getFilename();
  565. if ($filename[0] === '.' OR $filename[strlen($filename)-1] === '~')
  566. {
  567. // Skip all hidden files and UNIX backup files
  568. continue;
  569. }
  570. // Relative filename is the array key
  571. $key = $directory.$filename;
  572. if ($file->isDir())
  573. {
  574. if ($sub_dir = Kohana::list_files($key, $paths))
  575. {
  576. if (isset($found[$key]))
  577. {
  578. // Append the sub-directory list
  579. $found[$key] += $sub_dir;
  580. }
  581. else
  582. {
  583. // Create a new sub-directory list
  584. $found[$key] = $sub_dir;
  585. }
  586. }
  587. }
  588. else
  589. {
  590. if ( ! isset($found[$key]))
  591. {
  592. // Add new files to the list
  593. $found[$key] = realpath($file->getPathName());
  594. }
  595. }
  596. }
  597. }
  598. }
  599. // Sort the results alphabetically
  600. ksort($found);
  601. return $found;
  602. }
  603. /**
  604. * Loads a file within a totally empty scope and returns the output:
  605. *
  606. * $foo = Kohana::load('foo.php');
  607. *
  608. * @param string
  609. * @return mixed
  610. */
  611. public static function load($file)
  612. {
  613. return include $file;
  614. }
  615. /**
  616. * Creates a new configuration object for the requested group.
  617. *
  618. * @param string group name
  619. * @return Kohana_Config
  620. */
  621. public static function config($group)
  622. {
  623. static $config;
  624. if (strpos($group, '.') !== FALSE)
  625. {
  626. // Split the config group and path
  627. list ($group, $path) = explode('.', $group, 2);
  628. }
  629. if ( ! isset($config[$group]))
  630. {
  631. // Load the config group into the cache
  632. $config[$group] = Kohana::$config->load($group);
  633. }
  634. if (isset($path))
  635. {
  636. return Arr::path($config[$group], $path);
  637. }
  638. else
  639. {
  640. return $config[$group];
  641. }
  642. }
  643. /**
  644. * Provides simple file-based caching for strings and arrays:
  645. *
  646. * // Set the "foo" cache
  647. * Kohana::cache('foo', 'hello, world');
  648. *
  649. * // Get the "foo" cache
  650. * $foo = Kohana::cache('foo');
  651. *
  652. * All caches are stored as PHP code, generated with [var_export][ref-var].
  653. * Caching objects may not work as expected. Storing references or an
  654. * object or array that has recursion will cause an E_FATAL.
  655. *
  656. * [ref-var]: http://php.net/var_export
  657. *
  658. * @throws Kohana_Exception
  659. * @param string name of the cache
  660. * @param mixed data to cache
  661. * @param integer number of seconds the cache is valid for
  662. * @return mixed for getting
  663. * @return boolean for setting
  664. */
  665. public static function cache($name, $data = NULL, $lifetime = 60)
  666. {
  667. // Cache file is a hash of the name
  668. $file = sha1($name).'.txt';
  669. // Cache directories are split by keys to prevent filesystem overload
  670. $dir = Kohana::$cache_dir.DIRECTORY_SEPARATOR.$file[0].$file[1].DIRECTORY_SEPARATOR;
  671. try
  672. {
  673. if ($data === NULL)
  674. {
  675. if (is_file($dir.$file))
  676. {
  677. if ((time() - filemtime($dir.$file)) < $lifetime)
  678. {
  679. // Return the cache
  680. return unserialize(file_get_contents($dir.$file));
  681. }
  682. else
  683. {
  684. try
  685. {
  686. // Cache has expired
  687. unlink($dir.$file);
  688. }
  689. catch (Exception $e)
  690. {
  691. // Cache has already been deleted
  692. return NULL;
  693. }
  694. }
  695. }
  696. // Cache not found
  697. return NULL;
  698. }
  699. if ( ! is_dir($dir))
  700. {
  701. // Create the cache directory
  702. mkdir($dir, 0777, TRUE);
  703. // Set permissions (must be manually set to fix umask issues)
  704. chmod($dir, 0777);
  705. }
  706. // Write the cache
  707. return (bool) file_put_contents($dir.$file, serialize($data));
  708. }
  709. catch (Exception $e)
  710. {
  711. throw $e;
  712. }
  713. }
  714. /**
  715. * Get a message from a file. Messages are arbitary strings that are stored
  716. * in the messages/ directory and reference by a key. Translation is not
  717. * performed on the returned values.
  718. *
  719. * // Get "username" from messages/text.php
  720. * $username = Kohana::message('text', 'username');
  721. *
  722. * @param string file name
  723. * @param string key path to get
  724. * @param mixed default value if the path does not exist
  725. * @return string message string for the given path
  726. * @return array complete message list, when no path is specified
  727. * @uses Arr::merge
  728. * @uses Arr::path
  729. */
  730. public static function message($file, $path = NULL, $default = NULL)
  731. {
  732. static $messages;
  733. if ( ! isset($messages[$file]))
  734. {
  735. // Create a new message list
  736. $messages[$file] = array();
  737. if ($files = Kohana::find_file('messages', $file))
  738. {
  739. foreach ($files as $f)
  740. {
  741. // Combine all the messages recursively
  742. $messages[$file] = Arr::merge($messages[$file], Kohana::load($f));
  743. }
  744. }
  745. }
  746. if ($path === NULL)
  747. {
  748. // Return all of the messages
  749. return $messages[$file];
  750. }
  751. else
  752. {
  753. // Get a message using the path
  754. return Arr::path($messages[$file], $path, $default);
  755. }
  756. }
  757. /**
  758. * PHP error handler, converts all errors into ErrorExceptions. This handler
  759. * respects error_reporting settings.
  760. *
  761. * @throws ErrorException
  762. * @return TRUE
  763. */
  764. public static function error_handler($code, $error, $file = NULL, $line = NULL)
  765. {
  766. if (error_reporting() & $code)
  767. {
  768. // This error is not suppressed by current error reporting settings
  769. // Convert the error into an ErrorException
  770. throw new ErrorException($error, $code, 0, $file, $line);
  771. }
  772. // Do not execute the PHP error handler
  773. return TRUE;
  774. }
  775. /**
  776. * Inline exception handler, displays the error message, source of the
  777. * exception, and the stack trace of the error.
  778. *
  779. * @uses Kohana::exception_text
  780. * @param object exception object
  781. * @return boolean
  782. */
  783. public static function exception_handler(Exception $e)
  784. {
  785. try
  786. {
  787. // Get the exception information
  788. $type = get_class($e);
  789. $code = $e->getCode();
  790. $message = $e->getMessage();
  791. $file = $e->getFile();
  792. $line = $e->getLine();
  793. // Create a text version of the exception
  794. $error = Kohana::exception_text($e);
  795. if (is_object(Kohana::$log))
  796. {
  797. // Add this exception to the log
  798. Kohana::$log->add(Kohana::ERROR, $error);
  799. // Make sure the logs are written
  800. Kohana::$log->write();
  801. }
  802. if (Kohana::$is_cli)
  803. {
  804. // Just display the text of the exception
  805. echo "\n{$error}\n";
  806. return TRUE;
  807. }
  808. // Get the exception backtrace
  809. $trace = $e->getTrace();
  810. if ($e instanceof ErrorException)
  811. {
  812. if (isset(Kohana::$php_errors[$code]))
  813. {
  814. // Use the human-readable error name
  815. $code = Kohana::$php_errors[$code];
  816. }
  817. if (version_compare(PHP_VERSION, '5.3', '<'))
  818. {
  819. // Workaround for a bug in ErrorException::getTrace() that exists in
  820. // all PHP 5.2 versions. @see http://bugs.php.net/bug.php?id=45895
  821. for ($i = count($trace) - 1; $i > 0; --$i)
  822. {
  823. if (isset($trace[$i - 1]['args']))
  824. {
  825. // Re-position the args
  826. $trace[$i]['args'] = $trace[$i - 1]['args'];
  827. // Remove the args
  828. unset($trace[$i - 1]['args']);
  829. }
  830. }
  831. }
  832. }
  833. if ( ! headers_sent())
  834. {
  835. // Make sure the proper content type is sent with a 500 status
  836. header('Content-Type: text/html; charset='.Kohana::$charset, TRUE, 500);
  837. }
  838. // Start an output buffer
  839. ob_start();
  840. // Include the exception HTML
  841. include Kohana::find_file('views', 'kohana/error');
  842. // Display the contents of the output buffer
  843. echo ob_get_clean();
  844. return TRUE;
  845. }
  846. catch (Exception $e)
  847. {
  848. // Clean the output buffer if one exists
  849. ob_get_level() and ob_clean();
  850. // Display the exception text
  851. echo Kohana::exception_text($e), "\n";
  852. // Exit with an error status
  853. exit(1);
  854. }
  855. }
  856. /**
  857. * Catches errors that are not caught by the error handler, such as E_PARSE.
  858. *
  859. * @uses Kohana::exception_handler
  860. * @return void
  861. */
  862. public static function shutdown_handler()
  863. {
  864. if ( ! Kohana::$_init)
  865. {
  866. // Do not execute when not active
  867. return;
  868. }
  869. try
  870. {
  871. if (Kohana::$caching === TRUE AND Kohana::$_files_changed === TRUE)
  872. {
  873. // Write the file path cache
  874. Kohana::cache('Kohana::find_file()', Kohana::$_files);
  875. }
  876. }
  877. catch (Exception $e)
  878. {
  879. // Pass the exception to the handler
  880. Kohana::exception_handler($e);
  881. }
  882. if (Kohana::$errors AND $error = error_get_last() AND in_array($error['type'], Kohana::$shutdown_errors))
  883. {
  884. // Clean the output buffer
  885. ob_get_level() and ob_clean();
  886. // Fake an exception for nice debugging
  887. Kohana::exception_handler(new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']));
  888. // Shutdown now to avoid a "death loop"
  889. exit(1);
  890. }
  891. }
  892. /**
  893. * Get a single line of text representing the exception:
  894. *
  895. * Error [ Code ]: Message ~ File [ Line ]
  896. *
  897. * @param object Exception
  898. * @return string
  899. */
  900. public static function exception_text(Exception $e)
  901. {
  902. return sprintf('%s [ %s ]: %s ~ %s [ %d ]',
  903. get_class($e), $e->getCode(), strip_tags($e->getMessage()), Kohana::debug_path($e->getFile()), $e->getLine());
  904. }
  905. /**
  906. * Returns an HTML string of debugging information about any number of
  907. * variables, each wrapped in a "pre" tag:
  908. *
  909. * // Displays the type and value of each variable
  910. * echo Kohana::debug($foo, $bar, $baz);
  911. *
  912. * @param mixed variable to debug
  913. * @param ...
  914. * @return string
  915. */
  916. public static function debug()
  917. {
  918. if (func_num_args() === 0)
  919. return;
  920. // Get all passed variables
  921. $variables = func_get_args();
  922. $output = array();
  923. foreach ($variables as $var)
  924. {
  925. $output[] = Kohana::_dump($var, 1024);
  926. }
  927. return '<pre class="debug">'.implode("\n", $output).'</pre>';
  928. }
  929. /**
  930. * Returns an HTML string of information about a single variable.
  931. *
  932. * Borrows heavily on concepts from the Debug class of [Nette](http://nettephp.com/).
  933. *
  934. * @param mixed variable to dump
  935. * @param integer maximum length of strings
  936. * @return string
  937. */
  938. public static function dump($value, $length = 128)
  939. {
  940. return Kohana::_dump($value, $length);
  941. }
  942. /**
  943. * Helper for Kohana::dump(), handles recursion in arrays and objects.
  944. *
  945. * @param mixed variable to dump
  946. * @param integer maximum length of strings
  947. * @param integer recursion level (internal)
  948. * @return string
  949. */
  950. protected static function _dump( & $var, $length = 128, $level = 0)
  951. {
  952. if ($var === NULL)
  953. {
  954. return '<small>NULL</small>';
  955. }
  956. elseif (is_bool($var))
  957. {
  958. return '<small>bool</small> '.($var ? 'TRUE' : 'FALSE');
  959. }
  960. elseif (is_float($var))
  961. {
  962. return '<small>float</small> '.$var;
  963. }
  964. elseif (is_resource($var))
  965. {
  966. if (($type = get_resource_type($var)) === 'stream' AND $meta = stream_get_meta_data($var))
  967. {
  968. $meta = stream_get_meta_data($var);
  969. if (isset($meta['uri']))
  970. {
  971. $file = $meta['uri'];
  972. if (function_exists('stream_is_local'))
  973. {
  974. // Only exists on PHP >= 5.2.4
  975. if (stream_is_local($file))
  976. {
  977. $file = Kohana::debug_path($file);
  978. }
  979. }
  980. return '<small>resource</small><span>('.$type.')</span> '.htmlspecialchars($file, ENT_NOQUOTES, Kohana::$charset);
  981. }
  982. }
  983. else
  984. {
  985. return '<small>resource</small><span>('.$type.')</span>';
  986. }
  987. }
  988. elseif (is_string($var))
  989. {
  990. if (UTF8::strlen($var) > $length)
  991. {
  992. // Encode the truncated string
  993. $str = htmlspecialchars(UTF8::substr($var, 0, $length), ENT_NOQUOTES, Kohana::$charset).'&nbsp;&hellip;';
  994. }
  995. else
  996. {
  997. // Encode the string
  998. $str = htmlspecialchars($var, ENT_NOQUOTES, Kohana::$charset);
  999. }
  1000. return '<small>string</small><span>('.strlen($var).')</span> "'.$str.'"';
  1001. }
  1002. elseif (is_array($var))
  1003. {
  1004. $output = array();
  1005. // Indentation for this variable
  1006. $space = str_repeat($s = ' ', $level);
  1007. static $marker;
  1008. if ($marker === NULL)
  1009. {
  1010. // Make a unique marker
  1011. $marker = uniqid("\x00");
  1012. }
  1013. if (empty($var))
  1014. {
  1015. // Do nothing
  1016. }
  1017. elseif (isset($var[$marker]))
  1018. {
  1019. $output[] = "(\n$space$s*RECURSION*\n$space)";
  1020. }
  1021. elseif ($level < 5)
  1022. {
  1023. $output[] = "<span>(";
  1024. $var[$marker] = TRUE;
  1025. foreach ($var as $key => & $val)
  1026. {
  1027. if ($key === $marker) continue;
  1028. if ( ! is_int($key))
  1029. {
  1030. $key = '"'.htmlspecialchars($key, ENT_NOQUOTES, self::$charset).'"';
  1031. }
  1032. $output[] = "$space$s$key => ".Kohana::_dump($val, $length, $level + 1);
  1033. }
  1034. unset($var[$marker]);
  1035. $output[] = "$space)</span>";
  1036. }
  1037. else
  1038. {
  1039. // Depth too great
  1040. $output[] = "(\n$space$s...\n$space)";
  1041. }
  1042. return '<small>array</small><span>('.count($var).')</span> '.implode("\n", $output);
  1043. }
  1044. elseif (is_object($var))
  1045. {
  1046. // Copy the object as an array
  1047. $array = (array) $var;
  1048. $output = array();
  1049. // Indentation for this variable
  1050. $space = str_repeat($s = ' ', $level);
  1051. $hash = spl_object_hash($var);
  1052. // Objects that are being dumped
  1053. static $objects = array();
  1054. if (empty($var))
  1055. {
  1056. // Do nothing
  1057. }
  1058. elseif (isset($objects[$hash]))
  1059. {
  1060. $output[] = "{\n$space$s*RECURSION*\n$space}";
  1061. }
  1062. elseif ($level < 10)
  1063. {
  1064. $output[] = "<code>{";
  1065. $objects[$hash] = TRUE;
  1066. foreach ($array as $key => & $val)
  1067. {
  1068. if ($key[0] === "\x00")
  1069. {
  1070. // Determine if the access is protected or protected
  1071. $access = '<small>'.($key[1] === '*' ? 'protected' : 'private').'</small>';
  1072. // Remove the access level from the variable name
  1073. $key = substr($key, strrpos($key, "\x00") + 1);
  1074. }
  1075. else
  1076. {
  1077. $access = '<small>public</small>';
  1078. }
  1079. $output[] = "$space$s$access $key => ".Kohana::_dump($val, $length, $level + 1);
  1080. }
  1081. unset($objects[$hash]);
  1082. $output[] = "$space}</code>";
  1083. }
  1084. else
  1085. {
  1086. // Depth too great
  1087. $output[] = "{\n$space$s...\n$space}";
  1088. }
  1089. return '<small>object</small> <span>'.get_class($var).'('.count($array).')</span> '.implode("\n", $output);
  1090. }
  1091. else
  1092. {
  1093. return '<small>'.gettype($var).'</small> '.htmlspecialchars(print_r($var, TRUE), ENT_NOQUOTES, Kohana::$charset);
  1094. }
  1095. }
  1096. /**
  1097. * Removes application, system, modpath, or docroot from a filename,
  1098. * replacing them with the plain text equivalents. Useful for debugging
  1099. * when you want to display a shorter path.
  1100. *
  1101. * // Displays SYSPATH/classes/kohana.php
  1102. * echo Kohana::debug_path(Kohana::find_file('classes', 'kohana'));
  1103. *
  1104. * @param string path to debug
  1105. * @return string
  1106. */
  1107. public static function debug_path($file)
  1108. {
  1109. if (strpos($file, APPPATH) === 0)
  1110. {
  1111. $file = 'APPPATH/'.substr($file, strlen(APPPATH));
  1112. }
  1113. elseif (strpos($file, SYSPATH) === 0)
  1114. {
  1115. $file = 'SYSPATH/'.substr($file, strlen(SYSPATH));
  1116. }
  1117. elseif (strpos($file, MODPATH) === 0)
  1118. {
  1119. $file = 'MODPATH/'.substr($file, strlen(MODPATH));
  1120. }
  1121. elseif (strpos($file, DOCROOT) === 0)
  1122. {
  1123. $file = 'DOCROOT/'.substr($file, strlen(DOCROOT));
  1124. }
  1125. return $file;
  1126. }
  1127. /**
  1128. * Returns an HTML string, highlighting a specific line of a file, with some
  1129. * number of lines padded above and below.
  1130. *
  1131. * // Highlights the current line of the current file
  1132. * echo Kohana::debug_source(__FILE__, __LINE__);
  1133. *
  1134. * @param string file to open
  1135. * @param integer line number to highlight
  1136. * @param integer number of padding lines
  1137. * @return string source of file
  1138. * @return FALSE file is unreadable
  1139. */
  1140. public static function debug_source($file, $line_number, $padding = 5)
  1141. {
  1142. if ( ! $file OR ! is_readable($file))
  1143. {
  1144. // Continuing will cause errors
  1145. return FALSE;
  1146. }
  1147. // Open the file and set the line position
  1148. $file = fopen($file, 'r');
  1149. $line = 0;
  1150. // Set the reading range
  1151. $range = array('start' => $line_number - $padding, 'end' => $line_number + $padding);
  1152. // Set the zero-padding amount for line numbers
  1153. $format = '% '.strlen($range['end']).'d';
  1154. $source = '';
  1155. while (($row = fgets($file)) !== FALSE)
  1156. {
  1157. // Increment the line number
  1158. if (++$line > $range['end'])
  1159. break;
  1160. if ($line >= $range['start'])
  1161. {
  1162. // Make the row safe for output
  1163. $row = htmlspecialchars($row, ENT_NOQUOTES, Kohana::$charset);
  1164. // Trim whitespace and sanitize the row
  1165. $row = '<span class="number">'.sprintf($format, $line).'</span> '.$row;
  1166. if ($line === $line_number)
  1167. {
  1168. // Apply highlighting to this row
  1169. $row = '<span class="line highlight">'.$row.'</span>';
  1170. }
  1171. else
  1172. {
  1173. $row = '<span class="line">'.$row.'</span>';
  1174. }
  1175. // Add to the captured source
  1176. $source .= $row;
  1177. }
  1178. }
  1179. // Close the file
  1180. fclose($file);
  1181. return '<pre class="source"><code>'.$source.'</code></pre>';
  1182. }
  1183. /**
  1184. * Returns an array of HTML strings that represent each step in the backtrace.
  1185. *
  1186. * // Displays the entire current backtrace
  1187. * echo implode('<br/>', Kohana::trace());
  1188. *
  1189. * @param string path to debug
  1190. * @return string
  1191. */
  1192. public static function trace(array $trace = NULL)
  1193. {
  1194. if ($trace === NULL)
  1195. {
  1196. // Start a new trace
  1197. $trace = debug_backtrace();
  1198. }
  1199. // Non-standard function calls
  1200. $statements = array('include', 'include_once', 'require', 'require_once');
  1201. $output = array();
  1202. foreach ($trace as $step)
  1203. {
  1204. if ( ! isset($step['function']))
  1205. {
  1206. // Invalid trace step
  1207. continue;
  1208. }
  1209. if (isset($step['file']) AND isset($step['line']))
  1210. {
  1211. // Include the source of this step
  1212. $source = Kohana::debug_source($step['file'], $step['line']);
  1213. }
  1214. if (isset($step['file']))
  1215. {
  1216. $file = $step['file'];
  1217. if (isset($step['line']))
  1218. {
  1219. $line = $step['line'];
  1220. }
  1221. }
  1222. // function()
  1223. $function = $step['function'];
  1224. if (in_array($step['function'], $statements))
  1225. {
  1226. if (empty($step['args']))
  1227. {
  1228. // No arguments
  1229. $args = array();
  1230. }
  1231. else
  1232. {
  1233. // Sanitize the file path
  1234. $args = array($step['args'][0]);
  1235. }
  1236. }
  1237. elseif (isset($step['args']))
  1238. {
  1239. if (strpos($step['function'], '{closure}') !== FALSE)
  1240. {
  1241. // Introspection on closures in a stack trace is impossible
  1242. $params = NULL;
  1243. }
  1244. else
  1245. {
  1246. if (isset($step['class']))
  1247. {
  1248. if (method_exists($step['class'], $step['function']))
  1249. {
  1250. $reflection = new ReflectionMethod($step['class'], $step['function']);
  1251. }
  1252. else
  1253. {
  1254. $reflection = new ReflectionMethod($step['class'], '__call');
  1255. }
  1256. }
  1257. else
  1258. {
  1259. $reflection = new ReflectionFunction($step['function']);
  1260. }
  1261. // Get the function parameters
  1262. $params = $reflection->getParameters();
  1263. }
  1264. $args = array();
  1265. foreach ($step['args'] as $i => $arg)
  1266. {
  1267. if (isset($params[$i]))
  1268. {
  1269. // Assign the argument by the parameter name
  1270. $args[$params[$i]->name] = $arg;
  1271. }
  1272. else
  1273. {
  1274. // Assign the argument by number
  1275. $args[$i] = $arg;
  1276. }
  1277. }
  1278. }
  1279. if (isset($step['class']))
  1280. {
  1281. // Class->method() or Class::method()
  1282. $function = $step['class'].$step['type'].$step['function'];
  1283. }
  1284. $output[] = array(
  1285. 'function' => $function,
  1286. 'args' => isset($args) ? $args : NULL,
  1287. 'file' => isset($file) ? $file : NULL,
  1288. 'line' => isset($line) ? $line : NULL,
  1289. 'source' => isset($source) ? $source : NULL,
  1290. );
  1291. unset($function, $args, $file, $line, $source);
  1292. }
  1293. return $output;
  1294. }
  1295. private function __construct()
  1296. {
  1297. // This is a static class
  1298. }
  1299. } // End Kohana