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