Subversion Repositories oidplus

Rev

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