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