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.0.0 (Maelstrom)');
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-2013 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\system\application\IApplication>
66 protected static $applications = array();
69 * list of autoload directories
72 protected static $autoloadDirectories = array();
75 * list of unique instances of each core object
76 * @var array<\wcf\system\SingletonFactory>
78 protected static $coreObject = array();
81 * list of cached core objects
84 protected static $coreObjectCache = array();
88 * @var \wcf\system\database\Database
90 protected static $dbObj = null;
94 * @var \wcf\system\language\Language
96 protected static $languageObj = null;
99 * overrides disabled debug mode
102 protected static $overrideDebugMode = false;
106 * @var \wcf\system\session\SessionHandler
108 protected static $sessionObj = null;
112 * @var \wcf\system\template\TemplateEngine
114 protected static $tplObj = null;
117 * Calls all init functions of the WCF class.
119 public function __construct() {
120 // add autoload directory
121 self
::$autoloadDirectories['wcf'] = WCF_DIR
. 'lib/';
123 // define tmp directory
124 if (!defined('TMP_DIR')) define('TMP_DIR', FileUtil
::getTempFolder());
126 // start initialization
127 $this->initMagicQuotes();
129 $this->loadOptions();
130 $this->initSession();
131 $this->initLanguage();
133 $this->initCronjobs();
134 $this->initCoreObjects();
135 $this->initApplications();
136 $this->initBlacklist();
138 EventHandler
::getInstance()->fireAction($this, 'initialized');
142 * Replacement of the "__destruct()" method.
143 * Seems that under specific conditions (windows) the destructor is not called automatically.
144 * So we use the php register_shutdown_function to register an own destructor method.
145 * Flushs the output, closes caches and updates the session.
147 public static function destruct() {
149 // database has to be initialized
150 if (!is_object(self
::$dbObj)) return;
153 if (ob_get_level() && ini_get('output_handler')) {
161 if (is_object(self
::getSession())) {
162 self
::getSession()->update();
165 // execute shutdown actions of user storage handler
166 UserStorageHandler
::getInstance()->shutdown();
168 catch (\Exception
$exception) {
169 die("<pre>WCF::destruct() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
174 * Removes slashes in superglobal gpc data arrays if 'magic quotes gpc' is enabled.
176 protected function initMagicQuotes() {
177 if (function_exists('get_magic_quotes_gpc')) {
178 if (@get_magic_quotes_gpc
()) {
179 if (!empty($_REQUEST)) {
180 $_REQUEST = ArrayUtil
::stripslashes($_REQUEST);
182 if (!empty($_POST)) {
183 $_POST = ArrayUtil
::stripslashes($_POST);
186 $_GET = ArrayUtil
::stripslashes($_GET);
188 if (!empty($_COOKIE)) {
189 $_COOKIE = ArrayUtil
::stripslashes($_COOKIE);
191 if (!empty($_FILES)) {
192 foreach ($_FILES as $name => $attributes) {
193 foreach ($attributes as $key => $value) {
194 if ($key != 'tmp_name') {
195 $_FILES[$name][$key] = ArrayUtil
::stripslashes($value);
203 if (function_exists('set_magic_quotes_runtime')) {
204 @set_magic_quotes_runtime
(0);
209 * Returns the database object.
211 * @return \wcf\system\database\Database
213 public static final function getDB() {
218 * Returns the session object.
220 * @return \wcf\system\session\SessionHandler
222 public static final function getSession() {
223 return self
::$sessionObj;
227 * Returns the user object.
229 * @return \wcf\data\user\User
231 public static final function getUser() {
232 return self
::getSession()->getUser();
236 * Returns the language object.
238 * @return \wcf\data\language\Language
240 public static final function getLanguage() {
241 return self
::$languageObj;
245 * Returns the template object.
247 * @return \wcf\system\template\TemplateEngine
249 public static final function getTPL() {
250 return self
::$tplObj;
254 * Calls the show method on the given exception.
256 * @param \Exception $e
258 public static final function handleException(\Exception
$e) {
260 if ($e instanceof IPrintableException
) {
266 self
::handleException(new SystemException($e->getMessage(), $e->getCode(), '', $e));
268 catch (\Exception
$exception) {
269 die("<pre>WCF::handleException() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
274 * Catches php errors and throws instead a system exception.
276 * @param integer $errorNo
277 * @param string $message
278 * @param string $filename
279 * @param integer $lineNo
281 public static final function handleError($errorNo, $message, $filename, $lineNo) {
282 if (error_reporting() != 0) {
285 case 2: $type = 'warning';
287 case 8: $type = 'notice';
291 throw new SystemException('PHP '.$type.' in file '.$filename.' ('.$lineNo.'): '.$message, 0);
296 * Loads the database configuration and creates a new connection to the database.
298 protected function initDB() {
300 $dbHost = $dbUser = $dbPassword = $dbName = '';
302 $dbClass = 'wcf\system\database\MySQLDatabase';
303 require(WCF_DIR
.'config.inc.php');
305 // create database connection
306 self
::$dbObj = new $dbClass($dbHost, $dbUser, $dbPassword, $dbName, $dbPort);
310 * Loads the options file, automatically created if not exists.
312 protected function loadOptions() {
313 $filename = WCF_DIR
.'options.inc.php';
315 // create options file if doesn't exist
316 if (!file_exists($filename) ||
filemtime($filename) <= 1) {
317 OptionEditor
::rebuild();
319 require_once($filename);
323 * Starts the session system.
325 protected function initSession() {
326 $factory = new SessionFactory();
329 self
::$sessionObj = SessionHandler
::getInstance();
333 * Initialises the language engine.
335 protected function initLanguage() {
336 if (isset($_GET['l']) && !self
::getUser()->userID
) {
337 self
::getSession()->setLanguageID(intval($_GET['l']));
341 mb_internal_encoding('UTF-8');
342 if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
346 self
::$languageObj = LanguageFactory
::getInstance()->getUserLanguage(self
::getSession()->getLanguageID());
350 * Initialises the template engine.
352 protected function initTPL() {
353 self
::$tplObj = TemplateEngine
::getInstance();
354 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
355 $this->assignDefaultTemplateVariables();
361 * Initializes the user's style.
363 protected function initStyle() {
364 if (isset($_REQUEST['styleID'])) {
365 self
::getSession()->setStyleID(intval($_REQUEST['styleID']));
368 StyleHandler
::getInstance()->changeStyle(self
::getSession()->getStyleID());
372 * Executes the blacklist.
374 protected function initBlacklist() {
375 if (defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES
!= '') {
376 if (!StringUtil
::executeWordFilter(self
::getSession()->ipAddress
, BLACKLIST_IP_ADDRESSES
)) {
377 throw new PermissionDeniedException();
380 if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS
!= '') {
381 if (!StringUtil
::executeWordFilter(self
::getSession()->userAgent
, BLACKLIST_USER_AGENTS
)) {
382 throw new PermissionDeniedException();
385 if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES
!= '') {
386 if (!StringUtil
::executeWordFilter(@gethostbyaddr
(self
::getSession()->ipAddress
), BLACKLIST_HOSTNAMES
)) {
387 throw new PermissionDeniedException();
391 // handle banned users
392 if (self
::getUser()->userID
&& self
::getUser()->banned
) {
393 if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
394 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
397 throw new NamedUserException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
403 * Initializes applications.
405 protected function initApplications() {
406 // step 1) load all applications
407 $loadedApplications = array();
409 // register WCF as application
410 self
::$applications['wcf'] = ApplicationHandler
::getInstance()->getWCF();
412 if (PACKAGE_ID
== 1) {
416 // start main application
417 $application = ApplicationHandler
::getInstance()->getActiveApplication();
418 $loadedApplications[] = $this->loadApplication($application);
420 // register primary application
421 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
422 self
::$applications[$abbreviation] = $application;
424 // start dependent applications
425 $applications = ApplicationHandler
::getInstance()->getDependentApplications();
426 foreach ($applications as $application) {
427 $loadedApplications[] = $this->loadApplication($application, true);
430 // step 2) run each application
431 if (!class_exists('wcf\system\WCFACP', false)) {
432 foreach ($loadedApplications as $application) {
433 $application->__run();
436 // refresh the session 1 minute before it expires
437 self
::getTPL()->assign('__sessionKeepAlive', (SESSION_TIMEOUT
- 60));
442 * Loads an application.
444 * @param \wcf\data\application\Application $application
445 * @param boolean $isDependentApplication
446 * @return \wcf\system\application\IApplication
448 protected function loadApplication(Application
$application, $isDependentApplication = false) {
449 $applicationObject = null;
450 $package = PackageCache
::getInstance()->getPackage($application->packageID
);
451 // package cache might be outdated
452 if ($package === null) {
453 $package = new Package($application->packageID
);
455 // package cache is outdated, discard cache
456 if ($package->packageID
) {
457 PackageEditor
::resetCache();
460 // package id is invalid
461 throw new SystemException("application identified by package id '".$application->packageID
."' is unknown");
465 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
466 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
467 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
469 $className = $abbreviation.'\system\\'.strtoupper($abbreviation).'Core';
470 if (class_exists($className) && ClassUtil
::isInstanceOf($className, 'wcf\system\application\IApplication')) {
471 // include config file
472 $configPath = $packageDir . PackageInstallationDispatcher
::CONFIG_FILE
;
473 if (file_exists($configPath)) {
474 require_once($configPath);
477 throw new SystemException('Unable to load configuration for '.$package->package
);
480 // register template path if not within ACP
481 if (!class_exists('wcf\system\WCFACP', false)) {
482 // add template path and abbreviation
483 $this->getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
486 // init application and assign it as template variable
487 $applicationObject = call_user_func(array($className, 'getInstance'));
488 $this->getTPL()->assign('__'.$abbreviation, $applicationObject);
491 unset(self
::$autoloadDirectories[$abbreviation]);
492 throw new SystemException("Unable to run '".$package->package
."', '".$className."' is missing or does not implement 'wcf\system\application\IApplication'.");
495 // register template path in ACP
496 if (class_exists('wcf\system\WCFACP', false)) {
497 $this->getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
499 else if (!$isDependentApplication) {
501 $this->getTPL()->assign('baseHref', $application->getPageURL());
504 // register application
505 self
::$applications[$abbreviation] = $application;
507 return $applicationObject;
511 * Loads an application on runtime, do not use this outside the package installation.
513 * @param integer $packageID
515 public static function loadRuntimeApplication($packageID) {
516 $package = new Package($packageID);
517 $application = new Application($packageID);
519 $abbreviation = Package
::getAbbreviation($package->package
);
520 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
521 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
522 self
::$applications[$abbreviation] = $application;
523 self
::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
527 * Initializes core object cache.
529 protected function initCoreObjects() {
530 // ignore core objects if installing WCF
531 if (PACKAGE_ID
== 0) {
535 self
::$coreObjectCache = CoreObjectCacheBuilder
::getInstance()->getData();
539 * Assigns some default variables to the template engine.
541 protected function assignDefaultTemplateVariables() {
542 self
::getTPL()->registerPrefilter(array('event', 'hascontent', 'lang'));
543 self
::getTPL()->assign(array(
545 '__wcfVersion' => mb_substr(sha1(WCF_VERSION
), 0, 8)
550 * Wrapper for the getter methods of this class.
552 * @param string $name
553 * @return mixed value
555 public function __get($name) {
556 $method = 'get'.ucfirst($name);
557 if (method_exists($this, $method)) {
558 return $this->$method();
561 throw new SystemException("method '".$method."' does not exist in class WCF");
565 * Changes the active language.
567 * @param integer $languageID
569 public static final function setLanguage($languageID) {
570 self
::$languageObj = LanguageFactory
::getInstance()->getLanguage($languageID);
571 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
575 * Includes the required util or exception classes automatically.
577 * @param string $className
578 * @see spl_autoload_register()
580 public static final function autoload($className) {
581 $namespaces = explode('\\', $className);
582 if (count($namespaces) > 1) {
583 $applicationPrefix = array_shift($namespaces);
584 if ($applicationPrefix === '') {
585 $applicationPrefix = array_shift($namespaces);
587 if (isset(self
::$autoloadDirectories[$applicationPrefix])) {
588 $classPath = self
::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
589 if (file_exists($classPath)) {
590 require_once($classPath);
597 * @see \wcf\system\WCF::__callStatic()
599 public final function __call($name, array $arguments) {
600 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
601 if (!method_exists($this, $name)) {
602 return self
::__callStatic($name, $arguments);
605 return $this->$name($arguments);
609 * Returns dynamically loaded core objects.
611 * @param string $name
612 * @param array $arguments
614 public static final function __callStatic($name, array $arguments) {
615 $className = preg_replace('~^get~', '', $name);
617 if (isset(self
::$coreObject[$className])) {
618 return self
::$coreObject[$className];
621 $objectName = self
::getCoreObject($className);
622 if ($objectName === null) {
623 throw new SystemException("Core object '".$className."' is unknown.");
626 if (class_exists($objectName)) {
627 if (!(ClassUtil
::isInstanceOf($objectName, 'wcf\system\SingletonFactory'))) {
628 throw new SystemException("class '".$objectName."' does not implement the interface 'SingletonFactory'");
631 self
::$coreObject[$className] = call_user_func(array($objectName, 'getInstance'));
632 return self
::$coreObject[$className];
637 * Searches for cached core object definition.
639 * @param string $className
642 protected static final function getCoreObject($className) {
643 if (isset(self
::$coreObjectCache[$className])) {
644 return self
::$coreObjectCache[$className];
651 * Returns true if the debug mode is enabled, otherwise false.
655 public static function debugModeIsEnabled() {
657 if (self
::$overrideDebugMode) {
660 else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE
) {
668 * Returns true if benchmarking is enabled, otherwise false.
672 public static function benchmarkIsEnabled() {
673 // benchmarking is enabled by default
674 if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK
) return true;
679 * Returns domain path for given application.
681 * @param string $abbreviation
684 public static function getPath($abbreviation = 'wcf') {
685 // workaround during WCFSetup
690 if (!isset(self
::$applications[$abbreviation])) {
691 $abbreviation = 'wcf';
694 return self
::$applications[$abbreviation]->getPageURL();
698 * Returns a fully qualified anchor for current page.
700 * @param string $fragment
703 public function getAnchor($fragment) {
704 return self
::getRequestURI() . '#' . $fragment;
708 * Returns the URI of the current page.
712 public static function getRequestURI() {
713 // resolve path and query components
714 $scriptName = $_SERVER['SCRIPT_NAME'];
715 $pathInfo = RouteHandler
::getPathInfo();
716 if (empty($pathInfo)) {
717 // bug fix if URL omits script name and path
718 $scriptName = substr($scriptName, 0, strrpos($scriptName, '/'));
721 $path = str_replace('/index.php', '', str_replace($scriptName, '', $_SERVER['REQUEST_URI']));
722 if (!StringUtil
::isASCII($path) && !StringUtil
::isUTF8($path)) {
723 $path = StringUtil
::convertEncoding('ISO-8859-1', 'UTF-8', $path);
725 $path = FileUtil
::removeLeadingSlash($path);
726 $baseHref = self
::getTPL()->get('baseHref');
728 if (!empty($path) && mb_strpos($path, '?') !== 0) {
729 $baseHref .= 'index.php/';
732 return $baseHref . $path;
736 * Returns style handler.
738 * @return \wcf\system\style\StyleHandler
740 public function getStyleHandler() {
741 return StyleHandler
::getInstance();
745 * Returns number of available updates.
749 public function getAvailableUpdates() {
750 $data = PackageUpdateCacheBuilder
::getInstance()->getData();
751 return $data['updates'];
755 * Initialises the cronjobs.
757 protected function initCronjobs() {
759 self
::getTPL()->assign('executeCronjobs', CronjobScheduler
::getInstance()->getNextExec() < TIME_NOW
);