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.3.2');
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 $filename = WCF_DIR
. 'options.inc.php';
424 // create options file if doesn't exist
425 if (!\file_exists
($filename) || \filemtime
($filename) <= 1) {
426 OptionEditor
::rebuild();
430 // check if option file is complete and writable
432 if (!\
is_writable($filename)) {
433 FileUtil
::makeWritable($filename);
435 if (!\
is_writable($filename)) {
436 throw new SystemException("The option file '" . $filename . "' is not writable.");
440 // check if a previous write operation was incomplete and force rebuilding
441 if (!\
defined('WCF_OPTION_INC_PHP_SUCCESS')) {
442 OptionEditor
::rebuild();
447 if (ENABLE_DEBUG_MODE
) {
448 self
::$dbObj->enableDebugMode();
454 * Starts the session system.
456 protected function initSession()
458 $factory = new SessionFactory();
461 self
::$sessionObj = SessionHandler
::getInstance();
465 * Initialises the language engine.
467 protected function initLanguage()
469 if (isset($_GET['l']) && !self
::getUser()->userID
) {
470 self
::getSession()->setLanguageID(\
intval($_GET['l']));
474 \
mb_internal_encoding('UTF-8');
475 if (\function_exists
('mb_regex_encoding')) {
476 \
mb_regex_encoding('UTF-8');
481 self
::$languageObj = LanguageFactory
::getInstance()->getUserLanguage(self
::getSession()->getLanguageID());
485 * Initialises the template engine.
487 protected function initTPL()
489 self
::$tplObj = TemplateEngine
::getInstance();
490 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
491 $this->assignDefaultTemplateVariables();
497 * Initializes the user's style.
499 protected function initStyle()
501 if (isset($_REQUEST['styleID'])) {
502 self
::getSession()->setStyleID(\
intval($_REQUEST['styleID']));
505 $styleHandler = StyleHandler
::getInstance();
506 $styleHandler->changeStyle(self
::getSession()->getStyleID());
510 * Executes the blacklist.
512 protected function initBlacklist()
514 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
516 if (\
defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES
!= '') {
518 !StringUtil
::executeWordFilter(
519 UserUtil
::convertIPv6To4(UserUtil
::getIpAddress()),
520 BLACKLIST_IP_ADDRESSES
524 throw new AJAXException(
525 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
526 AJAXException
::INSUFFICIENT_PERMISSIONS
529 throw new PermissionDeniedException();
531 } elseif (!StringUtil
::executeWordFilter(UserUtil
::getIpAddress(), BLACKLIST_IP_ADDRESSES
)) {
533 throw new AJAXException(
534 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
535 AJAXException
::INSUFFICIENT_PERMISSIONS
538 throw new PermissionDeniedException();
542 if (\
defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS
!= '') {
543 if (!StringUtil
::executeWordFilter(UserUtil
::getUserAgent(), BLACKLIST_USER_AGENTS
)) {
545 throw new AJAXException(
546 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
547 AJAXException
::INSUFFICIENT_PERMISSIONS
550 throw new PermissionDeniedException();
554 if (\
defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES
!= '') {
555 if (!StringUtil
::executeWordFilter(@\
gethostbyaddr(UserUtil
::getIpAddress()), BLACKLIST_HOSTNAMES
)) {
557 throw new AJAXException(
558 self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
559 AJAXException
::INSUFFICIENT_PERMISSIONS
562 throw new PermissionDeniedException();
567 // handle banned users
568 if (self
::getUser()->userID
&& self
::getUser()->banned
&& !self
::getUser()->hasOwnerAccess()) {
570 throw new AJAXException(
571 self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'),
572 AJAXException
::INSUFFICIENT_PERMISSIONS
575 self
::$forceLogout = true;
578 if (isset($_COOKIE[COOKIE_PREFIX
. 'userID'])) {
579 HeaderUtil
::setCookie('userID', 0);
581 if (isset($_COOKIE[COOKIE_PREFIX
. 'password'])) {
582 HeaderUtil
::setCookie('password', '');
585 throw new NamedUserException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
591 * Initializes applications.
593 protected function initApplications()
595 // step 1) load all applications
596 $loadedApplications = [];
598 // register WCF as application
599 self
::$applications['wcf'] = ApplicationHandler
::getInstance()->getApplicationByID(1);
601 if (!\
class_exists(WCFACP
::class, false)) {
602 static::getTPL()->assign('baseHref', self
::$applications['wcf']->getPageURL());
605 // start main application
606 $application = ApplicationHandler
::getInstance()->getActiveApplication();
607 if ($application->packageID
!= 1) {
608 $loadedApplications[] = $this->loadApplication($application);
610 // register primary application
611 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
612 self
::$applications[$abbreviation] = $application;
615 // start dependent applications
616 $applications = ApplicationHandler
::getInstance()->getDependentApplications();
617 foreach ($applications as $application) {
618 if ($application->packageID
== 1) {
621 } elseif ($application->isTainted
) {
622 // ignore apps flagged for uninstallation
626 $loadedApplications[] = $this->loadApplication($application, true);
629 // step 2) run each application
630 if (!\
class_exists('wcf\system\WCFACP', false)) {
631 /** @var IApplication $application */
632 foreach ($loadedApplications as $application) {
633 $application->__run();
636 /** @deprecated The below variable is deprecated. */
637 self
::getTPL()->assign('__sessionKeepAlive', 59 * 60);
642 * Loads an application.
644 * @param Application $application
645 * @param bool $isDependentApplication
646 * @return IApplication
647 * @throws SystemException
649 protected function loadApplication(Application
$application, $isDependentApplication = false)
651 $package = PackageCache
::getInstance()->getPackage($application->packageID
);
652 // package cache might be outdated
653 if ($package === null) {
654 $package = new Package($application->packageID
);
656 // package cache is outdated, discard cache
657 if ($package->packageID
) {
658 PackageEditor
::resetCache();
660 // package id is invalid
661 throw new SystemException("application identified by package id '" . $application->packageID
. "' is unknown");
665 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
666 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $package->packageDir
);
667 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
669 $className = $abbreviation . '\system\\' . \
strtoupper($abbreviation) . 'Core';
671 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
672 if (!\
class_exists($className)) {
673 // check if both the Core and the app are on the same domain
674 $coreApp = ApplicationHandler
::getInstance()->getApplicationByID(1);
675 if ($coreApp->domainName
=== $application->domainName
) {
676 // resolve the relative path and use it to construct the autoload directory
677 $relativePath = FileUtil
::getRelativePath($coreApp->domainPath
, $application->domainPath
);
678 if ($relativePath !== './') {
679 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $relativePath);
680 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
682 if (\
class_exists($className)) {
683 // the class can now be found, update the `packageDir` value
684 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
690 if (\
class_exists($className) && \
is_subclass_of($className, IApplication
::class)) {
691 // include config file
692 $configPath = $packageDir . PackageInstallationDispatcher
::CONFIG_FILE
;
693 if (!\file_exists
($configPath)) {
694 Package
::writeConfigFile($package->packageID
);
697 if (\file_exists
($configPath)) {
698 require_once($configPath);
700 throw new SystemException('Unable to load configuration for ' . $package->package
);
703 // register template path if not within ACP
704 if (!\
class_exists('wcf\system\WCFACP', false)) {
705 // add template path and abbreviation
706 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
708 EmailTemplateEngine
::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
710 // init application and assign it as template variable
711 self
::$applicationObjects[$application->packageID
] = \
call_user_func([$className, 'getInstance']);
712 static::getTPL()->assign('__' . $abbreviation, self
::$applicationObjects[$application->packageID
]);
713 EmailTemplateEngine
::getInstance()->assign(
714 '__' . $abbreviation,
715 self
::$applicationObjects[$application->packageID
]
718 unset(self
::$autoloadDirectories[$abbreviation]);
719 throw new SystemException("Unable to run '" . $package->package
. "', '" . $className . "' is missing or does not implement '" . IApplication
::class . "'.");
722 // register template path in ACP
723 if (\
class_exists('wcf\system\WCFACP', false)) {
724 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
725 } elseif (!$isDependentApplication) {
727 static::getTPL()->assign('baseHref', $application->getPageURL());
730 // register application
731 self
::$applications[$abbreviation] = $application;
733 return self
::$applicationObjects[$application->packageID
];
737 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
739 * @param Application $application
740 * @return IApplication
742 public static function getApplicationObject(Application
$application)
744 if (isset(self
::$applicationObjects[$application->packageID
])) {
745 return self
::$applicationObjects[$application->packageID
];
750 * Returns the invoked application.
752 * @return Application
755 public static function getActiveApplication()
757 return ApplicationHandler
::getInstance()->getActiveApplication();
761 * Loads an application on runtime, do not use this outside the package installation.
763 * @param int $packageID
765 public static function loadRuntimeApplication($packageID)
767 $package = new Package($packageID);
768 $application = new Application($packageID);
770 $abbreviation = Package
::getAbbreviation($package->package
);
771 $packageDir = FileUtil
::getRealPath(WCF_DIR
. $package->packageDir
);
772 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
773 self
::$applications[$abbreviation] = $application;
774 self
::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
778 * Initializes core object cache.
780 protected function initCoreObjects()
782 // ignore core objects if installing WCF
783 if (PACKAGE_ID
== 0) {
787 self
::$coreObjectCache = CoreObjectCacheBuilder
::getInstance()->getData();
791 * Assigns some default variables to the template engine.
793 protected function assignDefaultTemplateVariables()
797 if (ENABLE_ENTERPRISE_MODE
) {
798 $wcf = new TemplateScriptingCore($wcf);
801 self
::getTPL()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang', 'csrfToken']);
802 self
::getTPL()->assign([
804 '__wcfVersion' => LAST_UPDATE_TIME
, // @deprecated 2.1, use LAST_UPDATE_TIME directly
807 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
808 // Execute background queue in this request, if it was requested and AJAX isn't used.
810 if (self
::getSession()->getVar('forceBackgroundQueuePerform')) {
811 self
::getTPL()->assign([
812 'forceBackgroundQueuePerform' => true,
815 self
::getSession()->unregister('forceBackgroundQueuePerform');
819 EmailTemplateEngine
::getInstance()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang']);
820 EmailTemplateEngine
::getInstance()->assign([
826 * Wrapper for the getter methods of this class.
828 * @param string $name
829 * @return mixed value
830 * @throws SystemException
832 public function __get($name)
834 $method = 'get' . \
ucfirst($name);
835 if (\
method_exists($this, $method)) {
836 return $this->{$method}();
839 throw new SystemException("method '" . $method . "' does not exist in class WCF");
843 * Returns true if current application (WCF) is treated as active and was invoked directly.
847 public function isActiveApplication()
849 return ApplicationHandler
::getInstance()->getActiveApplication()->packageID
== 1;
853 * Changes the active language.
855 * @param int $languageID
857 final public static function setLanguage($languageID)
859 if (!$languageID || LanguageFactory
::getInstance()->getLanguage($languageID) === null) {
860 $languageID = LanguageFactory
::getInstance()->getDefaultLanguageID();
863 self
::$languageObj = LanguageFactory
::getInstance()->getLanguage($languageID);
865 // the template engine may not be available yet, usually happens when
866 // changing the user (and thus the language id) during session init
867 if (self
::$tplObj !== null) {
868 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
869 EmailTemplateEngine
::getInstance()->setLanguageID(self
::getLanguage()->languageID
);
874 * Includes the required util or exception classes automatically.
876 * @param string $className
877 * @see spl_autoload_register()
879 final public static function autoload($className)
881 $namespaces = \
explode('\\', $className);
882 if (\
count($namespaces) > 1) {
883 $applicationPrefix = \array_shift
($namespaces);
884 if ($applicationPrefix === '') {
885 $applicationPrefix = \array_shift
($namespaces);
887 if (isset(self
::$autoloadDirectories[$applicationPrefix])) {
888 $classPath = self
::$autoloadDirectories[$applicationPrefix] . \
implode('/', $namespaces) . '.class.php';
890 // PHP will implicitly check if the file exists when including it, which means that we can save a
891 // redundant syscall/fs access by not checking for existence ourselves. Do not use require_once()!
892 @include_once
($classPath);
900 final public function __call($name, array $arguments)
902 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
903 if (!\
method_exists($this, $name)) {
904 return self
::__callStatic($name, $arguments);
907 throw new \
BadMethodCallException("Call to undefined method WCF::{$name}().");
911 * Returns dynamically loaded core objects.
913 * @param string $name
914 * @param array $arguments
916 * @throws SystemException
918 final public static function __callStatic($name, array $arguments)
920 $className = \
preg_replace('~^get~', '', $name);
922 if (isset(self
::$coreObject[$className])) {
923 return self
::$coreObject[$className];
926 $objectName = self
::getCoreObject($className);
927 if ($objectName === null) {
928 throw new SystemException("Core object '" . $className . "' is unknown.");
931 if (\
class_exists($objectName)) {
932 if (!\
is_subclass_of($objectName, SingletonFactory
::class)) {
933 throw new ParentClassException($objectName, SingletonFactory
::class);
936 self
::$coreObject[$className] = \
call_user_func([$objectName, 'getInstance']);
938 return self
::$coreObject[$className];
943 * Searches for cached core object definition.
945 * @param string $className
948 final protected static function getCoreObject($className)
950 if (isset(self
::$coreObjectCache[$className])) {
951 return self
::$coreObjectCache[$className];
956 * Returns true if the debug mode is enabled, otherwise false.
958 * @param bool $ignoreACP
961 public static function debugModeIsEnabled($ignoreACP = false)
964 if (!$ignoreACP && self
::$overrideDebugMode) {
966 } elseif (\
defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE
) {
974 * Returns true if benchmarking is enabled, otherwise false.
978 public static function benchmarkIsEnabled()
980 // benchmarking is enabled by default
981 if (!\
defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK
) {
989 * Returns domain path for given application.
991 * @param string $abbreviation
994 public static function getPath($abbreviation = 'wcf')
996 // workaround during WCFSetup
1001 if (!isset(self
::$applications[$abbreviation])) {
1002 $abbreviation = 'wcf';
1005 return self
::$applications[$abbreviation]->getPageURL();
1009 * Returns the domain path for the currently active application,
1010 * used to avoid CORS requests.
1014 public static function getActivePath()
1017 return self
::getPath();
1020 // We cannot rely on the ApplicationHandler's `getActiveApplication()` because
1021 // it uses the requested controller to determine the namespace. However, starting
1022 // with WoltLab Suite 5.2, system pages can be virtually assigned to a different
1023 // app, resolving against the target app without changing the namespace.
1024 return self
::getPath(ApplicationHandler
::getInstance()->getAbbreviation(PACKAGE_ID
));
1028 * Returns a fully qualified anchor for current page.
1030 * @param string $fragment
1033 public function getAnchor($fragment)
1035 return StringUtil
::encodeHTML(self
::getRequestURI() . '#' . $fragment);
1039 * Returns the currently active page or null if unknown.
1043 public static function getActivePage()
1045 if (self
::getActiveRequest() === null) {
1049 if (self
::getActiveRequest()->getClassName() === CmsPage
::class) {
1050 $metaData = self
::getActiveRequest()->getMetaData();
1051 if (isset($metaData['cms'])) {
1052 return PageCache
::getInstance()->getPage($metaData['cms']['pageID']);
1058 return PageCache
::getInstance()->getPageByController(self
::getActiveRequest()->getClassName());
1062 * Returns the currently active request.
1066 public static function getActiveRequest()
1068 return RequestHandler
::getInstance()->getActiveRequest();
1072 * Returns the URI of the current page.
1076 public static function getRequestURI()
1078 return \
preg_replace(
1079 '~^(https?://[^/]+)(?:/.*)?$~',
1081 self
::getTPL()->get('baseHref')
1082 ) . $_SERVER['REQUEST_URI'];
1086 * Resets Zend Opcache cache if installed and enabled.
1088 * @param string $script
1090 public static function resetZendOpcache($script = '')
1092 if (self
::$zendOpcacheEnabled === null) {
1093 self
::$zendOpcacheEnabled = false;
1095 if (\
extension_loaded('Zend Opcache') && @\
ini_get('opcache.enable')) {
1096 self
::$zendOpcacheEnabled = true;
1100 if (self
::$zendOpcacheEnabled) {
1101 if (empty($script)) {
1104 \
opcache_invalidate($script, true);
1110 * Returns style handler.
1112 * @return StyleHandler
1114 public function getStyleHandler()
1116 return StyleHandler
::getInstance();
1120 * Returns box handler.
1122 * @return BoxHandler
1125 public function getBoxHandler()
1127 return BoxHandler
::getInstance();
1131 * Returns number of available updates.
1135 public function getAvailableUpdates()
1137 $data = PackageUpdateCacheBuilder
::getInstance()->getData();
1139 return $data['updates'];
1143 * Returns a 8 character prefix for editor autosave.
1147 public function getAutosavePrefix()
1149 return \
substr(\
sha1(\
preg_replace('~^https~', 'http', self
::getPath())), 0, 8);
1153 * Returns the favicon URL or a base64 encoded image.
1157 public function getFavicon()
1159 $activeApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1160 $wcf = ApplicationHandler
::getInstance()->getWCF();
1161 $favicon = StyleHandler
::getInstance()->getStyle()->getRelativeFavicon();
1163 if ($activeApplication->domainName
!== $wcf->domainName
) {
1164 if (\file_exists
(WCF_DIR
. $favicon)) {
1165 $favicon = \file_get_contents
(WCF_DIR
. $favicon);
1167 return 'data:image/x-icon;base64,' . \base
64_encode
($favicon);
1171 return self
::getPath() . $favicon;
1175 * Returns true if the desktop notifications should be enabled.
1179 public function useDesktopNotifications()
1181 if (!ENABLE_DESKTOP_NOTIFICATIONS
) {
1183 } elseif (ApplicationHandler
::getInstance()->isMultiDomainSetup()) {
1184 $application = ApplicationHandler
::getInstance()->getApplicationByID(DESKTOP_NOTIFICATION_PACKAGE_ID
);
1185 // mismatch, default to Core
1186 if ($application === null) {
1187 $application = ApplicationHandler
::getInstance()->getApplicationByID(1);
1190 $currentApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1191 if ($currentApplication->domainName
!= $application->domainName
) {
1201 * Returns true if currently active request represents the landing page.
1205 public static function isLandingPage()
1207 if (self
::getActiveRequest() === null) {
1211 return self
::getActiveRequest()->isLandingPage();
1215 * Returns true if the given API version is currently supported.
1217 * @param int $apiVersion
1221 public static function isSupportedApiVersion($apiVersion)
1223 return ($apiVersion == WSC_API_VERSION
) || \
in_array($apiVersion, self
::$supportedLegacyApiVersions);
1227 * Returns the list of supported legacy API versions.
1232 public static function getSupportedLegacyApiVersions()
1234 return self
::$supportedLegacyApiVersions;
1238 * Initialises the cronjobs.
1240 protected function initCronjobs()
1243 self
::getTPL()->assign(
1245 CronjobScheduler
::getInstance()->getNextExec() < TIME_NOW
&& \
defined('OFFLINE') && !OFFLINE
1251 * Checks recursively that the most important system files of `com.woltlab.wcf` are writable.
1253 * @throws \RuntimeException if any relevant file or directory is not writable
1255 public static function checkWritability()
1257 $nonWritablePaths = [];
1259 $nonRecursiveDirectories = [
1264 foreach ($nonRecursiveDirectories as $directory) {
1265 $path = WCF_DIR
. $directory;
1266 if ($path === 'tmp/' && !\
is_dir($path)) {
1270 if (!\
is_writable($path)) {
1271 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1275 DirectoryUtil
::getInstance($path, false)
1276 ->executeCallback(static function ($file, \SplFileInfo
$fileInfo) use (&$nonWritablePaths) {
1277 if ($fileInfo instanceof \DirectoryIterator
) {
1278 if (!\
is_writable($fileInfo->getPath())) {
1279 $nonWritablePaths[] = FileUtil
::getRelativePath(
1280 $_SERVER['DOCUMENT_ROOT'],
1281 $fileInfo->getPath()
1284 } elseif (!\
is_writable($fileInfo->getRealPath())) {
1285 $nonWritablePaths[] = FileUtil
::getRelativePath(
1286 $_SERVER['DOCUMENT_ROOT'],
1287 $fileInfo->getPath()
1288 ) . $fileInfo->getFilename();
1293 $recursiveDirectories = [
1304 foreach ($recursiveDirectories as $directory) {
1305 $path = WCF_DIR
. $directory;
1307 if (!\
is_writable($path)) {
1308 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1312 DirectoryUtil
::getInstance($path)
1313 ->executeCallback(static function ($file, \SplFileInfo
$fileInfo) use (&$nonWritablePaths) {
1314 if ($fileInfo instanceof \DirectoryIterator
) {
1315 if (!\
is_writable($fileInfo->getPath())) {
1316 $nonWritablePaths[] = FileUtil
::getRelativePath(
1317 $_SERVER['DOCUMENT_ROOT'],
1318 $fileInfo->getPath()
1321 } elseif (!\
is_writable($fileInfo->getRealPath())) {
1322 $nonWritablePaths[] = FileUtil
::getRelativePath(
1323 $_SERVER['DOCUMENT_ROOT'],
1324 $fileInfo->getPath()
1325 ) . $fileInfo->getFilename();
1330 if (!empty($nonWritablePaths)) {
1332 throw new \
RuntimeException('The following paths are not writable: ' . \
implode(
1339 ) . (\
count($nonWritablePaths) > $maxPaths ?
',' . StringUtil
::HELLIP
: ''));