Subversion Repositories oidplus

Rev

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