-
Notifications
You must be signed in to change notification settings - Fork 144
/
WCF.class.php
1052 lines (913 loc) · 29.1 KB
/
WCF.class.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
namespace wcf\system;
use wcf\data\application\Application;
use wcf\data\option\OptionEditor;
use wcf\data\package\Package;
use wcf\data\package\PackageCache;
use wcf\data\package\PackageEditor;
use wcf\data\page\Page;
use wcf\data\page\PageCache;
use wcf\page\CmsPage;
use wcf\system\application\ApplicationHandler;
use wcf\system\application\IApplication;
use wcf\system\box\BoxHandler;
use wcf\system\cache\builder\CoreObjectCacheBuilder;
use wcf\system\cache\builder\PackageUpdateCacheBuilder;
use wcf\system\cronjob\CronjobScheduler;
use wcf\system\database\MySQLDatabase;
use wcf\system\event\EventHandler;
use wcf\system\exception\AJAXException;
use wcf\system\exception\ErrorException;
use wcf\system\exception\IPrintableException;
use wcf\system\exception\NamedUserException;
use wcf\system\exception\ParentClassException;
use wcf\system\exception\PermissionDeniedException;
use wcf\system\exception\SystemException;
use wcf\system\language\LanguageFactory;
use wcf\system\package\PackageInstallationDispatcher;
use wcf\system\request\Request;
use wcf\system\request\RequestHandler;
use wcf\system\session\SessionFactory;
use wcf\system\session\SessionHandler;
use wcf\system\style\StyleHandler;
use wcf\system\template\EmailTemplateEngine;
use wcf\system\template\TemplateEngine;
use wcf\system\user\storage\UserStorageHandler;
use wcf\util\FileUtil;
use wcf\util\HeaderUtil;
use wcf\util\StringUtil;
use wcf\util\UserUtil;
// try to set a time-limit to infinite
@set_time_limit(0);
// fix timezone warning issue
if (!@ini_get('date.timezone')) {
@date_default_timezone_set('Europe/London');
}
// define current woltlab suite version
define('WCF_VERSION', '3.1.0 Alpha 2');
// define current unix timestamp
define('TIME_NOW', time());
// wcf imports
if (!defined('NO_IMPORTS')) {
require_once(WCF_DIR.'lib/core.functions.php');
require_once(WCF_DIR.'lib/system/api/autoload.php');
}
/**
* WCF is the central class for the WoltLab Suite Core.
* It holds the database connection, access to template and language engine.
*
* @author Marcel Werk
* @copyright 2001-2017 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System
*/
class WCF {
/**
* list of currently loaded applications
* @var Application[]
*/
protected static $applications = [];
/**
* list of currently loaded application objects
* @var IApplication[]
*/
protected static $applicationObjects = [];
/**
* list of autoload directories
* @var array
*/
protected static $autoloadDirectories = [];
/**
* list of unique instances of each core object
* @var SingletonFactory[]
*/
protected static $coreObject = [];
/**
* list of cached core objects
* @var string[]
*/
protected static $coreObjectCache = [];
/**
* database object
* @var MySQLDatabase
*/
protected static $dbObj = null;
/**
* language object
* @var \wcf\data\language\Language
*/
protected static $languageObj = null;
/**
* overrides disabled debug mode
* @var boolean
*/
protected static $overrideDebugMode = false;
/**
* session object
* @var SessionHandler
*/
protected static $sessionObj = null;
/**
* template object
* @var TemplateEngine
*/
protected static $tplObj = null;
/**
* true if Zend Opcache is loaded and enabled
* @var boolean
*/
protected static $zendOpcacheEnabled = null;
/**
* force logout during destructor call
* @var boolean
*/
protected static $forceLogout = false;
/**
* Calls all init functions of the WCF class.
*/
public function __construct() {
// add autoload directory
self::$autoloadDirectories['wcf'] = WCF_DIR . 'lib/';
// define tmp directory
if (!defined('TMP_DIR')) define('TMP_DIR', FileUtil::getTempFolder());
// start initialization
$this->initDB();
$this->loadOptions();
$this->initSession();
$this->initLanguage();
$this->initTPL();
$this->initCronjobs();
$this->initCoreObjects();
$this->initApplications();
$this->initBlacklist();
EventHandler::getInstance()->fireAction($this, 'initialized');
}
/**
* Flushes the output, closes the session, performs background tasks and more.
*
* You *must* not create output in here under normal circumstances, as it might get eaten
* when gzip is enabled.
*/
public static function destruct() {
try {
// database has to be initialized
if (!is_object(self::$dbObj)) return;
$debug = self::debugModeIsEnabled(true);
if (!$debug) {
// flush output
if (ob_get_level()) ob_end_flush();
flush();
// close connection if using FPM
if (function_exists('fastcgi_finish_request')) fastcgi_finish_request();
}
// update session
if (is_object(self::getSession())) {
if (self::$forceLogout) {
// do logout
self::getSession()->delete();
}
else {
self::getSession()->update();
}
}
// execute shutdown actions of user storage handler
UserStorageHandler::getInstance()->shutdown();
}
catch (\Exception $exception) {
die("<pre>WCF::destruct() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
}
}
/**
* Returns the database object.
*
* @return \wcf\system\database\Database
*/
public static final function getDB() {
return self::$dbObj;
}
/**
* Returns the session object.
*
* @return SessionHandler
*/
public static final function getSession() {
return self::$sessionObj;
}
/**
* Returns the user object.
*
* @return \wcf\data\user\User
*/
public static final function getUser() {
return self::getSession()->getUser();
}
/**
* Returns the language object.
*
* @return \wcf\data\language\Language
*/
public static final function getLanguage() {
return self::$languageObj;
}
/**
* Returns the template object.
*
* @return TemplateEngine
*/
public static final function getTPL() {
return self::$tplObj;
}
/**
* Calls the show method on the given exception.
*
* @param \Exception $e
*/
public static final function handleException($e) {
if (ob_get_level()) {
// discard any output generated before the exception occurred, prevents exception
// being hidden inside HTML elements and therefore not visible in browser output
//
// ob_get_level() can return values > 1, if the PHP setting `output_buffering` is on
while (ob_get_level()) ob_end_clean();
// `identity` is the default "encoding" and basically means that the client
// must treat the content as if the header did not appear in first place, this
// also overrules the gzip header if present
@header('Content-Encoding: identity');
HeaderUtil::exceptionDisableGzip();
}
// backwards compatibility
if ($e instanceof IPrintableException) {
$e->show();
exit;
}
@header('HTTP/1.1 503 Service Unavailable');
try {
\wcf\functions\exception\printThrowable($e);
}
catch (\Throwable $e2) {
echo "<pre>An Exception was thrown while handling an Exception:\n\n";
echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e2);
echo "\n\nwas thrown while:\n\n";
echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e);
echo "\n\nwas handled.</pre>";
exit;
}
catch (\Exception $e2) {
echo "<pre>An Exception was thrown while handling an Exception:\n\n";
echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e2);
echo "\n\nwas thrown while:\n\n";
echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e);
echo "\n\nwas handled.</pre>";
exit;
}
}
/**
* Turns PHP errors into an ErrorException.
*
* @param integer $severity
* @param string $message
* @param string $file
* @param integer $line
* @throws ErrorException
*/
public static final function handleError($severity, $message, $file, $line) {
// this is necessary for the shut-up operator
if (error_reporting() == 0) return;
throw new ErrorException($message, 0, $severity, $file, $line);
}
/**
* Loads the database configuration and creates a new connection to the database.
*/
protected function initDB() {
// get configuration
$dbHost = $dbUser = $dbPassword = $dbName = '';
$dbPort = 0;
require(WCF_DIR.'config.inc.php');
// create database connection
self::$dbObj = new MySQLDatabase($dbHost, $dbUser, $dbPassword, $dbName, $dbPort);
}
/**
* Loads the options file, automatically created if not exists.
*/
protected function loadOptions() {
$filename = WCF_DIR.'options.inc.php';
// create options file if doesn't exist
if (!file_exists($filename) || filemtime($filename) <= 1) {
OptionEditor::rebuild();
}
require_once($filename);
// check if option file is complete and writable
if (PACKAGE_ID) {
if (!is_writable($filename)) {
FileUtil::makeWritable($filename);
if (!is_writable($filename)) {
throw new SystemException("The option file '" . $filename . "' is not writable.");
}
}
// check if a previous write operation was incomplete and force rebuilding
if (!defined('WCF_OPTION_INC_PHP_SUCCESS')) {
OptionEditor::rebuild();
require_once($filename);
}
}
}
/**
* Starts the session system.
*/
protected function initSession() {
$factory = new SessionFactory();
$factory->load();
self::$sessionObj = SessionHandler::getInstance();
self::$sessionObj->setHasValidCookie($factory->hasValidCookie());
}
/**
* Initialises the language engine.
*/
protected function initLanguage() {
if (isset($_GET['l']) && !self::getUser()->userID) {
self::getSession()->setLanguageID(intval($_GET['l']));
}
// set mb settings
mb_internal_encoding('UTF-8');
if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
mb_language('uni');
// get language
self::$languageObj = LanguageFactory::getInstance()->getUserLanguage(self::getSession()->getLanguageID());
}
/**
* Initialises the template engine.
*/
protected function initTPL() {
self::$tplObj = TemplateEngine::getInstance();
self::getTPL()->setLanguageID(self::getLanguage()->languageID);
$this->assignDefaultTemplateVariables();
$this->initStyle();
}
/**
* Initializes the user's style.
*/
protected function initStyle() {
if (isset($_REQUEST['styleID'])) {
self::getSession()->setStyleID(intval($_REQUEST['styleID']));
}
$styleHandler = StyleHandler::getInstance();
$styleHandler->changeStyle(self::getSession()->getStyleID());
}
/**
* Executes the blacklist.
*/
protected function initBlacklist() {
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
if (defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES != '') {
if (!StringUtil::executeWordFilter(UserUtil::convertIPv6To4(self::getSession()->ipAddress), BLACKLIST_IP_ADDRESSES)) {
if ($isAjax) {
throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
}
else {
throw new PermissionDeniedException();
}
}
else if (!StringUtil::executeWordFilter(self::getSession()->ipAddress, BLACKLIST_IP_ADDRESSES)) {
if ($isAjax) {
throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
}
else {
throw new PermissionDeniedException();
}
}
}
if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS != '') {
if (!StringUtil::executeWordFilter(self::getSession()->userAgent, BLACKLIST_USER_AGENTS)) {
if ($isAjax) {
throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
}
else {
throw new PermissionDeniedException();
}
}
}
if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES != '') {
if (!StringUtil::executeWordFilter(@gethostbyaddr(self::getSession()->ipAddress), BLACKLIST_HOSTNAMES)) {
if ($isAjax) {
throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
}
else {
throw new PermissionDeniedException();
}
}
}
// handle banned users
if (self::getUser()->userID && self::getUser()->banned) {
if ($isAjax) {
throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'), AJAXException::INSUFFICIENT_PERMISSIONS);
}
else {
self::$forceLogout = true;
// remove cookies
if (isset($_COOKIE[COOKIE_PREFIX.'userID'])) {
HeaderUtil::setCookie('userID', 0);
}
if (isset($_COOKIE[COOKIE_PREFIX.'password'])) {
HeaderUtil::setCookie('password', '');
}
throw new NamedUserException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
}
}
}
/**
* Initializes applications.
*/
protected function initApplications() {
// step 1) load all applications
$loadedApplications = [];
// register WCF as application
self::$applications['wcf'] = ApplicationHandler::getInstance()->getApplicationByID(1);
if (!class_exists(WCFACP::class, false)) {
static::getTPL()->assign('baseHref', self::$applications['wcf']->getPageURL());
}
// start main application
$application = ApplicationHandler::getInstance()->getActiveApplication();
if ($application->packageID != 1) {
$loadedApplications[] = $this->loadApplication($application);
// register primary application
$abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
self::$applications[$abbreviation] = $application;
}
// start dependent applications
$applications = ApplicationHandler::getInstance()->getDependentApplications();
foreach ($applications as $application) {
if ($application->packageID == 1) {
// ignore WCF
continue;
}
else if ($application->isTainted) {
// ignore apps flagged for uninstallation
continue;
}
$loadedApplications[] = $this->loadApplication($application, true);
}
// step 2) run each application
if (!class_exists('wcf\system\WCFACP', false)) {
/** @var IApplication $application */
foreach ($loadedApplications as $application) {
$application->__run();
}
// refresh the session 1 minute before it expires
self::getTPL()->assign('__sessionKeepAlive', SESSION_TIMEOUT - 60);
}
}
/**
* Loads an application.
*
* @param Application $application
* @param boolean $isDependentApplication
* @return IApplication
* @throws SystemException
*/
protected function loadApplication(Application $application, $isDependentApplication = false) {
$package = PackageCache::getInstance()->getPackage($application->packageID);
// package cache might be outdated
if ($package === null) {
$package = new Package($application->packageID);
// package cache is outdated, discard cache
if ($package->packageID) {
PackageEditor::resetCache();
}
else {
// package id is invalid
throw new SystemException("application identified by package id '".$application->packageID."' is unknown");
}
}
$abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
$packageDir = FileUtil::getRealPath(WCF_DIR.$package->packageDir);
self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
$className = $abbreviation.'\system\\'.strtoupper($abbreviation).'Core';
// class was not found, possibly the app was moved, but `packageDir` has not been adjusted
if (!class_exists($className)) {
// check if both the Core and the app are on the same domain
$coreApp = ApplicationHandler::getInstance()->getApplicationByID(1);
if ($coreApp->domainName === $application->domainName) {
// resolve the relative path and use it to construct the autoload directory
$relativePath = FileUtil::getRelativePath($coreApp->domainPath, $application->domainPath);
if ($relativePath !== './') {
$packageDir = FileUtil::getRealPath(WCF_DIR.$relativePath);
self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
if (class_exists($className)) {
// the class can now be found, update the `packageDir` value
(new PackageEditor($package))->update(['packageDir' => $relativePath]);
}
}
}
}
if (class_exists($className) && is_subclass_of($className, IApplication::class)) {
// include config file
$configPath = $packageDir . PackageInstallationDispatcher::CONFIG_FILE;
if (!file_exists($configPath)) {
Package::writeConfigFile($package->packageID);
}
if (file_exists($configPath)) {
require_once($configPath);
}
else {
throw new SystemException('Unable to load configuration for '.$package->package);
}
// register template path if not within ACP
if (!class_exists('wcf\system\WCFACP', false)) {
// add template path and abbreviation
static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
}
EmailTemplateEngine::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
// init application and assign it as template variable
self::$applicationObjects[$application->packageID] = call_user_func([$className, 'getInstance']);
static::getTPL()->assign('__'.$abbreviation, self::$applicationObjects[$application->packageID]);
EmailTemplateEngine::getInstance()->assign('__'.$abbreviation, self::$applicationObjects[$application->packageID]);
}
else {
unset(self::$autoloadDirectories[$abbreviation]);
throw new SystemException("Unable to run '".$package->package."', '".$className."' is missing or does not implement '".IApplication::class."'.");
}
// register template path in ACP
if (class_exists('wcf\system\WCFACP', false)) {
static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
}
else if (!$isDependentApplication) {
// assign base tag
static::getTPL()->assign('baseHref', $application->getPageURL());
}
// register application
self::$applications[$abbreviation] = $application;
return self::$applicationObjects[$application->packageID];
}
/**
* Returns the corresponding application object. Does not support the 'wcf' pseudo application.
*
* @param Application $application
* @return IApplication
*/
public static function getApplicationObject(Application $application) {
if (isset(self::$applicationObjects[$application->packageID])) {
return self::$applicationObjects[$application->packageID];
}
return null;
}
/**
* Loads an application on runtime, do not use this outside the package installation.
*
* @param integer $packageID
*/
public static function loadRuntimeApplication($packageID) {
$package = new Package($packageID);
$application = new Application($packageID);
$abbreviation = Package::getAbbreviation($package->package);
$packageDir = FileUtil::getRealPath(WCF_DIR.$package->packageDir);
self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
self::$applications[$abbreviation] = $application;
self::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
}
/**
* Initializes core object cache.
*/
protected function initCoreObjects() {
// ignore core objects if installing WCF
if (PACKAGE_ID == 0) {
return;
}
self::$coreObjectCache = CoreObjectCacheBuilder::getInstance()->getData();
}
/**
* Assigns some default variables to the template engine.
*/
protected function assignDefaultTemplateVariables() {
self::getTPL()->registerPrefilter(['event', 'hascontent', 'lang']);
self::getTPL()->assign([
'__wcf' => $this,
'__wcfVersion' => LAST_UPDATE_TIME // @deprecated 2.1, use LAST_UPDATE_TIME directly
]);
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
// Execute background queue in this request, if it was requested and AJAX isn't used.
if (!$isAjax) {
if (self::getSession()->getVar('forceBackgroundQueuePerform')) {
self::getTPL()->assign([
'forceBackgroundQueuePerform' => true
]);
self::getSession()->unregister('forceBackgroundQueuePerform');
}
}
EmailTemplateEngine::getInstance()->registerPrefilter(['event', 'hascontent', 'lang']);
EmailTemplateEngine::getInstance()->assign([
'__wcf' => $this
]);
}
/**
* Wrapper for the getter methods of this class.
*
* @param string $name
* @return mixed value
* @throws SystemException
*/
public function __get($name) {
$method = 'get'.ucfirst($name);
if (method_exists($this, $method)) {
return $this->$method();
}
throw new SystemException("method '".$method."' does not exist in class WCF");
}
/**
* Returns true if current application (WCF) is treated as active and was invoked directly.
*
* @return boolean
*/
public function isActiveApplication() {
return (ApplicationHandler::getInstance()->getActiveApplication()->packageID == 1);
}
/**
* Changes the active language.
*
* @param integer $languageID
*/
public static final function setLanguage($languageID) {
if (!$languageID || LanguageFactory::getInstance()->getLanguage($languageID) === null) {
$languageID = LanguageFactory::getInstance()->getDefaultLanguageID();
}
self::$languageObj = LanguageFactory::getInstance()->getLanguage($languageID);
self::getTPL()->setLanguageID(self::getLanguage()->languageID);
EmailTemplateEngine::getInstance()->setLanguageID(self::getLanguage()->languageID);
}
/**
* Includes the required util or exception classes automatically.
*
* @param string $className
* @see spl_autoload_register()
*/
public static final function autoload($className) {
$namespaces = explode('\\', $className);
if (count($namespaces) > 1) {
$applicationPrefix = array_shift($namespaces);
if ($applicationPrefix === '') {
$applicationPrefix = array_shift($namespaces);
}
if (isset(self::$autoloadDirectories[$applicationPrefix])) {
$classPath = self::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
if (file_exists($classPath)) {
require_once($classPath);
}
}
}
}
/**
* @inheritDoc
*/
public final function __call($name, array $arguments) {
// bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
if (!method_exists($this, $name)) {
return self::__callStatic($name, $arguments);
}
return $this->$name($arguments);
}
/**
* Returns dynamically loaded core objects.
*
* @param string $name
* @param array $arguments
* @return object
* @throws SystemException
*/
public static final function __callStatic($name, array $arguments) {
$className = preg_replace('~^get~', '', $name);
if (isset(self::$coreObject[$className])) {
return self::$coreObject[$className];
}
$objectName = self::getCoreObject($className);
if ($objectName === null) {
throw new SystemException("Core object '".$className."' is unknown.");
}
if (class_exists($objectName)) {
if (!is_subclass_of($objectName, SingletonFactory::class)) {
throw new ParentClassException($objectName, SingletonFactory::class);
}
self::$coreObject[$className] = call_user_func([$objectName, 'getInstance']);
return self::$coreObject[$className];
}
}
/**
* Searches for cached core object definition.
*
* @param string $className
* @return string
*/
protected static final function getCoreObject($className) {
if (isset(self::$coreObjectCache[$className])) {
return self::$coreObjectCache[$className];
}
return null;
}
/**
* Returns true if the debug mode is enabled, otherwise false.
*
* @param boolean $ignoreACP
* @return boolean
*/
public static function debugModeIsEnabled($ignoreACP = false) {
// ACP override
if (!$ignoreACP && self::$overrideDebugMode) {
return true;
}
else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE) {
return true;
}
return false;
}
/**
* Returns true if benchmarking is enabled, otherwise false.
*
* @return boolean
*/
public static function benchmarkIsEnabled() {
// benchmarking is enabled by default
if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK) return true;
return false;
}
/**
* Returns domain path for given application.
*
* @param string $abbreviation
* @return string
*/
public static function getPath($abbreviation = 'wcf') {
// workaround during WCFSetup
if (!PACKAGE_ID) {
return '../';
}
if (!isset(self::$applications[$abbreviation])) {
$abbreviation = 'wcf';
}
return self::$applications[$abbreviation]->getPageURL();
}
/**
* Returns the domain path for the currently active application,
* used to avoid CORS requests.
*
* @return string
*/
public static function getActivePath() {
if (!PACKAGE_ID) {
return self::getPath();
}
return self::getPath(ApplicationHandler::getInstance()->getAbbreviation(ApplicationHandler::getInstance()->getActiveApplication()->packageID));
}
/**
* Returns a fully qualified anchor for current page.
*
* @param string $fragment
* @return string
*/
public function getAnchor($fragment) {
return StringUtil::encodeHTML(self::getRequestURI() . '#' . $fragment);
}
/**
* Returns the currently active page or null if unknown.
*
* @return Page|null
*/
public static function getActivePage() {
if (self::getActiveRequest() === null) {
return null;
}
if (self::getActiveRequest()->getClassName() === CmsPage::class) {
$metaData = self::getActiveRequest()->getMetaData();
if (isset($metaData['cms'])) {
return PageCache::getInstance()->getPage($metaData['cms']['pageID']);
}
return null;
}
return PageCache::getInstance()->getPageByController(self::getActiveRequest()->getClassName());
}
/**
* Returns the currently active request.
*
* @return Request
*/
public static function getActiveRequest() {
return RequestHandler::getInstance()->getActiveRequest();
}
/**
* Returns the URI of the current page.
*
* @return string
*/
public static function getRequestURI() {
return preg_replace('~^(https?://[^/]+)(?:/.*)?$~', '$1', self::getTPL()->get('baseHref')) . $_SERVER['REQUEST_URI'];
}
/**
* Resets Zend Opcache cache if installed and enabled.
*
* @param string $script
*/
public static function resetZendOpcache($script = '') {
if (self::$zendOpcacheEnabled === null) {
self::$zendOpcacheEnabled = false;
if (extension_loaded('Zend Opcache') && @ini_get('opcache.enable')) {
self::$zendOpcacheEnabled = true;
}
}
if (self::$zendOpcacheEnabled) {
if (empty($script)) {
opcache_reset();
}
else {
opcache_invalidate($script, true);
}
}
}
/**
* Returns style handler.
*
* @return StyleHandler
*/
public function getStyleHandler() {
return StyleHandler::getInstance();
}
/**
* Returns box handler.
*
* @return BoxHandler
* @since 3.0
*/
public function getBoxHandler() {
return BoxHandler::getInstance();
}
/**
* Returns number of available updates.
*
* @return integer
*/
public function getAvailableUpdates() {
$data = PackageUpdateCacheBuilder::getInstance()->getData();
return $data['updates'];
}
/**
* Returns a 8 character prefix for editor autosave.
*
* @return string
*/
public function getAutosavePrefix() {
return substr(sha1(preg_replace('~^https~', 'http', self::getPath())), 0, 8);
}
/**
* Returns the favicon URL or a base64 encoded image.
*
* @return string
*/
public function getFavicon() {
$activeApplication = ApplicationHandler::getInstance()->getActiveApplication();
$wcf = ApplicationHandler::getInstance()->getWCF();
$favicon = StyleHandler::getInstance()->getStyle()->getRelativeFavicon();
if ($activeApplication->domainName !== $wcf->domainName) {
if (file_exists(WCF_DIR.$favicon)) {
$favicon = file_get_contents(WCF_DIR.$favicon);
return 'data:image/x-icon;base64,' . base64_encode($favicon);