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.25');
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
86 public const AVAILABLE_UPGRADE_VERSION
= '5.5';
89 * list of supported legacy API versions
93 private static $supportedLegacyApiVersions = [2017, 2018];
96 * list of currently loaded applications
99 protected static $applications = [];
102 * list of currently loaded application objects
103 * @var IApplication[]
105 protected static $applicationObjects = [];
108 * list of autoload directories
111 protected static $autoloadDirectories = [];
114 * list of unique instances of each core object
115 * @var SingletonFactory[]
117 protected static $coreObject = [];
120 * list of cached core objects
123 protected static $coreObjectCache = [];
129 protected static $dbObj;
133 * @var \wcf\data\language\Language
135 protected static $languageObj;
138 * overrides disabled debug mode
141 protected static $overrideDebugMode = false;
145 * @var SessionHandler
147 protected static $sessionObj;
151 * @var TemplateEngine
153 protected static $tplObj;
156 * true if Zend Opcache is loaded and enabled
159 protected static $zendOpcacheEnabled;
162 * force logout during destructor call
165 protected static $forceLogout = false;
168 * Calls all init functions of the WCF class.
170 public function __construct()
172 // add autoload directory
173 self
::$autoloadDirectories['wcf'] = WCF_DIR
. 'lib/';
175 // define tmp directory
176 if (!\
defined('TMP_DIR')) {
177 \
define('TMP_DIR', FileUtil
::getTempFolder());
180 // start initialization
182 $this->loadOptions();
183 $this->initSession();
184 $this->initLanguage();
186 $this->initCronjobs();
187 $this->initCoreObjects();
188 $this->initApplications();
189 $this->initBlacklist();
191 EventHandler
::getInstance()->fireAction($this, 'initialized');
195 * Flushes the output, closes the session, performs background tasks and more.
197 * You *must* not create output in here under normal circumstances, as it might get eaten
198 * when gzip is enabled.
200 public static function destruct()
203 // database has to be initialized
204 if (!\
is_object(self
::$dbObj)) {
208 $debug = self
::debugModeIsEnabled(true);
211 if (\
ob_get_level()) {
216 // close connection if using FPM
217 if (\function_exists
('fastcgi_finish_request')) {
218 fastcgi_finish_request();
223 if (\
is_object(self
::getSession())) {
224 if (self
::$forceLogout) {
226 self
::getSession()->delete();
228 self
::getSession()->update();
232 // execute shutdown actions of storage handlers
233 RegistryHandler
::getInstance()->shutdown();
234 UserStorageHandler
::getInstance()->shutdown();
235 } catch (\Exception
$exception) {
236 exit("<pre>WCF::destruct() Unhandled exception: " . $exception->getMessage() . "\n\n" . $exception->getTraceAsString());
241 * Returns the database object.
243 * @return \wcf\system\database\Database
245 final public static function getDB()
251 * Returns the session object.
253 * @return SessionHandler
255 final public static function getSession()
257 return self
::$sessionObj;
261 * Returns the user object.
263 * @return \wcf\data\user\User
265 final public static function getUser()
267 return self
::getSession()->getUser();
271 * Returns the language object.
273 * @return \wcf\data\language\Language
275 final public static function getLanguage()
277 return self
::$languageObj;
281 * Returns the template object.
283 * @return TemplateEngine
285 final public static function getTPL()
287 return self
::$tplObj;
291 * Calls the show method on the given exception.
293 * @param \Throwable $e
295 final public static function handleException($e)
297 // backwards compatibility
298 if ($e instanceof IPrintableException
) {
304 if (\
ob_get_level()) {
305 // discard any output generated before the exception occurred, prevents exception
306 // being hidden inside HTML elements and therefore not visible in browser output
308 // ob_get_level() can return values > 1, if the PHP setting `output_buffering` is on
309 while (\
ob_get_level()) {
314 @\
header('HTTP/1.1 503 Service Unavailable');
316 \wcf\functions\exception\
printThrowable($e);
317 } catch (\Throwable
$e2) {
318 echo "<pre>An Exception was thrown while handling an Exception:\n\n";
319 echo \
preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e2);
320 echo "\n\nwas thrown while:\n\n";
321 echo \
preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e);
322 echo "\n\nwas handled.</pre>";
329 * Turns PHP errors into an ErrorException.
331 * @param int $severity
332 * @param string $message
333 * @param string $file
335 * @throws ErrorException
337 final public static function handleError($severity, $message, $file, $line)
339 // this is necessary for the shut-up operator
340 if (!(\
error_reporting() & $severity)) {
344 throw new ErrorException($message, 0, $severity, $file, $line);
348 * Loads the database configuration and creates a new connection to the database.
350 protected function initDB()
353 $dbHost = $dbUser = $dbPassword = $dbName = '';
355 $defaultDriverOptions = [];
356 require(WCF_DIR
. 'config.inc.php');
358 // create database connection
359 self
::$dbObj = new MySQLDatabase(
367 $defaultDriverOptions
372 * Loads the options file, automatically created if not exists.
374 protected function loadOptions()
376 $this->defineLegacyOptions();
378 $filename = WCF_DIR
. 'options.inc.php';
380 // create options file if doesn't exist
381 if (!\file_exists
($filename) || \filemtime
($filename) <= 1) {
382 OptionEditor
::rebuild();
386 // check if option file is complete and writable
388 if (!\
is_writable($filename)) {
389 FileUtil
::makeWritable($filename);
391 if (!\
is_writable($filename)) {
392 throw new SystemException("The option file '" . $filename . "' is not writable.");
396 // check if a previous write operation was incomplete and force rebuilding
397 if (!\
defined('WCF_OPTION_INC_PHP_SUCCESS')) {
398 OptionEditor
::rebuild();
403 if (ENABLE_DEBUG_MODE
) {
404 self
::$dbObj->enableDebugMode();
410 * Defines constants for obsolete options, which were removed.
414 protected function defineLegacyOptions(): void
416 // The attachment module is always enabled since 5.2.
417 // https://github.com/WoltLab/WCF/issues/2531
418 \
define('MODULE_ATTACHMENT', 1);
420 // Users cannot react to their own content since 5.2.
421 // https://github.com/WoltLab/WCF/issues/2975
422 \
define('LIKE_ALLOW_FOR_OWN_CONTENT', 0);
423 \
define('LIKE_ENABLE_DISLIKE', 0);
425 // Thumbnails for attachments are already enabled since 5.3.
426 // https://github.com/WoltLab/WCF/pull/3444
427 \
define('ATTACHMENT_ENABLE_THUMBNAILS', 1);
429 // User markings are always applied in sidebars since 5.3.
430 // https://github.com/WoltLab/WCF/issues/3330
431 \
define('MESSAGE_SIDEBAR_ENABLE_USER_ONLINE_MARKING', 1);
433 // Password strength configuration is deprecated since 5.3.
434 \
define('REGISTER_ENABLE_PASSWORD_SECURITY_CHECK', 0);
435 \
define('REGISTER_PASSWORD_MIN_LENGTH', 0);
436 \
define('REGISTER_PASSWORD_MUST_CONTAIN_LOWER_CASE', 8);
437 \
define('REGISTER_PASSWORD_MUST_CONTAIN_UPPER_CASE', 0);
438 \
define('REGISTER_PASSWORD_MUST_CONTAIN_DIGIT', 0);
439 \
define('REGISTER_PASSWORD_MUST_CONTAIN_SPECIAL_CHAR', 0);
441 // rel=nofollow is always applied to external link since 5.3
442 // https://github.com/WoltLab/WCF/issues/3339
443 \
define('EXTERNAL_LINK_REL_NOFOLLOW', 1);
445 // Session validation is removed since 5.4.
446 // https://github.com/WoltLab/WCF/pull/3583
447 \
define('SESSION_VALIDATE_IP_ADDRESS', 0);
448 \
define('SESSION_VALIDATE_USER_AGENT', 0);
450 // Virtual sessions no longer exist since 5.4.
451 \
define('SESSION_ENABLE_VIRTUALIZATION', 1);
453 // The session timeout is fully managed since 5.4.
454 \
define('SESSION_TIMEOUT', 3600);
456 // gzip compression is removed in 5.4.
457 // https://github.com/WoltLab/WCF/issues/3634
458 \
define('HTTP_ENABLE_GZIP', 0);
460 // Meta keywords are no longer used since 5.4.
461 // https://github.com/WoltLab/WCF/issues/3561
462 \
define('META_KEYWORDS', '');
464 // The admin notification is redundant and removed in 5.4.
465 // https://github.com/WoltLab/WCF/issues/3674
466 \
define('REGISTER_ADMIN_NOTIFICATION', 0);
468 // The hostname blocklist was removed in 5.4.
469 // https://github.com/WoltLab/WCF/issues/3909
470 \
define('BLACKLIST_HOSTNAMES', '');
472 // Cover photos are always enabled since 5.4.
473 // https://github.com/WoltLab/WCF/issues/3902
474 \
define('MODULE_USER_COVER_PHOTO', 1);
478 * Starts the session system.
480 protected function initSession()
482 $factory = new SessionFactory();
485 self
::$sessionObj = SessionHandler
::getInstance();
489 * Initialises the language engine.
491 protected function initLanguage()
493 if (isset($_GET['l']) && !self
::getUser()->userID
) {
494 self
::getSession()->setLanguageID(\
intval($_GET['l']));
498 \
mb_internal_encoding('UTF-8');
499 if (\function_exists
('mb_regex_encoding')) {
500 \
mb_regex_encoding('UTF-8');
505 self
::$languageObj = LanguageFactory
::getInstance()->getUserLanguage(self
::getSession()->getLanguageID());
509 * Initialises the template engine.
511 protected function initTPL()
513 self
::$tplObj = TemplateEngine
::getInstance();
514 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
515 $this->assignDefaultTemplateVariables();
521 * Initializes the user's style.
523 protected function initStyle()
525 if (isset($_REQUEST['styleID'])) {
526 self
::getSession()->setStyleID(\
intval($_REQUEST['styleID']));
529 $styleHandler = StyleHandler
::getInstance();
530 $styleHandler->changeStyle(self
::getSession()->getStyleID());
534 * Executes the blacklist.
536 protected function initBlacklist()
538 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
540 if (\
defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES
!= '') {
542 !StringUtil
::executeWordFilter(
543 UserUtil
::convertIPv6To4(UserUtil
::getIpAddress()),
544 BLACKLIST_IP_ADDRESSES
548 throw new AJAXException(
549 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
550 AJAXException
::INSUFFICIENT_PERMISSIONS
553 throw new PermissionDeniedException();
555 } elseif (!StringUtil
::executeWordFilter(UserUtil
::getIpAddress(), BLACKLIST_IP_ADDRESSES
)) {
557 throw new AJAXException(
558 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
559 AJAXException
::INSUFFICIENT_PERMISSIONS
562 throw new PermissionDeniedException();
566 if (\
defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS
!= '') {
567 if (!StringUtil
::executeWordFilter(UserUtil
::getUserAgent(), BLACKLIST_USER_AGENTS
)) {
569 throw new AJAXException(
570 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
571 AJAXException
::INSUFFICIENT_PERMISSIONS
574 throw new PermissionDeniedException();
579 // handle banned users
580 if (self
::getUser()->userID
&& self
::getUser()->banned
&& !self
::getUser()->hasOwnerAccess()) {
582 throw new AJAXException(
583 self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'),
584 AJAXException
::INSUFFICIENT_PERMISSIONS
587 self
::$forceLogout = true;
590 if (isset($_COOKIE[COOKIE_PREFIX
. 'userID'])) {
591 HeaderUtil
::setCookie('userID', 0);
593 if (isset($_COOKIE[COOKIE_PREFIX
. 'password'])) {
594 HeaderUtil
::setCookie('password', '');
597 throw new NamedUserException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
603 * Initializes applications.
605 protected function initApplications()
607 // step 1) load all applications
608 $loadedApplications = [];
610 // register WCF as application
611 self
::$applications['wcf'] = ApplicationHandler
::getInstance()->getApplicationByID(1);
613 if (!\
class_exists(WCFACP
::class, false)) {
614 static::getTPL()->assign('baseHref', self
::$applications['wcf']->getPageURL());
617 // start main application
618 $application = ApplicationHandler
::getInstance()->getActiveApplication();
619 if ($application->packageID
!= 1) {
620 $loadedApplications[] = $this->loadApplication($application);
622 // register primary application
623 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
624 self
::$applications[$abbreviation] = $application;
627 // start dependent applications
628 $applications = ApplicationHandler
::getInstance()->getDependentApplications();
629 foreach ($applications as $application) {
630 if ($application->packageID
== 1) {
633 } elseif ($application->isTainted
) {
634 // ignore apps flagged for uninstallation
638 $loadedApplications[] = $this->loadApplication($application, true);
641 // step 2) run each application
642 if (!\
class_exists('wcf\system\WCFACP', false)) {
643 /** @var IApplication $application */
644 foreach ($loadedApplications as $application) {
645 $application->__run();
648 /** @deprecated The below variable is deprecated. */
649 self
::getTPL()->assign('__sessionKeepAlive', 59 * 60);
654 * Loads an application.
656 * @param Application $application
657 * @param bool $isDependentApplication
658 * @return IApplication
659 * @throws SystemException
661 protected function loadApplication(Application
$application, $isDependentApplication = false)
663 $package = PackageCache
::getInstance()->getPackage($application->packageID
);
664 // package cache might be outdated
665 if ($package === null) {
666 $package = new Package($application->packageID
);
668 // package cache is outdated, discard cache
669 if ($package->packageID
) {
670 PackageEditor
::resetCache();
672 // package id is invalid
673 throw new SystemException("application identified by package id '" . $application->packageID
. "' is unknown");
677 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
678 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $package->packageDir
);
679 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
681 $className = $abbreviation . '\system\\' . \
strtoupper($abbreviation) . 'Core';
683 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
684 if (!\
class_exists($className)) {
685 // check if both the Core and the app are on the same domain
686 $coreApp = ApplicationHandler
::getInstance()->getApplicationByID(1);
687 if ($coreApp->domainName
=== $application->domainName
) {
688 // resolve the relative path and use it to construct the autoload directory
689 $relativePath = FileUtil
::getRelativePath($coreApp->domainPath
, $application->domainPath
);
690 if ($relativePath !== './') {
691 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $relativePath);
692 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
694 if (\
class_exists($className)) {
695 // the class can now be found, update the `packageDir` value
696 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
702 if (\
class_exists($className) && \
is_subclass_of($className, IApplication
::class)) {
703 // include config file
704 $configPath = $packageDir . PackageInstallationDispatcher
::CONFIG_FILE
;
705 if (!\file_exists
($configPath)) {
706 Package
::writeConfigFile($package->packageID
);
709 if (\file_exists
($configPath)) {
710 require_once($configPath);
712 throw new SystemException('Unable to load configuration for ' . $package->package
);
715 // register template path if not within ACP
716 if (!\
class_exists('wcf\system\WCFACP', false)) {
717 // add template path and abbreviation
718 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
720 EmailTemplateEngine
::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
722 // init application and assign it as template variable
723 self
::$applicationObjects[$application->packageID
] = \
call_user_func([$className, 'getInstance']);
724 static::getTPL()->assign('__' . $abbreviation, self
::$applicationObjects[$application->packageID
]);
725 EmailTemplateEngine
::getInstance()->assign(
726 '__' . $abbreviation,
727 self
::$applicationObjects[$application->packageID
]
730 unset(self
::$autoloadDirectories[$abbreviation]);
731 throw new SystemException("Unable to run '" . $package->package
. "', '" . $className . "' is missing or does not implement '" . IApplication
::class . "'.");
734 // register template path in ACP
735 if (\
class_exists('wcf\system\WCFACP', false)) {
736 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
737 } elseif (!$isDependentApplication) {
739 static::getTPL()->assign('baseHref', $application->getPageURL());
742 // register application
743 self
::$applications[$abbreviation] = $application;
745 return self
::$applicationObjects[$application->packageID
];
749 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
751 * @param Application $application
752 * @return IApplication
754 public static function getApplicationObject(Application
$application)
756 return self
::$applicationObjects[$application->packageID
] ??
null;
760 * Returns the invoked application.
762 * @return Application
765 public static function getActiveApplication()
767 return ApplicationHandler
::getInstance()->getActiveApplication();
771 * Loads an application on runtime, do not use this outside the package installation.
773 * @param int $packageID
775 public static function loadRuntimeApplication($packageID)
777 $package = new Package($packageID);
778 $application = new Application($packageID);
780 $abbreviation = Package
::getAbbreviation($package->package
);
781 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $package->packageDir
);
782 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
783 self
::$applications[$abbreviation] = $application;
784 self
::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
788 * Initializes core object cache.
790 protected function initCoreObjects()
792 // ignore core objects if installing WCF
793 if (PACKAGE_ID
== 0) {
797 self
::$coreObjectCache = CoreObjectCacheBuilder
::getInstance()->getData();
801 * Assigns some default variables to the template engine.
803 protected function assignDefaultTemplateVariables()
807 if (ENABLE_ENTERPRISE_MODE
) {
808 $wcf = new TemplateScriptingCore($wcf);
811 self
::getTPL()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang', 'csrfToken']);
812 self
::getTPL()->assign([
814 '__wcfVersion' => LAST_UPDATE_TIME
, // @deprecated 2.1, use LAST_UPDATE_TIME directly
817 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
818 // Execute background queue in this request, if it was requested and AJAX isn't used.
820 if (self
::getSession()->getVar('forceBackgroundQueuePerform')) {
821 self
::getTPL()->assign([
822 'forceBackgroundQueuePerform' => true,
825 self
::getSession()->unregister('forceBackgroundQueuePerform');
829 EmailTemplateEngine
::getInstance()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang']);
830 EmailTemplateEngine
::getInstance()->assign([
836 * Wrapper for the getter methods of this class.
838 * @param string $name
839 * @return mixed value
840 * @throws SystemException
842 public function __get($name)
844 $method = 'get' . \
ucfirst($name);
845 if (\
method_exists($this, $method)) {
846 return $this->{$method}();
849 throw new SystemException("method '" . $method . "' does not exist in class WCF");
853 * Returns true if current application (WCF) is treated as active and was invoked directly.
857 public function isActiveApplication()
859 return ApplicationHandler
::getInstance()->getActiveApplication()->packageID
== 1;
863 * Changes the active language.
865 * @param int $languageID
867 final public static function setLanguage($languageID)
869 if (!$languageID || LanguageFactory
::getInstance()->getLanguage($languageID) === null) {
870 $languageID = LanguageFactory
::getInstance()->getDefaultLanguageID();
873 self
::$languageObj = LanguageFactory
::getInstance()->getLanguage($languageID);
875 // the template engine may not be available yet, usually happens when
876 // changing the user (and thus the language id) during session init
877 if (self
::$tplObj !== null) {
878 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
879 EmailTemplateEngine
::getInstance()->setLanguageID(self
::getLanguage()->languageID
);
884 * Includes the required util or exception classes automatically.
886 * @param string $className
887 * @see spl_autoload_register()
889 final public static function autoload($className)
891 $namespaces = \
explode('\\', $className);
892 if (\
count($namespaces) > 1) {
893 $applicationPrefix = \array_shift
($namespaces);
894 if ($applicationPrefix === '') {
895 $applicationPrefix = \array_shift
($namespaces);
897 if (isset(self
::$autoloadDirectories[$applicationPrefix])) {
898 $classPath = self
::$autoloadDirectories[$applicationPrefix] . \
implode('/', $namespaces) . '.class.php';
900 // PHP will implicitly check if the file exists when including it, which means that we can save a
901 // redundant syscall/fs access by not checking for existence ourselves. Do not use require_once()!
902 @include_once
($classPath);
910 final public function __call($name, array $arguments)
912 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
913 if (!\
method_exists($this, $name)) {
914 return self
::__callStatic($name, $arguments);
917 throw new \
BadMethodCallException("Call to undefined method WCF::{$name}().");
921 * Returns dynamically loaded core objects.
923 * @param string $name
924 * @param array $arguments
926 * @throws SystemException
928 final public static function __callStatic($name, array $arguments)
930 $className = \
preg_replace('~^get~', '', $name);
932 if (isset(self
::$coreObject[$className])) {
933 return self
::$coreObject[$className];
936 $objectName = self
::getCoreObject($className);
937 if ($objectName === null) {
938 throw new SystemException("Core object '" . $className . "' is unknown.");
941 if (\
class_exists($objectName)) {
942 if (!\
is_subclass_of($objectName, SingletonFactory
::class)) {
943 throw new ParentClassException($objectName, SingletonFactory
::class);
946 self
::$coreObject[$className] = \
call_user_func([$objectName, 'getInstance']);
948 return self
::$coreObject[$className];
953 * Searches for cached core object definition.
955 * @param string $className
956 * @return string|null
958 final protected static function getCoreObject($className)
960 return self
::$coreObjectCache[$className] ??
null;
964 * Returns true if the debug mode is enabled, otherwise false.
966 * @param bool $ignoreACP
969 public static function debugModeIsEnabled($ignoreACP = false)
972 if (!$ignoreACP && self
::$overrideDebugMode) {
974 } elseif (\
defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE
) {
982 * Returns true if benchmarking is enabled, otherwise false.
986 public static function benchmarkIsEnabled()
988 // benchmarking is enabled by default
989 if (!\
defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK
) {
997 * Returns domain path for given application.
999 * @param string $abbreviation
1002 public static function getPath($abbreviation = 'wcf')
1004 // workaround during WCFSetup
1009 if (!isset(self
::$applications[$abbreviation])) {
1010 $abbreviation = 'wcf';
1013 return self
::$applications[$abbreviation]->getPageURL();
1017 * Returns the domain path for the currently active application,
1018 * used to avoid CORS requests.
1022 public static function getActivePath()
1025 return self
::getPath();
1028 // We cannot rely on the ApplicationHandler's `getActiveApplication()` because
1029 // it uses the requested controller to determine the namespace. However, starting
1030 // with WoltLab Suite 5.2, system pages can be virtually assigned to a different
1031 // app, resolving against the target app without changing the namespace.
1032 return self
::getPath(ApplicationHandler
::getInstance()->getAbbreviation(PACKAGE_ID
));
1036 * Returns a fully qualified anchor for current page.
1038 * @param string $fragment
1041 public function getAnchor($fragment)
1043 return StringUtil
::encodeHTML(self
::getRequestURI() . '#' . $fragment);
1047 * Returns the currently active page or null if unknown.
1051 public static function getActivePage()
1053 if (self
::getActiveRequest() === null) {
1057 if (self
::getActiveRequest()->getClassName() === CmsPage
::class) {
1058 $metaData = self
::getActiveRequest()->getMetaData();
1059 if (isset($metaData['cms'])) {
1060 return PageCache
::getInstance()->getPage($metaData['cms']['pageID']);
1066 return PageCache
::getInstance()->getPageByController(self
::getActiveRequest()->getClassName());
1070 * Returns the currently active request.
1074 public static function getActiveRequest()
1076 return RequestHandler
::getInstance()->getActiveRequest();
1080 * Returns the URI of the current page.
1084 public static function getRequestURI()
1086 return \
preg_replace(
1087 '~^(https?://[^/]+)(?:/.*)?$~',
1089 self
::getTPL()->get('baseHref')
1090 ) . $_SERVER['REQUEST_URI'];
1094 * Resets Zend Opcache cache if installed and enabled.
1096 * @param string $script
1098 public static function resetZendOpcache($script = '')
1100 if (self
::$zendOpcacheEnabled === null) {
1101 self
::$zendOpcacheEnabled = false;
1103 if (\
extension_loaded('Zend Opcache') && @\
ini_get('opcache.enable')) {
1104 self
::$zendOpcacheEnabled = true;
1108 if (self
::$zendOpcacheEnabled) {
1109 if (empty($script)) {
1112 \
opcache_invalidate($script, true);
1118 * Returns style handler.
1120 * @return StyleHandler
1122 public function getStyleHandler()
1124 return StyleHandler
::getInstance();
1128 * Returns box handler.
1130 * @return BoxHandler
1133 public function getBoxHandler()
1135 return BoxHandler
::getInstance();
1139 * Returns number of available updates.
1143 public function getAvailableUpdates()
1145 $data = PackageUpdateCacheBuilder
::getInstance()->getData();
1147 return $data['updates'];
1151 * Returns a 8 character prefix for editor autosave.
1155 public function getAutosavePrefix()
1157 return \
substr(\
sha1(\
preg_replace('~^https~', 'http', self
::getPath())), 0, 8);
1161 * Returns the favicon URL or a base64 encoded image.
1165 public function getFavicon()
1167 $activeApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1168 $wcf = ApplicationHandler
::getInstance()->getWCF();
1169 $favicon = StyleHandler
::getInstance()->getStyle()->getRelativeFavicon();
1171 if ($activeApplication->domainName
!== $wcf->domainName
) {
1172 if (\file_exists
(WCF_DIR
. $favicon)) {
1173 $favicon = \file_get_contents
(WCF_DIR
. $favicon);
1175 return 'data:image/x-icon;base64,' . \base
64_encode
($favicon);
1179 return self
::getPath() . $favicon;
1183 * Returns true if the desktop notifications should be enabled.
1187 public function useDesktopNotifications()
1189 if (!ENABLE_DESKTOP_NOTIFICATIONS
) {
1191 } elseif (ApplicationHandler
::getInstance()->isMultiDomainSetup()) {
1192 $application = ApplicationHandler
::getInstance()->getApplicationByID(DESKTOP_NOTIFICATION_PACKAGE_ID
);
1193 // mismatch, default to Core
1194 if ($application === null) {
1195 $application = ApplicationHandler
::getInstance()->getApplicationByID(1);
1198 $currentApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1199 if ($currentApplication->domainName
!= $application->domainName
) {
1209 * Returns true if currently active request represents the landing page.
1213 public static function isLandingPage()
1215 if (self
::getActiveRequest() === null) {
1219 return self
::getActiveRequest()->isLandingPage();
1223 * Returns true if the given API version is currently supported.
1225 * @param int $apiVersion
1229 public static function isSupportedApiVersion($apiVersion)
1231 return ($apiVersion == WSC_API_VERSION
) || \
in_array($apiVersion, self
::$supportedLegacyApiVersions);
1235 * Returns the list of supported legacy API versions.
1240 public static function getSupportedLegacyApiVersions()
1242 return self
::$supportedLegacyApiVersions;
1246 * Initialises the cronjobs.
1248 protected function initCronjobs()
1251 self
::getTPL()->assign(
1253 CronjobScheduler
::getInstance()->getNextExec() < TIME_NOW
&& \
defined('OFFLINE') && !OFFLINE
1259 * Checks recursively that the most important system files of `com.woltlab.wcf` are writable.
1261 * @throws \RuntimeException if any relevant file or directory is not writable
1263 public static function checkWritability()
1265 $nonWritablePaths = [];
1267 $nonRecursiveDirectories = [
1272 foreach ($nonRecursiveDirectories as $directory) {
1273 $path = WCF_DIR
. $directory;
1274 if ($path === 'tmp/' && !\
is_dir($path)) {
1278 if (!\
is_writable($path)) {
1279 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1283 DirectoryUtil
::getInstance($path, false)
1284 ->executeCallback(static function ($file, \SplFileInfo
$fileInfo) use (&$nonWritablePaths) {
1285 if ($fileInfo instanceof \DirectoryIterator
) {
1286 if (!\
is_writable($fileInfo->getPath())) {
1287 $nonWritablePaths[] = FileUtil
::getRelativePath(
1288 $_SERVER['DOCUMENT_ROOT'],
1289 $fileInfo->getPath()
1292 } elseif (!\
is_writable($fileInfo->getRealPath())) {
1293 $nonWritablePaths[] = FileUtil
::getRelativePath(
1294 $_SERVER['DOCUMENT_ROOT'],
1295 $fileInfo->getPath()
1296 ) . $fileInfo->getFilename();
1301 $recursiveDirectories = [
1312 foreach ($recursiveDirectories as $directory) {
1313 $path = WCF_DIR
. $directory;
1315 if (!\
is_writable($path)) {
1316 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1320 DirectoryUtil
::getInstance($path)
1321 ->executeCallback(static function ($file, \SplFileInfo
$fileInfo) use (&$nonWritablePaths) {
1322 if ($fileInfo instanceof \DirectoryIterator
) {
1323 if (!\
is_writable($fileInfo->getPath())) {
1324 $nonWritablePaths[] = FileUtil
::getRelativePath(
1325 $_SERVER['DOCUMENT_ROOT'],
1326 $fileInfo->getPath()
1329 } elseif (!\
is_writable($fileInfo->getRealPath())) {
1330 $nonWritablePaths[] = FileUtil
::getRelativePath(
1331 $_SERVER['DOCUMENT_ROOT'],
1332 $fileInfo->getPath()
1333 ) . $fileInfo->getFilename();
1338 if (!empty($nonWritablePaths)) {
1340 throw new \
RuntimeException('The following paths are not writable: ' . \
implode(
1347 ) . (\
count($nonWritablePaths) > $maxPaths ?
',' . StringUtil
::HELLIP
: ''));