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