ILIAS  release_8 Revision v8.26
class.ilInitialisation.php
Go to the documentation of this file.
1<?php
2
19// TODO:
48
49require_once("libs/composer/vendor/autoload.php");
50
51// needed for slow queries, etc.
52if (!isset($GLOBALS['ilGlobalStartTime']) || !$GLOBALS['ilGlobalStartTime']) {
53 $GLOBALS['ilGlobalStartTime'] = microtime();
54}
55
56global $DIC;
57if (null === $DIC) {
58 // Don't remove this, intellisense autocompletion does not work in PhpStorm without a top level assignment
59 $DIC = new Container();
60}
61
72{
76 protected static function removeUnsafeCharacters(): void
77 {
78 // Remove unsafe characters from GET parameters.
79 // We do not need this characters in any case, so it is
80 // feasible to filter them everytime. POST parameters
81 // need attention through ilUtil::stripSlashes() and similar functions)
83 }
84
89 protected static function recursivelyRemoveUnsafeCharacters($var)
90 {
91 if (is_array($var)) {
92 $mod = [];
93 foreach ($var as $k => $v) {
96 }
97 return $mod;
98 }
99 return strip_tags(
100 str_replace(
101 array("\x00", "\n", "\r", "\\", "'", '"', "\x1a"),
102 "",
103 $var
104 )
105 );
106 }
107
111 protected static function requireCommonIncludes(): void
112 {
114 require_once "include/inc.ilias_version.php";
115
116 self::initGlobal("ilBench", "ilBenchmark", "./Services/Utilities/classes/class.ilBenchmark.php");
117 }
118
123 protected static function includePhp5Compliance(): void
124 {
127 require_once("include/inc.xml5compliance.php");
128 }
130 require_once("include/inc.xsl5compliance.php");
131 }
132
139 protected static function initIliasIniFile(): void
140 {
141 $ilIliasIniFile = new ilIniFile("./ilias.ini.php");
142 $ilIliasIniFile->read();
143 self::initGlobal('ilIliasIniFile', $ilIliasIniFile);
144
145 // initialize constants
146 if (!defined('ILIAS_DATA_DIR')) {
147 define("ILIAS_DATA_DIR", $ilIliasIniFile->readVariable("clients", "datadir"));
148 }
149 if (!defined('ILIAS_WEB_DIR')) {
150 define("ILIAS_WEB_DIR", $ilIliasIniFile->readVariable("clients", "path"));
151 }
152 if (!defined("ILIAS_ABSOLUTE_PATH")) {
153 define("ILIAS_ABSOLUTE_PATH", $ilIliasIniFile->readVariable('server', 'absolute_path'));
154 }
155
156 // logging
157 define("ILIAS_LOG_DIR", $ilIliasIniFile->readVariable("log", "path"));
158 define("ILIAS_LOG_FILE", $ilIliasIniFile->readVariable("log", "file"));
159 if (!defined("ILIAS_LOG_ENABLED")) {
160 define("ILIAS_LOG_ENABLED", $ilIliasIniFile->readVariable("log", "enabled"));
161 }
162 define("ILIAS_LOG_LEVEL", $ilIliasIniFile->readVariable("log", "level"));
163
164 // read path + command for third party tools from ilias.ini
165 define("PATH_TO_CONVERT", $ilIliasIniFile->readVariable("tools", "convert"));
166 define("PATH_TO_FFMPEG", $ilIliasIniFile->readVariable("tools", "ffmpeg"));
167 define("PATH_TO_ZIP", $ilIliasIniFile->readVariable("tools", "zip"));
168 define("PATH_TO_MKISOFS", $ilIliasIniFile->readVariable("tools", "mkisofs"));
169 define("PATH_TO_UNZIP", $ilIliasIniFile->readVariable("tools", "unzip"));
170 define("PATH_TO_GHOSTSCRIPT", $ilIliasIniFile->readVariable("tools", "ghostscript"));
171 define("PATH_TO_JAVA", $ilIliasIniFile->readVariable("tools", "java"));
172 define("URL_TO_LATEX", $ilIliasIniFile->readVariable("tools", "latex"));
173 define("PATH_TO_FOP", $ilIliasIniFile->readVariable("tools", "fop"));
174 define("PATH_TO_LESSC", $ilIliasIniFile->readVariable("tools", "lessc"));
175 define("PATH_TO_PHANTOMJS", $ilIliasIniFile->readVariable("tools", "phantomjs"));
176
177 if ($ilIliasIniFile->groupExists('error')) {
178 if ($ilIliasIniFile->variableExists('error', 'editor_url')) {
179 define("ERROR_EDITOR_URL", $ilIliasIniFile->readVariable('error', 'editor_url'));
180 }
181
182 if ($ilIliasIniFile->variableExists('error', 'editor_path_translations')) {
183 define(
184 "ERROR_EDITOR_PATH_TRANSLATIONS",
185 $ilIliasIniFile->readVariable('error', 'editor_path_translations')
186 );
187 }
188 }
189
190 // read virus scanner settings
191 switch ($ilIliasIniFile->readVariable("tools", "vscantype")) {
192 case "sophos":
193 define("IL_VIRUS_SCANNER", "Sophos");
194 define("IL_VIRUS_SCAN_COMMAND", $ilIliasIniFile->readVariable("tools", "scancommand"));
195 define("IL_VIRUS_CLEAN_COMMAND", $ilIliasIniFile->readVariable("tools", "cleancommand"));
196 break;
197
198 case "antivir":
199 define("IL_VIRUS_SCANNER", "AntiVir");
200 define("IL_VIRUS_SCAN_COMMAND", $ilIliasIniFile->readVariable("tools", "scancommand"));
201 define("IL_VIRUS_CLEAN_COMMAND", $ilIliasIniFile->readVariable("tools", "cleancommand"));
202 break;
203
204 case "clamav":
205 define("IL_VIRUS_SCANNER", "ClamAV");
206 define("IL_VIRUS_SCAN_COMMAND", $ilIliasIniFile->readVariable("tools", "scancommand"));
207 define("IL_VIRUS_CLEAN_COMMAND", $ilIliasIniFile->readVariable("tools", "cleancommand"));
208 break;
209 case "icap":
210 define("IL_VIRUS_SCANNER", "icap");
211 define("IL_ICAP_HOST", $ilIliasIniFile->readVariable("tools", "icap_host"));
212 define("IL_ICAP_PORT", $ilIliasIniFile->readVariable("tools", "icap_port"));
213 define("IL_ICAP_AV_COMMAND", $ilIliasIniFile->readVariable("tools", "icap_service_name"));
214 define("IL_ICAP_CLIENT", $ilIliasIniFile->readVariable("tools", "icap_client_path"));
215 break;
216
217 default:
218 define("IL_VIRUS_SCANNER", "None");
219 define("IL_VIRUS_CLEAN_COMMAND", '');
220 break;
221 }
222
224 define("IL_TIMEZONE", $tz);
225 }
226
227 protected static function initResourceStorage(): void
228 {
229 global $DIC;
230 (new InitResourceStorage())->init($DIC);
231 }
232
243 public static function bootstrapFilesystems(): void
244 {
245 global $DIC;
246
247 $DIC['filesystem.security.sanitizing.filename'] = function (Container $c) {
249 $c->fileServiceSettings()
250 );
251 };
252
253 $DIC['filesystem.factory'] = function ($c) {
254 return new \ILIAS\Filesystem\Provider\DelegatingFilesystemFactory($c['filesystem.security.sanitizing.filename']);
255 };
256
257 $DIC['filesystem.web'] = function ($c) {
258 //web
259
263 $delegatingFactory = $c['filesystem.factory'];
264 $webConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_ABSOLUTE_PATH . '/' . ILIAS_WEB_DIR . '/' . CLIENT_ID);
265 return $delegatingFactory->getLocal($webConfiguration);
266 };
267
268 $DIC['filesystem.storage'] = function ($c) {
269 //storage
270
274 $delegatingFactory = $c['filesystem.factory'];
275 $storageConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_DATA_DIR . '/' . CLIENT_ID);
276 return $delegatingFactory->getLocal($storageConfiguration);
277 };
278
279 $DIC['filesystem.temp'] = function ($c) {
280 //temp
281
285 $delegatingFactory = $c['filesystem.factory'];
286 $tempConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_DATA_DIR . '/' . CLIENT_ID . '/temp');
287 return $delegatingFactory->getLocal($tempConfiguration);
288 };
289
290 $DIC['filesystem.customizing'] = function ($c) {
291 //customizing
292
296 $delegatingFactory = $c['filesystem.factory'];
297 $customizingConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_ABSOLUTE_PATH . '/' . 'Customizing');
298 return $delegatingFactory->getLocal($customizingConfiguration);
299 };
300
301 $DIC['filesystem.libs'] = function ($c) {
302 //customizing
303
307 $delegatingFactory = $c['filesystem.factory'];
308 $customizingConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_ABSOLUTE_PATH . '/' . 'libs');
309 return $delegatingFactory->getLocal($customizingConfiguration, true);
310 };
311
312 $DIC['filesystem.node_modules'] = function ($c) {
313 //customizing
314
318 $delegatingFactory = $c['filesystem.factory'];
319 $customizingConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_ABSOLUTE_PATH . '/' . 'node_modules');
320 return $delegatingFactory->getLocal($customizingConfiguration, true);
321 };
322
323 $DIC['filesystem'] = function ($c) {
324 return new \ILIAS\Filesystem\FilesystemsImpl(
325 $c['filesystem.storage'],
326 $c['filesystem.web'],
327 $c['filesystem.temp'],
328 $c['filesystem.customizing'],
329 $c['filesystem.libs'],
330 $c['filesystem.node_modules']
331 );
332 };
333 }
334
341 public static function initFileUploadService(\ILIAS\DI\Container $dic): void
342 {
343 $dic['upload.processor-manager'] = function ($c) {
344 return new PreProcessorManagerImpl();
345 };
346
347 $dic['upload'] = function (\ILIAS\DI\Container $c) {
348 $fileUploadImpl = new \ILIAS\FileUpload\FileUploadImpl(
349 $c['upload.processor-manager'],
350 $c['filesystem'],
351 $c['http']
352 );
353 if ((defined('IL_VIRUS_SCANNER') && IL_VIRUS_SCANNER != "None") || (defined('IL_SCANNER_TYPE') && IL_SCANNER_TYPE == "1")) {
354 $fileUploadImpl->register(new ilVirusScannerPreProcessor(ilVirusScannerFactory::_getInstance()));
355 }
356
357 $fileUploadImpl->register(new FilenameSanitizerPreProcessor());
358 $fileUploadImpl->register(
360 $c->fileServiceSettings(),
361 $c->language()->txt("msg_info_blacklisted")
362 )
363 );
364 $fileUploadImpl->register(new InsecureFilenameSanitizerPreProcessor());
365 $fileUploadImpl->register(new SVGBlacklistPreProcessor(
366 $c->language()->txt("upload_svg_rejection_message"),
367 $c->language()->txt("upload_svg_rejection_message_script"),
368 $c->language()->txt("upload_svg_rejection_message_base64"),
369 $c->language()->txt("upload_svg_rejection_message_foreign_object"),
370 $c->language()->txt("upload_svg_rejection_message_elements")
371 ));
372
373 return $fileUploadImpl;
374 };
375 }
376
380 protected static function buildHTTPPath(): bool
381 {
382 global $DIC;
383
384 if ($DIC['https']->isDetected()) {
385 $protocol = 'https://';
386 } else {
387 $protocol = 'http://';
388 }
389 $host = $_SERVER['HTTP_HOST'];
390
391 $rq_uri = strip_tags($_SERVER['REQUEST_URI']);
392
393 // security fix: this failed, if the URI contained "?" and following "/"
394 // -> we remove everything after "?"
395 if (is_int($pos = strpos($rq_uri, "?"))) {
396 $rq_uri = substr($rq_uri, 0, $pos);
397 }
398
399 if (!defined('ILIAS_MODULE')) {
400 $path = pathinfo($rq_uri);
401 if (isset($path['extension']) && $path['extension'] !== '') {
402 $uri = dirname($rq_uri);
403 } else {
404 $uri = $rq_uri;
405 }
406 } else {
407 // if in module remove module name from HTTP_PATH
408 $path = dirname($rq_uri);
409
410 // dirname cuts the last directory from a directory path e.g content/classes return content
412
413 $dirs = explode('/', $module);
414 $uri = $path;
415 foreach ($dirs as $dir) {
416 $uri = dirname($uri);
417 }
418 }
419
420 $ilias_http_path = ilContext::modifyHttpPath(implode('', [$protocol, $host, $uri]));
421
422 // remove everything after the first .php in the path
423 $ilias_http_path = preg_replace('/(http|https)(:\/\/)(.*?\/.*?\.php).*/', '$1$2$3', $ilias_http_path);
424
425 $f = new \ILIAS\Data\Factory();
426 $uri = $f->uri(ilFileUtils::removeTrailingPathSeparators($ilias_http_path));
427
428 $base_URI = $uri->getBaseURI();
429
430 return define('ILIAS_HTTP_PATH', $base_URI);
431 }
432
437 protected static function determineClient(): void
438 {
439 if (defined('CLIENT_ID')) {
440 return;
441 }
442 global $DIC;
443 $df = new \ILIAS\Data\Factory();
444
445 // check whether ini file object exists
446 if (!$DIC->isDependencyAvailable('iliasIni')) {
447 self::abortAndDie('Fatal Error: ilInitialisation::determineClient called without initialisation of ILIAS ini file object.');
448 }
449
450 // determine the available clientIds (default, request, cookie)
451 $default_client_id = $DIC->iliasIni()->readVariable('clients', 'default');
452
453 if ($DIC->http()->wrapper()->query()->has('client_id')) {
454 $client_id_from_get = $DIC->http()->wrapper()->query()->retrieve(
455 'client_id',
456 self::getClientIdTransformation()
457 );
458 }
459 if ($DIC->http()->wrapper()->cookie()->has('ilClientId')) {
460 $client_id_from_cookie = $DIC->http()->wrapper()->cookie()->retrieve(
461 'ilClientId',
462 self::getClientIdTransformation()
463 );
464 }
465
466 // set the clientId by availability: 1. request, 2. cookie, fallback to defined default
467 $client_id_to_use = '';
468 if (isset($client_id_from_get) && $client_id_from_get !== '') {
469 $client_id_to_use = $client_id_from_get;
470 }
471
472 if ($client_id_to_use === '' && isset($client_id_from_cookie)) {
473 $client_id_to_use = $client_id_from_cookie;
474 }
475
476 $client_id_to_use = $client_id_to_use ?: $default_client_id;
477
478 define('CLIENT_ID', $df->clientId($client_id_to_use)->toString());
479 }
480
481
488 private static function getClientIdTransformation(): Transformation
489 {
490 return new class () implements Transformation {
494 public function transform($from): string
495 {
496 if (!is_string($from)) {
497 throw new InvalidArgumentException(__METHOD__ . " the argument is not a string.");
498 }
499 return strip_tags($from);
500 }
501
505 public function applyTo(Result $result): Result
506 {
507 return $result->then(function ($value): Result {
508 try {
509 return new Ok($this->transform($value));
510 } catch (Exception $exception) {
511 return new Error($exception);
512 }
513 });
514 }
515
519 public function __invoke($from): string
520 {
521 return $this->transform($from);
522 }
523 };
524 }
525
535 protected static function initClientIniFile(): void
536 {
537 global $ilIliasIniFile;
538
539 // check whether ILIAS_WEB_DIR is set.
540 if (ILIAS_WEB_DIR == "") {
541 self::abortAndDie("Fatal Error: ilInitialisation::initClientIniFile called without ILIAS_WEB_DIR.");
542 }
543
544 // check whether CLIENT_ID is set.
545 if (CLIENT_ID == "") {
546 self::abortAndDie("Fatal Error: ilInitialisation::initClientIniFile called without CLIENT_ID.");
547 }
548
549 $ini_file = "/client.ini.php";
550 if (defined('CLIENT_WEB_DIR')) {
551 $ini_file = CLIENT_WEB_DIR . $ini_file;
552 } else {
553 $ini_file = "./" . ILIAS_WEB_DIR . "/" . CLIENT_ID . "/client.ini.php";
554 }
555
556 // get settings from ini file
557 $ilClientIniFile = new ilIniFile($ini_file);
558 $ilClientIniFile->read();
559
560 // invalid client id / client ini
561 if ($ilClientIniFile->ERROR != "") {
562 $default_client = $ilIliasIniFile->readVariable("clients", "default");
563 if (CLIENT_ID !== "") {
564 $mess = array("en" => "Client does not exist.",
565 "de" => "Mandant ist ungültig."
566 );
567 self::redirect("index.php?client_id=" . $default_client, '', $mess);
568 } else {
569 self::abortAndDie("Fatal Error: ilInitialisation::initClientIniFile initializing client ini file abborted with: " . $ilClientIniFile->ERROR);
570 }
571 }
572
573 self::initGlobal("ilClientIniFile", $ilClientIniFile);
574 // set constants
575 define("DEBUG", (int) $ilClientIniFile->readVariable("system", "DEBUG"));
576 define("DEVMODE", (int) $ilClientIniFile->readVariable("system", "DEVMODE"));
577 define("SHOWNOTICES", (int) $ilClientIniFile->readVariable("system", "SHOWNOTICES"));
578 if (!defined("ROOT_FOLDER_ID")) {
579 define("ROOT_FOLDER_ID", (int) $ilClientIniFile->readVariable('system', 'ROOT_FOLDER_ID'));
580 }
581 if (!defined("SYSTEM_FOLDER_ID")) {
582 define("SYSTEM_FOLDER_ID", (int) $ilClientIniFile->readVariable('system', 'SYSTEM_FOLDER_ID'));
583 }
584 if (!defined("ROLE_FOLDER_ID")) {
585 define("ROLE_FOLDER_ID", (int) $ilClientIniFile->readVariable('system', 'ROLE_FOLDER_ID'));
586 }
587 define("MAIL_SETTINGS_ID", (int) $ilClientIniFile->readVariable('system', 'MAIL_SETTINGS_ID'));
588 $error_handler = $ilClientIniFile->readVariable('system', 'ERROR_HANDLER');
589 define("ERROR_HANDLER", $error_handler ?: "PRETTY_PAGE");
590
591 // this is for the online help installation, which sets OH_REF_ID to the
592 // ref id of the online module
593 define("OH_REF_ID", (int) $ilClientIniFile->readVariable("system", "OH_REF_ID"));
594
595 // see ilObject::TITLE_LENGTH, ilObject::DESC_LENGTH
596 // define ("MAXLENGTH_OBJ_TITLE",125);#$ilClientIniFile->readVariable('system','MAXLENGTH_OBJ_TITLE'));
597 // define ("MAXLENGTH_OBJ_DESC",$ilClientIniFile->readVariable('system','MAXLENGTH_OBJ_DESC'));
598
599 if (!defined("CLIENT_DATA_DIR")) {
600 define("CLIENT_DATA_DIR", ILIAS_DATA_DIR . "/" . CLIENT_ID);
601 }
602 if (!defined("CLIENT_WEB_DIR")) {
603 define("CLIENT_WEB_DIR", ILIAS_ABSOLUTE_PATH . "/" . ILIAS_WEB_DIR . "/" . CLIENT_ID);
604 }
605 define("CLIENT_NAME", $ilClientIniFile->readVariable('client', 'name')); // Change SS
606
607 $db_type = $ilClientIniFile->readVariable("db", "type");
608 if ($db_type === "") {
609 define("IL_DB_TYPE", ilDBConstants::TYPE_INNODB);
610 } else {
611 define("IL_DB_TYPE", $db_type);
612 }
613
614 $ilGlobalCacheSettings = new ilGlobalCacheSettings();
615 $ilGlobalCacheSettings->readFromIniFile($ilClientIniFile);
616 ilGlobalCache::setup($ilGlobalCacheSettings);
617 }
618
622 protected static function handleMaintenanceMode(): void
623 {
624 global $ilClientIniFile;
625
626 if (!$ilClientIniFile->readVariable("client", "access")) {
627 $mess = array(
628 "en" => "The server is not available due to maintenance." .
629 " We apologise for any inconvenience.",
630 "de" => "Der Server ist aufgrund von Wartungsarbeiten aktuell nicht verf&uuml;gbar." .
631 " Wir bitten um Verst&auml;ndnis. Versuchen Sie es sp&auml;ter noch einmal."
632 );
633 $mess_id = "init_error_maintenance";
634
635 if (ilContext::hasHTML() && is_file("./maintenance.html")) {
636 self::redirect("./maintenance.html", $mess_id, $mess);
637 } else {
638 $mess = self::translateMessage($mess_id, $mess);
639 self::abortAndDie($mess);
640 }
641 }
642 }
643
647 protected static function initDatabase(): void
648 {
649 // build dsn of database connection and connect
651 $ilDB->initFromIniFile();
652 $ilDB->connect();
653
654 self::initGlobal("ilDB", $ilDB);
655 }
656
661 public static function setSessionHandler(): void
662 {
663 $db_session_handler = new ilSessionDBHandler();
664 if (!$db_session_handler->setSaveHandler()) {
665 self::abortAndDie("Cannot start session handling.");
666 }
667
668 // Do not accept external session ids
669 if (!ilSession::_exists(session_id()) && !defined('IL_PHPUNIT_TEST')) {
670 // php7-todo, correct-with-php5-removal : alex, 1.3.2016: added if, please check
671 if (function_exists("session_status") && session_status() == PHP_SESSION_ACTIVE) {
672 session_regenerate_id();
673 }
674 }
675 }
676
680 protected static function setCookieConstants(): void
681 {
683 $cookie_path = '/';
684 } elseif (isset($GLOBALS['COOKIE_PATH'])) {
685 // use a predefined cookie path from WebAccessChecker
686 $cookie_path = $GLOBALS['COOKIE_PATH'];
687 } else {
688 $cookie_path = dirname($_SERVER['PHP_SELF']);
689 }
690
691 /* if ilias is called directly within the docroot $cookie_path
692 is set to '/' expecting on servers running under windows..
693 here it is set to '\'.
694 in both cases a further '/' won't be appended due to the following regex
695 */
696 $cookie_path .= (!preg_match("/[\/|\\\\]$/", $cookie_path)) ? "/" : "";
697
698 if ($cookie_path == "\\") {
699 $cookie_path = '/';
700 }
701
702 define('IL_COOKIE_HTTPONLY', true); // Default Value
703 define('IL_COOKIE_EXPIRE', 0);
704 define('IL_COOKIE_DOMAIN', '');
705 if (!defined('IL_COOKIE_PATH')) {
706 // Might be already defined by ./sso/index.php or other scripts (like those in ./Services/SAML/lib/*)
707 define('IL_COOKIE_PATH', $cookie_path);
708 }
709 }
710
711 private static function setClientIdCookie(): void
712 {
713 if (defined('CLIENT_ID') &&
714 !defined('IL_PHPUNIT_TEST') &&
716 ilUtil::setCookie('ilClientId', CLIENT_ID);
717 }
718 }
719
723 protected static function setSessionCookieParams(): void
724 {
725 global $ilSetting, $DIC;
726
727 if (!defined('IL_COOKIE_SECURE')) {
728 // If this code is executed, we can assume that \ilHTTPS::enableSecureCookies was NOT called before
729 // \ilHTTPS::enableSecureCookies already executes session_set_cookie_params()
730
731 $cookie_secure = !$ilSetting->get('https', '0') && $DIC['https']->isDetected();
732 define('IL_COOKIE_SECURE', $cookie_secure); // Default Value
733
734 $cookie_parameters = [
735 'lifetime' => IL_COOKIE_EXPIRE,
736 'path' => IL_COOKIE_PATH,
737 'domain' => IL_COOKIE_DOMAIN,
738 'secure' => IL_COOKIE_SECURE,
739 'httponly' => IL_COOKIE_HTTPONLY,
740 ];
741
742 if (
743 $cookie_secure &&
744 (!isset(session_get_cookie_params()['samesite']) || strtolower(session_get_cookie_params()['samesite']) !== 'strict')
745 ) {
746 $cookie_parameters['samesite'] = 'Lax';
747 }
748
749 session_set_cookie_params($cookie_parameters);
750 }
751 }
752
753 protected static function initMail(\ILIAS\DI\Container $c): void
754 {
755 $c["mail.mime.transport.factory"] = static function (\ILIAS\DI\Container $c) {
756 return new \ilMailMimeTransportFactory($c->settings(), $c->event());
757 };
758 $c["mail.mime.sender.factory"] = static function (\ILIAS\DI\Container $c) {
759 return new \ilMailMimeSenderFactory($c->settings());
760 };
761 $c["mail.texttemplates.service"] = static function (\ILIAS\DI\Container $c) {
762 return new \ilMailTemplateService(new \ilMailTemplateRepository($c->database()));
763 };
764 }
765
766 protected static function initCron(\ILIAS\DI\Container $c): void
767 {
768 $c['cron.repository'] = static function (\ILIAS\DI\Container $c): ilCronJobRepository {
769 return new ilCronJobRepositoryImpl(
770 $c->database(),
771 $c->settings(),
772 $c->logger()->cron(),
773 $c['component.repository'],
774 $c['component.factory']
775 );
776 };
777
778 $c['cron.manager'] = static function (\ILIAS\DI\Container $c): ilCronManager {
779 return new ilCronManagerImpl(
780 $c['cron.repository'],
781 $c->database(),
782 $c->settings(),
783 $c->logger()->cron(),
784 (new \ILIAS\Data\Factory())->clock()
785 );
786 };
787 }
788
792 protected static function initCustomObjectIcons(\ILIAS\DI\Container $c): void
793 {
794 $c["object.customicons.factory"] = function ($c) {
795 return new ilObjectCustomIconFactory(
796 $c->filesystem()->web(),
797 $c->upload(),
798 $c['ilObjDataCache']
799 );
800 };
801 }
802
803 protected static function initAvatar(\ILIAS\DI\Container $c): void
804 {
805 $c["user.avatar.factory"] = function ($c) {
806 return new \ilUserAvatarFactory($c);
807 };
808 }
809
810 protected static function initTermsOfService(\ILIAS\DI\Container $c): void
811 {
812 $c['tos.criteria.type.factory'] = function (
816 $c->rbac()->review(),
817 $c['ilObjDataCache'],
819 );
820 };
821
822 $c['tos.service'] = function (\ILIAS\DI\Container $c): ilTermsOfServiceHelper {
823 $persistence = new ilTermsOfServiceDataGatewayFactory();
824 $persistence->setDatabaseAdapter($c->database());
825 return new ilTermsOfServiceHelper(
826 $persistence,
827 $c['tos.document.evaluator'],
828 $c['tos.criteria.type.factory'],
830 );
831 };
832
833 $c['tos.document.evaluator'] = function (\ILIAS\DI\Container $c): ilTermsOfServiceDocumentEvaluation {
836 $c['tos.criteria.type.factory'],
837 $c->user(),
838 $c->logger()->tos()
839 ),
840 $c->user(),
841 $c->logger()->tos(),
842 ilTermsOfServiceDocument::orderBy('sorting')->get()
843 );
844 };
845 }
846
847 protected static function initAccessibilityControlConcept(\ILIAS\DI\Container $c): void
848 {
849 $c['acc.criteria.type.factory'] = function (\ILIAS\DI\Container $c) {
850 return new ilAccessibilityCriterionTypeFactory($c->rbac()->review(), $c['ilObjDataCache']);
851 };
852
853 $c['acc.document.evaluator'] = function (\ILIAS\DI\Container $c) {
856 $c['acc.criteria.type.factory'],
857 $c->user(),
858 $c->logger()->acc()
859 ),
860 $c->user(),
861 $c->logger()->acc(),
862 \ilAccessibilityDocument::orderBy('sorting')->get()
863 );
864 };
865 }
866
871 protected static function initSettings(): void
872 {
873 global $ilSetting;
874
876 "ilSetting",
877 "ilSetting",
878 "Services/Administration/classes/class.ilSetting.php"
879 );
880
881 // check correct setup
882 if (!$ilSetting->get("setup_ok")) {
883 self::abortAndDie("Setup is not completed. Please run setup routine again.");
884 }
885
886 // set anonymous user & role id and system role id
887 define("ANONYMOUS_USER_ID", (int) $ilSetting->get("anonymous_user_id"));
888 define("ANONYMOUS_ROLE_ID", (int) $ilSetting->get("anonymous_role_id"));
889 define("SYSTEM_USER_ID", (int) $ilSetting->get("system_user_id"));
890 define("SYSTEM_ROLE_ID", (int) $ilSetting->get("system_role_id"));
891 define("USER_FOLDER_ID", 7);
892
893 // recovery folder
894 define("RECOVERY_FOLDER_ID", (int) $ilSetting->get("recovery_folder_id"));
895
896 // installation id
897 define("IL_INST_ID", $ilSetting->get("inst_id", '0'));
898
899 // define default suffix replacements
900 define("SUFFIX_REPL_DEFAULT", "php,php3,php4,inc,lang,phtml,htaccess");
901 define("SUFFIX_REPL_ADDITIONAL", $ilSetting->get("suffix_repl_additional", ""));
902
903 if (ilContext::usesHTTP()) {
905 }
906 }
907
911 protected static function initStyle(): void
912 {
913 global $DIC;
914 $component_factory = $DIC["component.factory"];
915
916 // load style definitions
918 "styleDefinition",
919 "ilStyleDefinition",
920 "./Services/Style/System/classes/class.ilStyleDefinition.php"
921 );
922
923 // add user interface hook for style initialisation
924 foreach ($component_factory->getActivePluginsInSlot("uihk") as $ui_plugin) {
925 $gui_class = $ui_plugin->getUIClassInstance();
926 $gui_class->modifyGUI("Services/Init", "init_style", array("styleDefinition" => $DIC->systemStyle()));
927 }
928 }
929
933 public static function initUserAccount(): void
934 {
935 global $DIC;
936
937 static $context_init;
938
939 $uid = $GLOBALS['DIC']['ilAuthSession']->getUserId();
940 if ($uid) {
941 $DIC->user()->setId($uid);
942 $DIC->user()->read();
943 if (!isset($context_init)) {
944 if ($DIC->user()->isAnonymous()) {
945 $DIC->globalScreen()->tool()->context()->claim()->external();
946 } else {
947 $DIC->globalScreen()->tool()->context()->claim()->internal();
948 }
949 $context_init = true;
950 }
951 // init console log handler
952 ilLoggerFactory::getInstance()->initUser($DIC->user()->getLogin());
954 } else {
955 if (is_object($GLOBALS['ilLog'])) {
956 $GLOBALS['ilLog']->logStack();
957 }
958 self::abortAndDie("Init user account failed");
959 }
960 }
961
965 protected static function initLocale(): void
966 {
967 global $ilSetting;
968
969 if (trim($ilSetting->get("locale", '')) != "") {
970 $larr = explode(",", trim($ilSetting->get("locale")));
971 $ls = array();
972 $first = $larr[0];
973 foreach ($larr as $l) {
974 if (trim($l) != "") {
975 $ls[] = $l;
976 }
977 }
978 if (count($ls) > 0) {
979 setlocale(LC_ALL, $ls);
980
981 // #15347 - making sure that floats are not changed
982 setlocale(LC_NUMERIC, "C");
983 }
984 }
985 }
986
990 public static function goToPublicSection(): void
991 {
992 global $DIC;
993
994 if (ANONYMOUS_USER_ID == "") {
995 self::abortAndDie("Public Section enabled, but no Anonymous user found.");
996 }
997
998 $session_destroyed = false;
999 if ($DIC['ilAuthSession']->isExpired()) {
1000 $session_destroyed = true;
1002 }
1003 if (!$DIC['ilAuthSession']->isAuthenticated()) {
1004 $session_destroyed = true;
1006 }
1007
1008 if ($session_destroyed) {
1009 $GLOBALS['DIC']['ilAuthSession']->setAuthenticated(true, ANONYMOUS_USER_ID);
1010 }
1011
1013
1014 $target = '';
1015 if ($DIC->http()->wrapper()->query()->has('target')) {
1016 $target = $DIC->http()->wrapper()->query()->retrieve(
1017 'target',
1018 $DIC->refinery()->kindlyTo()->string()
1019 );
1020 }
1021
1022 // if target given, try to go there
1023 if (strlen($target)) {
1024 // when we are already "inside" goto.php no redirect is needed
1025 $current_script = substr(strrchr($_SERVER["PHP_SELF"], "/"), 1);
1026 if ($current_script == "goto.php") {
1027 return;
1028 }
1029 // goto will check if target is accessible or redirect to login
1030 self::redirect("goto.php?target=" . $_GET["target"]);
1031 }
1032
1033 // we do not know if ref_id of request is accesible, so redirecting to root
1035 "ilias.php?baseClass=ilrepositorygui&reloadpublic=1&cmd=&ref_id=" . (defined(
1036 'ROOT_FOLDER_ID'
1037 ) ? (string) ROOT_FOLDER_ID : '0')
1038 );
1039 }
1040
1044 protected static function goToLogin(): void
1045 {
1046 global $DIC;
1047
1048 $session_expired = false;
1049 ilLoggerFactory::getLogger('init')->debug('Redirecting to login page.');
1050
1051 if ($DIC['ilAuthSession']->isExpired()) {
1053 $session_expired = true;
1054 }
1055 if (!$DIC['ilAuthSession']->isAuthenticated()) {
1057 }
1058
1059 $target = $DIC->http()->wrapper()->query()->has('target')
1060 ? $DIC->http()->wrapper()->query()->retrieve(
1061 'target',
1062 $DIC->refinery()->kindlyTo()->string()
1063 )
1064 : '';
1065
1066 if (strlen($target)) {
1067 $target = "target=" . $target . "&";
1068 }
1069
1070 $client_id = $DIC->http()->wrapper()->cookie()->retrieve(
1071 'ilClientId',
1072 $DIC->refinery()->byTrying([
1073 $DIC->refinery()->kindlyTo()->string(),
1074 $DIC->refinery()->always('')
1075 ])
1076 );
1077 $script = "login.php?" . $target . "client_id=" . $client_id;
1078 $script .= $session_expired ? "&session_expired=1" : "";
1079
1081 $script,
1082 "init_error_authentication_fail",
1083 array(
1084 "en" => "Authentication failed.",
1085 "de" => "Authentifizierung fehlgeschlagen."
1086 )
1087 );
1088 }
1089
1093 protected static function initLanguage(bool $a_use_user_language = true): void
1094 {
1095 global $DIC;
1096
1100 global $rbacsystem;
1101
1102 if ($a_use_user_language) {
1103 if ($DIC->offsetExists('lng')) {
1104 $DIC->offsetUnset('lng');
1105 }
1107 } else {
1109 }
1110 if (is_object($rbacsystem) && $DIC->offsetExists('tree')) {
1111 $rbacsystem->initMemberView();
1112 }
1113 }
1114
1118 protected static function initAccessHandling(): void
1119 {
1121 'rbacreview',
1122 'ilRbacReview',
1123 './Services/AccessControl/classes/class.ilRbacReview.php',
1124 true
1125 );
1126
1127 $rbacsystem = ilRbacSystem::getInstance();
1128 self::initGlobal('rbacsystem', $rbacsystem, null, true);
1129
1131 'rbacadmin',
1132 'ilRbacAdmin',
1133 './Services/AccessControl/classes/class.ilRbacAdmin.php',
1134 true
1135 );
1136
1138 'ilAccess',
1139 'ilAccess',
1140 './Services/AccessControl/classes/class.ilAccess.php',
1141 true
1142 );
1143 }
1144
1148 protected static function initLog(): void
1149 {
1151
1152 self::initGlobal("ilLog", $log);
1153 // deprecated
1154 self::initGlobal("log", $log);
1155 }
1156
1160 protected static function initGlobal(
1161 string $a_name,
1162 $a_class,
1163 ?string $a_source_file = null,
1164 ?bool $destroy_existing = false
1165 ): void {
1166 global $DIC;
1167
1168 if ($destroy_existing) {
1169 if (isset($GLOBALS[$a_name])) {
1170 unset($GLOBALS[$a_name]);
1171 }
1172 if (isset($DIC[$a_name])) {
1173 unset($DIC[$a_name]);
1174 }
1175 }
1176
1177 $GLOBALS[$a_name] = is_object($a_class) ? $a_class : new $a_class();
1178
1179 $DIC[$a_name] = static function (Container $c) use ($a_name) {
1180 return $GLOBALS[$a_name];
1181 };
1182 }
1183
1184 protected static function abortAndDie(string $a_message): void
1185 {
1186 if (isset($GLOBALS['ilLog'])) {
1187 $GLOBALS['ilLog']->write("Fatal Error: ilInitialisation - " . $a_message);
1188 $GLOBALS['ilLog']->logStack();
1189 }
1190 die($a_message);
1191 }
1192
1196 protected static function handleDevMode(): void
1197 {
1198 if ((defined(SHOWNOTICES) && SHOWNOTICES) || version_compare(PHP_VERSION, '8.0', '>=')) {
1199 error_reporting(-1);
1200 }
1201 }
1202
1203 protected static bool $already_initialized = false;
1204
1205 public static function reinitILIAS(): void
1206 {
1207 self::$already_initialized = false;
1208 self::initILIAS();
1209 }
1210
1211 public static function reInitUser(): void
1212 {
1214 self::initSession();
1215 self::initUser();
1216
1218 self::resumeUserSession();
1219 }
1220 }
1221 }
1222
1226 public static function initILIAS(): void
1227 {
1228 if (self::$already_initialized) {
1229 return;
1230 }
1231
1232 $GLOBALS["DIC"] = new Container();
1233 $GLOBALS["DIC"]["ilLoggerFactory"] = function ($c) {
1235 };
1236
1237 self::$already_initialized = true;
1238
1239 self::initCore();
1240 self::initHTTPServices($GLOBALS["DIC"]);
1241 if (ilContext::initClient()) {
1242 self::initClient();
1243 self::initFileUploadService($GLOBALS["DIC"]);
1244 self::initSession();
1245
1246 if (ilContext::hasUser()) {
1247 self::initUser();
1248
1250 self::resumeUserSession();
1251 }
1252 }
1253
1254 // init after Auth otherwise breaks CAS
1255 self::includePhp5Compliance();
1256
1257 // language may depend on user setting
1258 self::initLanguage(true);
1259 $GLOBALS['DIC']['tree']->initLangCode();
1260
1261 self::initInjector($GLOBALS['DIC']);
1262 self::initBackgroundTasks($GLOBALS['DIC']);
1263 self::initKioskMode($GLOBALS['DIC']);
1264
1265 if (ilContext::hasHTML()) {
1266 self::initHTML();
1267 }
1268 }
1269
1270 // this MUST happen after everything else is initialized,
1271 // because this leads to rather unexpected behaviour which
1272 // is super hard to track down to this.
1273 self::replaceSuperGlobals($GLOBALS['DIC']);
1274 }
1275
1279 protected static function initSession(): void
1280 {
1281 if (isset($GLOBALS['DIC']['ilAuthSession'])) {
1282 unset($GLOBALS['DIC']['ilAuthSession']);
1283 }
1284
1285 $GLOBALS['DIC']['ilAuthSession'] = static function (Container $c): ilAuthSession {
1286 $auth_session = ilAuthSession::getInstance(
1287 $c['ilLoggerFactory']->getLogger('auth')
1288 );
1289 $auth_session->init();
1290 return $auth_session;
1291 };
1292 }
1293
1297 public static function handleErrorReporting(): void
1298 {
1299 // push the error level as high as possible / sane
1300 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
1301
1302 // see handleDevMode() - error reporting might be overwritten again
1303 // but we need the client ini first
1304 }
1305
1309 protected static function initCore(): void
1310 {
1311 global $ilErr;
1312
1313 self::handleErrorReporting();
1314
1315 // breaks CAS: must be included after CAS context isset in AuthUtils
1316 //self::includePhp5Compliance();
1317
1318 self::requireCommonIncludes();
1319
1320 $GLOBALS["DIC"]["ilias.version"] = (new ILIAS\Data\Factory())->version(ILIAS_VERSION_NUMERIC);
1321
1322 // error handler
1323 self::initGlobal(
1324 "ilErr",
1325 "ilErrorHandling",
1326 "./Services/Init/classes/class.ilErrorHandling.php"
1327 );
1330 [
1331 $ilErr, 'errorHandler'
1332 ]
1333 );
1334
1335 self::removeUnsafeCharacters();
1336
1337 self::initIliasIniFile();
1338
1339 define('IL_INITIAL_WD', getcwd());
1340
1341 // deprecated
1342 self::initGlobal("ilias", "ILIAS", "./Services/Init/classes/class.ilias.php");
1343 }
1344
1348 protected static function initClient(): void
1349 {
1350 global $https, $ilias, $DIC;
1351
1352 self::setCookieConstants();
1353
1354 self::determineClient();
1355
1356 self::bootstrapFilesystems();
1357
1358 self::initResourceStorage();
1359
1360 self::initClientIniFile();
1361
1362 // --- needs client ini
1363
1364 $ilias->client_id = (string) CLIENT_ID;
1365
1366 if (DEVMODE) {
1367 self::handleDevMode();
1368 }
1369
1370 self::handleMaintenanceMode();
1371
1372 self::initDatabase();
1373
1374 self::initComponentService($DIC);
1375
1376 // init dafault language
1377 self::initLanguage(false);
1378
1379 // moved after databases
1380 self::initLog();
1381
1382 self::initGlobal(
1383 "ilAppEventHandler",
1384 "ilAppEventHandler",
1385 "./Services/EventHandling/classes/class.ilAppEventHandler.php"
1386 );
1387
1388 // there are rare cases where initILIAS is called twice for a request
1389 // example goto.php is called and includes ilias.php later
1390 // we must prevent that ilPluginAdmin is initialized twice in
1391 // this case, since this won't get the values out of plugin.php the
1392 // second time properly
1393 if (!isset($DIC["ilPluginAdmin"]) || !$DIC["ilPluginAdmin"] instanceof ilPluginAdmin) {
1394 self::initGlobal(
1395 "ilPluginAdmin",
1396 new ilPluginAdmin($DIC["component.repository"]),
1397 "./Services/Component/classes/class.ilPluginAdmin.php"
1398 );
1399 }
1400 self::initGlobal("https", "ilHTTPS", "./Services/Http/classes/class.ilHTTPS.php");
1401 self::initSettings();
1402 self::setSessionHandler();
1403 self::initMail($GLOBALS['DIC']);
1404 self::initCron($GLOBALS['DIC']);
1405 self::initAvatar($GLOBALS['DIC']);
1406 self::initCustomObjectIcons($GLOBALS['DIC']);
1407 self::initTermsOfService($GLOBALS['DIC']);
1408 self::initAccessibilityControlConcept($GLOBALS['DIC']);
1409
1410 // --- needs settings
1411
1412 self::initLocale();
1413
1414 if (ilContext::usesHTTP()) {
1415 $https->enableSecureCookies();
1416 $https->checkProtocolAndRedirectIfNeeded();
1417 }
1418
1419 // --- object handling
1420
1421 self::initGlobal(
1422 "ilObjDataCache",
1423 "ilObjectDataCache",
1424 "./Services/Object/classes/class.ilObjectDataCache.php"
1425 );
1426
1427 self::initGlobal(
1428 "objDefinition",
1429 "ilObjectDefinition",
1430 "./Services/Object/classes/class.ilObjectDefinition.php"
1431 );
1432
1433 // $tree
1434 $tree = new ilTree(ROOT_FOLDER_ID);
1435 self::initGlobal("tree", $tree);
1436 unset($tree);
1437
1438 self::setSessionCookieParams();
1439 self::setClientIdCookie();
1440
1441 self::initRefinery($DIC);
1442
1443 (new InitCtrlService())->init($DIC);
1444
1445 // Init GlobalScreen
1446 self::initGlobalScreen($DIC);
1447 }
1448
1452 protected static function initUser(): void
1453 {
1454 global $ilias, $ilUser;
1455
1456 // $ilUser
1457 self::initGlobal(
1458 "ilUser",
1459 "ilObjUser",
1460 "./Services/User/classes/class.ilObjUser.php",
1461 true
1462 );
1463 $ilias->account = $ilUser;
1464
1465 self::initAccessHandling();
1466 }
1467
1471 public static function resumeUserSession(): void
1472 {
1473 global $DIC;
1474
1477 }
1478
1479 if (
1480 !$DIC['ilAuthSession']->isAuthenticated() or
1481 $DIC['ilAuthSession']->isExpired()
1482 ) {
1483 if ($GLOBALS['DIC']['ilAuthSession']->isExpired()) {
1485 }
1486 ilLoggerFactory::getLogger('init')->debug('Current session is invalid: ' . $GLOBALS['DIC']['ilAuthSession']->getId());
1487 $current_script = substr(strrchr($_SERVER["PHP_SELF"], "/"), 1);
1488 if (self::blockedAuthentication($current_script)) {
1489 ilLoggerFactory::getLogger('init')->debug('Authentication is started in current script.');
1490 // nothing todo: authentication is done in current script
1491 return;
1492 }
1493
1494 self::handleAuthenticationFail();
1495 return;
1496 }
1497 // valid session
1498
1499 self::initUserAccount();
1500 }
1501
1505 protected static function handleAuthenticationSuccess(): void
1506 {
1510 global $ilUser;
1511
1513 }
1514
1518 protected static function handleAuthenticationFail(): void
1519 {
1520 global $DIC;
1521
1522 ilLoggerFactory::getLogger('init')->debug('Handling of failed authentication.');
1523
1524 // #10608
1525 if (
1528 throw new Exception("Authentication failed.");
1529 }
1530
1531 if (($DIC->http()->request()->getQueryParams()['cmdMode'] ?? 0) === 'asynch') {
1532 $DIC->language()->loadLanguageModule('init');
1533 $DIC->http()->saveResponse(
1534 $DIC->http()->response()
1535 ->withStatus(403)
1536 ->withBody(Streams::ofString($DIC->language()->txt('init_error_authentication_fail')))
1537 );
1538 $DIC->http()->sendResponse();
1539 $DIC->http()->close();
1540 }
1541 if (
1542 $DIC['ilAuthSession']->isExpired() &&
1543 !\ilObjUser::_isAnonymous($DIC['ilAuthSession']->getUserId())
1544 ) {
1545 ilLoggerFactory::getLogger('init')->debug('Expired session found -> redirect to login page');
1546 self::goToLogin();
1547 return;
1548 }
1549 if (ilPublicSectionSettings::getInstance()->isEnabledForDomain($_SERVER['SERVER_NAME'])) {
1550 ilLoggerFactory::getLogger('init')->debug('Redirect to public section.');
1551 self::goToPublicSection();
1552 return;
1553 }
1554 ilLoggerFactory::getLogger('init')->debug('Redirect to login page.');
1555 self::goToLogin();
1556 }
1557
1561 protected static function initHTTPServices(\ILIAS\DI\Container $container): void
1562 {
1563 $init_http = new InitHttpServices();
1564 $init_http->init($container);
1565 }
1566
1570 private static function initGlobalScreen(\ILIAS\DI\Container $c): void
1571 {
1572 $c['global_screen'] = function () use ($c) {
1573 return new Services(
1575 $c->ui(),
1576 htmlentities(str_replace([" ", ".", "-"], "_", ILIAS_VERSION_NUMERIC))
1577 );
1578 };
1579 $c->globalScreen()->tool()->context()->stack()->clear();
1580 $c->globalScreen()->tool()->context()->claim()->main();
1581 }
1582
1586 public static function initUIFramework(\ILIAS\DI\Container $c): void
1587 {
1588 $init_ui = new InitUIFramework();
1589 $init_ui->init($c);
1590
1591 $component_repository = $c["component.repository"];
1592 $component_factory = $c["component.factory"];
1593 foreach ($component_repository->getPlugins() as $pl) {
1594 if (!$pl->isActive()) {
1595 continue;
1596 }
1597 $plugin = $component_factory->getPlugin($pl->getId());
1598 $c['ui.renderer'] = $plugin->exchangeUIRendererAfterInitialization($c);
1599
1600 foreach ($c->keys() as $key) {
1601 if (strpos($key, "ui.factory") === 0) {
1602 $c[$key] = $plugin->exchangeUIFactoryAfterInitialization($key, $c);
1603 }
1604 }
1605 }
1606 }
1607
1611 protected static function initRefinery(\ILIAS\DI\Container $container): void
1612 {
1613 $container['refinery'] = function ($container) {
1614 $dataFactory = new \ILIAS\Data\Factory();
1615 $language = $container['lng'];
1616
1617 return new \ILIAS\Refinery\Factory($dataFactory, $language);
1618 };
1619 }
1620
1624 protected static function replaceSuperGlobals(\ILIAS\DI\Container $container): void
1625 {
1627 $client_ini = $container['ilClientIniFile'];
1628
1629 $replace_super_globals = (
1630 !$client_ini->variableExists('server', 'prevent_super_global_replacement') ||
1631 !(bool) $client_ini->readVariable('server', 'prevent_super_global_replacement')
1632 );
1633
1634 if ($replace_super_globals) {
1635 $throwOnValueAssignment = defined('DEVMODE') && DEVMODE;
1636
1637 $_GET = new SuperGlobalDropInReplacement($container['refinery'], $_GET, $throwOnValueAssignment);
1638 $_POST = new SuperGlobalDropInReplacement($container['refinery'], $_POST, $throwOnValueAssignment);
1639 $_COOKIE = new SuperGlobalDropInReplacement($container['refinery'], $_COOKIE, $throwOnValueAssignment);
1640 $_REQUEST = new SuperGlobalDropInReplacement($container['refinery'], $_REQUEST, $throwOnValueAssignment);
1641 }
1642 }
1643
1644 protected static function initComponentService(\ILIAS\DI\Container $container): void
1645 {
1646 $init = new InitComponentService();
1647 $init->init($container);
1648 }
1649
1653 protected static function initHTML(): void
1654 {
1655 global $ilUser, $DIC;
1656
1657 if (ilContext::hasUser()) {
1658 // load style definitions
1659 // use the init function with plugin hook here, too
1660 self::initStyle();
1661 }
1662
1663 self::initUIFramework($GLOBALS["DIC"]);
1664 $tpl = new ilGlobalPageTemplate($DIC->globalScreen(), $DIC->ui(), $DIC->http());
1665 self::initGlobal("tpl", $tpl);
1666
1667 if (ilContext::hasUser()) {
1668 $dispatcher = new \ILIAS\Init\StartupSequence\StartUpSequenceDispatcher($DIC);
1669 $dispatcher->dispatch();
1670 }
1671
1672 self::initGlobal(
1673 "ilNavigationHistory",
1674 "ilNavigationHistory",
1675 "Services/Navigation/classes/class.ilNavigationHistory.php"
1676 );
1677
1678 self::initGlobal(
1679 "ilHelp",
1680 "ilHelpGUI",
1681 "Services/Help/classes/class.ilHelpGUI.php"
1682 );
1683
1684 self::initGlobal(
1685 "ilToolbar",
1686 "ilToolbarGUI",
1687 "./Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php"
1688 );
1689
1690 self::initGlobal(
1691 "ilLocator",
1692 "ilLocatorGUI",
1693 "./Services/Locator/classes/class.ilLocatorGUI.php"
1694 );
1695
1696 self::initGlobal(
1697 "ilTabs",
1698 "ilTabsGUI",
1699 "./Services/UIComponent/Tabs/classes/class.ilTabsGUI.php"
1700 );
1701
1702 if (ilContext::hasUser()) {
1703
1704 // set hits per page for all lists using table module
1705 $_GET['limit'] = (int) $ilUser->getPref('hits_per_page');
1706 ilSession::set('tbl_limit', $_GET['limit']);
1707
1708 // the next line makes it impossible to save the offset somehow in a session for
1709 // a specific table (I tried it for the user administration).
1710 // its not posssible to distinguish whether it has been set to page 1 (=offset = 0)
1711 // or not set at all (then we want the last offset, e.g. being used from a session var).
1712 // So I added the wrapping if statement. Seems to work (hopefully).
1713 // Alex April 14th 2006
1714 if (isset($_GET['offset']) && $_GET['offset'] != "") { // added April 14th 2006
1715 $_GET['offset'] = (int) $_GET['offset']; // old code
1716 }
1717
1718 self::initGlobal("lti", "ilLTIViewGUI", "./Services/LTI/classes/class.ilLTIViewGUI.php");
1719 $GLOBALS["DIC"]["lti"]->init();
1720 self::initKioskMode($GLOBALS["DIC"]);
1721 }
1722 }
1723
1724 protected static function getCurrentCmd(): string
1725 {
1726 $cmd = $_POST['cmd'] ?? ($_GET['cmd'] ?? '');
1727
1728 if (is_array($cmd)) {
1729 $cmd_keys = array_keys($cmd);
1730 $cmd = array_shift($cmd_keys) ?? '';
1731 }
1732
1733 return $cmd;
1734 }
1735
1739 protected static function blockedAuthentication(string $a_current_script): bool
1740 {
1741 global $DIC;
1742
1744 ilLoggerFactory::getLogger('init')->debug('Blocked authentication for WAC request.');
1745 return true;
1746 }
1748 ilLoggerFactory::getLogger('init')->debug('Blocked authentication for sso request.');
1749 return true;
1750 }
1752 ilLoggerFactory::getLogger('init')->debug('Blocked authentication for webdav request');
1753 return true;
1754 }
1756 ilLoggerFactory::getLogger('init')->debug('Blocked authentication for shibboleth request.');
1757 return true;
1758 }
1760 ilLoggerFactory::getLogger('init')->debug('Blocked authentication for lti provider requests.');
1761 return true;
1762 }
1764 ilLoggerFactory::getLogger('init')->debug('Blocked authentication for SAML request.');
1765 return true;
1766 }
1767 if (
1768 $a_current_script == "register.php" ||
1769 $a_current_script == "pwassist.php" ||
1770 $a_current_script == "confirmReg.php" ||
1771 $a_current_script == "il_securimage_play.php" ||
1772 $a_current_script == "il_securimage_show.php" ||
1773 $a_current_script == 'login.php'
1774 ) {
1775 ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for script: ' . $a_current_script);
1776 return true;
1777 }
1778
1779 $requestBaseClass = strtolower((string) ($_GET['baseClass'] ?? ''));
1780 if ($requestBaseClass == strtolower(ilStartUpGUI::class)) {
1781 $requestCmdClass = strtolower((string) ($_GET['cmdClass'] ?? ''));
1782 if (
1783 $requestCmdClass == strtolower(ilAccountRegistrationGUI::class) ||
1784 $requestCmdClass == strtolower(ilPasswordAssistanceGUI::class)
1785 ) {
1786 ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for cmdClass: ' . $requestCmdClass);
1787 return true;
1788 }
1789 $cmd = self::getCurrentCmd();
1790 if (
1791 $cmd == "showTermsOfService" ||
1792 $cmd == 'showAccountMigration' || $cmd == 'migrateAccount' ||
1793 $cmd == 'processCode' || $cmd == 'showLoginPage' || $cmd == 'showLogout' ||
1794 $cmd == 'doStandardAuthentication' || $cmd == 'doCasAuthentication'
1795 ) {
1796 ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for cmd: ' . $cmd);
1797 return true;
1798 }
1799 }
1800
1801 $target = '';
1802 if ($DIC->http()->wrapper()->query()->has('target')) {
1803 // @todo refinery undefind
1804 $target = $_GET['target'];
1805 }
1806
1807 // #12884
1808 if (
1809 ($a_current_script == "goto.php" && $target == "impr_0") ||
1810 $requestBaseClass == strtolower(ilImprintGUI::class)
1811 ) {
1812 ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for baseClass: ' . ($_GET['baseClass'] ?? ""));
1813 return true;
1814 }
1815
1816 if (
1817 (strtolower($requestCmdClass ?? "") === strtolower(ilAccessibilityControlConceptGUI::class))
1818 ) {
1819 ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for cmdClass: ' . $requestCmdClass);
1820 return true;
1821 }
1822
1823 if ($a_current_script == 'goto.php' && in_array($target, array(
1824 'usr_registration',
1825 'usr_nameassist',
1826 'usr_pwassist',
1827 'usr_agreement'
1828 ))) {
1829 ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for goto target: ' . $target);
1830 return true;
1831 }
1832 ilLoggerFactory::getLogger('auth')->debug('Authentication required');
1833 return false;
1834 }
1835
1839 protected static function translateMessage(string $a_message_id, array $a_message_static = null): string
1840 {
1841 global $ilDB, $lng, $ilSetting, $ilClientIniFile, $ilUser;
1842
1843 // current language
1844 if (!$lng) {
1845 $lang = "en";
1846 if ($ilUser) {
1847 $lang = $ilUser->getLanguage();
1848 } elseif (isset($_REQUEST["lang"])) {
1849 $lang = (string) $_REQUEST["lang"];
1850 } elseif ($ilSetting) {
1851 $lang = $ilSetting->get("language", '');
1852 } elseif ($ilClientIniFile) {
1853 $lang = $ilClientIniFile->readVariable("language", "default");
1854 }
1855 } else {
1856 $lang = $lng->getLangKey();
1857 }
1858
1859 $message = "";
1860 if ($ilDB && $a_message_id) {
1861 if (!$lng) {
1862 $lng = new ilLanguage($lang);
1863 }
1864
1865 $lng->loadLanguageModule("init");
1866 $message = $lng->txt($a_message_id);
1867 } elseif (is_array($a_message_static)) {
1868 if (!isset($a_message_static[$lang])) {
1869 $lang = "en";
1870 }
1871 $message = $a_message_static[$lang];
1872 }
1873 return $message;
1874 }
1875
1879 protected static function redirect(
1880 string $a_target,
1881 string $a_message_id = '',
1882 array $a_message_static = null
1883 ): void {
1884 // #12739
1885 if (defined("ILIAS_HTTP_PATH") &&
1886 !stristr($a_target, ILIAS_HTTP_PATH)) {
1887 $a_target = ILIAS_HTTP_PATH . "/" . $a_target;
1888 }
1889
1890 foreach (['ext_uid', 'soap_pw'] as $param) {
1891 if (false === strpos(
1892 $a_target,
1893 $param . '='
1894 ) && isset($GLOBALS['DIC']->http()->request()->getQueryParams()[$param])) {
1895 $a_target = \ilUtil::appendUrlParameterString($a_target, $param . '=' . \ilUtil::stripSlashes(
1896 $GLOBALS['DIC']->http()->request()->getQueryParams()[$param]
1897 ));
1898 }
1899 }
1900
1902 ilUtil::redirect($a_target);
1903 } else {
1904 $message = self::translateMessage($a_message_id, $a_message_static);
1905
1906 // user-directed linked message
1908 $link = self::translateMessage(
1909 "init_error_redirect_click",
1910 array("en" => 'Please click to continue.',
1911 "de" => 'Bitte klicken um fortzufahren.'
1912 )
1913 );
1914 $mess = $message .
1915 '<br /><a href="' . $a_target . '">' . $link . '</a>';
1916 } // plain text
1917 else {
1918 // not much we can do here
1919 $mess = $message;
1920
1921 if (!trim($mess)) {
1922 $mess = self::translateMessage(
1923 "init_error_redirect_info",
1924 array("en" => 'Redirect not supported by context.',
1925 "de" => 'Weiterleitungen werden durch Kontext nicht unterstützt.'
1926 )
1927 ) .
1928 ' (' . $a_target . ')';
1929 }
1930 }
1931
1932 self::abortAndDie($mess);
1933 }
1934 }
1935
1936 public static function redirectToStartingPage(string $target = ''): void
1937 {
1938 global $DIC;
1939
1940 // fallback, should never happen
1941 if ($DIC->user()->getId() === ANONYMOUS_USER_ID) {
1942 self::goToPublicSection();
1943 return;
1944 }
1945
1946 if (
1947 $target === '' &&
1948 $DIC->http()->wrapper()->query()->has('target')
1949 ) {
1950 $target = $DIC->http()->wrapper()->query()->retrieve(
1951 'target',
1952 $DIC->refinery()->kindlyTo()->string()
1953 );
1954 }
1955
1956 // for password change and incomplete profile
1957 // see ilDashboardGUI
1958 if ($target === '') {
1959 ilLoggerFactory::getLogger('init')->debug('Redirect to default starting page');
1960 $DIC->ctrl()->redirectToURL(ilUserUtil::getStartingPointAsUrl());
1961 } else {
1962 ilLoggerFactory::getLogger('init')->debug('Redirect to target: ' . $target);
1963 $DIC->ctrl()->redirectToURL("goto.php?target=" . $target);
1964 }
1965 }
1966
1967 private static function initBackgroundTasks(\ILIAS\DI\Container $c): void
1968 {
1969 global $ilIliasIniFile;
1970
1971 $n_of_tasks = $ilIliasIniFile->readVariable("background_tasks", "number_of_concurrent_tasks");
1972 $sync = $ilIliasIniFile->readVariable("background_tasks", "concurrency");
1973
1974 $n_of_tasks = $n_of_tasks ?: 5;
1975 $sync = $sync ?: 'sync'; // The default value is sync.
1976
1977 $c["bt.task_factory"] = function ($c) {
1978 return new \ILIAS\BackgroundTasks\Implementation\Tasks\BasicTaskFactory($c["di.injector"]);
1979 };
1980
1981 $c["bt.persistence"] = function ($c) {
1982 return \ILIAS\BackgroundTasks\Implementation\Persistence\BasicPersistence::instance($c->database());
1983 };
1984
1985 $c["bt.injector"] = function ($c) {
1986 return new \ILIAS\BackgroundTasks\Dependencies\Injector($c, new BaseDependencyMap());
1987 };
1988
1989 $c["bt.task_manager"] = function ($c) use ($sync) {
1990 if ($sync == 'sync') {
1991 return new \ILIAS\BackgroundTasks\Implementation\TaskManager\SyncTaskManager($c["bt.persistence"]);
1992 } elseif ($sync == 'async') {
1993 return new \ILIAS\BackgroundTasks\Implementation\TaskManager\AsyncTaskManager($c["bt.persistence"]);
1994 } else {
1995 throw new ilException("The supported Background Task Managers are sync and async. $sync given.");
1996 }
1997 };
1998 }
1999
2000 private static function initInjector(\ILIAS\DI\Container $c): void
2001 {
2002 $c["di.dependency_map"] = function ($c) {
2003 return new \ILIAS\BackgroundTasks\Dependencies\DependencyMap\BaseDependencyMap();
2004 };
2005
2006 $c["di.injector"] = function ($c) {
2007 return new \ILIAS\BackgroundTasks\Dependencies\Injector($c, $c["di.dependency_map"]);
2008 };
2009 }
2010
2011 private static function initKioskMode(\ILIAS\DI\Container $c): void
2012 {
2013 $c["service.kiosk_mode"] = function ($c) {
2014 return new ilKioskModeService(
2015 $c['ilCtrl'],
2016 $c['lng'],
2017 $c['ilAccess'],
2018 $c['objDefinition']
2019 );
2020 };
2021 }
2022}
if(!defined('PATH_SEPARATOR')) $GLOBALS['_PEAR_default_error_mode']
Definition: PEAR.php:64
const PEAR_ERROR_CALLBACK
Definition: PEAR.php:35
static orderBy($orderBy, string $orderDirection='ASC')
Customizing of pimple-DIC for ILIAS.
Definition: Container.php:32
Builds data types.
Definition: Factory.php:21
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Error.php:18
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Ok.php:17
Class SuperGlobalDropInReplacement This Class wraps SuperGlobals such as $_GET and $_POST to prevent ...
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
Class InitCtrlService wraps the initialization of ilCtrl.
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
Responsible for loading the Resource Storage into the dependency injection container of ILIAS.
Responsible for loading the UI Framework into the dependency injection container of ILIAS.
static setErrorHandling($mode=null, $options=null)
Sets how errors generated by this object should be handled.
Definition: PEAR.php:337
if(!isset($GLOBALS['ilGlobalStartTime'])||! $GLOBALS['ilGlobalStartTime']) global $DIC
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
const CONTEXT_HTTP
HTTP Auth used for WebDAV and CalDAV If a special handling for WebDAV or CalDAV is required overwrite...
static getInstance(\ilLogger $logger)
Get instance.
static isAuthenticationForced()
Check if authentication is should be forced.
static handleForcedAuthentication()
const CONTEXT_WEBDAV
static modifyHttpPath(string $httpPath)
const CONTEXT_SHIBBOLETH
const CONTEXT_APACHE_SSO
static supportsRedirects()
Are redirects supported?
static hasUser()
Based on user authentication?
const CONTEXT_SAML
static supportsPersistentSessions()
Check if context supports persistent session handling.
static getType()
Get context type.
static hasHTML()
Has HTML output.
static usesHTTP()
Uses HTTP aka browser.
const CONTEXT_LTI_PROVIDER
static initClient()
Init client.
const CONTEXT_SOAP
const CONTEXT_WAC
static getCountryCodes()
Get country codes (DIN EN 3166-1)
static getWrapper(string $a_type)
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
Class ilFileServicesFilenameSanitizer.
static removeTrailingPathSeparators(string $path)
Class ilGSProviderFactory.
Class ilGlobalCacheSettings.
static setup(ilGlobalCacheSettings $ilGlobalCacheSettings)
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
ILIAS Initialisation Utility Class perform basic setup: init database handler, load configuration fil...
static initDatabase()
initialise database object $ilDB
static initHTTPServices(\ILIAS\DI\Container $container)
static goToLogin()
go to login
static initILIAS()
ilias initialisation
static initLocale()
Init Locale.
static removeUnsafeCharacters()
Remove unsafe characters from GET.
static buildHTTPPath()
builds http path
static requireCommonIncludes()
get common include code files
static initClientIniFile()
This method provides a global instance of class ilIniFile for the client.ini.php file in variable $il...
static initSession()
Init auth session.
static initClient()
Init client-based objects (level 1)
static initCore()
Init core objects (level 0)
static recursivelyRemoveUnsafeCharacters($var)
static initUIFramework(\ILIAS\DI\Container $c)
init the ILIAS UI framework.
static includePhp5Compliance()
This is a hack for authentication.
static handleErrorReporting()
Set error reporting level.
static initFileUploadService(\ILIAS\DI\Container $dic)
Initializes the file upload service.
static initComponentService(\ILIAS\DI\Container $container)
static redirect(string $a_target, string $a_message_id='', array $a_message_static=null)
Redirects to target url if context supports it.
static determineClient()
This method determines the current client and sets the constant CLIENT_ID.
static initHTML()
init HTML output (level 3)
static initLog()
Init log instance.
static initAvatar(\ILIAS\DI\Container $c)
static goToPublicSection()
go to public section
static resumeUserSession()
Resume an existing user session.
static setSessionHandler()
set session handler to db Used in Soap/CAS
static handleDevMode()
Prepare developer tools.
static initUser()
Init user / authentification (level 2)
static initKioskMode(\ILIAS\DI\Container $c)
static initGlobal(string $a_name, $a_class, ?string $a_source_file=null, ?bool $destroy_existing=false)
static initBackgroundTasks(\ILIAS\DI\Container $c)
static initInjector(\ILIAS\DI\Container $c)
static setSessionCookieParams()
set session cookie params
static abortAndDie(string $a_message)
static blockedAuthentication(string $a_current_script)
Block authentication based on current request.
static initSettings()
initialise $ilSettings object and define constants Used in Soap
static initGlobalScreen(\ILIAS\DI\Container $c)
static initMail(\ILIAS\DI\Container $c)
static redirectToStartingPage(string $target='')
static initTermsOfService(\ILIAS\DI\Container $c)
static initRefinery(\ILIAS\DI\Container $container)
static initAccessibilityControlConcept(\ILIAS\DI\Container $c)
static getClientIdTransformation()
Refinery is not initialized early enough to provide a transformation to be used with the \ILIAS\HTTP ...
static handleMaintenanceMode()
handle maintenance mode
static initAccessHandling()
$ilAccess and $rbac... initialisation
static initUserAccount()
Init user with current account id.
static initCustomObjectIcons(\ILIAS\DI\Container $c)
static initCron(\ILIAS\DI\Container $c)
static initIliasIniFile()
This method provides a global instance of class ilIniFile for the ilias.ini.php file in variable $ilI...
static initStyle()
provide $styleDefinition object
static translateMessage(string $a_message_id, array $a_message_static=null)
Translate message if possible.
Central entry point for users of the service.
language handling
static getFallbackInstance()
Builds a global default language instance.
static getGlobalInstance()
Builds the global language object.
static getRootLogger()
The unique root logger has a fixed error level.
static getLogger(string $a_component_id)
Get component logger.
Class ilMailTemplateRepository.
Class ilObjTermsOfService.
static _isAnonymous(int $usr_id)
static updateAccess(ilObjUser $user)
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
Database Session Handling.
static _exists(string $a_session_id)
Check whether session exists.
const SESSION_CLOSE_LOGIN
static setClosingContext(int $a_context)
set closing context (for statistics)
static _destroy($a_session_id, ?int $a_closing_context=null, $a_expired_at=null)
Destroy session.
const SESSION_CLOSE_PUBLIC
static set(string $a_var, $a_val)
Set a value.
const SESSION_CLOSE_EXPIRE
Class ilTermsOfServiceHelper.
static initDefaultTimeZone(ilIniFile $ini)
Initialize default timezone from system settings.
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
static stripSlashes(string $a_str, bool $a_strip_html=true, string $a_allow="")
static appendUrlParameterString(string $a_url, string $a_par, bool $xml_style=false)
static redirect(string $a_script)
static setCookie(string $a_cookie_name, string $a_cookie_value='', bool $a_also_set_super_global=true, bool $a_set_cookie_invalid=false)
$c
Definition: cli.php:38
if(!file_exists(getcwd() . '/ilias.ini.php'))
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
Definition: confirmReg.php:20
const CLIENT_ID
Definition: constants.php:41
const ILIAS_DATA_DIR
Definition: constants.php:44
const ILIAS_WEB_DIR
Definition: constants.php:45
const CLIENT_WEB_DIR
Definition: constants.php:47
const ANONYMOUS_USER_ID
Definition: constants.php:27
const ROOT_FOLDER_ID
Definition: constants.php:32
$https
Definition: imgupload.php:35
$ilIliasIniFile
Definition: imgupload.php:32
$ilUser
Definition: imgupload.php:34
const ILIAS_VERSION_NUMERIC
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Result.php:15
then(callable $f)
Get a new result from the callable or do nothing if this is an error.
Interface Location.
Definition: Location.php:30
A transformation is a function from one datatype to another.
Interface ilTermsOfServiceDocumentEvaluation.
if($DIC->http() ->request() ->getMethod()=="GET" &&isset($DIC->http() ->request() ->getQueryParams()['tex'])) $tpl
Definition: latex.php:41
$client_id
Definition: ltiauth.php:68
$path
Definition: ltiservices.php:32
$cookie_path
Definition: metadata.php:39
const IL_COOKIE_PATH(isset($_GET["client_id"]))
Definition: metadata.php:64
Class HTTPServicesTest.
static http()
Fetches the global http state from ILIAS.
string $key
Consumer key/client ID value.
Definition: System.php:193
applyTo(Result $result)
@inheritDoc
__invoke($from)
@inheritDoc
Class ChatMainBarProvider \MainMenu\Provider.
global $ilSetting
Definition: privfeed.php:17
$_SERVER['HTTP_HOST']
Definition: raiseError.php:10
$ilErr
Definition: raiseError.php:17
$log
Definition: result.php:33
$dic
Definition: result.php:32
$_GET['client_id']
Definition: saml1-acs.php:21
$lng
$container
@noRector
Definition: wac.php:14
const ILIAS_MODULE
Definition: server.php:14
$lang
Definition: xapiexit.php:26
$message
Definition: xapiexit.php:32
$_COOKIE[session_name()]
Definition: xapitoken.php:54
$param
Definition: xapitoken.php:46