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 \Exception $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 // The attachment module is always enabled since 5.2.
371 // https://github.com/WoltLab/WCF/issues/2531
372 \
define('MODULE_ATTACHMENT', 1);
374 // Users cannot react to their own content since 5.2.
375 // https://github.com/WoltLab/WCF/issues/2975
376 \
define('LIKE_ALLOW_FOR_OWN_CONTENT', 0);
377 \
define('LIKE_ENABLE_DISLIKE', 0);
379 // Thumbnails for attachments are already enabled since 5.3.
380 // https://github.com/WoltLab/WCF/pull/3444
381 \
define('ATTACHMENT_ENABLE_THUMBNAILS', 1);
383 // User markings are always applied in sidebars since 5.3.
384 // https://github.com/WoltLab/WCF/issues/3330
385 \
define('MESSAGE_SIDEBAR_ENABLE_USER_ONLINE_MARKING', 1);
387 // Password strength configuration is deprecated since 5.3.
388 \
define('REGISTER_ENABLE_PASSWORD_SECURITY_CHECK', 0);
389 \
define('REGISTER_PASSWORD_MIN_LENGTH', 0);
390 \
define('REGISTER_PASSWORD_MUST_CONTAIN_LOWER_CASE', 8);
391 \
define('REGISTER_PASSWORD_MUST_CONTAIN_UPPER_CASE', 0);
392 \
define('REGISTER_PASSWORD_MUST_CONTAIN_DIGIT', 0);
393 \
define('REGISTER_PASSWORD_MUST_CONTAIN_SPECIAL_CHAR', 0);
395 // rel=nofollow is always applied to external link since 5.3
396 // https://github.com/WoltLab/WCF/issues/3339
397 \
define('EXTERNAL_LINK_REL_NOFOLLOW', 1);
399 // Session validation is removed since 5.4.
400 // https://github.com/WoltLab/WCF/pull/3583
401 \
define('SESSION_VALIDATE_IP_ADDRESS', 0);
402 \
define('SESSION_VALIDATE_USER_AGENT', 0);
404 // Virtual sessions no longer exist since 5.4.
405 \
define('SESSION_ENABLE_VIRTUALIZATION', 1);
407 // The session timeout is fully managed since 5.4.
408 \
define('SESSION_TIMEOUT', 3600);
410 // gzip compression is removed in 5.4.
411 // https://github.com/WoltLab/WCF/issues/3634
412 \
define('HTTP_ENABLE_GZIP', 0);
414 // Meta keywords are no longer used since 5.4.
415 // https://github.com/WoltLab/WCF/issues/3561
416 \
define('META_KEYWORDS', '');
418 // The admin notification is redundant and removed in 5.4.
419 // https://github.com/WoltLab/WCF/issues/3674
420 \
define('REGISTER_ADMIN_NOTIFICATION', 0);
422 // The hostname blocklist was removed in 5.4.
423 // https://github.com/WoltLab/WCF/issues/3909
424 \
define('BLACKLIST_HOSTNAMES', '');
426 // Cover photos are always enabled since 5.4.
427 // https://github.com/WoltLab/WCF/issues/3902
428 \
define('MODULE_USER_COVER_PHOTO', 1);
430 $filename = WCF_DIR
. 'options.inc.php';
432 // create options file if doesn't exist
433 if (!\file_exists
($filename) || \filemtime
($filename) <= 1) {
434 OptionEditor
::rebuild();
438 // check if option file is complete and writable
440 if (!\
is_writable($filename)) {
441 FileUtil
::makeWritable($filename);
443 if (!\
is_writable($filename)) {
444 throw new SystemException("The option file '" . $filename . "' is not writable.");
448 // check if a previous write operation was incomplete and force rebuilding
449 if (!\
defined('WCF_OPTION_INC_PHP_SUCCESS')) {
450 OptionEditor
::rebuild();
455 if (ENABLE_DEBUG_MODE
) {
456 self
::$dbObj->enableDebugMode();
462 * Starts the session system.
464 protected function initSession()
466 $factory = new SessionFactory();
469 self
::$sessionObj = SessionHandler
::getInstance();
473 * Initialises the language engine.
475 protected function initLanguage()
477 if (isset($_GET['l']) && !self
::getUser()->userID
) {
478 self
::getSession()->setLanguageID(\
intval($_GET['l']));
482 \
mb_internal_encoding('UTF-8');
483 if (\function_exists
('mb_regex_encoding')) {
484 \
mb_regex_encoding('UTF-8');
489 self
::$languageObj = LanguageFactory
::getInstance()->getUserLanguage(self
::getSession()->getLanguageID());
493 * Initialises the template engine.
495 protected function initTPL()
497 self
::$tplObj = TemplateEngine
::getInstance();
498 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
499 $this->assignDefaultTemplateVariables();
505 * Initializes the user's style.
507 protected function initStyle()
509 if (isset($_REQUEST['styleID'])) {
510 self
::getSession()->setStyleID(\
intval($_REQUEST['styleID']));
513 $styleHandler = StyleHandler
::getInstance();
514 $styleHandler->changeStyle(self
::getSession()->getStyleID());
518 * Executes the blacklist.
520 protected function initBlacklist()
522 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
524 if (\
defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES
!= '') {
526 !StringUtil
::executeWordFilter(
527 UserUtil
::convertIPv6To4(UserUtil
::getIpAddress()),
528 BLACKLIST_IP_ADDRESSES
532 throw new AJAXException(
533 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
534 AJAXException
::INSUFFICIENT_PERMISSIONS
537 throw new PermissionDeniedException();
539 } elseif (!StringUtil
::executeWordFilter(UserUtil
::getIpAddress(), BLACKLIST_IP_ADDRESSES
)) {
541 throw new AJAXException(
542 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
543 AJAXException
::INSUFFICIENT_PERMISSIONS
546 throw new PermissionDeniedException();
550 if (\
defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS
!= '') {
551 if (!StringUtil
::executeWordFilter(UserUtil
::getUserAgent(), BLACKLIST_USER_AGENTS
)) {
553 throw new AJAXException(
554 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
555 AJAXException
::INSUFFICIENT_PERMISSIONS
558 throw new PermissionDeniedException();
563 // handle banned users
564 if (self
::getUser()->userID
&& self
::getUser()->banned
&& !self
::getUser()->hasOwnerAccess()) {
566 throw new AJAXException(
567 self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'),
568 AJAXException
::INSUFFICIENT_PERMISSIONS
571 self
::$forceLogout = true;
574 if (isset($_COOKIE[COOKIE_PREFIX
. 'userID'])) {
575 HeaderUtil
::setCookie('userID', 0);
577 if (isset($_COOKIE[COOKIE_PREFIX
. 'password'])) {
578 HeaderUtil
::setCookie('password', '');
581 throw new NamedUserException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
587 * Initializes applications.
589 protected function initApplications()
591 // step 1) load all applications
592 $loadedApplications = [];
594 // register WCF as application
595 self
::$applications['wcf'] = ApplicationHandler
::getInstance()->getApplicationByID(1);
597 if (!\
class_exists(WCFACP
::class, false)) {
598 static::getTPL()->assign('baseHref', self
::$applications['wcf']->getPageURL());
601 // start main application
602 $application = ApplicationHandler
::getInstance()->getActiveApplication();
603 if ($application->packageID
!= 1) {
604 $loadedApplications[] = $this->loadApplication($application);
606 // register primary application
607 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
608 self
::$applications[$abbreviation] = $application;
611 // start dependent applications
612 $applications = ApplicationHandler
::getInstance()->getDependentApplications();
613 foreach ($applications as $application) {
614 if ($application->packageID
== 1) {
617 } elseif ($application->isTainted
) {
618 // ignore apps flagged for uninstallation
622 $loadedApplications[] = $this->loadApplication($application, true);
625 // step 2) run each application
626 if (!\
class_exists('wcf\system\WCFACP', false)) {
627 /** @var IApplication $application */
628 foreach ($loadedApplications as $application) {
629 $application->__run();
632 /** @deprecated The below variable is deprecated. */
633 self
::getTPL()->assign('__sessionKeepAlive', 59 * 60);
638 * Loads an application.
640 * @param Application $application
641 * @param bool $isDependentApplication
642 * @return IApplication
643 * @throws SystemException
645 protected function loadApplication(Application
$application, $isDependentApplication = false)
647 $package = PackageCache
::getInstance()->getPackage($application->packageID
);
648 // package cache might be outdated
649 if ($package === null) {
650 $package = new Package($application->packageID
);
652 // package cache is outdated, discard cache
653 if ($package->packageID
) {
654 PackageEditor
::resetCache();
656 // package id is invalid
657 throw new SystemException("application identified by package id '" . $application->packageID
. "' is unknown");
661 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
662 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $package->packageDir
);
663 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
665 $className = $abbreviation . '\system\\' . \
strtoupper($abbreviation) . 'Core';
667 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
668 if (!\
class_exists($className)) {
669 // check if both the Core and the app are on the same domain
670 $coreApp = ApplicationHandler
::getInstance()->getApplicationByID(1);
671 if ($coreApp->domainName
=== $application->domainName
) {
672 // resolve the relative path and use it to construct the autoload directory
673 $relativePath = FileUtil
::getRelativePath($coreApp->domainPath
, $application->domainPath
);
674 if ($relativePath !== './') {
675 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $relativePath);
676 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
678 if (\
class_exists($className)) {
679 // the class can now be found, update the `packageDir` value
680 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
686 if (\
class_exists($className) && \
is_subclass_of($className, IApplication
::class)) {
687 // include config file
688 $configPath = $packageDir . PackageInstallationDispatcher
::CONFIG_FILE
;
689 if (!\file_exists
($configPath)) {
690 Package
::writeConfigFile($package->packageID
);
693 if (\file_exists
($configPath)) {
694 require_once($configPath);
696 throw new SystemException('Unable to load configuration for ' . $package->package
);
699 // register template path if not within ACP
700 if (!\
class_exists('wcf\system\WCFACP', false)) {
701 // add template path and abbreviation
702 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
704 EmailTemplateEngine
::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
706 // init application and assign it as template variable
707 self
::$applicationObjects[$application->packageID
] = \
call_user_func([$className, 'getInstance']);
708 static::getTPL()->assign('__' . $abbreviation, self
::$applicationObjects[$application->packageID
]);
709 EmailTemplateEngine
::getInstance()->assign(
710 '__' . $abbreviation,
711 self
::$applicationObjects[$application->packageID
]
714 unset(self
::$autoloadDirectories[$abbreviation]);
715 throw new SystemException("Unable to run '" . $package->package
. "', '" . $className . "' is missing or does not implement '" . IApplication
::class . "'.");
718 // register template path in ACP
719 if (\
class_exists('wcf\system\WCFACP', false)) {
720 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
721 } elseif (!$isDependentApplication) {
723 static::getTPL()->assign('baseHref', $application->getPageURL());
726 // register application
727 self
::$applications[$abbreviation] = $application;
729 return self
::$applicationObjects[$application->packageID
];
733 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
735 * @param Application $application
736 * @return IApplication
738 public static function getApplicationObject(Application
$application)
740 if (isset(self
::$applicationObjects[$application->packageID
])) {
741 return self
::$applicationObjects[$application->packageID
];
746 * Returns the invoked application.
748 * @return Application
751 public static function getActiveApplication()
753 return ApplicationHandler
::getInstance()->getActiveApplication();
757 * Loads an application on runtime, do not use this outside the package installation.
759 * @param int $packageID
761 public static function loadRuntimeApplication($packageID)
763 $package = new Package($packageID);
764 $application = new Application($packageID);
766 $abbreviation = Package
::getAbbreviation($package->package
);
767 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $package->packageDir
);
768 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
769 self
::$applications[$abbreviation] = $application;
770 self
::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
774 * Initializes core object cache.
776 protected function initCoreObjects()
778 // ignore core objects if installing WCF
779 if (PACKAGE_ID
== 0) {
783 self
::$coreObjectCache = CoreObjectCacheBuilder
::getInstance()->getData();
787 * Assigns some default variables to the template engine.
789 protected function assignDefaultTemplateVariables()
793 if (ENABLE_ENTERPRISE_MODE
) {
794 $wcf = new TemplateScriptingCore($wcf);
797 self
::getTPL()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang', 'csrfToken']);
798 self
::getTPL()->assign([
800 '__wcfVersion' => LAST_UPDATE_TIME
, // @deprecated 2.1, use LAST_UPDATE_TIME directly
803 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
804 // Execute background queue in this request, if it was requested and AJAX isn't used.
806 if (self
::getSession()->getVar('forceBackgroundQueuePerform')) {
807 self
::getTPL()->assign([
808 'forceBackgroundQueuePerform' => true,
811 self
::getSession()->unregister('forceBackgroundQueuePerform');
815 EmailTemplateEngine
::getInstance()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang']);
816 EmailTemplateEngine
::getInstance()->assign([
822 * Wrapper for the getter methods of this class.
824 * @param string $name
825 * @return mixed value
826 * @throws SystemException
828 public function __get($name)
830 $method = 'get' . \
ucfirst($name);
831 if (\
method_exists($this, $method)) {
832 return $this->{$method}();
835 throw new SystemException("method '" . $method . "' does not exist in class WCF");
839 * Returns true if current application (WCF) is treated as active and was invoked directly.
843 public function isActiveApplication()
845 return ApplicationHandler
::getInstance()->getActiveApplication()->packageID
== 1;
849 * Changes the active language.
851 * @param int $languageID
853 final public static function setLanguage($languageID)
855 if (!$languageID || LanguageFactory
::getInstance()->getLanguage($languageID) === null) {
856 $languageID = LanguageFactory
::getInstance()->getDefaultLanguageID();
859 self
::$languageObj = LanguageFactory
::getInstance()->getLanguage($languageID);
861 // the template engine may not be available yet, usually happens when
862 // changing the user (and thus the language id) during session init
863 if (self
::$tplObj !== null) {
864 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
865 EmailTemplateEngine
::getInstance()->setLanguageID(self
::getLanguage()->languageID
);
870 * Includes the required util or exception classes automatically.
872 * @param string $className
873 * @see spl_autoload_register()
875 final public static function autoload($className)
877 $namespaces = \
explode('\\', $className);
878 if (\
count($namespaces) > 1) {
879 $applicationPrefix = \array_shift
($namespaces);
880 if ($applicationPrefix === '') {
881 $applicationPrefix = \array_shift
($namespaces);
883 if (isset(self
::$autoloadDirectories[$applicationPrefix])) {
884 $classPath = self
::$autoloadDirectories[$applicationPrefix] . \
implode('/', $namespaces) . '.class.php';
886 // PHP will implicitly check if the file exists when including it, which means that we can save a
887 // redundant syscall/fs access by not checking for existence ourselves. Do not use require_once()!
888 @include_once
($classPath);
896 final public function __call($name, array $arguments)
898 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
899 if (!\
method_exists($this, $name)) {
900 return self
::__callStatic($name, $arguments);
903 throw new \
BadMethodCallException("Call to undefined method WCF::{$name}().");
907 * Returns dynamically loaded core objects.
909 * @param string $name
910 * @param array $arguments
912 * @throws SystemException
914 final public static function __callStatic($name, array $arguments)
916 $className = \
preg_replace('~^get~', '', $name);
918 if (isset(self
::$coreObject[$className])) {
919 return self
::$coreObject[$className];
922 $objectName = self
::getCoreObject($className);
923 if ($objectName === null) {
924 throw new SystemException("Core object '" . $className . "' is unknown.");
927 if (\
class_exists($objectName)) {
928 if (!\
is_subclass_of($objectName, SingletonFactory
::class)) {
929 throw new ParentClassException($objectName, SingletonFactory
::class);
932 self
::$coreObject[$className] = \
call_user_func([$objectName, 'getInstance']);
934 return self
::$coreObject[$className];
939 * Searches for cached core object definition.
941 * @param string $className
944 final protected static function getCoreObject($className)
946 if (isset(self
::$coreObjectCache[$className])) {
947 return self
::$coreObjectCache[$className];
952 * Returns true if the debug mode is enabled, otherwise false.
954 * @param bool $ignoreACP
957 public static function debugModeIsEnabled($ignoreACP = false)
960 if (!$ignoreACP && self
::$overrideDebugMode) {
962 } elseif (\
defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE
) {
970 * Returns true if benchmarking is enabled, otherwise false.
974 public static function benchmarkIsEnabled()
976 // benchmarking is enabled by default
977 if (!\
defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK
) {
985 * Returns domain path for given application.
987 * @param string $abbreviation
990 public static function getPath($abbreviation = 'wcf')
992 // workaround during WCFSetup
997 if (!isset(self
::$applications[$abbreviation])) {
998 $abbreviation = 'wcf';
1001 return self
::$applications[$abbreviation]->getPageURL();
1005 * Returns the domain path for the currently active application,
1006 * used to avoid CORS requests.
1010 public static function getActivePath()
1013 return self
::getPath();
1016 // We cannot rely on the ApplicationHandler's `getActiveApplication()` because
1017 // it uses the requested controller to determine the namespace. However, starting
1018 // with WoltLab Suite 5.2, system pages can be virtually assigned to a different
1019 // app, resolving against the target app without changing the namespace.
1020 return self
::getPath(ApplicationHandler
::getInstance()->getAbbreviation(PACKAGE_ID
));
1024 * Returns a fully qualified anchor for current page.
1026 * @param string $fragment
1029 public function getAnchor($fragment)
1031 return StringUtil
::encodeHTML(self
::getRequestURI() . '#' . $fragment);
1035 * Returns the currently active page or null if unknown.
1039 public static function getActivePage()
1041 if (self
::getActiveRequest() === null) {
1045 if (self
::getActiveRequest()->getClassName() === CmsPage
::class) {
1046 $metaData = self
::getActiveRequest()->getMetaData();
1047 if (isset($metaData['cms'])) {
1048 return PageCache
::getInstance()->getPage($metaData['cms']['pageID']);
1054 return PageCache
::getInstance()->getPageByController(self
::getActiveRequest()->getClassName());
1058 * Returns the currently active request.
1062 public static function getActiveRequest()
1064 return RequestHandler
::getInstance()->getActiveRequest();
1068 * Returns the URI of the current page.
1072 public static function getRequestURI()
1074 return \
preg_replace(
1075 '~^(https?://[^/]+)(?:/.*)?$~',
1077 self
::getTPL()->get('baseHref')
1078 ) . $_SERVER['REQUEST_URI'];
1082 * Resets Zend Opcache cache if installed and enabled.
1084 * @param string $script
1086 public static function resetZendOpcache($script = '')
1088 if (self
::$zendOpcacheEnabled === null) {
1089 self
::$zendOpcacheEnabled = false;
1091 if (\
extension_loaded('Zend Opcache') && @\
ini_get('opcache.enable')) {
1092 self
::$zendOpcacheEnabled = true;
1096 if (self
::$zendOpcacheEnabled) {
1097 if (empty($script)) {
1100 \
opcache_invalidate($script, true);
1106 * Returns style handler.
1108 * @return StyleHandler
1110 public function getStyleHandler()
1112 return StyleHandler
::getInstance();
1116 * Returns box handler.
1118 * @return BoxHandler
1121 public function getBoxHandler()
1123 return BoxHandler
::getInstance();
1127 * Returns number of available updates.
1131 public function getAvailableUpdates()
1133 $data = PackageUpdateCacheBuilder
::getInstance()->getData();
1135 return $data['updates'];
1139 * Returns a 8 character prefix for editor autosave.
1143 public function getAutosavePrefix()
1145 return \
substr(\
sha1(\
preg_replace('~^https~', 'http', self
::getPath())), 0, 8);
1149 * Returns the favicon URL or a base64 encoded image.
1153 public function getFavicon()
1155 $activeApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1156 $wcf = ApplicationHandler
::getInstance()->getWCF();
1157 $favicon = StyleHandler
::getInstance()->getStyle()->getRelativeFavicon();
1159 if ($activeApplication->domainName
!== $wcf->domainName
) {
1160 if (\file_exists
(WCF_DIR
. $favicon)) {
1161 $favicon = \file_get_contents
(WCF_DIR
. $favicon);
1163 return 'data:image/x-icon;base64,' . \base
64_encode
($favicon);
1167 return self
::getPath() . $favicon;
1171 * Returns true if the desktop notifications should be enabled.
1175 public function useDesktopNotifications()
1177 if (!ENABLE_DESKTOP_NOTIFICATIONS
) {
1179 } elseif (ApplicationHandler
::getInstance()->isMultiDomainSetup()) {
1180 $application = ApplicationHandler
::getInstance()->getApplicationByID(DESKTOP_NOTIFICATION_PACKAGE_ID
);
1181 // mismatch, default to Core
1182 if ($application === null) {
1183 $application = ApplicationHandler
::getInstance()->getApplicationByID(1);
1186 $currentApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1187 if ($currentApplication->domainName
!= $application->domainName
) {
1197 * Returns true if currently active request represents the landing page.
1201 public static function isLandingPage()
1203 if (self
::getActiveRequest() === null) {
1207 return self
::getActiveRequest()->isLandingPage();
1211 * Returns true if the given API version is currently supported.
1213 * @param int $apiVersion
1217 public static function isSupportedApiVersion($apiVersion)
1219 return ($apiVersion == WSC_API_VERSION
) || \
in_array($apiVersion, self
::$supportedLegacyApiVersions);
1223 * Returns the list of supported legacy API versions.
1228 public static function getSupportedLegacyApiVersions()
1230 return self
::$supportedLegacyApiVersions;
1234 * Initialises the cronjobs.
1236 protected function initCronjobs()
1239 self
::getTPL()->assign(
1241 CronjobScheduler
::getInstance()->getNextExec() < TIME_NOW
&& \
defined('OFFLINE') && !OFFLINE
1247 * Checks recursively that the most important system files of `com.woltlab.wcf` are writable.
1249 * @throws \RuntimeException if any relevant file or directory is not writable
1251 public static function checkWritability()
1253 $nonWritablePaths = [];
1255 $nonRecursiveDirectories = [
1260 foreach ($nonRecursiveDirectories as $directory) {
1261 $path = WCF_DIR
. $directory;
1262 if ($path === 'tmp/' && !\
is_dir($path)) {
1266 if (!\
is_writable($path)) {
1267 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1271 DirectoryUtil
::getInstance($path, false)
1272 ->executeCallback(static function ($file, \SplFileInfo
$fileInfo) use (&$nonWritablePaths) {
1273 if ($fileInfo instanceof \DirectoryIterator
) {
1274 if (!\
is_writable($fileInfo->getPath())) {
1275 $nonWritablePaths[] = FileUtil
::getRelativePath(
1276 $_SERVER['DOCUMENT_ROOT'],
1277 $fileInfo->getPath()
1280 } elseif (!\
is_writable($fileInfo->getRealPath())) {
1281 $nonWritablePaths[] = FileUtil
::getRelativePath(
1282 $_SERVER['DOCUMENT_ROOT'],
1283 $fileInfo->getPath()
1284 ) . $fileInfo->getFilename();
1289 $recursiveDirectories = [
1300 foreach ($recursiveDirectories as $directory) {
1301 $path = WCF_DIR
. $directory;
1303 if (!\
is_writable($path)) {
1304 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1308 DirectoryUtil
::getInstance($path)
1309 ->executeCallback(static function ($file, \SplFileInfo
$fileInfo) use (&$nonWritablePaths) {
1310 if ($fileInfo instanceof \DirectoryIterator
) {
1311 if (!\
is_writable($fileInfo->getPath())) {
1312 $nonWritablePaths[] = FileUtil
::getRelativePath(
1313 $_SERVER['DOCUMENT_ROOT'],
1314 $fileInfo->getPath()
1317 } elseif (!\
is_writable($fileInfo->getRealPath())) {
1318 $nonWritablePaths[] = FileUtil
::getRelativePath(
1319 $_SERVER['DOCUMENT_ROOT'],
1320 $fileInfo->getPath()
1321 ) . $fileInfo->getFilename();
1326 if (!empty($nonWritablePaths)) {
1328 throw new \
RuntimeException('The following paths are not writable: ' . \
implode(
1335 ) . (\
count($nonWritablePaths) > $maxPaths ?
',' . StringUtil
::HELLIP
: ''));