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