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