3 use wcf\data\application\Application
;
4 use wcf\data\option\OptionEditor
;
5 use wcf\data\package\Package
;
6 use wcf\data\package\PackageCache
;
7 use wcf\data\package\PackageEditor
;
8 use wcf\data\page\Page
;
9 use wcf\data\page\PageCache
;
11 use wcf\system\application\ApplicationHandler
;
12 use wcf\system\application\IApplication
;
13 use wcf\system\box\BoxHandler
;
14 use wcf\system\cache\builder\CoreObjectCacheBuilder
;
15 use wcf\system\cache\builder\PackageUpdateCacheBuilder
;
16 use wcf\system\cronjob\CronjobScheduler
;
17 use wcf\system\database\MySQLDatabase
;
18 use wcf\system\event\EventHandler
;
19 use wcf\system\exception\AJAXException
;
20 use wcf\system\exception\ErrorException
;
21 use wcf\system\exception\IPrintableException
;
22 use wcf\system\exception\NamedUserException
;
23 use wcf\system\exception\ParentClassException
;
24 use wcf\system\exception\PermissionDeniedException
;
25 use wcf\system\exception\SystemException
;
26 use wcf\system\language\LanguageFactory
;
27 use wcf\system\package\PackageInstallationDispatcher
;
28 use wcf\system\registry\RegistryHandler
;
29 use wcf\system\request\Request
;
30 use wcf\system\request\RequestHandler
;
31 use wcf\system\session\SessionFactory
;
32 use wcf\system\session\SessionHandler
;
33 use wcf\system\style\StyleHandler
;
34 use wcf\system\template\EmailTemplateEngine
;
35 use wcf\system\template\TemplateEngine
;
36 use wcf\system\user\storage\UserStorageHandler
;
37 use wcf\util\DirectoryUtil
;
38 use wcf\util\FileUtil
;
39 use wcf\util\HeaderUtil
;
40 use wcf\util\StringUtil
;
41 use wcf\util\UserUtil
;
43 // phpcs:disable PSR1.Files.SideEffects
45 // try to set a time-limit to infinite
48 // fix timezone warning issue
49 if (!@ini_get
('date.timezone')) {
50 @date_default_timezone_set
('Europe/London');
53 // define current woltlab suite version
54 define('WCF_VERSION', '5.3.2');
56 // define current API version
58 define('WSC_API_VERSION', 2019);
60 // define current unix timestamp
61 define('TIME_NOW', time());
64 if (!defined('NO_IMPORTS')) {
65 require_once(WCF_DIR
.'lib/core.functions.php');
66 require_once(WCF_DIR
.'lib/system/api/autoload.php');
70 * WCF is the central class for the WoltLab Suite Core.
71 * It holds the database connection, access to template and language engine.
74 * @copyright 2001-2019 WoltLab GmbH
75 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
76 * @package WoltLabSuite\Core\System
80 * list of supported legacy API versions
84 private static $supportedLegacyApiVersions = [2017, 2018];
87 * list of currently loaded applications
90 protected static $applications = [];
93 * list of currently loaded application objects
96 protected static $applicationObjects = [];
99 * list of autoload directories
102 protected static $autoloadDirectories = [];
105 * list of unique instances of each core object
106 * @var SingletonFactory[]
108 protected static $coreObject = [];
111 * list of cached core objects
114 protected static $coreObjectCache = [];
120 protected static $dbObj;
124 * @var \wcf\data\language\Language
126 protected static $languageObj;
129 * overrides disabled debug mode
132 protected static $overrideDebugMode = false;
136 * @var SessionHandler
138 protected static $sessionObj;
142 * @var TemplateEngine
144 protected static $tplObj;
147 * true if Zend Opcache is loaded and enabled
150 protected static $zendOpcacheEnabled;
153 * force logout during destructor call
156 protected static $forceLogout = false;
159 * Calls all init functions of the WCF class.
161 public function __construct() {
162 // add autoload directory
163 self
::$autoloadDirectories['wcf'] = WCF_DIR
. 'lib/';
165 // define tmp directory
166 if (!defined('TMP_DIR')) define('TMP_DIR', FileUtil
::getTempFolder());
168 // start initialization
170 $this->loadOptions();
171 $this->initSession();
172 $this->initLanguage();
174 $this->initCronjobs();
175 $this->initCoreObjects();
176 $this->initApplications();
177 $this->initBlacklist();
179 EventHandler
::getInstance()->fireAction($this, 'initialized');
183 * Flushes the output, closes the session, performs background tasks and more.
185 * You *must* not create output in here under normal circumstances, as it might get eaten
186 * when gzip is enabled.
188 public static function destruct() {
190 // database has to be initialized
191 if (!is_object(self
::$dbObj)) return;
193 $debug = self
::debugModeIsEnabled(true);
196 if (ob_get_level()) ob_end_flush();
199 // close connection if using FPM
200 if (function_exists('fastcgi_finish_request')) fastcgi_finish_request();
204 if (is_object(self
::getSession())) {
205 if (self
::$forceLogout) {
207 self
::getSession()->delete();
210 self
::getSession()->update();
214 // execute shutdown actions of storage handlers
215 RegistryHandler
::getInstance()->shutdown();
216 UserStorageHandler
::getInstance()->shutdown();
218 catch (\Exception
$exception) {
219 die("<pre>WCF::destruct() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
224 * Returns the database object.
226 * @return \wcf\system\database\Database
228 public static final function getDB() {
233 * Returns the session object.
235 * @return SessionHandler
237 public static final function getSession() {
238 return self
::$sessionObj;
242 * Returns the user object.
244 * @return \wcf\data\user\User
246 public static final function getUser() {
247 return self
::getSession()->getUser();
251 * Returns the language object.
253 * @return \wcf\data\language\Language
255 public static final function getLanguage() {
256 return self
::$languageObj;
260 * Returns the template object.
262 * @return TemplateEngine
264 public static final function getTPL() {
265 return self
::$tplObj;
269 * Calls the show method on the given exception.
271 * @param \Exception $e
273 public static final function handleException($e) {
274 // backwards compatibility
275 if ($e instanceof IPrintableException
) {
280 if (ob_get_level()) {
281 // discard any output generated before the exception occurred, prevents exception
282 // being hidden inside HTML elements and therefore not visible in browser output
284 // ob_get_level() can return values > 1, if the PHP setting `output_buffering` is on
285 while (ob_get_level()) ob_end_clean();
288 @header
('HTTP/1.1 503 Service Unavailable');
290 \wcf\functions\exception\
printThrowable($e);
292 catch (\Throwable
$e2) {
293 echo "<pre>An Exception was thrown while handling an Exception:\n\n";
294 echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e2);
295 echo "\n\nwas thrown while:\n\n";
296 echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e);
297 echo "\n\nwas handled.</pre>";
303 * Turns PHP errors into an ErrorException.
305 * @param int $severity
306 * @param string $message
307 * @param string $file
309 * @throws ErrorException
311 public static final function handleError($severity, $message, $file, $line) {
312 // this is necessary for the shut-up operator
313 if (!(error_reporting() & $severity)) return;
315 throw new ErrorException($message, 0, $severity, $file, $line);
319 * Loads the database configuration and creates a new connection to the database.
321 protected function initDB() {
323 $dbHost = $dbUser = $dbPassword = $dbName = '';
325 $defaultDriverOptions = [];
326 require(WCF_DIR
.'config.inc.php');
328 // create database connection
329 self
::$dbObj = new MySQLDatabase($dbHost, $dbUser, $dbPassword, $dbName, $dbPort, false, false, $defaultDriverOptions);
333 * Loads the options file, automatically created if not exists.
335 protected function loadOptions() {
336 // The attachment module is always enabled since 5.2.
337 // https://github.com/WoltLab/WCF/issues/2531
338 define('MODULE_ATTACHMENT', 1);
340 // Users cannot react to their own content since 5.2.
341 // https://github.com/WoltLab/WCF/issues/2975
342 define('LIKE_ALLOW_FOR_OWN_CONTENT', 0);
343 define('LIKE_ENABLE_DISLIKE', 0);
345 // Thumbnails for attachments are already enabled since 5.3.
346 // https://github.com/WoltLab/WCF/pull/3444
347 define('ATTACHMENT_ENABLE_THUMBNAILS', 1);
349 // User markings are always applied in sidebars since 5.3.
350 // https://github.com/WoltLab/WCF/issues/3330
351 define('MESSAGE_SIDEBAR_ENABLE_USER_ONLINE_MARKING', 1);
353 // Password strength configuration is deprecated since 5.3.
354 define('REGISTER_ENABLE_PASSWORD_SECURITY_CHECK', 0);
355 define('REGISTER_PASSWORD_MIN_LENGTH', 0);
356 define('REGISTER_PASSWORD_MUST_CONTAIN_LOWER_CASE', 8);
357 define('REGISTER_PASSWORD_MUST_CONTAIN_UPPER_CASE', 0);
358 define('REGISTER_PASSWORD_MUST_CONTAIN_DIGIT', 0);
359 define('REGISTER_PASSWORD_MUST_CONTAIN_SPECIAL_CHAR', 0);
361 // rel=nofollow is always applied to external link since 5.3
362 // https://github.com/WoltLab/WCF/issues/3339
363 define('EXTERNAL_LINK_REL_NOFOLLOW', 1);
365 // Session validation is removed since 5.4.
366 // https://github.com/WoltLab/WCF/pull/3583
367 define('SESSION_VALIDATE_IP_ADDRESS', 0);
368 define('SESSION_VALIDATE_USER_AGENT', 0);
370 // Virtual sessions no longer exist since 5.4.
371 define('SESSION_ENABLE_VIRTUALIZATION', 1);
373 // The session timeout is fully managed since 5.4.
374 define('SESSION_TIMEOUT', 3600);
376 // gzip compression is removed in 5.4.
377 // https://github.com/WoltLab/WCF/issues/3634
378 define('HTTP_ENABLE_GZIP', 0);
380 // Meta keywords are no longer used since 5.4.
381 // https://github.com/WoltLab/WCF/issues/3561
382 define('META_KEYWORDS', '');
384 // The admin notification is redundant and removed in 5.4.
385 // https://github.com/WoltLab/WCF/issues/3674
386 define('REGISTER_ADMIN_NOTIFICATION', 0);
388 $filename = WCF_DIR
.'options.inc.php';
390 // create options file if doesn't exist
391 if (!file_exists($filename) ||
filemtime($filename) <= 1) {
392 OptionEditor
::rebuild();
396 // check if option file is complete and writable
398 if (!is_writable($filename)) {
399 FileUtil
::makeWritable($filename);
401 if (!is_writable($filename)) {
402 throw new SystemException("The option file '" . $filename . "' is not writable.");
406 // check if a previous write operation was incomplete and force rebuilding
407 if (!defined('WCF_OPTION_INC_PHP_SUCCESS')) {
408 OptionEditor
::rebuild();
413 if (ENABLE_DEBUG_MODE
) {
414 self
::$dbObj->enableDebugMode();
420 * Starts the session system.
422 protected function initSession() {
423 $factory = new SessionFactory();
426 self
::$sessionObj = SessionHandler
::getInstance();
430 * Initialises the language engine.
432 protected function initLanguage() {
433 if (isset($_GET['l']) && !self
::getUser()->userID
) {
434 self
::getSession()->setLanguageID(intval($_GET['l']));
438 mb_internal_encoding('UTF-8');
439 if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
443 self
::$languageObj = LanguageFactory
::getInstance()->getUserLanguage(self
::getSession()->getLanguageID());
447 * Initialises the template engine.
449 protected function initTPL() {
450 self
::$tplObj = TemplateEngine
::getInstance();
451 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
452 $this->assignDefaultTemplateVariables();
458 * Initializes the user's style.
460 protected function initStyle() {
461 if (isset($_REQUEST['styleID'])) {
462 self
::getSession()->setStyleID(intval($_REQUEST['styleID']));
465 $styleHandler = StyleHandler
::getInstance();
466 $styleHandler->changeStyle(self
::getSession()->getStyleID());
470 * Executes the blacklist.
472 protected function initBlacklist() {
473 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
475 if (defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES
!= '') {
476 if (!StringUtil
::executeWordFilter(UserUtil
::convertIPv6To4(UserUtil
::getIpAddress()), BLACKLIST_IP_ADDRESSES
)) {
478 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
481 throw new PermissionDeniedException();
484 else if (!StringUtil
::executeWordFilter(UserUtil
::getIpAddress(), BLACKLIST_IP_ADDRESSES
)) {
486 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
489 throw new PermissionDeniedException();
493 if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS
!= '') {
494 if (!StringUtil
::executeWordFilter(UserUtil
::getUserAgent(), BLACKLIST_USER_AGENTS
)) {
496 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
499 throw new PermissionDeniedException();
503 if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES
!= '') {
504 if (!StringUtil
::executeWordFilter(@gethostbyaddr
(UserUtil
::getIpAddress()), BLACKLIST_HOSTNAMES
)) {
506 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
509 throw new PermissionDeniedException();
514 // handle banned users
515 if (self
::getUser()->userID
&& self
::getUser()->banned
&& !self
::getUser()->hasOwnerAccess()) {
517 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
520 self
::$forceLogout = true;
523 if (isset($_COOKIE[COOKIE_PREFIX
.'userID'])) {
524 HeaderUtil
::setCookie('userID', 0);
526 if (isset($_COOKIE[COOKIE_PREFIX
.'password'])) {
527 HeaderUtil
::setCookie('password', '');
530 throw new NamedUserException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
536 * Initializes applications.
538 protected function initApplications() {
539 // step 1) load all applications
540 $loadedApplications = [];
542 // register WCF as application
543 self
::$applications['wcf'] = ApplicationHandler
::getInstance()->getApplicationByID(1);
545 if (!class_exists(WCFACP
::class, false)) {
546 static::getTPL()->assign('baseHref', self
::$applications['wcf']->getPageURL());
549 // start main application
550 $application = ApplicationHandler
::getInstance()->getActiveApplication();
551 if ($application->packageID
!= 1) {
552 $loadedApplications[] = $this->loadApplication($application);
554 // register primary application
555 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
556 self
::$applications[$abbreviation] = $application;
559 // start dependent applications
560 $applications = ApplicationHandler
::getInstance()->getDependentApplications();
561 foreach ($applications as $application) {
562 if ($application->packageID
== 1) {
566 else if ($application->isTainted
) {
567 // ignore apps flagged for uninstallation
571 $loadedApplications[] = $this->loadApplication($application, true);
574 // step 2) run each application
575 if (!class_exists('wcf\system\WCFACP', false)) {
576 /** @var IApplication $application */
577 foreach ($loadedApplications as $application) {
578 $application->__run();
581 /** @deprecated The below variable is deprecated. */
582 self
::getTPL()->assign('__sessionKeepAlive', 59 * 60);
587 * Loads an application.
589 * @param Application $application
590 * @param bool $isDependentApplication
591 * @return IApplication
592 * @throws SystemException
594 protected function loadApplication(Application
$application, $isDependentApplication = false) {
595 $package = PackageCache
::getInstance()->getPackage($application->packageID
);
596 // package cache might be outdated
597 if ($package === null) {
598 $package = new Package($application->packageID
);
600 // package cache is outdated, discard cache
601 if ($package->packageID
) {
602 PackageEditor
::resetCache();
605 // package id is invalid
606 throw new SystemException("application identified by package id '".$application->packageID
."' is unknown");
610 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
611 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
612 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
614 $className = $abbreviation.'\system\\'.strtoupper($abbreviation).'Core';
616 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
617 if (!class_exists($className)) {
618 // check if both the Core and the app are on the same domain
619 $coreApp = ApplicationHandler
::getInstance()->getApplicationByID(1);
620 if ($coreApp->domainName
=== $application->domainName
) {
621 // resolve the relative path and use it to construct the autoload directory
622 $relativePath = FileUtil
::getRelativePath($coreApp->domainPath
, $application->domainPath
);
623 if ($relativePath !== './') {
624 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$relativePath);
625 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
627 if (class_exists($className)) {
628 // the class can now be found, update the `packageDir` value
629 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
635 if (class_exists($className) && is_subclass_of($className, IApplication
::class)) {
636 // include config file
637 $configPath = $packageDir . PackageInstallationDispatcher
::CONFIG_FILE
;
638 if (!file_exists($configPath)) {
639 Package
::writeConfigFile($package->packageID
);
642 if (file_exists($configPath)) {
643 require_once($configPath);
646 throw new SystemException('Unable to load configuration for '.$package->package
);
649 // register template path if not within ACP
650 if (!class_exists('wcf\system\WCFACP', false)) {
651 // add template path and abbreviation
652 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
654 EmailTemplateEngine
::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
656 // init application and assign it as template variable
657 self
::$applicationObjects[$application->packageID
] = call_user_func([$className, 'getInstance']);
658 static::getTPL()->assign('__'.$abbreviation, self
::$applicationObjects[$application->packageID
]);
659 EmailTemplateEngine
::getInstance()->assign('__'.$abbreviation, self
::$applicationObjects[$application->packageID
]);
662 unset(self
::$autoloadDirectories[$abbreviation]);
663 throw new SystemException("Unable to run '".$package->package
."', '".$className."' is missing or does not implement '".IApplication
::class."'.");
666 // register template path in ACP
667 if (class_exists('wcf\system\WCFACP', false)) {
668 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
670 else if (!$isDependentApplication) {
672 static::getTPL()->assign('baseHref', $application->getPageURL());
675 // register application
676 self
::$applications[$abbreviation] = $application;
678 return self
::$applicationObjects[$application->packageID
];
682 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
684 * @param Application $application
685 * @return IApplication
687 public static function getApplicationObject(Application
$application) {
688 if (isset(self
::$applicationObjects[$application->packageID
])) {
689 return self
::$applicationObjects[$application->packageID
];
696 * Returns the invoked application.
698 * @return Application
701 public static function getActiveApplication() {
702 return ApplicationHandler
::getInstance()->getActiveApplication();
706 * Loads an application on runtime, do not use this outside the package installation.
708 * @param int $packageID
710 public static function loadRuntimeApplication($packageID) {
711 $package = new Package($packageID);
712 $application = new Application($packageID);
714 $abbreviation = Package
::getAbbreviation($package->package
);
715 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
716 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
717 self
::$applications[$abbreviation] = $application;
718 self
::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
722 * Initializes core object cache.
724 protected function initCoreObjects() {
725 // ignore core objects if installing WCF
726 if (PACKAGE_ID
== 0) {
730 self
::$coreObjectCache = CoreObjectCacheBuilder
::getInstance()->getData();
734 * Assigns some default variables to the template engine.
736 protected function assignDefaultTemplateVariables() {
739 if (ENABLE_ENTERPRISE_MODE
) {
740 $wcf = new TemplateScriptingCore($wcf);
743 self
::getTPL()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang', 'csrfToken']);
744 self
::getTPL()->assign([
746 '__wcfVersion' => LAST_UPDATE_TIME
// @deprecated 2.1, use LAST_UPDATE_TIME directly
749 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
750 // Execute background queue in this request, if it was requested and AJAX isn't used.
752 if (self
::getSession()->getVar('forceBackgroundQueuePerform')) {
753 self
::getTPL()->assign([
754 'forceBackgroundQueuePerform' => true
757 self
::getSession()->unregister('forceBackgroundQueuePerform');
761 EmailTemplateEngine
::getInstance()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang']);
762 EmailTemplateEngine
::getInstance()->assign([
768 * Wrapper for the getter methods of this class.
770 * @param string $name
771 * @return mixed value
772 * @throws SystemException
774 public function __get($name) {
775 $method = 'get'.ucfirst($name);
776 if (method_exists($this, $method)) {
777 return $this->$method();
780 throw new SystemException("method '".$method."' does not exist in class WCF");
784 * Returns true if current application (WCF) is treated as active and was invoked directly.
788 public function isActiveApplication() {
789 return (ApplicationHandler
::getInstance()->getActiveApplication()->packageID
== 1);
793 * Changes the active language.
795 * @param int $languageID
797 public static final function setLanguage($languageID) {
798 if (!$languageID || LanguageFactory
::getInstance()->getLanguage($languageID) === null) {
799 $languageID = LanguageFactory
::getInstance()->getDefaultLanguageID();
802 self
::$languageObj = LanguageFactory
::getInstance()->getLanguage($languageID);
804 // the template engine may not be available yet, usually happens when
805 // changing the user (and thus the language id) during session init
806 if (self
::$tplObj !== null) {
807 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
808 EmailTemplateEngine
::getInstance()->setLanguageID(self
::getLanguage()->languageID
);
813 * Includes the required util or exception classes automatically.
815 * @param string $className
816 * @see spl_autoload_register()
818 public static final function autoload($className) {
819 $namespaces = explode('\\', $className);
820 if (count($namespaces) > 1) {
821 $applicationPrefix = array_shift($namespaces);
822 if ($applicationPrefix === '') {
823 $applicationPrefix = array_shift($namespaces);
825 if (isset(self
::$autoloadDirectories[$applicationPrefix])) {
826 $classPath = self
::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
828 // PHP will implicitly check if the file exists when including it, which means that we can save a
829 // redundant syscall/fs access by not checking for existence ourselves. Do not use require_once()!
830 @include_once
($classPath);
838 public final function __call($name, array $arguments) {
839 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
840 if (!method_exists($this, $name)) {
841 return self
::__callStatic($name, $arguments);
844 throw new \
BadMethodCallException("Call to undefined method WCF::{$name}().");
848 * Returns dynamically loaded core objects.
850 * @param string $name
851 * @param array $arguments
853 * @throws SystemException
855 public static final function __callStatic($name, array $arguments) {
856 $className = preg_replace('~^get~', '', $name);
858 if (isset(self
::$coreObject[$className])) {
859 return self
::$coreObject[$className];
862 $objectName = self
::getCoreObject($className);
863 if ($objectName === null) {
864 throw new SystemException("Core object '".$className."' is unknown.");
867 if (class_exists($objectName)) {
868 if (!is_subclass_of($objectName, SingletonFactory
::class)) {
869 throw new ParentClassException($objectName, SingletonFactory
::class);
872 self
::$coreObject[$className] = call_user_func([$objectName, 'getInstance']);
873 return self
::$coreObject[$className];
878 * Searches for cached core object definition.
880 * @param string $className
883 protected static final function getCoreObject($className) {
884 if (isset(self
::$coreObjectCache[$className])) {
885 return self
::$coreObjectCache[$className];
892 * Returns true if the debug mode is enabled, otherwise false.
894 * @param bool $ignoreACP
897 public static function debugModeIsEnabled($ignoreACP = false) {
899 if (!$ignoreACP && self
::$overrideDebugMode) {
902 else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE
) {
910 * Returns true if benchmarking is enabled, otherwise false.
914 public static function benchmarkIsEnabled() {
915 // benchmarking is enabled by default
916 if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK
) return true;
921 * Returns domain path for given application.
923 * @param string $abbreviation
926 public static function getPath($abbreviation = 'wcf') {
927 // workaround during WCFSetup
932 if (!isset(self
::$applications[$abbreviation])) {
933 $abbreviation = 'wcf';
936 return self
::$applications[$abbreviation]->getPageURL();
940 * Returns the domain path for the currently active application,
941 * used to avoid CORS requests.
945 public static function getActivePath() {
947 return self
::getPath();
950 // We cannot rely on the ApplicationHandler's `getActiveApplication()` because
951 // it uses the requested controller to determine the namespace. However, starting
952 // with WoltLab Suite 5.2, system pages can be virtually assigned to a different
953 // app, resolving against the target app without changing the namespace.
954 return self
::getPath(ApplicationHandler
::getInstance()->getAbbreviation(PACKAGE_ID
));
958 * Returns a fully qualified anchor for current page.
960 * @param string $fragment
963 public function getAnchor($fragment) {
964 return StringUtil
::encodeHTML(self
::getRequestURI() . '#' . $fragment);
968 * Returns the currently active page or null if unknown.
972 public static function getActivePage() {
973 if (self
::getActiveRequest() === null) {
977 if (self
::getActiveRequest()->getClassName() === CmsPage
::class) {
978 $metaData = self
::getActiveRequest()->getMetaData();
979 if (isset($metaData['cms'])) {
980 return PageCache
::getInstance()->getPage($metaData['cms']['pageID']);
986 return PageCache
::getInstance()->getPageByController(self
::getActiveRequest()->getClassName());
990 * Returns the currently active request.
994 public static function getActiveRequest() {
995 return RequestHandler
::getInstance()->getActiveRequest();
999 * Returns the URI of the current page.
1003 public static function getRequestURI() {
1004 return preg_replace('~^(https?://[^/]+)(?:/.*)?$~', '$1', self
::getTPL()->get('baseHref')) . $_SERVER['REQUEST_URI'];
1008 * Resets Zend Opcache cache if installed and enabled.
1010 * @param string $script
1012 public static function resetZendOpcache($script = '') {
1013 if (self
::$zendOpcacheEnabled === null) {
1014 self
::$zendOpcacheEnabled = false;
1016 if (extension_loaded('Zend Opcache') && @ini_get
('opcache.enable')) {
1017 self
::$zendOpcacheEnabled = true;
1022 if (self
::$zendOpcacheEnabled) {
1023 if (empty($script)) {
1027 \
opcache_invalidate($script, true);
1033 * Returns style handler.
1035 * @return StyleHandler
1037 public function getStyleHandler() {
1038 return StyleHandler
::getInstance();
1042 * Returns box handler.
1044 * @return BoxHandler
1047 public function getBoxHandler() {
1048 return BoxHandler
::getInstance();
1052 * Returns number of available updates.
1056 public function getAvailableUpdates() {
1057 $data = PackageUpdateCacheBuilder
::getInstance()->getData();
1058 return $data['updates'];
1062 * Returns a 8 character prefix for editor autosave.
1066 public function getAutosavePrefix() {
1067 return substr(sha1(preg_replace('~^https~', 'http', self
::getPath())), 0, 8);
1071 * Returns the favicon URL or a base64 encoded image.
1075 public function getFavicon() {
1076 $activeApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1077 $wcf = ApplicationHandler
::getInstance()->getWCF();
1078 $favicon = StyleHandler
::getInstance()->getStyle()->getRelativeFavicon();
1080 if ($activeApplication->domainName
!== $wcf->domainName
) {
1081 if (file_exists(WCF_DIR
.$favicon)) {
1082 $favicon = file_get_contents(WCF_DIR
.$favicon);
1084 return 'data:image/x-icon;base64,' . base64_encode($favicon);
1088 return self
::getPath() . $favicon;
1092 * Returns true if the desktop notifications should be enabled.
1096 public function useDesktopNotifications() {
1097 if (!ENABLE_DESKTOP_NOTIFICATIONS
) {
1100 else if (ApplicationHandler
::getInstance()->isMultiDomainSetup()) {
1101 $application = ApplicationHandler
::getInstance()->getApplicationByID(DESKTOP_NOTIFICATION_PACKAGE_ID
);
1102 // mismatch, default to Core
1103 if ($application === null) $application = ApplicationHandler
::getInstance()->getApplicationByID(1);
1105 $currentApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1106 if ($currentApplication->domainName
!= $application->domainName
) {
1116 * Returns true if currently active request represents the landing page.
1120 public static function isLandingPage() {
1121 if (self
::getActiveRequest() === null) {
1125 return self
::getActiveRequest()->isLandingPage();
1129 * Returns true if the given API version is currently supported.
1131 * @param int $apiVersion
1135 public static function isSupportedApiVersion($apiVersion) {
1136 return ($apiVersion == WSC_API_VERSION
) ||
in_array($apiVersion, self
::$supportedLegacyApiVersions);
1140 * Returns the list of supported legacy API versions.
1145 public static function getSupportedLegacyApiVersions() {
1146 return self
::$supportedLegacyApiVersions;
1150 * Initialises the cronjobs.
1152 protected function initCronjobs() {
1154 self
::getTPL()->assign('executeCronjobs', CronjobScheduler
::getInstance()->getNextExec() < TIME_NOW
&& defined('OFFLINE') && !OFFLINE
);
1159 * Checks recursively that the most important system files of `com.woltlab.wcf` are writable.
1161 * @throws \RuntimeException if any relevant file or directory is not writable
1163 public static function checkWritability() {
1164 $nonWritablePaths = [];
1166 $nonRecursiveDirectories = [
1171 foreach ($nonRecursiveDirectories as $directory) {
1172 $path = WCF_DIR
. $directory;
1173 if ($path === 'tmp/' && !is_dir($path)) {
1177 if (!is_writable($path)) {
1178 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1182 DirectoryUtil
::getInstance($path, false)->executeCallback(function($file, \SplFileInfo
$fileInfo) use ($path, &$nonWritablePaths) {
1183 if ($fileInfo instanceof \DirectoryIterator
) {
1184 if (!is_writable($fileInfo->getPath())) {
1185 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $fileInfo->getPath());
1188 else if (!is_writable($fileInfo->getRealPath())) {
1189 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $fileInfo->getPath()) . $fileInfo->getFilename();
1194 $recursiveDirectories = [
1205 foreach ($recursiveDirectories as $directory) {
1206 $path = WCF_DIR
. $directory;
1208 if (!is_writable($path)) {
1209 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1213 DirectoryUtil
::getInstance($path)->executeCallback(function($file, \SplFileInfo
$fileInfo) use ($path, &$nonWritablePaths) {
1214 if ($fileInfo instanceof \DirectoryIterator
) {
1215 if (!is_writable($fileInfo->getPath())) {
1216 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $fileInfo->getPath());
1219 else if (!is_writable($fileInfo->getRealPath())) {
1220 $nonWritablePaths[] = FileUtil
::getRelativePath($_SERVER['DOCUMENT_ROOT'], $fileInfo->getPath()) . $fileInfo->getFilename();
1225 if (!empty($nonWritablePaths)) {
1227 throw new \
RuntimeException('The following paths are not writable: ' . implode(',', array_slice($nonWritablePaths, 0, $maxPaths)) . (count($nonWritablePaths) > $maxPaths ?
',' . StringUtil
::HELLIP
: ''));