Merge branch '5.3'
[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.4.0 Alpha 1');
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 // The hostname blocklist was removed in 5.4.
423 // https://github.com/WoltLab/WCF/issues/3909
424 \define('BLACKLIST_HOSTNAMES', '');
425
426 // Cover photos are always enabled since 5.4.
427 // https://github.com/WoltLab/WCF/issues/3902
428 \define('MODULE_USER_COVER_PHOTO', 1);
429
430 $filename = WCF_DIR . 'options.inc.php';
431
432 // create options file if doesn't exist
433 if (!\file_exists($filename) || \filemtime($filename) <= 1) {
434 OptionEditor::rebuild();
435 }
436 require($filename);
437
438 // check if option file is complete and writable
439 if (PACKAGE_ID) {
440 if (!\is_writable($filename)) {
441 FileUtil::makeWritable($filename);
442
443 if (!\is_writable($filename)) {
444 throw new SystemException("The option file '" . $filename . "' is not writable.");
445 }
446 }
447
448 // check if a previous write operation was incomplete and force rebuilding
449 if (!\defined('WCF_OPTION_INC_PHP_SUCCESS')) {
450 OptionEditor::rebuild();
451
452 require($filename);
453 }
454
455 if (ENABLE_DEBUG_MODE) {
456 self::$dbObj->enableDebugMode();
457 }
458 }
459 }
460
461 /**
462 * Starts the session system.
463 */
464 protected function initSession()
465 {
466 $factory = new SessionFactory();
467 $factory->load();
468
469 self::$sessionObj = SessionHandler::getInstance();
470 }
471
472 /**
473 * Initialises the language engine.
474 */
475 protected function initLanguage()
476 {
477 if (isset($_GET['l']) && !self::getUser()->userID) {
478 self::getSession()->setLanguageID(\intval($_GET['l']));
479 }
480
481 // set mb settings
482 \mb_internal_encoding('UTF-8');
483 if (\function_exists('mb_regex_encoding')) {
484 \mb_regex_encoding('UTF-8');
485 }
486 \mb_language('uni');
487
488 // get language
489 self::$languageObj = LanguageFactory::getInstance()->getUserLanguage(self::getSession()->getLanguageID());
490 }
491
492 /**
493 * Initialises the template engine.
494 */
495 protected function initTPL()
496 {
497 self::$tplObj = TemplateEngine::getInstance();
498 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
499 $this->assignDefaultTemplateVariables();
500
501 $this->initStyle();
502 }
503
504 /**
505 * Initializes the user's style.
506 */
507 protected function initStyle()
508 {
509 if (isset($_REQUEST['styleID'])) {
510 self::getSession()->setStyleID(\intval($_REQUEST['styleID']));
511 }
512
513 $styleHandler = StyleHandler::getInstance();
514 $styleHandler->changeStyle(self::getSession()->getStyleID());
515 }
516
517 /**
518 * Executes the blacklist.
519 */
520 protected function initBlacklist()
521 {
522 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
523
524 if (\defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES != '') {
525 if (
526 !StringUtil::executeWordFilter(
527 UserUtil::convertIPv6To4(UserUtil::getIpAddress()),
528 BLACKLIST_IP_ADDRESSES
529 )
530 ) {
531 if ($isAjax) {
532 throw new AJAXException(
533 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
534 AJAXException::INSUFFICIENT_PERMISSIONS
535 );
536 } else {
537 throw new PermissionDeniedException();
538 }
539 } elseif (!StringUtil::executeWordFilter(UserUtil::getIpAddress(), BLACKLIST_IP_ADDRESSES)) {
540 if ($isAjax) {
541 throw new AJAXException(
542 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
543 AJAXException::INSUFFICIENT_PERMISSIONS
544 );
545 } else {
546 throw new PermissionDeniedException();
547 }
548 }
549 }
550 if (\defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS != '') {
551 if (!StringUtil::executeWordFilter(UserUtil::getUserAgent(), BLACKLIST_USER_AGENTS)) {
552 if ($isAjax) {
553 throw new AJAXException(
554 self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'),
555 AJAXException::INSUFFICIENT_PERMISSIONS
556 );
557 } else {
558 throw new PermissionDeniedException();
559 }
560 }
561 }
562
563 // handle banned users
564 if (self::getUser()->userID && self::getUser()->banned && !self::getUser()->hasOwnerAccess()) {
565 if ($isAjax) {
566 throw new AJAXException(
567 self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'),
568 AJAXException::INSUFFICIENT_PERMISSIONS
569 );
570 } else {
571 self::$forceLogout = true;
572
573 // remove cookies
574 if (isset($_COOKIE[COOKIE_PREFIX . 'userID'])) {
575 HeaderUtil::setCookie('userID', 0);
576 }
577 if (isset($_COOKIE[COOKIE_PREFIX . 'password'])) {
578 HeaderUtil::setCookie('password', '');
579 }
580
581 throw new NamedUserException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
582 }
583 }
584 }
585
586 /**
587 * Initializes applications.
588 */
589 protected function initApplications()
590 {
591 // step 1) load all applications
592 $loadedApplications = [];
593
594 // register WCF as application
595 self::$applications['wcf'] = ApplicationHandler::getInstance()->getApplicationByID(1);
596
597 if (!\class_exists(WCFACP::class, false)) {
598 static::getTPL()->assign('baseHref', self::$applications['wcf']->getPageURL());
599 }
600
601 // start main application
602 $application = ApplicationHandler::getInstance()->getActiveApplication();
603 if ($application->packageID != 1) {
604 $loadedApplications[] = $this->loadApplication($application);
605
606 // register primary application
607 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
608 self::$applications[$abbreviation] = $application;
609 }
610
611 // start dependent applications
612 $applications = ApplicationHandler::getInstance()->getDependentApplications();
613 foreach ($applications as $application) {
614 if ($application->packageID == 1) {
615 // ignore WCF
616 continue;
617 } elseif ($application->isTainted) {
618 // ignore apps flagged for uninstallation
619 continue;
620 }
621
622 $loadedApplications[] = $this->loadApplication($application, true);
623 }
624
625 // step 2) run each application
626 if (!\class_exists('wcf\system\WCFACP', false)) {
627 /** @var IApplication $application */
628 foreach ($loadedApplications as $application) {
629 $application->__run();
630 }
631
632 /** @deprecated The below variable is deprecated. */
633 self::getTPL()->assign('__sessionKeepAlive', 59 * 60);
634 }
635 }
636
637 /**
638 * Loads an application.
639 *
640 * @param Application $application
641 * @param bool $isDependentApplication
642 * @return IApplication
643 * @throws SystemException
644 */
645 protected function loadApplication(Application $application, $isDependentApplication = false)
646 {
647 $package = PackageCache::getInstance()->getPackage($application->packageID);
648 // package cache might be outdated
649 if ($package === null) {
650 $package = new Package($application->packageID);
651
652 // package cache is outdated, discard cache
653 if ($package->packageID) {
654 PackageEditor::resetCache();
655 } else {
656 // package id is invalid
657 throw new SystemException("application identified by package id '" . $application->packageID . "' is unknown");
658 }
659 }
660
661 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
662 $packageDir = FileUtil::getRealPath(WCF_DIR . $package->packageDir);
663 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
664
665 $className = $abbreviation . '\system\\' . \strtoupper($abbreviation) . 'Core';
666
667 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
668 if (!\class_exists($className)) {
669 // check if both the Core and the app are on the same domain
670 $coreApp = ApplicationHandler::getInstance()->getApplicationByID(1);
671 if ($coreApp->domainName === $application->domainName) {
672 // resolve the relative path and use it to construct the autoload directory
673 $relativePath = FileUtil::getRelativePath($coreApp->domainPath, $application->domainPath);
674 if ($relativePath !== './') {
675 $packageDir = FileUtil::getRealPath(WCF_DIR . $relativePath);
676 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
677
678 if (\class_exists($className)) {
679 // the class can now be found, update the `packageDir` value
680 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
681 }
682 }
683 }
684 }
685
686 if (\class_exists($className) && \is_subclass_of($className, IApplication::class)) {
687 // include config file
688 $configPath = $packageDir . PackageInstallationDispatcher::CONFIG_FILE;
689 if (!\file_exists($configPath)) {
690 Package::writeConfigFile($package->packageID);
691 }
692
693 if (\file_exists($configPath)) {
694 require_once($configPath);
695 } else {
696 throw new SystemException('Unable to load configuration for ' . $package->package);
697 }
698
699 // register template path if not within ACP
700 if (!\class_exists('wcf\system\WCFACP', false)) {
701 // add template path and abbreviation
702 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
703 }
704 EmailTemplateEngine::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
705
706 // init application and assign it as template variable
707 self::$applicationObjects[$application->packageID] = \call_user_func([$className, 'getInstance']);
708 static::getTPL()->assign('__' . $abbreviation, self::$applicationObjects[$application->packageID]);
709 EmailTemplateEngine::getInstance()->assign(
710 '__' . $abbreviation,
711 self::$applicationObjects[$application->packageID]
712 );
713 } else {
714 unset(self::$autoloadDirectories[$abbreviation]);
715 throw new SystemException("Unable to run '" . $package->package . "', '" . $className . "' is missing or does not implement '" . IApplication::class . "'.");
716 }
717
718 // register template path in ACP
719 if (\class_exists('wcf\system\WCFACP', false)) {
720 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
721 } elseif (!$isDependentApplication) {
722 // assign base tag
723 static::getTPL()->assign('baseHref', $application->getPageURL());
724 }
725
726 // register application
727 self::$applications[$abbreviation] = $application;
728
729 return self::$applicationObjects[$application->packageID];
730 }
731
732 /**
733 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
734 *
735 * @param Application $application
736 * @return IApplication
737 */
738 public static function getApplicationObject(Application $application)
739 {
740 if (isset(self::$applicationObjects[$application->packageID])) {
741 return self::$applicationObjects[$application->packageID];
742 }
743 }
744
745 /**
746 * Returns the invoked application.
747 *
748 * @return Application
749 * @since 3.1
750 */
751 public static function getActiveApplication()
752 {
753 return ApplicationHandler::getInstance()->getActiveApplication();
754 }
755
756 /**
757 * Loads an application on runtime, do not use this outside the package installation.
758 *
759 * @param int $packageID
760 */
761 public static function loadRuntimeApplication($packageID)
762 {
763 $package = new Package($packageID);
764 $application = new Application($packageID);
765
766 $abbreviation = Package::getAbbreviation($package->package);
767 $packageDir = FileUtil::getRealPath(WCF_DIR . $package->packageDir);
768 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
769 self::$applications[$abbreviation] = $application;
770 self::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
771 }
772
773 /**
774 * Initializes core object cache.
775 */
776 protected function initCoreObjects()
777 {
778 // ignore core objects if installing WCF
779 if (PACKAGE_ID == 0) {
780 return;
781 }
782
783 self::$coreObjectCache = CoreObjectCacheBuilder::getInstance()->getData();
784 }
785
786 /**
787 * Assigns some default variables to the template engine.
788 */
789 protected function assignDefaultTemplateVariables()
790 {
791 $wcf = $this;
792
793 if (ENABLE_ENTERPRISE_MODE) {
794 $wcf = new TemplateScriptingCore($wcf);
795 }
796
797 self::getTPL()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang', 'csrfToken']);
798 self::getTPL()->assign([
799 '__wcf' => $wcf,
800 '__wcfVersion' => LAST_UPDATE_TIME, // @deprecated 2.1, use LAST_UPDATE_TIME directly
801 ]);
802
803 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
804 // Execute background queue in this request, if it was requested and AJAX isn't used.
805 if (!$isAjax) {
806 if (self::getSession()->getVar('forceBackgroundQueuePerform')) {
807 self::getTPL()->assign([
808 'forceBackgroundQueuePerform' => true,
809 ]);
810
811 self::getSession()->unregister('forceBackgroundQueuePerform');
812 }
813 }
814
815 EmailTemplateEngine::getInstance()->registerPrefilter(['event', 'hascontent', 'lang', 'jslang']);
816 EmailTemplateEngine::getInstance()->assign([
817 '__wcf' => $wcf,
818 ]);
819 }
820
821 /**
822 * Wrapper for the getter methods of this class.
823 *
824 * @param string $name
825 * @return mixed value
826 * @throws SystemException
827 */
828 public function __get($name)
829 {
830 $method = 'get' . \ucfirst($name);
831 if (\method_exists($this, $method)) {
832 return $this->{$method}();
833 }
834
835 throw new SystemException("method '" . $method . "' does not exist in class WCF");
836 }
837
838 /**
839 * Returns true if current application (WCF) is treated as active and was invoked directly.
840 *
841 * @return bool
842 */
843 public function isActiveApplication()
844 {
845 return ApplicationHandler::getInstance()->getActiveApplication()->packageID == 1;
846 }
847
848 /**
849 * Changes the active language.
850 *
851 * @param int $languageID
852 */
853 final public static function setLanguage($languageID)
854 {
855 if (!$languageID || LanguageFactory::getInstance()->getLanguage($languageID) === null) {
856 $languageID = LanguageFactory::getInstance()->getDefaultLanguageID();
857 }
858
859 self::$languageObj = LanguageFactory::getInstance()->getLanguage($languageID);
860
861 // the template engine may not be available yet, usually happens when
862 // changing the user (and thus the language id) during session init
863 if (self::$tplObj !== null) {
864 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
865 EmailTemplateEngine::getInstance()->setLanguageID(self::getLanguage()->languageID);
866 }
867 }
868
869 /**
870 * Includes the required util or exception classes automatically.
871 *
872 * @param string $className
873 * @see spl_autoload_register()
874 */
875 final public static function autoload($className)
876 {
877 $namespaces = \explode('\\', $className);
878 if (\count($namespaces) > 1) {
879 $applicationPrefix = \array_shift($namespaces);
880 if ($applicationPrefix === '') {
881 $applicationPrefix = \array_shift($namespaces);
882 }
883 if (isset(self::$autoloadDirectories[$applicationPrefix])) {
884 $classPath = self::$autoloadDirectories[$applicationPrefix] . \implode('/', $namespaces) . '.class.php';
885
886 // PHP will implicitly check if the file exists when including it, which means that we can save a
887 // redundant syscall/fs access by not checking for existence ourselves. Do not use require_once()!
888 @include_once($classPath);
889 }
890 }
891 }
892
893 /**
894 * @inheritDoc
895 */
896 final public function __call($name, array $arguments)
897 {
898 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
899 if (!\method_exists($this, $name)) {
900 return self::__callStatic($name, $arguments);
901 }
902
903 throw new \BadMethodCallException("Call to undefined method WCF::{$name}().");
904 }
905
906 /**
907 * Returns dynamically loaded core objects.
908 *
909 * @param string $name
910 * @param array $arguments
911 * @return object
912 * @throws SystemException
913 */
914 final public static function __callStatic($name, array $arguments)
915 {
916 $className = \preg_replace('~^get~', '', $name);
917
918 if (isset(self::$coreObject[$className])) {
919 return self::$coreObject[$className];
920 }
921
922 $objectName = self::getCoreObject($className);
923 if ($objectName === null) {
924 throw new SystemException("Core object '" . $className . "' is unknown.");
925 }
926
927 if (\class_exists($objectName)) {
928 if (!\is_subclass_of($objectName, SingletonFactory::class)) {
929 throw new ParentClassException($objectName, SingletonFactory::class);
930 }
931
932 self::$coreObject[$className] = \call_user_func([$objectName, 'getInstance']);
933
934 return self::$coreObject[$className];
935 }
936 }
937
938 /**
939 * Searches for cached core object definition.
940 *
941 * @param string $className
942 * @return string
943 */
944 final protected static function getCoreObject($className)
945 {
946 if (isset(self::$coreObjectCache[$className])) {
947 return self::$coreObjectCache[$className];
948 }
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) {
1042 return;
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
1051 return;
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 }
1338 }