ILIAS  trunk Revision v11.0_alpha-2638-g80c1d007f79
class.ilInitialisation.php
Go to the documentation of this file.
1 <?php
2 
19 // TODO:
37 
38 // needed for slow queries, etc.
39 if (!isset($GLOBALS['ilGlobalStartTime']) || !$GLOBALS['ilGlobalStartTime']) {
40  $GLOBALS['ilGlobalStartTime'] = microtime();
41 }
42 
53 {
57  protected static function removeUnsafeCharacters(): void
58  {
59  // Remove unsafe characters from GET parameters.
60  // We do not need this characters in any case, so it is
61  // feasible to filter them everytime. POST parameters
62  // need attention through ilUtil::stripSlashes() and similar functions)
63  $_GET = self::recursivelyRemoveUnsafeCharacters($_GET);
64  }
65 
70  protected static function recursivelyRemoveUnsafeCharacters($var)
71  {
72  if (is_array($var)) {
73  $mod = [];
74  foreach ($var as $k => $v) {
75  $k = self::recursivelyRemoveUnsafeCharacters($k);
76  $mod[$k] = self::recursivelyRemoveUnsafeCharacters($v);
77  }
78  return $mod;
79  }
80  return strip_tags(
81  str_replace(
82  array("\x00", "\n", "\r", "\\", "'", '"', "\x1a"),
83  "",
84  $var
85  )
86  );
87  }
88 
92  protected static function requireCommonIncludes(): void
93  {
95  require_once(__DIR__ . "/../../../../ilias_version.php");
96  self::initGlobal("ilBench", "ilBenchmark", "./components/ILIAS/Utilities/classes/class.ilBenchmark.php");
97  }
98 
105  protected static function initIliasIniFile(): void
106  {
107  $ilIliasIniFile = new ilIniFile(__DIR__ . "/../../../../ilias.ini.php");
108  $ilIliasIniFile->read();
109  self::initGlobal('ilIliasIniFile', $ilIliasIniFile);
110 
111  // initialize constants
112  // aka internal data directory
113  if (!defined('ILIAS_DATA_DIR')) {
114  define("ILIAS_DATA_DIR", $ilIliasIniFile->readVariable("clients", "datadir"));
115  }
116  // aka Public Web Directory in Web, relative path to the webroot (public).
117  if (!defined('ILIAS_WEB_DIR')) {
118  $from_ilias_ini = $ilIliasIniFile->readVariable("clients", "path");
119  $from_ilias_ini = str_replace('public/', '', $from_ilias_ini);
120  define("ILIAS_WEB_DIR", $from_ilias_ini);
121  }
122  if (!defined("ILIAS_ABSOLUTE_PATH")) {
123  define("ILIAS_ABSOLUTE_PATH", $ilIliasIniFile->readVariable('server', 'absolute_path'));
124  }
125 
126  // logging
127  define("ILIAS_LOG_DIR", $ilIliasIniFile->readVariable("log", "path"));
128  define("ILIAS_LOG_FILE", $ilIliasIniFile->readVariable("log", "file"));
129  if (!defined("ILIAS_LOG_ENABLED")) {
130  define("ILIAS_LOG_ENABLED", $ilIliasIniFile->readVariable("log", "enabled"));
131  }
132  define("ILIAS_LOG_LEVEL", $ilIliasIniFile->readVariable("log", "level"));
133 
134  // read path + command for third party tools from ilias.ini
135  define("PATH_TO_CONVERT", $ilIliasIniFile->readVariable("tools", "convert"));
136  define("PATH_TO_FFMPEG", $ilIliasIniFile->readVariable("tools", "ffmpeg"));
137  define("PATH_TO_ZIP", $ilIliasIniFile->readVariable("tools", "zip"));
138  define("PATH_TO_MKISOFS", $ilIliasIniFile->readVariable("tools", "mkisofs"));
139  define("PATH_TO_UNZIP", $ilIliasIniFile->readVariable("tools", "unzip"));
140  define("PATH_TO_GHOSTSCRIPT", $ilIliasIniFile->readVariable("tools", "ghostscript"));
141  define("PATH_TO_JAVA", $ilIliasIniFile->readVariable("tools", "java"));
142  define("URL_TO_LATEX", $ilIliasIniFile->readVariable("tools", "latex"));
143  define("PATH_TO_FOP", $ilIliasIniFile->readVariable("tools", "fop"));
144  define("PATH_TO_SCSS", $ilIliasIniFile->readVariable("tools", "scss"));
145  define("PATH_TO_PHANTOMJS", $ilIliasIniFile->readVariable("tools", "phantomjs"));
146 
147  if ($ilIliasIniFile->groupExists('error')) {
148  if ($ilIliasIniFile->variableExists('error', 'editor_url')) {
149  define("ERROR_EDITOR_URL", $ilIliasIniFile->readVariable('error', 'editor_url'));
150  }
151 
152  if ($ilIliasIniFile->variableExists('error', 'editor_path_translations')) {
153  define(
154  "ERROR_EDITOR_PATH_TRANSLATIONS",
155  $ilIliasIniFile->readVariable('error', 'editor_path_translations')
156  );
157  }
158  }
159 
160  // read virus scanner settings
161  switch ($ilIliasIniFile->readVariable("tools", "vscantype")) {
162  case "sophos":
163  define("IL_VIRUS_SCANNER", "Sophos");
164  define("IL_VIRUS_SCAN_COMMAND", $ilIliasIniFile->readVariable("tools", "scancommand"));
165  define("IL_VIRUS_CLEAN_COMMAND", $ilIliasIniFile->readVariable("tools", "cleancommand"));
166  break;
167 
168  case "antivir":
169  define("IL_VIRUS_SCANNER", "AntiVir");
170  define("IL_VIRUS_SCAN_COMMAND", $ilIliasIniFile->readVariable("tools", "scancommand"));
171  define("IL_VIRUS_CLEAN_COMMAND", $ilIliasIniFile->readVariable("tools", "cleancommand"));
172  break;
173 
174  case "clamav":
175  define("IL_VIRUS_SCANNER", "ClamAV");
176  define("IL_VIRUS_SCAN_COMMAND", $ilIliasIniFile->readVariable("tools", "scancommand"));
177  define("IL_VIRUS_CLEAN_COMMAND", $ilIliasIniFile->readVariable("tools", "cleancommand"));
178  break;
179  case "icap":
180  define("IL_VIRUS_SCANNER", "icap");
181  define("IL_ICAP_HOST", $ilIliasIniFile->readVariable("tools", "icap_host"));
182  define("IL_ICAP_PORT", $ilIliasIniFile->readVariable("tools", "icap_port"));
183  define("IL_ICAP_AV_COMMAND", $ilIliasIniFile->readVariable("tools", "icap_service_name"));
184  define("IL_ICAP_CLIENT", $ilIliasIniFile->readVariable("tools", "icap_client_path"));
185  break;
186 
187  default:
188  define("IL_VIRUS_SCANNER", "None");
189  define("IL_VIRUS_CLEAN_COMMAND", '');
190  break;
191  }
192 
194  define("IL_TIMEZONE", $tz);
195  }
196 
197  protected static function initResourceStorage(): void
198  {
199  global $DIC;
200  (new InitResourceStorage())->init($DIC);
201  }
202 
213  public static function bootstrapFilesystems(): void
214  {
215  global $DIC;
216 
217  $DIC['filesystem.security.sanitizing.filename'] = function (Container $c) {
219  $c->fileServiceSettings()
220  );
221  };
222 
223  $DIC['filesystem.factory'] = function ($c) {
224  return new \ILIAS\Filesystem\Provider\DelegatingFilesystemFactory($c['filesystem.security.sanitizing.filename']);
225  };
226 
227  $DIC['filesystem.web'] = function ($c) {
228  //web
229 
233  $delegatingFactory = $c['filesystem.factory'];
234  $webConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_ABSOLUTE_PATH . '/public/' . ILIAS_WEB_DIR . '/' . CLIENT_ID);
235  return $delegatingFactory->getLocal($webConfiguration);
236  };
237 
238  $DIC['filesystem.storage'] = function ($c) {
239  //storage
240 
244  $delegatingFactory = $c['filesystem.factory'];
245  $storageConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_DATA_DIR . '/' . CLIENT_ID);
246  return $delegatingFactory->getLocal($storageConfiguration);
247  };
248 
249  $DIC['filesystem.temp'] = function ($c) {
250  //temp
251 
255  $delegatingFactory = $c['filesystem.factory'];
256  $tempConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_DATA_DIR . '/' . CLIENT_ID . '/temp');
257  return $delegatingFactory->getLocal($tempConfiguration);
258  };
259 
260  $DIC['filesystem.customizing'] = function ($c) {
261  //customizing
262 
266  $delegatingFactory = $c['filesystem.factory'];
267  $customizingConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_ABSOLUTE_PATH . '/public/' . 'Customizing');
268  return $delegatingFactory->getLocal($customizingConfiguration);
269  };
270 
271  $DIC['filesystem.libs'] = function ($c) {
272  //customizing
273 
277  $delegatingFactory = $c['filesystem.factory'];
278  $customizingConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_ABSOLUTE_PATH . '/' . 'vendor');
279  return $delegatingFactory->getLocal($customizingConfiguration, true);
280  };
281 
282  $DIC['filesystem.node_modules'] = function ($c) {
283  //customizing
284 
288  $delegatingFactory = $c['filesystem.factory'];
289  $customizingConfiguration = new \ILIAS\Filesystem\Provider\Configuration\LocalConfig(ILIAS_ABSOLUTE_PATH . '/' . 'node_modules');
290  return $delegatingFactory->getLocal($customizingConfiguration, true);
291  };
292 
293  $DIC['filesystem'] = function ($c) {
294  return new \ILIAS\Filesystem\FilesystemsImpl(
295  $c['filesystem.storage'],
296  $c['filesystem.web'],
297  $c['filesystem.temp'],
298  $c['filesystem.customizing'],
299  $c['filesystem.libs'],
300  $c['filesystem.node_modules']
301  );
302  };
303  }
304 
311  public static function initFileUploadService(\ILIAS\DI\Container $dic): void
312  {
313  $dic['upload.processor-manager'] = function ($c) {
314  return new PreProcessorManagerImpl();
315  };
316 
317  $dic['upload'] = function (\ILIAS\DI\Container $c) {
318  $fileUploadImpl = new \ILIAS\FileUpload\FileUploadImpl(
319  $c['upload.processor-manager'],
320  $c['filesystem'],
321  $c['http']
322  );
323  if ((defined('IL_VIRUS_SCANNER') && IL_VIRUS_SCANNER != "None") || (defined('IL_SCANNER_TYPE') && IL_SCANNER_TYPE == "1")) {
324  $fileUploadImpl->register(new ilVirusScannerPreProcessor(ilVirusScannerFactory::_getInstance()));
325  }
326 
327  $fileUploadImpl->register(new FilenameSanitizerPreProcessor());
328  $fileUploadImpl->register(
330  $c->fileServiceSettings(),
331  $c->language()->txt("msg_info_blacklisted")
332  )
333  );
334  $fileUploadImpl->register(new InsecureFilenameSanitizerPreProcessor());
335  $fileUploadImpl->register(new SVGBlacklistPreProcessor(
336  $c->language()->txt("upload_svg_rejection_message"),
337  $c->language()->txt("upload_svg_rejection_message_script"),
338  $c->language()->txt("upload_svg_rejection_message_base64"),
339  $c->language()->txt("upload_svg_rejection_message_elements")
340  ));
341 
342  return $fileUploadImpl;
343  };
344  }
345 
346  protected static function initUploadPolicies(\ILIAS\DI\Container $dic): void
347  {
348  $dic['upload_policy_repository'] = static function ($dic) {
349  return new UploadPolicyDBRepository($dic->database());
350  };
351 
352  $dic['upload_policy_resolver'] = static function ($dic): UploadPolicyResolver {
353  return new UploadPolicyResolver(
354  $dic->rbac()->review(),
355  $dic->user(),
356  $dic['upload_policy_repository']->getAll(),
357  );
358  };
359  }
360 
361  protected static function buildHTTPPath(): bool
362  {
363  global $DIC;
364 
365  return define(
366  'ILIAS_HTTP_PATH',
367  (new \ILIAS\Init\Environment\HttpPathBuilder(
368  $DIC[\ILIAS\Data\Factory::class],
369  $DIC->settings(),
370  $DIC['https'],
371  $DIC['ilIliasIniFile'],
372  $_SERVER
373  ))->build()->getBaseURI()
374  );
375  }
376 
381  protected static function determineClient(): void
382  {
383  if (defined('CLIENT_ID')) {
384  return;
385  }
386  global $DIC;
387  $df = $DIC[\ILIAS\Data\Factory::class];
388 
389  // check whether ini file object exists
390  if (!$DIC->isDependencyAvailable('iliasIni')) {
391  self::abortAndDie('Fatal Error: ilInitialisation::determineClient called without initialisation of ILIAS ini file object.');
392  }
393 
394  $in_unit_tests = defined('IL_PHPUNIT_TEST');
395  $context_supports_persitent_session = ilContext::supportsPersistentSessions();
396  $can_set_cookie = !$in_unit_tests && $context_supports_persitent_session;
397  $has_request_client_id = $DIC->http()->wrapper()->query()->has('client_id');
398  $has_cookie_client_id = $DIC->http()->cookieJar()->has('ilClientId');
399 
400  // determine the available clientIds (default, request, cookie)
401  $default_client_id = $DIC->iliasIni()->readVariable('clients', 'default');
402 
403  if ($DIC->http()->wrapper()->query()->has('client_id')) {
404  $client_id_from_get = $DIC->http()->wrapper()->query()->retrieve(
405  'client_id',
406  self::getClientIdTransformation()
407  );
408  }
409  if ($DIC->http()->wrapper()->cookie()->has('ilClientId')) {
410  $client_id_from_cookie = $DIC->http()->wrapper()->cookie()->retrieve(
411  'ilClientId',
412  self::getClientIdTransformation()
413  );
414  }
415 
416  // set the clientId by availability: 1. request, 2. cookie, fallback to defined default
417  $client_id_to_use = '';
418  if (isset($client_id_from_get) && $client_id_from_get !== '') {
419  $client_id_to_use = $client_id_from_get;
420  }
421  // we found a client_id in $GET
422  if (isset($client_id_from_get) && strlen($client_id_from_get) > 0) {
423  // @todo refinery undefined
424  $client_id_to_use = $_GET['client_id'] = $df->clientId($client_id_from_get)->toString();
425  if ($can_set_cookie) {
426  ilUtil::setCookie('ilClientId', $client_id_to_use);
427  }
428  } else {
429  $client_id_to_use = $default_client_id;
430  if (!isset($_COOKIE['ilClientId'])) {
431  ilUtil::setCookie('ilClientId', $client_id_to_use);
432  }
433  }
434 
435  $client_id_to_use = $client_id_to_use ?: $default_client_id;
436 
437  define('CLIENT_ID', $df->clientId($client_id_to_use)->toString());
438  }
439 
440 
447  private static function getClientIdTransformation(): Transformation
448  {
449  return new class () implements Transformation {
453  public function transform($from): string
454  {
455  if (!is_string($from)) {
456  throw new InvalidArgumentException(__METHOD__ . " the argument is not a string.");
457  }
458  return strip_tags($from);
459  }
460 
464  public function applyTo(Result $result): Result
465  {
466  return $result->then(function ($value): Result {
467  try {
468  return new Ok($this->transform($value));
469  } catch (Exception $exception) {
470  return new Error($exception);
471  }
472  });
473  }
474 
478  public function __invoke($from): string
479  {
480  return $this->transform($from);
481  }
482  };
483  }
484 
494  protected static function initClientIniFile(): void
495  {
496  global $ilIliasIniFile;
497 
498  // check whether ILIAS_WEB_DIR is set.
499  if (!defined('ILIAS_WEB_DIR') || empty(ILIAS_WEB_DIR)) {
500  self::abortAndDie("Fatal Error: ilInitialisation::initClientIniFile called without ILIAS_WEB_DIR.");
501  }
502 
503  // check whether CLIENT_ID is set.
504  if (CLIENT_ID == "") {
505  self::abortAndDie("Fatal Error: ilInitialisation::initClientIniFile called without CLIENT_ID.");
506  }
507 
508  $ini_file = "/client.ini.php";
509  if (defined('CLIENT_WEB_DIR')) {
510  $ini_file = CLIENT_WEB_DIR . $ini_file;
511  } else {
512  $ini_file = __DIR__ . '/../../../../public/' . ILIAS_WEB_DIR . '/' . CLIENT_ID . '/client.ini.php';
513  }
514 
515  $ilClientIniFile = new ilIniFile($ini_file);
516  $ilClientIniFile->read();
517 
518  // invalid client id / client ini
519  if ($ilClientIniFile->ERROR != "") {
520  $default_client = $ilIliasIniFile->readVariable("clients", "default");
521  if (CLIENT_ID !== "") {
522  $mess = array("en" => "Client does not exist.",
523  "de" => "Mandant ist ungültig."
524  );
525  self::redirect("index.php?client_id=" . $default_client, '', $mess);
526  } else {
527  self::abortAndDie("Fatal Error: ilInitialisation::initClientIniFile initializing client ini file abborted with: " . $ilClientIniFile->ERROR);
528  }
529  }
530 
531  self::initGlobal("ilClientIniFile", $ilClientIniFile);
532  // set constants
533  define("DEVMODE", (int) $ilClientIniFile->readVariable("system", "DEVMODE"));
534  define("SHOWNOTICES", (int) $ilClientIniFile->readVariable("system", "SHOWNOTICES"));
535  if (!defined("ROOT_FOLDER_ID")) {
536  define("ROOT_FOLDER_ID", (int) $ilClientIniFile->readVariable('system', 'ROOT_FOLDER_ID'));
537  }
538  if (!defined("SYSTEM_FOLDER_ID")) {
539  define("SYSTEM_FOLDER_ID", (int) $ilClientIniFile->readVariable('system', 'SYSTEM_FOLDER_ID'));
540  }
541  if (!defined("ROLE_FOLDER_ID")) {
542  define("ROLE_FOLDER_ID", (int) $ilClientIniFile->readVariable('system', 'ROLE_FOLDER_ID'));
543  }
544  define("MAIL_SETTINGS_ID", (int) $ilClientIniFile->readVariable('system', 'MAIL_SETTINGS_ID'));
545  $error_handler = $ilClientIniFile->readVariable('system', 'ERROR_HANDLER');
546  define("ERROR_HANDLER", $error_handler ?: "PRETTY_PAGE");
547 
548  // this is for the online help installation, which sets OH_REF_ID to the
549  // ref id of the online module
550  define("OH_REF_ID", (int) $ilClientIniFile->readVariable("system", "OH_REF_ID"));
551 
552  // see ilObject::TITLE_LENGTH, ilObject::DESC_LENGTH
553  // define ("MAXLENGTH_OBJ_TITLE",125);#$ilClientIniFile->readVariable('system','MAXLENGTH_OBJ_TITLE'));
554  // define ("MAXLENGTH_OBJ_DESC",$ilClientIniFile->readVariable('system','MAXLENGTH_OBJ_DESC'));
555 
556  if (!defined("CLIENT_DATA_DIR")) {
557  define("CLIENT_DATA_DIR", ILIAS_DATA_DIR . "/" . CLIENT_ID);
558  }
559  if (!defined("CLIENT_WEB_DIR")) {
560  define("CLIENT_WEB_DIR", ILIAS_ABSOLUTE_PATH . "/public/" . ILIAS_WEB_DIR . "/" . CLIENT_ID);
561  }
562  define("CLIENT_NAME", $ilClientIniFile->readVariable('client', 'name')); // Change SS
563 
564  $db_type = $ilClientIniFile->readVariable("db", "type");
565  if ($db_type === "") {
566  define("IL_DB_TYPE", ilDBConstants::TYPE_INNODB);
567  } else {
568  define("IL_DB_TYPE", $db_type);
569  }
570  }
571 
575  protected static function handleMaintenanceMode(): void
576  {
577  global $ilClientIniFile;
578 
579  if (!$ilClientIniFile->readVariable("client", "access")) {
580  $mess = array(
581  "en" => "The server is not available due to maintenance." .
582  " We apologise for any inconvenience.",
583  "de" => "Der Server ist aufgrund von Wartungsarbeiten aktuell nicht verf&uuml;gbar." .
584  " Wir bitten um Verst&auml;ndnis. Versuchen Sie es sp&auml;ter noch einmal."
585  );
586  $mess_id = "init_error_maintenance";
587 
588  if (ilContext::hasHTML() && is_file("./maintenance.html")) {
589  self::redirect("./maintenance.html", $mess_id, $mess);
590  } else {
591  $mess = self::translateMessage($mess_id, $mess);
592  self::abortAndDie($mess);
593  }
594  }
595  }
596 
600  protected static function initDatabase(): void
601  {
602  // build dsn of database connection and connect
604  $ilDB->initFromIniFile();
605  $ilDB->connect();
606 
607  self::initGlobal("ilDB", $ilDB);
608  }
609 
610  protected static function initGlobalCache(): void
611  {
612  global $DIC;
613  $legacy_settings = new ilGlobalCacheSettingsAdapter(
614  $DIC->clientIni(),
615  $DIC->database(),
616  );
617  $DIC['global_cache'] = new \ILIAS\Cache\Services(
618  $legacy_settings->getConfig()
619  );
620  }
621 
626  public static function setSessionHandler(): void
627  {
628  $db_session_handler = new ilSessionDBHandler();
629  if (!$db_session_handler->setSaveHandler()) {
630  self::abortAndDie("Cannot start session handling.");
631  }
632 
633  // Do not accept external session ids
634  if (!ilSession::_exists(session_id()) && !defined('IL_PHPUNIT_TEST')) {
635  // php7-todo, correct-with-php5-removal : alex, 1.3.2016: added if, please check
636  if (function_exists("session_status") && session_status() == PHP_SESSION_ACTIVE) {
637  session_regenerate_id();
638  }
639  }
640  }
641 
645  protected static function setCookieConstants(): void
646  {
648  $cookie_path = '/';
649  } elseif (isset($GLOBALS['COOKIE_PATH'])) {
650  // use a predefined cookie path from WebAccessChecker
651  $cookie_path = $GLOBALS['COOKIE_PATH'];
652  } else {
653  $cookie_path = dirname($_SERVER['SCRIPT_NAME']);
654  }
655 
656  /* if ilias is called directly within the docroot $cookie_path
657  is set to '/' expecting on servers running under windows..
658  here it is set to '\'.
659  in both cases a further '/' won't be appended due to the following regex
660  */
661  $cookie_path .= (!preg_match("/[\/|\\\\]$/", $cookie_path)) ? "/" : "";
662 
663  if ($cookie_path == "\\") {
664  $cookie_path = '/';
665  }
666 
667  define('IL_COOKIE_HTTPONLY', true); // Default Value
668  define('IL_COOKIE_EXPIRE', 0);
669  define('IL_COOKIE_DOMAIN', '');
670  if (!defined('IL_COOKIE_PATH')) {
671  // Might be already defined by ./public/sso/index.php or other scripts (like those in ./components/ILIAS/SAML/lib/*)
672  define('IL_COOKIE_PATH', $cookie_path);
673  }
674  }
675 
676  private static function setClientIdCookie(): void
677  {
678  if (defined('CLIENT_ID') &&
679  !defined('IL_PHPUNIT_TEST') &&
681  ilUtil::setCookie('ilClientId', CLIENT_ID);
682  }
683  }
684 
688  protected static function setSessionCookieParams(): void
689  {
690  global $ilSetting, $DIC;
691 
692  if (!defined('IL_COOKIE_SECURE')) {
693  // If this code is executed, we can assume that \ilHTTPS::enableSecureCookies was NOT called before
694  // \ilHTTPS::enableSecureCookies already executes session_set_cookie_params()
695 
696  $cookie_secure = !$ilSetting->get('https', '0') && $DIC['https']->isDetected();
697  define('IL_COOKIE_SECURE', $cookie_secure); // Default Value
698 
699  $cookie_parameters = [
700  'lifetime' => IL_COOKIE_EXPIRE,
701  'path' => IL_COOKIE_PATH,
702  'domain' => IL_COOKIE_DOMAIN,
703  'secure' => IL_COOKIE_SECURE,
704  'httponly' => IL_COOKIE_HTTPONLY,
705  ];
706 
707  if (
708  $cookie_secure &&
709  (!isset(session_get_cookie_params()['samesite']) || strtolower(session_get_cookie_params()['samesite']) !== 'strict')
710  ) {
711  $cookie_parameters['samesite'] = 'Lax';
712  }
713 
714  session_set_cookie_params($cookie_parameters);
715  }
716  }
717 
718  protected static function initCron(\ILIAS\DI\Container $c): void
719  {
720  $c['cron.repository'] = static function (\ILIAS\DI\Container $c): ILIAS\Cron\Job\JobRepository {
722  $c->database(),
723  $c->settings(),
724  $c->logger()->cron(),
725  $c['component.repository'],
726  $c['component.factory']
727  );
728  };
729 
730  $c['cron.manager'] = static function (\ILIAS\DI\Container $c): ILIAS\Cron\Job\JobManager {
732  $c['cron.repository'],
733  $c->database(),
734  $c->settings(),
735  $c->logger()->cron(),
736  $c[\ILIAS\Data\Factory::class]->clock(),
737  );
738  };
739  }
740 
744  protected static function initCustomObjectIcons(\ILIAS\DI\Container $c): void
745  {
746  $c["object.customicons.factory"] = function ($c) {
747  return new CustomIconFactory(
748  $c->filesystem()->web(),
749  $c->upload(),
750  $c['ilObjDataCache']
751  );
752  };
753  }
754 
755  protected static function initAvatar(\ILIAS\DI\Container $c): void
756  {
757  $c["user.avatar.factory"] = function ($c) {
758  return new \ilUserAvatarFactory($c);
759  };
760  }
761 
762  protected static function initLegalDocuments(Container $c): void
763  {
764  $c['legalDocuments'] = static fn(Container $c) => new Conductor($c);
765  }
766 
767  protected static function initAccessibilityControlConcept(\ILIAS\DI\Container $c): void
768  {
769  $c['acc.criteria.type.factory'] = function (\ILIAS\DI\Container $c) {
770  return new ilAccessibilityCriterionTypeFactory($c->rbac()->review(), $c['ilObjDataCache']);
771  };
772 
773  $c['acc.document.evaluator'] = function (\ILIAS\DI\Container $c) {
776  $c['acc.criteria.type.factory'],
777  $c->user(),
778  $c->logger()->acc()
779  ),
780  $c->user(),
781  $c->logger()->acc(),
782  \ilAccessibilityDocument::orderBy('sorting')->get()
783  );
784  };
785  }
786 
791  protected static function initSettings(): void
792  {
793  global $ilSetting;
794 
795  self::initGlobal(
796  "ilSetting",
797  "ilSetting",
798  "components/ILIAS/Administration/classes/class.ilSetting.php"
799  );
800 
801  // check correct setup
802  if (!$ilSetting->get("setup_ok")) {
803  self::abortAndDie("Setup is not completed. Please run setup routine again.");
804  }
805 
806  // set anonymous user & role id and system role id
807  define("ANONYMOUS_USER_ID", (int) $ilSetting->get("anonymous_user_id"));
808  define("ANONYMOUS_ROLE_ID", (int) $ilSetting->get("anonymous_role_id"));
809  define("SYSTEM_USER_ID", (int) $ilSetting->get("system_user_id"));
810  define("SYSTEM_ROLE_ID", (int) $ilSetting->get("system_role_id"));
811  define("USER_FOLDER_ID", 7);
812 
813  // recovery folder
814  define("RECOVERY_FOLDER_ID", (int) $ilSetting->get("recovery_folder_id"));
815 
816  // installation id
817  define("IL_INST_ID", $ilSetting->get("inst_id", '0'));
818 
819  // define default suffix replacements
820  define("SUFFIX_REPL_DEFAULT", "php,php3,php4,inc,lang,phtml,htaccess");
821  define("SUFFIX_REPL_ADDITIONAL", $ilSetting->get("suffix_repl_additional", ""));
822 
823  if (ilContext::usesHTTP()) {
824  self::buildHTTPPath();
825  }
826  }
827 
831  protected static function initStyle(): void
832  {
833  global $DIC;
834  $component_factory = $DIC["component.factory"];
835 
836  // load style definitions
837  self::initGlobal(
838  "styleDefinition",
839  "ilStyleDefinition",
840  "./components/ILIAS/Style/System/classes/class.ilStyleDefinition.php"
841  );
842 
843  // add user interface hook for style initialisation
844  foreach ($component_factory->getActivePluginsInSlot("uihk") as $ui_plugin) {
845  $gui_class = $ui_plugin->getUIClassInstance();
846  $gui_class->modifyGUI("components/ILIAS/Init", "init_style", array("styleDefinition" => $DIC->systemStyle()));
847  }
848  }
849 
853  public static function initUserAccount(): void
854  {
855  global $DIC;
856 
857  static $context_init;
858 
859  $uid = $GLOBALS['DIC']['ilAuthSession']->getUserId();
860  if ($uid) {
861  $DIC->user()->setId($uid);
862  $DIC->user()->read();
863  if (!isset($context_init)) {
864  if ($DIC->user()->isAnonymous()) {
865  $DIC->globalScreen()->tool()->context()->claim()->external();
866  } else {
867  $DIC->globalScreen()->tool()->context()->claim()->internal();
868  }
869  $context_init = true;
870  }
871  // init console log handler
872  ilLoggerFactory::getInstance()->initUser($DIC->user()->getLogin());
873  \ilOnlineTracking::updateAccess($DIC->user());
874  } else {
875  if (is_object($GLOBALS['ilLog'])) {
876  $GLOBALS['ilLog']->logStack();
877  }
878  self::abortAndDie("Init user account failed");
879  }
880  }
881 
885  protected static function initLocale(): void
886  {
887  global $ilSetting;
888 
889  if ($ilSetting->get("locale") && trim($ilSetting->get("locale")) !== "") {
890  $larr = explode(",", trim($ilSetting->get("locale")));
891  $ls = array();
892  $first = $larr[0];
893  foreach ($larr as $l) {
894  if (trim($l) != "") {
895  $ls[] = $l;
896  }
897  }
898  if (count($ls) > 0) {
899  setlocale(LC_ALL, $ls);
900 
901  // #15347 - making sure that floats are not changed
902  setlocale(LC_NUMERIC, "C");
903  }
904  }
905  }
906 
910  public static function goToPublicSection(): void
911  {
912  global $DIC;
913 
914  if (ANONYMOUS_USER_ID == "") {
915  self::abortAndDie("Public Section enabled, but no Anonymous user found.");
916  }
917 
918  $session_destroyed = false;
919  if ($DIC['ilAuthSession']->isExpired()) {
920  $session_destroyed = true;
922  }
923  if (!$DIC['ilAuthSession']->isAuthenticated()) {
924  $session_destroyed = true;
926  }
927 
928  if ($session_destroyed) {
929  $GLOBALS['DIC']['ilAuthSession']->setAuthenticated(true, ANONYMOUS_USER_ID);
930  }
931 
932  self::initUserAccount();
933 
934  $target = '';
935  if ($DIC->http()->wrapper()->query()->has('target')) {
936  $target = $DIC->http()->wrapper()->query()->retrieve(
937  'target',
938  $DIC->refinery()->kindlyTo()->string()
939  );
940  }
941 
942  // if target given, try to go there
943  if (strlen($target)) {
944  // when we are already "inside" goto.php no redirect is needed
945  $current_script = substr(strrchr($_SERVER["PHP_SELF"], "/"), 1);
946  if ($current_script == "goto.php") {
947  return;
948  }
949  // goto will check if target is accessible or redirect to login
950  self::redirect("goto.php?target=" . $target);
951  }
952 
953  // we do not know if ref_id of request is accesible, so redirecting to root
954  self::redirect(
955  "ilias.php?baseClass=ilrepositorygui&reloadpublic=1&cmd=&ref_id=" . (defined(
956  'ROOT_FOLDER_ID'
957  ) ? (string) ROOT_FOLDER_ID : '0')
958  );
959  }
960 
964  protected static function goToLogin(): void
965  {
966  global $DIC;
967 
968  $session_expired = false;
969  ilLoggerFactory::getLogger('init')->debug('Redirecting to login page.');
970 
971  if ($DIC['ilAuthSession']->isExpired()) {
973  $session_expired = true;
974  }
975  if (!$DIC['ilAuthSession']->isAuthenticated()) {
977  }
978 
979  $target = $DIC->http()->wrapper()->query()->has('target')
980  ? $DIC->http()->wrapper()->query()->retrieve(
981  'target',
982  $DIC->refinery()->kindlyTo()->string()
983  )
984  : '';
985 
986  if (strlen($target)) {
987  $target = "target=" . $target . "&";
988  }
989 
990  $client_id = $DIC->http()->wrapper()->cookie()->retrieve(
991  'ilClientId',
992  $DIC->refinery()->byTrying([
993  $DIC->refinery()->kindlyTo()->string(),
994  $DIC->refinery()->always('')
995  ])
996  );
997 
998  $script = "login.php?" . $target . "client_id=" . $client_id;
999  $script .= $session_expired ? "&session_expired=1" : "";
1000 
1001  self::redirect(
1002  $script,
1003  "init_error_authentication_fail",
1004  array(
1005  "en" => "Authentication failed.",
1006  "de" => "Authentifizierung fehlgeschlagen."
1007  )
1008  );
1009  }
1010 
1014  protected static function initLanguage(bool $a_use_user_language = true): void
1015  {
1016  global $DIC;
1017 
1021  global $rbacsystem;
1022 
1023  if ($a_use_user_language) {
1024  if ($DIC->offsetExists('lng')) {
1025  $DIC->offsetUnset('lng');
1026  }
1027  self::initGlobal('lng', ilLanguage::getGlobalInstance());
1028  } else {
1029  self::initGlobal('lng', ilLanguage::getFallbackInstance());
1030  }
1031  if (is_object($rbacsystem) && $DIC->offsetExists('tree')) {
1032  $rbacsystem->initMemberView();
1033  }
1034  }
1035 
1039  protected static function initAccessHandling(): void
1040  {
1041  self::initGlobal(
1042  "rbacreview",
1043  "ilRbacReview",
1044  "./components/ILIAS/AccessControl/classes/class.ilRbacReview.php",
1045  true
1046  );
1047 
1048  $rbacsystem = ilRbacSystem::getInstance();
1049  self::initGlobal('rbacsystem', $rbacsystem, null, true);
1050 
1051  self::initGlobal(
1052  "rbacadmin",
1053  "ilRbacAdmin",
1054  "./components/ILIAS/AccessControl/classes/class.ilRbacAdmin.php",
1055  true
1056  );
1057 
1058  self::initGlobal(
1059  "ilAccess",
1060  "ilAccess",
1061  "./components/ILIAS/AccessControl/classes/class.ilAccess.php",
1062  true
1063  );
1064  }
1065 
1069  protected static function initLog(): void
1070  {
1072 
1073  self::initGlobal("ilLog", $log);
1074  // deprecated
1075  self::initGlobal("log", $log);
1076  }
1077 
1081  protected static function initGlobal(
1082  string $a_name,
1083  $a_class,
1084  ?string $a_source_file = null,
1085  ?bool $destroy_existing = false
1086  ): void {
1087  global $DIC;
1088 
1089  if ($destroy_existing) {
1090  if (isset($GLOBALS[$a_name])) {
1091  unset($GLOBALS[$a_name]);
1092  }
1093  if (isset($DIC[$a_name])) {
1094  unset($DIC[$a_name]);
1095  }
1096  }
1097 
1098  $GLOBALS[$a_name] = is_object($a_class) ? $a_class : new $a_class();
1099 
1100  $DIC[$a_name] = static function (Container $c) use ($a_name) {
1101  return $GLOBALS[$a_name];
1102  };
1103  }
1104 
1105  protected static function abortAndDie(string $a_message): void
1106  {
1107  if (isset($GLOBALS['ilLog'])) {
1108  $GLOBALS['ilLog']->write("Fatal Error: ilInitialisation - " . $a_message);
1109  $GLOBALS['ilLog']->logStack();
1110  }
1111  die($a_message);
1112  }
1113 
1117  protected static function handleDevMode(): void
1118  {
1119  error_reporting(-1);
1120  }
1121 
1122  protected static bool $already_initialized = false;
1123 
1124  public static function reinitILIAS(): void
1125  {
1126  self::$already_initialized = false;
1127  self::initILIAS();
1128  }
1129 
1130  public static function reInitUser(): void
1131  {
1133  self::initSession();
1134  self::initUser();
1135 
1137  self::resumeUserSession();
1138  }
1139  }
1140  }
1141 
1145  public static function initILIAS(): void
1146  {
1147  if (self::$already_initialized) {
1148  return;
1149  }
1150 
1151  $GLOBALS["DIC"]["ilLoggerFactory"] = function ($c) {
1153  };
1154 
1155  self::$already_initialized = true;
1156 
1157  self::initCore();
1158  self::initHTTPServices($GLOBALS["DIC"]);
1159  if (ilContext::initClient()) {
1160  self::initFileUploadService($GLOBALS["DIC"]);
1161  Init::init($GLOBALS["DIC"]);
1162  self::initClient();
1163  self::initSession();
1164 
1165  if (ilContext::hasUser()) {
1166  self::initUser();
1167 
1169  self::resumeUserSession();
1170  }
1171  }
1172 
1173  // language may depend on user setting
1174  self::initLanguage(true);
1175  $GLOBALS['DIC']['tree']->initLangCode();
1176 
1177  self::initInjector($GLOBALS['DIC']);
1178  self::initBackgroundTasks($GLOBALS['DIC']);
1179  self::initKioskMode($GLOBALS['DIC']);
1180 
1181  if (ilContext::hasHTML()) {
1182  self::initHTML();
1183  }
1184  }
1185 
1186  // this MUST happen after everything else is initialized,
1187  // because this leads to rather unexpected behaviour which
1188  // is super hard to track down to this.
1189  self::replaceSuperGlobals($GLOBALS['DIC']);
1190  }
1191 
1195  protected static function initSession(): void
1196  {
1197  if (isset($GLOBALS['DIC']['ilAuthSession'])) {
1198  unset($GLOBALS['DIC']['ilAuthSession']);
1199  }
1200 
1201  $GLOBALS['DIC']['ilAuthSession'] = static function (Container $c): ilAuthSession {
1202  $auth_session = ilAuthSession::getInstance(
1203  $c['ilLoggerFactory']->getLogger('auth')
1204  );
1205  $auth_session->init();
1206  return $auth_session;
1207  };
1208  }
1209 
1213  public static function handleErrorReporting(): void
1214  {
1215  // push the error level as high as possible / sane
1216  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
1217 
1218  // see handleDevMode() - error reporting might be overwritten again
1219  // but we need the client ini first
1220  }
1221 
1225  protected static function initCore(): void
1226  {
1227  global $ilErr;
1228 
1229  self::handleErrorReporting();
1230 
1231  self::requireCommonIncludes();
1232  $GLOBALS["DIC"]["ilias.version"] = $GLOBALS["DIC"][\ILIAS\Data\Factory::class]->version(ILIAS_VERSION_NUMERIC);
1233 
1234  // error handler
1235  self::initGlobal(
1236  "ilErr",
1237  "ilErrorHandling",
1238  "./components/ILIAS/Init/classes/class.ilErrorHandling.php"
1239  );
1240 
1241  self::removeUnsafeCharacters();
1242 
1243  self::initIliasIniFile();
1244 
1245  define('IL_INITIAL_WD', getcwd());
1246 
1247  // deprecated
1248  self::initGlobal("ilias", "ILIAS", "./components/ILIAS/Init/classes/class.ilias.php");
1249  }
1250 
1254  protected static function initClient(): void
1255  {
1256  global $https, $ilias, $DIC;
1257 
1258  self::setCookieConstants();
1259 
1260  self::determineClient();
1261 
1262  self::bootstrapFilesystems();
1263 
1264  self::initResourceStorage();
1265 
1266  self::initClientIniFile();
1267 
1268  // --- needs client ini
1269 
1270  $ilias->client_id = (string) CLIENT_ID;
1271 
1272  if (DEVMODE) {
1273  self::handleDevMode();
1274  }
1275 
1276  self::handleMaintenanceMode();
1277 
1278  self::initDatabase();
1279 
1280  self::initGlobalCache();
1281 
1282  self::initComponentService($DIC);
1283 
1284  // init dafault language
1285  self::initLanguage(false);
1286 
1287  // moved after databases
1288  self::initLog();
1289 
1290  self::initGlobal(
1291  "ilAppEventHandler",
1292  "ilAppEventHandler",
1293  "./components/ILIAS/EventHandling/classes/class.ilAppEventHandler.php"
1294  );
1295 
1296  // there are rare cases where initILIAS is called twice for a request
1297  // example goto.php is called and includes ilias.php later
1298  // we must prevent that ilPluginAdmin is initialized twice in
1299  // this case, since this won't get the values out of plugin.php the
1300  // second time properly
1301  if (!isset($DIC["ilPluginAdmin"]) || !$DIC["ilPluginAdmin"] instanceof ilPluginAdmin) {
1302  self::initGlobal(
1303  "ilPluginAdmin",
1304  new ilPluginAdmin($DIC["component.repository"]),
1305  "./components/ILIAS/Component/classes/class.ilPluginAdmin.php"
1306  );
1307  }
1308  self::initGlobal("https", "ilHTTPS", "./components/ILIAS/Http/classes/class.ilHTTPS.php");
1309  self::initSettings();
1310  self::setSessionHandler();
1311  self::initCron($GLOBALS['DIC']);
1312  self::initAvatar($GLOBALS['DIC']);
1313  self::initCustomObjectIcons($GLOBALS['DIC']);
1314  self::initLegalDocuments($GLOBALS['DIC']);
1315  self::initAccessibilityControlConcept($GLOBALS['DIC']);
1316  self::initLearningObjectMetadata($GLOBALS['DIC']);
1317 
1318  // --- needs settings
1319 
1320  self::initLocale();
1321 
1322  if (ilContext::usesHTTP()) {
1323  $https->enableSecureCookies();
1324  $https->checkProtocolAndRedirectIfNeeded();
1325  }
1326 
1327  // --- object handling
1328 
1329  self::initGlobal(
1330  "ilObjDataCache",
1331  "ilObjectDataCache",
1332  "./components/ILIAS/Object/classes/class.ilObjectDataCache.php"
1333  );
1334 
1335  self::initGlobal(
1336  "objDefinition",
1337  "ilObjectDefinition",
1338  "./components/ILIAS/Object/classes/class.ilObjectDefinition.php"
1339  );
1340 
1341  // $tree
1342  $tree = new ilTree(ROOT_FOLDER_ID);
1343  self::initGlobal("tree", $tree);
1344  unset($tree);
1345 
1346  self::setSessionCookieParams();
1347  self::setClientIdCookie();
1348 
1349  (new InitCtrlService())->init($DIC);
1350 
1351  // Init GlobalScreen
1352  self::initGlobalScreen($DIC);
1353  }
1354 
1358  protected static function initUser(): void
1359  {
1360  global $ilias, $ilUser;
1361 
1362  // $ilUser
1363  self::initGlobal(
1364  "ilUser",
1366  "./components/ILIAS/User/classes/class.ilObjUser.php",
1367  true
1368  );
1369  $ilias->account = $ilUser;
1370 
1371  self::initAccessHandling();
1372  }
1373 
1377  public static function resumeUserSession(): void
1378  {
1379  global $DIC;
1380 
1383  }
1384 
1385  if (
1386  !$DIC['ilAuthSession']->isAuthenticated() ||
1387  $DIC['ilAuthSession']->isExpired()
1388  ) {
1389  if ($GLOBALS['DIC']['ilAuthSession']->isExpired()) {
1391  }
1392 
1393  ilLoggerFactory::getLogger('init')->debug('Current session is invalid: ' . $GLOBALS['DIC']['ilAuthSession']->getId());
1394  $current_script = substr(strrchr($_SERVER["PHP_SELF"], "/"), 1);
1395  if (self::blockedAuthentication($current_script)) {
1396  ilLoggerFactory::getLogger('init')->debug('Authentication is started in current script.');
1397  // nothing todo: authentication is done in current script
1398  return;
1399  }
1400 
1401  self::handleAuthenticationFail();
1402  return;
1403  }
1404  // valid session
1405 
1406  self::initUserAccount();
1407  }
1408 
1412  protected static function handleAuthenticationSuccess(): void
1413  {
1417  global $ilUser;
1418 
1420  }
1421 
1425  protected static function handleAuthenticationFail(): void
1426  {
1427  global $DIC;
1428 
1429  ilLoggerFactory::getLogger('init')->debug('Handling of failed authentication.');
1430 
1431  // #10608
1432  if (
1435  throw new Exception("Authentication failed.");
1436  }
1437 
1438  if (($DIC->http()->request()->getQueryParams()['cmdMode'] ?? 0) === 'asynch') {
1439  $DIC->language()->loadLanguageModule('init');
1440  $DIC->http()->saveResponse(
1441  $DIC->http()->response()
1442  ->withStatus(403)
1443  ->withBody(Streams::ofString($DIC->language()->txt('init_error_authentication_fail')))
1444  );
1445  $DIC->http()->sendResponse();
1446  $DIC->http()->close();
1447  }
1448  if (
1449  $DIC['ilAuthSession']->isExpired() &&
1450  !\ilObjUser::_isAnonymous($DIC['ilAuthSession']->getUserId())
1451  ) {
1452  ilLoggerFactory::getLogger('init')->debug('Expired session found -> redirect to login page');
1453  self::goToLogin();
1454  return;
1455  }
1456  if (ilPublicSectionSettings::getInstance()->isEnabledForDomain($_SERVER['SERVER_NAME']) &&
1457  $DIC->access()->checkAccessOfUser(ANONYMOUS_USER_ID, 'read', '', ROOT_FOLDER_ID)) {
1458  ilLoggerFactory::getLogger('init')->debug('Redirect to public section.');
1459  self::goToPublicSection();
1460  return;
1461  }
1462  ilLoggerFactory::getLogger('init')->debug('Redirect to login page.');
1463  self::goToLogin();
1464  }
1465 
1469  protected static function initHTTPServices(\ILIAS\DI\Container $container): void
1470  {
1471  $init_http = new InitHttpServices();
1472  $init_http->init($container);
1473 
1474  \ILIAS\StaticURL\Init::init($container);
1475  }
1476 
1480  private static function initGlobalScreen(\ILIAS\DI\Container $c): void
1481  {
1482  $c['global_screen'] = function () use ($c) {
1483  return new Services(
1484  new ilGSProviderFactory($c),
1485  $c->ui(),
1486  htmlentities(str_replace([" ", ".", "-"], "_", ILIAS_VERSION_NUMERIC))
1487  );
1488  };
1489  $c->globalScreen()->tool()->context()->stack()->clear();
1490  $c->globalScreen()->tool()->context()->claim()->main();
1491  }
1492 
1498  {
1499  $component_repository = $c["component.repository"];
1500  $component_factory = $c["component.factory"];
1501  foreach ($component_repository->getPlugins() as $pl) {
1502  if (!$pl->isActive()) {
1503  continue;
1504  }
1505  $plugin = $component_factory->getPlugin($pl->getId());
1506  $c['ui.renderer'] = $plugin->exchangeUIRendererAfterInitialization($c);
1507 
1508  foreach ($c->keys() as $key) {
1509  if (strpos($key, "ui.factory") === 0) {
1510  $c[$key] = $plugin->exchangeUIFactoryAfterInitialization($key, $c);
1511  }
1512  }
1513  }
1514  }
1515 
1519  protected static function replaceSuperGlobals(\ILIAS\DI\Container $container): void
1520  {
1522  $client_ini = $container['ilClientIniFile'];
1523 
1524  $replace_super_globals = (
1525  !$client_ini->variableExists('server', 'prevent_super_global_replacement') ||
1526  !(bool) $client_ini->readVariable('server', 'prevent_super_global_replacement')
1527  );
1528 
1529  if ($replace_super_globals) {
1530  $throwOnValueAssignment = defined('DEVMODE') && DEVMODE;
1531 
1532  $_GET = new SuperGlobalDropInReplacement($container['refinery'], $_GET, $throwOnValueAssignment);
1533  $_POST = new SuperGlobalDropInReplacement($container['refinery'], $_POST, $throwOnValueAssignment);
1534  $_COOKIE = new SuperGlobalDropInReplacement($container['refinery'], $_COOKIE, $throwOnValueAssignment);
1535  $_REQUEST = new SuperGlobalDropInReplacement($container['refinery'], $_REQUEST, $throwOnValueAssignment);
1536  }
1537  }
1538 
1539  protected static function initComponentService(\ILIAS\DI\Container $container): void
1540  {
1541  $init = new InitComponentService();
1542  $init->init($container);
1543  }
1544 
1548  protected static function initHTML(): void
1549  {
1550  global $ilUser, $DIC;
1551 
1552  if (ilContext::hasUser()) {
1553  // load style definitions
1554  // use the init function with plugin hook here, too
1555  self::initStyle();
1556 
1557  self::initUploadPolicies($DIC);
1558  }
1559 
1560  self::applyPluginManipulationsToUiFramework($GLOBALS["DIC"]);
1561  $tpl = new ilGlobalPageTemplate($DIC->globalScreen(), $DIC->ui(), $DIC->http());
1562  self::initGlobal("tpl", $tpl);
1563 
1564  if (ilContext::hasUser()) {
1565  $dispatcher = new \ILIAS\Init\StartupSequence\StartUpSequenceDispatcher($DIC);
1566  $dispatcher->dispatch();
1567  }
1568 
1569  self::initGlobal(
1570  "ilNavigationHistory",
1571  "ilNavigationHistory",
1572  "components/ILIAS/Navigation/classes/class.ilNavigationHistory.php"
1573  );
1574 
1575  self::initGlobal(
1576  "ilHelp",
1577  "ilHelpGUI",
1578  "components/ILIAS/Help/classes/class.ilHelpGUI.php"
1579  );
1580 
1581  if (DEVMODE) {
1582  $DIC["help.text_retriever"] = new ILIAS\UI\Help\TextRetriever\Echoing();
1583  } else {
1584  $DIC["help.text_retriever"] = new ilHelpUITextRetriever();
1585  }
1586 
1587  self::initGlobal(
1588  "ilToolbar",
1589  "ilToolbarGUI",
1590  "./components/ILIAS/UIComponent/Toolbar/classes/class.ilToolbarGUI.php"
1591  );
1592 
1593  self::initGlobal(
1594  "ilLocator",
1595  "ilLocatorGUI",
1596  "./components/ILIAS/Locator/classes/class.ilLocatorGUI.php"
1597  );
1598 
1599  self::initGlobal(
1600  "ilTabs",
1601  "ilTabsGUI",
1602  "./components/ILIAS/UIComponent/Tabs/classes/class.ilTabsGUI.php"
1603  );
1604 
1605  if (ilContext::hasUser()) {
1606  // the next line makes it impossible to save the offset somehow in a session for
1607  // a specific table (I tried it for the user administration).
1608  // its not posssible to distinguish whether it has been set to page 1 (=offset = 0)
1609  // or not set at all (then we want the last offset, e.g. being used from a session var).
1610  // So I added the wrapping if statement. Seems to work (hopefully).
1611  // Alex April 14th 2006
1612  // @todo not replaced by refinery due to unknown sideeffects
1613  if (isset($_GET['offset']) && $_GET['offset'] != "") {
1614  $_GET['offset'] = (int) $_GET['offset']; // old code
1615  }
1616 
1617  self::initGlobal("lti", "ilLTIViewGUI", "./components/ILIAS/LTIProvider/classes/class.ilLTIViewGUI.php");
1618  $GLOBALS["DIC"]["lti"]->init();
1619  self::initKioskMode($GLOBALS["DIC"]);
1620  }
1621  }
1622 
1626  protected static function blockedAuthentication(string $a_current_script): bool
1627  {
1628  global $DIC;
1629 
1631  ilLoggerFactory::getLogger('init')->debug('Blocked authentication for WAC request.');
1632  return true;
1633  }
1635  ilLoggerFactory::getLogger('init')->debug('Blocked authentication for sso request.');
1636  return true;
1637  }
1639  ilLoggerFactory::getLogger('init')->debug('Blocked authentication for webdav request');
1640  return true;
1641  }
1643  ilLoggerFactory::getLogger('init')->debug('Blocked authentication for shibboleth request.');
1644  return true;
1645  }
1647  ilLoggerFactory::getLogger('init')->debug('Blocked authentication for lti provider requests.');
1648  return true;
1649  }
1651  ilLoggerFactory::getLogger('init')->debug('Blocked authentication for SAML request.');
1652  return true;
1653  }
1654  if (
1655  $a_current_script == "register.php" ||
1656  $a_current_script == "pwassist.php" ||
1657  $a_current_script == "confirmReg.php" ||
1658  $a_current_script == "il_securimage_play.php" ||
1659  $a_current_script == "il_securimage_show.php" ||
1660  $a_current_script == 'login.php'
1661  ) {
1662  ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for script: ' . $a_current_script);
1663  return true;
1664  }
1665 
1666  // @todo refinery undefined
1667  $requestBaseClass = strtolower((string) ($_GET['baseClass'] ?? ''));
1668  if ($requestBaseClass == strtolower(ilStartUpGUI::class)) {
1669  $requestCmdClass = strtolower((string) ($_GET['cmdClass'] ?? ''));
1670  if (
1671  $requestCmdClass == strtolower(ilAccountRegistrationGUI::class) ||
1672  $requestCmdClass == strtolower(ilPasswordAssistanceGUI::class)
1673  ) {
1674  ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for cmdClass: ' . $requestCmdClass);
1675  return true;
1676  }
1677  $cmd = $DIC->ctrl()->getCmd();
1678 
1679  if (in_array($cmd, [
1680  'showLegalDocuments',
1681  'showAccountMigration',
1682  'migrateAccount',
1683  'processCode',
1684  'showLoginPage',
1685  'showLogout',
1686  'doStandardAuthentication',
1687  'doCasAuthentication',
1688  ], true)) {
1689  ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for cmd: ' . $cmd);
1690  return true;
1691  }
1692  }
1693 
1694  $target = '';
1695  if ($DIC->http()->wrapper()->query()->has('target')) {
1696  // @todo refinery undefined
1697  $target = $_GET['target'];
1698  }
1699 
1700  // #12884
1701  if (
1702  ($a_current_script == "goto.php" && $target == "impr_0") ||
1703  $requestBaseClass == strtolower(ilImprintGUI::class)
1704  ) {
1705  // @todo refinery undefind
1706  ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for baseClass: ' . ($_GET['baseClass'] ?? ""));
1707  return true;
1708  }
1709 
1710  if (
1711  (strtolower($requestCmdClass ?? "") === strtolower(ilAccessibilityControlConceptGUI::class))
1712  ) {
1713  ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for cmdClass: ' . $requestCmdClass);
1714  return true;
1715  }
1716 
1717  if ($a_current_script == 'goto.php' && in_array($target, array(
1718  'usr_registration',
1719  'usr_nameassist',
1720  'usr_pwassist',
1721  'usr_agreement'
1722  ))) {
1723  ilLoggerFactory::getLogger('auth')->debug('Blocked authentication for goto target: ' . $target);
1724  return true;
1725  }
1726 
1727 
1728  $current_ref_id = $DIC->http()->wrapper()->query()->has('ref_id')
1729  ? $DIC->http()->wrapper()->query()->retrieve('ref_id', $DIC->refinery()->kindlyTo()->int())
1730  : null;
1731 
1732  if (null !== $current_ref_id
1733  && $DIC->user()->getId() === 0
1734  && $DIC->access()->checkAccessOfUser(
1736  'visible',
1737  '',
1738  $current_ref_id
1739  )) {
1740  return true;
1741  }
1742 
1743 
1744  ilLoggerFactory::getLogger('auth')->debug('Authentication required');
1745  return false;
1746  }
1747 
1751  protected static function translateMessage(string $a_message_id, ?array $a_message_static = null): string
1752  {
1753  global $ilDB, $lng, $ilSetting, $ilClientIniFile, $ilUser;
1754 
1755  // current language
1756  if (!$lng) {
1757  $lang = "en";
1758  if ($ilUser) {
1759  $lang = $ilUser->getLanguage();
1760  } elseif (isset($_REQUEST["lang"])) {
1761  $lang = (string) $_REQUEST["lang"];
1762  } elseif ($ilSetting) {
1763  $lang = $ilSetting->get("language", '');
1764  } elseif ($ilClientIniFile) {
1765  $lang = $ilClientIniFile->readVariable("language", "default");
1766  }
1767  } else {
1768  $lang = $lng->getLangKey();
1769  }
1770 
1771  $message = "";
1772  if ($ilDB && $a_message_id) {
1773  if (!$lng) {
1774  $lng = new ilLanguage($lang);
1775  }
1776 
1777  $lng->loadLanguageModule("init");
1778  $message = $lng->txt($a_message_id);
1779  } elseif (is_array($a_message_static)) {
1780  if (!isset($a_message_static[$lang])) {
1781  $lang = "en";
1782  }
1783  $message = $a_message_static[$lang];
1784  }
1785  return $message;
1786  }
1787 
1791  protected static function redirect(
1792  string $a_target,
1793  string $a_message_id = '',
1794  ?array $a_message_static = null
1795  ): void {
1796  // #12739
1797  if (defined("ILIAS_HTTP_PATH") &&
1798  !stristr($a_target, ILIAS_HTTP_PATH)) {
1799  $a_target = ILIAS_HTTP_PATH . "/" . $a_target;
1800  }
1801 
1802  foreach (['ext_uid', 'soap_pw'] as $param) {
1803  if (false === strpos(
1804  $a_target,
1805  $param . '='
1806  ) && isset($GLOBALS['DIC']->http()->request()->getQueryParams()[$param])) {
1807  $a_target = \ilUtil::appendUrlParameterString($a_target, $param . '=' . \ilUtil::stripSlashes(
1808  $GLOBALS['DIC']->http()->request()->getQueryParams()[$param]
1809  ));
1810  }
1811  }
1812 
1814  ilUtil::redirect($a_target);
1815  } else {
1816  $message = self::translateMessage($a_message_id, $a_message_static);
1817 
1818  // user-directed linked message
1820  $link = self::translateMessage(
1821  "init_error_redirect_click",
1822  array("en" => 'Please click to continue.',
1823  "de" => 'Bitte klicken um fortzufahren.'
1824  )
1825  );
1826  $mess = $message .
1827  '<br /><a href="' . $a_target . '">' . $link . '</a>';
1828  } // plain text
1829  else {
1830  // not much we can do here
1831  $mess = $message;
1832 
1833  if (!trim($mess)) {
1834  $mess = self::translateMessage(
1835  "init_error_redirect_info",
1836  array("en" => 'Redirect not supported by context.',
1837  "de" => 'Weiterleitungen werden durch Kontext nicht unterstützt.'
1838  )
1839  ) .
1840  ' (' . $a_target . ')';
1841  }
1842  }
1843 
1844  self::abortAndDie($mess);
1845  }
1846  }
1847 
1848  public static function redirectToStartingPage(string $target = ''): void
1849  {
1850  global $DIC;
1851 
1852  // fallback, should never happen
1853  if ($DIC->user()->getId() === ANONYMOUS_USER_ID) {
1854  self::goToPublicSection();
1855  return;
1856  }
1857 
1858  if (
1859  $target === '' &&
1860  $DIC->http()->wrapper()->query()->has('target')
1861  ) {
1862  $target = $DIC->http()->wrapper()->query()->retrieve(
1863  'target',
1864  $DIC->refinery()->kindlyTo()->string()
1865  );
1866  }
1867 
1868  // for password change and incomplete profile
1869  // see ilDashboardGUI
1870  if ($target === '') {
1871  ilLoggerFactory::getLogger('init')->debug('Redirect to default starting page');
1872  $DIC->ctrl()->redirectToURL(ilUserUtil::getStartingPointAsUrl());
1873  } else {
1874  ilLoggerFactory::getLogger('init')->debug('Redirect to target: ' . $target);
1875  $DIC->ctrl()->redirectToURL("goto.php?target=" . $target);
1876  }
1877  }
1878 
1879  private static function initBackgroundTasks(\ILIAS\DI\Container $c): void
1880  {
1881  global $ilIliasIniFile;
1882 
1883  $n_of_tasks = $ilIliasIniFile->readVariable("background_tasks", "number_of_concurrent_tasks");
1884  $sync = $ilIliasIniFile->readVariable("background_tasks", "concurrency");
1885 
1886  $n_of_tasks = $n_of_tasks ?: 5;
1887  $sync = $sync ?: 'sync'; // The default value is sync.
1888 
1889  $c["bt.task_factory"] = function ($c) {
1890  return new \ILIAS\BackgroundTasks\Implementation\Tasks\BasicTaskFactory($c["di.injector"]);
1891  };
1892 
1893  $c["bt.persistence"] = function ($c) {
1894  return \ILIAS\BackgroundTasks\Implementation\Persistence\BasicPersistence::instance($c->database());
1895  };
1896 
1897  $c["bt.injector"] = function ($c) {
1898  return new \ILIAS\BackgroundTasks\Dependencies\Injector($c, new BaseDependencyMap());
1899  };
1900 
1901  $c["bt.task_manager"] = function ($c) use ($sync) {
1902  if ($sync == 'sync') {
1903  return new \ILIAS\BackgroundTasks\Implementation\TaskManager\SyncTaskManager($c["bt.persistence"]);
1904  } elseif ($sync == 'async') {
1905  return new \ILIAS\BackgroundTasks\Implementation\TaskManager\AsyncTaskManager($c["bt.persistence"]);
1906  } else {
1907  throw new ilException("The supported Background Task Managers are sync and async. $sync given.");
1908  }
1909  };
1910  }
1911 
1912  private static function initInjector(\ILIAS\DI\Container $c): void
1913  {
1914  $c["di.dependency_map"] = function ($c) {
1915  return new \ILIAS\BackgroundTasks\Dependencies\DependencyMap\BaseDependencyMap();
1916  };
1917 
1918  $c["di.injector"] = function ($c) {
1919  return new \ILIAS\BackgroundTasks\Dependencies\Injector($c, $c["di.dependency_map"]);
1920  };
1921  }
1922 
1923  private static function initKioskMode(\ILIAS\DI\Container $c): void
1924  {
1925  $c["service.kiosk_mode"] = function ($c) {
1926  return new ilKioskModeService(
1927  $c['ilCtrl'],
1928  $c['lng'],
1929  $c['ilAccess'],
1930  $c['objDefinition']
1931  );
1932  };
1933  }
1934 
1935  private static function initLearningObjectMetadata(\ILIAS\DI\Container $c): void
1936  {
1937  $c['learning_object_metadata'] = function ($c) {
1938  return new \ILIAS\MetaData\Services\Services($c);
1939  };
1940  }
1941 }
static initHTTPServices(\ILIAS\DI\Container $container)
then(callable $f)
Get a new result from the callable or do nothing if this is an error.
static initAvatar(\ILIAS\DI\Container $c)
static handleMaintenanceMode()
handle maintenance mode
$_GET["client_id"]
Definition: webdav.php:30
static hasUser()
Based on user authentication?
static appendUrlParameterString(string $a_url, string $a_par, bool $xml_style=false)
const int CONTEXT_HTTP
HTTP Auth used for WebDAV and CalDAV If a special handling for WebDAV or CalDAV is required overwrite...
const CONTEXT_WAC
Class InitCtrlService wraps the initialization of ilCtrl.
const ANONYMOUS_USER_ID
Definition: constants.php:27
static getLogger(string $a_component_id)
Get component logger.
This describes a facility that the UI framework can use to retrieve some help text.
static applyPluginManipulationsToUiFramework(\ILIAS\DI\Container $c)
const int SESSION_CLOSE_LOGIN
static usesHTTP()
Uses HTTP aka browser.
static initFileUploadService(\ILIAS\DI\Container $dic)
Initializes the file upload service.
const ROOT_FOLDER_ID
Definition: constants.php:32
static initHTML()
init HTML output (level 3)
static orderBy(string $orderBy, string $orderDirection='ASC')
const CONTEXT_WEBDAV
static _exists(string $a_session_id)
Interface Observer Contains several chained tasks and infos about them.
static initKioskMode(\ILIAS\DI\Container $c)
static stripSlashes(string $a_str, bool $a_strip_html=true, string $a_allow="")
static abortAndDie(string $a_message)
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
static updateAccess(ilObjUser $user)
Responsible for loading the Resource Storage into the dependency injection container of ILIAS...
static determineClient()
This method determines the current client and sets the constant CLIENT_ID.
static init(Container $c)
Definition: Init.php:36
static isAuthenticationForced()
const CONTEXT_LTI_PROVIDER
static initDefaultTimeZone(ilIniFile $ini)
Initialize default timezone from system settings.
const CONTEXT_SHIBBOLETH
static goToPublicSection()
go to public section
static blockedAuthentication(string $a_current_script)
Block authentication based on current request.
$c
Definition: deliver.php:25
static resumeUserSession()
Resume an existing user session.
static setSessionHandler()
set session handler to db Used in Soap
static initSession()
Init auth session.
Customizing of pimple-DIC for ILIAS.
Definition: Container.php:35
Class SuperGlobalDropInReplacement This Class wraps SuperGlobals such as $_GET and $_POST to prevent ...
static getGlobalInstance()
Builds the global language object.
const int SESSION_CLOSE_PUBLIC
$ilErr
Definition: raiseError.php:33
$container
Definition: wac.php:36
static initBackgroundTasks(\ILIAS\DI\Container $c)
static initAccessHandling()
$ilAccess and $rbac...
static getWrapper(string $a_type)
static initLegalDocuments(Container $c)
while($session_entry=$r->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) return null
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
static initCron(\ILIAS\DI\Container $c)
static redirect(string $a_target, string $a_message_id='', ?array $a_message_static=null)
Redirects to target url if context supports it.
static initILIAS()
ilias initialisation
static handleForcedAuthentication()
$ilIliasIniFile
Definition: server.php:35
const ILIAS_VERSION_NUMERIC
static http()
Fetches the global http state from ILIAS.
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
static initDatabase()
initialise database object $ilDB
static initCustomObjectIcons(\ILIAS\DI\Container $c)
const CONTEXT_SAML
$GLOBALS["DIC"]
Definition: wac.php:53
$log
Definition: result.php:32
static initClientIniFile()
This method provides a global instance of class ilIniFile for the client.ini.php file in variable $il...
static setCookie(string $a_cookie_name, string $a_cookie_value='', bool $a_also_set_super_global=true, bool $a_set_cookie_invalid=false)
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
static hasHTML()
Has HTML output.
Class HTTPServicesTest.
$_SERVER['HTTP_HOST']
Definition: raiseError.php:26
$param
Definition: xapitoken.php:46
const CLIENT_ID
Definition: constants.php:41
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Ok.php:30
global $DIC
Definition: shib_login.php:26
static initLearningObjectMetadata(\ILIAS\DI\Container $c)
static initGlobal(string $a_name, $a_class, ?string $a_source_file=null, ?bool $destroy_existing=false)
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
static initLocale()
Init Locale.
static requireCommonIncludes()
get common include code files
const CLIENT_WEB_DIR
Definition: constants.php:47
static initLog()
Init log instance.
static initStyle()
provide $styleDefinition object
static getFallbackInstance()
Builds a global default language instance.
static initClient()
Init client-based objects (level 1)
const ILIAS_DATA_DIR
Definition: constants.php:44
static initIliasIniFile()
This method provides a global instance of class ilIniFile for the ilias.ini.php file in variable $ilI...
Class ilFileServicesFilenameSanitizer.
static _isAnonymous(int $usr_id)
static redirect(string $a_script)
static _destroy($a_session_id, ?int $a_closing_context=null, $a_expired_at=null)
Destroy session.
$lang
Definition: xapiexit.php:25
const int SESSION_CLOSE_EXPIRE
static initUploadPolicies(\ILIAS\DI\Container $dic)
static translateMessage(string $a_message_id, ?array $a_message_static=null)
Translate message if possible.
static removeUnsafeCharacters()
Remove unsafe characters from GET.
static initCore()
Init core objects (level 0)
static setSessionCookieParams()
set session cookie params
static supportsPersistentSessions()
Check if context supports persistent session handling.
static redirectToStartingPage(string $target='')
Central entry point for users of the service.
global $ilSetting
Definition: privfeed.php:31
static setClosingContext(int $a_context)
set closing context (for statistics)
static getInstance(ilLogger $logger)
static initClient()
Init client.
global $lng
Definition: privfeed.php:31
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
A transformation is a function from one datatype to another.
static initInjector(\ILIAS\DI\Container $c)
static getClientIdTransformation()
Refinery is not initialized early enough to provide a transformation to be used with the implementat...
static initComponentService(\ILIAS\DI\Container $container)
$dic
Definition: result.php:31
$client_id
Definition: ltiauth.php:66
$message
Definition: xapiexit.php:31
static goToLogin()
go to login
static initAccessibilityControlConcept(\ILIAS\DI\Container $c)
static getType()
Get context type.
static initGlobalScreen(\ILIAS\DI\Container $c)
static initUserAccount()
Init user with current account id.
$_COOKIE[session_name()]
Definition: xapitoken.php:54
static recursivelyRemoveUnsafeCharacters($var)
$cookie_path
Definition: index.php:29
const CONTEXT_SOAP
static handleErrorReporting()
Set error reporting level.
static initSettings()
initialise $ilSettings object and define constants Used in Soap
const CONTEXT_APACHE_SSO
static initUser()
Init user / authentification (level 2)
const IL_COOKIE_PATH(isset($_GET['client_id']))
Definition: index.php:47
Responsible for loading the HTTP Service into the dependency injection container of ILIAS...
static getRootLogger()
The unique root logger has a fixed error level.
const ILIAS_WEB_DIR
Definition: constants.php:45
static supportsRedirects()
Are redirects supported?
static handleDevMode()
Prepare developer tools.