Subversion Repositories oidplus

Rev

Rev 1015 | Rev 1041 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2022 Daniel Marschall, ViaThinkSoft
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *     http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  */
  19.  
  20. if (!defined('INSIDE_OIDPLUS')) die();
  21.  
  22. class OIDplus extends OIDplusBaseClass {
  23.         private static /*OIDplusPagePlugin[]*/ $pagePlugins = array();
  24.         private static /*OIDplusAuthPlugin[]*/ $authPlugins = array();
  25.         private static /*OIDplusLoggerPlugin[]*/ $loggerPlugins = array();
  26.         private static /*OIDplusObjectTypePlugin[]*/ $objectTypePlugins = array();
  27.         private static /*string[]*/ $enabledObjectTypes = array();
  28.         private static /*string[]*/ $disabledObjectTypes = array();
  29.         private static /*OIDplusDatabasePlugin[]*/ $dbPlugins = array();
  30.         private static /*OIDplusCaptchaPlugin[]*/ $captchaPlugins = array();
  31.         private static /*OIDplusSqlSlangPlugin[]*/ $sqlSlangPlugins = array();
  32.         private static /*OIDplusLanguagePlugin[]*/ $languagePlugins = array();
  33.         private static /*OIDplusDesignPlugin[]*/ $designPlugins = array();
  34.  
  35.         protected static $html = true;
  36.  
  37.         /*public*/ const DEFAULT_LANGUAGE = 'enus'; // the language of the source code
  38.  
  39.         /*public*/ const PATH_RELATIVE = 1;                   // e.g. "../"
  40.         /*public*/ const PATH_ABSOLUTE = 2;                   // e.g. "http://www.example.com/oidplus/"
  41.         /*public*/ const PATH_ABSOLUTE_CANONICAL = 3;         // e.g. "http://www.example.org/oidplus/" (if baseconfig CANONICAL_SYSTEM_URL is set)
  42.         /*public*/ const PATH_RELATIVE_TO_ROOT = 4;           // e.g. "/oidplus/"
  43.         /*public*/ const PATH_RELATIVE_TO_ROOT_CANONICAL = 5; // e.g. "/oidplus/" (if baseconfig CANONICAL_SYSTEM_URL is set)
  44.  
  45.         // These plugin types can contain HTML code and therefore may
  46.         // emit (non-setup) CSS/JS code via their manifest.
  47.         /*public*/ const INTERACTIVE_PLUGIN_TYPES = array(
  48.                 'publicPages',
  49.                 'raPages',
  50.                 'adminPages',
  51.                 'objectTypes',
  52.                 'captcha'
  53.         );
  54.  
  55.         private function __construct() {
  56.         }
  57.  
  58.         # --- Static classes
  59.  
  60.         private static $baseConfig = null;
  61.         private static $old_config_format = false;
  62.         public static function baseConfig() {
  63.                 $first_init = false;
  64.  
  65.                 if ($first_init = is_null(self::$baseConfig)) {
  66.                         self::$baseConfig = new OIDplusBaseConfig();
  67.                 }
  68.  
  69.                 if ($first_init) {
  70.                         // Include a file containing various size/depth limitations of OIDs
  71.                         // It is important to include it before userdata/baseconfig/config.inc.php was included,
  72.                         // so we can give userdata/baseconfig/config.inc.php the chance to override the values.
  73.  
  74.                         include OIDplus::localpath().'includes/oidplus_limits.inc.php';
  75.  
  76.                         // Include config file
  77.  
  78.                         $config_file = OIDplus::localpath() . 'userdata/baseconfig/config.inc.php';
  79.                         $config_file_old = OIDplus::localpath() . 'includes/config.inc.php'; // backwards compatibility
  80.  
  81.                         if (!file_exists($config_file) && file_exists($config_file_old)) {
  82.                                 $config_file = $config_file_old;
  83.                         }
  84.  
  85.                         if (file_exists($config_file)) {
  86.                                 if (self::$old_config_format) {
  87.                                         // Note: We may only include it once due to backwards compatibility,
  88.                                         //       since in version 2.0, the configuration was defined using define() statements
  89.                                         // Attention: This does mean that a full re-init (e.g. for test cases) is not possible
  90.                                         //            if a version 2.0 config is used!
  91.                                         include_once $config_file;
  92.                                 } else {
  93.                                         include $config_file;
  94.                                 }
  95.  
  96.                                 if (defined('OIDPLUS_CONFIG_VERSION') && (OIDPLUS_CONFIG_VERSION == 2.0)) {
  97.                                         self::$old_config_format = true;
  98.  
  99.                                         // Backwards compatibility 2.0 => 2.1
  100.                                         foreach (get_defined_constants(true)['user'] as $name => $value) {
  101.                                                 $name = str_replace('OIDPLUS_', '', $name);
  102.                                                 if ($name == 'SESSION_SECRET') $name = 'SERVER_SECRET';
  103.                                                 if ($name == 'MYSQL_QUERYLOG') $name = 'QUERY_LOGFILE';
  104.                                                 if (($name == 'MYSQL_PASSWORD') || ($name == 'ODBC_PASSWORD') || ($name == 'PDO_PASSWORD') || ($name == 'PGSQL_PASSWORD')) {
  105.                                                         self::$baseConfig->setValue($name, base64_decode($value));
  106.                                                 } else {
  107.                                                         if ($name == 'CONFIG_VERSION') $value = 2.1;
  108.                                                         self::$baseConfig->setValue($name, $value);
  109.                                                 }
  110.                                         }
  111.                                 }
  112.                         } else {
  113.                                 if (!is_dir(OIDplus::localpath().'setup')) {
  114.                                         throw new OIDplusConfigInitializationException(_L('File %1 is missing, but setup can\'t be started because its directory missing.','userdata/baseconfig/config.inc.php'));
  115.                                 } else {
  116.                                         if (self::$html) {
  117.                                                 if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE_TO_ROOT).'setup/') !== 0) {
  118.                                                         header('Location:'.OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/');
  119.                                                         die(_L('Redirecting to setup...'));
  120.                                                 } else {
  121.                                                         return self::$baseConfig;
  122.                                                 }
  123.                                         } else {
  124.                                                 // This can be displayed in e.g. ajax.php
  125.                                                 throw new OIDplusConfigInitializationException(_L('File %1 is missing. Please run setup again.','userdata/baseconfig/config.inc.php'));
  126.                                         }
  127.                                 }
  128.                         }
  129.  
  130.                         // Check important config settings
  131.  
  132.                         if (self::$baseConfig->getValue('CONFIG_VERSION') != 2.1) {
  133.                                 if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/') !== 0) {
  134.                                         throw new OIDplusConfigInitializationException(_L("The information located in %1 is outdated.",realpath($config_file)));
  135.                                 }
  136.                         }
  137.  
  138.                         if (self::$baseConfig->getValue('SERVER_SECRET', '') === '') {
  139.                                 if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/') !== 0) {
  140.                                         throw new OIDplusConfigInitializationException(_L("You must set a value for SERVER_SECRET in %1 for the system to operate secure.",realpath($config_file)));
  141.                                 }
  142.                         }
  143.                 }
  144.  
  145.                 return self::$baseConfig;
  146.         }
  147.  
  148.         private static $config = null;
  149.         public static function config() {
  150.                 if ($first_init = is_null(self::$config)) {
  151.                         self::$config = new OIDplusConfig();
  152.                 }
  153.  
  154.                 if ($first_init) {
  155.                         // These are important settings for base functionalities and therefore are not inside plugins
  156.                         self::$config->prepareConfigKey('system_title', 'What is the name of your RA?', 'OIDplus 2.0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  157.                                 if (empty($value)) {
  158.                                         throw new OIDplusException(_L('Please enter a value for the system title.'));
  159.                                 }
  160.                         });
  161.                         self::$config->prepareConfigKey('admin_email', 'E-Mail address of the system administrator', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  162.                                 if (!empty($value) && !OIDplus::mailUtils()->validMailAddress($value)) {
  163.                                         throw new OIDplusException(_L('This is not a correct email address'));
  164.                                 }
  165.                         });
  166.                         self::$config->prepareConfigKey('global_cc', 'Global CC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function(&$value) {
  167.                                 $value = trim($value);
  168.                                 if ($value === '') return;
  169.                                 $addrs = explode(';', $value);
  170.                                 foreach ($addrs as $addr) {
  171.                                         $addr = trim($addr);
  172.                                         if (!empty($addr) && !OIDplus::mailUtils()->validMailAddress($addr)) {
  173.                                                 throw new OIDplusException(_L('%1 is not a correct email address',$addr));
  174.                                         }
  175.                                 }
  176.                         });
  177.                         self::$config->prepareConfigKey('global_bcc', 'Global BCC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function(&$value) {
  178.                                 $value = trim($value);
  179.                                 if ($value === '') return;
  180.                                 $addrs = explode(';', $value);
  181.                                 foreach ($addrs as $addr) {
  182.                                         $addr = trim($addr);
  183.                                         if (!empty($addr) && !OIDplus::mailUtils()->validMailAddress($addr)) {
  184.                                                 throw new OIDplusException(_L('%1 is not a correct email address',$addr));
  185.                                         }
  186.                                 }
  187.                         });
  188.                         self::$config->prepareConfigKey('objecttypes_initialized', 'List of object type plugins that were initialized once', '', OIDplusConfig::PROTECTION_READONLY, function($value) {
  189.                                 // Nothing here yet
  190.                         });
  191.                         self::$config->prepareConfigKey('objecttypes_enabled', 'Enabled object types and their order, separated with a semicolon (please reload the page so that the change is applied)', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  192.                                 # TODO: when objecttypes_enabled is changed at the admin control panel, we need to do a reload of the page, so that jsTree will be updated. Is there anything we can do?
  193.  
  194.                                 $ary = explode(';',$value);
  195.                                 $uniq_ary = array_unique($ary);
  196.  
  197.                                 if (count($ary) != count($uniq_ary)) {
  198.                                         throw new OIDplusException(_L('Please check your input. Some object types are double.'));
  199.                                 }
  200.  
  201.                                 foreach ($ary as $ot_check) {
  202.                                         $ns_found = false;
  203.                                         foreach (OIDplus::getEnabledObjectTypes() as $ot) {
  204.                                                 if ($ot::ns() == $ot_check) {
  205.                                                         $ns_found = true;
  206.                                                         break;
  207.                                                 }
  208.                                         }
  209.                                         foreach (OIDplus::getDisabledObjectTypes() as $ot) {
  210.                                                 if ($ot::ns() == $ot_check) {
  211.                                                         $ns_found = true;
  212.                                                         break;
  213.                                                 }
  214.                                         }
  215.                                         if (!$ns_found) {
  216.                                                 throw new OIDplusException(_L('Please check your input. Namespace "%1" is not found',$ot_check));
  217.                                         }
  218.                                 }
  219.                         });
  220.                         self::$config->prepareConfigKey('oidplus_private_key', 'Private key for this system', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
  221.                                 // Nothing here yet
  222.                         });
  223.                         self::$config->prepareConfigKey('oidplus_public_key', 'Public key for this system. If you "clone" your system, you must delete this key (e.g. using phpMyAdmin), so that a new one is created.', '', OIDplusConfig::PROTECTION_READONLY, function($value) {
  224.                                 // Nothing here yet
  225.                         });
  226.                         self::$config->prepareConfigKey('last_known_system_url', 'Last known System URL', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
  227.                                 // Nothing here yet
  228.                         });
  229.                         self::$config->prepareConfigKey('last_known_version', 'Last known OIDplus Version', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
  230.                                 // Nothing here yet
  231.                         });
  232.                         self::$config->prepareConfigKey('default_ra_auth_method', 'Default auth method used for generating password of RAs (must exist in plugins/[vendorname]/auth/)?', 'A3_bcrypt', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  233.                                 $good = true;
  234.                                 if (strpos($value,'/') !== false) $good = false;
  235.                                 if (strpos($value,'\\') !== false) $good = false;
  236.                                 if (strpos($value,'..') !== false) $good = false;
  237.                                 if (!$good) {
  238.                                         throw new OIDplusException(_L('Invalid auth plugin folder name. Do only enter a folder name, not an absolute or relative path'));
  239.                                 }
  240.  
  241.                                 if (!wildcard_is_dir(OIDplus::localpath().'plugins/'.'*'.'/auth/'.$value)) {
  242.                                         throw new OIDplusException(_L('The auth plugin "%1" does not exist in plugin directory %2',$value,'plugins/[vendorname]/auth/'));
  243.                                 }
  244.                         });
  245.                 }
  246.  
  247.                 return self::$config;
  248.         }
  249.  
  250.         private static $gui = null;
  251.         public static function gui() {
  252.                 if (is_null(self::$gui)) {
  253.                         self::$gui = new OIDplusGui();
  254.                 }
  255.                 return self::$gui;
  256.         }
  257.  
  258.         private static $authUtils = null;
  259.         public static function authUtils() {
  260.                 if (is_null(self::$authUtils)) {
  261.                         self::$authUtils = new OIDplusAuthUtils();
  262.                 }
  263.                 return self::$authUtils;
  264.         }
  265.  
  266.         private static $mailUtils = null;
  267.         public static function mailUtils() {
  268.                 if (is_null(self::$mailUtils)) {
  269.                         self::$mailUtils = new OIDplusMailUtils();
  270.                 }
  271.                 return self::$mailUtils;
  272.         }
  273.  
  274.         private static $cookieUtils = null;
  275.         public static function cookieUtils() {
  276.                 if (is_null(self::$cookieUtils)) {
  277.                         self::$cookieUtils = new OIDplusCookieUtils();
  278.                 }
  279.                 return self::$cookieUtils;
  280.         }
  281.  
  282.         private static $menuUtils = null;
  283.         public static function menuUtils() {
  284.                 if (is_null(self::$menuUtils)) {
  285.                         self::$menuUtils = new OIDplusMenuUtils();
  286.                 }
  287.                 return self::$menuUtils;
  288.         }
  289.  
  290.         private static $logger = null;
  291.         public static function logger() {
  292.                 if (is_null(self::$logger)) {
  293.                         self::$logger = new OIDplusLogger();
  294.                 }
  295.                 return self::$logger;
  296.         }
  297.  
  298.         # --- SQL slang plugin
  299.  
  300.         private static function registerSqlSlangPlugin(OIDplusSqlSlangPlugin $plugin) {
  301.                 $name = $plugin::id();
  302.                 if ($name === '') return false;
  303.  
  304.                 if (isset(self::$sqlSlangPlugins[$name])) {
  305.                         $plugintype_hf = _L('SQL slang');
  306.                         throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
  307.                 }
  308.  
  309.                 self::$sqlSlangPlugins[$name] = $plugin;
  310.  
  311.                 return true;
  312.         }
  313.  
  314.         public static function getSqlSlangPlugins() {
  315.                 return self::$sqlSlangPlugins;
  316.         }
  317.  
  318.         public static function getSqlSlangPlugin($id)/*: ?OIDplusSqlSlangPlugin*/ {
  319.                 if (isset(self::$sqlSlangPlugins[$id])) {
  320.                         return self::$sqlSlangPlugins[$id];
  321.                 } else {
  322.                         return null;
  323.                 }
  324.         }
  325.  
  326.         # --- Database plugin
  327.  
  328.         private static function registerDatabasePlugin(OIDplusDatabasePlugin $plugin) {
  329.                 $name = $plugin::id();
  330.                 if ($name === '') return false;
  331.  
  332.                 if (isset(self::$dbPlugins[$name])) {
  333.                         $plugintype_hf = _L('Database');
  334.                         throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
  335.                 }
  336.  
  337.                 self::$dbPlugins[$name] = $plugin;
  338.  
  339.                 return true;
  340.         }
  341.  
  342.         public static function getDatabasePlugins() {
  343.                 return self::$dbPlugins;
  344.         }
  345.  
  346.         public static function getActiveDatabasePlugin() {
  347.                 $db_plugin_name = OIDplus::baseConfig()->getValue('DATABASE_PLUGIN','');
  348.                 if ($db_plugin_name === '') {
  349.                         throw new OIDplusConfigInitializationException(_L('No database plugin selected in config file'));
  350.                 }
  351.                 foreach (self::$dbPlugins as $name => $plugin) {
  352.                         if (strtolower($name) == strtolower($db_plugin_name)) {
  353.                                 return $plugin;
  354.                         }
  355.                 }
  356.                 throw new OIDplusConfigInitializationException(_L('Database plugin "%1" not found',$db_plugin_name));
  357.         }
  358.  
  359.         private static $dbMainSession = null;
  360.         public static function db() {
  361.                 if (is_null(self::$dbMainSession)) {
  362.                         self::$dbMainSession = self::getActiveDatabasePlugin()->newConnection();
  363.                 }
  364.                 if (!self::$dbMainSession->isConnected()) self::$dbMainSession->connect();
  365.                 return self::$dbMainSession;
  366.         }
  367.  
  368.         private static $dbIsolatedSession = null;
  369.         public static function dbIsolated() {
  370.                 if (is_null(self::$dbIsolatedSession)) {
  371.                         self::$dbIsolatedSession = self::getActiveDatabasePlugin()->newConnection();
  372.                 }
  373.                 if (!self::$dbIsolatedSession->isConnected()) self::$dbIsolatedSession->connect();
  374.                 return self::$dbIsolatedSession;
  375.         }
  376.  
  377.         # --- CAPTCHA plugin
  378.  
  379.         private static function registerCaptchaPlugin(OIDplusCaptchaPlugin $plugin) {
  380.                 $name = $plugin::id();
  381.                 if ($name === '') return false;
  382.  
  383.                 if (isset(self::$captchaPlugins[$name])) {
  384.                         $plugintype_hf = _L('CAPTCHA');
  385.                         throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
  386.                 }
  387.  
  388.                 self::$captchaPlugins[$name] = $plugin;
  389.  
  390.                 return true;
  391.         }
  392.  
  393.         public static function getCaptchaPlugins() {
  394.                 return self::$captchaPlugins;
  395.         }
  396.  
  397.         public static function getActiveCaptchaPluginId() {
  398.                 $captcha_plugin_name = OIDplus::baseConfig()->getValue('CAPTCHA_PLUGIN', '');
  399.  
  400.                 if (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false) && ($captcha_plugin_name === '')) {
  401.                         // Legacy config file support!
  402.                         $captcha_plugin_name = 'reCAPTCHA';
  403.                 }
  404.  
  405.                 if ($captcha_plugin_name === '') $captcha_plugin_name = 'None'; // the "None" plugin is a must-have!
  406.  
  407.                 return $captcha_plugin_name;
  408.         }
  409.  
  410.         public static function getActiveCaptchaPlugin() {
  411.                 $captcha_plugin_name = OIDplus::getActiveCaptchaPluginId();
  412.                 foreach (self::$captchaPlugins as $name => $plugin) {
  413.                         if (strtolower($name) == strtolower($captcha_plugin_name)) {
  414.                                 return $plugin;
  415.                         }
  416.                 }
  417.                 throw new OIDplusConfigInitializationException(_L('CAPTCHA plugin "%1" not found',$captcha_plugin_name));
  418.         }
  419.  
  420.         # --- Page plugin
  421.  
  422.         private static function registerPagePlugin(OIDplusPagePlugin $plugin) {
  423.                 self::$pagePlugins[] = $plugin;
  424.  
  425.                 return true;
  426.         }
  427.  
  428.         public static function getPagePlugins() {
  429.                 return self::$pagePlugins;
  430.         }
  431.  
  432.         # --- Auth plugin
  433.  
  434.         private static function registerAuthPlugin(OIDplusAuthPlugin $plugin) {
  435.                 if (OIDplus::baseConfig()->getValue('DEBUG')) {
  436.                         $password = generateRandomString(25);
  437.  
  438.                         try {
  439.                                 $authInfo = $plugin->generate($password);
  440.                         } catch (OIDplusException $e) {
  441.                                 // This can happen when the AuthKey or Salt is too long
  442.                                 throw new OIDplusException(_L('Auth plugin "%1" is erroneous: %2',basename($plugin->getPluginDirectory()),$e->getMessage()));
  443.                         }
  444.                         $salt = $authInfo->getSalt();
  445.                         $authKey = $authInfo->getAuthKey();
  446.  
  447.                         $authInfo_SaltDiff = clone $authInfo;
  448.                         $authInfo_SaltDiff->setSalt(strrev($authInfo_SaltDiff->getSalt()));
  449.  
  450.                         $authInfo_AuthKeyDiff = clone $authInfo;
  451.                         $authInfo_AuthKeyDiff->setAuthKey(strrev($authInfo_AuthKeyDiff->getAuthKey()));
  452.  
  453.                         if ((!$plugin->verify($authInfo,$password)) ||
  454.                            (!empty($salt) && $plugin->verify($authInfo_SaltDiff,$password)) ||
  455.                            ($plugin->verify($authInfo_AuthKeyDiff,$password)) ||
  456.                            ($plugin->verify($authInfo,$password.'x'))) {
  457.                                 throw new OIDplusException(_L('Auth plugin "%1" is erroneous: Generate/Verify self test failed',basename($plugin->getPluginDirectory())));
  458.                         }
  459.                 }
  460.  
  461.                 self::$authPlugins[] = $plugin;
  462.                 return true;
  463.         }
  464.  
  465.         public static function getAuthPlugins() {
  466.                 return self::$authPlugins;
  467.         }
  468.  
  469.         # --- Language plugin
  470.  
  471.         private static function registerLanguagePlugin(OIDplusLanguagePlugin $plugin) {
  472.                 self::$languagePlugins[] = $plugin;
  473.                 return true;
  474.         }
  475.  
  476.         public static function getLanguagePlugins() {
  477.                 return self::$languagePlugins;
  478.         }
  479.  
  480.         # --- Design plugin
  481.  
  482.         private static function registerDesignPlugin(OIDplusDesignPlugin $plugin) {
  483.                 self::$designPlugins[] = $plugin;
  484.                 return true;
  485.         }
  486.  
  487.         public static function getDesignPlugins() {
  488.                 return self::$designPlugins;
  489.         }
  490.  
  491.         public static function getActiveDesignPlugin() {
  492.                 $plugins = OIDplus::getDesignPlugins();
  493.                 foreach ($plugins as $plugin) {
  494.                         if ((basename($plugin->getPluginDirectory())) == OIDplus::config()->getValue('design','default')) {
  495.                                 return $plugin;
  496.                         }
  497.                 }
  498.                 return null;
  499.         }
  500.  
  501.         # --- Logger plugin
  502.  
  503.         private static function registerLoggerPlugin(OIDplusLoggerPlugin $plugin) {
  504.                 self::$loggerPlugins[] = $plugin;
  505.                 return true;
  506.         }
  507.  
  508.         public static function getLoggerPlugins() {
  509.                 return self::$loggerPlugins;
  510.         }
  511.  
  512.         # --- Object type plugin
  513.  
  514.         private static function registerObjectTypePlugin(OIDplusObjectTypePlugin $plugin) {
  515.                 self::$objectTypePlugins[] = $plugin;
  516.  
  517.                 $ot = $plugin::getObjectTypeClassName();
  518.                 self::registerObjectType($ot);
  519.  
  520.                 return true;
  521.         }
  522.  
  523.         private static function registerObjectType($ot) {
  524.                 $ns = $ot::ns();
  525.                 if (empty($ns)) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Namespace must not be empty',$ot));
  526.  
  527.                 // Currently, we must enforce that namespaces in objectType plugins are lowercase, because prefilterQuery() makes all namespaces lowercase and the DBMS should be case-sensitive
  528.                 if ($ns != strtolower($ns)) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Namespace %2 must be lower-case',$ot,$ns));
  529.  
  530.                 $root = $ot::root();
  531.                 if (!str_starts_with($root,$ns.':')) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Root node (%2) is in wrong namespace (needs starts with %3)!',$ot,$root,$ns.':'));
  532.  
  533.                 $ns_found = false;
  534.                 foreach (array_merge(OIDplus::getEnabledObjectTypes(), OIDplus::getDisabledObjectTypes()) as $test_ot) {
  535.                         if ($test_ot::ns() == $ns) {
  536.                                 $ns_found = true;
  537.                                 break;
  538.                         }
  539.                 }
  540.                 if ($ns_found) {
  541.                         throw new OIDplusException(_L('Attention: Two objectType plugins use the same namespace "%1"!',$ns));
  542.                 }
  543.  
  544.                 $init = OIDplus::config()->getValue("objecttypes_initialized");
  545.                 $init_ary = empty($init) ? array() : explode(';', $init);
  546.                 $init_ary = array_map('trim', $init_ary);
  547.  
  548.                 $enabled = OIDplus::config()->getValue("objecttypes_enabled");
  549.                 $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
  550.                 $enabled_ary = array_map('trim', $enabled_ary);
  551.  
  552.                 $do_enable = false;
  553.                 if (in_array($ns, $enabled_ary)) {
  554.                         // If it is in the list of enabled object types, it is enabled (obviously)
  555.                         $do_enable = true;
  556.                 } else {
  557.                         if (!OIDplus::config()->getValue('oobe_objects_done')) {
  558.                                 // If the OOBE wizard is NOT done, then just enable the "oid" object type by default
  559.                                 $do_enable = $ns == 'oid';
  560.                         } else {
  561.                                 // If the OOBE wizard was done (once), then
  562.                                 // we will enable all object types which were never initialized
  563.                                 // (i.e. a plugin folder was freshly added)
  564.                                 $do_enable = !in_array($ns, $init_ary);
  565.                         }
  566.                 }
  567.  
  568.                 if ($do_enable) {
  569.                         self::$enabledObjectTypes[] = $ot;
  570.                         usort(self::$enabledObjectTypes, function($a, $b) {
  571.                                 $enabled = OIDplus::config()->getValue("objecttypes_enabled");
  572.                                 $enabled_ary = explode(';', $enabled);
  573.  
  574.                                 $idx_a = array_search($a::ns(), $enabled_ary);
  575.                                 $idx_b = array_search($b::ns(), $enabled_ary);
  576.  
  577.                                 if ($idx_a == $idx_b) {
  578.                                     return 0;
  579.                                 }
  580.                                 return ($idx_a > $idx_b) ? +1 : -1;
  581.                         });
  582.                 } else {
  583.                         self::$disabledObjectTypes[] = $ot;
  584.                 }
  585.  
  586.                 if (!in_array($ns, $init_ary)) {
  587.                         // Was never initialized before, so we add it to the list of enabled object types once
  588.  
  589.                         if ($do_enable) {
  590.                                 $enabled_ary[] = $ns;
  591.                                 // Important: Don't validate the input, because the other object types might not be initialized yet! So use setValueNoCallback() instead setValue().
  592.                                 OIDplus::config()->setValueNoCallback("objecttypes_enabled", implode(';', $enabled_ary));
  593.                         }
  594.  
  595.                         $init_ary[] = $ns;
  596.                         OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
  597.                 }
  598.         }
  599.  
  600.         public static function getObjectTypePlugins() {
  601.                 return self::$objectTypePlugins;
  602.         }
  603.  
  604.         public static function getObjectTypePluginsEnabled() {
  605.                 $res = array();
  606.                 foreach (self::$objectTypePlugins as $plugin) {
  607.                         $ot = $plugin::getObjectTypeClassName();
  608.                         if (in_array($ot, self::$enabledObjectTypes)) $res[] = $plugin;
  609.                 }
  610.                 return $res;
  611.         }
  612.  
  613.         public static function getObjectTypePluginsDisabled() {
  614.                 $res = array();
  615.                 foreach (self::$objectTypePlugins as $plugin) {
  616.                         $ot = $plugin::getObjectTypeClassName();
  617.                         if (in_array($ot, self::$disabledObjectTypes)) $res[] = $plugin;
  618.                 }
  619.                 return $res;
  620.         }
  621.  
  622.         public static function getEnabledObjectTypes() {
  623.                 return self::$enabledObjectTypes;
  624.         }
  625.  
  626.         public static function getDisabledObjectTypes() {
  627.                 return self::$disabledObjectTypes;
  628.         }
  629.  
  630.         # --- Plugin handling functions
  631.  
  632.         public static function getAllPlugins()/*: array*/ {
  633.                 $res = array();
  634.                 $res = array_merge($res, self::$pagePlugins);
  635.                 $res = array_merge($res, self::$authPlugins);
  636.                 $res = array_merge($res, self::$loggerPlugins);
  637.                 $res = array_merge($res, self::$objectTypePlugins);
  638.                 $res = array_merge($res, self::$dbPlugins);
  639.                 $res = array_merge($res, self::$captchaPlugins);
  640.                 $res = array_merge($res, self::$sqlSlangPlugins);
  641.                 $res = array_merge($res, self::$languagePlugins);
  642.                 $res = array_merge($res, self::$designPlugins);
  643.                 return $res;
  644.         }
  645.  
  646.         public static function getPluginByOid($oid)/*: ?OIDplusPlugin*/ {
  647.                 $plugins = self::getAllPlugins();
  648.                 foreach ($plugins as $plugin) {
  649.                         if (oid_dotnotation_equal($plugin->getManifest()->getOid(), $oid)) {
  650.                                 return $plugin;
  651.                         }
  652.                 }
  653.                 return null;
  654.         }
  655.  
  656.         public static function getPluginByClassName($classname)/*: ?OIDplusPlugin*/ {
  657.                 $plugins = self::getAllPlugins();
  658.                 foreach ($plugins as $plugin) {
  659.                         if (get_class($plugin) === $classname) {
  660.                                 return $plugin;
  661.                         }
  662.                 }
  663.                 return null;
  664.         }
  665.  
  666.         /**
  667.         * @return array<OIDplusPluginManifest>|array<string,array<string,OIDplusPluginManifest>>
  668.         */
  669.         public static function getAllPluginManifests($pluginFolderMasks='*', $flat=true): array {
  670.                 $out = array();
  671.                 // Note: glob() will sort by default, so we do not need a page priority attribute.
  672.                 //       So you just need to use a numeric plugin directory prefix (padded).
  673.                 $ary = array();
  674.                 foreach (explode(',',$pluginFolderMasks) as $pluginFolderMask) {
  675.                         $ary = array_merge($ary,glob(OIDplus::localpath().'plugins/'.'*'.'/'.$pluginFolderMask.'/'.'*'.'/manifest.xml'));
  676.                 }
  677.  
  678.                 // Sort the plugins by their type and name, as if they would be in a single vendor-folder!
  679.                 uasort($ary, function($a,$b) {
  680.                         if ($a == $b) return 0;
  681.  
  682.                         $ary = explode('/',$a);
  683.                         $bry = explode('/',$b);
  684.  
  685.                         // First sort by type (publicPage, auth, database, language, ...)
  686.                         $a_type = $ary[count($ary)-1-2];
  687.                         $b_type = $bry[count($bry)-1-2];
  688.                         if ($a_type < $b_type) return -1;
  689.                         if ($a_type > $b_type) return 1;
  690.  
  691.                         // Then sort by name (090_login, 100_whois, etc.)
  692.                         $a_name = $ary[count($ary)-1-1];
  693.                         $b_name = $bry[count($bry)-1-1];
  694.                         if ($a_name < $b_name) return -1;
  695.                         if ($a_name > $b_name) return 1;
  696.  
  697.                         // If it is still equal, then finally sort by vendorname
  698.                         $a_vendor = $ary[count($ary)-1-3];
  699.                         $b_vendor = $bry[count($bry)-1-3];
  700.                         if ($a_vendor < $b_vendor) return -1;
  701.                         if ($a_vendor > $b_vendor) return 1;
  702.                         return 0;
  703.                 });
  704.  
  705.                 foreach ($ary as $ini) {
  706.                         if (!file_exists($ini)) continue;
  707.  
  708.                         $manifest = new OIDplusPluginManifest();
  709.                         $manifest->loadManifest($ini);
  710.  
  711.                         $class_name = $manifest->getPhpMainClass();
  712.                         if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
  713.                                 continue;
  714.                         }
  715.  
  716.                         if ($flat) {
  717.                                 $out[] = $manifest;
  718.                         } else {
  719.                                 $plugintype_folder = basename(dirname(dirname($ini)));
  720.                                 $pluginname_folder = basename(dirname($ini));
  721.  
  722.                                 if (!isset($out[$plugintype_folder])) $out[$plugintype_folder] = array();
  723.                                 if (!isset($out[$plugintype_folder][$pluginname_folder])) $out[$plugintype_folder][$pluginname_folder] = array();
  724.                                 $out[$plugintype_folder][$pluginname_folder] = $manifest;
  725.                         }
  726.                 }
  727.                 return $out;
  728.         }
  729.  
  730.         /**
  731.         * @return array<string>
  732.         */
  733.         public static function registerAllPlugins($pluginDirName, $expectedPluginClass, $registerCallback): array {
  734.                 $out = array();
  735.                 if (is_array($pluginDirName)) {
  736.                         $ary = array();
  737.                         foreach ($pluginDirName as $pluginDirName_) {
  738.                                 $ary = array_merge($ary, self::getAllPluginManifests($pluginDirName_, false));
  739.                         }
  740.                 } else {
  741.                         $ary = self::getAllPluginManifests($pluginDirName, false);
  742.                 }
  743.                 $known_plugin_oids = array();
  744.                 if (OIDplus::baseConfig()->getValue('DEBUG')) {
  745.                         $fake_feature = uuid_to_oid(gen_uuid());
  746.                 } else {
  747.                         $fake_feature = null;
  748.                 }
  749.                 foreach ($ary as $plugintype_folder => $bry) {
  750.                         foreach ($bry as $pluginname_folder => $manifest) {
  751.                                 $class_name = $manifest->getPhpMainClass();
  752.  
  753.                                 // Before we load the plugin, we want to make some checks to confirm
  754.                                 // that the plugin is working correctly.
  755.  
  756.                                 if (!$class_name) {
  757.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Manifest does not declare a PHP main class'));
  758.                                 }
  759.                                 if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
  760.                                         continue;
  761.                                 }
  762.                                 if (!class_exists($class_name)) {
  763.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Manifest declares PHP main class as "%1", but it could not be found',$class_name));
  764.                                 }
  765.                                 if (!is_subclass_of($class_name, $expectedPluginClass)) {
  766.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Plugin main class "%1" is expected to be a subclass of "%2"',$class_name,$expectedPluginClass));
  767.                                 }
  768.                                 if (($class_name!=$manifest->getTypeClass()) && (!is_subclass_of($class_name,$manifest->getTypeClass()))) {
  769.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Plugin main class "%1" is expected to be a subclass of "%2", according to type declared in manifest',$class_name,$manifest->getTypeClass()));
  770.                                 }
  771.                                 if (($manifest->getTypeClass()!=$expectedPluginClass) && (!is_subclass_of($manifest->getTypeClass(),$expectedPluginClass))) {
  772.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Class declared in manifest is "%1" does not fit expected class for this plugin type "%2"',$manifest->getTypeClass(),$expectedPluginClass));
  773.                                 }
  774.  
  775.                                 $plugin_oid = $manifest->getOid();
  776.                                 if (!$plugin_oid) {
  777.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Does not have an OID'));
  778.                                 }
  779.                                 if (!oid_valid_dotnotation($plugin_oid, false, false, 2)) {
  780.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Plugin OID "%1" is invalid (needs to be valid dot-notation)',$plugin_oid));
  781.                                 }
  782.                                 if (isset($known_plugin_oids[$plugin_oid])) {
  783.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('The OID "%1" is already used by the plugin "%2"',$plugin_oid,$known_plugin_oids[$plugin_oid]));
  784.                                 }
  785.  
  786.                                 $full_plugin_dir = dirname($manifest->getManifestFile());
  787.                                 $full_plugin_dir = substr($full_plugin_dir, strlen(OIDplus::localpath()));
  788.  
  789.                                 $dir_is_viathinksoft = str_starts_with($full_plugin_dir, 'plugins/viathinksoft/') || str_starts_with($full_plugin_dir, 'plugins\\viathinksoft\\');
  790.                                 $oid_is_viathinksoft = str_starts_with($plugin_oid, '1.3.6.1.4.1.37476.2.5.2.4.'); // { iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) 37476 products(2) oidplus(5) v2(2) plugins(4) }
  791.                                 if ($dir_is_viathinksoft != $oid_is_viathinksoft) {
  792.                                         throw new OIDplusException(_L('Plugin "%1/%2" is misplaced',$plugintype_folder,$pluginname_folder).': '._L('The plugin is in the wrong folder. The folder %1 can only be used by official ViaThinkSoft plugins','plugins/viathinksoft/'));
  793.                                 }
  794.  
  795.                                 $known_plugin_oids[$plugin_oid] = $plugintype_folder.'/'.$pluginname_folder;
  796.  
  797.                                 $obj = new $class_name();
  798.  
  799.                                 if (OIDplus::baseConfig()->getValue('DEBUG')) {
  800.                                         if ($obj->implementsFeature($fake_feature)) {
  801.                                                 // see https://devblogs.microsoft.com/oldnewthing/20040211-00/?p=40663
  802.                                                 throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('implementsFeature() always returns true'));
  803.                                         }
  804.                                 }
  805.  
  806.                                 // TODO: Maybe as additional plugin-test, we should also check if plugins are allowed to define CSS/JS, i.e. the plugin type is element of OIDplus::INTERACTIVE_PLUGIN_TYPES
  807.                                 $tmp = $manifest->getManifestLinkedFiles();
  808.                                 foreach ($tmp as $file) {
  809.                                         if (!file_exists($file)) {
  810.                                                 throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('File %1 was defined in manifest, but it is not existing',$file));
  811.                                         }
  812.                                 }
  813.  
  814.                                 // Now we can continue
  815.  
  816.                                 $out[] = $class_name;
  817.                                 if (!is_null($registerCallback)) {
  818.                                         call_user_func($registerCallback, $obj);
  819.  
  820.                                         // Alternative approaches:
  821.                                         //$registerCallback[0]::{$registerCallback[1]}($obj);
  822.                                         // or:
  823.                                         //forward_static_call($registerCallback, $obj);
  824.                                 }
  825.                         }
  826.  
  827.                 }
  828.                 return $out;
  829.         }
  830.  
  831.         # --- Initialization of OIDplus
  832.  
  833.         public static function init($html=true, $keepBaseConfig=true) {
  834.                 self::$html = $html;
  835.  
  836.                 // Reset internal state, so we can re-init verything if required
  837.  
  838.                 if (self::$old_config_format) {
  839.                         // We need to do this, because define() cannot be undone
  840.                         // Note: This can only happen in very special cases (e.g. test cases) where you call init() twice
  841.                         throw new OIDplusConfigInitializationException(_L('A full re-initialization is not possible if a version 2.0 config file (containing "defines") is used. Please update to a config 2.1 file by running setup again.'));
  842.                 }
  843.  
  844.                 self::$config = null;
  845.                 if (!$keepBaseConfig) self::$baseConfig = null;  // for test cases we need to be able to control base config and setting values manually, so $keepBaseConfig needs to be true
  846.                 self::$gui = null;
  847.                 self::$authUtils = null;
  848.                 self::$mailUtils = null;
  849.                 self::$menuUtils = null;
  850.                 self::$logger = null;
  851.                 self::$dbMainSession = null;
  852.                 self::$dbIsolatedSession = null;
  853.                 self::$pagePlugins = array();
  854.                 self::$authPlugins = array();
  855.                 self::$loggerPlugins = array();
  856.                 self::$objectTypePlugins = array();
  857.                 self::$enabledObjectTypes = array();
  858.                 self::$disabledObjectTypes = array();
  859.                 self::$dbPlugins = array();
  860.                 self::$captchaPlugins = array();
  861.                 self::$sqlSlangPlugins = array();
  862.                 self::$languagePlugins = array();
  863.                 self::$designPlugins = array();
  864.                 self::$system_id_cache = null;
  865.                 self::$sslAvailableCache = null;
  866.                 self::$translationArray = array();
  867.  
  868.                 // Continue...
  869.  
  870.                 OIDplus::baseConfig(); // this loads the base configuration located in userdata/baseconfig/config.inc.php (once!)
  871.                                        // You can do changes to the configuration afterwards using OIDplus::baseConfig()->...
  872.  
  873.                 // Register database types (highest priority)
  874.  
  875.                 // SQL slangs
  876.  
  877.                 self::registerAllPlugins('sqlSlang', 'OIDplusSqlSlangPlugin', array('OIDplus','registerSqlSlangPlugin'));
  878.                 foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
  879.                         $plugin->init($html);
  880.                 }
  881.  
  882.                 // Database providers
  883.  
  884.                 self::registerAllPlugins('database', 'OIDplusDatabasePlugin', array('OIDplus','registerDatabasePlugin'));
  885.                 foreach (OIDplus::getDatabasePlugins() as $plugin) {
  886.                         $plugin->init($html);
  887.                 }
  888.  
  889.                 // Do redirect stuff etc.
  890.  
  891.                 self::isSslAvailable(); // This function does automatic redirects
  892.  
  893.                 // Construct the configuration manager
  894.  
  895.                 OIDplus::config(); // During the construction, various system settings are prepared if required
  896.  
  897.                 // Initialize public / private keys
  898.  
  899.                 OIDplus::getPkiStatus(true);
  900.  
  901.                 // Register non-DB plugins
  902.  
  903.                 self::registerAllPlugins(array('publicPages', 'raPages', 'adminPages'), 'OIDplusPagePlugin', array('OIDplus','registerPagePlugin'));
  904.                 self::registerAllPlugins('auth', 'OIDplusAuthPlugin', array('OIDplus','registerAuthPlugin'));
  905.                 self::registerAllPlugins('logger', 'OIDplusLoggerPlugin', array('OIDplus','registerLoggerPlugin'));
  906.                 OIDplusLogger::reLogMissing(); // Some previous plugins might have tried to log. Repeat that now.
  907.                 self::registerAllPlugins('objectTypes', 'OIDplusObjectTypePlugin', array('OIDplus','registerObjectTypePlugin'));
  908.                 self::registerAllPlugins('language', 'OIDplusLanguagePlugin', array('OIDplus','registerLanguagePlugin'));
  909.                 self::registerAllPlugins('design', 'OIDplusDesignPlugin', array('OIDplus','registerDesignPlugin'));
  910.                 self::registerAllPlugins('captcha', 'OIDplusCaptchaPlugin', array('OIDplus','registerCaptchaPlugin'));
  911.  
  912.                 // Initialize non-DB plugins
  913.  
  914.                 foreach (OIDplus::getPagePlugins() as $plugin) {
  915.                         $plugin->init($html);
  916.                 }
  917.                 foreach (OIDplus::getAuthPlugins() as $plugin) {
  918.                         $plugin->init($html);
  919.                 }
  920.                 foreach (OIDplus::getLoggerPlugins() as $plugin) {
  921.                         $plugin->init($html);
  922.                 }
  923.                 foreach (OIDplus::getObjectTypePlugins() as $plugin) {
  924.                         $plugin->init($html);
  925.                 }
  926.                 foreach (OIDplus::getLanguagePlugins() as $plugin) {
  927.                         $plugin->init($html);
  928.                 }
  929.                 foreach (OIDplus::getDesignPlugins() as $plugin) {
  930.                         $plugin->init($html);
  931.                 }
  932.                 foreach (OIDplus::getCaptchaPlugins() as $plugin) {
  933.                         $plugin->init($html);
  934.                 }
  935.  
  936.                 if (PHP_SAPI != 'cli') {
  937.  
  938.                         // Prepare some security related response headers (default values)
  939.  
  940.                         $content_language =
  941.                                 strtolower(substr(OIDplus::getCurrentLang(),0,2)) . '-' .
  942.                                 strtoupper(substr(OIDplus::getCurrentLang(),2,2)); // e.g. 'en-US'
  943.  
  944.                         $http_headers = array(
  945.                                 "X-Content-Type-Options" => "nosniff",
  946.                                 "X-XSS-Protection" => "1; mode=block",
  947.                                 "X-Frame-Options" => "SAMEORIGIN",
  948.                                 "Referrer-Policy" => array(
  949.                                         "no-referrer-when-downgrade"
  950.                                 ),
  951.                                 "Cache-Control" => array(
  952.                                         "no-cache",
  953.                                         "no-store",
  954.                                         "must-revalidate"
  955.                                 ),
  956.                                 "Pragma" => "no-cache",
  957.                                 "Content-Language" => $content_language,
  958.                                 "Expires" => "0",
  959.                                 "Content-Security-Policy" => array(
  960.                                         // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
  961.  
  962.                                         // --- Fetch directives ---
  963.                                         "child-src" => array(
  964.                                                 "'self'",
  965.                                                 "blob:"
  966.                                         ),
  967.                                         "connect-src" => array(
  968.                                                 "'self'",
  969.                                                 "blob:"
  970.                                         ),
  971.                                         "default-src" => array(
  972.                                                 "'self'",
  973.                                                 "blob:",
  974.                                                 "https://cdnjs.cloudflare.com/"
  975.                                         ),
  976.                                         "font-src" => array(
  977.                                                 "'self'",
  978.                                                 "blob:"
  979.                                         ),
  980.                                         "frame-src" => array(
  981.                                                 "'self'",
  982.                                                 "blob:"
  983.                                         ),
  984.                                         "img-src" => array(
  985.                                                 "blob:",
  986.                                                 "data:",
  987.                                                 "http:",
  988.                                                 "https:"
  989.                                         ),
  990.                                         "manifest-src" => array(
  991.                                                 "'self'",
  992.                                                 "blob:"
  993.                                         ),
  994.                                         "media-src" => array(
  995.                                                 "'self'",
  996.                                                 "blob:"
  997.                                         ),
  998.                                         "object-src" => array(
  999.                                                 "'none'"
  1000.                                         ),
  1001.                                         "prefetch-src" => array(
  1002.                                                 "'self'",
  1003.                                                 "blob:"
  1004.                                         ),
  1005.                                         "script-src" => array(
  1006.                                                 "'self'",
  1007.                                                 "'unsafe-inline'",
  1008.                                                 "'unsafe-eval'",
  1009.                                                 "blob:",
  1010.                                                 "https://cdnjs.cloudflare.com/",
  1011.                                                 "https://polyfill.io/"
  1012.                                         ),
  1013.                                         // script-src-elem not used
  1014.                                         // script-src-attr not used
  1015.                                         "style-src" => array(
  1016.                                                 "'self'",
  1017.                                                 "'unsafe-inline'",
  1018.                                                 "https://cdnjs.cloudflare.com/"
  1019.                                         ),
  1020.                                         // style-src-elem not used
  1021.                                         // style-src-attr not used
  1022.                                         "worker-src" => array(
  1023.                                                 "'self'",
  1024.                                                 "blob:"
  1025.                                         ),
  1026.  
  1027.                                         // --- Navigation directives ---
  1028.                                         "frame-ancestors" => array(
  1029.                                                "'none'"
  1030.                                         ),
  1031.                                 )
  1032.                         );
  1033.  
  1034.                         // Give plugins the opportunity to manipulate/extend the headers
  1035.  
  1036.                         foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
  1037.                                 $plugin->httpHeaderCheck($http_headers);
  1038.                         }
  1039.                         //foreach (OIDplus::getDatabasePlugins() as $plugin) {
  1040.                         if ($plugin = OIDplus::getActiveDatabasePlugin()) {
  1041.                                 $plugin->httpHeaderCheck($http_headers);
  1042.                         }
  1043.                         foreach (OIDplus::getPagePlugins() as $plugin) {
  1044.                                 $plugin->httpHeaderCheck($http_headers);
  1045.                         }
  1046.                         foreach (OIDplus::getAuthPlugins() as $plugin) {
  1047.                                 $plugin->httpHeaderCheck($http_headers);
  1048.                         }
  1049.                         foreach (OIDplus::getLoggerPlugins() as $plugin) {
  1050.                                 $plugin->httpHeaderCheck($http_headers);
  1051.                         }
  1052.                         foreach (OIDplus::getObjectTypePlugins() as $plugin) {
  1053.                                 $plugin->httpHeaderCheck($http_headers);
  1054.                         }
  1055.                         foreach (OIDplus::getLanguagePlugins() as $plugin) {
  1056.                                 $plugin->httpHeaderCheck($http_headers);
  1057.                         }
  1058.                         foreach (OIDplus::getDesignPlugins() as $plugin) {
  1059.                                 $plugin->httpHeaderCheck($http_headers);
  1060.                         }
  1061.                         //foreach (OIDplus::getCaptchaPlugins() as $plugin) {
  1062.                         if ($plugin = OIDplus::getActiveCaptchaPlugin()) {
  1063.                                 $plugin->httpHeaderCheck($http_headers);
  1064.                         }
  1065.  
  1066.                         // Prepare to send the headers to the client
  1067.                         // The headers are sent automatically when the first output comes or the script ends
  1068.  
  1069.                         foreach ($http_headers as $name => $val) {
  1070.  
  1071.                                 // Plugins can remove standard OIDplus headers by setting the value to null.
  1072.                                 if (is_null($val)) continue; /** @phpstan-ignore-line */
  1073.  
  1074.                                 // Some headers can be written as arrays to make it easier for plugin authors
  1075.                                 // to manipulate/extend the contents.
  1076.                                 if (is_array($val)) {
  1077.                                         if ((strtolower($name) == 'cache-control') ||
  1078.                                             (strtolower($name) == 'referrer-policy'))
  1079.                                         {
  1080.                                                 if (count($val) == 0) continue;
  1081.                                                 $val = implode(', ', $val);
  1082.                                         } else if (strtolower($name) == 'content-security-policy') {
  1083.                                                 if (count($val) == 0) continue;
  1084.                                                 foreach ($val as $tmp1 => &$tmp2) {
  1085.                                                         $tmp2 = array_unique($tmp2);
  1086.                                                         $tmp2 = $tmp1.' '.implode(' ', $tmp2);
  1087.                                                 }
  1088.                                                 $val = implode('; ', $val);
  1089.                                         } else {
  1090.                                                 throw new OIDplusException(_L('HTTP header "%1" cannot be written as array. A newly installed plugin is probably misusing the method "%2".',$name,'httpHeaderCheck'));
  1091.                                         }
  1092.                                 }
  1093.  
  1094.                                 if (is_string($val)) {
  1095.                                         header("$name: $val");
  1096.                                 }
  1097.                         }
  1098.  
  1099.                 } // endif (PHP_SAPI != 'cli')
  1100.  
  1101.                 // Initialize other stuff (i.e. things which require the logger!)
  1102.  
  1103.                 OIDplus::recognizeSystemUrl(); // Make sure "last_known_system_url" is set
  1104.                 OIDplus::recognizeVersion(); // Make sure "last_known_version" is set and a log entry is created
  1105.         }
  1106.  
  1107.         # --- System URL, System ID, PKI, and other functions
  1108.  
  1109.         private static function recognizeSystemUrl() {
  1110.                 try {
  1111.                         $url = OIDplus::webpath(null,self::PATH_ABSOLUTE_CANONICAL); // TODO: canonical or not?
  1112.                         OIDplus::config()->setValue('last_known_system_url', $url);
  1113.                 } catch (Exception $e) {
  1114.                 }
  1115.         }
  1116.  
  1117.         private static function getExecutingScriptPathDepth() {
  1118.                 if (PHP_SAPI == 'cli') {
  1119.                         global $argv;
  1120.                         $test_dir = dirname(realpath($argv[0]));
  1121.                 } else {
  1122.                         if (!isset($_SERVER["SCRIPT_FILENAME"])) return false;
  1123.                         $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
  1124.                 }
  1125.                 $test_dir = str_replace('\\', '/', $test_dir);
  1126.                 $steps_up = 0;
  1127.                 while (!file_exists($test_dir.'/oidplus.min.css.php')) { // We just assume that only the OIDplus base directory contains "oidplus.min.css.php" and not any subordinate directory!
  1128.                         $test_dir = dirname($test_dir);
  1129.                         $steps_up++;
  1130.                         if ($steps_up == 1000) return false; // to make sure there will never be an infinite loop
  1131.                 }
  1132.                 return $steps_up;
  1133.         }
  1134.  
  1135.         public static function isSSL() {
  1136.                 return isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
  1137.         }
  1138.  
  1139.         /**
  1140.          * Returns the URL of the system.
  1141.          * @param int $mode If true or OIDplus::PATH_RELATIVE, the returning path is relative to the currently executed
  1142.          *                  PHP script (i.e. index.php , not the plugin PHP script!). False or OIDplus::PATH_ABSOLUTE is
  1143.          *                  results in an absolute URL. OIDplus::PATH_ABSOLUTE_CANONICAL is an absolute URL,
  1144.          *                  but a canonical path (set by base config setting CANONICAL_SYSTEM_URL) is preferred.
  1145.          * @return string|false The URL, with guaranteed trailing path delimiter for directories
  1146.          */
  1147.         private static function getSystemUrl($mode) {
  1148.                 if ($mode === self::PATH_RELATIVE) {
  1149.                         $steps_up = self::getExecutingScriptPathDepth();
  1150.                         if ($steps_up === false) {
  1151.                                 return false;
  1152.                         } else {
  1153.                                 return str_repeat('../', $steps_up);
  1154.                         }
  1155.                 } else {
  1156.                         if ($mode === self::PATH_ABSOLUTE_CANONICAL) {
  1157.                                 $tmp = OIDplus::baseConfig()->getValue('CANONICAL_SYSTEM_URL', '');
  1158.                                 if ($tmp) {
  1159.                                         return rtrim($tmp,'/').'/';
  1160.                                 }
  1161.                         }
  1162.  
  1163.                         if (PHP_SAPI == 'cli') {
  1164.                                 try {
  1165.                                         return OIDplus::config()->getValue('last_known_system_url', false);
  1166.                                 } catch (Exception $e) {
  1167.                                         return false;
  1168.                                 }
  1169.                         } else {
  1170.                                 // First, try to find out how many levels we need to go up
  1171.                                 $steps_up = self::getExecutingScriptPathDepth();
  1172.  
  1173.                                 // Then go up these amount of levels, based on SCRIPT_NAME/argv[0]
  1174.                                 $res = dirname($_SERVER['SCRIPT_NAME'].'index.php'); // This fake 'index.php' ensures that SCRIPT_NAME does not end with '/', which would make dirname() fail
  1175.                                 for ($i=0; $i<$steps_up; $i++) {
  1176.                                         $res = dirname($res);
  1177.                                 }
  1178.                                 $res = str_replace('\\', '/', $res);
  1179.                                 if ($res == '/') $res = '';
  1180.  
  1181.                                 // Add protocol and hostname
  1182.                                 $is_ssl = self::isSSL();
  1183.                                 $protocol = $is_ssl ? 'https' : 'http'; // do not translate
  1184.                                 $host = $_SERVER['HTTP_HOST']; // includes port if it is not 80/443
  1185.  
  1186.                                 return $protocol.'://'.$host.$res.'/';
  1187.                         }
  1188.                 }
  1189.         }
  1190.  
  1191.         private static function getSystemIdFromPubKey($pubKey) {
  1192.                 $m = array();
  1193.                 if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
  1194.                         return smallhash(base64_decode($m[1]));
  1195.                 }
  1196.                 return false;
  1197.         }
  1198.  
  1199.         private static $system_id_cache = null;
  1200.         public static function getSystemId($oid=false) {
  1201.                 if (!is_null(self::$system_id_cache)) {
  1202.                         $out = self::$system_id_cache;
  1203.                 } else {
  1204.                         $out = false;
  1205.  
  1206.                         if (self::getPkiStatus(true)) {
  1207.                                 $pubKey = OIDplus::getSystemPublicKey();
  1208.                                 $out = self::getSystemIdFromPubKey($pubKey);
  1209.                         }
  1210.                         self::$system_id_cache = $out;
  1211.                 }
  1212.                 if (!$out) return false;
  1213.                 return ($oid ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
  1214.         }
  1215.  
  1216.         public static function getOpenSslCnf() {
  1217.                 // The following functions need a config file, otherway they don't work
  1218.                 // - openssl_csr_new
  1219.                 // - openssl_csr_sign
  1220.                 // - openssl_pkey_export
  1221.                 // - openssl_pkey_export_to_file
  1222.                 // - openssl_pkey_new
  1223.                 $tmp = @getenv('OPENSSL_CONF');
  1224.                 if ($tmp && file_exists($tmp)) return $tmp;
  1225.  
  1226.                 // OpenSSL in XAMPP does not work OOBE, since the OPENSSL_CONF is
  1227.                 // C:/xampp/apache/bin/openssl.cnf and not C:/xampp/apache/conf/openssl.cnf
  1228.                 // Bug reports are more than 10 years old and nobody cares...
  1229.                 // Use our own config file
  1230.                 return __DIR__.'/../../vendor/phpseclib/phpseclib/phpseclib/openssl.cnf';
  1231.         }
  1232.  
  1233.         private static function getPrivKeyPassphraseFilename() {
  1234.                 return OIDplus::localpath() . 'userdata/privkey_secret.php';
  1235.         }
  1236.  
  1237.         private static function tryCreatePrivKeyPassphrase() {
  1238.                 $file = self::getPrivKeyPassphraseFilename();
  1239.  
  1240.                 $passphrase = generateRandomString(64);
  1241.                 $cont = "<?php\n";
  1242.                 $cont .= "// ATTENTION! This file was automatically generated by OIDplus to encrypt the private key\n";
  1243.                 $cont .= "// that is located in your database configuration table. DO NOT ALTER OR DELETE THIS FILE,\n";
  1244.                 $cont .= "// otherwise you will lose your OIDplus System-ID and all services connected with it!\n";
  1245.                 $cont .= "// If multiple systems access the same database, then this file must be synchronous\n";
  1246.                 $cont .= "// between all systems, otherwise you will lose your system ID, too!\n";
  1247.                 $cont .= "\$passphrase = '$passphrase';\n";
  1248.                 $cont .= "// End of file\n";
  1249.  
  1250.                 @file_put_contents($file, $cont);
  1251.         }
  1252.  
  1253.         private static function getPrivKeyPassphrase() {
  1254.                 $file = self::getPrivKeyPassphraseFilename();
  1255.                 if (!file_exists($file)) return false;
  1256.                 $cont = file_get_contents($file);
  1257.                 $m = array();
  1258.                 if (!preg_match("@'(.+)'@isU", $cont, $m)) return false;
  1259.                 return $m[1];
  1260.         }
  1261.  
  1262.         public static function getSystemPrivateKey() {
  1263.                 $privKey = OIDplus::config()->getValue('oidplus_private_key');
  1264.                 if ($privKey == '') return false;
  1265.  
  1266.                 $passphrase = self::getPrivKeyPassphrase();
  1267.                 if ($passphrase !== false) {
  1268.                         $privKey = decrypt_private_key($privKey, $passphrase);
  1269.                 }
  1270.  
  1271.                 if (is_privatekey_encrypted($privKey)) {
  1272.                         // This can happen if the key file has vanished
  1273.                         return false;
  1274.                 }
  1275.  
  1276.                 return $privKey;
  1277.         }
  1278.  
  1279.         public static function getSystemPublicKey() {
  1280.                 $pubKey = OIDplus::config()->getValue('oidplus_public_key');
  1281.                 if ($pubKey == '') return false;
  1282.                 return $pubKey;
  1283.         }
  1284.  
  1285.         public static function getPkiStatus($try_generate=false) {
  1286.                 if (!function_exists('openssl_pkey_new')) return false;
  1287.  
  1288.                 if ($try_generate) {
  1289.                         // For debug purposes: Invalidate current key once:
  1290.                         //OIDplus::config()->setValue('oidplus_private_key', '');
  1291.  
  1292.                         $privKey = OIDplus::getSystemPrivateKey();
  1293.                         $pubKey = OIDplus::getSystemPublicKey();
  1294.                         if (!verify_private_public_key($privKey, $pubKey)) {
  1295.                                 if ($pubKey) {
  1296.                                         OIDplus::logger()->log("[WARN]A!", "The private/public key-pair is broken. A new key-pair will now be generated for your system. Your System-ID will change.");
  1297.                                 }
  1298.  
  1299.                                 $pkey_config = array(
  1300.                                     "digest_alg" => "sha512",
  1301.                                     "private_key_bits" => defined('OPENSSL_SUPPLEMENT') ? 1024 : 2048, // openssl_supplement.inc.php is based on phpseclib, which is very slow. So we use 1024 bits instead of 2048 bits
  1302.                                     "private_key_type" => OPENSSL_KEYTYPE_RSA,
  1303.                                     "config" => OIDplus::getOpenSslCnf()
  1304.                                 );
  1305.  
  1306.                                 // Create the private and public key
  1307.                                 $res = openssl_pkey_new($pkey_config);
  1308.                                 if ($res === false) return false;
  1309.  
  1310.                                 // Extract the private key from $res to $privKey
  1311.                                 if (openssl_pkey_export($res, $privKey, null, $pkey_config) === false) return false;
  1312.  
  1313.                                 // Extract the public key from $res to $pubKey
  1314.                                 $tmp = openssl_pkey_get_details($res);
  1315.                                 if ($tmp === false) return false;
  1316.                                 $pubKey = $tmp["key"];
  1317.  
  1318.                                 // encrypt new keys using a passphrase stored in a secret file
  1319.                                 self::tryCreatePrivKeyPassphrase(); // *try* (re)generate this file
  1320.                                 $passphrase = self::getPrivKeyPassphrase();
  1321.                                 if ($passphrase !== false) {
  1322.                                         $privKey = encrypt_private_key($privKey, $passphrase);
  1323.                                 }
  1324.  
  1325.                                 // Calculate the system ID from the public key
  1326.                                 $system_id = self::getSystemIdFromPubKey($pubKey);
  1327.                                 if ($system_id !== false) {
  1328.                                         // Save the key pair to database
  1329.                                         OIDplus::config()->setValue('oidplus_private_key', $privKey);
  1330.                                         OIDplus::config()->setValue('oidplus_public_key', $pubKey);
  1331.  
  1332.                                         // Log the new system ID
  1333.                                         OIDplus::logger()->log("[INFO]A!", "A new private/public key-pair for your system had been generated. Your SystemID is now $system_id");
  1334.                                 }
  1335.                         } else {
  1336.                                 $passphrase = self::getPrivKeyPassphrase();
  1337.                                 $rawPrivKey = OIDplus::config()->getValue('oidplus_private_key');
  1338.                                 if (($passphrase === false) || !is_privatekey_encrypted($rawPrivKey)) {
  1339.                                         // Upgrade to new encrypted keys
  1340.                                         self::tryCreatePrivKeyPassphrase(); // *try* generate this file
  1341.                                         $passphrase = self::getPrivKeyPassphrase();
  1342.                                         if ($passphrase !== false) {
  1343.                                                 $privKey = encrypt_private_key($privKey, $passphrase);
  1344.                                                 OIDplus::logger()->log("[INFO]A!", "The private/public key-pair has been upgraded to an encrypted key-pair. The key is saved in ".self::getPrivKeyPassphraseFilename());
  1345.                                                 OIDplus::config()->setValue('oidplus_private_key', $privKey);
  1346.                                         }
  1347.                                 }
  1348.                         }
  1349.                 }
  1350.  
  1351.                 $privKey = OIDplus::getSystemPrivateKey();
  1352.                 $pubKey = OIDplus::getSystemPublicKey();
  1353.                 return verify_private_public_key($privKey, $pubKey);
  1354.         }
  1355.  
  1356.         public static function getInstallType() {
  1357.                 $counter = 0;
  1358.  
  1359.                 if ($new_version_file_exists = file_exists(OIDplus::localpath().'.version.php')) {
  1360.                         $counter++;
  1361.                 }
  1362.                 if ($old_version_file_exists = file_exists(OIDplus::localpath().'oidplus_version.txt')) {
  1363.                         $counter++;
  1364.                 }
  1365.                 $version_file_exists = $old_version_file_exists | $new_version_file_exists;
  1366.                 if ($svn_dir_exists = (is_dir(OIDplus::localpath().'.svn') ||
  1367.                                        is_dir(OIDplus::localpath().'../.svn'))) { // in case we checked out the root instead of the "trunk"
  1368.                         $counter++;
  1369.                 }
  1370.                 // if ($git_dir_exists = is_dir(OIDplus::localpath().'.git')) {
  1371.                 if ($git_dir_exists = (OIDplus::findGitFolder() !== false)) {
  1372.                         $counter++;
  1373.                 }
  1374.  
  1375.                 if ($counter === 0) {
  1376.                         return 'unknown'; // do not translate
  1377.                 }
  1378.                 else if ($counter > 1) {
  1379.                         return 'ambigous'; // do not translate
  1380.                 }
  1381.                 else if ($svn_dir_exists) {
  1382.                         return 'svn-wc'; // do not translate
  1383.                 }
  1384.                 else if ($git_dir_exists) {
  1385.                         return 'git-wc'; // do not translate
  1386.                 }
  1387.                 else if ($version_file_exists) {
  1388.                         return 'svn-snapshot'; // do not translate
  1389.                 }
  1390.         }
  1391.  
  1392.         private static function recognizeVersion() {
  1393.                 try {
  1394.                         $ver_prev = OIDplus::config()->getValue("last_known_version");
  1395.                         $ver_now = OIDplus::getVersion();
  1396.                         if (($ver_now != '') && ($ver_prev != '') && ($ver_now != $ver_prev)) {
  1397.                                 // TODO: Problem: When the system was updated using SVN, then the IP address of the next random visitor of the website is logged!
  1398.                                 OIDplus::logger()->log("[INFO]A!", "System version changed from '$ver_prev' to '$ver_now'");
  1399.  
  1400.                                 // Just to be sure, recanonize objects (we don't do it at every page visit due to performance reasons)
  1401.                                 self::recanonizeObjects();
  1402.                         }
  1403.                         OIDplus::config()->setValue("last_known_version", $ver_now);
  1404.                 } catch (Exception $e) {
  1405.                 }
  1406.         }
  1407.  
  1408.         public static function getVersion() {
  1409.                 static $cachedVersion = null;
  1410.                 if (!is_null($cachedVersion)) {
  1411.                         return $cachedVersion;
  1412.                 }
  1413.  
  1414.                 $installType = OIDplus::getInstallType();
  1415.  
  1416.                 if ($installType === 'svn-wc') {
  1417.                         $ver = get_svn_revision(OIDplus::localpath());
  1418.                         if ($ver)
  1419.                                 return ($cachedVersion = 'svn-'.$ver);
  1420.                         $ver = get_svn_revision(OIDplus::localpath().'../'); // in case we checked out the root instead of the "trunk"
  1421.                         if ($ver)
  1422.                                 return ($cachedVersion = 'svn-'.$ver);
  1423.                 }
  1424.  
  1425.                 if ($installType === 'git-wc') {
  1426.                         $ver = OIDplus::getGitsvnRevision(OIDplus::localpath());
  1427.                         if ($ver)
  1428.                                 return ($cachedVersion = 'svn-'.$ver);
  1429.                 }
  1430.  
  1431.                 if ($installType === 'svn-snapshot') {
  1432.                         $cont = '';
  1433.                         if (file_exists($filename = OIDplus::localpath().'oidplus_version.txt'))
  1434.                                 $cont = file_get_contents($filename);
  1435.                         if (file_exists($filename = OIDplus::localpath().'.version.php'))
  1436.                                 $cont = file_get_contents($filename);
  1437.                         $m = array();
  1438.                         if (preg_match('@Revision (\d+)@', $cont, $m)) // do not translate
  1439.                                 return ($cachedVersion = 'svn-'.$m[1]); // do not translate
  1440.                 }
  1441.  
  1442.                 return ($cachedVersion = false); // version ambigous or unknown
  1443.         }
  1444.  
  1445.         const ENFORCE_SSL_NO   = 0;
  1446.         const ENFORCE_SSL_YES  = 1;
  1447.         const ENFORCE_SSL_AUTO = 2;
  1448.         private static $sslAvailableCache = null;
  1449.         public static function isSslAvailable() {
  1450.                 if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
  1451.  
  1452.                 if (PHP_SAPI == 'cli') {
  1453.                         self::$sslAvailableCache = false;
  1454.                         return false;
  1455.                 }
  1456.  
  1457.                 $timeout = 2;
  1458.                 $already_ssl = self::isSSL();
  1459.                 $ssl_port = 443;
  1460.  
  1461.                 if ($already_ssl) {
  1462.                         OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, false, null, true/*forceInsecure*/);
  1463.                         self::$sslAvailableCache = true;
  1464.                         return true;
  1465.                 } else {
  1466.                         if (isset($_COOKIE['SSL_CHECK']) && ($_COOKIE['SSL_CHECK'] == '1')) {
  1467.                                 // The cookie "SSL_CHECK" is set once a website was loaded with HTTPS.
  1468.                                 // It forces subsequent HTTP calls to redirect to HTTPS (like HSTS).
  1469.                                 // The reason is the following problem:
  1470.                                 // If you open the page with HTTPS first, then the CSRF token cookies will get the "secure" flag
  1471.                                 // If you open the page then with HTTP, the HTTP cannot access the secure CSRF cookies,
  1472.                                 // Chrome will then block "Set-Cookie" since the HTTP cookie would overwrite the HTTPS cookie.
  1473.                                 // Note: SSL_CHECK is NOT a replacement for HSTS! You should use HSTS,
  1474.                                 // because on there your browser ensures that HTTPS is called, before the server
  1475.                                 // is even contacted (and therefore, no HTTP connection can be hacked).
  1476.                                 $mode = OIDplus::ENFORCE_SSL_YES;
  1477.                         } else {
  1478.                                 $mode = OIDplus::baseConfig()->getValue('ENFORCE_SSL', OIDplus::ENFORCE_SSL_AUTO);
  1479.                         }
  1480.  
  1481.                         if ($mode == OIDplus::ENFORCE_SSL_NO) {
  1482.                                 // No SSL available
  1483.                                 self::$sslAvailableCache = false;
  1484.                                 return false;
  1485.                         } else if ($mode == OIDplus::ENFORCE_SSL_YES) {
  1486.                                 // Force SSL
  1487.                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  1488.                                 header('Location:'.$location);
  1489.                                 die(_L('Redirecting to HTTPS...'));
  1490.                         } else if ($mode == OIDplus::ENFORCE_SSL_AUTO) {
  1491.                                 // Automatic SSL detection
  1492.                                 if (isset($_COOKIE['SSL_CHECK'])) {
  1493.                                         // We already had the HTTPS detection done before.
  1494.                                         if ($_COOKIE['SSL_CHECK'] == '1') {
  1495.                                                 // HTTPS was detected before, but we are HTTP. Redirect now
  1496.                                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  1497.                                                 header('Location:'.$location);
  1498.                                                 die(_L('Redirecting to HTTPS...'));
  1499.                                         } else {
  1500.                                                 // No HTTPS available. Do nothing.
  1501.                                                 self::$sslAvailableCache = false;
  1502.                                                 return false;
  1503.                                         }
  1504.                                 } else {
  1505.                                         // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
  1506.                                         $errno = -1;
  1507.                                         $errstr = '';
  1508.                                         if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
  1509.                                                 // HTTPS detected. Redirect now, and remember that we had detected HTTPS
  1510.                                                 OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, false, null, true/*forceInsecure*/);
  1511.                                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  1512.                                                 header('Location:'.$location);
  1513.                                                 die(_L('Redirecting to HTTPS...'));
  1514.                                         } else {
  1515.                                                 // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
  1516.                                                 OIDplus::cookieUtils()->setcookie('SSL_CHECK', '0', 0, false, null, true/*forceInsecure*/);
  1517.                                                 self::$sslAvailableCache = false;
  1518.                                                 return false;
  1519.                                         }
  1520.                                 }
  1521.                         }
  1522.                 }
  1523.         }
  1524.  
  1525.         /**
  1526.          * Gets a local path pointing to a resource
  1527.          * @param string $target Target resource (file or directory must exist), or null to get the OIDplus base directory
  1528.          * @param boolean $relative If true, the returning path is relative to the currently executed PHP file (not the CLI working directory)
  1529.          * @return string|false The local path, with guaranteed trailing path delimiter for directories
  1530.          */
  1531.         public static function localpath($target=null, $relative=false) {
  1532.                 if (is_null($target)) {
  1533.                         $target = __DIR__.'/../../';
  1534.                 }
  1535.  
  1536.                 if ($relative) {
  1537.                         // First, try to find out how many levels we need to go up
  1538.                         $steps_up = self::getExecutingScriptPathDepth();
  1539.                         if ($steps_up === false) return false;
  1540.  
  1541.                         // Virtually go back from the executing PHP script to the OIDplus base path
  1542.                         $res = str_repeat('../',$steps_up);
  1543.  
  1544.                         // Then go to the desired location
  1545.                         $basedir = realpath(__DIR__.'/../../');
  1546.                         $target = realpath($target);
  1547.                         if ($target === false) return false;
  1548.                         $res .= substr($target, strlen($basedir)+1);
  1549.                         $res = rtrim($res,'/'); // avoid '..//' for localpath(null,true)
  1550.                 } else {
  1551.                         $res = realpath($target);
  1552.                 }
  1553.  
  1554.                 if (is_dir($target)) $res .= '/';
  1555.  
  1556.                 $res = str_replace('/', DIRECTORY_SEPARATOR, $res);
  1557.  
  1558.                 return $res;
  1559.         }
  1560.  
  1561.         /**
  1562.          * Gets a URL pointing to a resource
  1563.          * @param string $target Target resource (file or directory must exist), or null to get the OIDplus base directory
  1564.          * @param int|boolean $mode If true or OIDplus::PATH_RELATIVE, the returning path is relative to the currently executed
  1565.          *                          PHP script (i.e. index.php , not the plugin PHP script!). False or OIDplus::PATH_ABSOLUTE is
  1566.          *                          results in an absolute URL. OIDplus::PATH_ABSOLUTE_CANONICAL is an absolute URL,
  1567.          *                          but a canonical path (set by base config setting CANONICAL_SYSTEM_URL) is preferred.
  1568.          * @return string|false The URL, with guaranteed trailing path delimiter for directories
  1569.          */
  1570.         public static function webpath($target=null, $mode=self::PATH_ABSOLUTE_CANONICAL) {
  1571.                 // backwards compatibility
  1572.                 if ($mode === true) $mode = self::PATH_RELATIVE;
  1573.                 if ($mode === false) $mode = self::PATH_ABSOLUTE;
  1574.  
  1575.                 if ($mode == OIDplus::PATH_RELATIVE_TO_ROOT) {
  1576.                         $tmp = OIDplus::webpath($target,OIDplus::PATH_ABSOLUTE);
  1577.                         if ($tmp === false) return false;
  1578.                         $tmp = parse_url($tmp);
  1579.                         if ($tmp === false) return false;
  1580.                         if (!isset($tmp['path'])) return false;
  1581.                         return $tmp['path'];
  1582.                 }
  1583.  
  1584.                 if ($mode == OIDplus::PATH_RELATIVE_TO_ROOT_CANONICAL) {
  1585.                         $tmp = OIDplus::webpath($target,OIDplus::PATH_ABSOLUTE_CANONICAL);
  1586.                         if ($tmp === false) return false;
  1587.                         $tmp = parse_url($tmp);
  1588.                         if ($tmp === false) return false;
  1589.                         if (!isset($tmp['path'])) return false;
  1590.                         return $tmp['path'];
  1591.                 }
  1592.  
  1593.                 $res = self::getSystemUrl($mode); // Note: already contains a trailing path delimiter
  1594.                 if ($res === false) return false;
  1595.  
  1596.                 if (!is_null($target)) {
  1597.                         $basedir = realpath(__DIR__.'/../../');
  1598.                         $target = realpath($target);
  1599.                         if ($target === false) return false;
  1600.                         $tmp = substr($target, strlen($basedir)+1);
  1601.                         $res .= str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
  1602.                         if (is_dir($target)) $res .= '/';
  1603.                 }
  1604.  
  1605.                 return $res;
  1606.         }
  1607.  
  1608.         public static function canonicalURL() {
  1609.                 // First part: OIDplus system URL (or canonical system URL)
  1610.                 $sysurl = OIDplus::getSystemUrl(self::PATH_ABSOLUTE_CANONICAL);
  1611.  
  1612.                 // Second part: Directory
  1613.                 $basedir = realpath(__DIR__.'/../../');
  1614.                 $target = realpath('.');
  1615.                 if ($target === false) return false;
  1616.                 $tmp = substr($target, strlen($basedir)+1);
  1617.                 $res = str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
  1618.                 if (is_dir($target) && ($res != '')) $res .= '/';
  1619.  
  1620.                 // Third part: File name
  1621.                 $tmp = explode('/',$_SERVER['SCRIPT_NAME']);
  1622.                 $tmp = end($tmp);
  1623.  
  1624.                 // Fourth part: Query string (ordered)
  1625.                 $tmp2 = getSortedQuery();
  1626.                 if ($tmp2 != '') $tmp2 = '?'.$tmp2;
  1627.  
  1628.                 return $sysurl.$res.$tmp.$tmp2;
  1629.         }
  1630.  
  1631.         private static $shutdown_functions = array();
  1632.         public static function register_shutdown_function($func) {
  1633.                 self::$shutdown_functions[] = $func;
  1634.         }
  1635.  
  1636.         public static function invoke_shutdown() {
  1637.                 foreach (self::$shutdown_functions as $func) {
  1638.                         $func();
  1639.                 }
  1640.         }
  1641.  
  1642.         public static function getAvailableLangs() {
  1643.                 $langs = array();
  1644.                 foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
  1645.                         $code = $pluginManifest->getLanguageCode();
  1646.                         $langs[] = $code;
  1647.                 }
  1648.                 return $langs;
  1649.         }
  1650.  
  1651.         public static function getCurrentLang() {
  1652.                 if (isset($_GET['lang'])) {
  1653.                         $lang = $_GET['lang'];
  1654.                 } else if (isset($_POST['lang'])) {
  1655.                         $lang = $_POST['lang'];
  1656.                 } else if (isset($_COOKIE['LANGUAGE'])) {
  1657.                         $lang = $_COOKIE['LANGUAGE'];
  1658.                 } else {
  1659.                         $lang = self::DEFAULT_LANGUAGE;
  1660.                 }
  1661.                 $lang = substr(preg_replace('@[^a-z]@ismU', '', $lang),0,4); // sanitize
  1662.                 return $lang;
  1663.         }
  1664.  
  1665.         public static function handleLangArgument() {
  1666.                 if (isset($_GET['lang'])) {
  1667.                         // The "?lang=" argument is only for NoScript-Browsers/SearchEngines
  1668.                         // In case someone who has JavaScript clicks a ?lang= link, they should get
  1669.                         // the page in that language, but the cookie must be set, otherwise
  1670.                         // the menu and other stuff would be in their cookie-based-language and not the
  1671.                         // argument-based-language.
  1672.                         OIDplus::cookieUtils()->setcookie('LANGUAGE', $_GET['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
  1673.                 } else if (isset($_POST['lang'])) {
  1674.                         OIDplus::cookieUtils()->setcookie('LANGUAGE', $_POST['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
  1675.                 }
  1676.         }
  1677.  
  1678.         private static $translationArray = array();
  1679.         protected static function getTranslationFileContents($translation_file) {
  1680.                 // First, try the cache
  1681.                 $cache_file = __DIR__ . '/../../userdata/cache/translation_'.md5($translation_file).'.ser';
  1682.                 if (file_exists($cache_file) && (filemtime($cache_file) == filemtime($translation_file))) {
  1683.                         $cac = @unserialize(file_get_contents($cache_file));
  1684.                         if ($cac) return $cac;
  1685.                 }
  1686.  
  1687.                 // If not successful, then load the XML file
  1688.                 $xml = @simplexml_load_string(file_get_contents($translation_file));
  1689.                 if (!$xml) return array(); // if there is an UTF-8 or parsing error, don't output any errors, otherwise the JavaScript is corrupt and the page won't render correctly
  1690.                 $cac = array();
  1691.                 foreach ($xml->message as $msg) {
  1692.                         $src = trim($msg->source->__toString());
  1693.                         $dst = trim($msg->target->__toString());
  1694.                         $cac[$src] = $dst;
  1695.                 }
  1696.                 @file_put_contents($cache_file,serialize($cac));
  1697.                 @touch($cache_file,filemtime($translation_file));
  1698.                 return $cac;
  1699.         }
  1700.         public static function getTranslationArray($requested_lang='*') {
  1701.                 foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
  1702.                         $lang = $pluginManifest->getLanguageCode();
  1703.                         if (strpos($lang,'/') !== false) continue; // just to be sure
  1704.                         if (strpos($lang,'\\') !== false) continue; // just to be sure
  1705.                         if (strpos($lang,'..') !== false) continue; // just to be sure
  1706.  
  1707.                         if (($requested_lang != '*') && ($lang != $requested_lang)) continue;
  1708.  
  1709.                         if (!isset(self::$translationArray[$lang])) {
  1710.                                 self::$translationArray[$lang] = array();
  1711.  
  1712.                                 $wildcard = $pluginManifest->getLanguageMessages();
  1713.                                 if (strpos($wildcard,'/') !== false) continue; // just to be sure
  1714.                                 if (strpos($wildcard,'\\') !== false) continue; // just to be sure
  1715.                                 if (strpos($wildcard,'..') !== false) continue; // just to be sure
  1716.  
  1717.                                 $translation_files = glob(__DIR__.'/../../plugins/'.'*'.'/language/'.$lang.'/'.$wildcard);
  1718.                                 sort($translation_files);
  1719.                                 foreach ($translation_files as $translation_file) {
  1720.                                         if (!file_exists($translation_file)) continue;
  1721.                                         $cac = self::getTranslationFileContents($translation_file);
  1722.                                         foreach ($cac as $src => $dst) {
  1723.                                                 self::$translationArray[$lang][$src] = $dst;
  1724.                                         }
  1725.                                 }
  1726.                         }
  1727.                 }
  1728.                 return self::$translationArray;
  1729.         }
  1730.  
  1731.         public static function getEditionInfo() {
  1732.                 return @parse_ini_file(__DIR__.'/../edition.ini', true)['Edition'];
  1733.         }
  1734.  
  1735.         public static function findGitFolder() {
  1736.                 // Git command line saves git information in folder ".git"
  1737.                 // Plesk git saves git information in folder "../../../git/oidplus/" (or similar)
  1738.                 $dir = OIDplus::localpath();
  1739.                 if (is_dir($dir.'/.git')) return $dir.'/.git';
  1740.                 $i = 0;
  1741.                 do {
  1742.                         if (is_dir($dir.'/git')) {
  1743.                                 $confs = @glob($dir.'/git/'.'*'.'/config');
  1744.                                 if ($confs) foreach ($confs as $conf) {
  1745.                                         $cont = file_get_contents($conf);
  1746.                                         if (isset(OIDplus::getEditionInfo()['gitrepo']) && (OIDplus::getEditionInfo()['gitrepo'] != '') && (strpos($cont, OIDplus::getEditionInfo()['gitrepo']) !== false)) {
  1747.                                                 return dirname($conf);
  1748.                                         }
  1749.                                 }
  1750.                         }
  1751.                         $i++;
  1752.                 } while (($i<100) && ($dir != ($new_dir = @realpath($dir.'/../'))) && ($dir = $new_dir));
  1753.                 return false;
  1754.         }
  1755.  
  1756.         public static function getGitsvnRevision($dir='') {
  1757.                 try {
  1758.                         // tries command line and binary parsing
  1759.                         // requires vendor/danielmarschall/git_utils.inc.php
  1760.                         $git_dir = OIDplus::findGitFolder();
  1761.                         if ($git_dir === false) return false;
  1762.                         $commit_msg = git_get_latest_commit_message($git_dir);
  1763.                 } catch (Exception $e) {
  1764.                         return false;
  1765.                 }
  1766.  
  1767.                 $m = array();
  1768.                 if (preg_match('%git-svn-id: (.+)@(\\d+) %ismU', $commit_msg, $m)) {
  1769.                         return $m[2];
  1770.                 } else {
  1771.                         return false;
  1772.                 }
  1773.         }
  1774.  
  1775.         public static function prefilterQuery($static_node_id, $throw_exception) {
  1776.                 // Let namespace be case-insensitive
  1777.                 $ary = explode(':', $static_node_id, 2);
  1778.                 $ary[0] = strtolower($ary[0]);
  1779.                 $static_node_id = implode(':', $ary);
  1780.  
  1781.                 // Ask plugins if they want to change the node id
  1782.                 foreach (OIDplus::getObjectTypePluginsEnabled() as $plugin) {
  1783.                         $static_node_id = $plugin->prefilterQuery($static_node_id, $throw_exception);
  1784.                 }
  1785.  
  1786.                 return $static_node_id;
  1787.         }
  1788.  
  1789.         public static function isCronjob() {
  1790.                 return explode('.',basename($_SERVER['SCRIPT_NAME']))[0] === 'cron';
  1791.         }
  1792.  
  1793.         private static function recanonizeObjects() {
  1794.                 #
  1795.                 # Since OIDplus svn-184, entries in the database need to have a canonical ID
  1796.                 # If the ID is not canonical (e.g. GUIDs missing hyphens), the object cannot be opened in OIDplus
  1797.                 # This script re-canonizes the object IDs if required.
  1798.                 # In SVN Rev 856, the canonization for GUID, IPv4 and IPv6 have changed, requiring another
  1799.                 # re-canonization
  1800.                 #
  1801.                 $res = OIDplus::db()->query("select id from ###objects");
  1802.                 while ($row = $res->fetch_array()) {
  1803.                         $ida = $row['id'];
  1804.                         $obj = OIDplusObject::parse($ida);
  1805.                         if (!$obj) continue;
  1806.                         $idb = $obj->nodeId();
  1807.                         if (($idb) && ($ida != $idb)) {
  1808.                                 OIDplus::db()->transaction_begin();
  1809.                                 OIDplus::db()->query("update ###objects set id = ? where id = ?", array($idb, $ida));
  1810.                                 OIDplus::db()->query("update ###asn1id set oid = ? where oid = ?", array($idb, $ida));
  1811.                                 OIDplus::db()->query("update ###iri set oid = ? where oid = ?", array($idb, $ida));
  1812.                                 OIDplus::db()->query("update ###log_object set id = ? where id = ?", array($idb, $ida));
  1813.                                 OIDplus::logger()->log("[INFO]A!", "Object name '$ida' has been changed to '$idb' during re-canonization");
  1814.                                 OIDplus::db()->transaction_commit();
  1815.                                 OIDplusObject::resetObjectInformationCache();
  1816.                         }
  1817.                 }
  1818.         }
  1819.  
  1820. }
  1821.