Fixed typo
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / lib / system / WCF.class.php
CommitLineData
d335fa16
AE
1<?php
2namespace wcf\system;
3use wcf\data\application\Application;
4use wcf\data\option\OptionEditor;
5use wcf\data\package\Package;
6use wcf\data\package\PackageCache;
7use wcf\data\package\PackageEditor;
12a2ff01
AE
8use wcf\data\page\Page;
9use wcf\data\page\PageCache;
5346b183 10use wcf\page\CmsPage;
d335fa16 11use wcf\system\application\ApplicationHandler;
f341086b 12use wcf\system\application\IApplication;
55b402a0 13use wcf\system\box\BoxHandler;
d335fa16
AE
14use wcf\system\cache\builder\CoreObjectCacheBuilder;
15use wcf\system\cache\builder\PackageUpdateCacheBuilder;
16use wcf\system\cronjob\CronjobScheduler;
157054c9 17use wcf\system\database\MySQLDatabase;
d335fa16
AE
18use wcf\system\event\EventHandler;
19use wcf\system\exception\AJAXException;
b25ad8f3 20use wcf\system\exception\ErrorException;
d335fa16
AE
21use wcf\system\exception\IPrintableException;
22use wcf\system\exception\NamedUserException;
7b9ff46b 23use wcf\system\exception\ParentClassException;
d335fa16
AE
24use wcf\system\exception\PermissionDeniedException;
25use wcf\system\exception\SystemException;
26use wcf\system\language\LanguageFactory;
27use wcf\system\package\PackageInstallationDispatcher;
11117cd5 28use wcf\system\registry\RegistryHandler;
12a2ff01 29use wcf\system\request\Request;
a80873d5 30use wcf\system\request\RequestHandler;
d335fa16
AE
31use wcf\system\session\SessionFactory;
32use wcf\system\session\SessionHandler;
33use wcf\system\style\StyleHandler;
15621401 34use wcf\system\template\EmailTemplateEngine;
d335fa16
AE
35use wcf\system\template\TemplateEngine;
36use wcf\system\user\storage\UserStorageHandler;
d335fa16 37use wcf\util\FileUtil;
8418bed7 38use wcf\util\HeaderUtil;
d335fa16 39use wcf\util\StringUtil;
dc0015ab 40use wcf\util\UserUtil;
d335fa16
AE
41
42// try to set a time-limit to infinite
43@set_time_limit(0);
44
45// fix timezone warning issue
46if (!@ini_get('date.timezone')) {
47 @date_default_timezone_set('Europe/London');
48}
49
359841c3 50// define current woltlab suite version
04acbf0b 51define('WCF_VERSION', '5.2.0 Alpha 1');
d335fa16 52
89484ba0 53// define current API version
04acbf0b 54define('WSC_API_VERSION', 2019);
89484ba0 55
d335fa16
AE
56// define current unix timestamp
57define('TIME_NOW', time());
58
59// wcf imports
60if (!defined('NO_IMPORTS')) {
61 require_once(WCF_DIR.'lib/core.functions.php');
d11a8c9e 62 require_once(WCF_DIR.'lib/system/api/autoload.php');
d335fa16
AE
63}
64
65/**
e71525e4 66 * WCF is the central class for the WoltLab Suite Core.
d335fa16
AE
67 * It holds the database connection, access to template and language engine.
68 *
69 * @author Marcel Werk
7b7b9764 70 * @copyright 2001-2019 WoltLab GmbH
d335fa16 71 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
e71525e4 72 * @package WoltLabSuite\Core\System
d335fa16
AE
73 */
74class WCF {
89484ba0
AE
75 /**
76 * list of supported legacy API versions
77 * @var integer[]
78 */
04acbf0b 79 private static $supportedLegacyApiVersions = [2017, 2018];
89484ba0 80
d335fa16
AE
81 /**
82 * list of currently loaded applications
893aace3 83 * @var Application[]
d335fa16 84 */
058cbd6a 85 protected static $applications = [];
d335fa16
AE
86
87 /**
88 * list of currently loaded application objects
7a23a706 89 * @var IApplication[]
d335fa16 90 */
058cbd6a 91 protected static $applicationObjects = [];
d335fa16
AE
92
93 /**
94 * list of autoload directories
95 * @var array
96 */
058cbd6a 97 protected static $autoloadDirectories = [];
d335fa16
AE
98
99 /**
100 * list of unique instances of each core object
7a23a706 101 * @var SingletonFactory[]
d335fa16 102 */
058cbd6a 103 protected static $coreObject = [];
d335fa16
AE
104
105 /**
106 * list of cached core objects
7a23a706 107 * @var string[]
d335fa16 108 */
058cbd6a 109 protected static $coreObjectCache = [];
d335fa16
AE
110
111 /**
112 * database object
4e25add7 113 * @var MySQLDatabase
d335fa16 114 */
85099417 115 protected static $dbObj;
d335fa16
AE
116
117 /**
118 * language object
a59497a6 119 * @var \wcf\data\language\Language
d335fa16 120 */
85099417 121 protected static $languageObj;
d335fa16
AE
122
123 /**
124 * overrides disabled debug mode
125 * @var boolean
126 */
127 protected static $overrideDebugMode = false;
128
129 /**
130 * session object
4e25add7 131 * @var SessionHandler
d335fa16 132 */
85099417 133 protected static $sessionObj;
d335fa16
AE
134
135 /**
136 * template object
4e25add7 137 * @var TemplateEngine
d335fa16 138 */
85099417 139 protected static $tplObj;
d335fa16
AE
140
141 /**
142 * true if Zend Opcache is loaded and enabled
143 * @var boolean
144 */
85099417 145 protected static $zendOpcacheEnabled;
d335fa16 146
ab84d9ca
AE
147 /**
148 * force logout during destructor call
149 * @var boolean
150 */
151 protected static $forceLogout = false;
152
d335fa16
AE
153 /**
154 * Calls all init functions of the WCF class.
155 */
156 public function __construct() {
157 // add autoload directory
158 self::$autoloadDirectories['wcf'] = WCF_DIR . 'lib/';
159
160 // define tmp directory
161 if (!defined('TMP_DIR')) define('TMP_DIR', FileUtil::getTempFolder());
162
163 // start initialization
d335fa16
AE
164 $this->initDB();
165 $this->loadOptions();
166 $this->initSession();
167 $this->initLanguage();
168 $this->initTPL();
169 $this->initCronjobs();
170 $this->initCoreObjects();
171 $this->initApplications();
172 $this->initBlacklist();
173
174 EventHandler::getInstance()->fireAction($this, 'initialized');
175 }
176
177 /**
3ba197fa
TD
178 * Flushes the output, closes the session, performs background tasks and more.
179 *
180 * You *must* not create output in here under normal circumstances, as it might get eaten
181 * when gzip is enabled.
d335fa16
AE
182 */
183 public static function destruct() {
184 try {
185 // database has to be initialized
186 if (!is_object(self::$dbObj)) return;
187
3ba197fa
TD
188 $debug = self::debugModeIsEnabled(true);
189 if (!$debug) {
190 // flush output
191 if (ob_get_level()) ob_end_flush();
d335fa16 192 flush();
3ba197fa
TD
193
194 // close connection if using FPM
195 if (function_exists('fastcgi_finish_request')) fastcgi_finish_request();
d335fa16
AE
196 }
197
198 // update session
199 if (is_object(self::getSession())) {
ab84d9ca
AE
200 if (self::$forceLogout) {
201 // do logout
1eb97b3a 202 self::getSession()->delete();
ab84d9ca
AE
203 }
204 else {
205 self::getSession()->update();
206 }
d335fa16
AE
207 }
208
11117cd5
AE
209 // execute shutdown actions of storage handlers
210 RegistryHandler::getInstance()->shutdown();
d335fa16
AE
211 UserStorageHandler::getInstance()->shutdown();
212 }
213 catch (\Exception $exception) {
214 die("<pre>WCF::destruct() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
215 }
216 }
217
d335fa16
AE
218 /**
219 * Returns the database object.
220 *
221 * @return \wcf\system\database\Database
222 */
223 public static final function getDB() {
224 return self::$dbObj;
225 }
226
227 /**
228 * Returns the session object.
229 *
4e25add7 230 * @return SessionHandler
d335fa16
AE
231 */
232 public static final function getSession() {
233 return self::$sessionObj;
234 }
235
236 /**
237 * Returns the user object.
238 *
239 * @return \wcf\data\user\User
240 */
241 public static final function getUser() {
242 return self::getSession()->getUser();
243 }
244
245 /**
246 * Returns the language object.
247 *
248 * @return \wcf\data\language\Language
249 */
250 public static final function getLanguage() {
251 return self::$languageObj;
252 }
253
254 /**
255 * Returns the template object.
256 *
4e25add7 257 * @return TemplateEngine
d335fa16
AE
258 */
259 public static final function getTPL() {
260 return self::$tplObj;
261 }
262
263 /**
264 * Calls the show method on the given exception.
265 *
266 * @param \Exception $e
267 */
e09c7044 268 public static final function handleException($e) {
cbf81afa
AE
269 // backwards compatibility
270 if ($e instanceof IPrintableException) {
271 $e->show();
272 exit;
273 }
274
f8434d25 275 if (ob_get_level()) {
1615fc2e 276 // discard any output generated before the exception occurred, prevents exception
f8434d25 277 // being hidden inside HTML elements and therefore not visible in browser output
f46ac60e
AE
278 //
279 // ob_get_level() can return values > 1, if the PHP setting `output_buffering` is on
280 while (ob_get_level()) ob_end_clean();
5f2c3ab4 281
fef5bd1f
AE
282 // Some webservers are broken and will apply gzip encoding at all cost, but they fail
283 // to set a proper `Content-Encoding` HTTP header and mess things up even more.
284 // Especially the `identity` value appears to be unrecognized by some of them, hence
285 // we'll just gzip the output of the exception to prevent them from tampering.
286 // This part is copied from `HeaderUtil` in order to isolate the exception handler!
4d7a0b73 287 if (defined('HTTP_ENABLE_GZIP') && HTTP_ENABLE_GZIP && !defined('HTTP_DISABLE_GZIP')) {
ac8615e4
LK
288 if (function_exists('gzcompress') && !@ini_get('zlib.output_compression') && !@ini_get('output_handler') && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
289 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false) {
fef5bd1f
AE
290 @header('Content-Encoding: x-gzip');
291 }
292 else {
293 @header('Content-Encoding: gzip');
294 }
295
296 ob_start(function($output) {
297 $size = strlen($output);
298 $crc = crc32($output);
299
300 $newOutput = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff";
301 $newOutput .= substr(gzcompress($output, 1), 2, -4);
302 $newOutput .= pack('V', $crc);
303 $newOutput .= pack('V', $size);
304
305 return $newOutput;
306 });
307 }
308 }
f8434d25
AE
309 }
310
5bc5a7e6 311 @header('HTTP/1.1 503 Service Unavailable');
d335fa16 312 try {
5bc5a7e6 313 \wcf\functions\exception\printThrowable($e);
d335fa16 314 }
5bc5a7e6
TD
315 catch (\Throwable $e2) {
316 echo "<pre>An Exception was thrown while handling an Exception:\n\n";
6b7d6653 317 echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e2);
5bc5a7e6 318 echo "\n\nwas thrown while:\n\n";
6b7d6653 319 echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e);
5bc5a7e6
TD
320 echo "\n\nwas handled.</pre>";
321 exit;
e09c7044 322 }
d335fa16
AE
323 }
324
325 /**
b25ad8f3 326 * Turns PHP errors into an ErrorException.
d335fa16 327 *
ac52543a 328 * @param integer $severity
d335fa16 329 * @param string $message
ac52543a
MS
330 * @param string $file
331 * @param integer $line
2b770bdd 332 * @throws ErrorException
d335fa16 333 */
b25ad8f3 334 public static final function handleError($severity, $message, $file, $line) {
b2aa772d 335 // this is necessary for the shut-up operator
b25ad8f3
TD
336 if (error_reporting() == 0) return;
337
338 throw new ErrorException($message, 0, $severity, $file, $line);
d335fa16
AE
339 }
340
341 /**
342 * Loads the database configuration and creates a new connection to the database.
343 */
344 protected function initDB() {
345 // get configuration
346 $dbHost = $dbUser = $dbPassword = $dbName = '';
347 $dbPort = 0;
20e541d6 348 $defaultDriverOptions = [];
d335fa16
AE
349 require(WCF_DIR.'config.inc.php');
350
351 // create database connection
20e541d6 352 self::$dbObj = new MySQLDatabase($dbHost, $dbUser, $dbPassword, $dbName, $dbPort, false, false, $defaultDriverOptions);
d335fa16
AE
353 }
354
355 /**
356 * Loads the options file, automatically created if not exists.
357 */
358 protected function loadOptions() {
dd2d8c0c 359 // the attachment module is always enabled since 5.2
85099417
AE
360 // https://github.com/WoltLab/WCF/issues/2531
361 define('MODULE_ATTACHMENT', 1);
362
d335fa16
AE
363 $filename = WCF_DIR.'options.inc.php';
364
365 // create options file if doesn't exist
366 if (!file_exists($filename) || filemtime($filename) <= 1) {
367 OptionEditor::rebuild();
368 }
11beb0a0 369 require($filename);
b842faa1
AE
370
371 // check if option file is complete and writable
372 if (PACKAGE_ID) {
373 if (!is_writable($filename)) {
374 FileUtil::makeWritable($filename);
375
376 if (!is_writable($filename)) {
377 throw new SystemException("The option file '" . $filename . "' is not writable.");
378 }
379 }
380
381 // check if a previous write operation was incomplete and force rebuilding
382 if (!defined('WCF_OPTION_INC_PHP_SUCCESS')) {
383 OptionEditor::rebuild();
384
11beb0a0 385 require($filename);
b842faa1
AE
386 }
387 }
d335fa16
AE
388 }
389
390 /**
391 * Starts the session system.
392 */
393 protected function initSession() {
f341086b 394 $factory = new SessionFactory();
d335fa16
AE
395 $factory->load();
396
f341086b 397 self::$sessionObj = SessionHandler::getInstance();
91082aee 398 self::$sessionObj->setHasValidCookie($factory->hasValidCookie());
d335fa16
AE
399 }
400
401 /**
402 * Initialises the language engine.
403 */
404 protected function initLanguage() {
405 if (isset($_GET['l']) && !self::getUser()->userID) {
406 self::getSession()->setLanguageID(intval($_GET['l']));
407 }
408
409 // set mb settings
410 mb_internal_encoding('UTF-8');
411 if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
412 mb_language('uni');
413
414 // get language
f341086b 415 self::$languageObj = LanguageFactory::getInstance()->getUserLanguage(self::getSession()->getLanguageID());
d335fa16
AE
416 }
417
418 /**
419 * Initialises the template engine.
420 */
421 protected function initTPL() {
f341086b 422 self::$tplObj = TemplateEngine::getInstance();
d335fa16
AE
423 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
424 $this->assignDefaultTemplateVariables();
425
426 $this->initStyle();
427 }
428
429 /**
430 * Initializes the user's style.
431 */
432 protected function initStyle() {
433 if (isset($_REQUEST['styleID'])) {
434 self::getSession()->setStyleID(intval($_REQUEST['styleID']));
435 }
436
f341086b 437 $styleHandler = StyleHandler::getInstance();
d11a8c9e 438 $styleHandler->changeStyle(self::getSession()->getStyleID());
d335fa16
AE
439 }
440
441 /**
442 * Executes the blacklist.
443 */
444 protected function initBlacklist() {
fa75ccfb
AE
445 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
446
d335fa16 447 if (defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES != '') {
dc0015ab 448 if (!StringUtil::executeWordFilter(UserUtil::convertIPv6To4(self::getSession()->ipAddress), BLACKLIST_IP_ADDRESSES)) {
fa75ccfb 449 if ($isAjax) {
a1721f86 450 throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
fa75ccfb
AE
451 }
452 else {
453 throw new PermissionDeniedException();
454 }
dc0015ab
AE
455 }
456 else if (!StringUtil::executeWordFilter(self::getSession()->ipAddress, BLACKLIST_IP_ADDRESSES)) {
fa75ccfb 457 if ($isAjax) {
a1721f86 458 throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
fa75ccfb
AE
459 }
460 else {
461 throw new PermissionDeniedException();
462 }
d335fa16
AE
463 }
464 }
465 if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS != '') {
466 if (!StringUtil::executeWordFilter(self::getSession()->userAgent, BLACKLIST_USER_AGENTS)) {
fa75ccfb 467 if ($isAjax) {
a1721f86 468 throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
fa75ccfb
AE
469 }
470 else {
471 throw new PermissionDeniedException();
472 }
d335fa16
AE
473 }
474 }
475 if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES != '') {
476 if (!StringUtil::executeWordFilter(@gethostbyaddr(self::getSession()->ipAddress), BLACKLIST_HOSTNAMES)) {
fa75ccfb 477 if ($isAjax) {
a1721f86 478 throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
fa75ccfb
AE
479 }
480 else {
481 throw new PermissionDeniedException();
482 }
d335fa16
AE
483 }
484 }
485
486 // handle banned users
d0ebece3 487 if (self::getUser()->userID && self::getUser()->banned && !self::getUser()->hasOwnerAccess()) {
fa75ccfb 488 if ($isAjax) {
d335fa16
AE
489 throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'), AJAXException::INSUFFICIENT_PERMISSIONS);
490 }
491 else {
ab84d9ca
AE
492 self::$forceLogout = true;
493
494 // remove cookies
495 if (isset($_COOKIE[COOKIE_PREFIX.'userID'])) {
496 HeaderUtil::setCookie('userID', 0);
497 }
498 if (isset($_COOKIE[COOKIE_PREFIX.'password'])) {
499 HeaderUtil::setCookie('password', '');
500 }
501
d335fa16
AE
502 throw new NamedUserException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
503 }
504 }
505 }
506
507 /**
508 * Initializes applications.
509 */
510 protected function initApplications() {
511 // step 1) load all applications
058cbd6a 512 $loadedApplications = [];
d335fa16
AE
513
514 // register WCF as application
39abe192 515 self::$applications['wcf'] = ApplicationHandler::getInstance()->getApplicationByID(1);
d335fa16 516
39abe192 517 if (!class_exists(WCFACP::class, false)) {
b2b2c26b 518 static::getTPL()->assign('baseHref', self::$applications['wcf']->getPageURL());
39abe192
AE
519 }
520
d335fa16
AE
521 // start main application
522 $application = ApplicationHandler::getInstance()->getActiveApplication();
39abe192
AE
523 if ($application->packageID != 1) {
524 $loadedApplications[] = $this->loadApplication($application);
525
526 // register primary application
527 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
528 self::$applications[$abbreviation] = $application;
529 }
d335fa16
AE
530
531 // start dependent applications
532 $applications = ApplicationHandler::getInstance()->getDependentApplications();
533 foreach ($applications as $application) {
39abe192
AE
534 if ($application->packageID == 1) {
535 // ignore WCF
536 continue;
537 }
f4eafe37
AE
538 else if ($application->isTainted) {
539 // ignore apps flagged for uninstallation
540 continue;
541 }
39abe192 542
d335fa16
AE
543 $loadedApplications[] = $this->loadApplication($application, true);
544 }
545
546 // step 2) run each application
547 if (!class_exists('wcf\system\WCFACP', false)) {
f341086b 548 /** @var IApplication $application */
d335fa16
AE
549 foreach ($loadedApplications as $application) {
550 $application->__run();
551 }
552
553 // refresh the session 1 minute before it expires
63b9817b 554 self::getTPL()->assign('__sessionKeepAlive', SESSION_TIMEOUT - 60);
d335fa16
AE
555 }
556 }
557
558 /**
559 * Loads an application.
560 *
2b770bdd
MS
561 * @param Application $application
562 * @param boolean $isDependentApplication
563 * @return IApplication
564 * @throws SystemException
d335fa16
AE
565 */
566 protected function loadApplication(Application $application, $isDependentApplication = false) {
d335fa16
AE
567 $package = PackageCache::getInstance()->getPackage($application->packageID);
568 // package cache might be outdated
569 if ($package === null) {
570 $package = new Package($application->packageID);
571
572 // package cache is outdated, discard cache
573 if ($package->packageID) {
574 PackageEditor::resetCache();
575 }
576 else {
577 // package id is invalid
578 throw new SystemException("application identified by package id '".$application->packageID."' is unknown");
579 }
580 }
e54191ea 581
d335fa16
AE
582 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
583 $packageDir = FileUtil::getRealPath(WCF_DIR.$package->packageDir);
584 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
585
586 $className = $abbreviation.'\system\\'.strtoupper($abbreviation).'Core';
59162cf3
AE
587
588 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
589 if (!class_exists($className)) {
590 // check if both the Core and the app are on the same domain
591 $coreApp = ApplicationHandler::getInstance()->getApplicationByID(1);
592 if ($coreApp->domainName === $application->domainName) {
593 // resolve the relative path and use it to construct the autoload directory
594 $relativePath = FileUtil::getRelativePath($coreApp->domainPath, $application->domainPath);
595 if ($relativePath !== './') {
596 $packageDir = FileUtil::getRealPath(WCF_DIR.$relativePath);
597 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
598
599 if (class_exists($className)) {
600 // the class can now be found, update the `packageDir` value
601 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
602 }
603 }
604 }
605 }
606
157054c9 607 if (class_exists($className) && is_subclass_of($className, IApplication::class)) {
d335fa16
AE
608 // include config file
609 $configPath = $packageDir . PackageInstallationDispatcher::CONFIG_FILE;
b842faa1
AE
610 if (!file_exists($configPath)) {
611 Package::writeConfigFile($package->packageID);
612 }
613
d335fa16
AE
614 if (file_exists($configPath)) {
615 require_once($configPath);
616 }
617 else {
618 throw new SystemException('Unable to load configuration for '.$package->package);
619 }
620
621 // register template path if not within ACP
622 if (!class_exists('wcf\system\WCFACP', false)) {
623 // add template path and abbreviation
b2b2c26b 624 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
d335fa16 625 }
15621401 626 EmailTemplateEngine::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
d335fa16
AE
627
628 // init application and assign it as template variable
058cbd6a 629 self::$applicationObjects[$application->packageID] = call_user_func([$className, 'getInstance']);
b2b2c26b 630 static::getTPL()->assign('__'.$abbreviation, self::$applicationObjects[$application->packageID]);
15621401 631 EmailTemplateEngine::getInstance()->assign('__'.$abbreviation, self::$applicationObjects[$application->packageID]);
d335fa16
AE
632 }
633 else {
634 unset(self::$autoloadDirectories[$abbreviation]);
157054c9 635 throw new SystemException("Unable to run '".$package->package."', '".$className."' is missing or does not implement '".IApplication::class."'.");
d335fa16
AE
636 }
637
638 // register template path in ACP
639 if (class_exists('wcf\system\WCFACP', false)) {
b2b2c26b 640 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
d335fa16
AE
641 }
642 else if (!$isDependentApplication) {
643 // assign base tag
b2b2c26b 644 static::getTPL()->assign('baseHref', $application->getPageURL());
d335fa16
AE
645 }
646
647 // register application
648 self::$applications[$abbreviation] = $application;
649
650 return self::$applicationObjects[$application->packageID];
651 }
652
653 /**
654 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
655 *
4e25add7
MS
656 * @param Application $application
657 * @return IApplication
d335fa16
AE
658 */
659 public static function getApplicationObject(Application $application) {
660 if (isset(self::$applicationObjects[$application->packageID])) {
661 return self::$applicationObjects[$application->packageID];
662 }
663
664 return null;
665 }
666
dbf41d8a
AE
667 /**
668 * Returns the invoked application.
669 *
670 * @return Application
8e152e07 671 * @since 3.1
dbf41d8a
AE
672 */
673 public static function getActiveApplication() {
674 return ApplicationHandler::getInstance()->getActiveApplication();
675 }
676
d335fa16
AE
677 /**
678 * Loads an application on runtime, do not use this outside the package installation.
679 *
680 * @param integer $packageID
681 */
682 public static function loadRuntimeApplication($packageID) {
683 $package = new Package($packageID);
684 $application = new Application($packageID);
685
686 $abbreviation = Package::getAbbreviation($package->package);
687 $packageDir = FileUtil::getRealPath(WCF_DIR.$package->packageDir);
688 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
689 self::$applications[$abbreviation] = $application;
690 self::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
691 }
692
693 /**
694 * Initializes core object cache.
695 */
696 protected function initCoreObjects() {
697 // ignore core objects if installing WCF
698 if (PACKAGE_ID == 0) {
699 return;
700 }
701
702 self::$coreObjectCache = CoreObjectCacheBuilder::getInstance()->getData();
703 }
704
705 /**
706 * Assigns some default variables to the template engine.
707 */
708 protected function assignDefaultTemplateVariables() {
058cbd6a
MS
709 self::getTPL()->registerPrefilter(['event', 'hascontent', 'lang']);
710 self::getTPL()->assign([
d335fa16 711 '__wcf' => $this,
e71525e4 712 '__wcfVersion' => LAST_UPDATE_TIME // @deprecated 2.1, use LAST_UPDATE_TIME directly
058cbd6a 713 ]);
54de7a5f
TD
714
715 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
716 // Execute background queue in this request, if it was requested and AJAX isn't used.
717 if (!$isAjax) {
718 if (self::getSession()->getVar('forceBackgroundQueuePerform')) {
719 self::getTPL()->assign([
720 'forceBackgroundQueuePerform' => true
721 ]);
722
723 self::getSession()->unregister('forceBackgroundQueuePerform');
724 }
725 }
726
15621401
TD
727 EmailTemplateEngine::getInstance()->registerPrefilter(['event', 'hascontent', 'lang']);
728 EmailTemplateEngine::getInstance()->assign([
729 '__wcf' => $this
730 ]);
d335fa16
AE
731 }
732
733 /**
734 * Wrapper for the getter methods of this class.
735 *
736 * @param string $name
737 * @return mixed value
2b770bdd 738 * @throws SystemException
d335fa16
AE
739 */
740 public function __get($name) {
741 $method = 'get'.ucfirst($name);
742 if (method_exists($this, $method)) {
743 return $this->$method();
744 }
745
746 throw new SystemException("method '".$method."' does not exist in class WCF");
747 }
748
487db634
MW
749 /**
750 * Returns true if current application (WCF) is treated as active and was invoked directly.
751 *
752 * @return boolean
753 */
754 public function isActiveApplication() {
755 return (ApplicationHandler::getInstance()->getActiveApplication()->packageID == 1);
756 }
757
d335fa16
AE
758 /**
759 * Changes the active language.
760 *
761 * @param integer $languageID
762 */
763 public static final function setLanguage($languageID) {
5b8eae2c
MW
764 if (!$languageID || LanguageFactory::getInstance()->getLanguage($languageID) === null) {
765 $languageID = LanguageFactory::getInstance()->getDefaultLanguageID();
766 }
2d90d60f 767
d335fa16 768 self::$languageObj = LanguageFactory::getInstance()->getLanguage($languageID);
b372bd53
AE
769
770 // the template engine may not be available yet, usually happens when
771 // changing the user (and thus the language id) during session init
772 if (self::$tplObj !== null) {
773 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
774 EmailTemplateEngine::getInstance()->setLanguageID(self::getLanguage()->languageID);
775 }
d335fa16
AE
776 }
777
778 /**
779 * Includes the required util or exception classes automatically.
780 *
781 * @param string $className
782 * @see spl_autoload_register()
783 */
784 public static final function autoload($className) {
785 $namespaces = explode('\\', $className);
786 if (count($namespaces) > 1) {
787 $applicationPrefix = array_shift($namespaces);
788 if ($applicationPrefix === '') {
789 $applicationPrefix = array_shift($namespaces);
790 }
791 if (isset(self::$autoloadDirectories[$applicationPrefix])) {
792 $classPath = self::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
6f609fec
AE
793
794 // PHP will implicitly check if the file exists when including it, which means that we can save a
795 // redundant syscall/fs access by not checking for existence ourselves. Do not use require_once()!
796 @include_once($classPath);
d335fa16
AE
797 }
798 }
799 }
800
801 /**
0fcfe5f6 802 * @inheritDoc
d335fa16
AE
803 */
804 public final function __call($name, array $arguments) {
805 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
806 if (!method_exists($this, $name)) {
807 return self::__callStatic($name, $arguments);
808 }
809
810 return $this->$name($arguments);
811 }
812
813 /**
814 * Returns dynamically loaded core objects.
815 *
816 * @param string $name
817 * @param array $arguments
71952a87 818 * @return object
2b770bdd 819 * @throws SystemException
d335fa16
AE
820 */
821 public static final function __callStatic($name, array $arguments) {
822 $className = preg_replace('~^get~', '', $name);
823
824 if (isset(self::$coreObject[$className])) {
825 return self::$coreObject[$className];
826 }
827
828 $objectName = self::getCoreObject($className);
829 if ($objectName === null) {
830 throw new SystemException("Core object '".$className."' is unknown.");
831 }
832
833 if (class_exists($objectName)) {
63b9817b 834 if (!is_subclass_of($objectName, SingletonFactory::class)) {
7b9ff46b 835 throw new ParentClassException($objectName, SingletonFactory::class);
d335fa16
AE
836 }
837
058cbd6a 838 self::$coreObject[$className] = call_user_func([$objectName, 'getInstance']);
d335fa16
AE
839 return self::$coreObject[$className];
840 }
841 }
842
843 /**
844 * Searches for cached core object definition.
845 *
846 * @param string $className
847 * @return string
848 */
849 protected static final function getCoreObject($className) {
850 if (isset(self::$coreObjectCache[$className])) {
851 return self::$coreObjectCache[$className];
852 }
853
854 return null;
855 }
856
857 /**
858 * Returns true if the debug mode is enabled, otherwise false.
859 *
860 * @param boolean $ignoreACP
861 * @return boolean
862 */
863 public static function debugModeIsEnabled($ignoreACP = false) {
864 // ACP override
865 if (!$ignoreACP && self::$overrideDebugMode) {
866 return true;
867 }
868 else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE) {
869 return true;
870 }
871
872 return false;
873 }
874
875 /**
876 * Returns true if benchmarking is enabled, otherwise false.
877 *
878 * @return boolean
879 */
880 public static function benchmarkIsEnabled() {
881 // benchmarking is enabled by default
882 if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK) return true;
883 return false;
884 }
885
886 /**
887 * Returns domain path for given application.
888 *
889 * @param string $abbreviation
890 * @return string
891 */
892 public static function getPath($abbreviation = 'wcf') {
893 // workaround during WCFSetup
894 if (!PACKAGE_ID) {
895 return '../';
896 }
897
898 if (!isset(self::$applications[$abbreviation])) {
899 $abbreviation = 'wcf';
900 }
901
902 return self::$applications[$abbreviation]->getPageURL();
903 }
904
5d1c96bc
AE
905 /**
906 * Returns the domain path for the currently active application,
907 * used to avoid CORS requests.
908 *
909 * @return string
910 */
911 public static function getActivePath() {
912 if (!PACKAGE_ID) {
913 return self::getPath();
914 }
915
916 return self::getPath(ApplicationHandler::getInstance()->getAbbreviation(ApplicationHandler::getInstance()->getActiveApplication()->packageID));
917 }
918
d335fa16
AE
919 /**
920 * Returns a fully qualified anchor for current page.
921 *
922 * @param string $fragment
923 * @return string
924 */
925 public function getAnchor($fragment) {
694f6545 926 return StringUtil::encodeHTML(self::getRequestURI() . '#' . $fragment);
d335fa16
AE
927 }
928
12a2ff01
AE
929 /**
930 * Returns the currently active page or null if unknown.
931 *
b212ba66 932 * @return Page|null
12a2ff01
AE
933 */
934 public static function getActivePage() {
a039ebd2
AE
935 if (self::getActiveRequest() === null) {
936 return null;
937 }
938
5346b183
AE
939 if (self::getActiveRequest()->getClassName() === CmsPage::class) {
940 $metaData = self::getActiveRequest()->getMetaData();
b212ba66
MS
941 if (isset($metaData['cms'])) {
942 return PageCache::getInstance()->getPage($metaData['cms']['pageID']);
943 }
944
945 return null;
5346b183
AE
946 }
947
12a2ff01
AE
948 return PageCache::getInstance()->getPageByController(self::getActiveRequest()->getClassName());
949 }
950
951 /**
952 * Returns the currently active request.
953 *
954 * @return Request
955 */
956 public static function getActiveRequest() {
957 return RequestHandler::getInstance()->getActiveRequest();
958 }
959
d335fa16
AE
960 /**
961 * Returns the URI of the current page.
962 *
963 * @return string
964 */
965 public static function getRequestURI() {
c68f6161 966 return preg_replace('~^(https?://[^/]+)(?:/.*)?$~', '$1', self::getTPL()->get('baseHref')) . $_SERVER['REQUEST_URI'];
d335fa16
AE
967 }
968
969 /**
970 * Resets Zend Opcache cache if installed and enabled.
971 *
972 * @param string $script
973 */
974 public static function resetZendOpcache($script = '') {
975 if (self::$zendOpcacheEnabled === null) {
976 self::$zendOpcacheEnabled = false;
977
978 if (extension_loaded('Zend Opcache') && @ini_get('opcache.enable')) {
979 self::$zendOpcacheEnabled = true;
980 }
981
982 }
983
984 if (self::$zendOpcacheEnabled) {
985 if (empty($script)) {
986 opcache_reset();
987 }
988 else {
989 opcache_invalidate($script, true);
990 }
991 }
992 }
993
994 /**
995 * Returns style handler.
996 *
4e25add7 997 * @return StyleHandler
d335fa16
AE
998 */
999 public function getStyleHandler() {
1000 return StyleHandler::getInstance();
1001 }
1002
55b402a0
MW
1003 /**
1004 * Returns box handler.
1005 *
1006 * @return BoxHandler
e71525e4 1007 * @since 3.0
55b402a0
MW
1008 */
1009 public function getBoxHandler() {
1010 return BoxHandler::getInstance();
1011 }
1012
d335fa16
AE
1013 /**
1014 * Returns number of available updates.
1015 *
1016 * @return integer
1017 */
1018 public function getAvailableUpdates() {
1019 $data = PackageUpdateCacheBuilder::getInstance()->getData();
1020 return $data['updates'];
1021 }
1022
1023 /**
1024 * Returns a 8 character prefix for editor autosave.
1025 *
1026 * @return string
1027 */
1028 public function getAutosavePrefix() {
1029 return substr(sha1(preg_replace('~^https~', 'http', self::getPath())), 0, 8);
1030 }
1031
1032 /**
1033 * Returns the favicon URL or a base64 encoded image.
1034 *
1035 * @return string
1036 */
1037 public function getFavicon() {
1038 $activeApplication = ApplicationHandler::getInstance()->getActiveApplication();
39abe192 1039 $wcf = ApplicationHandler::getInstance()->getWCF();
aef117b5 1040 $favicon = StyleHandler::getInstance()->getStyle()->getRelativeFavicon();
d335fa16 1041
39abe192 1042 if ($activeApplication->domainName !== $wcf->domainName) {
aef117b5
AE
1043 if (file_exists(WCF_DIR.$favicon)) {
1044 $favicon = file_get_contents(WCF_DIR.$favicon);
d335fa16
AE
1045
1046 return 'data:image/x-icon;base64,' . base64_encode($favicon);
1047 }
1048 }
1049
aef117b5 1050 return self::getPath() . $favicon;
d335fa16
AE
1051 }
1052
6e4aa12f
AE
1053 /**
1054 * Returns true if the desktop notifications should be enabled.
1055 *
1056 * @return boolean
1057 */
1058 public function useDesktopNotifications() {
1059 if (!ENABLE_DESKTOP_NOTIFICATIONS) {
1060 return false;
1061 }
1062 else if (ApplicationHandler::getInstance()->isMultiDomainSetup()) {
1063 $application = ApplicationHandler::getInstance()->getApplicationByID(DESKTOP_NOTIFICATION_PACKAGE_ID);
1064 // mismatch, default to Core
1065 if ($application === null) $application = ApplicationHandler::getInstance()->getApplicationByID(1);
1066
1067 $currentApplication = ApplicationHandler::getInstance()->getActiveApplication();
1068 if ($currentApplication->domainName != $application->domainName) {
1069 // different domain
1070 return false;
1071 }
1072 }
1073
1074 return true;
1075 }
1076
a80873d5
AE
1077 /**
1078 * Returns true if currently active request represents the landing page.
1079 *
8ff2cd79 1080 * @return boolean
a80873d5 1081 */
0fdd7f96 1082 public static function isLandingPage() {
a039ebd2
AE
1083 if (self::getActiveRequest() === null) {
1084 return false;
1085 }
1086
1087 return self::getActiveRequest()->isLandingPage();
a80873d5
AE
1088 }
1089
89484ba0
AE
1090 /**
1091 * Returns true if the given API version is currently supported.
1092 *
1093 * @param integer $apiVersion
1094 * @return boolean
1095 */
1096 public static function isSupportedApiVersion($apiVersion) {
1097 return ($apiVersion == WSC_API_VERSION) || in_array($apiVersion, self::$supportedLegacyApiVersions);
1098 }
1099
1100 /**
1101 * Returns the list of supported legacy API versions.
1102 *
1103 * @return integer[]
1104 */
1105 public static function getSupportedLegacyApiVersions() {
1106 return self::$supportedLegacyApiVersions;
1107 }
1108
d335fa16
AE
1109 /**
1110 * Initialises the cronjobs.
1111 */
1112 protected function initCronjobs() {
1113 if (PACKAGE_ID) {
63b9817b 1114 self::getTPL()->assign('executeCronjobs', CronjobScheduler::getInstance()->getNextExec() < TIME_NOW && defined('OFFLINE') && !OFFLINE);
d335fa16
AE
1115 }
1116 }
1117}