50fb7058f124eb16dd6745924ae7188c79f2ce65
[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 * true if Zend Opcache is loaded and enabled
118 * @var boolean
119 */
120 protected static $zendOpcacheEnabled = null;
121
122 /**
123 * Calls all init functions of the WCF class.
124 */
125 public function __construct() {
126 // add autoload directory
127 self::$autoloadDirectories['wcf'] = WCF_DIR . 'lib/';
128
129 // define tmp directory
130 if (!defined('TMP_DIR')) define('TMP_DIR', FileUtil::getTempFolder());
131
132 // start initialization
133 $this->initMagicQuotes();
134 $this->initDB();
135 $this->loadOptions();
136 $this->initSession();
137 $this->initLanguage();
138 $this->initTPL();
139 $this->initCronjobs();
140 $this->initCoreObjects();
141 $this->initApplications();
142 $this->initBlacklist();
143
144 EventHandler::getInstance()->fireAction($this, 'initialized');
145 }
146
147 /**
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.
152 */
153 public static function destruct() {
154 try {
155 // database has to be initialized
156 if (!is_object(self::$dbObj)) return;
157
158 // flush output
159 if (ob_get_level() && ini_get('output_handler')) {
160 ob_flush();
161 }
162 else {
163 flush();
164 }
165
166 // update session
167 if (is_object(self::getSession())) {
168 self::getSession()->update();
169 }
170
171 // execute shutdown actions of user storage handler
172 UserStorageHandler::getInstance()->shutdown();
173 }
174 catch (\Exception $exception) {
175 die("<pre>WCF::destruct() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
176 }
177 }
178
179 /**
180 * Removes slashes in superglobal gpc data arrays if 'magic quotes gpc' is enabled.
181 */
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);
187 }
188 if (!empty($_POST)) {
189 $_POST = ArrayUtil::stripslashes($_POST);
190 }
191 if (!empty($_GET)) {
192 $_GET = ArrayUtil::stripslashes($_GET);
193 }
194 if (!empty($_COOKIE)) {
195 $_COOKIE = ArrayUtil::stripslashes($_COOKIE);
196 }
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);
202 }
203 }
204 }
205 }
206 }
207 }
208
209 if (function_exists('set_magic_quotes_runtime')) {
210 @set_magic_quotes_runtime(0);
211 }
212 }
213
214 /**
215 * Returns the database object.
216 *
217 * @return \wcf\system\database\Database
218 */
219 public static final function getDB() {
220 return self::$dbObj;
221 }
222
223 /**
224 * Returns the session object.
225 *
226 * @return \wcf\system\session\SessionHandler
227 */
228 public static final function getSession() {
229 return self::$sessionObj;
230 }
231
232 /**
233 * Returns the user object.
234 *
235 * @return \wcf\data\user\User
236 */
237 public static final function getUser() {
238 return self::getSession()->getUser();
239 }
240
241 /**
242 * Returns the language object.
243 *
244 * @return \wcf\data\language\Language
245 */
246 public static final function getLanguage() {
247 return self::$languageObj;
248 }
249
250 /**
251 * Returns the template object.
252 *
253 * @return \wcf\system\template\TemplateEngine
254 */
255 public static final function getTPL() {
256 return self::$tplObj;
257 }
258
259 /**
260 * Calls the show method on the given exception.
261 *
262 * @param \Exception $e
263 */
264 public static final function handleException(\Exception $e) {
265 try {
266 if ($e instanceof IPrintableException) {
267 $e->show();
268 exit;
269 }
270
271 // repack Exception
272 self::handleException(new SystemException($e->getMessage(), $e->getCode(), '', $e));
273 }
274 catch (\Exception $exception) {
275 die("<pre>WCF::handleException() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
276 }
277 }
278
279 /**
280 * Catches php errors and throws instead a system exception.
281 *
282 * @param integer $errorNo
283 * @param string $message
284 * @param string $filename
285 * @param integer $lineNo
286 */
287 public static final function handleError($errorNo, $message, $filename, $lineNo) {
288 if (error_reporting() != 0) {
289 $type = 'error';
290 switch ($errorNo) {
291 case 2: $type = 'warning';
292 break;
293 case 8: $type = 'notice';
294 break;
295 }
296
297 throw new SystemException('PHP '.$type.' in file '.$filename.' ('.$lineNo.'): '.$message, 0);
298 }
299 }
300
301 /**
302 * Loads the database configuration and creates a new connection to the database.
303 */
304 protected function initDB() {
305 // get configuration
306 $dbHost = $dbUser = $dbPassword = $dbName = '';
307 $dbPort = 0;
308 $dbClass = 'wcf\system\database\MySQLDatabase';
309 require(WCF_DIR.'config.inc.php');
310
311 // create database connection
312 self::$dbObj = new $dbClass($dbHost, $dbUser, $dbPassword, $dbName, $dbPort);
313 }
314
315 /**
316 * Loads the options file, automatically created if not exists.
317 */
318 protected function loadOptions() {
319 $filename = WCF_DIR.'options.inc.php';
320
321 // create options file if doesn't exist
322 if (!file_exists($filename) || filemtime($filename) <= 1) {
323 OptionEditor::rebuild();
324 }
325 require_once($filename);
326 }
327
328 /**
329 * Starts the session system.
330 */
331 protected function initSession() {
332 $factory = new SessionFactory();
333 $factory->load();
334
335 self::$sessionObj = SessionHandler::getInstance();
336 }
337
338 /**
339 * Initialises the language engine.
340 */
341 protected function initLanguage() {
342 if (isset($_GET['l']) && !self::getUser()->userID) {
343 self::getSession()->setLanguageID(intval($_GET['l']));
344 }
345
346 // set mb settings
347 mb_internal_encoding('UTF-8');
348 if (function_exists('mb_regex_encoding')) mb_regex_encoding('UTF-8');
349 mb_language('uni');
350
351 // get language
352 self::$languageObj = LanguageFactory::getInstance()->getUserLanguage(self::getSession()->getLanguageID());
353 }
354
355 /**
356 * Initialises the template engine.
357 */
358 protected function initTPL() {
359 self::$tplObj = TemplateEngine::getInstance();
360 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
361 $this->assignDefaultTemplateVariables();
362
363 $this->initStyle();
364 }
365
366 /**
367 * Initializes the user's style.
368 */
369 protected function initStyle() {
370 if (isset($_REQUEST['styleID'])) {
371 self::getSession()->setStyleID(intval($_REQUEST['styleID']));
372 }
373
374 StyleHandler::getInstance()->changeStyle(self::getSession()->getStyleID());
375 }
376
377 /**
378 * Executes the blacklist.
379 */
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();
384 }
385 }
386 if (defined('BLACKLIST_USER_AGENTS') && BLACKLIST_USER_AGENTS != '') {
387 if (!StringUtil::executeWordFilter(self::getSession()->userAgent, BLACKLIST_USER_AGENTS)) {
388 throw new PermissionDeniedException();
389 }
390 }
391 if (defined('BLACKLIST_HOSTNAMES') && BLACKLIST_HOSTNAMES != '') {
392 if (!StringUtil::executeWordFilter(@gethostbyaddr(self::getSession()->ipAddress), BLACKLIST_HOSTNAMES)) {
393 throw new PermissionDeniedException();
394 }
395 }
396
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);
401 }
402 else {
403 throw new NamedUserException(self::getLanguage()->getDynamicVariable('wcf.user.error.isBanned'));
404 }
405 }
406 }
407
408 /**
409 * Initializes applications.
410 */
411 protected function initApplications() {
412 // step 1) load all applications
413 $loadedApplications = array();
414
415 // register WCF as application
416 self::$applications['wcf'] = ApplicationHandler::getInstance()->getWCF();
417
418 if (PACKAGE_ID == 1) {
419 return;
420 }
421
422 // start main application
423 $application = ApplicationHandler::getInstance()->getActiveApplication();
424 $loadedApplications[] = $this->loadApplication($application);
425
426 // register primary application
427 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
428 self::$applications[$abbreviation] = $application;
429
430 // start dependent applications
431 $applications = ApplicationHandler::getInstance()->getDependentApplications();
432 foreach ($applications as $application) {
433 $loadedApplications[] = $this->loadApplication($application, true);
434 }
435
436 // step 2) run each application
437 if (!class_exists('wcf\system\WCFACP', false)) {
438 foreach ($loadedApplications as $application) {
439 $application->__run();
440 }
441
442 // refresh the session 1 minute before it expires
443 self::getTPL()->assign('__sessionKeepAlive', (SESSION_TIMEOUT - 60));
444 }
445 }
446
447 /**
448 * Loads an application.
449 *
450 * @param \wcf\data\application\Application $application
451 * @param boolean $isDependentApplication
452 * @return \wcf\system\application\IApplication
453 */
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);
460
461 // package cache is outdated, discard cache
462 if ($package->packageID) {
463 PackageEditor::resetCache();
464 }
465 else {
466 // package id is invalid
467 throw new SystemException("application identified by package id '".$application->packageID."' is unknown");
468 }
469 }
470
471 $abbreviation = ApplicationHandler::getInstance()->getAbbreviation($application->packageID);
472 $packageDir = FileUtil::getRealPath(WCF_DIR.$package->packageDir);
473 self::$autoloadDirectories[$abbreviation] = $packageDir . 'lib/';
474
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);
481 }
482 else {
483 throw new SystemException('Unable to load configuration for '.$package->package);
484 }
485
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/');
490 }
491
492 // init application and assign it as template variable
493 $applicationObject = call_user_func(array($className, 'getInstance'));
494 $this->getTPL()->assign('__'.$abbreviation, $applicationObject);
495 }
496 else {
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'.");
499 }
500
501 // register template path in ACP
502 if (class_exists('wcf\system\WCFACP', false)) {
503 $this->getTPL()->addApplication($abbreviation, $packageDir . 'acp/templates/');
504 }
505 else if (!$isDependentApplication) {
506 // assign base tag
507 $this->getTPL()->assign('baseHref', $application->getPageURL());
508 }
509
510 // register application
511 self::$applications[$abbreviation] = $application;
512
513 return $applicationObject;
514 }
515
516 /**
517 * Loads an application on runtime, do not use this outside the package installation.
518 *
519 * @param integer $packageID
520 */
521 public static function loadRuntimeApplication($packageID) {
522 $package = new Package($packageID);
523 $application = new Application($packageID);
524
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/');
530 }
531
532 /**
533 * Initializes core object cache.
534 */
535 protected function initCoreObjects() {
536 // ignore core objects if installing WCF
537 if (PACKAGE_ID == 0) {
538 return;
539 }
540
541 self::$coreObjectCache = CoreObjectCacheBuilder::getInstance()->getData();
542 }
543
544 /**
545 * Assigns some default variables to the template engine.
546 */
547 protected function assignDefaultTemplateVariables() {
548 self::getTPL()->registerPrefilter(array('event', 'hascontent', 'lang'));
549 self::getTPL()->assign(array(
550 '__wcf' => $this,
551 '__wcfVersion' => mb_substr(sha1(WCF_VERSION), 0, 8)
552 ));
553 }
554
555 /**
556 * Wrapper for the getter methods of this class.
557 *
558 * @param string $name
559 * @return mixed value
560 */
561 public function __get($name) {
562 $method = 'get'.ucfirst($name);
563 if (method_exists($this, $method)) {
564 return $this->$method();
565 }
566
567 throw new SystemException("method '".$method."' does not exist in class WCF");
568 }
569
570 /**
571 * Changes the active language.
572 *
573 * @param integer $languageID
574 */
575 public static final function setLanguage($languageID) {
576 self::$languageObj = LanguageFactory::getInstance()->getLanguage($languageID);
577 self::getTPL()->setLanguageID(self::getLanguage()->languageID);
578 }
579
580 /**
581 * Includes the required util or exception classes automatically.
582 *
583 * @param string $className
584 * @see spl_autoload_register()
585 */
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);
592 }
593 if (isset(self::$autoloadDirectories[$applicationPrefix])) {
594 $classPath = self::$autoloadDirectories[$applicationPrefix] . implode('/', $namespaces) . '.class.php';
595 if (file_exists($classPath)) {
596 require_once($classPath);
597 }
598 }
599 }
600 }
601
602 /**
603 * @see \wcf\system\WCF::__callStatic()
604 */
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);
609 }
610
611 return $this->$name($arguments);
612 }
613
614 /**
615 * Returns dynamically loaded core objects.
616 *
617 * @param string $name
618 * @param array $arguments
619 */
620 public static final function __callStatic($name, array $arguments) {
621 $className = preg_replace('~^get~', '', $name);
622
623 if (isset(self::$coreObject[$className])) {
624 return self::$coreObject[$className];
625 }
626
627 $objectName = self::getCoreObject($className);
628 if ($objectName === null) {
629 throw new SystemException("Core object '".$className."' is unknown.");
630 }
631
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'");
635 }
636
637 self::$coreObject[$className] = call_user_func(array($objectName, 'getInstance'));
638 return self::$coreObject[$className];
639 }
640 }
641
642 /**
643 * Searches for cached core object definition.
644 *
645 * @param string $className
646 * @return string
647 */
648 protected static final function getCoreObject($className) {
649 if (isset(self::$coreObjectCache[$className])) {
650 return self::$coreObjectCache[$className];
651 }
652
653 return null;
654 }
655
656 /**
657 * Returns true if the debug mode is enabled, otherwise false.
658 *
659 * @return boolean
660 */
661 public static function debugModeIsEnabled() {
662 // ACP override
663 if (self::$overrideDebugMode) {
664 return true;
665 }
666 else if (defined('ENABLE_DEBUG_MODE') && ENABLE_DEBUG_MODE) {
667 return true;
668 }
669
670 return false;
671 }
672
673 /**
674 * Returns true if benchmarking is enabled, otherwise false.
675 *
676 * @return boolean
677 */
678 public static function benchmarkIsEnabled() {
679 // benchmarking is enabled by default
680 if (!defined('ENABLE_BENCHMARK') || ENABLE_BENCHMARK) return true;
681 return false;
682 }
683
684 /**
685 * Returns domain path for given application.
686 *
687 * @param string $abbreviation
688 * @return string
689 */
690 public static function getPath($abbreviation = 'wcf') {
691 // workaround during WCFSetup
692 if (!PACKAGE_ID) {
693 return '../';
694 }
695
696 if (!isset(self::$applications[$abbreviation])) {
697 $abbreviation = 'wcf';
698 }
699
700 return self::$applications[$abbreviation]->getPageURL();
701 }
702
703 /**
704 * Returns a fully qualified anchor for current page.
705 *
706 * @param string $fragment
707 * @return string
708 */
709 public function getAnchor($fragment) {
710 return self::getRequestURI() . '#' . $fragment;
711 }
712
713 /**
714 * Returns the URI of the current page.
715 *
716 * @return string
717 */
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, '/'));
725 }
726
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);
730 }
731 $path = FileUtil::removeLeadingSlash($path);
732 $baseHref = self::getTPL()->get('baseHref');
733
734 if (!empty($path) && mb_strpos($path, '?') !== 0) {
735 $baseHref .= 'index.php/';
736 }
737
738 return $baseHref . $path;
739 }
740
741 /**
742 * Resets Zend Opcache cache if installed and enabled.
743 *
744 * @param string $script
745 */
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;
750 }
751
752 self::$zendOpcacheEnabled = false;
753 }
754
755 if (self::$zendOpcacheEnabled) {
756 if (empty($script)) {
757 opcache_reset();
758 }
759 else {
760 opcache_invalidate($script, true);
761 }
762 }
763 }
764
765 /**
766 * Returns style handler.
767 *
768 * @return \wcf\system\style\StyleHandler
769 */
770 public function getStyleHandler() {
771 return StyleHandler::getInstance();
772 }
773
774 /**
775 * Returns number of available updates.
776 *
777 * @return integer
778 */
779 public function getAvailableUpdates() {
780 $data = PackageUpdateCacheBuilder::getInstance()->getData();
781 return $data['updates'];
782 }
783
784 /**
785 * Initialises the cronjobs.
786 */
787 protected function initCronjobs() {
788 if (PACKAGE_ID) {
789 self::getTPL()->assign('executeCronjobs', CronjobScheduler::getInstance()->getNextExec() < TIME_NOW);
790 }
791 }
792 }