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