dd891799f3c87835c0325bcce2673ac6f3ec2c7f
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / lib / system / WCF.class.php
1 <?php
2 namespace wcf\system;
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
31 // try to set a time-limit to infinite
32 @set_time_limit(0);
33
34 // fix timezone warning issue
35 if (!@ini_get('date.timezone')) {
36 @date_default_timezone_set('Europe/London');
37 }
38
39 // define current wcf version
40 define('WCF_VERSION', '2.0.0 (Maelstrom)');
41
42 // define current unix timestamp
43 define('TIME_NOW', time());
44
45 // wcf imports
46 if (!defined('NO_IMPORTS')) {
47 require_once(WCF_DIR.'lib/core.functions.php');
48 }
49
50 /**
51 * WCF is the central class for the community framework.
52 * It holds the database connection, access to template and language engine.
53 *
54 * @author Marcel Werk
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
58 * @subpackage system
59 * @category Community Framework
60 */
61 class WCF {
62 /**
63 * list of currently loaded applications
64 * @var array<\wcf\system\application\IApplication>
65 */
66 protected static $applications = array();
67
68 /**
69 * list of autoload directories
70 * @var array
71 */
72 protected static $autoloadDirectories = array();
73
74 /**
75 * list of unique instances of each core object
76 * @var array<\wcf\system\SingletonFactory>
77 */
78 protected static $coreObject = array();
79
80 /**
81 * list of cached core objects
82 * @var array<array>
83 */
84 protected static $coreObjectCache = array();
85
86 /**
87 * database object
88 * @var \wcf\system\database\Database
89 */
90 protected static $dbObj = null;
91
92 /**
93 * language object
94 * @var \wcf\system\language\Language
95 */
96 protected static $languageObj = null;
97
98 /**
99 * overrides disabled debug mode
100 * @var boolean
101 */
102 protected static $overrideDebugMode = false;
103
104 /**
105 * session object
106 * @var \wcf\system\session\SessionHandler
107 */
108 protected static $sessionObj = null;
109
110 /**
111 * template object
112 * @var \wcf\system\template\TemplateEngine
113 */
114 protected static $tplObj = null;
115
116 /**
117 * Calls all init functions of the WCF class.
118 */
119 public function __construct() {
120 // add autoload directory
121 self::$autoloadDirectories['wcf'] = WCF_DIR . 'lib/';
122
123 // define tmp directory
124 if (!defined('TMP_DIR')) define('TMP_DIR', FileUtil::getTempFolder());
125
126 // start initialization
127 $this->initMagicQuotes();
128 $this->initDB();
129 $this->loadOptions();
130 $this->initSession();
131 $this->initLanguage();
132 $this->initTPL();
133 $this->initCronjobs();
134 $this->initCoreObjects();
135 $this->initApplications();
136 $this->initBlacklist();
137
138 EventHandler::getInstance()->fireAction($this, 'initialized');
139 }
140
141 /**
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.
146 */
147 public static function destruct() {
148 try {
149 // database has to be initialized
150 if (!is_object(self::$dbObj)) return;
151
152 // flush output
153 if (ob_get_level() && ini_get('output_handler')) {
154 ob_flush();
155 }
156 else {
157 flush();
158 }
159
160 // update session
161 if (is_object(self::getSession())) {
162 self::getSession()->update();
163 }
164
165 // execute shutdown actions of user storage handler
166 UserStorageHandler::getInstance()->shutdown();
167 }
168 catch (\Exception $exception) {
169 die("<pre>WCF::destruct() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
170 }
171 }
172
173 /**
174 * Removes slashes in superglobal gpc data arrays if 'magic quotes gpc' is enabled.
175 */
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);
181 }
182 if (!empty($_POST)) {
183 $_POST = ArrayUtil::stripslashes($_POST);
184 }
185 if (!empty($_GET)) {
186 $_GET = ArrayUtil::stripslashes($_GET);
187 }
188 if (!empty($_COOKIE)) {
189 $_COOKIE = ArrayUtil::stripslashes($_COOKIE);
190 }
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);
196 }
197 }
198 }
199 }
200 }
201 }
202
203 if (function_exists('set_magic_quotes_runtime')) {
204 @set_magic_quotes_runtime(0);
205 }
206 }
207
208 /**
209 * Returns the database object.
210 *
211 * @return \wcf\system\database\Database
212 */
213 public static final function getDB() {
214 return self::$dbObj;
215 }
216
217 /**
218 * Returns the session object.
219 *
220 * @return \wcf\system\session\SessionHandler
221 */
222 public static final function getSession() {
223 return self::$sessionObj;
224 }
225
226 /**
227 * Returns the user object.
228 *
229 * @return \wcf\data\user\User
230 */
231 public static final function getUser() {
232 return self::getSession()->getUser();
233 }
234
235 /**
236 * Returns the language object.
237 *
238 * @return \wcf\data\language\Language
239 */
240 public static final function getLanguage() {
241 return self::$languageObj;
242 }
243
244 /**
245 * Returns the template object.
246 *
247 * @return \wcf\system\template\TemplateEngine
248 */
249 public static final function getTPL() {
250 return self::$tplObj;
251 }
252
253 /**
254 * Calls the show method on the given exception.
255 *
256 * @param \Exception $e
257 */
258 public static final function handleException(\Exception $e) {
259 try {
260 if ($e instanceof IPrintableException) {
261 $e->show();
262 exit;
263 }
264
265 // repack Exception
266 self::handleException(new SystemException($e->getMessage(), $e->getCode(), '', $e));
267 }
268 catch (\Exception $exception) {
269 die("<pre>WCF::handleException() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
270 }
271 }
272
273 /**
274 * Catches php errors and throws instead a system exception.
275 *
276 * @param integer $errorNo
277 * @param string $message
278 * @param string $filename
279 * @param integer $lineNo
280 */
281 public static final function handleError($errorNo, $message, $filename, $lineNo) {
282 if (error_reporting() != 0) {
283 $type = 'error';
284 switch ($errorNo) {
285 case 2: $type = 'warning';
286 break;
287 case 8: $type = 'notice';
288 break;
289 }
290
291 throw new SystemException('PHP '.$type.' in file '.$filename.' ('.$lineNo.'): '.$message, 0);
292 }
293 }
294
295 /**
296 * Loads the database configuration and creates a new connection to the database.
297 */
298 protected function initDB() {
299 // get configuration
300 $dbHost = $dbUser = $dbPassword = $dbName = '';
301 $dbPort = 0;
302 $dbClass = 'wcf\system\database\MySQLDatabase';
303 require(WCF_DIR.'config.inc.php');
304
305 // create database connection
306 self::$dbObj = new $dbClass($dbHost, $dbUser, $dbPassword, $dbName, $dbPort);
307 }
308
309 /**
310 * Loads the options file, automatically created if not exists.
311 */
312 protected function loadOptions() {
313 $filename = WCF_DIR.'options.inc.php';
314
315 // create options file if doesn't exist
316 if (!file_exists($filename) || filemtime($filename) <= 1) {
317 OptionEditor::rebuild();
318 }
319 require_once($filename);
320 }
321
322 /**
323 * Starts the session system.
324 */
325 protected function initSession() {
326 $factory = new SessionFactory();
327 $factory->load();
328
329 self::$sessionObj = SessionHandler::getInstance();
330 }
331
332 /**
333 * Initialises the language engine.
334 */
335 protected function initLanguage() {
336 if (isset($_GET['l']) && !self::getUser()->userID) {
337 self::getSession()->setLanguageID(intval($_GET['l']));
338 }
339
340 // set mb settings
341 mb_internal_encoding('UTF-8');
342 if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
343 mb_language('uni');
344
345 // get language
346 self::$languageObj = LanguageFactory::getInstance()->getUserLanguage(self::getSession()->getLanguageID());
347 }
348
349 /**
350 * Initialises the template engine.
351 */
352 protected function initTPL() {
353 self::$tplObj = TemplateEngine::getInstance();
354 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
355 $this->assignDefaultTemplateVariables();
356
357 $this->initStyle();
358 }
359
360 /**
361 * Initializes the user's style.
362 */
363 protected function initStyle() {
364 if (isset($_REQUEST['styleID'])) {
365 self::getSession()->setStyleID(intval($_REQUEST['styleID']));
366 }
367
368 StyleHandler::getInstance()->changeStyle(self::getSession()->getStyleID());
369 }
370
371 /**
372 * Executes the blacklist.
373 */
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();
378 }
379 }
380 if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS != '') {
381 if (!StringUtil::executeWordFilter(self::getSession()->userAgent, BLACKLIST_USER_AGENTS)) {
382 throw new PermissionDeniedException();
383 }
384 }
385 if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES != '') {
386 if (!StringUtil::executeWordFilter(@gethostbyaddr(self::getSession()->ipAddress), BLACKLIST_HOSTNAMES)) {
387 throw new PermissionDeniedException();
388 }
389 }
390
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);
395 }
396 else {
397 throw new NamedUserException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
398 }
399 }
400 }
401
402 /**
403 * Initializes applications.
404 */
405 protected function initApplications() {
406 // step 1) load all applications
407 $loadedApplications = array();
408
409 // register WCF as application
410 self::$applications['wcf'] = ApplicationHandler::getInstance()->getWCF();
411
412 if (PACKAGE_ID == 1) {
413 return;
414 }
415
416 // start main application
417 $application = ApplicationHandler::getInstance()->getActiveApplication();
418 $loadedApplications[] = $this->loadApplication($application);
419
420 // register primary application
421 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
422 self::$applications[$abbreviation] = $application;
423
424 // start dependent applications
425 $applications = ApplicationHandler::getInstance()->getDependentApplications();
426 foreach ($applications as $application) {
427 $loadedApplications[] = $this->loadApplication($application, true);
428 }
429
430 // step 2) run each application
431 if (!class_exists('wcf\system\WCFACP', false)) {
432 foreach ($loadedApplications as $application) {
433 $application->__run();
434 }
435
436 // refresh the session 1 minute before it expires
437 self::getTPL()->assign('__sessionKeepAlive', (SESSION_TIMEOUT - 60));
438 }
439 }
440
441 /**
442 * Loads an application.
443 *
444 * @param \wcf\data\application\Application $application
445 * @param boolean $isDependentApplication
446 * @return \wcf\system\application\IApplication
447 */
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);
454
455 // package cache is outdated, discard cache
456 if ($package->packageID) {
457 PackageEditor::resetCache();
458 }
459 else {
460 // package id is invalid
461 throw new SystemException("application identified by package id '".$application->packageID."' is unknown");
462 }
463 }
464
465 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
466 $packageDir = FileUtil::getRealPath(WCF_DIR.$package->packageDir);
467 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
468
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);
475 }
476 else {
477 throw new SystemException('Unable to load configuration for '.$package->package);
478 }
479
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/');
484 }
485
486 // init application and assign it as template variable
487 $applicationObject = call_user_func(array($className, 'getInstance'));
488 $this->getTPL()->assign('__'.$abbreviation, $applicationObject);
489 }
490 else {
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'.");
493 }
494
495 // register template path in ACP
496 if (class_exists('wcf\system\WCFACP', false)) {
497 $this->getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
498 }
499 else if (!$isDependentApplication) {
500 // assign base tag
501 $this->getTPL()->assign('baseHref', $application->getPageURL());
502 }
503
504 // register application
505 self::$applications[$abbreviation] = $application;
506
507 return $applicationObject;
508 }
509
510 /**
511 * Loads an application on runtime, do not use this outside the package installation.
512 *
513 * @param integer $packageID
514 */
515 public static function loadRuntimeApplication($packageID) {
516 $package = new Package($packageID);
517 $application = new Application($packageID);
518
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/');
524 }
525
526 /**
527 * Initializes core object cache.
528 */
529 protected function initCoreObjects() {
530 // ignore core objects if installing WCF
531 if (PACKAGE_ID == 0) {
532 return;
533 }
534
535 self::$coreObjectCache = CoreObjectCacheBuilder::getInstance()->getData();
536 }
537
538 /**
539 * Assigns some default variables to the template engine.
540 */
541 protected function assignDefaultTemplateVariables() {
542 self::getTPL()->registerPrefilter(array('event', 'hascontent', 'lang'));
543 self::getTPL()->assign(array(
544 '__wcf' => $this,
545 '__wcfVersion' => mb_substr(sha1(WCF_VERSION), 0, 8)
546 ));
547 }
548
549 /**
550 * Wrapper for the getter methods of this class.
551 *
552 * @param string $name
553 * @return mixed value
554 */
555 public function __get($name) {
556 $method = 'get'.ucfirst($name);
557 if (method_exists($this, $method)) {
558 return $this->$method();
559 }
560
561 throw new SystemException("method '".$method."' does not exist in class WCF");
562 }
563
564 /**
565 * Changes the active language.
566 *
567 * @param integer $languageID
568 */
569 public static final function setLanguage($languageID) {
570 self::$languageObj = LanguageFactory::getInstance()->getLanguage($languageID);
571 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
572 }
573
574 /**
575 * Includes the required util or exception classes automatically.
576 *
577 * @param string $className
578 * @see spl_autoload_register()
579 */
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);
586 }
587 if (isset(self::$autoloadDirectories[$applicationPrefix])) {
588 $classPath = self::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
589 if (file_exists($classPath)) {
590 require_once($classPath);
591 }
592 }
593 }
594 }
595
596 /**
597 * @see \wcf\system\WCF::__callStatic()
598 */
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);
603 }
604
605 return $this->$name($arguments);
606 }
607
608 /**
609 * Returns dynamically loaded core objects.
610 *
611 * @param string $name
612 * @param array $arguments
613 */
614 public static final function __callStatic($name, array $arguments) {
615 $className = preg_replace('~^get~', '', $name);
616
617 if (isset(self::$coreObject[$className])) {
618 return self::$coreObject[$className];
619 }
620
621 $objectName = self::getCoreObject($className);
622 if ($objectName === null) {
623 throw new SystemException("Core object '".$className."' is unknown.");
624 }
625
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'");
629 }
630
631 self::$coreObject[$className] = call_user_func(array($objectName, 'getInstance'));
632 return self::$coreObject[$className];
633 }
634 }
635
636 /**
637 * Searches for cached core object definition.
638 *
639 * @param string $className
640 * @return string
641 */
642 protected static final function getCoreObject($className) {
643 if (isset(self::$coreObjectCache[$className])) {
644 return self::$coreObjectCache[$className];
645 }
646
647 return null;
648 }
649
650 /**
651 * Returns true if the debug mode is enabled, otherwise false.
652 *
653 * @return boolean
654 */
655 public static function debugModeIsEnabled() {
656 // ACP override
657 if (self::$overrideDebugMode) {
658 return true;
659 }
660 else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE) {
661 return true;
662 }
663
664 return false;
665 }
666
667 /**
668 * Returns true if benchmarking is enabled, otherwise false.
669 *
670 * @return boolean
671 */
672 public static function benchmarkIsEnabled() {
673 // benchmarking is enabled by default
674 if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK) return true;
675 return false;
676 }
677
678 /**
679 * Returns domain path for given application.
680 *
681 * @param string $abbreviation
682 * @return string
683 */
684 public static function getPath($abbreviation = 'wcf') {
685 // workaround during WCFSetup
686 if (!PACKAGE_ID) {
687 return '../';
688 }
689
690 if (!isset(self::$applications[$abbreviation])) {
691 $abbreviation = 'wcf';
692 }
693
694 return self::$applications[$abbreviation]->getPageURL();
695 }
696
697 /**
698 * Returns a fully qualified anchor for current page.
699 *
700 * @param string $fragment
701 * @return string
702 */
703 public function getAnchor($fragment) {
704 return self::getRequestURI() . '#' . $fragment;
705 }
706
707 /**
708 * Returns the URI of the current page.
709 *
710 * @return string
711 */
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, '/'));
719 }
720
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);
724 }
725 $path = FileUtil::removeLeadingSlash($path);
726 $baseHref = self::getTPL()->get('baseHref');
727
728 if (!empty($path) && mb_strpos($path, '?') !== 0) {
729 $baseHref .= 'index.php/';
730 }
731
732 return $baseHref . $path;
733 }
734
735 /**
736 * Returns style handler.
737 *
738 * @return \wcf\system\style\StyleHandler
739 */
740 public function getStyleHandler() {
741 return StyleHandler::getInstance();
742 }
743
744 /**
745 * Returns number of available updates.
746 *
747 * @return integer
748 */
749 public function getAvailableUpdates() {
750 $data = PackageUpdateCacheBuilder::getInstance()->getData();
751 return $data['updates'];
752 }
753
754 /**
755 * Initialises the cronjobs.
756 */
757 protected function initCronjobs() {
758 if (PACKAGE_ID) {
759 self::getTPL()->assign('executeCronjobs', CronjobScheduler::getInstance()->getNextExec() < TIME_NOW);
760 }
761 }
762 }