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