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