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 * true if Zend Opcache is loaded and enabled
120 protected static $zendOpcacheEnabled = null;
123 * Calls all init functions of the WCF class.
125 public function __construct() {
126 // add autoload directory
127 self
::$autoloadDirectories['wcf'] = WCF_DIR
. 'lib/';
129 // define tmp directory
130 if (!defined('TMP_DIR')) define('TMP_DIR', FileUtil
::getTempFolder());
132 // start initialization
133 $this->initMagicQuotes();
135 $this->loadOptions();
136 $this->initSession();
137 $this->initLanguage();
139 $this->initCronjobs();
140 $this->initCoreObjects();
141 $this->initApplications();
142 $this->initBlacklist();
144 EventHandler
::getInstance()->fireAction($this, 'initialized');
148 * Replacement of the "__destruct()" method.
149 * Seems that under specific conditions (windows) the destructor is not called automatically.
150 * So we use the php register_shutdown_function to register an own destructor method.
151 * Flushs the output, closes caches and updates the session.
153 public static function destruct() {
155 // database has to be initialized
156 if (!is_object(self
::$dbObj)) return;
159 if (ob_get_level() && ini_get('output_handler')) {
167 if (is_object(self
::getSession())) {
168 self
::getSession()->update();
171 // execute shutdown actions of user storage handler
172 UserStorageHandler
::getInstance()->shutdown();
174 catch (\Exception
$exception) {
175 die("<pre>WCF::destruct() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
180 * Removes slashes in superglobal gpc data arrays if 'magic quotes gpc' is enabled.
182 protected function initMagicQuotes() {
183 if (function_exists('get_magic_quotes_gpc')) {
184 if (@get_magic_quotes_gpc
()) {
185 if (!empty($_REQUEST)) {
186 $_REQUEST = ArrayUtil
::stripslashes($_REQUEST);
188 if (!empty($_POST)) {
189 $_POST = ArrayUtil
::stripslashes($_POST);
192 $_GET = ArrayUtil
::stripslashes($_GET);
194 if (!empty($_COOKIE)) {
195 $_COOKIE = ArrayUtil
::stripslashes($_COOKIE);
197 if (!empty($_FILES)) {
198 foreach ($_FILES as $name => $attributes) {
199 foreach ($attributes as $key => $value) {
200 if ($key != 'tmp_name') {
201 $_FILES[$name][$key] = ArrayUtil
::stripslashes($value);
209 if (function_exists('set_magic_quotes_runtime')) {
210 @set_magic_quotes_runtime
(0);
215 * Returns the database object.
217 * @return \wcf\system\database\Database
219 public static final function getDB() {
224 * Returns the session object.
226 * @return \wcf\system\session\SessionHandler
228 public static final function getSession() {
229 return self
::$sessionObj;
233 * Returns the user object.
235 * @return \wcf\data\user\User
237 public static final function getUser() {
238 return self
::getSession()->getUser();
242 * Returns the language object.
244 * @return \wcf\data\language\Language
246 public static final function getLanguage() {
247 return self
::$languageObj;
251 * Returns the template object.
253 * @return \wcf\system\template\TemplateEngine
255 public static final function getTPL() {
256 return self
::$tplObj;
260 * Calls the show method on the given exception.
262 * @param \Exception $e
264 public static final function handleException(\Exception
$e) {
266 if ($e instanceof IPrintableException
) {
272 self
::handleException(new SystemException($e->getMessage(), $e->getCode(), '', $e));
274 catch (\Exception
$exception) {
275 die("<pre>WCF::handleException() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
280 * Catches php errors and throws instead a system exception.
282 * @param integer $errorNo
283 * @param string $message
284 * @param string $filename
285 * @param integer $lineNo
287 public static final function handleError($errorNo, $message, $filename, $lineNo) {
288 if (error_reporting() != 0) {
291 case 2: $type = 'warning';
293 case 8: $type = 'notice';
297 throw new SystemException('PHP '.$type.' in file '.$filename.' ('.$lineNo.'): '.$message, 0);
302 * Loads the database configuration and creates a new connection to the database.
304 protected function initDB() {
306 $dbHost = $dbUser = $dbPassword = $dbName = '';
308 $dbClass = 'wcf\system\database\MySQLDatabase';
309 require(WCF_DIR
.'config.inc.php');
311 // create database connection
312 self
::$dbObj = new $dbClass($dbHost, $dbUser, $dbPassword, $dbName, $dbPort);
316 * Loads the options file, automatically created if not exists.
318 protected function loadOptions() {
319 $filename = WCF_DIR
.'options.inc.php';
321 // create options file if doesn't exist
322 if (!file_exists($filename) ||
filemtime($filename) <= 1) {
323 OptionEditor
::rebuild();
325 require_once($filename);
329 * Starts the session system.
331 protected function initSession() {
332 $factory = new SessionFactory();
335 self
::$sessionObj = SessionHandler
::getInstance();
339 * Initialises the language engine.
341 protected function initLanguage() {
342 if (isset($_GET['l']) && !self
::getUser()->userID
) {
343 self
::getSession()->setLanguageID(intval($_GET['l']));
347 mb_internal_encoding('UTF-8');
348 if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
352 self
::$languageObj = LanguageFactory
::getInstance()->getUserLanguage(self
::getSession()->getLanguageID());
356 * Initialises the template engine.
358 protected function initTPL() {
359 self
::$tplObj = TemplateEngine
::getInstance();
360 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
361 $this->assignDefaultTemplateVariables();
367 * Initializes the user's style.
369 protected function initStyle() {
370 if (isset($_REQUEST['styleID'])) {
371 self
::getSession()->setStyleID(intval($_REQUEST['styleID']));
374 StyleHandler
::getInstance()->changeStyle(self
::getSession()->getStyleID());
378 * Executes the blacklist.
380 protected function initBlacklist() {
381 if (defined('BLACKLIST_IP_ADDRESSES') && BLACKLIST_IP_ADDRESSES
!= '') {
382 if (!StringUtil
::executeWordFilter(self
::getSession()->ipAddress
, BLACKLIST_IP_ADDRESSES
)) {
383 throw new PermissionDeniedException();
386 if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS
!= '') {
387 if (!StringUtil
::executeWordFilter(self
::getSession()->userAgent
, BLACKLIST_USER_AGENTS
)) {
388 throw new PermissionDeniedException();
391 if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES
!= '') {
392 if (!StringUtil
::executeWordFilter(@gethostbyaddr
(self
::getSession()->ipAddress
), BLACKLIST_HOSTNAMES
)) {
393 throw new PermissionDeniedException();
397 // handle banned users
398 if (self
::getUser()->userID
&& self
::getUser()->banned
) {
399 if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
400 throw new AJAXException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'), AJAXException
::INSUFFICIENT_PERMISSIONS
);
403 throw new NamedUserException(self
::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
409 * Initializes applications.
411 protected function initApplications() {
412 // step 1) load all applications
413 $loadedApplications = array();
415 // register WCF as application
416 self
::$applications['wcf'] = ApplicationHandler
::getInstance()->getWCF();
418 if (PACKAGE_ID
== 1) {
422 // start main application
423 $application = ApplicationHandler
::getInstance()->getActiveApplication();
424 $loadedApplications[] = $this->loadApplication($application);
426 // register primary application
427 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
428 self
::$applications[$abbreviation] = $application;
430 // start dependent applications
431 $applications = ApplicationHandler
::getInstance()->getDependentApplications();
432 foreach ($applications as $application) {
433 $loadedApplications[] = $this->loadApplication($application, true);
436 // step 2) run each application
437 if (!class_exists('wcf\system\WCFACP', false)) {
438 foreach ($loadedApplications as $application) {
439 $application->__run();
442 // refresh the session 1 minute before it expires
443 self
::getTPL()->assign('__sessionKeepAlive', (SESSION_TIMEOUT
- 60));
448 * Loads an application.
450 * @param \wcf\data\application\Application $application
451 * @param boolean $isDependentApplication
452 * @return \wcf\system\application\IApplication
454 protected function loadApplication(Application
$application, $isDependentApplication = false) {
455 $applicationObject = null;
456 $package = PackageCache
::getInstance()->getPackage($application->packageID
);
457 // package cache might be outdated
458 if ($package === null) {
459 $package = new Package($application->packageID
);
461 // package cache is outdated, discard cache
462 if ($package->packageID
) {
463 PackageEditor
::resetCache();
466 // package id is invalid
467 throw new SystemException("application identified by package id '".$application->packageID
."' is unknown");
471 $abbreviation = ApplicationHandler
::getInstance()->getAbbreviation($application->packageID
);
472 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
473 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
475 $className = $abbreviation.'\system\\'.strtoupper($abbreviation).'Core';
476 if (class_exists($className) && ClassUtil
::isInstanceOf($className, 'wcf\system\application\IApplication')) {
477 // include config file
478 $configPath = $packageDir . PackageInstallationDispatcher
::CONFIG_FILE
;
479 if (file_exists($configPath)) {
480 require_once($configPath);
483 throw new SystemException('Unable to load configuration for '.$package->package
);
486 // register template path if not within ACP
487 if (!class_exists('wcf\system\WCFACP', false)) {
488 // add template path and abbreviation
489 $this->getTPL()->addApplication($abbreviation, $packageDir . 'templates/');
492 // init application and assign it as template variable
493 $applicationObject = call_user_func(array($className, 'getInstance'));
494 $this->getTPL()->assign('__'.$abbreviation, $applicationObject);
497 unset(self
::$autoloadDirectories[$abbreviation]);
498 throw new SystemException("Unable to run '".$package->package
."', '".$className."' is missing or does not implement 'wcf\system\application\IApplication'.");
501 // register template path in ACP
502 if (class_exists('wcf\system\WCFACP', false)) {
503 $this->getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
505 else if (!$isDependentApplication) {
507 $this->getTPL()->assign('baseHref', $application->getPageURL());
510 // register application
511 self
::$applications[$abbreviation] = $application;
513 return $applicationObject;
517 * Loads an application on runtime, do not use this outside the package installation.
519 * @param integer $packageID
521 public static function loadRuntimeApplication($packageID) {
522 $package = new Package($packageID);
523 $application = new Application($packageID);
525 $abbreviation = Package
::getAbbreviation($package->package
);
526 $packageDir = FileUtil
::getRealPath(WCF_DIR
.$package->packageDir
);
527 self
::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
528 self
::$applications[$abbreviation] = $application;
529 self
::getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
533 * Initializes core object cache.
535 protected function initCoreObjects() {
536 // ignore core objects if installing WCF
537 if (PACKAGE_ID
== 0) {
541 self
::$coreObjectCache = CoreObjectCacheBuilder
::getInstance()->getData();
545 * Assigns some default variables to the template engine.
547 protected function assignDefaultTemplateVariables() {
548 self
::getTPL()->registerPrefilter(array('event', 'hascontent', 'lang'));
549 self
::getTPL()->assign(array(
551 '__wcfVersion' => mb_substr(sha1(WCF_VERSION
), 0, 8)
556 * Wrapper for the getter methods of this class.
558 * @param string $name
559 * @return mixed value
561 public function __get($name) {
562 $method = 'get'.ucfirst($name);
563 if (method_exists($this, $method)) {
564 return $this->$method();
567 throw new SystemException("method '".$method."' does not exist in class WCF");
571 * Changes the active language.
573 * @param integer $languageID
575 public static final function setLanguage($languageID) {
576 self
::$languageObj = LanguageFactory
::getInstance()->getLanguage($languageID);
577 self
::getTPL()->setLanguageID(self
::getLanguage()->languageID
);
581 * Includes the required util or exception classes automatically.
583 * @param string $className
584 * @see spl_autoload_register()
586 public static final function autoload($className) {
587 $namespaces = explode('\\', $className);
588 if (count($namespaces) > 1) {
589 $applicationPrefix = array_shift($namespaces);
590 if ($applicationPrefix === '') {
591 $applicationPrefix = array_shift($namespaces);
593 if (isset(self
::$autoloadDirectories[$applicationPrefix])) {
594 $classPath = self
::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
595 if (file_exists($classPath)) {
596 require_once($classPath);
603 * @see \wcf\system\WCF::__callStatic()
605 public final function __call($name, array $arguments) {
606 // bug fix to avoid php crash, see http://bugs.php.net/bug.php?id=55020
607 if (!method_exists($this, $name)) {
608 return self
::__callStatic($name, $arguments);
611 return $this->$name($arguments);
615 * Returns dynamically loaded core objects.
617 * @param string $name
618 * @param array $arguments
620 public static final function __callStatic($name, array $arguments) {
621 $className = preg_replace('~^get~', '', $name);
623 if (isset(self
::$coreObject[$className])) {
624 return self
::$coreObject[$className];
627 $objectName = self
::getCoreObject($className);
628 if ($objectName === null) {
629 throw new SystemException("Core object '".$className."' is unknown.");
632 if (class_exists($objectName)) {
633 if (!(ClassUtil
::isInstanceOf($objectName, 'wcf\system\SingletonFactory'))) {
634 throw new SystemException("class '".$objectName."' does not implement the interface 'SingletonFactory'");
637 self
::$coreObject[$className] = call_user_func(array($objectName, 'getInstance'));
638 return self
::$coreObject[$className];
643 * Searches for cached core object definition.
645 * @param string $className
648 protected static final function getCoreObject($className) {
649 if (isset(self
::$coreObjectCache[$className])) {
650 return self
::$coreObjectCache[$className];
657 * Returns true if the debug mode is enabled, otherwise false.
661 public static function debugModeIsEnabled() {
663 if (self
::$overrideDebugMode) {
666 else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE
) {
674 * Returns true if benchmarking is enabled, otherwise false.
678 public static function benchmarkIsEnabled() {
679 // benchmarking is enabled by default
680 if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK
) return true;
685 * Returns domain path for given application.
687 * @param string $abbreviation
690 public static function getPath($abbreviation = 'wcf') {
691 // workaround during WCFSetup
696 if (!isset(self
::$applications[$abbreviation])) {
697 $abbreviation = 'wcf';
700 return self
::$applications[$abbreviation]->getPageURL();
704 * Returns a fully qualified anchor for current page.
706 * @param string $fragment
709 public function getAnchor($fragment) {
710 return self
::getRequestURI() . '#' . $fragment;
714 * Returns the URI of the current page.
718 public static function getRequestURI() {
719 // resolve path and query components
720 $scriptName = $_SERVER['SCRIPT_NAME'];
721 $pathInfo = RouteHandler
::getPathInfo();
722 if (empty($pathInfo)) {
723 // bug fix if URL omits script name and path
724 $scriptName = substr($scriptName, 0, strrpos($scriptName, '/'));
727 $path = str_replace('/index.php', '', str_replace($scriptName, '', $_SERVER['REQUEST_URI']));
728 if (!StringUtil
::isASCII($path) && !StringUtil
::isUTF8($path)) {
729 $path = StringUtil
::convertEncoding('ISO-8859-1', 'UTF-8', $path);
731 $path = FileUtil
::removeLeadingSlash($path);
732 $baseHref = self
::getTPL()->get('baseHref');
734 if (!empty($path) && mb_strpos($path, '?') !== 0) {
735 $baseHref .= 'index.php/';
738 return $baseHref . $path;
742 * Resets Zend Opcache cache if installed and enabled.
744 * @param string $script
746 public static function resetZendOpcache($script = '') {
747 if (self
::$zendOpcacheEnabled === null) {
748 if (extension_loaded('Zend Opcache') && @ini_get
('opcache.enable')) {
749 self
::$zendOpcacheEnabled = true;
752 self
::$zendOpcacheEnabled = false;
755 if (self
::$zendOpcacheEnabled) {
756 if (empty($script)) {
760 opcache_invalidate($script, true);
766 * Returns style handler.
768 * @return \wcf\system\style\StyleHandler
770 public function getStyleHandler() {
771 return StyleHandler
::getInstance();
775 * Returns number of available updates.
779 public function getAvailableUpdates() {
780 $data = PackageUpdateCacheBuilder
::getInstance()->getData();
781 return $data['updates'];
785 * Initialises the cronjobs.
787 protected function initCronjobs() {
789 self
::getTPL()->assign('executeCronjobs', CronjobScheduler
::getInstance()->getNextExec() < TIME_NOW
);