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.1');
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 if (ob_get_level()) {
271 // discard any output generated before the exception occurred, prevents exception
272 // being hidden inside HTML elements and therefore not visible in browser output
273 //
274 // ob_get_level() can return values > 1, if the PHP setting `output_buffering` is on
275 while (ob_get_level()) ob_end_clean();
276
277 // `identity` is the default "encoding" and basically means that the client
278 // must treat the content as if the header did not appear in first place, this
279 // also overrules the gzip header if present
280 @header('Content-Encoding: identity');
281 HeaderUtil::exceptionDisableGzip();
282 }
283
284 // backwards compatibility
285 if ($e instanceof IPrintableException) {
286 $e->show();
287 exit;
288 }
289
290 @header('HTTP/1.1 503 Service Unavailable');
291 try {
292 \wcf\functions\exception\printThrowable($e);
293 }
294 catch (\Throwable $e2) {
295 echo "<pre>An Exception was thrown while handling an Exception:\n\n";
296 echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e2);
297 echo "\n\nwas thrown while:\n\n";
298 echo preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $e);
299 echo "\n\nwas handled.</pre>";
300 exit;
301 }
302 }
303
304 /**
305 * Turns PHP errors into an ErrorException.
306 *
307 * @param integer $severity
308 * @param string $message
309 * @param string $file
310 * @param integer $line
311 * @throws ErrorException
312 */
313 public static final function handleError($severity, $message, $file, $line) {
314 // this is necessary for the shut-up operator
315 if (error_reporting() == 0) return;
316
317 throw new ErrorException($message, 0, $severity, $file, $line);
318 }
319
320 /**
321 * Loads the database configuration and creates a new connection to the database.
322 */
323 protected function initDB() {
324 // get configuration
325 $dbHost = $dbUser = $dbPassword = $dbName = '';
326 $dbPort = 0;
327 require(WCF_DIR.'config.inc.php');
328
329 // create database connection
330 self::$dbObj = new MySQLDatabase($dbHost, $dbUser, $dbPassword, $dbName, $dbPort);
331 }
332
333 /**
334 * Loads the options file, automatically created if not exists.
335 */
336 protected function loadOptions() {
337 $filename = WCF_DIR.'options.inc.php';
338
339 // create options file if doesn't exist
340 if (!file_exists($filename) || filemtime($filename) <= 1) {
341 OptionEditor::rebuild();
342 }
343 require_once($filename);
344
345 // check if option file is complete and writable
346 if (PACKAGE_ID) {
347 if (!is_writable($filename)) {
348 FileUtil::makeWritable($filename);
349
350 if (!is_writable($filename)) {
351 throw new SystemException("The option file '" . $filename . "' is not writable.");
352 }
353 }
354
355 // check if a previous write operation was incomplete and force rebuilding
356 if (!defined('WCF_OPTION_INC_PHP_SUCCESS')) {
357 OptionEditor::rebuild();
358
359 require_once($filename);
360 }
361 }
362 }
363
364 /**
365 * Starts the session system.
366 */
367 protected function initSession() {
368 $factory = new SessionFactory();
369 $factory->load();
370
371 self::$sessionObj = SessionHandler::getInstance();
372 self::$sessionObj->setHasValidCookie($factory->hasValidCookie());
373 }
374
375 /**
376 * Initialises the language engine.
377 */
378 protected function initLanguage() {
379 if (isset($_GET['l']) && !self::getUser()->userID) {
380 self::getSession()->setLanguageID(intval($_GET['l']));
381 }
382
383 // set mb settings
384 mb_internal_encoding('UTF-8');
385 if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
386 mb_language('uni');
387
388 // get language
389 self::$languageObj = LanguageFactory::getInstance()->getUserLanguage(self::getSession()->getLanguageID());
390 }
391
392 /**
393 * Initialises the template engine.
394 */
395 protected function initTPL() {
396 self::$tplObj = TemplateEngine::getInstance();
397 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
398 $this->assignDefaultTemplateVariables();
399
400 $this->initStyle();
401 }
402
403 /**
404 * Initializes the user's style.
405 */
406 protected function initStyle() {
407 if (isset($_REQUEST['styleID'])) {
408 self::getSession()->setStyleID(intval($_REQUEST['styleID']));
409 }
410
411 $styleHandler = StyleHandler::getInstance();
412 $styleHandler->changeStyle(self::getSession()->getStyleID());
413 }
414
415 /**
416 * Executes the blacklist.
417 */
418 protected function initBlacklist() {
419 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
420
421 if (defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES != '') {
422 if (!StringUtil::executeWordFilter(UserUtil::convertIPv6To4(self::getSession()->ipAddress), BLACKLIST_IP_ADDRESSES)) {
423 if ($isAjax) {
424 throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
425 }
426 else {
427 throw new PermissionDeniedException();
428 }
429 }
430 else if (!StringUtil::executeWordFilter(self::getSession()->ipAddress, BLACKLIST_IP_ADDRESSES)) {
431 if ($isAjax) {
432 throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
433 }
434 else {
435 throw new PermissionDeniedException();
436 }
437 }
438 }
439 if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS != '') {
440 if (!StringUtil::executeWordFilter(self::getSession()->userAgent, BLACKLIST_USER_AGENTS)) {
441 if ($isAjax) {
442 throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
443 }
444 else {
445 throw new PermissionDeniedException();
446 }
447 }
448 }
449 if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES != '') {
450 if (!StringUtil::executeWordFilter(@gethostbyaddr(self::getSession()->ipAddress), BLACKLIST_HOSTNAMES)) {
451 if ($isAjax) {
452 throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.ajax.error.permissionDenied'), AJAXException::INSUFFICIENT_PERMISSIONS);
453 }
454 else {
455 throw new PermissionDeniedException();
456 }
457 }
458 }
459
460 // handle banned users
461 if (self::getUser()->userID && self::getUser()->banned) {
462 if ($isAjax) {
463 throw new AJAXException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'), AJAXException::INSUFFICIENT_PERMISSIONS);
464 }
465 else {
466 self::$forceLogout = true;
467
468 // remove cookies
469 if (isset($_COOKIE[COOKIE_PREFIX.'userID'])) {
470 HeaderUtil::setCookie('userID', 0);
471 }
472 if (isset($_COOKIE[COOKIE_PREFIX.'password'])) {
473 HeaderUtil::setCookie('password', '');
474 }
475
476 throw new NamedUserException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
477 }
478 }
479 }
480
481 /**
482 * Initializes applications.
483 */
484 protected function initApplications() {
485 // step 1) load all applications
486 $loadedApplications = [];
487
488 // register WCF as application
489 self::$applications['wcf'] = ApplicationHandler::getInstance()->getApplicationByID(1);
490
491 if (!class_exists(WCFACP::class, false)) {
492 static::getTPL()->assign('baseHref', self::$applications['wcf']->getPageURL());
493 }
494
495 // start main application
496 $application = ApplicationHandler::getInstance()->getActiveApplication();
497 if ($application->packageID != 1) {
498 $loadedApplications[] = $this->loadApplication($application);
499
500 // register primary application
501 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
502 self::$applications[$abbreviation] = $application;
503 }
504
505 // start dependent applications
506 $applications = ApplicationHandler::getInstance()->getDependentApplications();
507 foreach ($applications as $application) {
508 if ($application->packageID == 1) {
509 // ignore WCF
510 continue;
511 }
512 else if ($application->isTainted) {
513 // ignore apps flagged for uninstallation
514 continue;
515 }
516
517 $loadedApplications[] = $this->loadApplication($application, true);
518 }
519
520 // step 2) run each application
521 if (!class_exists('wcf\system\WCFACP', false)) {
522 /** @var IApplication $application */
523 foreach ($loadedApplications as $application) {
524 $application->__run();
525 }
526
527 // refresh the session 1 minute before it expires
528 self::getTPL()->assign('__sessionKeepAlive', SESSION_TIMEOUT - 60);
529 }
530 }
531
532 /**
533 * Loads an application.
534 *
535 * @param Application $application
536 * @param boolean $isDependentApplication
537 * @return IApplication
538 * @throws SystemException
539 */
540 protected function loadApplication(Application $application, $isDependentApplication = false) {
541 $package = PackageCache::getInstance()->getPackage($application->packageID);
542 // package cache might be outdated
543 if ($package === null) {
544 $package = new Package($application->packageID);
545
546 // package cache is outdated, discard cache
547 if ($package->packageID) {
548 PackageEditor::resetCache();
549 }
550 else {
551 // package id is invalid
552 throw new SystemException("application identified by package id '".$application->packageID."' is unknown");
553 }
554 }
555
556 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
557 $packageDir = FileUtil::getRealPath(WCF_DIR.$package->packageDir);
558 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
559
560 $className = $abbreviation.'\system\\'.strtoupper($abbreviation).'Core';
561
562 // class was not found, possibly the app was moved, but `packageDir` has not been adjusted
563 if (!class_exists($className)) {
564 // check if both the Core and the app are on the same domain
565 $coreApp = ApplicationHandler::getInstance()->getApplicationByID(1);
566 if ($coreApp->domainName === $application->domainName) {
567 // resolve the relative path and use it to construct the autoload directory
568 $relativePath = FileUtil::getRelativePath($coreApp->domainPath, $application->domainPath);
569 if ($relativePath !== './') {
570 $packageDir = FileUtil::getRealPath(WCF_DIR.$relativePath);
571 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
572
573 if (class_exists($className)) {
574 // the class can now be found, update the `packageDir` value
575 (new PackageEditor($package))->update(['packageDir' => $relativePath]);
576 }
577 }
578 }
579 }
580
581 if (class_exists($className) && is_subclass_of($className, IApplication::class)) {
582 // include config file
583 $configPath = $packageDir . PackageInstallationDispatcher::CONFIG_FILE;
584 if (!file_exists($configPath)) {
585 Package::writeConfigFile($package->packageID);
586 }
587
588 if (file_exists($configPath)) {
589 require_once($configPath);
590 }
591 else {
592 throw new SystemException('Unable to load configuration for '.$package->package);
593 }
594
595 // register template path if not within ACP
596 if (!class_exists('wcf\system\WCFACP', false)) {
597 // add template path and abbreviation
598 static::getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
599 }
600 EmailTemplateEngine::getInstance()->addApplication($abbreviation, $packageDir . 'templates/');
601
602 // init application and assign it as template variable
603 self::$applicationObjects[$application->packageID] = call_user_func([$className, 'getInstance']);
604 static::getTPL()->assign('__'.$abbreviation, self::$applicationObjects[$application->packageID]);
605 EmailTemplateEngine::getInstance()->assign('__'.$abbreviation, self::$applicationObjects[$application->packageID]);
606 }
607 else {
608 unset(self::$autoloadDirectories[$abbreviation]);
609 throw new SystemException("Unable to run '".$package->package."', '".$className."' is missing or does not implement '".IApplication::class."'.");
610 }
611
612 // register template path in ACP
613 if (class_exists('wcf\system\WCFACP', false)) {
614 static::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
615 }
616 else if (!$isDependentApplication) {
617 // assign base tag
618 static::getTPL()->assign('baseHref', $application->getPageURL());
619 }
620
621 // register application
622 self::$applications[$abbreviation] = $application;
623
624 return self::$applicationObjects[$application->packageID];
625 }
626
627 /**
628 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
629 *
630 * @param Application $application
631 * @return IApplication
632 */
633 public static function getApplicationObject(Application $application) {
634 if (isset(self::$applicationObjects[$application->packageID])) {
635 return self::$applicationObjects[$application->packageID];
636 }
637
638 return null;
639 }
640
641 /**
642 * Returns the invoked application.
643 *
644 * @return Application
645 */
646 public static function getActiveApplication() {
647 return ApplicationHandler::getInstance()->getActiveApplication();
648 }
649
650 /**
651 * Loads an application on runtime, do not use this outside the package installation.
652 *
653 * @param integer $packageID
654 */
655 public static function loadRuntimeApplication($packageID) {
656 $package = new Package($packageID);
657 $application = new Application($packageID);
658
659 $abbreviation = Package::getAbbreviation($package->package);
660 $packageDir = FileUtil::getRealPath(WCF_DIR.$package->packageDir);
661 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
662 self::$applications[$abbreviation] = $application;
663 self::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
664 }
665
666 /**
667 * Initializes core object cache.
668 */
669 protected function initCoreObjects() {
670 // ignore core objects if installing WCF
671 if (PACKAGE_ID == 0) {
672 return;
673 }
674
675 self::$coreObjectCache = CoreObjectCacheBuilder::getInstance()->getData();
676 }
677
678 /**
679 * Assigns some default variables to the template engine.
680 */
681 protected function assignDefaultTemplateVariables() {
682 self::getTPL()->registerPrefilter(['event', 'hascontent', 'lang']);
683 self::getTPL()->assign([
684 '__wcf' => $this,
685 '__wcfVersion' => LAST_UPDATE_TIME // @deprecated 2.1, use LAST_UPDATE_TIME directly
686 ]);
687
688 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
689 // Execute background queue in this request, if it was requested and AJAX isn't used.
690 if (!$isAjax) {
691 if (self::getSession()->getVar('forceBackgroundQueuePerform')) {
692 self::getTPL()->assign([
693 'forceBackgroundQueuePerform' => true
694 ]);
695
696 self::getSession()->unregister('forceBackgroundQueuePerform');
697 }
698 }
699
700 EmailTemplateEngine::getInstance()->registerPrefilter(['event', 'hascontent', 'lang']);
701 EmailTemplateEngine::getInstance()->assign([
702 '__wcf' => $this
703 ]);
704 }
705
706 /**
707 * Wrapper for the getter methods of this class.
708 *
709 * @param string $name
710 * @return mixed value
711 * @throws SystemException
712 */
713 public function __get($name) {
714 $method = 'get'.ucfirst($name);
715 if (method_exists($this, $method)) {
716 return $this->$method();
717 }
718
719 throw new SystemException("method '".$method."' does not exist in class WCF");
720 }
721
722 /**
723 * Returns true if current application (WCF) is treated as active and was invoked directly.
724 *
725 * @return boolean
726 */
727 public function isActiveApplication() {
728 return (ApplicationHandler::getInstance()->getActiveApplication()->packageID == 1);
729 }
730
731 /**
732 * Changes the active language.
733 *
734 * @param integer $languageID
735 */
736 public static final function setLanguage($languageID) {
737 if (!$languageID || LanguageFactory::getInstance()->getLanguage($languageID) === null) {
738 $languageID = LanguageFactory::getInstance()->getDefaultLanguageID();
739 }
740
741 self::$languageObj = LanguageFactory::getInstance()->getLanguage($languageID);
742
743 // the template engine may not be available yet, usually happens when
744 // changing the user (and thus the language id) during session init
745 if (self::$tplObj !== null) {
746 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
747 EmailTemplateEngine::getInstance()->setLanguageID(self::getLanguage()->languageID);
748 }
749 }
750
751 /**
752 * Includes the required util or exception classes automatically.
753 *
754 * @param string $className
755 * @see spl_autoload_register()
756 */
757 public static final function autoload($className) {
758 $namespaces = explode('\\', $className);
759 if (count($namespaces) > 1) {
760 $applicationPrefix = array_shift($namespaces);
761 if ($applicationPrefix === '') {
762 $applicationPrefix = array_shift($namespaces);
763 }
764 if (isset(self::$autoloadDirectories[$applicationPrefix])) {
765 $classPath = self::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
766 if (file_exists($classPath)) {
767 require_once($classPath);
768 }
769 }
770 }
771 }
772
773 /**
774 * @inheritDoc
775 */
776 public final function __call($name, array $arguments) {
777 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
778 if (!method_exists($this, $name)) {
779 return self::__callStatic($name, $arguments);
780 }
781
782 return $this->$name($arguments);
783 }
784
785 /**
786 * Returns dynamically loaded core objects.
787 *
788 * @param string $name
789 * @param array $arguments
790 * @return object
791 * @throws SystemException
792 */
793 public static final function __callStatic($name, array $arguments) {
794 $className = preg_replace('~^get~', '', $name);
795
796 if (isset(self::$coreObject[$className])) {
797 return self::$coreObject[$className];
798 }
799
800 $objectName = self::getCoreObject($className);
801 if ($objectName === null) {
802 throw new SystemException("Core object '".$className."' is unknown.");
803 }
804
805 if (class_exists($objectName)) {
806 if (!is_subclass_of($objectName, SingletonFactory::class)) {
807 throw new ParentClassException($objectName, SingletonFactory::class);
808 }
809
810 self::$coreObject[$className] = call_user_func([$objectName, 'getInstance']);
811 return self::$coreObject[$className];
812 }
813 }
814
815 /**
816 * Searches for cached core object definition.
817 *
818 * @param string $className
819 * @return string
820 */
821 protected static final function getCoreObject($className) {
822 if (isset(self::$coreObjectCache[$className])) {
823 return self::$coreObjectCache[$className];
824 }
825
826 return null;
827 }
828
829 /**
830 * Returns true if the debug mode is enabled, otherwise false.
831 *
832 * @param boolean $ignoreACP
833 * @return boolean
834 */
835 public static function debugModeIsEnabled($ignoreACP = false) {
836 // ACP override
837 if (!$ignoreACP && self::$overrideDebugMode) {
838 return true;
839 }
840 else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE) {
841 return true;
842 }
843
844 return false;
845 }
846
847 /**
848 * Returns true if benchmarking is enabled, otherwise false.
849 *
850 * @return boolean
851 */
852 public static function benchmarkIsEnabled() {
853 // benchmarking is enabled by default
854 if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK) return true;
855 return false;
856 }
857
858 /**
859 * Returns domain path for given application.
860 *
861 * @param string $abbreviation
862 * @return string
863 */
864 public static function getPath($abbreviation = 'wcf') {
865 // workaround during WCFSetup
866 if (!PACKAGE_ID) {
867 return '../';
868 }
869
870 if (!isset(self::$applications[$abbreviation])) {
871 $abbreviation = 'wcf';
872 }
873
874 return self::$applications[$abbreviation]->getPageURL();
875 }
876
877 /**
878 * Returns the domain path for the currently active application,
879 * used to avoid CORS requests.
880 *
881 * @return string
882 */
883 public static function getActivePath() {
884 if (!PACKAGE_ID) {
885 return self::getPath();
886 }
887
888 return self::getPath(ApplicationHandler::getInstance()->getAbbreviation(ApplicationHandler::getInstance()->getActiveApplication()->packageID));
889 }
890
891 /**
892 * Returns a fully qualified anchor for current page.
893 *
894 * @param string $fragment
895 * @return string
896 */
897 public function getAnchor($fragment) {
898 return StringUtil::encodeHTML(self::getRequestURI() . '#' . $fragment);
899 }
900
901 /**
902 * Returns the currently active page or null if unknown.
903 *
904 * @return Page|null
905 */
906 public static function getActivePage() {
907 if (self::getActiveRequest() === null) {
908 return null;
909 }
910
911 if (self::getActiveRequest()->getClassName() === CmsPage::class) {
912 $metaData = self::getActiveRequest()->getMetaData();
913 if (isset($metaData['cms'])) {
914 return PageCache::getInstance()->getPage($metaData['cms']['pageID']);
915 }
916
917 return null;
918 }
919
920 return PageCache::getInstance()->getPageByController(self::getActiveRequest()->getClassName());
921 }
922
923 /**
924 * Returns the currently active request.
925 *
926 * @return Request
927 */
928 public static function getActiveRequest() {
929 return RequestHandler::getInstance()->getActiveRequest();
930 }
931
932 /**
933 * Returns the URI of the current page.
934 *
935 * @return string
936 */
937 public static function getRequestURI() {
938 return preg_replace('~^(https?://[^/]+)(?:/.*)?$~', '$1', self::getTPL()->get('baseHref')) . $_SERVER['REQUEST_URI'];
939 }
940
941 /**
942 * Resets Zend Opcache cache if installed and enabled.
943 *
944 * @param string $script
945 */
946 public static function resetZendOpcache($script = '') {
947 if (self::$zendOpcacheEnabled === null) {
948 self::$zendOpcacheEnabled = false;
949
950 if (extension_loaded('Zend Opcache') && @ini_get('opcache.enable')) {
951 self::$zendOpcacheEnabled = true;
952 }
953
954 }
955
956 if (self::$zendOpcacheEnabled) {
957 if (empty($script)) {
958 opcache_reset();
959 }
960 else {
961 opcache_invalidate($script, true);
962 }
963 }
964 }
965
966 /**
967 * Returns style handler.
968 *
969 * @return StyleHandler
970 */
971 public function getStyleHandler() {
972 return StyleHandler::getInstance();
973 }
974
975 /**
976 * Returns box handler.
977 *
978 * @return BoxHandler
979 * @since 3.0
980 */
981 public function getBoxHandler() {
982 return BoxHandler::getInstance();
983 }
984
985 /**
986 * Returns number of available updates.
987 *
988 * @return integer
989 */
990 public function getAvailableUpdates() {
991 $data = PackageUpdateCacheBuilder::getInstance()->getData();
992 return $data['updates'];
993 }
994
995 /**
996 * Returns a 8 character prefix for editor autosave.
997 *
998 * @return string
999 */
1000 public function getAutosavePrefix() {
1001 return substr(sha1(preg_replace('~^https~', 'http', self::getPath())), 0, 8);
1002 }
1003
1004 /**
1005 * Returns the favicon URL or a base64 encoded image.
1006 *
1007 * @return string
1008 */
1009 public function getFavicon() {
1010 $activeApplication = ApplicationHandler::getInstance()->getActiveApplication();
1011 $wcf = ApplicationHandler::getInstance()->getWCF();
1012 $favicon = StyleHandler::getInstance()->getStyle()->getRelativeFavicon();
1013
1014 if ($activeApplication->domainName !== $wcf->domainName) {
1015 if (file_exists(WCF_DIR.$favicon)) {
1016 $favicon = file_get_contents(WCF_DIR.$favicon);
1017
1018 return 'data:image/x-icon;base64,' . base64_encode($favicon);
1019 }
1020 }
1021
1022 return self::getPath() . $favicon;
1023 }
1024
1025 /**
1026 * Returns true if the desktop notifications should be enabled.
1027 *
1028 * @return boolean
1029 */
1030 public function useDesktopNotifications() {
1031 if (!ENABLE_DESKTOP_NOTIFICATIONS) {
1032 return false;
1033 }
1034 else if (ApplicationHandler::getInstance()->isMultiDomainSetup()) {
1035 $application = ApplicationHandler::getInstance()->getApplicationByID(DESKTOP_NOTIFICATION_PACKAGE_ID);
1036 // mismatch, default to Core
1037 if ($application === null) $application = ApplicationHandler::getInstance()->getApplicationByID(1);
1038
1039 $currentApplication = ApplicationHandler::getInstance()->getActiveApplication();
1040 if ($currentApplication->domainName != $application->domainName) {
1041 // different domain
1042 return false;
1043 }
1044 }
1045
1046 return true;
1047 }
1048
1049 /**
1050 * Returns true if currently active request represents the landing page.
1051 *
1052 * @return boolean
1053 */
1054 public static function isLandingPage() {
1055 if (self::getActiveRequest() === null) {
1056 return false;
1057 }
1058
1059 return self::getActiveRequest()->isLandingPage();
1060 }
1061
1062 /**
1063 * Returns true if the given API version is currently supported.
1064 *
1065 * @param integer $apiVersion
1066 * @return boolean
1067 */
1068 public static function isSupportedApiVersion($apiVersion) {
1069 return ($apiVersion == WSC_API_VERSION) || in_array($apiVersion, self::$supportedLegacyApiVersions);
1070 }
1071
1072 /**
1073 * Returns the list of supported legacy API versions.
1074 *
1075 * @return integer[]
1076 */
1077 public static function getSupportedLegacyApiVersions() {
1078 return self::$supportedLegacyApiVersions;
1079 }
1080
1081 /**
1082 * Initialises the cronjobs.
1083 */
1084 protected function initCronjobs() {
1085 if (PACKAGE_ID) {
1086 self::getTPL()->assign('executeCronjobs', CronjobScheduler::getInstance()->getNextExec() < TIME_NOW && defined('OFFLINE') && !OFFLINE);
1087 }
1088 }
1089 }