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