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\system\application\ApplicationHandler
;
9 use wcf\system\cache\builder\CoreObjectCacheBuilder
;
10 use wcf\system\cache\builder\PackageUpdateCacheBuilder
;
11 use wcf\system\cronjob\CronjobScheduler
;
12 use wcf\system\event\EventHandler
;
13 use wcf\system\exception\AJAXException
;
14 use wcf\system\exception\IPrintableException
;
15 use wcf\system\exception\NamedUserException
;
16 use wcf\system\exception\PermissionDeniedException
;
17 use wcf\system\exception\SystemException
;
18 use wcf\system\language\LanguageFactory
;
19 use wcf\system\package\PackageInstallationDispatcher
;
20 use wcf\system\request\RouteHandler
;
21 use wcf\system\session\SessionFactory
;
22 use wcf\system\session\SessionHandler
;
23 use wcf\system\style\StyleHandler
;
24 use wcf\system\template\TemplateEngine
;
25 use wcf\system\user\storage\UserStorageHandler
;
26 use wcf\util\ArrayUtil
;
27 use wcf\util\ClassUtil
;
28 use wcf\util\FileUtil
;
29 use wcf\util\StringUtil
;
30 use wcf\util\UserUtil
;
32 // try to set a time-limit to infinite
35 // fix timezone warning issue
36 if (!@ini_get
('date.timezone')) {
37 @date_default_timezone_set
('Europe/London');
40 // define current wcf version
41 define('WCF_VERSION', '2.1.21 pl 1 (Typhoon)');
43 // define current unix timestamp
44 define('TIME_NOW', time());
47 if (!defined('NO_IMPORTS')) {
48 require_once(WCF_DIR
.'lib/core.functions.php');
52 * WCF is the central class for the community framework.
53 * It holds the database connection, access to template and language engine.
56 * @copyright 2001-2016 WoltLab GmbH
57 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
58 * @package com.woltlab.wcf
60 * @category Community Framework
64 * list of currently loaded applications
65 * @var array<\wcf\data\application\Application>
67 protected static $applications = array();
70 * list of currently loaded application objects
71 * @var array<\wcf\system\application\IApplication>
73 protected static $applicationObjects = array();
76 * list of autoload directories
79 protected static $autoloadDirectories = array();
82 * list of unique instances of each core object
83 * @var array<\wcf\system\SingletonFactory>
85 protected static $coreObject = array();
88 * list of cached core objects
91 protected static $coreObjectCache = array();
95 * @var \wcf\system\database\Database
97 protected static $dbObj = null;
101 * @var \wcf\data\language\Language
103 protected static $languageObj = null;
106 * overrides disabled debug mode
109 protected static $overrideDebugMode = false;
113 * @var \wcf\system\session\SessionHandler
115 protected static $sessionObj = null;
119 * @var \wcf\system\template\TemplateEngine
121 protected static $tplObj = null;
124 * true if Zend Opcache is loaded and enabled
127 protected static $zendOpcacheEnabled = null;
130 * Calls all init functions of the WCF class.
132 public function __construct() {
133 // add autoload directory
134 self
::$autoloadDirectories['wcf'] = WCF_DIR
. 'lib/';
136 // define tmp directory
137 if (!defined('TMP_DIR')) define('TMP_DIR', FileUtil
::getTempFolder());
139 // start initialization
140 $this->initMagicQuotes();
142 $this->loadOptions();
143 $this->initSession();
144 $this->initLanguage();
146 $this->initCronjobs();
147 $this->initCoreObjects();
148 $this->initApplications();
149 $this->initBlacklist();
151 EventHandler
::getInstance()->fireAction($this, 'initialized');
155 * Replacement of the "__destruct()" method.
156 * Seems that under specific conditions (windows) the destructor is not called automatically.
157 * So we use the php register_shutdown_function to register an own destructor method.
158 * Flushs the output, closes caches and updates the session.
160 public static function destruct() {
162 // database has to be initialized
163 if (!is_object(self
::$dbObj)) return;
166 if (ob_get_level() && ini_get('output_handler')) {
174 if (is_object(self
::getSession())) {
175 self
::getSession()->update();
178 // execute shutdown actions of user storage handler
179 UserStorageHandler
::getInstance()->shutdown();
181 catch (\Exception
$exception) {
182 die("<pre>WCF::destruct() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
187 * Removes slashes in superglobal gpc data arrays if 'magic quotes gpc' is enabled.
189 protected function initMagicQuotes() {
190 if (function_exists('get_magic_quotes_gpc')) {
191 if (@get_magic_quotes_gpc
()) {
192 if (!empty($_REQUEST)) {
193 $_REQUEST = ArrayUtil
::stripslashes($_REQUEST);
195 if (!empty($_POST)) {
196 $_POST = ArrayUtil
::stripslashes($_POST);
199 $_GET = ArrayUtil
::stripslashes($_GET);
201 if (!empty($_COOKIE)) {
202 $_COOKIE = ArrayUtil
::stripslashes($_COOKIE);
204 if (!empty($_FILES)) {
205 foreach ($_FILES as $name => $attributes) {
206 foreach ($attributes as $key => $value) {
207 if ($key != 'tmp_name') {
208 $_FILES[$name][$key] = ArrayUtil
::stripslashes($value);
216 if (function_exists('set_magic_quotes_runtime')) {
217 @set_magic_quotes_runtime
(0);
222 * Returns the database object.
224 * @return \wcf\system\database\Database
226 public static final function getDB() {
231 * Returns the session object.
233 * @return \wcf\system\session\SessionHandler
235 public static final function getSession() {
236 return self
::$sessionObj;
240 * Returns the user object.
242 * @return \wcf\data\user\User
244 public static final function getUser() {
245 return self
::getSession()->getUser();
249 * Returns the language object.
251 * @return \wcf\data\language\Language
253 public static final function getLanguage() {
254 return self
::$languageObj;
258 * Returns the template object.
260 * @return \wcf\system\template\TemplateEngine
262 public static final function getTPL() {
263 return self
::$tplObj;
267 * Calls the show method on the given exception.
269 * @param \Exception $e
271 public static final function handleException($e) {
273 if (!($e instanceof \Exception
)) throw $e;
275 if ($e instanceof IPrintableException
) {
281 self
::handleException(new SystemException($e->getMessage(), $e->getCode(), '', $e));
283 catch (\Throwable
$exception) {
284 die("<pre>WCF::handleException() Unhandled exception: ".$exception->getMessage()."\n\n".preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $exception->getTraceAsString()));
286 catch (\Exception
$exception) {
287 die("<pre>WCF::handleException() Unhandled exception: ".$exception->getMessage()."\n\n".preg_replace('/Database->__construct\(.*\)/', 'Database->__construct(...)', $exception->getTraceAsString()));
292 * Catches php errors and throws instead a system exception.
294 * @param integer $errorNo
295 * @param string $message
296 * @param string $filename
297 * @param integer $lineNo
299 public static final function handleError($errorNo, $message, $filename, $lineNo) {
300 if (error_reporting() != 0) {
303 case 2: $type = 'warning';
305 case 8: $type = 'notice';
309 throw new SystemException('PHP '.$type.' in file '.$filename.' ('.$lineNo.'): '.$message, 0);
314 * Loads the database configuration and creates a new connection to the database.
316 protected function initDB() {
318 $dbHost = $dbUser = $dbPassword = $dbName = '';
320 $dbClass = 'wcf\system\database\MySQLDatabase';
321 require(WCF_DIR
.'config.inc.php');
323 // create database connection
324 self
::$dbObj = new $dbClass($dbHost, $dbUser, $dbPassword, $dbName, $dbPort);
328 * Loads the options file, automatically created if not exists.
330 protected function loadOptions() {
331 $filename = WCF_DIR
.'options.inc.php';
333 // create options file if doesn't exist
334 if (!file_exists($filename) ||
filemtime($filename) <= 1) {
335 OptionEditor
::rebuild();
337 require_once($filename);
341 * Starts the session system.
343 protected function initSession() {
344 $factory = new SessionFactory();
347 self
::$sessionObj = SessionHandler
::getInstance();
351 * Initialises the language engine.
353 protected function initLanguage() {
354 if (isset($_GET['l']) && !self
::getUser()->userID
) {
355 self
::getSession()->setLanguageID(intval($_GET['l']));
359 mb_internal_encoding('UTF-8');
360 if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
364 self
::$languageObj = LanguageFactory
::getInstance()->getUserLanguage(self
::getSession()->getLanguageID());
368 * Initialises the template engine.
370 protected function initTPL() {
371 self
::$tplObj = TemplateEngine
::getInstance();
372 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
373 $this->assignDefaultTemplateVariables();
379 * Initializes the user's style.
381 protected function initStyle() {
382 if (isset($_REQUEST['styleID'])) {
383 self
::getSession()->setStyleID(intval($_REQUEST['styleID']));
386 StyleHandler
::getInstance()->changeStyle(self
::getSession()->getStyleID());
390 * Executes the blacklist.
392 protected function initBlacklist() {
393 $isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
395 if (defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES
!= '') {
396 if (!StringUtil
::executeWordFilter(UserUtil
::convertIPv6To4(self
::getSession()->ipAddress
), BLACKLIST_IP_ADDRESSES
)) {
398 throw new AJAXException(self
::getLanguage()->get('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
401 throw new PermissionDeniedException();
404 else if (!StringUtil
::executeWordFilter(self
::getSession()->ipAddress
, BLACKLIST_IP_ADDRESSES
)) {
406 throw new AJAXException(self
::getLanguage()->get('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
409 throw new PermissionDeniedException();
413 if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS
!= '') {
414 if (!StringUtil
::executeWordFilter(self
::getSession()->userAgent
, BLACKLIST_USER_AGENTS
)) {
416 throw new AJAXException(self
::getLanguage()->get('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
419 throw new PermissionDeniedException();
423 if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES
!= '') {
424 if (!StringUtil
::executeWordFilter(@gethostbyaddr
(self
::getSession()->ipAddress
), BLACKLIST_HOSTNAMES
)) {
426 throw new AJAXException(self
::getLanguage()->get('wcf.ajax.error.permissionDenied'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
429 throw new PermissionDeniedException();
434 // handle banned users
435 if (self
::getUser()->userID
&& self
::getUser()->banned
) {
437 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
440 throw new NamedUserException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
446 * Initializes applications.
448 protected function initApplications() {
449 // step 1) load all applications
450 $loadedApplications = array();
452 // register WCF as application
453 self
::$applications['wcf'] = ApplicationHandler
::getInstance()->getWCF();
455 if (PACKAGE_ID
== 1) {
459 // start main application
460 $application = ApplicationHandler
::getInstance()->getActiveApplication();
461 $loadedApplications[] = $this->loadApplication($application);
463 // register primary application
464 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
465 self
::$applications[$abbreviation] = $application;
467 // start dependent applications
468 $applications = ApplicationHandler
::getInstance()->getDependentApplications();
469 foreach ($applications as $application) {
470 $loadedApplications[] = $this->loadApplication($application, true);
473 // step 2) run each application
474 if (!class_exists('wcf\system\WCFACP', false)) {
475 foreach ($loadedApplications as $application) {
476 $application->__run();
479 // refresh the session 1 minute before it expires
480 self
::getTPL()->assign('__sessionKeepAlive', (SESSION_TIMEOUT
- 60));
485 * Loads an application.
487 * @param \wcf\data\application\Application $application
488 * @param boolean $isDependentApplication
489 * @return \wcf\system\application\IApplication
491 protected function loadApplication(Application
$application, $isDependentApplication = false) {
492 $applicationObject = null;
493 $package = PackageCache
::getInstance()->getPackage($application->packageID
);
494 // package cache might be outdated
495 if ($package === null) {
496 $package = new Package($application->packageID
);
498 // package cache is outdated, discard cache
499 if ($package->packageID
) {
500 PackageEditor
::resetCache();
503 // package id is invalid
504 throw new SystemException("application identified by package id '".$application->packageID
."' is unknown");
508 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
509 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
510 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
512 $className = $abbreviation.'\system\\'.strtoupper($abbreviation).'Core';
513 if (class_exists($className) && ClassUtil
::isInstanceOf($className, 'wcf\system\application\IApplication')) {
514 // include config file
515 $configPath = $packageDir . PackageInstallationDispatcher
::CONFIG_FILE
;
516 if (file_exists($configPath)) {
517 require_once($configPath);
520 throw new SystemException('Unable to load configuration for '.$package->package
);
523 // register template path if not within ACP
524 if (!class_exists('wcf\system\WCFACP', false)) {
525 // add template path and abbreviation
526 $this->getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
529 // init application and assign it as template variable
530 self
::$applicationObjects[$application->packageID
] = call_user_func(array($className, 'getInstance'));
531 $this->getTPL()->assign('__'.$abbreviation, self
::$applicationObjects[$application->packageID
]);
534 unset(self
::$autoloadDirectories[$abbreviation]);
535 throw new SystemException("Unable to run '".$package->package
."', '".$className."' is missing or does not implement 'wcf\system\application\IApplication'.");
538 // register template path in ACP
539 if (class_exists('wcf\system\WCFACP', false)) {
540 $this->getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
542 else if (!$isDependentApplication) {
544 $this->getTPL()->assign('baseHref', $application->getPageURL());
547 // register application
548 self
::$applications[$abbreviation] = $application;
550 return self
::$applicationObjects[$application->packageID
];
554 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
556 * @param \wcf\data\application\Application $application
557 * @return \wcf\system\application\IApplication
559 public static function getApplicationObject(Application
$application) {
560 if (isset(self
::$applicationObjects[$application->packageID
])) {
561 return self
::$applicationObjects[$application->packageID
];
568 * Loads an application on runtime, do not use this outside the package installation.
570 * @param integer $packageID
572 public static function loadRuntimeApplication($packageID) {
573 $package = new Package($packageID);
574 $application = new Application($packageID);
576 $abbreviation = Package
::getAbbreviation($package->package
);
577 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
578 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
579 self
::$applications[$abbreviation] = $application;
580 self
::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
584 * Initializes core object cache.
586 protected function initCoreObjects() {
587 // ignore core objects if installing WCF
588 if (PACKAGE_ID
== 0) {
592 self
::$coreObjectCache = CoreObjectCacheBuilder
::getInstance()->getData();
596 * Assigns some default variables to the template engine.
598 protected function assignDefaultTemplateVariables() {
599 self
::getTPL()->registerPrefilter(array('event', 'hascontent', 'lang'));
600 self
::getTPL()->assign(array(
602 '__wcfVersion' => LAST_UPDATE_TIME
// @deprecated since 2.1, use LAST_UPDATE_TIME directly
607 * Wrapper for the getter methods of this class.
609 * @param string $name
610 * @return mixed value
612 public function __get($name) {
613 $method = 'get'.ucfirst($name);
614 if (method_exists($this, $method)) {
615 return $this->$method();
618 throw new SystemException("method '".$method."' does not exist in class WCF");
622 * Changes the active language.
624 * @param integer $languageID
626 public static final function setLanguage($languageID) {
627 self
::$languageObj = LanguageFactory
::getInstance()->getLanguage($languageID);
628 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
632 * Includes the required util or exception classes automatically.
634 * @param string $className
635 * @see spl_autoload_register()
637 public static final function autoload($className) {
638 $namespaces = explode('\\', $className);
639 if (count($namespaces) > 1) {
640 $applicationPrefix = array_shift($namespaces);
641 if ($applicationPrefix === '') {
642 $applicationPrefix = array_shift($namespaces);
644 if (isset(self
::$autoloadDirectories[$applicationPrefix])) {
645 $classPath = self
::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
646 if (file_exists($classPath)) {
647 require_once($classPath);
654 * @see \wcf\system\WCF::__callStatic()
656 public final function __call($name, array $arguments) {
657 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
658 if (!method_exists($this, $name)) {
659 return self
::__callStatic($name, $arguments);
662 return $this->$name($arguments);
666 * Returns dynamically loaded core objects.
668 * @param string $name
669 * @param array $arguments
671 public static final function __callStatic($name, array $arguments) {
672 $className = preg_replace('~^get~', '', $name);
674 if (isset(self
::$coreObject[$className])) {
675 return self
::$coreObject[$className];
678 $objectName = self
::getCoreObject($className);
679 if ($objectName === null) {
680 throw new SystemException("Core object '".$className."' is unknown.");
683 if (class_exists($objectName)) {
684 if (!(ClassUtil
::isInstanceOf($objectName, 'wcf\system\SingletonFactory'))) {
685 throw new SystemException("class '".$objectName."' does not implement the interface 'SingletonFactory'");
688 self
::$coreObject[$className] = call_user_func(array($objectName, 'getInstance'));
689 return self
::$coreObject[$className];
694 * Searches for cached core object definition.
696 * @param string $className
699 protected static final function getCoreObject($className) {
700 if (isset(self
::$coreObjectCache[$className])) {
701 return self
::$coreObjectCache[$className];
708 * Returns true if the debug mode is enabled, otherwise false.
710 * @param boolean $ignoreACP
713 public static function debugModeIsEnabled($ignoreACP = false) {
715 if (!$ignoreACP && self
::$overrideDebugMode) {
718 else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE
) {
726 * Returns true if benchmarking is enabled, otherwise false.
730 public static function benchmarkIsEnabled() {
731 // benchmarking is enabled by default
732 if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK
) return true;
737 * Returns domain path for given application.
739 * @param string $abbreviation
742 public static function getPath($abbreviation = 'wcf') {
743 // workaround during WCFSetup
748 if (!isset(self
::$applications[$abbreviation])) {
749 $abbreviation = 'wcf';
752 return self
::$applications[$abbreviation]->getPageURL();
756 * Returns a fully qualified anchor for current page.
758 * @param string $fragment
761 public function getAnchor($fragment) {
762 return StringUtil
::encodeHTML(self
::getRequestURI() . '#' . $fragment);
766 * Returns the URI of the current page.
770 public static function getRequestURI() {
771 if (URL_LEGACY_MODE
) {
772 // resolve path and query components
773 $scriptName = $_SERVER['SCRIPT_NAME'];
774 $pathInfo = RouteHandler
::getPathInfo();
775 if (empty($pathInfo)) {
776 // bug fix if URL omits script name and path
777 $scriptName = substr($scriptName, 0, strrpos($scriptName, '/'));
780 $path = str_replace('/index.php', '', str_replace($scriptName, '', $_SERVER['REQUEST_URI']));
781 if (!StringUtil
::isUTF8($path)) {
782 $path = StringUtil
::convertEncoding('ISO-8859-1', 'UTF-8', $path);
784 $path = FileUtil
::removeLeadingSlash($path);
785 $baseHref = self
::getTPL()->get('baseHref');
787 if (!empty($path) && mb_strpos($path, '?') !== 0) {
788 $baseHref .= 'index.php/';
791 return $baseHref . $path;
794 $url = preg_replace('~^(https?://[^/]+)(?:/.*)?$~', '$1', self
::getTPL()->get('baseHref'));
795 $url .= $_SERVER['REQUEST_URI'];
802 * Resets Zend Opcache cache if installed and enabled.
804 * @param string $script
806 public static function resetZendOpcache($script = '') {
807 if (self
::$zendOpcacheEnabled === null) {
808 self
::$zendOpcacheEnabled = false;
810 if (extension_loaded('Zend Opcache') && @ini_get
('opcache.enable')) {
811 self
::$zendOpcacheEnabled = true;
816 if (self
::$zendOpcacheEnabled) {
817 if (empty($script)) {
821 opcache_invalidate($script, true);
827 * Returns style handler.
829 * @return \wcf\system\style\StyleHandler
831 public function getStyleHandler() {
832 return StyleHandler
::getInstance();
836 * Returns number of available updates.
840 public function getAvailableUpdates() {
841 $data = PackageUpdateCacheBuilder
::getInstance()->getData();
842 return $data['updates'];
846 * Returns a 8 character prefix for editor autosave.
850 public function getAutosavePrefix() {
851 return substr(sha1(preg_replace('~^https~', 'http', self
::getPath())), 0, 8);
855 * Returns the favicon URL or a base64 encoded image.
859 public function getFavicon() {
860 $activeApplication = ApplicationHandler
::getInstance()->getActiveApplication();
861 $wcf = ApplicationHandler
::getInstance()->getWCF();
863 if ($activeApplication->domainName
!== $wcf->domainName
) {
864 if (file_exists(WCF_DIR
.'images/favicon.ico')) {
865 $favicon = file_get_contents(WCF_DIR
.'images/favicon.ico');
867 return 'data:image/x-icon;base64,' . base64_encode($favicon);
871 return self
::getPath() . 'images/favicon.ico';
875 * Initialises the cronjobs.
877 protected function initCronjobs() {
879 self
::getTPL()->assign('executeCronjobs', (CronjobScheduler
::getInstance()->getNextExec() < TIME_NOW
&& defined('OFFLINE') && !OFFLINE
));