Core.php 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. <?php
  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) Kohana Team
  14. * @license https://koseven.ga/LICENSE.md
  15. */
  16. class Kohana_Core {
  17. // Release version and codename
  18. const VERSION = '3.3.9';
  19. const CODENAME = 'karlsruhe';
  20. // Common environment type constants for consistency and convenience
  21. const PRODUCTION = 10;
  22. const STAGING = 20;
  23. const TESTING = 30;
  24. const DEVELOPMENT = 40;
  25. // Format of cache files: header, cache name, and data
  26. const FILE_CACHE = ":header \n\n// :name\n\n:data\n";
  27. /**
  28. * @var string Current environment name
  29. */
  30. public static $environment = Kohana::DEVELOPMENT;
  31. /**
  32. * @var boolean True if Kohana is running on windows
  33. */
  34. public static $is_windows = FALSE;
  35. /**
  36. * @var string
  37. */
  38. public static $content_type = 'text/html';
  39. /**
  40. * @var string character set of input and output
  41. */
  42. public static $charset = 'utf-8';
  43. /**
  44. * @var string the name of the server Kohana is hosted upon
  45. */
  46. public static $server_name = '';
  47. /**
  48. * @var array list of valid host names for this instance
  49. */
  50. public static $hostnames = [];
  51. /**
  52. * @var string base URL to the application
  53. */
  54. public static $base_url = '/';
  55. /**
  56. * @var string Application index file, added to links generated by Kohana. Set by [Kohana::init]
  57. */
  58. public static $index_file = 'index.php';
  59. /**
  60. * @var string Cache directory, used by [Kohana::cache]. Set by [Kohana::init]
  61. */
  62. public static $cache_dir;
  63. /**
  64. * @var integer Default lifetime for caching, in seconds, used by [Kohana::cache]. Set by [Kohana::init]
  65. */
  66. public static $cache_life = 60;
  67. /**
  68. * @var boolean Whether to use internal caching for [Kohana::find_file], does not apply to [Kohana::cache]. Set by [Kohana::init]
  69. */
  70. public static $caching = FALSE;
  71. /**
  72. * @var boolean Whether to enable [profiling](kohana/profiling). Set by [Kohana::init]
  73. */
  74. public static $profiling = TRUE;
  75. /**
  76. * @var boolean Enable Kohana catching and displaying PHP errors and exceptions. Set by [Kohana::init]
  77. */
  78. public static $errors = TRUE;
  79. /**
  80. * @var array Types of errors to display at shutdown
  81. */
  82. public static $shutdown_errors = [E_PARSE, E_ERROR, E_USER_ERROR];
  83. /**
  84. * @var boolean set the X-Powered-By header
  85. */
  86. public static $expose = FALSE;
  87. /**
  88. * @var Log logging object
  89. */
  90. public static $log;
  91. /**
  92. * @var Config config object
  93. */
  94. public static $config;
  95. /**
  96. * @var boolean Has [Kohana::init] been called?
  97. */
  98. protected static $_init = FALSE;
  99. /**
  100. * @var array Currently active modules
  101. */
  102. protected static $_modules = [];
  103. /**
  104. * @var array Include paths that are used to find files
  105. */
  106. protected static $_paths = [APPPATH, SYSPATH];
  107. /**
  108. * @var array File path cache, used when caching is true in [Kohana::init]
  109. */
  110. protected static $_files = [];
  111. /**
  112. * @var boolean Has the file path cache changed during this execution? Used internally when when caching is true in [Kohana::init]
  113. */
  114. protected static $_files_changed = FALSE;
  115. /**
  116. * Initializes the environment:
  117. *
  118. * - Determines the current environment
  119. * - Set global settings
  120. * - Sanitizes GET, POST, and COOKIE variables
  121. * - Converts GET, POST, and COOKIE variables to the global character set
  122. *
  123. * The following settings can be set:
  124. *
  125. * Type | Setting | Description | Default Value
  126. * ----------|------------|------------------------------------------------|---------------
  127. * `string` | base_url | The base URL for your application. This should be the *relative* path from your DOCROOT to your `index.php` file, in other words, if Kohana is in a subfolder, set this to the subfolder name, otherwise leave it as the default. **The leading slash is required**, trailing slash is optional. | `"/"`
  128. * `string` | index_file | The name of the [front controller](http://en.wikipedia.org/wiki/Front_Controller_pattern). This is used by Kohana to generate relative urls like [HTML::anchor()] and [URL::base()]. This is usually `index.php`. To [remove index.php from your urls](tutorials/clean-urls), set this to `FALSE`. | `"index.php"`
  129. * `string` | charset | Character set used for all input and output | `"utf-8"`
  130. * `string` | cache_dir | Kohana's cache directory. Used by [Kohana::cache] for simple internal caching, like [Fragments](kohana/fragments) and **\[caching database queries](this should link somewhere)**. This has nothing to do with the [Cache module](cache). | `APPPATH."cache"`
  131. * `integer` | cache_life | Lifetime, in seconds, of items cached by [Kohana::cache] | `60`
  132. * `boolean` | errors | Should Kohana catch PHP errors and uncaught Exceptions and show the `error_view`. See [Error Handling](kohana/errors) for more info. <br /> <br /> Recommended setting: `TRUE` while developing, `FALSE` on production servers. | `TRUE`
  133. * `boolean` | profile | Whether to enable the [Profiler](kohana/profiling). <br /> <br />Recommended setting: `TRUE` while developing, `FALSE` on production servers. | `TRUE`
  134. * `boolean` | caching | Cache file locations to speed up [Kohana::find_file]. This has nothing to do with [Kohana::cache], [Fragments](kohana/fragments) or the [Cache module](cache). <br /> <br /> Recommended setting: `FALSE` while developing, `TRUE` on production servers. | `FALSE`
  135. * `boolean` | expose | Set the X-Powered-By header
  136. *
  137. * @throws Kohana_Exception
  138. * @param array $settings Array of settings. See above.
  139. * @return void
  140. * @uses Kohana::sanitize
  141. * @uses Kohana::cache
  142. * @uses Profiler
  143. */
  144. public static function init(array $settings = NULL)
  145. {
  146. if (Kohana::$_init)
  147. {
  148. // Do not allow execution twice
  149. return;
  150. }
  151. // Kohana is now initialized
  152. Kohana::$_init = TRUE;
  153. if (isset($settings['profile']))
  154. {
  155. // Enable profiling
  156. Kohana::$profiling = (bool) $settings['profile'];
  157. }
  158. // Start an output buffer
  159. ob_start();
  160. if (isset($settings['errors']))
  161. {
  162. // Enable error handling
  163. Kohana::$errors = (bool) $settings['errors'];
  164. }
  165. if (Kohana::$errors === TRUE)
  166. {
  167. // Enable Kohana exception handling, adds stack traces and error source.
  168. set_exception_handler(['Kohana_Exception', 'handler']);
  169. // Enable Kohana error handling, converts all PHP errors to exceptions.
  170. set_error_handler(['Kohana', 'error_handler']);
  171. }
  172. /**
  173. * Enable xdebug parameter collection in development mode to improve fatal stack traces.
  174. */
  175. if (Kohana::$environment == Kohana::DEVELOPMENT AND extension_loaded('xdebug'))
  176. {
  177. ini_set('xdebug.collect_params', 3);
  178. }
  179. // Enable the Kohana shutdown handler, which catches E_FATAL errors.
  180. register_shutdown_function(['Kohana', 'shutdown_handler']);
  181. if (isset($settings['expose']))
  182. {
  183. Kohana::$expose = (bool) $settings['expose'];
  184. }
  185. // Determine if we are running in a Windows environment
  186. Kohana::$is_windows = (DIRECTORY_SEPARATOR === '\\');
  187. if (isset($settings['cache_dir']))
  188. {
  189. if ( ! is_dir($settings['cache_dir']))
  190. {
  191. try
  192. {
  193. // Create the cache directory
  194. mkdir($settings['cache_dir'], 0755, TRUE);
  195. // Set permissions (must be manually set to fix umask issues)
  196. chmod($settings['cache_dir'], 0755);
  197. }
  198. catch (Exception $e)
  199. {
  200. throw new Kohana_Exception('Could not create cache directory :dir',
  201. [':dir' => Debug::path($settings['cache_dir'])]);
  202. }
  203. }
  204. // Set the cache directory path
  205. Kohana::$cache_dir = realpath($settings['cache_dir']);
  206. }
  207. else
  208. {
  209. // Use the default cache directory
  210. Kohana::$cache_dir = APPPATH.'cache';
  211. }
  212. if ( ! is_writable(Kohana::$cache_dir))
  213. {
  214. throw new Kohana_Exception('Directory :dir must be writable',
  215. [':dir' => Debug::path(Kohana::$cache_dir)]);
  216. }
  217. if (isset($settings['cache_life']))
  218. {
  219. // Set the default cache lifetime
  220. Kohana::$cache_life = (int) $settings['cache_life'];
  221. }
  222. if (isset($settings['caching']))
  223. {
  224. // Enable or disable internal caching
  225. Kohana::$caching = (bool) $settings['caching'];
  226. }
  227. if (Kohana::$caching === TRUE)
  228. {
  229. // Load the file path cache
  230. Kohana::$_files = Kohana::cache('Kohana::find_file()');
  231. }
  232. if (isset($settings['charset']))
  233. {
  234. // Set the system character set
  235. Kohana::$charset = strtolower($settings['charset']);
  236. }
  237. if (function_exists('mb_internal_encoding'))
  238. {
  239. // Set the MB extension encoding to the same character set
  240. mb_internal_encoding(Kohana::$charset);
  241. }
  242. if (isset($settings['base_url']))
  243. {
  244. // Set the base URL
  245. Kohana::$base_url = rtrim($settings['base_url'], '/').'/';
  246. }
  247. if (isset($settings['index_file']))
  248. {
  249. // Set the index file
  250. Kohana::$index_file = trim($settings['index_file'], '/');
  251. }
  252. // Sanitize all request variables
  253. $_GET = Kohana::sanitize($_GET);
  254. $_POST = Kohana::sanitize($_POST);
  255. $_COOKIE = Kohana::sanitize($_COOKIE);
  256. // Load the logger if one doesn't already exist
  257. if ( ! Kohana::$log instanceof Log)
  258. {
  259. Kohana::$log = Log::instance();
  260. }
  261. // Load the config if one doesn't already exist
  262. if ( ! Kohana::$config instanceof Config)
  263. {
  264. Kohana::$config = new Config;
  265. }
  266. }
  267. /**
  268. * Cleans up the environment:
  269. *
  270. * - Restore the previous error and exception handlers
  271. * - Destroy the Kohana::$log and Kohana::$config objects
  272. *
  273. * @return void
  274. */
  275. public static function deinit()
  276. {
  277. if (Kohana::$_init)
  278. {
  279. // Removed the autoloader
  280. spl_autoload_unregister(['Kohana', 'auto_load']);
  281. if (Kohana::$errors)
  282. {
  283. // Go back to the previous error handler
  284. restore_error_handler();
  285. // Go back to the previous exception handler
  286. restore_exception_handler();
  287. }
  288. // Destroy objects created by init
  289. Kohana::$log = Kohana::$config = NULL;
  290. // Reset internal storage
  291. Kohana::$_modules = Kohana::$_files = [];
  292. Kohana::$_paths = [APPPATH, SYSPATH];
  293. // Reset file cache status
  294. Kohana::$_files_changed = FALSE;
  295. // Kohana is no longer initialized
  296. Kohana::$_init = FALSE;
  297. }
  298. }
  299. /**
  300. * Recursively sanitizes an input variable:
  301. *
  302. * - Normalizes all newlines to LF
  303. *
  304. * @param mixed $value any variable
  305. * @return mixed sanitized variable
  306. */
  307. public static function sanitize($value)
  308. {
  309. if (is_array($value) OR is_object($value))
  310. {
  311. foreach ($value as $key => $val)
  312. {
  313. // Recursively clean each value
  314. $value[$key] = Kohana::sanitize($val);
  315. }
  316. }
  317. elseif (is_string($value))
  318. {
  319. if (strpos($value, "\r") !== FALSE)
  320. {
  321. // Standardize newlines
  322. $value = str_replace(["\r\n", "\r"], "\n", $value);
  323. }
  324. }
  325. return $value;
  326. }
  327. /**
  328. * Provides auto-loading support of classes that follow Kohana's [class
  329. * naming conventions](kohana/conventions#class-names-and-file-location).
  330. * See [Loading Classes](kohana/autoloading) for more information.
  331. *
  332. * // Loads classes/My/Class/Name.php
  333. * Kohana::auto_load('My_Class_Name');
  334. *
  335. * or with a custom directory:
  336. *
  337. * // Loads vendor/My/Class/Name.php
  338. * Kohana::auto_load('My_Class_Name', 'vendor');
  339. *
  340. * You should never have to call this function, as simply calling a class
  341. * will cause it to be called.
  342. *
  343. * This function must be enabled as an autoloader in the bootstrap:
  344. *
  345. * spl_autoload_register(array('Kohana', 'auto_load'));
  346. *
  347. * @param string $class Class name
  348. * @param string $directory Directory to load from
  349. * @return boolean
  350. */
  351. public static function auto_load($class, $directory = 'classes')
  352. {
  353. // Transform the class name according to PSR-0
  354. $class = ltrim($class, '\\');
  355. $file = '';
  356. $namespace = '';
  357. if ($last_namespace_position = strripos($class, '\\'))
  358. {
  359. $namespace = substr($class, 0, $last_namespace_position);
  360. $class = substr($class, $last_namespace_position + 1);
  361. $file = str_replace('\\', DIRECTORY_SEPARATOR, $namespace).DIRECTORY_SEPARATOR;
  362. }
  363. $file .= str_replace('_', DIRECTORY_SEPARATOR, $class);
  364. if ($path = Kohana::find_file($directory, $file))
  365. {
  366. // Load the class file
  367. require $path;
  368. // Class has been found
  369. return TRUE;
  370. }
  371. // Class is not in the filesystem
  372. return FALSE;
  373. }
  374. /**
  375. * Provides auto-loading support of classes that follow Kohana's old class
  376. * naming conventions.
  377. *
  378. * This is included for compatibility purposes with older modules.
  379. *
  380. * @param string $class Class name
  381. * @param string $directory Directory to load from
  382. * @return boolean
  383. */
  384. public static function auto_load_lowercase($class, $directory = 'classes')
  385. {
  386. // Transform the class name into a path
  387. $file = str_replace('_', DIRECTORY_SEPARATOR, strtolower($class));
  388. if ($path = Kohana::find_file($directory, $file))
  389. {
  390. // Load the class file
  391. require $path;
  392. // Class has been found
  393. return TRUE;
  394. }
  395. // Class is not in the filesystem
  396. return FALSE;
  397. }
  398. /**
  399. * Changes the currently enabled modules. Module paths may be relative
  400. * or absolute, but must point to a directory:
  401. *
  402. * Kohana::modules(array('modules/foo', MODPATH.'bar'));
  403. *
  404. * @param array $modules list of module paths
  405. * @return array enabled modules
  406. */
  407. public static function modules(array $modules = NULL)
  408. {
  409. if ($modules === NULL)
  410. {
  411. // Not changing modules, just return the current set
  412. return Kohana::$_modules;
  413. }
  414. // Start a new list of include paths, APPPATH first
  415. $paths = [APPPATH];
  416. foreach ($modules as $name => $path)
  417. {
  418. if (is_dir($path))
  419. {
  420. // Add the module to include paths
  421. $paths[] = $modules[$name] = realpath($path).DIRECTORY_SEPARATOR;
  422. }
  423. else
  424. {
  425. // This module is invalid, remove it
  426. throw new Kohana_Exception('Attempted to load an invalid or missing module \':module\' at \':path\'', [
  427. ':module' => $name,
  428. ':path' => Debug::path($path),
  429. ]);
  430. }
  431. }
  432. // Finish the include paths by adding SYSPATH
  433. $paths[] = SYSPATH;
  434. // Set the new include paths
  435. Kohana::$_paths = $paths;
  436. // Set the current module list
  437. Kohana::$_modules = $modules;
  438. foreach (Kohana::$_modules as $path)
  439. {
  440. $init = $path.'init'.EXT;
  441. if (is_file($init))
  442. {
  443. // Include the module initialization file once
  444. require_once $init;
  445. }
  446. }
  447. return Kohana::$_modules;
  448. }
  449. /**
  450. * Returns the the currently active include paths, including the
  451. * application, system, and each module's path.
  452. *
  453. * @return array
  454. */
  455. public static function include_paths()
  456. {
  457. return Kohana::$_paths;
  458. }
  459. /**
  460. * Searches for a file in the [Cascading Filesystem](kohana/files), and
  461. * returns the path to the file that has the highest precedence, so that it
  462. * can be included.
  463. *
  464. * When searching the "config", "messages", or "i18n" directories, or when
  465. * the `$array` flag is set to true, an array of all the files that match
  466. * that path in the [Cascading Filesystem](kohana/files) will be returned.
  467. * These files will return arrays which must be merged together.
  468. *
  469. * If no extension is given, the default extension (`EXT` set in
  470. * `index.php`) will be used.
  471. *
  472. * // Returns an absolute path to views/template.php
  473. * Kohana::find_file('views', 'template');
  474. *
  475. * // Returns an absolute path to media/css/style.css
  476. * Kohana::find_file('media', 'css/style', 'css');
  477. *
  478. * // Returns an array of all the "mimes" configuration files
  479. * Kohana::find_file('config', 'mimes');
  480. *
  481. * @param string $dir directory name (views, i18n, classes, extensions, etc.)
  482. * @param string $file filename with subdirectory
  483. * @param string $ext extension to search for
  484. * @param boolean $array return an array of files?
  485. * @return array a list of files when $array is TRUE
  486. * @return string single file path
  487. */
  488. public static function find_file($dir, $file, $ext = NULL, $array = FALSE)
  489. {
  490. if ($ext === NULL)
  491. {
  492. // Use the default extension
  493. $ext = EXT;
  494. }
  495. elseif ($ext)
  496. {
  497. // Prefix the extension with a period
  498. $ext = ".{$ext}";
  499. }
  500. else
  501. {
  502. // Use no extension
  503. $ext = '';
  504. }
  505. // Create a partial path of the filename
  506. $path = $dir.DIRECTORY_SEPARATOR.$file.$ext;
  507. if (Kohana::$caching === TRUE AND isset(Kohana::$_files[$path.($array ? '_array' : '_path')]))
  508. {
  509. // This path has been cached
  510. return Kohana::$_files[$path.($array ? '_array' : '_path')];
  511. }
  512. if (Kohana::$profiling === TRUE AND class_exists('Profiler', FALSE))
  513. {
  514. // Start a new benchmark
  515. $benchmark = Profiler::start('Kohana', __FUNCTION__);
  516. }
  517. if ($array OR $dir === 'config' OR $dir === 'i18n' OR $dir === 'messages')
  518. {
  519. // Include paths must be searched in reverse
  520. $paths = array_reverse(Kohana::$_paths);
  521. // Array of files that have been found
  522. $found = [];
  523. foreach ($paths as $dir)
  524. {
  525. if (is_file($dir.$path))
  526. {
  527. // This path has a file, add it to the list
  528. $found[] = $dir.$path;
  529. }
  530. }
  531. }
  532. else
  533. {
  534. // The file has not been found yet
  535. $found = FALSE;
  536. foreach (Kohana::$_paths as $dir)
  537. {
  538. if (is_file($dir.$path))
  539. {
  540. // A path has been found
  541. $found = $dir.$path;
  542. // Stop searching
  543. break;
  544. }
  545. }
  546. }
  547. if (Kohana::$caching === TRUE)
  548. {
  549. // Add the path to the cache
  550. Kohana::$_files[$path.($array ? '_array' : '_path')] = $found;
  551. // Files have been changed
  552. Kohana::$_files_changed = TRUE;
  553. }
  554. if (isset($benchmark))
  555. {
  556. // Stop the benchmark
  557. Profiler::stop($benchmark);
  558. }
  559. return $found;
  560. }
  561. /**
  562. * Recursively finds all of the files in the specified directory at any
  563. * location in the [Cascading Filesystem](kohana/files), and returns an
  564. * array of all the files found, sorted alphabetically.
  565. *
  566. * // Find all view files.
  567. * $views = Kohana::list_files('views');
  568. *
  569. * @param string $directory directory name
  570. * @param array $paths list of paths to search
  571. * @return array
  572. */
  573. public static function list_files($directory = NULL, array $paths = NULL)
  574. {
  575. if ($directory !== NULL)
  576. {
  577. // Add the directory separator
  578. $directory .= DIRECTORY_SEPARATOR;
  579. }
  580. if ($paths === NULL)
  581. {
  582. // Use the default paths
  583. $paths = Kohana::$_paths;
  584. }
  585. // Create an array for the files
  586. $found = [];
  587. foreach ($paths as $path)
  588. {
  589. if (is_dir($path.$directory))
  590. {
  591. // Create a new directory iterator
  592. $dir = new DirectoryIterator($path.$directory);
  593. foreach ($dir as $file)
  594. {
  595. // Get the file name
  596. $filename = $file->getFilename();
  597. if ($filename[0] === '.' OR $filename[strlen($filename)-1] === '~')
  598. {
  599. // Skip all hidden files and UNIX backup files
  600. continue;
  601. }
  602. // Relative filename is the array key
  603. $key = $directory.$filename;
  604. if ($file->isDir())
  605. {
  606. if ($sub_dir = Kohana::list_files($key, $paths))
  607. {
  608. if (isset($found[$key]))
  609. {
  610. // Append the sub-directory list
  611. $found[$key] += $sub_dir;
  612. }
  613. else
  614. {
  615. // Create a new sub-directory list
  616. $found[$key] = $sub_dir;
  617. }
  618. }
  619. }
  620. else
  621. {
  622. if ( ! isset($found[$key]))
  623. {
  624. // Add new files to the list
  625. $found[$key] = realpath($file->getPathname());
  626. }
  627. }
  628. }
  629. }
  630. }
  631. // Sort the results alphabetically
  632. ksort($found);
  633. return $found;
  634. }
  635. /**
  636. * Loads a file within a totally empty scope and returns the output:
  637. *
  638. * $foo = Kohana::load('foo.php');
  639. *
  640. * @param string $file
  641. * @return mixed
  642. */
  643. public static function load($file)
  644. {
  645. return include $file;
  646. }
  647. /**
  648. * Cache variables using current cache module if enabled, if not uses Kohana::file_cache
  649. *
  650. * // Set the "foo" cache
  651. * Kohana::cache('foo', 'hello, world');
  652. *
  653. * // Get the "foo" cache
  654. * $foo = Kohana::cache('foo');
  655. *
  656. * @throws Kohana_Exception
  657. * @param string $name name of the cache
  658. * @param mixed $data data to cache
  659. * @param integer $lifetime number of seconds the cache is valid for
  660. * @return mixed for getting
  661. * @return boolean for setting
  662. */
  663. public static function cache($name, $data = NULL, $lifetime = NULL)
  664. {
  665. //in case the Kohana_Cache is not yet loaded we need to use the normal cache...sucks but happens onload
  666. if (class_exists('Kohana_Cache'))
  667. {
  668. //deletes the cache
  669. if ($lifetime===0)
  670. return Cache::instance()->delete($name);
  671. //no data provided we read
  672. if ($data===NULL)
  673. return Cache::instance()->get($name);
  674. //saves data
  675. else
  676. return Cache::instance()->set($name,$data, $lifetime);
  677. }
  678. else
  679. return self::file_cache($name, $data, $lifetime);
  680. }
  681. /**
  682. * Provides simple file-based caching for strings and arrays:
  683. *
  684. * // Set the "foo" cache
  685. * Kohana::file_cache('foo', 'hello, world');
  686. *
  687. * // Get the "foo" cache
  688. * $foo = Kohana::file_cache('foo');
  689. *
  690. * All caches are stored as PHP code, generated with [var_export][ref-var].
  691. * Caching objects may not work as expected. Storing references or an
  692. * object or array that has recursion will cause an E_FATAL.
  693. *
  694. * The cache directory and default cache lifetime is set by [Kohana::init]
  695. *
  696. * [ref-var]: http://php.net/var_export
  697. *
  698. * @throws Kohana_Exception
  699. * @param string $name name of the cache
  700. * @param mixed $data data to cache
  701. * @param integer $lifetime number of seconds the cache is valid for
  702. * @return mixed for getting
  703. * @return boolean for setting
  704. */
  705. public static function file_cache($name, $data = NULL, $lifetime = NULL)
  706. {
  707. // Cache file is a hash of the name
  708. $file = sha1($name).'.txt';
  709. // Cache directories are split by keys to prevent filesystem overload
  710. $dir = Kohana::$cache_dir.DIRECTORY_SEPARATOR.$file[0].$file[1].DIRECTORY_SEPARATOR;
  711. if ($lifetime === NULL)
  712. {
  713. // Use the default lifetime
  714. $lifetime = Kohana::$cache_life;
  715. }
  716. if ($data === NULL)
  717. {
  718. if (is_file($dir.$file))
  719. {
  720. if ((time() - filemtime($dir.$file)) < $lifetime)
  721. {
  722. // Return the cache
  723. try
  724. {
  725. return unserialize(file_get_contents($dir.$file));
  726. }
  727. catch (Exception $e)
  728. {
  729. // Cache is corrupt, let return happen normally.
  730. }
  731. }
  732. else
  733. {
  734. try
  735. {
  736. // Cache has expired
  737. unlink($dir.$file);
  738. }
  739. catch (Exception $e)
  740. {
  741. // Cache has mostly likely already been deleted,
  742. // let return happen normally.
  743. }
  744. }
  745. }
  746. // Cache not found
  747. return NULL;
  748. }
  749. if ( ! is_dir($dir))
  750. {
  751. // Create the cache directory
  752. mkdir($dir, 0777, TRUE);
  753. // Set permissions (must be manually set to fix umask issues)
  754. chmod($dir, 0777);
  755. }
  756. // Force the data to be a string
  757. $data = serialize($data);
  758. try
  759. {
  760. // Write the cache
  761. return (bool) file_put_contents($dir.$file, $data, LOCK_EX);
  762. }
  763. catch (Exception $e)
  764. {
  765. // Failed to write cache
  766. return FALSE;
  767. }
  768. }
  769. /**
  770. * Get a message from a file. Messages are arbitrary strings that are stored
  771. * in the `messages/` directory and reference by a key. Translation is not
  772. * performed on the returned values. See [message files](kohana/files/messages)
  773. * for more information.
  774. *
  775. * // Get "username" from messages/text.php
  776. * $username = Kohana::message('text', 'username');
  777. *
  778. * @param string $file file name
  779. * @param string $path key path to get
  780. * @param mixed $default default value if the path does not exist
  781. * @return string message string for the given path
  782. * @return array complete message list, when no path is specified
  783. * @uses Arr::merge
  784. * @uses Arr::path
  785. */
  786. public static function message($file, $path = NULL, $default = NULL)
  787. {
  788. static $messages;
  789. if ( ! isset($messages[$file]))
  790. {
  791. // Create a new message list
  792. $messages[$file] = [];
  793. if ($files = Kohana::find_file('messages', $file))
  794. {
  795. foreach ($files as $f)
  796. {
  797. // Combine all the messages recursively
  798. $messages[$file] = Arr::merge($messages[$file], Kohana::load($f));
  799. }
  800. }
  801. }
  802. if ($path === NULL)
  803. {
  804. // Return all of the messages
  805. return $messages[$file];
  806. }
  807. else
  808. {
  809. // Get a message using the path
  810. return Arr::path($messages[$file], $path, $default);
  811. }
  812. }
  813. /**
  814. * PHP error handler, converts all errors into ErrorExceptions. This handler
  815. * respects error_reporting settings.
  816. *
  817. * @throws ErrorException
  818. * @return TRUE
  819. */
  820. public static function error_handler($code, $error, $file = NULL, $line = NULL)
  821. {
  822. if (error_reporting() & $code)
  823. {
  824. // This error is not suppressed by current error reporting settings
  825. // Convert the error into an ErrorException
  826. throw new ErrorException($error, $code, 0, $file, $line);
  827. }
  828. // Do not execute the PHP error handler
  829. return TRUE;
  830. }
  831. /**
  832. * Catches errors that are not caught by the error handler, such as E_PARSE.
  833. *
  834. * @uses Kohana_Exception::handler
  835. * @return void
  836. */
  837. public static function shutdown_handler()
  838. {
  839. if ( ! Kohana::$_init)
  840. {
  841. // Do not execute when not active
  842. return;
  843. }
  844. try
  845. {
  846. if (Kohana::$caching === TRUE AND Kohana::$_files_changed === TRUE)
  847. {
  848. // Write the file path cache
  849. Kohana::cache('Kohana::find_file()', Kohana::$_files);
  850. }
  851. }
  852. catch (Exception $e)
  853. {
  854. // Pass the exception to the handler
  855. Kohana_Exception::handler($e);
  856. }
  857. if (Kohana::$errors AND $error = error_get_last() AND in_array($error['type'], Kohana::$shutdown_errors))
  858. {
  859. // Clean the output buffer
  860. ob_get_level() AND ob_clean();
  861. // Fake an exception for nice debugging
  862. Kohana_Exception::handler(new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']));
  863. // Shutdown now to avoid a "death loop"
  864. exit(1);
  865. }
  866. }
  867. /**
  868. * Generates a version string based on the variables defined above.
  869. *
  870. * @return string
  871. */
  872. public static function version()
  873. {
  874. return 'Koseven '.Kohana::VERSION.' ('.Kohana::CODENAME.')';
  875. }
  876. }