Merge branch '5.4'
[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
925d0afe 56\define('WCF_VERSION', '5.4.0 Beta 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);
f35e23b5
MS
469
470 // The master password has been removed since 5.5.
471 // https://github.com/WoltLab/WCF/issues/3913
472 \define('MODULE_MASTER_PASSWORD', 0);
a9229942
TD
473 }
474
475 /**
476 * Starts the session system.
477 */
478 protected function initSession()
479 {
480 $factory = new SessionFactory();
481 $factory->load();
482
483 self::$sessionObj = SessionHandler::getInstance();
484 }
485
486 /**
487 * Initialises the language engine.
488 */
489 protected function initLanguage()
490 {
491 if (isset($_GET['l']) && !self::getUser()->userID) {
492 self::getSession()->setLanguageID(\intval($_GET['l']));
493 }
494
495 // set mb settings
496 \mb_internal_encoding('UTF-8');
497 if (\function_exists('mb_regex_encoding')) {
498 \mb_regex_encoding('UTF-8');
499 }
500 \mb_language('uni');
501
502 // get language
503 self::$languageObj = LanguageFactory::getInstance()->getUserLanguage(self::getSession()->getLanguageID());
504 }
505
506 /**
507 * Initialises the template engine.
508 */
509 protected function initTPL()
510 {
511 self::$tplObj = TemplateEngine::getInstance();
512 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
513 $this->assignDefaultTemplateVariables();
514
515 $this->initStyle();
516 }
517
518 /**
519 * Initializes the user's style.
520 */
521 protected function initStyle()
522 {
523 if (isset($_REQUEST['styleID'])) {
524 self::getSession()->setStyleID(\intval($_REQUEST['styleID']));
525 }
526
527 $styleHandler = StyleHandler::getInstance();
528 $styleHandler->changeStyle(self::getSession()->getStyleID());
529 }
530
531 /**
532 * Executes the blacklist.
533 */
534 protected function initBlacklist()
535 {
536 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
537
538 if (\defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES != '') {
539 if (
540 !StringUtil::executeWordFilter(
541 UserUtil::convertIPv6To4(UserUtil::getIpAddress()),
542 BLACKLIST_IP_ADDRESSES
543 )
544 ) {
545 if ($isAjax) {
546 throw new AJAXException(
547 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
548 AJAXException::INSUFFICIENT_PERMISSIONS
549 );
550 } else {
551 throw new PermissionDeniedException();
552 }
553 } elseif (!StringUtil::executeWordFilter(UserUtil::getIpAddress(), BLACKLIST_IP_ADDRESSES)) {
554 if ($isAjax) {
555 throw new AJAXException(
556 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
557 AJAXException::INSUFFICIENT_PERMISSIONS
558 );
559 } else {
560 throw new PermissionDeniedException();
561 }
562 }
563 }
564 if (\defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS != '') {
565 if (!StringUtil::executeWordFilter(UserUtil::getUserAgent(), BLACKLIST_USER_AGENTS)) {
566 if ($isAjax) {
567 throw new AJAXException(
568 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
569 AJAXException::INSUFFICIENT_PERMISSIONS
570 );
571 } else {
572 throw new PermissionDeniedException();
573 }
574 }
575 }
8b73fa91 576
a9229942
TD
577 // handle banned users
578 if (self::getUser()->userID && self::getUser()->banned && !self::getUser()->hasOwnerAccess()) {
579 if ($isAjax) {
580 throw new AJAXException(
581 self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'),
582 AJAXException::INSUFFICIENT_PERMISSIONS
583 );
584 } else {
585 self::$forceLogout = true;
586
587 // remove cookies
588 if (isset($_COOKIE[COOKIE_PREFIX . 'userID'])) {
589 HeaderUtil::setCookie('userID', 0);
590 }
591 if (isset($_COOKIE[COOKIE_PREFIX . 'password'])) {
592 HeaderUtil::setCookie('password', '');
593 }
594
595 throw new NamedUserException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
596 }
597 }
598 }
599
600 /**
601 * Initializes applications.
602 */
603 protected function initApplications()
604 {
605 // step 1) load all applications
606 $loadedApplications = [];
607
608 // register WCF as application
609 self::$applications['wcf'] = ApplicationHandler::getInstance()->getApplicationByID(1);
610
611 if (!\class_exists(WCFACP::class, false)) {
612 static::getTPL()->assign('baseHref', self::$applications['wcf']->getPageURL());
613 }
614
615 // start main application
616 $application = ApplicationHandler::getInstance()->getActiveApplication();
617 if ($application->packageID != 1) {
618 $loadedApplications[] = $this->loadApplication($application);
619
620 // register primary application
621 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
622 self::$applications[$abbreviation] = $application;
623 }
624
625 // start dependent applications
626 $applications = ApplicationHandler::getInstance()->getDependentApplications();
627 foreach ($applications as $application) {
628 if ($application->packageID == 1) {
629 // ignore WCF
630 continue;
631 } elseif ($application->isTainted) {
632 // ignore apps flagged for uninstallation
633 continue;
634 }
635
636 $loadedApplications[] = $this->loadApplication($application, true);
637 }
638
639 // step 2) run each application
640 if (!\class_exists('wcf\system\WCFACP', false)) {
641 /** @var IApplication $application */
642 foreach ($loadedApplications as $application) {
643 $application->__run();
644 }
645
646 /** @deprecated The below variable is deprecated. */
647 self::getTPL()->assign('__sessionKeepAlive', 59 * 60);
648 }
649 }
650
651 /**
652 * Loads an application.
653 *
654 * @param Application $application
655 * @param bool $isDependentApplication
656 * @return IApplication
657 * @throws SystemException
658 */
659 protected function loadApplication(Application $application, $isDependentApplication = false)
660 {
661 $package = PackageCache::getInstance()->getPackage($application->packageID);
662 // package cache might be outdated
663 if ($package === null) {
664 $package = new Package($application->packageID);
665
666 // package cache is outdated, discard cache
667 if ($package->packageID) {
668 PackageEditor::resetCache();
669 } else {
670 // package id is invalid
671 throw new SystemException("application identified by package id '" . $application->packageID . "' is unknown");
672 }
673 }
674
675 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
676 $packageDir = FileUtil::getRealPath(WCF_DIR . $package->packageDir);
677 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
678
679 $className = $abbreviation . '\system\\' . \strtoupper($abbreviation) . 'Core';
680
681 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
682 if (!\class_exists($className)) {
683 // check if both the Core and the app are on the same domain
684 $coreApp = ApplicationHandler::getInstance()->getApplicationByID(1);
685 if ($coreApp->domainName === $application->domainName) {
686 // resolve the relative path and use it to construct the autoload directory
687 $relativePath = FileUtil::getRelativePath($coreApp->domainPath, $application->domainPath);
688 if ($relativePath !== './') {
689 $packageDir = FileUtil::getRealPath(WCF_DIR . $relativePath);
690 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
691
692 if (\class_exists($className)) {
693 // the class can now be found, update the `packageDir` value
694 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
695 }
696 }
697 }
698 }
699
700 if (\class_exists($className) && \is_subclass_of($className, IApplication::class)) {
701 // include config file
702 $configPath = $packageDir . PackageInstallationDispatcher::CONFIG_FILE;
703 if (!\file_exists($configPath)) {
704 Package::writeConfigFile($package->packageID);
705 }
706
707 if (\file_exists($configPath)) {
708 require_once($configPath);
709 } else {
710 throw new SystemException('Unable to load configuration for ' . $package->package);
711 }
712
713 // register template path if not within ACP
714 if (!\class_exists('wcf\system\WCFACP', false)) {
715 // add template path and abbreviation
716 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
717 }
718 EmailTemplateEngine::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
719
720 // init application and assign it as template variable
721 self::$applicationObjects[$application->packageID] = \call_user_func([$className, 'getInstance']);
722 static::getTPL()->assign('__' . $abbreviation, self::$applicationObjects[$application->packageID]);
723 EmailTemplateEngine::getInstance()->assign(
724 '__' . $abbreviation,
725 self::$applicationObjects[$application->packageID]
726 );
727 } else {
728 unset(self::$autoloadDirectories[$abbreviation]);
729 throw new SystemException("Unable to run '" . $package->package . "', '" . $className . "' is missing or does not implement '" . IApplication::class . "'.");
730 }
731
732 // register template path in ACP
733 if (\class_exists('wcf\system\WCFACP', false)) {
734 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
735 } elseif (!$isDependentApplication) {
736 // assign base tag
737 static::getTPL()->assign('baseHref', $application->getPageURL());
738 }
739
740 // register application
741 self::$applications[$abbreviation] = $application;
742
743 return self::$applicationObjects[$application->packageID];
744 }
745
746 /**
747 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
748 *
749 * @param Application $application
750 * @return IApplication
751 */
752 public static function getApplicationObject(Application $application)
753 {
813c41ce 754 return self::$applicationObjects[$application->packageID] ?? null;
a9229942
TD
755 }
756
757 /**
758 * Returns the invoked application.
759 *
760 * @return Application
761 * @since 3.1
762 */
763 public static function getActiveApplication()
764 {
765 return ApplicationHandler::getInstance()->getActiveApplication();
766 }
767
768 /**
769 * Loads an application on runtime, do not use this outside the package installation.
770 *
771 * @param int $packageID
772 */
773 public static function loadRuntimeApplication($packageID)
774 {
775 $package = new Package($packageID);
776 $application = new Application($packageID);
777
778 $abbreviation = Package::getAbbreviation($package->package);
779 $packageDir = FileUtil::getRealPath(WCF_DIR . $package->packageDir);
780 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
781 self::$applications[$abbreviation] = $application;
782 self::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
783 }
784
785 /**
786 * Initializes core object cache.
787 */
788 protected function initCoreObjects()
789 {
790 // ignore core objects if installing WCF
791 if (PACKAGE_ID == 0) {
792 return;
793 }
794
795 self::$coreObjectCache = CoreObjectCacheBuilder::getInstance()->getData();
796 }
797
798 /**
799 * Assigns some default variables to the template engine.
800 */
801 protected function assignDefaultTemplateVariables()
802 {
803 $wcf = $this;
804
805 if (ENABLE_ENTERPRISE_MODE) {
806 $wcf = new TemplateScriptingCore($wcf);
807 }
808
809 self::getTPL()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang', 'csrfToken']);
810 self::getTPL()->assign([
811 '__wcf' => $wcf,
812 '__wcfVersion' => LAST_UPDATE_TIME, // @deprecated 2.1, use LAST_UPDATE_TIME directly
813 ]);
814
815 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
816 // Execute background queue in this request, if it was requested and AJAX isn't used.
817 if (!$isAjax) {
818 if (self::getSession()->getVar('forceBackgroundQueuePerform')) {
819 self::getTPL()->assign([
820 'forceBackgroundQueuePerform' => true,
821 ]);
822
823 self::getSession()->unregister('forceBackgroundQueuePerform');
824 }
825 }
826
827 EmailTemplateEngine::getInstance()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang']);
828 EmailTemplateEngine::getInstance()->assign([
829 '__wcf' => $wcf,
830 ]);
831 }
832
833 /**
834 * Wrapper for the getter methods of this class.
835 *
836 * @param string $name
837 * @return mixed value
838 * @throws SystemException
839 */
840 public function __get($name)
841 {
842 $method = 'get' . \ucfirst($name);
843 if (\method_exists($this, $method)) {
844 return $this->{$method}();
845 }
846
847 throw new SystemException("method '" . $method . "' does not exist in class WCF");
848 }
849
850 /**
851 * Returns true if current application (WCF) is treated as active and was invoked directly.
852 *
853 * @return bool
854 */
855 public function isActiveApplication()
856 {
857 return ApplicationHandler::getInstance()->getActiveApplication()->packageID == 1;
858 }
859
860 /**
861 * Changes the active language.
862 *
863 * @param int $languageID
864 */
865 final public static function setLanguage($languageID)
866 {
867 if (!$languageID || LanguageFactory::getInstance()->getLanguage($languageID) === null) {
868 $languageID = LanguageFactory::getInstance()->getDefaultLanguageID();
869 }
870
871 self::$languageObj = LanguageFactory::getInstance()->getLanguage($languageID);
872
873 // the template engine may not be available yet, usually happens when
874 // changing the user (and thus the language id) during session init
875 if (self::$tplObj !== null) {
876 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
877 EmailTemplateEngine::getInstance()->setLanguageID(self::getLanguage()->languageID);
878 }
879 }
880
881 /**
882 * Includes the required util or exception classes automatically.
883 *
884 * @param string $className
885 * @see spl_autoload_register()
886 */
887 final public static function autoload($className)
888 {
889 $namespaces = \explode('\\', $className);
890 if (\count($namespaces) > 1) {
891 $applicationPrefix = \array_shift($namespaces);
892 if ($applicationPrefix === '') {
893 $applicationPrefix = \array_shift($namespaces);
894 }
895 if (isset(self::$autoloadDirectories[$applicationPrefix])) {
896 $classPath = self::$autoloadDirectories[$applicationPrefix] . \implode('/', $namespaces) . '.class.php';
897
898 // PHP will implicitly check if the file exists when including it, which means that we can save a
899 // redundant syscall/fs access by not checking for existence ourselves. Do not use require_once()!
900 @include_once($classPath);
901 }
902 }
903 }
904
905 /**
906 * @inheritDoc
907 */
908 final public function __call($name, array $arguments)
909 {
910 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
911 if (!\method_exists($this, $name)) {
912 return self::__callStatic($name, $arguments);
913 }
914
915 throw new \BadMethodCallException("Call to undefined method WCF::{$name}().");
916 }
917
918 /**
919 * Returns dynamically loaded core objects.
920 *
921 * @param string $name
922 * @param array $arguments
923 * @return object
924 * @throws SystemException
925 */
926 final public static function __callStatic($name, array $arguments)
927 {
928 $className = \preg_replace('~^get~', '', $name);
929
930 if (isset(self::$coreObject[$className])) {
931 return self::$coreObject[$className];
932 }
933
934 $objectName = self::getCoreObject($className);
935 if ($objectName === null) {
936 throw new SystemException("Core object '" . $className . "' is unknown.");
937 }
938
939 if (\class_exists($objectName)) {
940 if (!\is_subclass_of($objectName, SingletonFactory::class)) {
941 throw new ParentClassException($objectName, SingletonFactory::class);
942 }
943
944 self::$coreObject[$className] = \call_user_func([$objectName, 'getInstance']);
945
946 return self::$coreObject[$className];
947 }
948 }
949
950 /**
951 * Searches for cached core object definition.
952 *
953 * @param string $className
5227ebc7 954 * @return string|null
a9229942
TD
955 */
956 final protected static function getCoreObject($className)
957 {
813c41ce 958 return self::$coreObjectCache[$className] ?? null;
a9229942
TD
959 }
960
961 /**
962 * Returns true if the debug mode is enabled, otherwise false.
963 *
964 * @param bool $ignoreACP
965 * @return bool
966 */
967 public static function debugModeIsEnabled($ignoreACP = false)
968 {
969 // ACP override
970 if (!$ignoreACP && self::$overrideDebugMode) {
971 return true;
972 } elseif (\defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE) {
973 return true;
974 }
975
976 return false;
977 }
978
979 /**
980 * Returns true if benchmarking is enabled, otherwise false.
981 *
982 * @return bool
983 */
984 public static function benchmarkIsEnabled()
985 {
986 // benchmarking is enabled by default
987 if (!\defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK) {
988 return true;
989 }
990
991 return false;
992 }
993
994 /**
995 * Returns domain path for given application.
996 *
997 * @param string $abbreviation
998 * @return string
999 */
1000 public static function getPath($abbreviation = 'wcf')
1001 {
1002 // workaround during WCFSetup
1003 if (!PACKAGE_ID) {
1004 return '../';
1005 }
1006
1007 if (!isset(self::$applications[$abbreviation])) {
1008 $abbreviation = 'wcf';
1009 }
1010
1011 return self::$applications[$abbreviation]->getPageURL();
1012 }
1013
1014 /**
1015 * Returns the domain path for the currently active application,
1016 * used to avoid CORS requests.
1017 *
1018 * @return string
1019 */
1020 public static function getActivePath()
1021 {
1022 if (!PACKAGE_ID) {
1023 return self::getPath();
1024 }
1025
1026 // We cannot rely on the ApplicationHandler's `getActiveApplication()` because
1027 // it uses the requested controller to determine the namespace. However, starting
1028 // with WoltLab Suite 5.2, system pages can be virtually assigned to a different
1029 // app, resolving against the target app without changing the namespace.
1030 return self::getPath(ApplicationHandler::getInstance()->getAbbreviation(PACKAGE_ID));
1031 }
1032
1033 /**
1034 * Returns a fully qualified anchor for current page.
1035 *
1036 * @param string $fragment
1037 * @return string
1038 */
1039 public function getAnchor($fragment)
1040 {
1041 return StringUtil::encodeHTML(self::getRequestURI() . '#' . $fragment);
1042 }
1043
1044 /**
1045 * Returns the currently active page or null if unknown.
1046 *
1047 * @return Page|null
1048 */
1049 public static function getActivePage()
1050 {
1051 if (self::getActiveRequest() === null) {
c0b28aa2 1052 return null;
a9229942
TD
1053 }
1054
1055 if (self::getActiveRequest()->getClassName() === CmsPage::class) {
1056 $metaData = self::getActiveRequest()->getMetaData();
1057 if (isset($metaData['cms'])) {
1058 return PageCache::getInstance()->getPage($metaData['cms']['pageID']);
1059 }
1060
c0b28aa2 1061 return null;
a9229942
TD
1062 }
1063
1064 return PageCache::getInstance()->getPageByController(self::getActiveRequest()->getClassName());
1065 }
1066
1067 /**
1068 * Returns the currently active request.
1069 *
1070 * @return Request
1071 */
1072 public static function getActiveRequest()
1073 {
1074 return RequestHandler::getInstance()->getActiveRequest();
1075 }
1076
1077 /**
1078 * Returns the URI of the current page.
1079 *
1080 * @return string
1081 */
1082 public static function getRequestURI()
1083 {
1084 return \preg_replace(
1085 '~^(https?://[^/]+)(?:/.*)?$~',
1086 '$1',
1087 self::getTPL()->get('baseHref')
1088 ) . $_SERVER['REQUEST_URI'];
1089 }
1090
1091 /**
1092 * Resets Zend Opcache cache if installed and enabled.
1093 *
1094 * @param string $script
1095 */
1096 public static function resetZendOpcache($script = '')
1097 {
1098 if (self::$zendOpcacheEnabled === null) {
1099 self::$zendOpcacheEnabled = false;
1100
1101 if (\extension_loaded('Zend Opcache') && @\ini_get('opcache.enable')) {
1102 self::$zendOpcacheEnabled = true;
1103 }
1104 }
1105
1106 if (self::$zendOpcacheEnabled) {
1107 if (empty($script)) {
1108 \opcache_reset();
1109 } else {
1110 \opcache_invalidate($script, true);
1111 }
1112 }
1113 }
1114
1115 /**
1116 * Returns style handler.
1117 *
1118 * @return StyleHandler
1119 */
1120 public function getStyleHandler()
1121 {
1122 return StyleHandler::getInstance();
1123 }
1124
1125 /**
1126 * Returns box handler.
1127 *
1128 * @return BoxHandler
1129 * @since 3.0
1130 */
1131 public function getBoxHandler()
1132 {
1133 return BoxHandler::getInstance();
1134 }
1135
1136 /**
1137 * Returns number of available updates.
1138 *
1139 * @return int
1140 */
1141 public function getAvailableUpdates()
1142 {
1143 $data = PackageUpdateCacheBuilder::getInstance()->getData();
1144
1145 return $data['updates'];
1146 }
1147
1148 /**
1149 * Returns a 8 character prefix for editor autosave.
1150 *
1151 * @return string
1152 */
1153 public function getAutosavePrefix()
1154 {
1155 return \substr(\sha1(\preg_replace('~^https~', 'http', self::getPath())), 0, 8);
1156 }
1157
1158 /**
1159 * Returns the favicon URL or a base64 encoded image.
1160 *
1161 * @return string
1162 */
1163 public function getFavicon()
1164 {
1165 $activeApplication = ApplicationHandler::getInstance()->getActiveApplication();
1166 $wcf = ApplicationHandler::getInstance()->getWCF();
1167 $favicon = StyleHandler::getInstance()->getStyle()->getRelativeFavicon();
1168
1169 if ($activeApplication->domainName !== $wcf->domainName) {
1170 if (\file_exists(WCF_DIR . $favicon)) {
1171 $favicon = \file_get_contents(WCF_DIR . $favicon);
1172
1173 return 'data:image/x-icon;base64,' . \base64_encode($favicon);
1174 }
1175 }
1176
1177 return self::getPath() . $favicon;
1178 }
1179
1180 /**
1181 * Returns true if the desktop notifications should be enabled.
1182 *
1183 * @return bool
1184 */
1185 public function useDesktopNotifications()
1186 {
1187 if (!ENABLE_DESKTOP_NOTIFICATIONS) {
1188 return false;
1189 } elseif (ApplicationHandler::getInstance()->isMultiDomainSetup()) {
1190 $application = ApplicationHandler::getInstance()->getApplicationByID(DESKTOP_NOTIFICATION_PACKAGE_ID);
1191 // mismatch, default to Core
1192 if ($application === null) {
1193 $application = ApplicationHandler::getInstance()->getApplicationByID(1);
1194 }
1195
1196 $currentApplication = ApplicationHandler::getInstance()->getActiveApplication();
1197 if ($currentApplication->domainName != $application->domainName) {
1198 // different domain
1199 return false;
1200 }
1201 }
1202
1203 return true;
1204 }
1205
1206 /**
1207 * Returns true if currently active request represents the landing page.
1208 *
1209 * @return bool
1210 */
1211 public static function isLandingPage()
1212 {
1213 if (self::getActiveRequest() === null) {
1214 return false;
1215 }
1216
1217 return self::getActiveRequest()->isLandingPage();
1218 }
1219
1220 /**
1221 * Returns true if the given API version is currently supported.
1222 *
1223 * @param int $apiVersion
1224 * @return bool
1225 * @deprecated 5.2
1226 */
1227 public static function isSupportedApiVersion($apiVersion)
1228 {
1229 return ($apiVersion == WSC_API_VERSION) || \in_array($apiVersion, self::$supportedLegacyApiVersions);
1230 }
1231
1232 /**
1233 * Returns the list of supported legacy API versions.
1234 *
1235 * @return int[]
1236 * @deprecated 5.2
1237 */
1238 public static function getSupportedLegacyApiVersions()
1239 {
1240 return self::$supportedLegacyApiVersions;
1241 }
1242
1243 /**
1244 * Initialises the cronjobs.
1245 */
1246 protected function initCronjobs()
1247 {
1248 if (PACKAGE_ID) {
1249 self::getTPL()->assign(
1250 'executeCronjobs',
1251 CronjobScheduler::getInstance()->getNextExec() < TIME_NOW && \defined('OFFLINE') && !OFFLINE
1252 );
1253 }
1254 }
1255
1256 /**
1257 * Checks recursively that the most important system files of `com.woltlab.wcf` are writable.
1258 *
1259 * @throws \RuntimeException if any relevant file or directory is not writable
1260 */
1261 public static function checkWritability()
1262 {
1263 $nonWritablePaths = [];
1264
1265 $nonRecursiveDirectories = [
1266 '',
1267 'acp/',
1268 'tmp/',
1269 ];
1270 foreach ($nonRecursiveDirectories as $directory) {
1271 $path = WCF_DIR . $directory;
1272 if ($path === 'tmp/' && !\is_dir($path)) {
1273 continue;
1274 }
1275
1276 if (!\is_writable($path)) {
1277 $nonWritablePaths[] = FileUtil::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1278 continue;
1279 }
1280
1281 DirectoryUtil::getInstance($path, false)
1282 ->executeCallback(static function ($file, \SplFileInfo $fileInfo) use (&$nonWritablePaths) {
1283 if ($fileInfo instanceof \DirectoryIterator) {
1284 if (!\is_writable($fileInfo->getPath())) {
1285 $nonWritablePaths[] = FileUtil::getRelativePath(
1286 $_SERVER['DOCUMENT_ROOT'],
1287 $fileInfo->getPath()
1288 );
1289 }
1290 } elseif (!\is_writable($fileInfo->getRealPath())) {
1291 $nonWritablePaths[] = FileUtil::getRelativePath(
1292 $_SERVER['DOCUMENT_ROOT'],
1293 $fileInfo->getPath()
1294 ) . $fileInfo->getFilename();
1295 }
1296 });
1297 }
1298
1299 $recursiveDirectories = [
1300 'acp/js/',
1301 'acp/style/',
1302 'acp/templates/',
1303 'acp/uninstall/',
1304 'js/',
1305 'lib/',
1306 'log/',
1307 'style/',
1308 'templates/',
1309 ];
1310 foreach ($recursiveDirectories as $directory) {
1311 $path = WCF_DIR . $directory;
1312
1313 if (!\is_writable($path)) {
1314 $nonWritablePaths[] = FileUtil::getRelativePath($_SERVER['DOCUMENT_ROOT'], $path);
1315 continue;
1316 }
1317
1318 DirectoryUtil::getInstance($path)
1319 ->executeCallback(static function ($file, \SplFileInfo $fileInfo) use (&$nonWritablePaths) {
1320 if ($fileInfo instanceof \DirectoryIterator) {
1321 if (!\is_writable($fileInfo->getPath())) {
1322 $nonWritablePaths[] = FileUtil::getRelativePath(
1323 $_SERVER['DOCUMENT_ROOT'],
1324 $fileInfo->getPath()
1325 );
1326 }
1327 } elseif (!\is_writable($fileInfo->getRealPath())) {
1328 $nonWritablePaths[] = FileUtil::getRelativePath(
1329 $_SERVER['DOCUMENT_ROOT'],
1330 $fileInfo->getPath()
1331 ) . $fileInfo->getFilename();
1332 }
1333 });
1334 }
1335
1336 if (!empty($nonWritablePaths)) {
1337 $maxPaths = 10;
1338 throw new \RuntimeException('The following paths are not writable: ' . \implode(
1339 ',',
1340 \array_slice(
1341 $nonWritablePaths,
1342 0,
1343 $maxPaths
1344 )
1345 ) . (\count($nonWritablePaths) > $maxPaths ? ',' . StringUtil::HELLIP : ''));
1346 }
1347 }
d335fa16 1348}