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