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