5 use wcf\data\application\Application
;
6 use wcf\data\option\OptionEditor
;
7 use wcf\data\package\Package
;
8 use wcf\data\package\PackageCache
;
9 use wcf\data\package\PackageEditor
;
10 use wcf\data\page\Page
;
11 use wcf\data\page\PageCache
;
13 use wcf\system\application\ApplicationHandler
;
14 use wcf\system\application\IApplication
;
15 use wcf\system\box\BoxHandler
;
16 use wcf\system\cache\builder\CoreObjectCacheBuilder
;
17 use wcf\system\cache\builder\PackageUpdateCacheBuilder
;
18 use wcf\system\cronjob\CronjobScheduler
;
19 use wcf\system\database\MySQLDatabase
;
20 use wcf\system\event\EventHandler
;
21 use wcf\system\exception\AJAXException
;
22 use wcf\system\exception\ErrorException
;
23 use wcf\system\exception\IPrintableException
;
24 use wcf\system\exception\NamedUserException
;
25 use wcf\system\exception\ParentClassException
;
26 use wcf\system\exception\PermissionDeniedException
;
27 use wcf\system\exception\SystemException
;
28 use wcf\system\language\LanguageFactory
;
29 use wcf\system\package\PackageInstallationDispatcher
;
30 use wcf\system\registry\RegistryHandler
;
31 use wcf\system\request\Request
;
32 use wcf\system\request\RequestHandler
;
33 use wcf\system\session\SessionFactory
;
34 use wcf\system\session\SessionHandler
;
35 use wcf\system\style\StyleHandler
;
36 use wcf\system\template\EmailTemplateEngine
;
37 use wcf\system\template\TemplateEngine
;
38 use wcf\system\user\storage\UserStorageHandler
;
39 use wcf\util\DirectoryUtil
;
40 use wcf\util\FileUtil
;
41 use wcf\util\HeaderUtil
;
42 use wcf\util\StringUtil
;
43 use wcf\util\UserUtil
;
45 // phpcs:disable PSR1.Files.SideEffects
47 // try to set a time-limit to infinite
50 // fix timezone warning issue
51 if (!@\
ini_get('date.timezone')) {
52 @\
date_default_timezone_set('Europe/London');
55 // define current woltlab suite version
56 \
define('WCF_VERSION', '5.4.0 Alpha 1');
58 // define current API version
60 \
define('WSC_API_VERSION', 2019);
62 // define current unix timestamp
63 \
define('TIME_NOW', \time
());
66 if (!\
defined('NO_IMPORTS')) {
67 require_once(WCF_DIR
. 'lib/core.functions.php');
68 require_once(WCF_DIR
. 'lib/system/api/autoload.php');
72 * WCF is the central class for the WoltLab Suite Core.
73 * It holds the database connection, access to template and language engine.
76 * @copyright 2001-2019 WoltLab GmbH
77 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
78 * @package WoltLabSuite\Core\System
83 * list of supported legacy API versions
87 private static $supportedLegacyApiVersions = [2017, 2018];
90 * list of currently loaded applications
93 protected static $applications = [];
96 * list of currently loaded application objects
99 protected static $applicationObjects = [];
102 * list of autoload directories
105 protected static $autoloadDirectories = [];
108 * list of unique instances of each core object
109 * @var SingletonFactory[]
111 protected static $coreObject = [];
114 * list of cached core objects
117 protected static $coreObjectCache = [];
123 protected static $dbObj;
127 * @var \wcf\data\language\Language
129 protected static $languageObj;
132 * overrides disabled debug mode
135 protected static $overrideDebugMode = false;
139 * @var SessionHandler
141 protected static $sessionObj;
145 * @var TemplateEngine
147 protected static $tplObj;
150 * true if Zend Opcache is loaded and enabled
153 protected static $zendOpcacheEnabled;
156 * force logout during destructor call
159 protected static $forceLogout = false;
162 * Calls all init functions of the WCF class.
164 public function __construct()
166 // add autoload directory
167 self
::$autoloadDirectories['wcf'] = WCF_DIR
. 'lib/';
169 // define tmp directory
170 if (!\
defined('TMP_DIR')) {
171 \
define('TMP_DIR', FileUtil
::getTempFolder());
174 // start initialization
176 $this->loadOptions();
177 $this->initSession();
178 $this->initLanguage();
180 $this->initCronjobs();
181 $this->initCoreObjects();
182 $this->initApplications();
183 $this->initBlacklist();
185 EventHandler
::getInstance()->fireAction($this, 'initialized');
189 * Flushes the output, closes the session, performs background tasks and more.
191 * You *must* not create output in here under normal circumstances, as it might get eaten
192 * when gzip is enabled.
194 public static function destruct()
197 // database has to be initialized
198 if (!\
is_object(self
::$dbObj)) {
202 $debug = self
::debugModeIsEnabled(true);
205 if (\
ob_get_level()) {
210 // close connection if using FPM
211 if (\function_exists
('fastcgi_finish_request')) {
212 fastcgi_finish_request();
217 if (\
is_object(self
::getSession())) {
218 if (self
::$forceLogout) {
220 self
::getSession()->delete();
222 self
::getSession()->update();
226 // execute shutdown actions of storage handlers
227 RegistryHandler
::getInstance()->shutdown();
228 UserStorageHandler
::getInstance()->shutdown();
229 } catch (\Exception
$exception) {
230 exit("<pre>WCF::destruct() Unhandled exception: " . $exception->getMessage() . "\n\n" . $exception->getTraceAsString());
235 * Returns the database object.
237 * @return \wcf\system\database\Database
239 final public static function getDB()
245 * Returns the session object.
247 * @return SessionHandler
249 final public static function getSession()
251 return self
::$sessionObj;
255 * Returns the user object.
257 * @return \wcf\data\user\User
259 final public static function getUser()
261 return self
::getSession()->getUser();
265 * Returns the language object.
267 * @return \wcf\data\language\Language
269 final public static function getLanguage()
271 return self
::$languageObj;
275 * Returns the template object.
277 * @return TemplateEngine
279 final public static function getTPL()
281 return self
::$tplObj;
285 * Calls the show method on the given exception.
287 * @param \Throwable $e
289 final public static function handleException($e)
291 // backwards compatibility
292 if ($e instanceof IPrintableException
) {
298 if (\
ob_get_level()) {
299 // discard any output generated before the exception occurred, prevents exception
300 // being hidden inside HTML elements and therefore not visible in browser output
302 // ob_get_level() can return values > 1, if the PHP setting `output_buffering` is on
303 while (\
ob_get_level()) {
308 @\
header('HTTP/1.1 503 Service Unavailable');
310 \wcf\functions\exception\
printThrowable($e);
311 } catch (\Throwable
$e2) {
312 echo "<pre>An Exception was thrown while handling an Exception:\n\n";
313 echo \
preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e2);
314 echo "\n\nwas thrown while:\n\n";
315 echo \
preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e);
316 echo "\n\nwas handled.</pre>";
323 * Turns PHP errors into an ErrorException.
325 * @param int $severity
326 * @param string $message
327 * @param string $file
329 * @throws ErrorException
331 final public static function handleError($severity, $message, $file, $line)
333 // this is necessary for the shut-up operator
334 if (!(\
error_reporting() & $severity)) {
338 throw new ErrorException($message, 0, $severity, $file, $line);
342 * Loads the database configuration and creates a new connection to the database.
344 protected function initDB()
347 $dbHost = $dbUser = $dbPassword = $dbName = '';
349 $defaultDriverOptions = [];
350 require(WCF_DIR
. 'config.inc.php');
352 // create database connection
353 self
::$dbObj = new MySQLDatabase(
361 $defaultDriverOptions
366 * Loads the options file, automatically created if not exists.
368 protected function loadOptions()
370 $this->defineLegacyOptions();
372 $filename = WCF_DIR
. 'options.inc.php';
374 // create options file if doesn't exist
375 if (!\file_exists
($filename) || \filemtime
($filename) <= 1) {
376 OptionEditor
::rebuild();
380 // check if option file is complete and writable
382 if (!\
is_writable($filename)) {
383 FileUtil
::makeWritable($filename);
385 if (!\
is_writable($filename)) {
386 throw new SystemException("The option file '" . $filename . "' is not writable.");
390 // check if a previous write operation was incomplete and force rebuilding
391 if (!\
defined('WCF_OPTION_INC_PHP_SUCCESS')) {
392 OptionEditor
::rebuild();
397 if (ENABLE_DEBUG_MODE
) {
398 self
::$dbObj->enableDebugMode();
404 * Defines constants for obsolete options, which were removed.
408 protected function defineLegacyOptions(): void
410 // The attachment module is always enabled since 5.2.
411 // https://github.com/WoltLab/WCF/issues/2531
412 \
define('MODULE_ATTACHMENT', 1);
414 // Users cannot react to their own content since 5.2.
415 // https://github.com/WoltLab/WCF/issues/2975
416 \
define('LIKE_ALLOW_FOR_OWN_CONTENT', 0);
417 \
define('LIKE_ENABLE_DISLIKE', 0);
419 // Thumbnails for attachments are already enabled since 5.3.
420 // https://github.com/WoltLab/WCF/pull/3444
421 \
define('ATTACHMENT_ENABLE_THUMBNAILS', 1);
423 // User markings are always applied in sidebars since 5.3.
424 // https://github.com/WoltLab/WCF/issues/3330
425 \
define('MESSAGE_SIDEBAR_ENABLE_USER_ONLINE_MARKING', 1);
427 // Password strength configuration is deprecated since 5.3.
428 \
define('REGISTER_ENABLE_PASSWORD_SECURITY_CHECK', 0);
429 \
define('REGISTER_PASSWORD_MIN_LENGTH', 0);
430 \
define('REGISTER_PASSWORD_MUST_CONTAIN_LOWER_CASE', 8);
431 \
define('REGISTER_PASSWORD_MUST_CONTAIN_UPPER_CASE', 0);
432 \
define('REGISTER_PASSWORD_MUST_CONTAIN_DIGIT', 0);
433 \
define('REGISTER_PASSWORD_MUST_CONTAIN_SPECIAL_CHAR', 0);
435 // rel=nofollow is always applied to external link since 5.3
436 // https://github.com/WoltLab/WCF/issues/3339
437 \
define('EXTERNAL_LINK_REL_NOFOLLOW', 1);
439 // Session validation is removed since 5.4.
440 // https://github.com/WoltLab/WCF/pull/3583
441 \
define('SESSION_VALIDATE_IP_ADDRESS', 0);
442 \
define('SESSION_VALIDATE_USER_AGENT', 0);
444 // Virtual sessions no longer exist since 5.4.
445 \
define('SESSION_ENABLE_VIRTUALIZATION', 1);
447 // The session timeout is fully managed since 5.4.
448 \
define('SESSION_TIMEOUT', 3600);
450 // gzip compression is removed in 5.4.
451 // https://github.com/WoltLab/WCF/issues/3634
452 \
define('HTTP_ENABLE_GZIP', 0);
454 // Meta keywords are no longer used since 5.4.
455 // https://github.com/WoltLab/WCF/issues/3561
456 \
define('META_KEYWORDS', '');
458 // The admin notification is redundant and removed in 5.4.
459 // https://github.com/WoltLab/WCF/issues/3674
460 \
define('REGISTER_ADMIN_NOTIFICATION', 0);
462 // The hostname blocklist was removed in 5.4.
463 // https://github.com/WoltLab/WCF/issues/3909
464 \
define('BLACKLIST_HOSTNAMES', '');
466 // Cover photos are always enabled since 5.4.
467 // https://github.com/WoltLab/WCF/issues/3902
468 \
define('MODULE_USER_COVER_PHOTO', 1);
472 * Starts the session system.
474 protected function initSession()
476 $factory = new SessionFactory();
479 self
::$sessionObj = SessionHandler
::getInstance();
483 * Initialises the language engine.
485 protected function initLanguage()
487 if (isset($_GET['l']) && !self
::getUser()->userID
) {
488 self
::getSession()->setLanguageID(\
intval($_GET['l']));
492 \
mb_internal_encoding('UTF-8');
493 if (\function_exists
('mb_regex_encoding')) {
494 \
mb_regex_encoding('UTF-8');
499 self
::$languageObj = LanguageFactory
::getInstance()->getUserLanguage(self
::getSession()->getLanguageID());
503 * Initialises the template engine.
505 protected function initTPL()
507 self
::$tplObj = TemplateEngine
::getInstance();
508 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
509 $this->assignDefaultTemplateVariables();
515 * Initializes the user's style.
517 protected function initStyle()
519 if (isset($_REQUEST['styleID'])) {
520 self
::getSession()->setStyleID(\
intval($_REQUEST['styleID']));
523 $styleHandler = StyleHandler
::getInstance();
524 $styleHandler->changeStyle(self
::getSession()->getStyleID());
528 * Executes the blacklist.
530 protected function initBlacklist()
532 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
534 if (\
defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES
!= '') {
536 !StringUtil
::executeWordFilter(
537 UserUtil
::convertIPv6To4(UserUtil
::getIpAddress()),
538 BLACKLIST_IP_ADDRESSES
542 throw new AJAXException(
543 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
544 AJAXException
::INSUFFICIENT_PERMISSIONS
547 throw new PermissionDeniedException();
549 } elseif (!StringUtil
::executeWordFilter(UserUtil
::getIpAddress(), BLACKLIST_IP_ADDRESSES
)) {
551 throw new AJAXException(
552 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
553 AJAXException
::INSUFFICIENT_PERMISSIONS
556 throw new PermissionDeniedException();
560 if (\
defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS
!= '') {
561 if (!StringUtil
::executeWordFilter(UserUtil
::getUserAgent(), BLACKLIST_USER_AGENTS
)) {
563 throw new AJAXException(
564 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
565 AJAXException
::INSUFFICIENT_PERMISSIONS
568 throw new PermissionDeniedException();
573 // handle banned users
574 if (self
::getUser()->userID
&& self
::getUser()->banned
&& !self
::getUser()->hasOwnerAccess()) {
576 throw new AJAXException(
577 self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'),
578 AJAXException
::INSUFFICIENT_PERMISSIONS
581 self
::$forceLogout = true;
584 if (isset($_COOKIE[COOKIE_PREFIX
. 'userID'])) {
585 HeaderUtil
::setCookie('userID', 0);
587 if (isset($_COOKIE[COOKIE_PREFIX
. 'password'])) {
588 HeaderUtil
::setCookie('password', '');
591 throw new NamedUserException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
597 * Initializes applications.
599 protected function initApplications()
601 // step 1) load all applications
602 $loadedApplications = [];
604 // register WCF as application
605 self
::$applications['wcf'] = ApplicationHandler
::getInstance()->getApplicationByID(1);
607 if (!\
class_exists(WCFACP
::class, false)) {
608 static::getTPL()->assign('baseHref', self
::$applications['wcf']->getPageURL());
611 // start main application
612 $application = ApplicationHandler
::getInstance()->getActiveApplication();
613 if ($application->packageID
!= 1) {
614 $loadedApplications[] = $this->loadApplication($application);
616 // register primary application
617 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
618 self
::$applications[$abbreviation] = $application;
621 // start dependent applications
622 $applications = ApplicationHandler
::getInstance()->getDependentApplications();
623 foreach ($applications as $application) {
624 if ($application->packageID
== 1) {
627 } elseif ($application->isTainted
) {
628 // ignore apps flagged for uninstallation
632 $loadedApplications[] = $this->loadApplication($application, true);
635 // step 2) run each application
636 if (!\
class_exists('wcf\system\WCFACP', false)) {
637 /** @var IApplication $application */
638 foreach ($loadedApplications as $application) {
639 $application->__run();
642 /** @deprecated The below variable is deprecated. */
643 self
::getTPL()->assign('__sessionKeepAlive', 59 * 60);
648 * Loads an application.
650 * @param Application $application
651 * @param bool $isDependentApplication
652 * @return IApplication
653 * @throws SystemException
655 protected function loadApplication(Application
$application, $isDependentApplication = false)
657 $package = PackageCache
::getInstance()->getPackage($application->packageID
);
658 // package cache might be outdated
659 if ($package === null) {
660 $package = new Package($application->packageID
);
662 // package cache is outdated, discard cache
663 if ($package->packageID
) {
664 PackageEditor
::resetCache();
666 // package id is invalid
667 throw new SystemException("application identified by package id '" . $application->packageID
. "' is unknown");
671 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
672 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $package->packageDir
);
673 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
675 $className = $abbreviation . '\system\\' . \
strtoupper($abbreviation) . 'Core';
677 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
678 if (!\
class_exists($className)) {
679 // check if both the Core and the app are on the same domain
680 $coreApp = ApplicationHandler
::getInstance()->getApplicationByID(1);
681 if ($coreApp->domainName
=== $application->domainName
) {
682 // resolve the relative path and use it to construct the autoload directory
683 $relativePath = FileUtil
::getRelativePath($coreApp->domainPath
, $application->domainPath
);
684 if ($relativePath !== './') {
685 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $relativePath);
686 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
688 if (\
class_exists($className)) {
689 // the class can now be found, update the `packageDir` value
690 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
696 if (\
class_exists($className) && \
is_subclass_of($className, IApplication
::class)) {
697 // include config file
698 $configPath = $packageDir . PackageInstallationDispatcher
::CONFIG_FILE
;
699 if (!\file_exists
($configPath)) {
700 Package
::writeConfigFile($package->packageID
);
703 if (\file_exists
($configPath)) {
704 require_once($configPath);
706 throw new SystemException('Unable to load configuration for ' . $package->package
);
709 // register template path if not within ACP
710 if (!\
class_exists('wcf\system\WCFACP', false)) {
711 // add template path and abbreviation
712 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
714 EmailTemplateEngine
::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
716 // init application and assign it as template variable
717 self
::$applicationObjects[$application->packageID
] = \
call_user_func([$className, 'getInstance']);
718 static::getTPL()->assign('__' . $abbreviation, self
::$applicationObjects[$application->packageID
]);
719 EmailTemplateEngine
::getInstance()->assign(
720 '__' . $abbreviation,
721 self
::$applicationObjects[$application->packageID
]
724 unset(self
::$autoloadDirectories[$abbreviation]);
725 throw new SystemException("Unable to run '" . $package->package
. "', '" . $className . "' is missing or does not implement '" . IApplication
::class . "'.");
728 // register template path in ACP
729 if (\
class_exists('wcf\system\WCFACP', false)) {
730 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
731 } elseif (!$isDependentApplication) {
733 static::getTPL()->assign('baseHref', $application->getPageURL());
736 // register application
737 self
::$applications[$abbreviation] = $application;
739 return self
::$applicationObjects[$application->packageID
];
743 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
745 * @param Application $application
746 * @return IApplication
748 public static function getApplicationObject(Application
$application)
750 return self
::$applicationObjects[$application->packageID
] ??
null;
754 * Returns the invoked application.
756 * @return Application
759 public static function getActiveApplication()
761 return ApplicationHandler
::getInstance()->getActiveApplication();
765 * Loads an application on runtime, do not use this outside the package installation.
767 * @param int $packageID
769 public static function loadRuntimeApplication($packageID)
771 $package = new Package($packageID);
772 $application = new Application($packageID);
774 $abbreviation = Package
::getAbbreviation($package->package
);
775 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $package->packageDir
);
776 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
777 self
::$applications[$abbreviation] = $application;
778 self
::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
782 * Initializes core object cache.
784 protected function initCoreObjects()
786 // ignore core objects if installing WCF
787 if (PACKAGE_ID
== 0) {
791 self
::$coreObjectCache = CoreObjectCacheBuilder
::getInstance()->getData();
795 * Assigns some default variables to the template engine.
797 protected function assignDefaultTemplateVariables()
801 if (ENABLE_ENTERPRISE_MODE
) {
802 $wcf = new TemplateScriptingCore($wcf);
805 self
::getTPL()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang', 'csrfToken']);
806 self
::getTPL()->assign([
808 '__wcfVersion' => LAST_UPDATE_TIME
, // @deprecated 2.1, use LAST_UPDATE_TIME directly
811 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
812 // Execute background queue in this request, if it was requested and AJAX isn't used.
814 if (self
::getSession()->getVar('forceBackgroundQueuePerform')) {
815 self
::getTPL()->assign([
816 'forceBackgroundQueuePerform' => true,
819 self
::getSession()->unregister('forceBackgroundQueuePerform');
823 EmailTemplateEngine
::getInstance()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang']);
824 EmailTemplateEngine
::getInstance()->assign([
830 * Wrapper for the getter methods of this class.
832 * @param string $name
833 * @return mixed value
834 * @throws SystemException
836 public function __get($name)
838 $method = 'get' . \
ucfirst($name);
839 if (\
method_exists($this, $method)) {
840 return $this->{$method}();
843 throw new SystemException("method '" . $method . "' does not exist in class WCF");
847 * Returns true if current application (WCF) is treated as active and was invoked directly.
851 public function isActiveApplication()
853 return ApplicationHandler
::getInstance()->getActiveApplication()->packageID
== 1;
857 * Changes the active language.
859 * @param int $languageID
861 final public static function setLanguage($languageID)
863 if (!$languageID || LanguageFactory
::getInstance()->getLanguage($languageID) === null) {
864 $languageID = LanguageFactory
::getInstance()->getDefaultLanguageID();
867 self
::$languageObj = LanguageFactory
::getInstance()->getLanguage($languageID);
869 // the template engine may not be available yet, usually happens when
870 // changing the user (and thus the language id) during session init
871 if (self
::$tplObj !== null) {
872 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
873 EmailTemplateEngine
::getInstance()->setLanguageID(self
::getLanguage()->languageID
);
878 * Includes the required util or exception classes automatically.
880 * @param string $className
881 * @see spl_autoload_register()
883 final public static function autoload($className)
885 $namespaces = \
explode('\\', $className);
886 if (\
count($namespaces) > 1) {
887 $applicationPrefix = \array_shift
($namespaces);
888 if ($applicationPrefix === '') {
889 $applicationPrefix = \array_shift
($namespaces);
891 if (isset(self
::$autoloadDirectories[$applicationPrefix])) {
892 $classPath = self
::$autoloadDirectories[$applicationPrefix] . \
implode('/', $namespaces) . '.class.php';
894 // PHP will implicitly check if the file exists when including it, which means that we can save a
895 // redundant syscall/fs access by not checking for existence ourselves. Do not use require_once()!
896 @include_once
($classPath);
904 final public function __call($name, array $arguments)
906 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
907 if (!\
method_exists($this, $name)) {
908 return self
::__callStatic($name, $arguments);
911 throw new \
BadMethodCallException("Call to undefined method WCF::{$name}().");
915 * Returns dynamically loaded core objects.
917 * @param string $name
918 * @param array $arguments
920 * @throws SystemException
922 final public static function __callStatic($name, array $arguments)
924 $className = \
preg_replace('~^get~', '', $name);
926 if (isset(self
::$coreObject[$className])) {
927 return self
::$coreObject[$className];
930 $objectName = self
::getCoreObject($className);
931 if ($objectName === null) {
932 throw new SystemException("Core object '" . $className . "' is unknown.");
935 if (\
class_exists($objectName)) {
936 if (!\
is_subclass_of($objectName, SingletonFactory
::class)) {
937 throw new ParentClassException($objectName, SingletonFactory
::class);
940 self
::$coreObject[$className] = \
call_user_func([$objectName, 'getInstance']);
942 return self
::$coreObject[$className];
947 * Searches for cached core object definition.
949 * @param string $className
950 * @return string|null
952 final protected static function getCoreObject($className)
954 return self
::$coreObjectCache[$className] ??
null;
958 * Returns true if the debug mode is enabled, otherwise false.
960 * @param bool $ignoreACP
963 public static function debugModeIsEnabled($ignoreACP = false)
966 if (!$ignoreACP && self
::$overrideDebugMode) {
968 } elseif (\
defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE
) {
976 * Returns true if benchmarking is enabled, otherwise false.
980 public static function benchmarkIsEnabled()
982 // benchmarking is enabled by default
983 if (!\
defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK
) {
991 * Returns domain path for given application.
993 * @param string $abbreviation
996 public static function getPath($abbreviation = 'wcf')
998 // workaround during WCFSetup
1003 if (!isset(self
::$applications[$abbreviation])) {
1004 $abbreviation = 'wcf';
1007 return self
::$applications[$abbreviation]->getPageURL();
1011 * Returns the domain path for the currently active application,
1012 * used to avoid CORS requests.
1016 public static function getActivePath()
1019 return self
::getPath();
1022 // We cannot rely on the ApplicationHandler's `getActiveApplication()` because
1023 // it uses the requested controller to determine the namespace. However, starting
1024 // with WoltLab Suite 5.2, system pages can be virtually assigned to a different
1025 // app, resolving against the target app without changing the namespace.
1026 return self
::getPath(ApplicationHandler
::getInstance()->getAbbreviation(PACKAGE_ID
));
1030 * Returns a fully qualified anchor for current page.
1032 * @param string $fragment
1035 public function getAnchor($fragment)
1037 return StringUtil
::encodeHTML(self
::getRequestURI() . '#' . $fragment);
1041 * Returns the currently active page or null if unknown.
1045 public static function getActivePage()
1047 if (self
::getActiveRequest() === null) {
1051 if (self
::getActiveRequest()->getClassName() === CmsPage
::class) {
1052 $metaData = self
::getActiveRequest()->getMetaData();
1053 if (isset($metaData['cms'])) {
1054 return PageCache
::getInstance()->getPage($metaData['cms']['pageID']);
1060 return PageCache
::getInstance()->getPageByController(self
::getActiveRequest()->getClassName());
1064 * Returns the currently active request.
1068 public static function getActiveRequest()
1070 return RequestHandler
::getInstance()->getActiveRequest();
1074 * Returns the URI of the current page.
1078 public static function getRequestURI()
1080 return \
preg_replace(
1081 '~^(https?://[^/]+)(?:/.*)?$~',
1083 self
::getTPL()->get('baseHref')
1084 ) . $_SERVER['REQUEST_URI'];
1088 * Resets Zend Opcache cache if installed and enabled.
1090 * @param string $script
1092 public static function resetZendOpcache($script = '')
1094 if (self
::$zendOpcacheEnabled === null) {
1095 self
::$zendOpcacheEnabled = false;
1097 if (\
extension_loaded('Zend Opcache') && @\
ini_get('opcache.enable')) {
1098 self
::$zendOpcacheEnabled = true;
1102 if (self
::$zendOpcacheEnabled) {
1103 if (empty($script)) {
1106 \
opcache_invalidate($script, true);
1112 * Returns style handler.
1114 * @return StyleHandler
1116 public function getStyleHandler()
1118 return StyleHandler
::getInstance();
1122 * Returns box handler.
1124 * @return BoxHandler
1127 public function getBoxHandler()
1129 return BoxHandler
::getInstance();
1133 * Returns number of available updates.
1137 public function getAvailableUpdates()
1139 $data = PackageUpdateCacheBuilder
::getInstance()->getData();
1141 return $data['updates'];
1145 * Returns a 8 character prefix for editor autosave.
1149 public function getAutosavePrefix()
1151 return \
substr(\
sha1(\
preg_replace('~^https~', 'http', self
::getPath())), 0, 8);
1155 * Returns the favicon URL or a base64 encoded image.
1159 public function getFavicon()
1161 $activeApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1162 $wcf = ApplicationHandler
::getInstance()->getWCF();
1163 $favicon = StyleHandler
::getInstance()->getStyle()->getRelativeFavicon();
1165 if ($activeApplication->domainName
!== $wcf->domainName
) {
1166 if (\file_exists
(WCF_DIR
. $favicon)) {
1167 $favicon = \file_get_contents
(WCF_DIR
. $favicon);
1169 return 'data:image/x-icon;base64,' . \base
64_encode
($favicon);
1173 return self
::getPath() . $favicon;
1177 * Returns true if the desktop notifications should be enabled.
1181 public function useDesktopNotifications()
1183 if (!ENABLE_DESKTOP_NOTIFICATIONS
) {
1185 } elseif (ApplicationHandler
::getInstance()->isMultiDomainSetup()) {
1186 $application = ApplicationHandler
::getInstance()->getApplicationByID(DESKTOP_NOTIFICATION_PACKAGE_ID
);
1187 // mismatch, default to Core
1188 if ($application === null) {
1189 $application = ApplicationHandler
::getInstance()->getApplicationByID(1);
1192 $currentApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1193 if ($currentApplication->domainName
!= $application->domainName
) {
1203 * Returns true if currently active request represents the landing page.
1207 public static function isLandingPage()
1209 if (self
::getActiveRequest() === null) {
1213 return self
::getActiveRequest()->isLandingPage();
1217 * Returns true if the given API version is currently supported.
1219 * @param int $apiVersion
1223 public static function isSupportedApiVersion($apiVersion)
1225 return ($apiVersion == WSC_API_VERSION
) || \
in_array($apiVersion, self
::$supportedLegacyApiVersions);
1229 * Returns the list of supported legacy API versions.
1234 public static function getSupportedLegacyApiVersions()
1236 return self
::$supportedLegacyApiVersions;
1240 * Initialises the cronjobs.
1242 protected function initCronjobs()
1245 self
::getTPL()->assign(
1247 CronjobScheduler
::getInstance()->getNextExec() < TIME_NOW
&& \
defined('OFFLINE') && !OFFLINE
1253 * Checks recursively that the most important system files of `com.woltlab.wcf` are writable.
1255 * @throws \RuntimeException if any relevant file or directory is not writable
1257 public static function checkWritability()
1259 $nonWritablePaths = [];
1261 $nonRecursiveDirectories = [
1266 foreach ($nonRecursiveDirectories as $directory) {
1267 $path = WCF_DIR
. $directory;
1268 if ($path === 'tmp/' && !\
is_dir($path)) {
1272 if (!\
is_writable($path)) {
1273 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1277 DirectoryUtil
::getInstance($path, false)
1278 ->executeCallback(static function ($file, \SplFileInfo
$fileInfo) use (&$nonWritablePaths) {
1279 if ($fileInfo instanceof \DirectoryIterator
) {
1280 if (!\
is_writable($fileInfo->getPath())) {
1281 $nonWritablePaths[] = FileUtil
::getRelativePath(
1282 $_SERVER['DOCUMENT_ROOT'],
1283 $fileInfo->getPath()
1286 } elseif (!\
is_writable($fileInfo->getRealPath())) {
1287 $nonWritablePaths[] = FileUtil
::getRelativePath(
1288 $_SERVER['DOCUMENT_ROOT'],
1289 $fileInfo->getPath()
1290 ) . $fileInfo->getFilename();
1295 $recursiveDirectories = [
1306 foreach ($recursiveDirectories as $directory) {
1307 $path = WCF_DIR
. $directory;
1309 if (!\
is_writable($path)) {
1310 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1314 DirectoryUtil
::getInstance($path)
1315 ->executeCallback(static function ($file, \SplFileInfo
$fileInfo) use (&$nonWritablePaths) {
1316 if ($fileInfo instanceof \DirectoryIterator
) {
1317 if (!\
is_writable($fileInfo->getPath())) {
1318 $nonWritablePaths[] = FileUtil
::getRelativePath(
1319 $_SERVER['DOCUMENT_ROOT'],
1320 $fileInfo->getPath()
1323 } elseif (!\
is_writable($fileInfo->getRealPath())) {
1324 $nonWritablePaths[] = FileUtil
::getRelativePath(
1325 $_SERVER['DOCUMENT_ROOT'],
1326 $fileInfo->getPath()
1327 ) . $fileInfo->getFilename();
1332 if (!empty($nonWritablePaths)) {
1334 throw new \
RuntimeException('The following paths are not writable: ' . \
implode(
1341 ) . (\
count($nonWritablePaths) > $maxPaths ?
',' . StringUtil
::HELLIP
: ''));