Add explicit `return null;` statements
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / lib / system / WCF.class.php
CommitLineData
d335fa16 1<?php
a9229942 2
d335fa16 3namespace wcf\system;
a9229942 4
d335fa16
AE
5use wcf\data\application\Application;
6use wcf\data\option\OptionEditor;
7use wcf\data\package\Package;
8use wcf\data\package\PackageCache;
9use wcf\data\package\PackageEditor;
12a2ff01
AE
10use wcf\data\page\Page;
11use wcf\data\page\PageCache;
5346b183 12use wcf\page\CmsPage;
d335fa16 13use wcf\system\application\ApplicationHandler;
f341086b 14use wcf\system\application\IApplication;
55b402a0 15use wcf\system\box\BoxHandler;
d335fa16
AE
16use wcf\system\cache\builder\CoreObjectCacheBuilder;
17use wcf\system\cache\builder\PackageUpdateCacheBuilder;
18use wcf\system\cronjob\CronjobScheduler;
157054c9 19use wcf\system\database\MySQLDatabase;
d335fa16
AE
20use wcf\system\event\EventHandler;
21use wcf\system\exception\AJAXException;
b25ad8f3 22use wcf\system\exception\ErrorException;
d335fa16
AE
23use wcf\system\exception\IPrintableException;
24use wcf\system\exception\NamedUserException;
7b9ff46b 25use wcf\system\exception\ParentClassException;
d335fa16
AE
26use wcf\system\exception\PermissionDeniedException;
27use wcf\system\exception\SystemException;
28use wcf\system\language\LanguageFactory;
29use wcf\system\package\PackageInstallationDispatcher;
11117cd5 30use wcf\system\registry\RegistryHandler;
12a2ff01 31use wcf\system\request\Request;
a80873d5 32use wcf\system\request\RequestHandler;
d335fa16
AE
33use wcf\system\session\SessionFactory;
34use wcf\system\session\SessionHandler;
35use wcf\system\style\StyleHandler;
15621401 36use wcf\system\template\EmailTemplateEngine;
d335fa16
AE
37use wcf\system\template\TemplateEngine;
38use wcf\system\user\storage\UserStorageHandler;
66d9b64b 39use wcf\util\DirectoryUtil;
d335fa16 40use wcf\util\FileUtil;
8418bed7 41use wcf\util\HeaderUtil;
d335fa16 42use wcf\util\StringUtil;
dc0015ab 43use wcf\util\UserUtil;
d335fa16 44
82d72850
TD
45// phpcs:disable PSR1.Files.SideEffects
46
d335fa16 47// try to set a time-limit to infinite
a9229942 48@\set_time_limit(0);
d335fa16
AE
49
50// fix timezone warning issue
a9229942
TD
51if (!@\ini_get('date.timezone')) {
52 @\date_default_timezone_set('Europe/London');
d335fa16
AE
53}
54
359841c3 55// define current woltlab suite version
a3bfdecc 56\define('WCF_VERSION', '5.4.0 Alpha 1');
d335fa16 57
89484ba0 58// define current API version
0e8af3ef 59// @deprecated 5.2
a9229942 60\define('WSC_API_VERSION', 2019);
89484ba0 61
d335fa16 62// define current unix timestamp
a9229942 63\define('TIME_NOW', \time());
d335fa16
AE
64
65// wcf imports
a9229942
TD
66if (!\defined('NO_IMPORTS')) {
67 require_once(WCF_DIR . 'lib/core.functions.php');
68 require_once(WCF_DIR . 'lib/system/api/autoload.php');
d335fa16
AE
69}
70
71/**
e71525e4 72 * WCF is the central class for the WoltLab Suite Core.
d335fa16 73 * It holds the database connection, access to template and language engine.
a9229942
TD
74 *
75 * @author Marcel Werk
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
d335fa16 79 */
a9229942
TD
80class WCF
81{
82 /**
83 * list of supported legacy API versions
84 * @var int[]
85 * @deprecated 5.2
86 */
87 private static $supportedLegacyApiVersions = [2017, 2018];
88
89 /**
90 * list of currently loaded applications
91 * @var Application[]
92 */
93 protected static $applications = [];
94
95 /**
96 * list of currently loaded application objects
97 * @var IApplication[]
98 */
99 protected static $applicationObjects = [];
100
101 /**
102 * list of autoload directories
103 * @var array
104 */
105 protected static $autoloadDirectories = [];
106
107 /**
108 * list of unique instances of each core object
109 * @var SingletonFactory[]
110 */
111 protected static $coreObject = [];
112
113 /**
114 * list of cached core objects
115 * @var string[]
116 */
117 protected static $coreObjectCache = [];
118
119 /**
120 * database object
121 * @var MySQLDatabase
122 */
123 protected static $dbObj;
124
125 /**
126 * language object
127 * @var \wcf\data\language\Language
128 */
129 protected static $languageObj;
130
131 /**
132 * overrides disabled debug mode
133 * @var bool
134 */
135 protected static $overrideDebugMode = false;
136
137 /**
138 * session object
139 * @var SessionHandler
140 */
141 protected static $sessionObj;
142
143 /**
144 * template object
145 * @var TemplateEngine
146 */
147 protected static $tplObj;
148
149 /**
150 * true if Zend Opcache is loaded and enabled
151 * @var bool
152 */
153 protected static $zendOpcacheEnabled;
154
155 /**
156 * force logout during destructor call
157 * @var bool
158 */
159 protected static $forceLogout = false;
160
161 /**
162 * Calls all init functions of the WCF class.
163 */
164 public function __construct()
165 {
166 // add autoload directory
167 self::$autoloadDirectories['wcf'] = WCF_DIR . 'lib/';
168
169 // define tmp directory
170 if (!\defined('TMP_DIR')) {
171 \define('TMP_DIR', FileUtil::getTempFolder());
172 }
173
174 // start initialization
175 $this->initDB();
176 $this->loadOptions();
177 $this->initSession();
178 $this->initLanguage();
179 $this->initTPL();
180 $this->initCronjobs();
181 $this->initCoreObjects();
182 $this->initApplications();
183 $this->initBlacklist();
184
185 EventHandler::getInstance()->fireAction($this, 'initialized');
186 }
187
188 /**
189 * Flushes the output, closes the session, performs background tasks and more.
190 *
191 * You *must* not create output in here under normal circumstances, as it might get eaten
192 * when gzip is enabled.
193 */
194 public static function destruct()
195 {
196 try {
197 // database has to be initialized
198 if (!\is_object(self::$dbObj)) {
199 return;
200 }
201
202 $debug = self::debugModeIsEnabled(true);
203 if (!$debug) {
204 // flush output
205 if (\ob_get_level()) {
206 \ob_end_flush();
207 }
208 \flush();
209
210 // close connection if using FPM
211 if (\function_exists('fastcgi_finish_request')) {
212 fastcgi_finish_request();
213 }
214 }
215
216 // update session
217 if (\is_object(self::getSession())) {
218 if (self::$forceLogout) {
219 // do logout
220 self::getSession()->delete();
221 } else {
222 self::getSession()->update();
223 }
224 }
225
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());
231 }
232 }
233
234 /**
235 * Returns the database object.
236 *
237 * @return \wcf\system\database\Database
238 */
239 final public static function getDB()
240 {
241 return self::$dbObj;
242 }
243
244 /**
245 * Returns the session object.
246 *
247 * @return SessionHandler
248 */
249 final public static function getSession()
250 {
251 return self::$sessionObj;
252 }
253
254 /**
255 * Returns the user object.
256 *
257 * @return \wcf\data\user\User
258 */
259 final public static function getUser()
260 {
261 return self::getSession()->getUser();
262 }
263
264 /**
265 * Returns the language object.
266 *
267 * @return \wcf\data\language\Language
268 */
269 final public static function getLanguage()
270 {
271 return self::$languageObj;
272 }
273
274 /**
275 * Returns the template object.
276 *
277 * @return TemplateEngine
278 */
279 final public static function getTPL()
280 {
281 return self::$tplObj;
282 }
283
284 /**
285 * Calls the show method on the given exception.
286 *
52439f61 287 * @param \Throwable $e
a9229942
TD
288 */
289 final public static function handleException($e)
290 {
291 // backwards compatibility
292 if ($e instanceof IPrintableException) {
293 $e->show();
294
295 exit;
296 }
297
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
301 //
302 // ob_get_level() can return values > 1, if the PHP setting `output_buffering` is on
303 while (\ob_get_level()) {
304 \ob_end_clean();
305 }
306 }
307
308 @\header('HTTP/1.1 503 Service Unavailable');
309 try {
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>";
317
318 exit;
319 }
320 }
321
322 /**
323 * Turns PHP errors into an ErrorException.
324 *
325 * @param int $severity
326 * @param string $message
327 * @param string $file
328 * @param int $line
329 * @throws ErrorException
330 */
331 final public static function handleError($severity, $message, $file, $line)
332 {
333 // this is necessary for the shut-up operator
334 if (!(\error_reporting() & $severity)) {
335 return;
336 }
337
338 throw new ErrorException($message, 0, $severity, $file, $line);
339 }
340
341 /**
342 * Loads the database configuration and creates a new connection to the database.
343 */
344 protected function initDB()
345 {
346 // get configuration
347 $dbHost = $dbUser = $dbPassword = $dbName = '';
348 $dbPort = 0;
349 $defaultDriverOptions = [];
350 require(WCF_DIR . 'config.inc.php');
351
352 // create database connection
353 self::$dbObj = new MySQLDatabase(
354 $dbHost,
355 $dbUser,
356 $dbPassword,
357 $dbName,
358 $dbPort,
359 false,
360 false,
361 $defaultDriverOptions
362 );
363 }
364
365 /**
366 * Loads the options file, automatically created if not exists.
367 */
368 protected function loadOptions()
4dfebec1
MS
369 {
370 $this->defineLegacyOptions();
371
372 $filename = WCF_DIR . 'options.inc.php';
373
374 // create options file if doesn't exist
375 if (!\file_exists($filename) || \filemtime($filename) <= 1) {
376 OptionEditor::rebuild();
377 }
378 require($filename);
379
380 // check if option file is complete and writable
381 if (PACKAGE_ID) {
382 if (!\is_writable($filename)) {
383 FileUtil::makeWritable($filename);
384
385 if (!\is_writable($filename)) {
386 throw new SystemException("The option file '" . $filename . "' is not writable.");
387 }
388 }
389
390 // check if a previous write operation was incomplete and force rebuilding
391 if (!\defined('WCF_OPTION_INC_PHP_SUCCESS')) {
392 OptionEditor::rebuild();
393
394 require($filename);
395 }
396
397 if (ENABLE_DEBUG_MODE) {
398 self::$dbObj->enableDebugMode();
399 }
400 }
401 }
402
403 /**
404 * Defines constants for obsolete options, which were removed.
405 *
406 * @since 5.4
407 */
408 protected function defineLegacyOptions(): void
a9229942
TD
409 {
410 // The attachment module is always enabled since 5.2.
411 // https://github.com/WoltLab/WCF/issues/2531
412 \define('MODULE_ATTACHMENT', 1);
413
414 // Users cannot react to their own content since 5.2.
415 // https://github.com/WoltLab/WCF/issues/2975
416 \define('LIKE_ALLOW_FOR_OWN_CONTENT', 0);
417 \define('LIKE_ENABLE_DISLIKE', 0);
418
419 // Thumbnails for attachments are already enabled since 5.3.
420 // https://github.com/WoltLab/WCF/pull/3444
421 \define('ATTACHMENT_ENABLE_THUMBNAILS', 1);
422
423 // User markings are always applied in sidebars since 5.3.
424 // https://github.com/WoltLab/WCF/issues/3330
425 \define('MESSAGE_SIDEBAR_ENABLE_USER_ONLINE_MARKING', 1);
426
427 // Password strength configuration is deprecated since 5.3.
428 \define('REGISTER_ENABLE_PASSWORD_SECURITY_CHECK', 0);
429 \define('REGISTER_PASSWORD_MIN_LENGTH', 0);
430 \define('REGISTER_PASSWORD_MUST_CONTAIN_LOWER_CASE', 8);
431 \define('REGISTER_PASSWORD_MUST_CONTAIN_UPPER_CASE', 0);
432 \define('REGISTER_PASSWORD_MUST_CONTAIN_DIGIT', 0);
433 \define('REGISTER_PASSWORD_MUST_CONTAIN_SPECIAL_CHAR', 0);
434
435 // rel=nofollow is always applied to external link since 5.3
436 // https://github.com/WoltLab/WCF/issues/3339
437 \define('EXTERNAL_LINK_REL_NOFOLLOW', 1);
438
439 // Session validation is removed since 5.4.
440 // https://github.com/WoltLab/WCF/pull/3583
441 \define('SESSION_VALIDATE_IP_ADDRESS', 0);
442 \define('SESSION_VALIDATE_USER_AGENT', 0);
443
444 // Virtual sessions no longer exist since 5.4.
445 \define('SESSION_ENABLE_VIRTUALIZATION', 1);
446
447 // The session timeout is fully managed since 5.4.
448 \define('SESSION_TIMEOUT', 3600);
449
450 // gzip compression is removed in 5.4.
451 // https://github.com/WoltLab/WCF/issues/3634
452 \define('HTTP_ENABLE_GZIP', 0);
453
454 // Meta keywords are no longer used since 5.4.
455 // https://github.com/WoltLab/WCF/issues/3561
456 \define('META_KEYWORDS', '');
457
458 // The admin notification is redundant and removed in 5.4.
459 // https://github.com/WoltLab/WCF/issues/3674
460 \define('REGISTER_ADMIN_NOTIFICATION', 0);
461
8b73fa91
TD
462 // The hostname blocklist was removed in 5.4.
463 // https://github.com/WoltLab/WCF/issues/3909
464 \define('BLACKLIST_HOSTNAMES', '');
465
2634aad9
AE
466 // Cover photos are always enabled since 5.4.
467 // https://github.com/WoltLab/WCF/issues/3902
468 \define('MODULE_USER_COVER_PHOTO', 1);
a9229942
TD
469 }
470
471 /**
472 * Starts the session system.
473 */
474 protected function initSession()
475 {
476 $factory = new SessionFactory();
477 $factory->load();
478
479 self::$sessionObj = SessionHandler::getInstance();
480 }
481
482 /**
483 * Initialises the language engine.
484 */
485 protected function initLanguage()
486 {
487 if (isset($_GET['l']) && !self::getUser()->userID) {
488 self::getSession()->setLanguageID(\intval($_GET['l']));
489 }
490
491 // set mb settings
492 \mb_internal_encoding('UTF-8');
493 if (\function_exists('mb_regex_encoding')) {
494 \mb_regex_encoding('UTF-8');
495 }
496 \mb_language('uni');
497
498 // get language
499 self::$languageObj = LanguageFactory::getInstance()->getUserLanguage(self::getSession()->getLanguageID());
500 }
501
502 /**
503 * Initialises the template engine.
504 */
505 protected function initTPL()
506 {
507 self::$tplObj = TemplateEngine::getInstance();
508 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
509 $this->assignDefaultTemplateVariables();
510
511 $this->initStyle();
512 }
513
514 /**
515 * Initializes the user's style.
516 */
517 protected function initStyle()
518 {
519 if (isset($_REQUEST['styleID'])) {
520 self::getSession()->setStyleID(\intval($_REQUEST['styleID']));
521 }
522
523 $styleHandler = StyleHandler::getInstance();
524 $styleHandler->changeStyle(self::getSession()->getStyleID());
525 }
526
527 /**
528 * Executes the blacklist.
529 */
530 protected function initBlacklist()
531 {
532 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
533
534 if (\defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES != '') {
535 if (
536 !StringUtil::executeWordFilter(
537 UserUtil::convertIPv6To4(UserUtil::getIpAddress()),
538 BLACKLIST_IP_ADDRESSES
539 )
540 ) {
541 if ($isAjax) {
542 throw new AJAXException(
543 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
544 AJAXException::INSUFFICIENT_PERMISSIONS
545 );
546 } else {
547 throw new PermissionDeniedException();
548 }
549 } elseif (!StringUtil::executeWordFilter(UserUtil::getIpAddress(), BLACKLIST_IP_ADDRESSES)) {
550 if ($isAjax) {
551 throw new AJAXException(
552 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
553 AJAXException::INSUFFICIENT_PERMISSIONS
554 );
555 } else {
556 throw new PermissionDeniedException();
557 }
558 }
559 }
560 if (\defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS != '') {
561 if (!StringUtil::executeWordFilter(UserUtil::getUserAgent(), BLACKLIST_USER_AGENTS)) {
562 if ($isAjax) {
563 throw new AJAXException(
564 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
565 AJAXException::INSUFFICIENT_PERMISSIONS
566 );
567 } else {
568 throw new PermissionDeniedException();
569 }
570 }
571 }
8b73fa91 572
a9229942
TD
573 // handle banned users
574 if (self::getUser()->userID && self::getUser()->banned && !self::getUser()->hasOwnerAccess()) {
575 if ($isAjax) {
576 throw new AJAXException(
577 self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'),
578 AJAXException::INSUFFICIENT_PERMISSIONS
579 );
580 } else {
581 self::$forceLogout = true;
582
583 // remove cookies
584 if (isset($_COOKIE[COOKIE_PREFIX . 'userID'])) {
585 HeaderUtil::setCookie('userID', 0);
586 }
587 if (isset($_COOKIE[COOKIE_PREFIX . 'password'])) {
588 HeaderUtil::setCookie('password', '');
589 }
590
591 throw new NamedUserException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
592 }
593 }
594 }
595
596 /**
597 * Initializes applications.
598 */
599 protected function initApplications()
600 {
601 // step 1) load all applications
602 $loadedApplications = [];
603
604 // register WCF as application
605 self::$applications['wcf'] = ApplicationHandler::getInstance()->getApplicationByID(1);
606
607 if (!\class_exists(WCFACP::class, false)) {
608 static::getTPL()->assign('baseHref', self::$applications['wcf']->getPageURL());
609 }
610
611 // start main application
612 $application = ApplicationHandler::getInstance()->getActiveApplication();
613 if ($application->packageID != 1) {
614 $loadedApplications[] = $this->loadApplication($application);
615
616 // register primary application
617 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
618 self::$applications[$abbreviation] = $application;
619 }
620
621 // start dependent applications
622 $applications = ApplicationHandler::getInstance()->getDependentApplications();
623 foreach ($applications as $application) {
624 if ($application->packageID == 1) {
625 // ignore WCF
626 continue;
627 } elseif ($application->isTainted) {
628 // ignore apps flagged for uninstallation
629 continue;
630 }
631
632 $loadedApplications[] = $this->loadApplication($application, true);
633 }
634
635 // step 2) run each application
636 if (!\class_exists('wcf\system\WCFACP', false)) {
637 /** @var IApplication $application */
638 foreach ($loadedApplications as $application) {
639 $application->__run();
640 }
641
642 /** @deprecated The below variable is deprecated. */
643 self::getTPL()->assign('__sessionKeepAlive', 59 * 60);
644 }
645 }
646
647 /**
648 * Loads an application.
649 *
650 * @param Application $application
651 * @param bool $isDependentApplication
652 * @return IApplication
653 * @throws SystemException
654 */
655 protected function loadApplication(Application $application, $isDependentApplication = false)
656 {
657 $package = PackageCache::getInstance()->getPackage($application->packageID);
658 // package cache might be outdated
659 if ($package === null) {
660 $package = new Package($application->packageID);
661
662 // package cache is outdated, discard cache
663 if ($package->packageID) {
664 PackageEditor::resetCache();
665 } else {
666 // package id is invalid
667 throw new SystemException("application identified by package id '" . $application->packageID . "' is unknown");
668 }
669 }
670
671 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
672 $packageDir = FileUtil::getRealPath(WCF_DIR . $package->packageDir);
673 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
674
675 $className = $abbreviation . '\system\\' . \strtoupper($abbreviation) . 'Core';
676
677 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
678 if (!\class_exists($className)) {
679 // check if both the Core and the app are on the same domain
680 $coreApp = ApplicationHandler::getInstance()->getApplicationByID(1);
681 if ($coreApp->domainName === $application->domainName) {
682 // resolve the relative path and use it to construct the autoload directory
683 $relativePath = FileUtil::getRelativePath($coreApp->domainPath, $application->domainPath);
684 if ($relativePath !== './') {
685 $packageDir = FileUtil::getRealPath(WCF_DIR . $relativePath);
686 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
687
688 if (\class_exists($className)) {
689 // the class can now be found, update the `packageDir` value
690 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
691 }
692 }
693 }
694 }
695
696 if (\class_exists($className) && \is_subclass_of($className, IApplication::class)) {
697 // include config file
698 $configPath = $packageDir . PackageInstallationDispatcher::CONFIG_FILE;
699 if (!\file_exists($configPath)) {
700 Package::writeConfigFile($package->packageID);
701 }
702
703 if (\file_exists($configPath)) {
704 require_once($configPath);
705 } else {
706 throw new SystemException('Unable to load configuration for ' . $package->package);
707 }
708
709 // register template path if not within ACP
710 if (!\class_exists('wcf\system\WCFACP', false)) {
711 // add template path and abbreviation
712 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
713 }
714 EmailTemplateEngine::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
715
716 // init application and assign it as template variable
717 self::$applicationObjects[$application->packageID] = \call_user_func([$className, 'getInstance']);
718 static::getTPL()->assign('__' . $abbreviation, self::$applicationObjects[$application->packageID]);
719 EmailTemplateEngine::getInstance()->assign(
720 '__' . $abbreviation,
721 self::$applicationObjects[$application->packageID]
722 );
723 } else {
724 unset(self::$autoloadDirectories[$abbreviation]);
725 throw new SystemException("Unable to run '" . $package->package . "', '" . $className . "' is missing or does not implement '" . IApplication::class . "'.");
726 }
727
728 // register template path in ACP
729 if (\class_exists('wcf\system\WCFACP', false)) {
730 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
731 } elseif (!$isDependentApplication) {
732 // assign base tag
733 static::getTPL()->assign('baseHref', $application->getPageURL());
734 }
735
736 // register application
737 self::$applications[$abbreviation] = $application;
738
739 return self::$applicationObjects[$application->packageID];
740 }
741
742 /**
743 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
744 *
745 * @param Application $application
746 * @return IApplication
747 */
748 public static function getApplicationObject(Application $application)
749 {
813c41ce 750 return self::$applicationObjects[$application->packageID] ?? null;
a9229942
TD
751 }
752
753 /**
754 * Returns the invoked application.
755 *
756 * @return Application
757 * @since 3.1
758 */
759 public static function getActiveApplication()
760 {
761 return ApplicationHandler::getInstance()->getActiveApplication();
762 }
763
764 /**
765 * Loads an application on runtime, do not use this outside the package installation.
766 *
767 * @param int $packageID
768 */
769 public static function loadRuntimeApplication($packageID)
770 {
771 $package = new Package($packageID);
772 $application = new Application($packageID);
773
774 $abbreviation = Package::getAbbreviation($package->package);
775 $packageDir = FileUtil::getRealPath(WCF_DIR . $package->packageDir);
776 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
777 self::$applications[$abbreviation] = $application;
778 self::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
779 }
780
781 /**
782 * Initializes core object cache.
783 */
784 protected function initCoreObjects()
785 {
786 // ignore core objects if installing WCF
787 if (PACKAGE_ID == 0) {
788 return;
789 }
790
791 self::$coreObjectCache = CoreObjectCacheBuilder::getInstance()->getData();
792 }
793
794 /**
795 * Assigns some default variables to the template engine.
796 */
797 protected function assignDefaultTemplateVariables()
798 {
799 $wcf = $this;
800
801 if (ENABLE_ENTERPRISE_MODE) {
802 $wcf = new TemplateScriptingCore($wcf);
803 }
804
805 self::getTPL()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang', 'csrfToken']);
806 self::getTPL()->assign([
807 '__wcf' => $wcf,
808 '__wcfVersion' => LAST_UPDATE_TIME, // @deprecated 2.1, use LAST_UPDATE_TIME directly
809 ]);
810
811 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
812 // Execute background queue in this request, if it was requested and AJAX isn't used.
813 if (!$isAjax) {
814 if (self::getSession()->getVar('forceBackgroundQueuePerform')) {
815 self::getTPL()->assign([
816 'forceBackgroundQueuePerform' => true,
817 ]);
818
819 self::getSession()->unregister('forceBackgroundQueuePerform');
820 }
821 }
822
823 EmailTemplateEngine::getInstance()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang']);
824 EmailTemplateEngine::getInstance()->assign([
825 '__wcf' => $wcf,
826 ]);
827 }
828
829 /**
830 * Wrapper for the getter methods of this class.
831 *
832 * @param string $name
833 * @return mixed value
834 * @throws SystemException
835 */
836 public function __get($name)
837 {
838 $method = 'get' . \ucfirst($name);
839 if (\method_exists($this, $method)) {
840 return $this->{$method}();
841 }
842
843 throw new SystemException("method '" . $method . "' does not exist in class WCF");
844 }
845
846 /**
847 * Returns true if current application (WCF) is treated as active and was invoked directly.
848 *
849 * @return bool
850 */
851 public function isActiveApplication()
852 {
853 return ApplicationHandler::getInstance()->getActiveApplication()->packageID == 1;
854 }
855
856 /**
857 * Changes the active language.
858 *
859 * @param int $languageID
860 */
861 final public static function setLanguage($languageID)
862 {
863 if (!$languageID || LanguageFactory::getInstance()->getLanguage($languageID) === null) {
864 $languageID = LanguageFactory::getInstance()->getDefaultLanguageID();
865 }
866
867 self::$languageObj = LanguageFactory::getInstance()->getLanguage($languageID);
868
869 // the template engine may not be available yet, usually happens when
870 // changing the user (and thus the language id) during session init
871 if (self::$tplObj !== null) {
872 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
873 EmailTemplateEngine::getInstance()->setLanguageID(self::getLanguage()->languageID);
874 }
875 }
876
877 /**
878 * Includes the required util or exception classes automatically.
879 *
880 * @param string $className
881 * @see spl_autoload_register()
882 */
883 final public static function autoload($className)
884 {
885 $namespaces = \explode('\\', $className);
886 if (\count($namespaces) > 1) {
887 $applicationPrefix = \array_shift($namespaces);
888 if ($applicationPrefix === '') {
889 $applicationPrefix = \array_shift($namespaces);
890 }
891 if (isset(self::$autoloadDirectories[$applicationPrefix])) {
892 $classPath = self::$autoloadDirectories[$applicationPrefix] . \implode('/', $namespaces) . '.class.php';
893
894 // PHP will implicitly check if the file exists when including it, which means that we can save a
895 // redundant syscall/fs access by not checking for existence ourselves. Do not use require_once()!
896 @include_once($classPath);
897 }
898 }
899 }
900
901 /**
902 * @inheritDoc
903 */
904 final public function __call($name, array $arguments)
905 {
906 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
907 if (!\method_exists($this, $name)) {
908 return self::__callStatic($name, $arguments);
909 }
910
911 throw new \BadMethodCallException("Call to undefined method WCF::{$name}().");
912 }
913
914 /**
915 * Returns dynamically loaded core objects.
916 *
917 * @param string $name
918 * @param array $arguments
919 * @return object
920 * @throws SystemException
921 */
922 final public static function __callStatic($name, array $arguments)
923 {
924 $className = \preg_replace('~^get~', '', $name);
925
926 if (isset(self::$coreObject[$className])) {
927 return self::$coreObject[$className];
928 }
929
930 $objectName = self::getCoreObject($className);
931 if ($objectName === null) {
932 throw new SystemException("Core object '" . $className . "' is unknown.");
933 }
934
935 if (\class_exists($objectName)) {
936 if (!\is_subclass_of($objectName, SingletonFactory::class)) {
937 throw new ParentClassException($objectName, SingletonFactory::class);
938 }
939
940 self::$coreObject[$className] = \call_user_func([$objectName, 'getInstance']);
941
942 return self::$coreObject[$className];
943 }
944 }
945
946 /**
947 * Searches for cached core object definition.
948 *
949 * @param string $className
5227ebc7 950 * @return string|null
a9229942
TD
951 */
952 final protected static function getCoreObject($className)
953 {
813c41ce 954 return self::$coreObjectCache[$className] ?? null;
a9229942
TD
955 }
956
957 /**
958 * Returns true if the debug mode is enabled, otherwise false.
959 *
960 * @param bool $ignoreACP
961 * @return bool
962 */
963 public static function debugModeIsEnabled($ignoreACP = false)
964 {
965 // ACP override
966 if (!$ignoreACP && self::$overrideDebugMode) {
967 return true;
968 } elseif (\defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE) {
969 return true;
970 }
971
972 return false;
973 }
974
975 /**
976 * Returns true if benchmarking is enabled, otherwise false.
977 *
978 * @return bool
979 */
980 public static function benchmarkIsEnabled()
981 {
982 // benchmarking is enabled by default
983 if (!\defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK) {
984 return true;
985 }
986
987 return false;
988 }
989
990 /**
991 * Returns domain path for given application.
992 *
993 * @param string $abbreviation
994 * @return string
995 */
996 public static function getPath($abbreviation = 'wcf')
997 {
998 // workaround during WCFSetup
999 if (!PACKAGE_ID) {
1000 return '../';
1001 }
1002
1003 if (!isset(self::$applications[$abbreviation])) {
1004 $abbreviation = 'wcf';
1005 }
1006
1007 return self::$applications[$abbreviation]->getPageURL();
1008 }
1009
1010 /**
1011 * Returns the domain path for the currently active application,
1012 * used to avoid CORS requests.
1013 *
1014 * @return string
1015 */
1016 public static function getActivePath()
1017 {
1018 if (!PACKAGE_ID) {
1019 return self::getPath();
1020 }
1021
1022 // We cannot rely on the ApplicationHandler's `getActiveApplication()` because
1023 // it uses the requested controller to determine the namespace. However, starting
1024 // with WoltLab Suite 5.2, system pages can be virtually assigned to a different
1025 // app, resolving against the target app without changing the namespace.
1026 return self::getPath(ApplicationHandler::getInstance()->getAbbreviation(PACKAGE_ID));
1027 }
1028
1029 /**
1030 * Returns a fully qualified anchor for current page.
1031 *
1032 * @param string $fragment
1033 * @return string
1034 */
1035 public function getAnchor($fragment)
1036 {
1037 return StringUtil::encodeHTML(self::getRequestURI() . '#' . $fragment);
1038 }
1039
1040 /**
1041 * Returns the currently active page or null if unknown.
1042 *
1043 * @return Page|null
1044 */
1045 public static function getActivePage()
1046 {
1047 if (self::getActiveRequest() === null) {
c0b28aa2 1048 return null;
a9229942
TD
1049 }
1050
1051 if (self::getActiveRequest()->getClassName() === CmsPage::class) {
1052 $metaData = self::getActiveRequest()->getMetaData();
1053 if (isset($metaData['cms'])) {
1054 return PageCache::getInstance()->getPage($metaData['cms']['pageID']);
1055 }
1056
c0b28aa2 1057 return null;
a9229942
TD
1058 }
1059
1060 return PageCache::getInstance()->getPageByController(self::getActiveRequest()->getClassName());
1061 }
1062
1063 /**
1064 * Returns the currently active request.
1065 *
1066 * @return Request
1067 */
1068 public static function getActiveRequest()
1069 {
1070 return RequestHandler::getInstance()->getActiveRequest();
1071 }
1072
1073 /**
1074 * Returns the URI of the current page.
1075 *
1076 * @return string
1077 */
1078 public static function getRequestURI()
1079 {
1080 return \preg_replace(
1081 '~^(https?://[^/]+)(?:/.*)?$~',
1082 '$1',
1083 self::getTPL()->get('baseHref')
1084 ) . $_SERVER['REQUEST_URI'];
1085 }
1086
1087 /**
1088 * Resets Zend Opcache cache if installed and enabled.
1089 *
1090 * @param string $script
1091 */
1092 public static function resetZendOpcache($script = '')
1093 {
1094 if (self::$zendOpcacheEnabled === null) {
1095 self::$zendOpcacheEnabled = false;
1096
1097 if (\extension_loaded('Zend Opcache') && @\ini_get('opcache.enable')) {
1098 self::$zendOpcacheEnabled = true;
1099 }
1100 }
1101
1102 if (self::$zendOpcacheEnabled) {
1103 if (empty($script)) {
1104 \opcache_reset();
1105 } else {
1106 \opcache_invalidate($script, true);
1107 }
1108 }
1109 }
1110
1111 /**
1112 * Returns style handler.
1113 *
1114 * @return StyleHandler
1115 */
1116 public function getStyleHandler()
1117 {
1118 return StyleHandler::getInstance();
1119 }
1120
1121 /**
1122 * Returns box handler.
1123 *
1124 * @return BoxHandler
1125 * @since 3.0
1126 */
1127 public function getBoxHandler()
1128 {
1129 return BoxHandler::getInstance();
1130 }
1131
1132 /**
1133 * Returns number of available updates.
1134 *
1135 * @return int
1136 */
1137 public function getAvailableUpdates()
1138 {
1139 $data = PackageUpdateCacheBuilder::getInstance()->getData();
1140
1141 return $data['updates'];
1142 }
1143
1144 /**
1145 * Returns a 8 character prefix for editor autosave.
1146 *
1147 * @return string
1148 */
1149 public function getAutosavePrefix()
1150 {
1151 return \substr(\sha1(\preg_replace('~^https~', 'http', self::getPath())), 0, 8);
1152 }
1153
1154 /**
1155 * Returns the favicon URL or a base64 encoded image.
1156 *
1157 * @return string
1158 */
1159 public function getFavicon()
1160 {
1161 $activeApplication = ApplicationHandler::getInstance()->getActiveApplication();
1162 $wcf = ApplicationHandler::getInstance()->getWCF();
1163 $favicon = StyleHandler::getInstance()->getStyle()->getRelativeFavicon();
1164
1165 if ($activeApplication->domainName !== $wcf->domainName) {
1166 if (\file_exists(WCF_DIR . $favicon)) {
1167 $favicon = \file_get_contents(WCF_DIR . $favicon);
1168
1169 return 'data:image/x-icon;base64,' . \base64_encode($favicon);
1170 }
1171 }
1172
1173 return self::getPath() . $favicon;
1174 }
1175
1176 /**
1177 * Returns true if the desktop notifications should be enabled.
1178 *
1179 * @return bool
1180 */
1181 public function useDesktopNotifications()
1182 {
1183 if (!ENABLE_DESKTOP_NOTIFICATIONS) {
1184 return false;
1185 } elseif (ApplicationHandler::getInstance()->isMultiDomainSetup()) {
1186 $application = ApplicationHandler::getInstance()->getApplicationByID(DESKTOP_NOTIFICATION_PACKAGE_ID);
1187 // mismatch, default to Core
1188 if ($application === null) {
1189 $application = ApplicationHandler::getInstance()->getApplicationByID(1);
1190 }
1191
1192 $currentApplication = ApplicationHandler::getInstance()->getActiveApplication();
1193 if ($currentApplication->domainName != $application->domainName) {
1194 // different domain
1195 return false;
1196 }
1197 }
1198
1199 return true;
1200 }
1201
1202 /**
1203 * Returns true if currently active request represents the landing page.
1204 *
1205 * @return bool
1206 */
1207 public static function isLandingPage()
1208 {
1209 if (self::getActiveRequest() === null) {
1210 return false;
1211 }
1212
1213 return self::getActiveRequest()->isLandingPage();
1214 }
1215
1216 /**
1217 * Returns true if the given API version is currently supported.
1218 *
1219 * @param int $apiVersion
1220 * @return bool
1221 * @deprecated 5.2
1222 */
1223 public static function isSupportedApiVersion($apiVersion)
1224 {
1225 return ($apiVersion == WSC_API_VERSION) || \in_array($apiVersion, self::$supportedLegacyApiVersions);
1226 }
1227
1228 /**
1229 * Returns the list of supported legacy API versions.
1230 *
1231 * @return int[]
1232 * @deprecated 5.2
1233 */
1234 public static function getSupportedLegacyApiVersions()
1235 {
1236 return self::$supportedLegacyApiVersions;
1237 }
1238
1239 /**
1240 * Initialises the cronjobs.
1241 */
1242 protected function initCronjobs()
1243 {
1244 if (PACKAGE_ID) {
1245 self::getTPL()->assign(
1246 'executeCronjobs',
1247 CronjobScheduler::getInstance()->getNextExec() < TIME_NOW && \defined('OFFLINE') && !OFFLINE
1248 );
1249 }
1250 }
1251
1252 /**
1253 * Checks recursively that the most important system files of `com.woltlab.wcf` are writable.
1254 *
1255 * @throws \RuntimeException if any relevant file or directory is not writable
1256 */
1257 public static function checkWritability()
1258 {
1259 $nonWritablePaths = [];
1260
1261 $nonRecursiveDirectories = [
1262 '',
1263 'acp/',
1264 'tmp/',
1265 ];
1266 foreach ($nonRecursiveDirectories as $directory) {
1267 $path = WCF_DIR . $directory;
1268 if ($path === 'tmp/' && !\is_dir($path)) {
1269 continue;
1270 }
1271
1272 if (!\is_writable($path)) {
1273 $nonWritablePaths[] = FileUtil::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1274 continue;
1275 }
1276
1277 DirectoryUtil::getInstance($path, false)
1278 ->executeCallback(static function ($file, \SplFileInfo $fileInfo) use (&$nonWritablePaths) {
1279 if ($fileInfo instanceof \DirectoryIterator) {
1280 if (!\is_writable($fileInfo->getPath())) {
1281 $nonWritablePaths[] = FileUtil::getRelativePath(
1282 $_SERVER['DOCUMENT_ROOT'],
1283 $fileInfo->getPath()
1284 );
1285 }
1286 } elseif (!\is_writable($fileInfo->getRealPath())) {
1287 $nonWritablePaths[] = FileUtil::getRelativePath(
1288 $_SERVER['DOCUMENT_ROOT'],
1289 $fileInfo->getPath()
1290 ) . $fileInfo->getFilename();
1291 }
1292 });
1293 }
1294
1295 $recursiveDirectories = [
1296 'acp/js/',
1297 'acp/style/',
1298 'acp/templates/',
1299 'acp/uninstall/',
1300 'js/',
1301 'lib/',
1302 'log/',
1303 'style/',
1304 'templates/',
1305 ];
1306 foreach ($recursiveDirectories as $directory) {
1307 $path = WCF_DIR . $directory;
1308
1309 if (!\is_writable($path)) {
1310 $nonWritablePaths[] = FileUtil::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1311 continue;
1312 }
1313
1314 DirectoryUtil::getInstance($path)
1315 ->executeCallback(static function ($file, \SplFileInfo $fileInfo) use (&$nonWritablePaths) {
1316 if ($fileInfo instanceof \DirectoryIterator) {
1317 if (!\is_writable($fileInfo->getPath())) {
1318 $nonWritablePaths[] = FileUtil::getRelativePath(
1319 $_SERVER['DOCUMENT_ROOT'],
1320 $fileInfo->getPath()
1321 );
1322 }
1323 } elseif (!\is_writable($fileInfo->getRealPath())) {
1324 $nonWritablePaths[] = FileUtil::getRelativePath(
1325 $_SERVER['DOCUMENT_ROOT'],
1326 $fileInfo->getPath()
1327 ) . $fileInfo->getFilename();
1328 }
1329 });
1330 }
1331
1332 if (!empty($nonWritablePaths)) {
1333 $maxPaths = 10;
1334 throw new \RuntimeException('The following paths are not writable: ' . \implode(
1335 ',',
1336 \array_slice(
1337 $nonWritablePaths,
1338 0,
1339 $maxPaths
1340 )
1341 ) . (\count($nonWritablePaths) > $maxPaths ? ',' . StringUtil::HELLIP : ''));
1342 }
1343 }
d335fa16 1344}