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
;
31 // try to set a time-limit to infinite
34 // fix timezone warning issue
35 if (!@ini_get
('date.timezone')) {
36 @date_default_timezone_set
('Europe/London');
39 // define current wcf version
40 define('WCF_VERSION', '2.1.0 Alpha 1 (Typhoon)');
42 // define current unix timestamp
43 define('TIME_NOW', time());
46 if (!defined('NO_IMPORTS')) {
47 require_once(WCF_DIR
.'lib/core.functions.php');
51 * WCF is the central class for the community framework.
52 * It holds the database connection, access to template and language engine.
55 * @copyright 2001-2014 WoltLab GmbH
56 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
57 * @package com.woltlab.wcf
59 * @category Community Framework
63 * list of currently loaded applications
64 * @var array<\wcf\data\application\Application>
66 protected static $applications = array();
69 * list of currently loaded application objects
70 * @var array<\wcf\system\application\IApplication>
72 protected static $applicationObjects = array();
75 * list of autoload directories
78 protected static $autoloadDirectories = array();
81 * list of unique instances of each core object
82 * @var array<\wcf\system\SingletonFactory>
84 protected static $coreObject = array();
87 * list of cached core objects
90 protected static $coreObjectCache = array();
94 * @var \wcf\system\database\Database
96 protected static $dbObj = null;
100 * @var \wcf\system\language\Language
102 protected static $languageObj = null;
105 * overrides disabled debug mode
108 protected static $overrideDebugMode = false;
112 * @var \wcf\system\session\SessionHandler
114 protected static $sessionObj = null;
118 * @var \wcf\system\template\TemplateEngine
120 protected static $tplObj = null;
123 * true if Zend Opcache is loaded and enabled
126 protected static $zendOpcacheEnabled = null;
129 * Calls all init functions of the WCF class.
131 public function __construct() {
132 // add autoload directory
133 self
::$autoloadDirectories['wcf'] = WCF_DIR
. 'lib/';
135 // define tmp directory
136 if (!defined('TMP_DIR')) define('TMP_DIR', FileUtil
::getTempFolder());
138 // start initialization
139 $this->initMagicQuotes();
141 $this->loadOptions();
142 $this->initSession();
143 $this->initLanguage();
145 $this->initCronjobs();
146 $this->initCoreObjects();
147 $this->initApplications();
148 $this->initBlacklist();
150 EventHandler
::getInstance()->fireAction($this, 'initialized');
154 * Replacement of the "__destruct()" method.
155 * Seems that under specific conditions (windows) the destructor is not called automatically.
156 * So we use the php register_shutdown_function to register an own destructor method.
157 * Flushs the output, closes caches and updates the session.
159 public static function destruct() {
161 // database has to be initialized
162 if (!is_object(self
::$dbObj)) return;
165 if (ob_get_level() && ini_get('output_handler')) {
173 if (is_object(self
::getSession())) {
174 self
::getSession()->update();
177 // execute shutdown actions of user storage handler
178 UserStorageHandler
::getInstance()->shutdown();
180 catch (\Exception
$exception) {
181 die("<pre>WCF::destruct() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
186 * Removes slashes in superglobal gpc data arrays if 'magic quotes gpc' is enabled.
188 protected function initMagicQuotes() {
189 if (function_exists('get_magic_quotes_gpc')) {
190 if (@get_magic_quotes_gpc
()) {
191 if (!empty($_REQUEST)) {
192 $_REQUEST = ArrayUtil
::stripslashes($_REQUEST);
194 if (!empty($_POST)) {
195 $_POST = ArrayUtil
::stripslashes($_POST);
198 $_GET = ArrayUtil
::stripslashes($_GET);
200 if (!empty($_COOKIE)) {
201 $_COOKIE = ArrayUtil
::stripslashes($_COOKIE);
203 if (!empty($_FILES)) {
204 foreach ($_FILES as $name => $attributes) {
205 foreach ($attributes as $key => $value) {
206 if ($key != 'tmp_name') {
207 $_FILES[$name][$key] = ArrayUtil
::stripslashes($value);
215 if (function_exists('set_magic_quotes_runtime')) {
216 @set_magic_quotes_runtime
(0);
221 * Returns the database object.
223 * @return \wcf\system\database\Database
225 public static final function getDB() {
230 * Returns the session object.
232 * @return \wcf\system\session\SessionHandler
234 public static final function getSession() {
235 return self
::$sessionObj;
239 * Returns the user object.
241 * @return \wcf\data\user\User
243 public static final function getUser() {
244 return self
::getSession()->getUser();
248 * Returns the language object.
250 * @return \wcf\data\language\Language
252 public static final function getLanguage() {
253 return self
::$languageObj;
257 * Returns the template object.
259 * @return \wcf\system\template\TemplateEngine
261 public static final function getTPL() {
262 return self
::$tplObj;
266 * Calls the show method on the given exception.
268 * @param \Exception $e
270 public static final function handleException(\Exception
$e) {
272 if ($e instanceof IPrintableException
) {
278 self
::handleException(new SystemException($e->getMessage(), $e->getCode(), '', $e));
280 catch (\Exception
$exception) {
281 die("<pre>WCF::handleException() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
286 * Catches php errors and throws instead a system exception.
288 * @param integer $errorNo
289 * @param string $message
290 * @param string $filename
291 * @param integer $lineNo
293 public static final function handleError($errorNo, $message, $filename, $lineNo) {
294 if (error_reporting() != 0) {
297 case 2: $type = 'warning';
299 case 8: $type = 'notice';
303 throw new SystemException('PHP '.$type.' in file '.$filename.' ('.$lineNo.'): '.$message, 0);
308 * Loads the database configuration and creates a new connection to the database.
310 protected function initDB() {
312 $dbHost = $dbUser = $dbPassword = $dbName = '';
314 $dbClass = 'wcf\system\database\MySQLDatabase';
315 require(WCF_DIR
.'config.inc.php');
317 // create database connection
318 self
::$dbObj = new $dbClass($dbHost, $dbUser, $dbPassword, $dbName, $dbPort);
322 * Loads the options file, automatically created if not exists.
324 protected function loadOptions() {
325 $filename = WCF_DIR
.'options.inc.php';
327 // create options file if doesn't exist
328 if (!file_exists($filename) ||
filemtime($filename) <= 1) {
329 OptionEditor
::rebuild();
331 require_once($filename);
335 * Starts the session system.
337 protected function initSession() {
338 $factory = new SessionFactory();
341 self
::$sessionObj = SessionHandler
::getInstance();
345 * Initialises the language engine.
347 protected function initLanguage() {
348 if (isset($_GET['l']) && !self
::getUser()->userID
) {
349 self
::getSession()->setLanguageID(intval($_GET['l']));
353 mb_internal_encoding('UTF-8');
354 if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
358 self
::$languageObj = LanguageFactory
::getInstance()->getUserLanguage(self
::getSession()->getLanguageID());
362 * Initialises the template engine.
364 protected function initTPL() {
365 self
::$tplObj = TemplateEngine
::getInstance();
366 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
367 $this->assignDefaultTemplateVariables();
373 * Initializes the user's style.
375 protected function initStyle() {
376 if (isset($_REQUEST['styleID'])) {
377 self
::getSession()->setStyleID(intval($_REQUEST['styleID']));
380 StyleHandler
::getInstance()->changeStyle(self
::getSession()->getStyleID());
384 * Executes the blacklist.
386 protected function initBlacklist() {
387 if (defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES
!= '') {
388 if (!StringUtil
::executeWordFilter(self
::getSession()->ipAddress
, BLACKLIST_IP_ADDRESSES
)) {
389 throw new PermissionDeniedException();
392 if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS
!= '') {
393 if (!StringUtil
::executeWordFilter(self
::getSession()->userAgent
, BLACKLIST_USER_AGENTS
)) {
394 throw new PermissionDeniedException();
397 if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES
!= '') {
398 if (!StringUtil
::executeWordFilter(@gethostbyaddr
(self
::getSession()->ipAddress
), BLACKLIST_HOSTNAMES
)) {
399 throw new PermissionDeniedException();
403 // handle banned users
404 if (self
::getUser()->userID
&& self
::getUser()->banned
) {
405 if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
406 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
409 throw new NamedUserException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
415 * Initializes applications.
417 protected function initApplications() {
418 // step 1) load all applications
419 $loadedApplications = array();
421 // register WCF as application
422 self
::$applications['wcf'] = ApplicationHandler
::getInstance()->getWCF();
424 if (PACKAGE_ID
== 1) {
428 // start main application
429 $application = ApplicationHandler
::getInstance()->getActiveApplication();
430 $loadedApplications[] = $this->loadApplication($application);
432 // register primary application
433 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
434 self
::$applications[$abbreviation] = $application;
436 // start dependent applications
437 $applications = ApplicationHandler
::getInstance()->getDependentApplications();
438 foreach ($applications as $application) {
439 $loadedApplications[] = $this->loadApplication($application, true);
442 // step 2) run each application
443 if (!class_exists('wcf\system\WCFACP', false)) {
444 foreach ($loadedApplications as $application) {
445 $application->__run();
448 // refresh the session 1 minute before it expires
449 self
::getTPL()->assign('__sessionKeepAlive', (SESSION_TIMEOUT
- 60));
454 * Loads an application.
456 * @param \wcf\data\application\Application $application
457 * @param boolean $isDependentApplication
458 * @return \wcf\system\application\IApplication
460 protected function loadApplication(Application
$application, $isDependentApplication = false) {
461 $applicationObject = null;
462 $package = PackageCache
::getInstance()->getPackage($application->packageID
);
463 // package cache might be outdated
464 if ($package === null) {
465 $package = new Package($application->packageID
);
467 // package cache is outdated, discard cache
468 if ($package->packageID
) {
469 PackageEditor
::resetCache();
472 // package id is invalid
473 throw new SystemException("application identified by package id '".$application->packageID
."' is unknown");
477 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
478 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
479 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
481 $className = $abbreviation.'\system\\'.strtoupper($abbreviation).'Core';
482 if (class_exists($className) && ClassUtil
::isInstanceOf($className, 'wcf\system\application\IApplication')) {
483 // include config file
484 $configPath = $packageDir . PackageInstallationDispatcher
::CONFIG_FILE
;
485 if (file_exists($configPath)) {
486 require_once($configPath);
489 throw new SystemException('Unable to load configuration for '.$package->package
);
492 // register template path if not within ACP
493 if (!class_exists('wcf\system\WCFACP', false)) {
494 // add template path and abbreviation
495 $this->getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
498 // init application and assign it as template variable
499 self
::$applicationObjects[$application->packageID
] = call_user_func(array($className, 'getInstance'));
500 $this->getTPL()->assign('__'.$abbreviation, self
::$applicationObjects[$application->packageID
]);
503 unset(self
::$autoloadDirectories[$abbreviation]);
504 throw new SystemException("Unable to run '".$package->package
."', '".$className."' is missing or does not implement 'wcf\system\application\IApplication'.");
507 // register template path in ACP
508 if (class_exists('wcf\system\WCFACP', false)) {
509 $this->getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
511 else if (!$isDependentApplication) {
513 $this->getTPL()->assign('baseHref', $application->getPageURL());
516 // register application
517 self
::$applications[$abbreviation] = $application;
519 return self
::$applicationObjects[$application->packageID
];
523 * Returns the corresponding application object. Does not support the 'wcf' pseudo application.
525 * @param wcf\data\application\Application $application
526 * @return \wcf\system\application\IApplication
528 public static function getApplicationObject(Application
$application) {
529 if (isset(self
::$applicationObjects[$application->packageID
])) {
530 return self
::$applicationObjects[$application->packageID
];
537 * Loads an application on runtime, do not use this outside the package installation.
539 * @param integer $packageID
541 public static function loadRuntimeApplication($packageID) {
542 $package = new Package($packageID);
543 $application = new Application($packageID);
545 $abbreviation = Package
::getAbbreviation($package->package
);
546 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
547 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
548 self
::$applications[$abbreviation] = $application;
549 self
::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
553 * Initializes core object cache.
555 protected function initCoreObjects() {
556 // ignore core objects if installing WCF
557 if (PACKAGE_ID
== 0) {
561 self
::$coreObjectCache = CoreObjectCacheBuilder
::getInstance()->getData();
565 * Assigns some default variables to the template engine.
567 protected function assignDefaultTemplateVariables() {
568 self
::getTPL()->registerPrefilter(array('event', 'hascontent', 'lang'));
569 self
::getTPL()->assign(array(
571 '__wcfVersion' => mb_substr(sha1(WCF_VERSION
), 0, 8)
576 * Wrapper for the getter methods of this class.
578 * @param string $name
579 * @return mixed value
581 public function __get($name) {
582 $method = 'get'.ucfirst($name);
583 if (method_exists($this, $method)) {
584 return $this->$method();
587 throw new SystemException("method '".$method."' does not exist in class WCF");
591 * Changes the active language.
593 * @param integer $languageID
595 public static final function setLanguage($languageID) {
596 self
::$languageObj = LanguageFactory
::getInstance()->getLanguage($languageID);
597 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
601 * Includes the required util or exception classes automatically.
603 * @param string $className
604 * @see spl_autoload_register()
606 public static final function autoload($className) {
607 $namespaces = explode('\\', $className);
608 if (count($namespaces) > 1) {
609 $applicationPrefix = array_shift($namespaces);
610 if ($applicationPrefix === '') {
611 $applicationPrefix = array_shift($namespaces);
613 if (isset(self
::$autoloadDirectories[$applicationPrefix])) {
614 $classPath = self
::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
615 if (file_exists($classPath)) {
616 require_once($classPath);
623 * @see \wcf\system\WCF::__callStatic()
625 public final function __call($name, array $arguments) {
626 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
627 if (!method_exists($this, $name)) {
628 return self
::__callStatic($name, $arguments);
631 return $this->$name($arguments);
635 * Returns dynamically loaded core objects.
637 * @param string $name
638 * @param array $arguments
640 public static final function __callStatic($name, array $arguments) {
641 $className = preg_replace('~^get~', '', $name);
643 if (isset(self
::$coreObject[$className])) {
644 return self
::$coreObject[$className];
647 $objectName = self
::getCoreObject($className);
648 if ($objectName === null) {
649 throw new SystemException("Core object '".$className."' is unknown.");
652 if (class_exists($objectName)) {
653 if (!(ClassUtil
::isInstanceOf($objectName, 'wcf\system\SingletonFactory'))) {
654 throw new SystemException("class '".$objectName."' does not implement the interface 'SingletonFactory'");
657 self
::$coreObject[$className] = call_user_func(array($objectName, 'getInstance'));
658 return self
::$coreObject[$className];
663 * Searches for cached core object definition.
665 * @param string $className
668 protected static final function getCoreObject($className) {
669 if (isset(self
::$coreObjectCache[$className])) {
670 return self
::$coreObjectCache[$className];
677 * Returns true if the debug mode is enabled, otherwise false.
681 public static function debugModeIsEnabled() {
683 if (self
::$overrideDebugMode) {
686 else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE
) {
694 * Returns true if benchmarking is enabled, otherwise false.
698 public static function benchmarkIsEnabled() {
699 // benchmarking is enabled by default
700 if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK
) return true;
705 * Returns domain path for given application.
707 * @param string $abbreviation
710 public static function getPath($abbreviation = 'wcf') {
711 // workaround during WCFSetup
716 if (!isset(self
::$applications[$abbreviation])) {
717 $abbreviation = 'wcf';
720 return self
::$applications[$abbreviation]->getPageURL();
724 * Returns a fully qualified anchor for current page.
726 * @param string $fragment
729 public function getAnchor($fragment) {
730 return self
::getRequestURI() . '#' . $fragment;
734 * Returns the URI of the current page.
738 public static function getRequestURI() {
739 // resolve path and query components
740 $scriptName = $_SERVER['SCRIPT_NAME'];
741 $pathInfo = RouteHandler
::getPathInfo();
742 if (empty($pathInfo)) {
743 // bug fix if URL omits script name and path
744 $scriptName = substr($scriptName, 0, strrpos($scriptName, '/'));
747 $path = str_replace('/index.php', '', str_replace($scriptName, '', $_SERVER['REQUEST_URI']));
748 if (!StringUtil
::isASCII($path) && !StringUtil
::isUTF8($path)) {
749 $path = StringUtil
::convertEncoding('ISO-8859-1', 'UTF-8', $path);
751 $path = FileUtil
::removeLeadingSlash($path);
752 $baseHref = self
::getTPL()->get('baseHref');
754 if (!empty($path) && mb_strpos($path, '?') !== 0) {
755 $baseHref .= 'index.php/';
758 return $baseHref . $path;
762 * Resets Zend Opcache cache if installed and enabled.
764 * @param string $script
766 public static function resetZendOpcache($script = '') {
767 if (self
::$zendOpcacheEnabled === null) {
768 self
::$zendOpcacheEnabled = false;
770 if (extension_loaded('Zend Opcache') && @ini_get
('opcache.enable')) {
771 self
::$zendOpcacheEnabled = true;
776 if (self
::$zendOpcacheEnabled) {
777 if (empty($script)) {
781 opcache_invalidate($script, true);
787 * Returns style handler.
789 * @return \wcf\system\style\StyleHandler
791 public function getStyleHandler() {
792 return StyleHandler
::getInstance();
796 * Returns number of available updates.
800 public function getAvailableUpdates() {
801 $data = PackageUpdateCacheBuilder
::getInstance()->getData();
802 return $data['updates'];
806 * @see \wcf\system\request\RouteHandler::secureConnection()
808 public function secureConnection() {
809 return RouteHandler
::secureConnection();
813 * Initialises the cronjobs.
815 protected function initCronjobs() {
817 self
::getTPL()->assign('executeCronjobs', CronjobScheduler
::getInstance()->getNextExec() < TIME_NOW
);