2 declare(strict_types
=1);
4 use wcf\data\application\Application
;
5 use wcf\data\option\OptionEditor
;
6 use wcf\data\package\Package
;
7 use wcf\data\package\PackageCache
;
8 use wcf\data\package\PackageEditor
;
9 use wcf\data\page\Page
;
10 use wcf\data\page\PageCache
;
12 use wcf\system\application\ApplicationHandler
;
13 use wcf\system\application\IApplication
;
14 use wcf\system\box\BoxHandler
;
15 use wcf\system\cache\builder\CoreObjectCacheBuilder
;
16 use wcf\system\cache\builder\PackageUpdateCacheBuilder
;
17 use wcf\system\cronjob\CronjobScheduler
;
18 use wcf\system\database\MySQLDatabase
;
19 use wcf\system\event\EventHandler
;
20 use wcf\system\exception\AJAXException
;
21 use wcf\system\exception\ErrorException
;
22 use wcf\system\exception\IPrintableException
;
23 use wcf\system\exception\NamedUserException
;
24 use wcf\system\exception\ParentClassException
;
25 use wcf\system\exception\PermissionDeniedException
;
26 use wcf\system\exception\SystemException
;
27 use wcf\system\language\LanguageFactory
;
28 use wcf\system\package\PackageInstallationDispatcher
;
29 use wcf\system\registry\RegistryHandler
;
30 use wcf\system\request\Request
;
31 use wcf\system\request\RequestHandler
;
32 use wcf\system\session\SessionFactory
;
33 use wcf\system\session\SessionHandler
;
34 use wcf\system\style\StyleHandler
;
35 use wcf\system\template\EmailTemplateEngine
;
36 use wcf\system\template\TemplateEngine
;
37 use wcf\system\user\storage\UserStorageHandler
;
38 use wcf\util\FileUtil
;
39 use wcf\util\HeaderUtil
;
40 use wcf\util\StringUtil
;
41 use wcf\util\UserUtil
;
43 // try to set a time-limit to infinite
46 // fix timezone warning issue
47 if (!@ini_get
('date.timezone')) {
48 @date_default_timezone_set
('Europe/London');
51 // define current woltlab suite version
52 define('WCF_VERSION', '3.1.4');
54 // define current API version
55 define('WSC_API_VERSION', 2018);
57 // define current unix timestamp
58 define('TIME_NOW', time());
61 if (!defined('NO_IMPORTS')) {
62 require_once(WCF_DIR
.'lib/core.functions.php');
63 require_once(WCF_DIR
.'lib/system/api/autoload.php');
67 * WCF is the central class for the WoltLab Suite Core.
68 * It holds the database connection, access to template and language engine.
71 * @copyright 2001-2018 WoltLab GmbH
72 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
73 * @package WoltLabSuite\Core\System
77 * list of supported legacy API versions
80 private static $supportedLegacyApiVersions = [2017];
83 * list of currently loaded applications
86 protected static $applications = [];
89 * list of currently loaded application objects
92 protected static $applicationObjects = [];
95 * list of autoload directories
98 protected static $autoloadDirectories = [];
101 * list of unique instances of each core object
102 * @var SingletonFactory[]
104 protected static $coreObject = [];
107 * list of cached core objects
110 protected static $coreObjectCache = [];
116 protected static $dbObj;
120 * @var \wcf\data\language\Language
122 protected static $languageObj;
125 * overrides disabled debug mode
128 protected static $overrideDebugMode = false;
132 * @var SessionHandler
134 protected static $sessionObj;
138 * @var TemplateEngine
140 protected static $tplObj;
143 * true if Zend Opcache is loaded and enabled
146 protected static $zendOpcacheEnabled;
149 * force logout during destructor call
152 protected static $forceLogout = false;
155 * Calls all init functions of the WCF class.
157 public function __construct() {
158 // add autoload directory
159 self
::$autoloadDirectories['wcf'] = WCF_DIR
. 'lib/';
161 // define tmp directory
162 if (!defined('TMP_DIR')) define('TMP_DIR', FileUtil
::getTempFolder());
164 // start initialization
166 $this->loadOptions();
167 $this->initSession();
168 $this->initLanguage();
170 $this->initCronjobs();
171 $this->initCoreObjects();
172 $this->initApplications();
173 $this->initBlacklist();
175 EventHandler
::getInstance()->fireAction($this, 'initialized');
179 * Flushes the output, closes the session, performs background tasks and more.
181 * You *must* not create output in here under normal circumstances, as it might get eaten
182 * when gzip is enabled.
184 public static function destruct() {
186 // database has to be initialized
187 if (!is_object(self
::$dbObj)) return;
189 $debug = self
::debugModeIsEnabled(true);
192 if (ob_get_level()) ob_end_flush();
195 // close connection if using FPM
196 if (function_exists('fastcgi_finish_request')) fastcgi_finish_request();
200 if (is_object(self
::getSession())) {
201 if (self
::$forceLogout) {
203 self
::getSession()->delete();
206 self
::getSession()->update();
210 // execute shutdown actions of storage handlers
211 RegistryHandler
::getInstance()->shutdown();
212 UserStorageHandler
::getInstance()->shutdown();
214 catch (\Exception
$exception) {
215 die("<pre>WCF::destruct() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
220 * Returns the database object.
222 * @return \wcf\system\database\Database
224 public static final function getDB() {
229 * Returns the session object.
231 * @return SessionHandler
233 public static final function getSession() {
234 return self
::$sessionObj;
238 * Returns the user object.
240 * @return \wcf\data\user\User
242 public static final function getUser() {
243 return self
::getSession()->getUser();
247 * Returns the language object.
249 * @return \wcf\data\language\Language
251 public static final function getLanguage() {
252 return self
::$languageObj;
256 * Returns the template object.
258 * @return TemplateEngine
260 public static final function getTPL() {
261 return self
::$tplObj;
265 * Calls the show method on the given exception.
267 * @param \Exception $e
269 public static final function handleException($e) {
270 // backwards compatibility
271 if ($e instanceof IPrintableException
) {
276 if (ob_get_level()) {
277 // discard any output generated before the exception occurred, prevents exception
278 // being hidden inside HTML elements and therefore not visible in browser output
280 // ob_get_level() can return values > 1, if the PHP setting `output_buffering` is on
281 while (ob_get_level()) ob_end_clean();
283 // Some webservers are broken and will apply gzip encoding at all cost, but they fail
284 // to set a proper `Content-Encoding` HTTP header and mess things up even more.
285 // Especially the `identity` value appears to be unrecognized by some of them, hence
286 // we'll just gzip the output of the exception to prevent them from tampering.
287 // This part is copied from `HeaderUtil` in order to isolate the exception handler!
288 if (defined('HTTP_ENABLE_GZIP') && HTTP_ENABLE_GZIP
&& !defined('HTTP_DISABLE_GZIP')) {
289 if (function_exists('gzcompress') && !@ini_get
('zlib.output_compression') && !@ini_get
('output_handler') && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
290 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false) {
291 @header
('Content-Encoding: x-gzip');
294 @header
('Content-Encoding: gzip');
297 ob_start(function($output) {
298 $size = strlen($output);
299 $crc = crc32($output);
301 $newOutput = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff";
302 $newOutput .= substr(gzcompress($output, 1), 2, -4);
303 $newOutput .= pack('V', $crc);
304 $newOutput .= pack('V', $size);
312 @header
('HTTP/1.1 503 Service Unavailable');
314 \wcf\functions\exception\
printThrowable($e);
316 catch (\Throwable
$e2) {
317 echo "<pre>An Exception was thrown while handling an Exception:\n\n";
318 echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e2);
319 echo "\n\nwas thrown while:\n\n";
320 echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e);
321 echo "\n\nwas handled.</pre>";
327 * Turns PHP errors into an ErrorException.
329 * @param integer $severity
330 * @param string $message
331 * @param string $file
332 * @param integer $line
333 * @throws ErrorException
335 public static final function handleError($severity, $message, $file, $line) {
336 // this is necessary for the shut-up operator
337 if (error_reporting() == 0) return;
339 throw new ErrorException($message, 0, $severity, $file, $line);
343 * Loads the database configuration and creates a new connection to the database.
345 protected function initDB() {
347 $dbHost = $dbUser = $dbPassword = $dbName = '';
349 require(WCF_DIR
.'config.inc.php');
351 // create database connection
352 self
::$dbObj = new MySQLDatabase($dbHost, $dbUser, $dbPassword, $dbName, $dbPort);
356 * Loads the options file, automatically created if not exists.
358 protected function loadOptions() {
359 // the attachment module is always enabled since 3.2
360 // https://github.com/WoltLab/WCF/issues/2531
361 define('MODULE_ATTACHMENT', 1);
363 $filename = WCF_DIR
.'options.inc.php';
365 // create options file if doesn't exist
366 if (!file_exists($filename) ||
filemtime($filename) <= 1) {
367 OptionEditor
::rebuild();
371 // check if option file is complete and writable
373 if (!is_writable($filename)) {
374 FileUtil
::makeWritable($filename);
376 if (!is_writable($filename)) {
377 throw new SystemException("The option file '" . $filename . "' is not writable.");
381 // check if a previous write operation was incomplete and force rebuilding
382 if (!defined('WCF_OPTION_INC_PHP_SUCCESS')) {
383 OptionEditor
::rebuild();
391 * Starts the session system.
393 protected function initSession() {
394 $factory = new SessionFactory();
397 self
::$sessionObj = SessionHandler
::getInstance();
398 self
::$sessionObj->setHasValidCookie($factory->hasValidCookie());
402 * Initialises the language engine.
404 protected function initLanguage() {
405 if (isset($_GET['l']) && !self
::getUser()->userID
) {
406 self
::getSession()->setLanguageID(intval($_GET['l']));
410 mb_internal_encoding('UTF-8');
411 if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
415 self
::$languageObj = LanguageFactory
::getInstance()->getUserLanguage(self
::getSession()->getLanguageID());
419 * Initialises the template engine.
421 protected function initTPL() {
422 self
::$tplObj = TemplateEngine
::getInstance();
423 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
424 $this->assignDefaultTemplateVariables();
430 * Initializes the user's style.
432 protected function initStyle() {
433 if (isset($_REQUEST['styleID'])) {
434 self
::getSession()->setStyleID(intval($_REQUEST['styleID']));
437 $styleHandler = StyleHandler
::getInstance();
438 $styleHandler->changeStyle(self
::getSession()->getStyleID());
442 * Executes the blacklist.
444 protected function initBlacklist() {
445 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
447 if (defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES
!= '') {
448 if (!StringUtil
::executeWordFilter(UserUtil
::convertIPv6To4(self
::getSession()->ipAddress
), BLACKLIST_IP_ADDRESSES
)) {
450 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
453 throw new PermissionDeniedException();
456 else if (!StringUtil
::executeWordFilter(self
::getSession()->ipAddress
, BLACKLIST_IP_ADDRESSES
)) {
458 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
461 throw new PermissionDeniedException();
465 if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS
!= '') {
466 if (!StringUtil
::executeWordFilter(self
::getSession()->userAgent
, BLACKLIST_USER_AGENTS
)) {
468 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
471 throw new PermissionDeniedException();
475 if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES
!= '') {
476 if (!StringUtil
::executeWordFilter(@gethostbyaddr
(self
::getSession()->ipAddress
), BLACKLIST_HOSTNAMES
)) {
478 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
481 throw new PermissionDeniedException();
486 // handle banned users
487 if (self
::getUser()->userID
&& self
::getUser()->banned
) {
489 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
492 self
::$forceLogout = true;
495 if (isset($_COOKIE[COOKIE_PREFIX
.'userID'])) {
496 HeaderUtil
::setCookie('userID', 0);
498 if (isset($_COOKIE[COOKIE_PREFIX
.'password'])) {
499 HeaderUtil
::setCookie('password', '');
502 throw new NamedUserException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
508 * Initializes applications.
510 protected function initApplications() {
511 // step 1) load all applications
512 $loadedApplications = [];
514 // register WCF as application
515 self
::$applications['wcf'] = ApplicationHandler
::getInstance()->getApplicationByID(1);
517 if (!class_exists(WCFACP
::class, false)) {
518 static::getTPL()->assign('baseHref', self
::$applications['wcf']->getPageURL());
521 // start main application
522 $application = ApplicationHandler
::getInstance()->getActiveApplication();
523 if ($application->packageID
!= 1) {
524 $loadedApplications[] = $this->loadApplication($application);
526 // register primary application
527 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
528 self
::$applications[$abbreviation] = $application;
531 // start dependent applications
532 $applications = ApplicationHandler
::getInstance()->getDependentApplications();
533 foreach ($applications as $application) {
534 if ($application->packageID
== 1) {
538 else if ($application->isTainted
) {
539 // ignore apps flagged for uninstallation
543 $loadedApplications[] = $this->loadApplication($application, true);
546 // step 2) run each application
547 if (!class_exists('wcf\system\WCFACP', false)) {
548 /** @var IApplication $application */
549 foreach ($loadedApplications as $application) {
550 $application->__run();
553 // refresh the session 1 minute before it expires
554 self
::getTPL()->assign('__sessionKeepAlive', SESSION_TIMEOUT
- 60);
559 * Loads an application.
561 * @param Application $application
562 * @param boolean $isDependentApplication
563 * @return IApplication
564 * @throws SystemException
566 protected function loadApplication(Application
$application, $isDependentApplication = false) {
567 $package = PackageCache
::getInstance()->getPackage($application->packageID
);
568 // package cache might be outdated
569 if ($package === null) {
570 $package = new Package($application->packageID
);
572 // package cache is outdated, discard cache
573 if ($package->packageID
) {
574 PackageEditor
::resetCache();
577 // package id is invalid
578 throw new SystemException("application identified by package id '".$application->packageID
."' is unknown");
582 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
583 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
584 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
586 $className = $abbreviation.'\system\\'.strtoupper($abbreviation).'Core';
588 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
589 if (!class_exists($className)) {
590 // check if both the Core and the app are on the same domain
591 $coreApp = ApplicationHandler
::getInstance()->getApplicationByID(1);
592 if ($coreApp->domainName
=== $application->domainName
) {
593 // resolve the relative path and use it to construct the autoload directory
594 $relativePath = FileUtil
::getRelativePath($coreApp->domainPath
, $application->domainPath
);
595 if ($relativePath !== './') {
596 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$relativePath);
597 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
599 if (class_exists($className)) {
600 // the class can now be found, update the `packageDir` value
601 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
607 if (class_exists($className) && is_subclass_of($className, IApplication
::class)) {
608 // include config file
609 $configPath = $packageDir . PackageInstallationDispatcher
::CONFIG_FILE
;
610 if (!file_exists($configPath)) {
611 Package
::writeConfigFile($package->packageID
);
614 if (file_exists($configPath)) {
615 require_once($configPath);
618 throw new SystemException('Unable to load configuration for '.$package->package
);
621 // register template path if not within ACP
622 if (!class_exists('wcf\system\WCFACP', false)) {
623 // add template path and abbreviation
624 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
626 EmailTemplateEngine
::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
628 // init application and assign it as template variable
629 self
::$applicationObjects[$application->packageID
] = call_user_func([$className, 'getInstance']);
630 static::getTPL()->assign('__'.$abbreviation, self
::$applicationObjects[$application->packageID
]);
631 EmailTemplateEngine
::getInstance()->assign('__'.$abbreviation, self
::$applicationObjects[$application->packageID
]);
634 unset(self
::$autoloadDirectories[$abbreviation]);
635 throw new SystemException("Unable to run '".$package->package
."', '".$className."' is missing or does not implement '".IApplication
::class."'.");
638 // register template path in ACP
639 if (class_exists('wcf\system\WCFACP', false)) {
640 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
642 else if (!$isDependentApplication) {
644 static::getTPL()->assign('baseHref', $application->getPageURL());
647 // register application
648 self
::$applications[$abbreviation] = $application;
650 return self
::$applicationObjects[$application->packageID
];
654 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
656 * @param Application $application
657 * @return IApplication
659 public static function getApplicationObject(Application
$application) {
660 if (isset(self
::$applicationObjects[$application->packageID
])) {
661 return self
::$applicationObjects[$application->packageID
];
668 * Returns the invoked application.
670 * @return Application
673 public static function getActiveApplication() {
674 return ApplicationHandler
::getInstance()->getActiveApplication();
678 * Loads an application on runtime, do not use this outside the package installation.
680 * @param integer $packageID
682 public static function loadRuntimeApplication($packageID) {
683 $package = new Package($packageID);
684 $application = new Application($packageID);
686 $abbreviation = Package
::getAbbreviation($package->package
);
687 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
688 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
689 self
::$applications[$abbreviation] = $application;
690 self
::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
694 * Initializes core object cache.
696 protected function initCoreObjects() {
697 // ignore core objects if installing WCF
698 if (PACKAGE_ID
== 0) {
702 self
::$coreObjectCache = CoreObjectCacheBuilder
::getInstance()->getData();
706 * Assigns some default variables to the template engine.
708 protected function assignDefaultTemplateVariables() {
709 self
::getTPL()->registerPrefilter(['event', 'hascontent', 'lang']);
710 self
::getTPL()->assign([
712 '__wcfVersion' => LAST_UPDATE_TIME
// @deprecated 2.1, use LAST_UPDATE_TIME directly
715 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
716 // Execute background queue in this request, if it was requested and AJAX isn't used.
718 if (self
::getSession()->getVar('forceBackgroundQueuePerform')) {
719 self
::getTPL()->assign([
720 'forceBackgroundQueuePerform' => true
723 self
::getSession()->unregister('forceBackgroundQueuePerform');
727 EmailTemplateEngine
::getInstance()->registerPrefilter(['event', 'hascontent', 'lang']);
728 EmailTemplateEngine
::getInstance()->assign([
734 * Wrapper for the getter methods of this class.
736 * @param string $name
737 * @return mixed value
738 * @throws SystemException
740 public function __get($name) {
741 $method = 'get'.ucfirst($name);
742 if (method_exists($this, $method)) {
743 return $this->$method();
746 throw new SystemException("method '".$method."' does not exist in class WCF");
750 * Returns true if current application (WCF) is treated as active and was invoked directly.
754 public function isActiveApplication() {
755 return (ApplicationHandler
::getInstance()->getActiveApplication()->packageID
== 1);
759 * Changes the active language.
761 * @param integer $languageID
763 public static final function setLanguage($languageID) {
764 if (!$languageID || LanguageFactory
::getInstance()->getLanguage($languageID) === null) {
765 $languageID = LanguageFactory
::getInstance()->getDefaultLanguageID();
768 self
::$languageObj = LanguageFactory
::getInstance()->getLanguage($languageID);
770 // the template engine may not be available yet, usually happens when
771 // changing the user (and thus the language id) during session init
772 if (self
::$tplObj !== null) {
773 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
774 EmailTemplateEngine
::getInstance()->setLanguageID(self
::getLanguage()->languageID
);
779 * Includes the required util or exception classes automatically.
781 * @param string $className
782 * @see spl_autoload_register()
784 public static final function autoload($className) {
785 $namespaces = explode('\\', $className);
786 if (count($namespaces) > 1) {
787 $applicationPrefix = array_shift($namespaces);
788 if ($applicationPrefix === '') {
789 $applicationPrefix = array_shift($namespaces);
791 if (isset(self
::$autoloadDirectories[$applicationPrefix])) {
792 $classPath = self
::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
793 if (file_exists($classPath)) {
794 require_once($classPath);
803 public final function __call($name, array $arguments) {
804 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
805 if (!method_exists($this, $name)) {
806 return self
::__callStatic($name, $arguments);
809 return $this->$name($arguments);
813 * Returns dynamically loaded core objects.
815 * @param string $name
816 * @param array $arguments
818 * @throws SystemException
820 public static final function __callStatic($name, array $arguments) {
821 $className = preg_replace('~^get~', '', $name);
823 if (isset(self
::$coreObject[$className])) {
824 return self
::$coreObject[$className];
827 $objectName = self
::getCoreObject($className);
828 if ($objectName === null) {
829 throw new SystemException("Core object '".$className."' is unknown.");
832 if (class_exists($objectName)) {
833 if (!is_subclass_of($objectName, SingletonFactory
::class)) {
834 throw new ParentClassException($objectName, SingletonFactory
::class);
837 self
::$coreObject[$className] = call_user_func([$objectName, 'getInstance']);
838 return self
::$coreObject[$className];
843 * Searches for cached core object definition.
845 * @param string $className
848 protected static final function getCoreObject($className) {
849 if (isset(self
::$coreObjectCache[$className])) {
850 return self
::$coreObjectCache[$className];
857 * Returns true if the debug mode is enabled, otherwise false.
859 * @param boolean $ignoreACP
862 public static function debugModeIsEnabled($ignoreACP = false) {
864 if (!$ignoreACP && self
::$overrideDebugMode) {
867 else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE
) {
875 * Returns true if benchmarking is enabled, otherwise false.
879 public static function benchmarkIsEnabled() {
880 // benchmarking is enabled by default
881 if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK
) return true;
886 * Returns domain path for given application.
888 * @param string $abbreviation
891 public static function getPath($abbreviation = 'wcf') {
892 // workaround during WCFSetup
897 if (!isset(self
::$applications[$abbreviation])) {
898 $abbreviation = 'wcf';
901 return self
::$applications[$abbreviation]->getPageURL();
905 * Returns the domain path for the currently active application,
906 * used to avoid CORS requests.
910 public static function getActivePath() {
912 return self
::getPath();
915 return self
::getPath(ApplicationHandler
::getInstance()->getAbbreviation(ApplicationHandler
::getInstance()->getActiveApplication()->packageID
));
919 * Returns a fully qualified anchor for current page.
921 * @param string $fragment
924 public function getAnchor($fragment) {
925 return StringUtil
::encodeHTML(self
::getRequestURI() . '#' . $fragment);
929 * Returns the currently active page or null if unknown.
933 public static function getActivePage() {
934 if (self
::getActiveRequest() === null) {
938 if (self
::getActiveRequest()->getClassName() === CmsPage
::class) {
939 $metaData = self
::getActiveRequest()->getMetaData();
940 if (isset($metaData['cms'])) {
941 return PageCache
::getInstance()->getPage($metaData['cms']['pageID']);
947 return PageCache
::getInstance()->getPageByController(self
::getActiveRequest()->getClassName());
951 * Returns the currently active request.
955 public static function getActiveRequest() {
956 return RequestHandler
::getInstance()->getActiveRequest();
960 * Returns the URI of the current page.
964 public static function getRequestURI() {
965 return preg_replace('~^(https?://[^/]+)(?:/.*)?$~', '$1', self
::getTPL()->get('baseHref')) . $_SERVER['REQUEST_URI'];
969 * Resets Zend Opcache cache if installed and enabled.
971 * @param string $script
973 public static function resetZendOpcache($script = '') {
974 if (self
::$zendOpcacheEnabled === null) {
975 self
::$zendOpcacheEnabled = false;
977 if (extension_loaded('Zend Opcache') && @ini_get
('opcache.enable')) {
978 self
::$zendOpcacheEnabled = true;
983 if (self
::$zendOpcacheEnabled) {
984 if (empty($script)) {
988 opcache_invalidate($script, true);
994 * Returns style handler.
996 * @return StyleHandler
998 public function getStyleHandler() {
999 return StyleHandler
::getInstance();
1003 * Returns box handler.
1005 * @return BoxHandler
1008 public function getBoxHandler() {
1009 return BoxHandler
::getInstance();
1013 * Returns number of available updates.
1017 public function getAvailableUpdates() {
1018 $data = PackageUpdateCacheBuilder
::getInstance()->getData();
1019 return $data['updates'];
1023 * Returns a 8 character prefix for editor autosave.
1027 public function getAutosavePrefix() {
1028 return substr(sha1(preg_replace('~^https~', 'http', self
::getPath())), 0, 8);
1032 * Returns the favicon URL or a base64 encoded image.
1036 public function getFavicon() {
1037 $activeApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1038 $wcf = ApplicationHandler
::getInstance()->getWCF();
1039 $favicon = StyleHandler
::getInstance()->getStyle()->getRelativeFavicon();
1041 if ($activeApplication->domainName
!== $wcf->domainName
) {
1042 if (file_exists(WCF_DIR
.$favicon)) {
1043 $favicon = file_get_contents(WCF_DIR
.$favicon);
1045 return 'data:image/x-icon;base64,' . base64_encode($favicon);
1049 return self
::getPath() . $favicon;
1053 * Returns true if the desktop notifications should be enabled.
1057 public function useDesktopNotifications() {
1058 if (!ENABLE_DESKTOP_NOTIFICATIONS
) {
1061 else if (ApplicationHandler
::getInstance()->isMultiDomainSetup()) {
1062 $application = ApplicationHandler
::getInstance()->getApplicationByID(DESKTOP_NOTIFICATION_PACKAGE_ID
);
1063 // mismatch, default to Core
1064 if ($application === null) $application = ApplicationHandler
::getInstance()->getApplicationByID(1);
1066 $currentApplication = ApplicationHandler
::getInstance()->getActiveApplication();
1067 if ($currentApplication->domainName
!= $application->domainName
) {
1077 * Returns true if currently active request represents the landing page.
1081 public static function isLandingPage() {
1082 if (self
::getActiveRequest() === null) {
1086 return self
::getActiveRequest()->isLandingPage();
1090 * Returns true if the given API version is currently supported.
1092 * @param integer $apiVersion
1095 public static function isSupportedApiVersion($apiVersion) {
1096 return ($apiVersion == WSC_API_VERSION
) ||
in_array($apiVersion, self
::$supportedLegacyApiVersions);
1100 * Returns the list of supported legacy API versions.
1104 public static function getSupportedLegacyApiVersions() {
1105 return self
::$supportedLegacyApiVersions;
1109 * Initialises the cronjobs.
1111 protected function initCronjobs() {
1113 self
::getTPL()->assign('executeCronjobs', CronjobScheduler
::getInstance()->getNextExec() < TIME_NOW
&& defined('OFFLINE') && !OFFLINE
);