Apply PSR-12 code style (#3886)
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / lib / system / WCF.class.php
1 <?php
2
3 namespace wcf\system;
4
5 use wcf\data\application\Application;
6 use wcf\data\option\OptionEditor;
7 use wcf\data\package\Package;
8 use wcf\data\package\PackageCache;
9 use wcf\data\package\PackageEditor;
10 use wcf\data\page\Page;
11 use wcf\data\page\PageCache;
12 use wcf\page\CmsPage;
13 use wcf\system\application\ApplicationHandler;
14 use wcf\system\application\IApplication;
15 use wcf\system\box\BoxHandler;
16 use wcf\system\cache\builder\CoreObjectCacheBuilder;
17 use wcf\system\cache\builder\PackageUpdateCacheBuilder;
18 use wcf\system\cronjob\CronjobScheduler;
19 use wcf\system\database\MySQLDatabase;
20 use wcf\system\event\EventHandler;
21 use wcf\system\exception\AJAXException;
22 use wcf\system\exception\ErrorException;
23 use wcf\system\exception\IPrintableException;
24 use wcf\system\exception\NamedUserException;
25 use wcf\system\exception\ParentClassException;
26 use wcf\system\exception\PermissionDeniedException;
27 use wcf\system\exception\SystemException;
28 use wcf\system\language\LanguageFactory;
29 use wcf\system\package\PackageInstallationDispatcher;
30 use wcf\system\registry\RegistryHandler;
31 use wcf\system\request\Request;
32 use wcf\system\request\RequestHandler;
33 use wcf\system\session\SessionFactory;
34 use wcf\system\session\SessionHandler;
35 use wcf\system\style\StyleHandler;
36 use wcf\system\template\EmailTemplateEngine;
37 use wcf\system\template\TemplateEngine;
38 use wcf\system\user\storage\UserStorageHandler;
39 use wcf\util\DirectoryUtil;
40 use wcf\util\FileUtil;
41 use wcf\util\HeaderUtil;
42 use wcf\util\StringUtil;
43 use wcf\util\UserUtil;
44
45 // phpcs:disable PSR1.Files.SideEffects
46
47 // try to set a time-limit to infinite
48 @\set_time_limit(0);
49
50 // fix timezone warning issue
51 if (!@\ini_get('date.timezone')) {
52 @\date_default_timezone_set('Europe/London');
53 }
54
55 // define current woltlab suite version
56 \define('WCF_VERSION', '5.3.2');
57
58 // define current API version
59 // @deprecated 5.2
60 \define('WSC_API_VERSION', 2019);
61
62 // define current unix timestamp
63 \define('TIME_NOW', \time());
64
65 // wcf imports
66 if (!\defined('NO_IMPORTS')) {
67 require_once(WCF_DIR . 'lib/core.functions.php');
68 require_once(WCF_DIR . 'lib/system/api/autoload.php');
69 }
70
71 /**
72 * WCF is the central class for the WoltLab Suite Core.
73 * It holds the database connection, access to template and language engine.
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
79 */
80 class 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 *
287 * @param \Exception $e
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()
369 {
370 // The attachment module is always enabled since 5.2.
371 // https://github.com/WoltLab/WCF/issues/2531
372 \define('MODULE_ATTACHMENT', 1);
373
374 // Users cannot react to their own content since 5.2.
375 // https://github.com/WoltLab/WCF/issues/2975
376 \define('LIKE_ALLOW_FOR_OWN_CONTENT', 0);
377 \define('LIKE_ENABLE_DISLIKE', 0);
378
379 // Thumbnails for attachments are already enabled since 5.3.
380 // https://github.com/WoltLab/WCF/pull/3444
381 \define('ATTACHMENT_ENABLE_THUMBNAILS', 1);
382
383 // User markings are always applied in sidebars since 5.3.
384 // https://github.com/WoltLab/WCF/issues/3330
385 \define('MESSAGE_SIDEBAR_ENABLE_USER_ONLINE_MARKING', 1);
386
387 // Password strength configuration is deprecated since 5.3.
388 \define('REGISTER_ENABLE_PASSWORD_SECURITY_CHECK', 0);
389 \define('REGISTER_PASSWORD_MIN_LENGTH', 0);
390 \define('REGISTER_PASSWORD_MUST_CONTAIN_LOWER_CASE', 8);
391 \define('REGISTER_PASSWORD_MUST_CONTAIN_UPPER_CASE', 0);
392 \define('REGISTER_PASSWORD_MUST_CONTAIN_DIGIT', 0);
393 \define('REGISTER_PASSWORD_MUST_CONTAIN_SPECIAL_CHAR', 0);
394
395 // rel=nofollow is always applied to external link since 5.3
396 // https://github.com/WoltLab/WCF/issues/3339
397 \define('EXTERNAL_LINK_REL_NOFOLLOW', 1);
398
399 // Session validation is removed since 5.4.
400 // https://github.com/WoltLab/WCF/pull/3583
401 \define('SESSION_VALIDATE_IP_ADDRESS', 0);
402 \define('SESSION_VALIDATE_USER_AGENT', 0);
403
404 // Virtual sessions no longer exist since 5.4.
405 \define('SESSION_ENABLE_VIRTUALIZATION', 1);
406
407 // The session timeout is fully managed since 5.4.
408 \define('SESSION_TIMEOUT', 3600);
409
410 // gzip compression is removed in 5.4.
411 // https://github.com/WoltLab/WCF/issues/3634
412 \define('HTTP_ENABLE_GZIP', 0);
413
414 // Meta keywords are no longer used since 5.4.
415 // https://github.com/WoltLab/WCF/issues/3561
416 \define('META_KEYWORDS', '');
417
418 // The admin notification is redundant and removed in 5.4.
419 // https://github.com/WoltLab/WCF/issues/3674
420 \define('REGISTER_ADMIN_NOTIFICATION', 0);
421
422 $filename = WCF_DIR . 'options.inc.php';
423
424 // create options file if doesn't exist
425 if (!\file_exists($filename) || \filemtime($filename) <= 1) {
426 OptionEditor::rebuild();
427 }
428 require($filename);
429
430 // check if option file is complete and writable
431 if (PACKAGE_ID) {
432 if (!\is_writable($filename)) {
433 FileUtil::makeWritable($filename);
434
435 if (!\is_writable($filename)) {
436 throw new SystemException("The option file '" . $filename . "' is not writable.");
437 }
438 }
439
440 // check if a previous write operation was incomplete and force rebuilding
441 if (!\defined('WCF_OPTION_INC_PHP_SUCCESS')) {
442 OptionEditor::rebuild();
443
444 require($filename);
445 }
446
447 if (ENABLE_DEBUG_MODE) {
448 self::$dbObj->enableDebugMode();
449 }
450 }
451 }
452
453 /**
454 * Starts the session system.
455 */
456 protected function initSession()
457 {
458 $factory = new SessionFactory();
459 $factory->load();
460
461 self::$sessionObj = SessionHandler::getInstance();
462 }
463
464 /**
465 * Initialises the language engine.
466 */
467 protected function initLanguage()
468 {
469 if (isset($_GET['l']) && !self::getUser()->userID) {
470 self::getSession()->setLanguageID(\intval($_GET['l']));
471 }
472
473 // set mb settings
474 \mb_internal_encoding('UTF-8');
475 if (\function_exists('mb_regex_encoding')) {
476 \mb_regex_encoding('UTF-8');
477 }
478 \mb_language('uni');
479
480 // get language
481 self::$languageObj = LanguageFactory::getInstance()->getUserLanguage(self::getSession()->getLanguageID());
482 }
483
484 /**
485 * Initialises the template engine.
486 */
487 protected function initTPL()
488 {
489 self::$tplObj = TemplateEngine::getInstance();
490 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
491 $this->assignDefaultTemplateVariables();
492
493 $this->initStyle();
494 }
495
496 /**
497 * Initializes the user's style.
498 */
499 protected function initStyle()
500 {
501 if (isset($_REQUEST['styleID'])) {
502 self::getSession()->setStyleID(\intval($_REQUEST['styleID']));
503 }
504
505 $styleHandler = StyleHandler::getInstance();
506 $styleHandler->changeStyle(self::getSession()->getStyleID());
507 }
508
509 /**
510 * Executes the blacklist.
511 */
512 protected function initBlacklist()
513 {
514 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
515
516 if (\defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES != '') {
517 if (
518 !StringUtil::executeWordFilter(
519 UserUtil::convertIPv6To4(UserUtil::getIpAddress()),
520 BLACKLIST_IP_ADDRESSES
521 )
522 ) {
523 if ($isAjax) {
524 throw new AJAXException(
525 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
526 AJAXException::INSUFFICIENT_PERMISSIONS
527 );
528 } else {
529 throw new PermissionDeniedException();
530 }
531 } elseif (!StringUtil::executeWordFilter(UserUtil::getIpAddress(), BLACKLIST_IP_ADDRESSES)) {
532 if ($isAjax) {
533 throw new AJAXException(
534 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
535 AJAXException::INSUFFICIENT_PERMISSIONS
536 );
537 } else {
538 throw new PermissionDeniedException();
539 }
540 }
541 }
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 }
554 if (\defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES != '') {
555 if (!StringUtil::executeWordFilter(@\gethostbyaddr(UserUtil::getIpAddress()), BLACKLIST_HOSTNAMES)) {
556 if ($isAjax) {
557 throw new AJAXException(
558 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
559 AJAXException::INSUFFICIENT_PERMISSIONS
560 );
561 } else {
562 throw new PermissionDeniedException();
563 }
564 }
565 }
566
567 // handle banned users
568 if (self::getUser()->userID && self::getUser()->banned && !self::getUser()->hasOwnerAccess()) {
569 if ($isAjax) {
570 throw new AJAXException(
571 self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'),
572 AJAXException::INSUFFICIENT_PERMISSIONS
573 );
574 } else {
575 self::$forceLogout = true;
576
577 // remove cookies
578 if (isset($_COOKIE[COOKIE_PREFIX . 'userID'])) {
579 HeaderUtil::setCookie('userID', 0);
580 }
581 if (isset($_COOKIE[COOKIE_PREFIX . 'password'])) {
582 HeaderUtil::setCookie('password', '');
583 }
584
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 {
744 if (isset(self::$applicationObjects[$application->packageID])) {
745 return self::$applicationObjects[$application->packageID];
746 }
747 }
748
749 /**
750 * Returns the invoked application.
751 *
752 * @return Application
753 * @since 3.1
754 */
755 public static function getActiveApplication()
756 {
757 return ApplicationHandler::getInstance()->getActiveApplication();
758 }
759
760 /**
761 * Loads an application on runtime, do not use this outside the package installation.
762 *
763 * @param int $packageID
764 */
765 public static function loadRuntimeApplication($packageID)
766 {
767 $package = new Package($packageID);
768 $application = new Application($packageID);
769
770 $abbreviation = Package::getAbbreviation($package->package);
771 $packageDir = FileUtil::getRealPath(WCF_DIR . $package->packageDir);
772 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
773 self::$applications[$abbreviation] = $application;
774 self::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
775 }
776
777 /**
778 * Initializes core object cache.
779 */
780 protected function initCoreObjects()
781 {
782 // ignore core objects if installing WCF
783 if (PACKAGE_ID == 0) {
784 return;
785 }
786
787 self::$coreObjectCache = CoreObjectCacheBuilder::getInstance()->getData();
788 }
789
790 /**
791 * Assigns some default variables to the template engine.
792 */
793 protected function assignDefaultTemplateVariables()
794 {
795 $wcf = $this;
796
797 if (ENABLE_ENTERPRISE_MODE) {
798 $wcf = new TemplateScriptingCore($wcf);
799 }
800
801 self::getTPL()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang', 'csrfToken']);
802 self::getTPL()->assign([
803 '__wcf' => $wcf,
804 '__wcfVersion' => LAST_UPDATE_TIME, // @deprecated 2.1, use LAST_UPDATE_TIME directly
805 ]);
806
807 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
808 // Execute background queue in this request, if it was requested and AJAX isn't used.
809 if (!$isAjax) {
810 if (self::getSession()->getVar('forceBackgroundQueuePerform')) {
811 self::getTPL()->assign([
812 'forceBackgroundQueuePerform' => true,
813 ]);
814
815 self::getSession()->unregister('forceBackgroundQueuePerform');
816 }
817 }
818
819 EmailTemplateEngine::getInstance()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang']);
820 EmailTemplateEngine::getInstance()->assign([
821 '__wcf' => $wcf,
822 ]);
823 }
824
825 /**
826 * Wrapper for the getter methods of this class.
827 *
828 * @param string $name
829 * @return mixed value
830 * @throws SystemException
831 */
832 public function __get($name)
833 {
834 $method = 'get' . \ucfirst($name);
835 if (\method_exists($this, $method)) {
836 return $this->{$method}();
837 }
838
839 throw new SystemException("method '" . $method . "' does not exist in class WCF");
840 }
841
842 /**
843 * Returns true if current application (WCF) is treated as active and was invoked directly.
844 *
845 * @return bool
846 */
847 public function isActiveApplication()
848 {
849 return ApplicationHandler::getInstance()->getActiveApplication()->packageID == 1;
850 }
851
852 /**
853 * Changes the active language.
854 *
855 * @param int $languageID
856 */
857 final public static function setLanguage($languageID)
858 {
859 if (!$languageID || LanguageFactory::getInstance()->getLanguage($languageID) === null) {
860 $languageID = LanguageFactory::getInstance()->getDefaultLanguageID();
861 }
862
863 self::$languageObj = LanguageFactory::getInstance()->getLanguage($languageID);
864
865 // the template engine may not be available yet, usually happens when
866 // changing the user (and thus the language id) during session init
867 if (self::$tplObj !== null) {
868 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
869 EmailTemplateEngine::getInstance()->setLanguageID(self::getLanguage()->languageID);
870 }
871 }
872
873 /**
874 * Includes the required util or exception classes automatically.
875 *
876 * @param string $className
877 * @see spl_autoload_register()
878 */
879 final public static function autoload($className)
880 {
881 $namespaces = \explode('\\', $className);
882 if (\count($namespaces) > 1) {
883 $applicationPrefix = \array_shift($namespaces);
884 if ($applicationPrefix === '') {
885 $applicationPrefix = \array_shift($namespaces);
886 }
887 if (isset(self::$autoloadDirectories[$applicationPrefix])) {
888 $classPath = self::$autoloadDirectories[$applicationPrefix] . \implode('/', $namespaces) . '.class.php';
889
890 // PHP will implicitly check if the file exists when including it, which means that we can save a
891 // redundant syscall/fs access by not checking for existence ourselves. Do not use require_once()!
892 @include_once($classPath);
893 }
894 }
895 }
896
897 /**
898 * @inheritDoc
899 */
900 final public function __call($name, array $arguments)
901 {
902 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
903 if (!\method_exists($this, $name)) {
904 return self::__callStatic($name, $arguments);
905 }
906
907 throw new \BadMethodCallException("Call to undefined method WCF::{$name}().");
908 }
909
910 /**
911 * Returns dynamically loaded core objects.
912 *
913 * @param string $name
914 * @param array $arguments
915 * @return object
916 * @throws SystemException
917 */
918 final public static function __callStatic($name, array $arguments)
919 {
920 $className = \preg_replace('~^get~', '', $name);
921
922 if (isset(self::$coreObject[$className])) {
923 return self::$coreObject[$className];
924 }
925
926 $objectName = self::getCoreObject($className);
927 if ($objectName === null) {
928 throw new SystemException("Core object '" . $className . "' is unknown.");
929 }
930
931 if (\class_exists($objectName)) {
932 if (!\is_subclass_of($objectName, SingletonFactory::class)) {
933 throw new ParentClassException($objectName, SingletonFactory::class);
934 }
935
936 self::$coreObject[$className] = \call_user_func([$objectName, 'getInstance']);
937
938 return self::$coreObject[$className];
939 }
940 }
941
942 /**
943 * Searches for cached core object definition.
944 *
945 * @param string $className
946 * @return string
947 */
948 final protected static function getCoreObject($className)
949 {
950 if (isset(self::$coreObjectCache[$className])) {
951 return self::$coreObjectCache[$className];
952 }
953 }
954
955 /**
956 * Returns true if the debug mode is enabled, otherwise false.
957 *
958 * @param bool $ignoreACP
959 * @return bool
960 */
961 public static function debugModeIsEnabled($ignoreACP = false)
962 {
963 // ACP override
964 if (!$ignoreACP && self::$overrideDebugMode) {
965 return true;
966 } elseif (\defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE) {
967 return true;
968 }
969
970 return false;
971 }
972
973 /**
974 * Returns true if benchmarking is enabled, otherwise false.
975 *
976 * @return bool
977 */
978 public static function benchmarkIsEnabled()
979 {
980 // benchmarking is enabled by default
981 if (!\defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK) {
982 return true;
983 }
984
985 return false;
986 }
987
988 /**
989 * Returns domain path for given application.
990 *
991 * @param string $abbreviation
992 * @return string
993 */
994 public static function getPath($abbreviation = 'wcf')
995 {
996 // workaround during WCFSetup
997 if (!PACKAGE_ID) {
998 return '../';
999 }
1000
1001 if (!isset(self::$applications[$abbreviation])) {
1002 $abbreviation = 'wcf';
1003 }
1004
1005 return self::$applications[$abbreviation]->getPageURL();
1006 }
1007
1008 /**
1009 * Returns the domain path for the currently active application,
1010 * used to avoid CORS requests.
1011 *
1012 * @return string
1013 */
1014 public static function getActivePath()
1015 {
1016 if (!PACKAGE_ID) {
1017 return self::getPath();
1018 }
1019
1020 // We cannot rely on the ApplicationHandler's `getActiveApplication()` because
1021 // it uses the requested controller to determine the namespace. However, starting
1022 // with WoltLab Suite 5.2, system pages can be virtually assigned to a different
1023 // app, resolving against the target app without changing the namespace.
1024 return self::getPath(ApplicationHandler::getInstance()->getAbbreviation(PACKAGE_ID));
1025 }
1026
1027 /**
1028 * Returns a fully qualified anchor for current page.
1029 *
1030 * @param string $fragment
1031 * @return string
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) {
1046 return;
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
1055 return;
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 }
1342 }