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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
|
<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
* Provides Kohana-specific helper functions. This is where the magic happens!
*
* $Id: Kohana.php 4372 2009-05-28 17:00:34Z ixmatus $
*
* @package Core
* @author Kohana Team
* @copyright (c) 2007-2008 Kohana Team
* @license http://kohanaphp.com/license.html
*/
final class Kohana {
// The singleton instance of the controller
public static $instance;
// Output buffering level
private static $buffer_level;
// Will be set to TRUE when an exception is caught
public static $has_error = FALSE;
// The final output that will displayed by Kohana
public static $output = '';
// The current user agent
public static $user_agent;
// The current locale
public static $locale;
// Configuration
private static $configuration;
// Include paths
private static $include_paths;
// Logged messages
private static $log;
// Cache lifetime
private static $cache_lifetime;
// Log levels
private static $log_levels = array
(
'error' => 1,
'alert' => 2,
'info' => 3,
'debug' => 4,
);
// Internal caches and write status
private static $internal_cache = array();
private static $write_cache;
private static $internal_cache_path;
private static $internal_cache_key;
private static $internal_cache_encrypt;
/**
* Sets up the PHP environment. Adds error/exception handling, output
* buffering, and adds an auto-loading method for loading classes.
*
* This method is run immediately when this file is loaded, and is
* benchmarked as environment_setup.
*
* For security, this function also destroys the $_REQUEST global variable.
* Using the proper global (GET, POST, COOKIE, etc) is inherently more secure.
* The recommended way to fetch a global variable is using the Input library.
* @see http://www.php.net/globals
*
* @return void
*/
public static function setup()
{
static $run;
// This function can only be run once
if ($run === TRUE)
return;
// Start the environment setup benchmark
Benchmark::start(SYSTEM_BENCHMARK.'_environment_setup');
// Define Kohana error constant
define('E_KOHANA', 42);
// Define 404 error constant
define('E_PAGE_NOT_FOUND', 43);
// Define database error constant
define('E_DATABASE_ERROR', 44);
if (self::$cache_lifetime = self::config('core.internal_cache'))
{
// Are we using encryption for caches?
self::$internal_cache_encrypt = self::config('core.internal_cache_encrypt');
if(self::$internal_cache_encrypt===TRUE)
{
self::$internal_cache_key = self::config('core.internal_cache_key');
// Be sure the key is of acceptable length for the mcrypt algorithm used
self::$internal_cache_key = substr(self::$internal_cache_key, 0, 24);
}
// Set the directory to be used for the internal cache
if ( ! self::$internal_cache_path = self::config('core.internal_cache_path'))
{
self::$internal_cache_path = APPPATH.'cache/';
}
// Load cached configuration and language files
self::$internal_cache['configuration'] = self::cache('configuration', self::$cache_lifetime);
self::$internal_cache['language'] = self::cache('language', self::$cache_lifetime);
// Load cached file paths
self::$internal_cache['find_file_paths'] = self::cache('find_file_paths', self::$cache_lifetime);
// Enable cache saving
Event::add('system.shutdown', array(__CLASS__, 'internal_cache_save'));
}
// Disable notices and "strict" errors
$ER = error_reporting(~E_NOTICE & ~E_STRICT);
// Set the user agent
self::$user_agent = ( ! empty($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : '');
if (function_exists('date_default_timezone_set'))
{
$timezone = self::config('locale.timezone');
// Set default timezone, due to increased validation of date settings
// which cause massive amounts of E_NOTICEs to be generated in PHP 5.2+
date_default_timezone_set(empty($timezone) ? date_default_timezone_get() : $timezone);
}
// Restore error reporting
error_reporting($ER);
// Start output buffering
ob_start(array(__CLASS__, 'output_buffer'));
// Save buffering level
self::$buffer_level = ob_get_level();
// Set autoloader
spl_autoload_register(array('Kohana', 'auto_load'));
// Set error handler
set_error_handler(array('Kohana', 'exception_handler'));
// Set exception handler
set_exception_handler(array('Kohana', 'exception_handler'));
// Send default text/html UTF-8 header
header('Content-Type: text/html; charset=UTF-8');
// Load locales
$locales = self::config('locale.language');
// Make first locale UTF-8
$locales[0] .= '.UTF-8';
// Set locale information
self::$locale = setlocale(LC_ALL, $locales);
if (self::$configuration['core']['log_threshold'] > 0)
{
// Set the log directory
self::log_directory(self::$configuration['core']['log_directory']);
// Enable log writing at shutdown
register_shutdown_function(array(__CLASS__, 'log_save'));
}
// Enable Kohana routing
Event::add('system.routing', array('Router', 'find_uri'));
Event::add('system.routing', array('Router', 'setup'));
// Enable Kohana controller initialization
Event::add('system.execute', array('Kohana', 'instance'));
// Enable Kohana 404 pages
Event::add('system.404', array('Kohana', 'show_404'));
// Enable Kohana output handling
Event::add('system.shutdown', array('Kohana', 'shutdown'));
if (self::config('core.enable_hooks') === TRUE)
{
// Find all the hook files
$hooks = self::list_files('hooks', TRUE);
foreach ($hooks as $file)
{
// Load the hook
include $file;
}
}
// Setup is complete, prevent it from being run again
$run = TRUE;
// Stop the environment setup routine
Benchmark::stop(SYSTEM_BENCHMARK.'_environment_setup');
}
/**
* Loads the controller and initializes it. Runs the pre_controller,
* post_controller_constructor, and post_controller events. Triggers
* a system.404 event when the route cannot be mapped to a controller.
*
* This method is benchmarked as controller_setup and controller_execution.
*
* @return object instance of controller
*/
public static function & instance()
{
if (self::$instance === NULL)
{
Benchmark::start(SYSTEM_BENCHMARK.'_controller_setup');
// Include the Controller file
require Router::$controller_path;
try
{
// Start validation of the controller
$class = new ReflectionClass(ucfirst(Router::$controller).'_Controller');
}
catch (ReflectionException $e)
{
// Controller does not exist
Event::run('system.404');
}
if ($class->isAbstract() OR (IN_PRODUCTION AND $class->getConstant('ALLOW_PRODUCTION') == FALSE))
{
// Controller is not allowed to run in production
Event::run('system.404');
}
// Run system.pre_controller
Event::run('system.pre_controller');
// Create a new controller instance
$controller = $class->newInstance();
// Controller constructor has been executed
Event::run('system.post_controller_constructor');
try
{
// Load the controller method
$method = $class->getMethod(Router::$method);
// Method exists
if (Router::$method[0] === '_')
{
// Do not allow access to hidden methods
Event::run('system.404');
}
if ($method->isProtected() or $method->isPrivate())
{
// Do not attempt to invoke protected methods
throw new ReflectionException('protected controller method');
}
// Default arguments
$arguments = Router::$arguments;
}
catch (ReflectionException $e)
{
// Use __call instead
$method = $class->getMethod('__call');
// Use arguments in __call format
$arguments = array(Router::$method, Router::$arguments);
}
// Stop the controller setup benchmark
Benchmark::stop(SYSTEM_BENCHMARK.'_controller_setup');
// Start the controller execution benchmark
Benchmark::start(SYSTEM_BENCHMARK.'_controller_execution');
// Execute the controller method
$method->invokeArgs($controller, $arguments);
// Controller method has been executed
Event::run('system.post_controller');
// Stop the controller execution benchmark
Benchmark::stop(SYSTEM_BENCHMARK.'_controller_execution');
}
return self::$instance;
}
/**
* Get all include paths. APPPATH is the first path, followed by module
* paths in the order they are configured, follow by the SYSPATH.
*
* @param boolean re-process the include paths
* @return array
*/
public static function include_paths($process = FALSE)
{
if ($process === TRUE)
{
// Add APPPATH as the first path
self::$include_paths = array(APPPATH);
foreach (self::$configuration['core']['modules'] as $path)
{
if ($path = str_replace('\\', '/', realpath($path)))
{
// Add a valid path
self::$include_paths[] = $path.'/';
}
}
// Add SYSPATH as the last path
self::$include_paths[] = SYSPATH;
}
return self::$include_paths;
}
/**
* Get a config item or group.
*
* @param string item name
* @param boolean force a forward slash (/) at the end of the item
* @param boolean is the item required?
* @return mixed
*/
public static function config($key, $slash = FALSE, $required = TRUE)
{
if (self::$configuration === NULL)
{
// Load core configuration
self::$configuration['core'] = self::config_load('core');
// Re-parse the include paths
self::include_paths(TRUE);
}
// Get the group name from the key
$group = explode('.', $key, 2);
$group = $group[0];
if ( ! isset(self::$configuration[$group]))
{
// Load the configuration group
self::$configuration[$group] = self::config_load($group, $required);
}
// Get the value of the key string
$value = self::key_string(self::$configuration, $key);
if ($slash === TRUE AND is_string($value) AND $value !== '')
{
// Force the value to end with "/"
$value = rtrim($value, '/').'/';
}
return $value;
}
/**
* Sets a configuration item, if allowed.
*
* @param string config key string
* @param string config value
* @return boolean
*/
public static function config_set($key, $value)
{
// Do this to make sure that the config array is already loaded
self::config($key);
if (substr($key, 0, 7) === 'routes.')
{
// Routes cannot contain sub keys due to possible dots in regex
$keys = explode('.', $key, 2);
}
else
{
// Convert dot-noted key string to an array
$keys = explode('.', $key);
}
// Used for recursion
$conf =& self::$configuration;
$last = count($keys) - 1;
foreach ($keys as $i => $k)
{
if ($i === $last)
{
$conf[$k] = $value;
}
else
{
$conf =& $conf[$k];
}
}
if ($key === 'core.modules')
{
// Reprocess the include paths
self::include_paths(TRUE);
}
return TRUE;
}
/**
* Load a config file.
*
* @param string config filename, without extension
* @param boolean is the file required?
* @return array
*/
public static function config_load($name, $required = TRUE)
{
if ($name === 'core')
{
// Load the application configuration file
require APPPATH.'config/config'.EXT;
if ( ! isset($config['site_domain']))
{
// Invalid config file
die('Your Kohana application configuration file is not valid.');
}
return $config;
}
if (isset(self::$internal_cache['configuration'][$name]))
return self::$internal_cache['configuration'][$name];
// Load matching configs
$configuration = array();
if ($files = self::find_file('config', $name, $required))
{
foreach ($files as $file)
{
require $file;
if (isset($config) AND is_array($config))
{
// Merge in configuration
$configuration = array_merge($configuration, $config);
}
}
}
if ( ! isset(self::$write_cache['configuration']))
{
// Cache has changed
self::$write_cache['configuration'] = TRUE;
}
return self::$internal_cache['configuration'][$name] = $configuration;
}
/**
* Clears a config group from the cached configuration.
*
* @param string config group
* @return void
*/
public static function config_clear($group)
{
// Remove the group from config
unset(self::$configuration[$group], self::$internal_cache['configuration'][$group]);
if ( ! isset(self::$write_cache['configuration']))
{
// Cache has changed
self::$write_cache['configuration'] = TRUE;
}
}
/**
* Add a new message to the log.
*
* @param string type of message
* @param string message text
* @return void
*/
public static function log($type, $message)
{
if (self::$log_levels[$type] <= self::$configuration['core']['log_threshold'])
{
$message = array(date('Y-m-d H:i:s P'), $type, $message);
// Run the system.log event
Event::run('system.log', $message);
self::$log[] = $message;
}
}
/**
* Save all currently logged messages.
*
* @return void
*/
public static function log_save()
{
if (empty(self::$log) OR self::$configuration['core']['log_threshold'] < 1)
return;
// Filename of the log
$filename = self::log_directory().date('Y-m-d').'.log'.EXT;
if ( ! is_file($filename))
{
// Write the SYSPATH checking header
file_put_contents($filename,
'<?php defined(\'SYSPATH\') or die(\'No direct script access.\'); ?>'.PHP_EOL.PHP_EOL);
// Prevent external writes
chmod($filename, 0644);
}
// Messages to write
$messages = array();
do
{
// Load the next mess
list ($date, $type, $text) = array_shift(self::$log);
// Add a new message line
$messages[] = $date.' --- '.$type.': '.$text;
}
while ( ! empty(self::$log));
// Write messages to log file
file_put_contents($filename, implode(PHP_EOL, $messages).PHP_EOL, FILE_APPEND);
}
/**
* Get or set the logging directory.
*
* @param string new log directory
* @return string
*/
public static function log_directory($dir = NULL)
{
static $directory;
if ( ! empty($dir))
{
// Get the directory path
$dir = realpath($dir);
if (is_dir($dir) AND is_writable($dir))
{
// Change the log directory
$directory = str_replace('\\', '/', $dir).'/';
}
else
{
// Log directory is invalid
throw new Kohana_Exception('core.log_dir_unwritable', $dir);
}
}
return $directory;
}
/**
* Load data from a simple cache file. This should only be used internally,
* and is NOT a replacement for the Cache library.
*
* @param string unique name of cache
* @param integer expiration in seconds
* @return mixed
*/
public static function cache($name, $lifetime)
{
if ($lifetime > 0)
{
$path = self::$internal_cache_path.'kohana_'.$name;
if (is_file($path))
{
// Check the file modification time
if ((time() - filemtime($path)) < $lifetime)
{
// Cache is valid! Now, do we need to decrypt it?
if(self::$internal_cache_encrypt===TRUE)
{
$data = file_get_contents($path);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::$internal_cache_key, $data, MCRYPT_MODE_ECB, $iv);
$cache = unserialize($decrypted_text);
// If the key changed, delete the cache file
if(!$cache)
unlink($path);
// If cache is false (as above) return NULL, otherwise, return the cache
return ($cache ? $cache : NULL);
}
else
{
return unserialize(file_get_contents($path));
}
}
else
{
// Cache is invalid, delete it
unlink($path);
}
}
}
// No cache found
return NULL;
}
/**
* Save data to a simple cache file. This should only be used internally, and
* is NOT a replacement for the Cache library.
*
* @param string cache name
* @param mixed data to cache
* @param integer expiration in seconds
* @return boolean
*/
public static function cache_save($name, $data, $lifetime)
{
if ($lifetime < 1)
return FALSE;
$path = self::$internal_cache_path.'kohana_'.$name;
if ($data === NULL)
{
// Delete cache
return (is_file($path) and unlink($path));
}
else
{
// Using encryption? Encrypt the data when we write it
if(self::$internal_cache_encrypt===TRUE)
{
// Encrypt and write data to cache file
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
// Serialize and encrypt!
$encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::$internal_cache_key, serialize($data), MCRYPT_MODE_ECB, $iv);
return (bool) file_put_contents($path, $encrypted_text);
}
else
{
// Write data to cache file
return (bool) file_put_contents($path, serialize($data));
}
}
}
/**
* Kohana output handler. Called during ob_clean, ob_flush, and their variants.
*
* @param string current output buffer
* @return string
*/
public static function output_buffer($output)
{
// Could be flushing, so send headers first
if ( ! Event::has_run('system.send_headers'))
{
// Run the send_headers event
Event::run('system.send_headers');
}
self::$output = $output;
// Set and return the final output
return self::$output;
}
/**
* Closes all open output buffers, either by flushing or cleaning, and stores the Kohana
* output buffer for display during shutdown.
*
* @param boolean disable to clear buffers, rather than flushing
* @return void
*/
public static function close_buffers($flush = TRUE)
{
if (ob_get_level() >= self::$buffer_level)
{
// Set the close function
$close = ($flush === TRUE) ? 'ob_end_flush' : 'ob_end_clean';
while (ob_get_level() > self::$buffer_level)
{
// Flush or clean the buffer
$close();
}
// Store the Kohana output buffer
ob_end_clean();
}
}
/**
* Triggers the shutdown of Kohana by closing the output buffer, runs the system.display event.
*
* @return void
*/
public static function shutdown()
{
// Close output buffers
self::close_buffers(TRUE);
// Run the output event
Event::run('system.display', self::$output);
// Render the final output
self::render(self::$output);
}
/**
* Inserts global Kohana variables into the generated output and prints it.
*
* @param string final output that will displayed
* @return void
*/
public static function render($output)
{
if (self::config('core.render_stats') === TRUE)
{
// Fetch memory usage in MB
$memory = function_exists('memory_get_usage') ? (memory_get_usage() / 1024 / 1024) : 0;
// Fetch benchmark for page execution time
$benchmark = Benchmark::get(SYSTEM_BENCHMARK.'_total_execution');
// Replace the global template variables
$output = str_replace(
array
(
'{kohana_version}',
'{kohana_codename}',
'{execution_time}',
'{memory_usage}',
'{included_files}',
),
array
(
KOHANA_VERSION,
KOHANA_CODENAME,
$benchmark['time'],
number_format($memory, 2).'MB',
count(get_included_files()),
),
$output
);
}
if ($level = self::config('core.output_compression') AND ini_get('output_handler') !== 'ob_gzhandler' AND (int) ini_get('zlib.output_compression') === 0)
{
if ($level < 1 OR $level > 9)
{
// Normalize the level to be an integer between 1 and 9. This
// step must be done to prevent gzencode from triggering an error
$level = max(1, min($level, 9));
}
if (stripos(@$_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
{
$compress = 'gzip';
}
elseif (stripos(@$_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') !== FALSE)
{
$compress = 'deflate';
}
}
if (isset($compress) AND $level > 0)
{
switch ($compress)
{
case 'gzip':
// Compress output using gzip
$output = gzencode($output, $level);
break;
case 'deflate':
// Compress output using zlib (HTTP deflate)
$output = gzdeflate($output, $level);
break;
}
// This header must be sent with compressed content to prevent
// browser caches from breaking
header('Vary: Accept-Encoding');
// Send the content encoding header
header('Content-Encoding: '.$compress);
// Sending Content-Length in CGI can result in unexpected behavior
if (stripos(PHP_SAPI, 'cgi') === FALSE)
{
header('Content-Length: '.strlen($output));
}
}
echo $output;
}
/**
* Displays a 404 page.
*
* @throws Kohana_404_Exception
* @param string URI of page
* @param string custom template
* @return void
*/
public static function show_404($page = FALSE, $template = FALSE)
{
throw new Kohana_404_Exception($page, $template);
}
/**
* Dual-purpose PHP error and exception handler. Uses the kohana_error_page
* view to display the message.
*
* @param integer|object exception object or error code
* @param string error message
* @param string filename
* @param integer line number
* @return void
*/
public static function exception_handler($exception, $message = NULL, $file = NULL, $line = NULL)
{
try
{
// PHP errors have 5 args, always
$PHP_ERROR = (func_num_args() === 5);
// Test to see if errors should be displayed
if ($PHP_ERROR AND (error_reporting() & $exception) === 0)
return;
// This is useful for hooks to determine if a page has an error
self::$has_error = TRUE;
// Error handling will use exactly 5 args, every time
if ($PHP_ERROR)
{
$code = $exception;
$type = 'PHP Error';
$template = 'kohana_error_page';
}
else
{
$code = $exception->getCode();
$type = get_class($exception);
$message = $exception->getMessage();
$file = $exception->getFile();
$line = $exception->getLine();
$template = ($exception instanceof Kohana_Exception) ? $exception->getTemplate() : 'kohana_error_page';
}
if (is_numeric($code))
{
$codes = self::lang('errors');
if ( ! empty($codes[$code]))
{
list($level, $error, $description) = $codes[$code];
}
else
{
$level = 1;
$error = $PHP_ERROR ? 'Unknown Error' : get_class($exception);
$description = '';
}
}
else
{
// Custom error message, this will never be logged
$level = 5;
$error = $code;
$description = '';
}
// Remove the DOCROOT from the path, as a security precaution
$file = str_replace('\\', '/', realpath($file));
$file = preg_replace('|^'.preg_quote(DOCROOT).'|', '', $file);
if ($level <= self::$configuration['core']['log_threshold'])
{
// Log the error
self::log('error', self::lang('core.uncaught_exception', $type, $message, $file, $line));
}
if ($PHP_ERROR)
{
$description = self::lang('errors.'.E_RECOVERABLE_ERROR);
$description = is_array($description) ? $description[2] : '';
if ( ! headers_sent())
{
// Send the 500 header
header('HTTP/1.1 500 Internal Server Error');
}
}
else
{
if (method_exists($exception, 'sendHeaders') AND ! headers_sent())
{
// Send the headers if they have not already been sent
$exception->sendHeaders();
}
}
// Close all output buffers except for Kohana
while (ob_get_level() > self::$buffer_level)
{
ob_end_clean();
}
// Test if display_errors is on
if (self::$configuration['core']['display_errors'] === TRUE)
{
if ( ! IN_PRODUCTION AND $line != FALSE)
{
// Remove the first entry of debug_backtrace(), it is the exception_handler call
$trace = $PHP_ERROR ? array_slice(debug_backtrace(), 1) : $exception->getTrace();
// Beautify backtrace
$trace = self::backtrace($trace);
}
// Load the error
require self::find_file('views', empty($template) ? 'kohana_error_page' : $template);
}
else
{
// Get the i18n messages
$error = self::lang('core.generic_error');
$message = self::lang('core.errors_disabled', url::site(), url::site(Router::$current_uri));
// Load the errors_disabled view
require self::find_file('views', 'kohana_error_disabled');
}
if ( ! Event::has_run('system.shutdown'))
{
// Run the shutdown even to ensure a clean exit
Event::run('system.shutdown');
}
// Turn off error reporting
error_reporting(0);
exit;
}
catch (Exception $e)
{
if (IN_PRODUCTION)
{
die('Fatal Error');
}
else
{
die('Fatal Error: '.$e->getMessage().' File: '.$e->getFile().' Line: '.$e->getLine());
}
}
}
/**
* Provides class auto-loading.
*
* @throws Kohana_Exception
* @param string name of class
* @return bool
*/
public static function auto_load($class)
{
if (class_exists($class, FALSE))
return TRUE;
if (($suffix = strrpos($class, '_')) > 0)
{
// Find the class suffix
$suffix = substr($class, $suffix + 1);
}
else
{
// No suffix
$suffix = FALSE;
}
if ($suffix === 'Core')
{
$type = 'libraries';
$file = substr($class, 0, -5);
}
elseif ($suffix === 'Controller')
{
$type = 'controllers';
// Lowercase filename
$file = strtolower(substr($class, 0, -11));
}
elseif ($suffix === 'Model')
{
$type = 'models';
// Lowercase filename
$file = strtolower(substr($class, 0, -6));
}
elseif ($suffix === 'Driver')
{
$type = 'libraries/drivers';
$file = str_replace('_', '/', substr($class, 0, -7));
}
else
{
// This could be either a library or a helper, but libraries must
// always be capitalized, so we check if the first character is
// uppercase. If it is, we are loading a library, not a helper.
$type = ($class[0] < 'a') ? 'libraries' : 'helpers';
$file = $class;
}
if ($filename = self::find_file($type, $file))
{
// Load the class
require $filename;
}
else
{
// The class could not be found
return FALSE;
}
if ($filename = self::find_file($type, self::$configuration['core']['extension_prefix'].$class))
{
// Load the class extension
require $filename;
}
elseif ($suffix !== 'Core' AND class_exists($class.'_Core', FALSE))
{
// Class extension to be evaluated
$extension = 'class '.$class.' extends '.$class.'_Core { }';
// Start class analysis
$core = new ReflectionClass($class.'_Core');
if ($core->isAbstract())
{
// Make the extension abstract
$extension = 'abstract '.$extension;
}
// Transparent class extensions are handled using eval. This is
// a disgusting hack, but it gets the job done.
eval($extension);
}
return TRUE;
}
/**
* Find a resource file in a given directory. Files will be located according
* to the order of the include paths. Configuration and i18n files will be
* returned in reverse order.
*
* @throws Kohana_Exception if file is required and not found
* @param string directory to search in
* @param string filename to look for (without extension)
* @param boolean file required
* @param string file extension
* @return array if the type is config, i18n or l10n
* @return string if the file is found
* @return FALSE if the file is not found
*/
public static function find_file($directory, $filename, $required = FALSE, $ext = FALSE)
{
// NOTE: This test MUST be not be a strict comparison (===), or empty
// extensions will be allowed!
if ($ext == '')
{
// Use the default extension
$ext = EXT;
}
else
{
// Add a period before the extension
$ext = '.'.$ext;
}
// Search path
$search = $directory.'/'.$filename.$ext;
if (isset(self::$internal_cache['find_file_paths'][$search]))
return self::$internal_cache['find_file_paths'][$search];
// Load include paths
$paths = self::$include_paths;
// Nothing found, yet
$found = NULL;
if ($directory === 'config' OR $directory === 'i18n')
{
// Search in reverse, for merging
$paths = array_reverse($paths);
foreach ($paths as $path)
{
if (is_file($path.$search))
{
// A matching file has been found
$found[] = $path.$search;
}
}
}
else
{
foreach ($paths as $path)
{
if (is_file($path.$search))
{
// A matching file has been found
$found = $path.$search;
// Stop searching
break;
}
}
}
if ($found === NULL)
{
if ($required === TRUE)
{
// Directory i18n key
$directory = 'core.'.inflector::singular($directory);
// If the file is required, throw an exception
throw new Kohana_Exception('core.resource_not_found', self::lang($directory), $filename);
}
else
{
// Nothing was found, return FALSE
$found = FALSE;
}
}
if ( ! isset(self::$write_cache['find_file_paths']))
{
// Write cache at shutdown
self::$write_cache['find_file_paths'] = TRUE;
}
return self::$internal_cache['find_file_paths'][$search] = $found;
}
/**
* Lists all files and directories in a resource path.
*
* @param string directory to search
* @param boolean list all files to the maximum depth?
* @param string full path to search (used for recursion, *never* set this manually)
* @return array filenames and directories
*/
public static function list_files($directory, $recursive = FALSE, $path = FALSE)
{
$files = array();
if ($path === FALSE)
{
$paths = array_reverse(self::include_paths());
foreach ($paths as $path)
{
// Recursively get and merge all files
$files = array_merge($files, self::list_files($directory, $recursive, $path.$directory));
}
}
else
{
$path = rtrim($path, '/').'/';
if (is_readable($path))
{
$items = (array) glob($path.'*');
if ( ! empty($items))
{
foreach ($items as $index => $item)
{
$files[] = $item = str_replace('\\', '/', $item);
// Handle recursion
if (is_dir($item) AND $recursive == TRUE)
{
// Filename should only be the basename
$item = pathinfo($item, PATHINFO_BASENAME);
// Append sub-directory search
$files = array_merge($files, self::list_files($directory, TRUE, $path.$item));
}
}
}
}
}
return $files;
}
/**
* Fetch an i18n language item.
*
* @param string language key to fetch
* @param array additional information to insert into the line
* @return string i18n language string, or the requested key if the i18n item is not found
*/
public static function lang($key, $args = array())
{
// Extract the main group from the key
$group = explode('.', $key, 2);
$group = $group[0];
// Get locale name
$locale = self::config('locale.language.0');
if ( ! isset(self::$internal_cache['language'][$locale][$group]))
{
// Messages for this group
$messages = array();
if ($files = self::find_file('i18n', $locale.'/'.$group))
{
foreach ($files as $file)
{
include $file;
// Merge in configuration
if ( ! empty($lang) AND is_array($lang))
{
foreach ($lang as $k => $v)
{
$messages[$k] = $v;
}
}
}
}
if ( ! isset(self::$write_cache['language']))
{
// Write language cache
self::$write_cache['language'] = TRUE;
}
self::$internal_cache['language'][$locale][$group] = $messages;
}
// Get the line from cache
$line = self::key_string(self::$internal_cache['language'][$locale], $key);
if ($line === NULL)
{
self::log('error', 'Missing i18n entry '.$key.' for language '.$locale);
// Return the key string as fallback
return $key;
}
if (is_string($line) AND func_num_args() > 1)
{
$args = array_slice(func_get_args(), 1);
// Add the arguments into the line
$line = vsprintf($line, is_array($args[0]) ? $args[0] : $args);
}
return $line;
}
/**
* Returns the value of a key, defined by a 'dot-noted' string, from an array.
*
* @param array array to search
* @param string dot-noted string: foo.bar.baz
* @return string if the key is found
* @return void if the key is not found
*/
public static function key_string($array, $keys)
{
if (empty($array))
return NULL;
// Prepare for loop
$keys = explode('.', $keys);
do
{
// Get the next key
$key = array_shift($keys);
if (isset($array[$key]))
{
if (is_array($array[$key]) AND ! empty($keys))
{
// Dig down to prepare the next loop
$array = $array[$key];
}
else
{
// Requested key was found
return $array[$key];
}
}
else
{
// Requested key is not set
break;
}
}
while ( ! empty($keys));
return NULL;
}
/**
* Sets values in an array by using a 'dot-noted' string.
*
* @param array array to set keys in (reference)
* @param string dot-noted string: foo.bar.baz
* @return mixed fill value for the key
* @return void
*/
public static function key_string_set( & $array, $keys, $fill = NULL)
{
if (is_object($array) AND ($array instanceof ArrayObject))
{
// Copy the array
$array_copy = $array->getArrayCopy();
// Is an object
$array_object = TRUE;
}
else
{
if ( ! is_array($array))
{
// Must always be an array
$array = (array) $array;
}
// Copy is a reference to the array
$array_copy =& $array;
}
if (empty($keys))
return $array;
// Create keys
$keys = explode('.', $keys);
// Create reference to the array
$row =& $array_copy;
for ($i = 0, $end = count($keys) - 1; $i <= $end; $i++)
{
// Get the current key
$key = $keys[$i];
if ( ! isset($row[$key]))
{
if (isset($keys[$i + 1]))
{
// Make the value an array
$row[$key] = array();
}
else
{
// Add the fill key
$row[$key] = $fill;
}
}
elseif (isset($keys[$i + 1]))
{
// Make the value an array
$row[$key] = (array) $row[$key];
}
// Go down a level, creating a new row reference
$row =& $row[$key];
}
if (isset($array_object))
{
// Swap the array back in
$array->exchangeArray($array_copy);
}
}
/**
* Retrieves current user agent information:
* keys: browser, version, platform, mobile, robot, referrer, languages, charsets
* tests: is_browser, is_mobile, is_robot, accept_lang, accept_charset
*
* @param string key or test name
* @param string used with "accept" tests: user_agent(accept_lang, en)
* @return array languages and charsets
* @return string all other keys
* @return boolean all tests
*/
public static function user_agent($key = 'agent', $compare = NULL)
{
static $info;
// Return the raw string
if ($key === 'agent')
return self::$user_agent;
if ($info === NULL)
{
// Parse the user agent and extract basic information
$agents = self::config('user_agents');
foreach ($agents as $type => $data)
{
foreach ($data as $agent => $name)
{
if (stripos(self::$user_agent, $agent) !== FALSE)
{
if ($type === 'browser' AND preg_match('|'.preg_quote($agent).'[^0-9.]*+([0-9.][0-9.a-z]*)|i', self::$user_agent, $match))
{
// Set the browser version
$info['version'] = $match[1];
}
// Set the agent name
$info[$type] = $name;
break;
}
}
}
}
if (empty($info[$key]))
{
switch ($key)
{
case 'is_robot':
case 'is_browser':
case 'is_mobile':
// A boolean result
$return = ! empty($info[substr($key, 3)]);
break;
case 'languages':
$return = array();
if ( ! empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
{
if (preg_match_all('/[-a-z]{2,}/', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])), $matches))
{
// Found a result
$return = $matches[0];
}
}
break;
case 'charsets':
$return = array();
if ( ! empty($_SERVER['HTTP_ACCEPT_CHARSET']))
{
if (preg_match_all('/[-a-z0-9]{2,}/', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET'])), $matches))
{
// Found a result
$return = $matches[0];
}
}
break;
case 'referrer':
if ( ! empty($_SERVER['HTTP_REFERER']))
{
// Found a result
$return = trim($_SERVER['HTTP_REFERER']);
}
break;
}
// Cache the return value
isset($return) and $info[$key] = $return;
}
if ( ! empty($compare))
{
// The comparison must always be lowercase
$compare = strtolower($compare);
switch ($key)
{
case 'accept_lang':
// Check if the lange is accepted
return in_array($compare, self::user_agent('languages'));
break;
case 'accept_charset':
// Check if the charset is accepted
return in_array($compare, self::user_agent('charsets'));
break;
default:
// Invalid comparison
return FALSE;
break;
}
}
// Return the key, if set
return isset($info[$key]) ? $info[$key] : NULL;
}
/**
* Quick debugging of any variable. Any number of parameters can be set.
*
* @return string
*/
public static function debug()
{
if (func_num_args() === 0)
return;
// Get params
$params = func_get_args();
$output = array();
foreach ($params as $var)
{
$output[] = '<pre>('.gettype($var).') '.html::specialchars(print_r($var, TRUE)).'</pre>';
}
return implode("\n", $output);
}
/**
* Displays nice backtrace information.
* @see http://php.net/debug_backtrace
*
* @param array backtrace generated by an exception or debug_backtrace
* @return string
*/
public static function backtrace($trace)
{
if ( ! is_array($trace))
return;
// Final output
$output = array();
foreach ($trace as $entry)
{
$temp = '<li>';
if (isset($entry['file']))
{
$temp .= self::lang('core.error_file_line', preg_replace('!^'.preg_quote(DOCROOT).'!', '', $entry['file']), $entry['line']);
}
$temp .= '<pre>';
if (isset($entry['class']))
{
// Add class and call type
$temp .= $entry['class'].$entry['type'];
}
// Add function
$temp .= $entry['function'].'( ';
// Add function args
if (isset($entry['args']) AND is_array($entry['args']))
{
// Separator starts as nothing
$sep = '';
while ($arg = array_shift($entry['args']))
{
if (is_string($arg) AND is_file($arg))
{
// Remove docroot from filename
$arg = preg_replace('!^'.preg_quote(DOCROOT).'!', '', $arg);
}
$temp .= $sep.html::specialchars(print_r($arg, TRUE));
// Change separator to a comma
$sep = ', ';
}
}
$temp .= ' )</pre></li>';
$output[] = $temp;
}
return '<ul class="backtrace">'.implode("\n", $output).'</ul>';
}
/**
* Saves the internal caches: configuration, include paths, etc.
*
* @return boolean
*/
public static function internal_cache_save()
{
if ( ! is_array(self::$write_cache))
return FALSE;
// Get internal cache names
$caches = array_keys(self::$write_cache);
// Nothing written
$written = FALSE;
foreach ($caches as $cache)
{
if (isset(self::$internal_cache[$cache]))
{
// Write the cache file
self::cache_save($cache, self::$internal_cache[$cache], self::$configuration['core']['internal_cache']);
// A cache has been written
$written = TRUE;
}
}
return $written;
}
} // End Kohana
/**
* Creates a generic i18n exception.
*/
class Kohana_Exception extends Exception {
// Template file
protected $template = 'kohana_error_page';
// Header
protected $header = FALSE;
// Error code
protected $code = E_KOHANA;
/**
* Set exception message.
*
* @param string i18n language key for the message
* @param array addition line parameters
*/
public function __construct($error)
{
$args = array_slice(func_get_args(), 1);
// Fetch the error message
$message = Kohana::lang($error, $args);
if ($message === $error OR empty($message))
{
// Unable to locate the message for the error
$message = 'Unknown Exception: '.$error;
}
// Sets $this->message the proper way
parent::__construct($message);
}
/**
* Magic method for converting an object to a string.
*
* @return string i18n message
*/
public function __toString()
{
return (string) $this->message;
}
/**
* Fetch the template name.
*
* @return string
*/
public function getTemplate()
{
return $this->template;
}
/**
* Sends an Internal Server Error header.
*
* @return void
*/
public function sendHeaders()
{
// Send the 500 header
header('HTTP/1.1 500 Internal Server Error');
}
} // End Kohana Exception
/**
* Creates a custom exception.
*/
class Kohana_User_Exception extends Kohana_Exception {
/**
* Set exception title and message.
*
* @param string exception title string
* @param string exception message string
* @param string custom error template
*/
public function __construct($title, $message, $template = FALSE)
{
Exception::__construct($message);
$this->code = $title;
if ($template !== FALSE)
{
$this->template = $template;
}
}
} // End Kohana PHP Exception
/**
* Creates a Page Not Found exception.
*/
class Kohana_404_Exception extends Kohana_Exception {
protected $code = E_PAGE_NOT_FOUND;
/**
* Set internal properties.
*
* @param string URL of page
* @param string custom error template
*/
public function __construct($page = FALSE, $template = FALSE)
{
if ($page === FALSE)
{
// Construct the page URI using Router properties
$page = Router::$current_uri.Router::$url_suffix.Router::$query_string;
}
Exception::__construct(Kohana::lang('core.page_not_found', $page));
$this->template = $template;
}
/**
* Sends "File Not Found" headers, to emulate server behavior.
*
* @return void
*/
public function sendHeaders()
{
// Send the 404 header
header('HTTP/1.1 404 File Not Found');
}
} // End Kohana 404 Exception
|