Subversion Repositories oidplus

Rev

Rev 702 | Rev 719 | 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 - 2021 Daniel Marschall, ViaThinkSoft
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *     http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  */
  19.  
  20. if (!defined('INSIDE_OIDPLUS')) die();
  21.  
  22. class OIDplus {
  23.         private static /*OIDplusPagePlugin[]*/ $pagePlugins = array();
  24.         private static /*OIDplusAuthPlugin[]*/ $authPlugins = array();
  25.         private static /*OIDplusLoggerPlugin[]*/ $loggerPlugins = array();
  26.         private static /*OIDplusObjectTypePlugin[]*/ $objectTypePlugins = array();
  27.         private static /*string[]*/ $enabledObjectTypes = array();
  28.         private static /*string[]*/ $disabledObjectTypes = array();
  29.         private static /*OIDplusDatabasePlugin[]*/ $dbPlugins = array();
  30.         private static /*OIDplusCaptchaPlugin[]*/ $captchaPlugins = array();
  31.         private static /*OIDplusSqlSlangPlugin[]*/ $sqlSlangPlugins = array();
  32.         private static /*OIDplusLanguagePlugin[]*/ $languagePlugins = array();
  33.         private static /*OIDplusDesignPlugin[]*/ $designPlugins = array();
  34.  
  35.         protected static $html = true;
  36.  
  37.         /*public*/ const DEFAULT_LANGUAGE = 'enus'; // the language of the source code
  38.  
  39.         private function __construct() {
  40.         }
  41.  
  42.         # --- Static classes
  43.  
  44.         private static $baseConfig = null;
  45.         private static $old_config_format = false;
  46.         public static function baseConfig() {
  47.                 $first_init = false;
  48.  
  49.                 if ($first_init = is_null(self::$baseConfig)) {
  50.                         self::$baseConfig = new OIDplusBaseConfig();
  51.                 }
  52.  
  53.                 if ($first_init) {
  54.                         // Include a file containing various size/depth limitations of OIDs
  55.                         // It is important to include it before userdata/baseconfig/config.inc.php was included,
  56.                         // so we can give userdata/baseconfig/config.inc.php the chance to override the values.
  57.  
  58.                         include OIDplus::localpath().'includes/oidplus_limits.inc.php';
  59.  
  60.                         // Include config file
  61.  
  62.                         $config_file = OIDplus::localpath() . 'userdata/baseconfig/config.inc.php';
  63.                         $config_file_old = OIDplus::localpath() . 'includes/config.inc.php'; // backwards compatibility
  64.  
  65.                         if (!file_exists($config_file) && file_exists($config_file_old)) {
  66.                                 $config_file = $config_file_old;
  67.                         }
  68.  
  69.                         if (file_exists($config_file)) {
  70.                                 if (self::$old_config_format) {
  71.                                         // Note: We may only include it once due to backwards compatibility,
  72.                                         //       since in version 2.0, the configuration was defined using define() statements
  73.                                         // Attention: This does mean that a full re-init (e.g. for test cases) is not possible
  74.                                         //            if a version 2.0 config is used!
  75.                                         include_once $config_file;
  76.                                 } else {
  77.                                         include $config_file;
  78.                                 }
  79.  
  80.                                 if (defined('OIDPLUS_CONFIG_VERSION') && (OIDPLUS_CONFIG_VERSION == 2.0)) {
  81.                                         self::$old_config_format = true;
  82.  
  83.                                         // Backwards compatibility 2.0 => 2.1
  84.                                         foreach (get_defined_constants(true)['user'] as $name => $value) {
  85.                                                 $name = str_replace('OIDPLUS_', '', $name);
  86.                                                 if ($name == 'SESSION_SECRET') $name = 'SERVER_SECRET';
  87.                                                 if ($name == 'MYSQL_QUERYLOG') $name = 'QUERY_LOGFILE';
  88.                                                 if (($name == 'MYSQL_PASSWORD') || ($name == 'ODBC_PASSWORD') || ($name == 'PDO_PASSWORD') || ($name == 'PGSQL_PASSWORD')) {
  89.                                                         self::$baseConfig->setValue($name, base64_decode($value));
  90.                                                 } else {
  91.                                                         if ($name == 'CONFIG_VERSION') $value = 2.1;
  92.                                                         self::$baseConfig->setValue($name, $value);
  93.                                                 }
  94.                                         }
  95.                                 }
  96.                         } else {
  97.                                 if (!is_dir(OIDplus::localpath().'setup')) {
  98.                                         throw new OIDplusConfigInitializationException(_L('File %1 is missing, but setup can\'t be started because its directory missing.','userdata/baseconfig/config.inc.php'));
  99.                                 } else {
  100.                                         if (self::$html) {
  101.                                                 if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,true).'setup/') !== 0) {
  102.                                                         header('Location:'.OIDplus::webpath().'setup/');
  103.                                                         die(_L('Redirecting to setup...'));
  104.                                                 } else {
  105.                                                         return self::$baseConfig;
  106.                                                 }
  107.                                         } else {
  108.                                                 // This can be displayed in e.g. ajax.php
  109.                                                 throw new OIDplusConfigInitializationException(_L('File %1 is missing. Please run setup again.','userdata/baseconfig/config.inc.php'));
  110.                                         }
  111.                                 }
  112.                         }
  113.  
  114.                         // Check important config settings
  115.  
  116.                         if (self::$baseConfig->getValue('CONFIG_VERSION') != 2.1) {
  117.                                 if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,true).'setup/') !== 0) {
  118.                                         throw new OIDplusConfigInitializationException(_L("The information located in %1 is outdated.",realpath($config_file)));
  119.                                 }
  120.                         }
  121.  
  122.                         if (self::$baseConfig->getValue('SERVER_SECRET', '') === '') {
  123.                                 if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,true).'setup/') !== 0) {
  124.                                         throw new OIDplusConfigInitializationException(_L("You must set a value for SERVER_SECRET in %1 for the system to operate secure.",realpath($config_file)));
  125.                                 }
  126.                         }
  127.                 }
  128.  
  129.                 return self::$baseConfig;
  130.         }
  131.  
  132.         private static $config = null;
  133.         public static function config() {
  134.                 if ($first_init = is_null(self::$config)) {
  135.                         self::$config = new OIDplusConfig();
  136.                 }
  137.  
  138.                 if ($first_init) {
  139.                         // These are important settings for base functionalities and therefore are not inside plugins
  140.                         self::$config->prepareConfigKey('system_title', 'What is the name of your RA?', 'OIDplus 2.0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  141.                                 if (empty($value)) {
  142.                                         throw new OIDplusException(_L('Please enter a value for the system title.'));
  143.                                 }
  144.                         });
  145.                         self::$config->prepareConfigKey('admin_email', 'E-Mail address of the system administrator', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  146.                                 if (!empty($value) && !OIDplus::mailUtils()->validMailAddress($value)) {
  147.                                         throw new OIDplusException(_L('This is not a correct email address'));
  148.                                 }
  149.                         });
  150.                         self::$config->prepareConfigKey('global_cc', 'Global CC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
  151.                                 if (!empty($value) && !OIDplus::mailUtils()->validMailAddress($value)) {
  152.                                         throw new OIDplusException(_L('This is not a correct email address'));
  153.                                 }
  154.                         });
  155.                         self::$config->prepareConfigKey('objecttypes_initialized', 'List of object type plugins that were initialized once', '', OIDplusConfig::PROTECTION_READONLY, function($value) {
  156.                                 // Nothing here yet
  157.                         });
  158.                         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) {
  159.                                 # 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?
  160.  
  161.                                 $ary = explode(';',$value);
  162.                                 $uniq_ary = array_unique($ary);
  163.  
  164.                                 if (count($ary) != count($uniq_ary)) {
  165.                                         throw new OIDplusException(_L('Please check your input. Some object types are double.'));
  166.                                 }
  167.  
  168.                                 foreach ($ary as $ot_check) {
  169.                                         $ns_found = false;
  170.                                         foreach (OIDplus::getEnabledObjectTypes() as $ot) {
  171.                                                 if ($ot::ns() == $ot_check) {
  172.                                                         $ns_found = true;
  173.                                                         break;
  174.                                                 }
  175.                                         }
  176.                                         foreach (OIDplus::getDisabledObjectTypes() as $ot) {
  177.                                                 if ($ot::ns() == $ot_check) {
  178.                                                         $ns_found = true;
  179.                                                         break;
  180.                                                 }
  181.                                         }
  182.                                         if (!$ns_found) {
  183.                                                 throw new OIDplusException(_L('Please check your input. Namespace "%1" is not found',$ot_check));
  184.                                         }
  185.                                 }
  186.                         });
  187.                         self::$config->prepareConfigKey('oidplus_private_key', 'Private key for this system', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
  188.                                 // Nothing here yet
  189.                         });
  190.                         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) {
  191.                                 // Nothing here yet
  192.                         });
  193.                         self::$config->prepareConfigKey('last_known_system_url', 'Last known System URL', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
  194.                                 // Nothing here yet
  195.                         });
  196.                         self::$config->prepareConfigKey('last_known_version', 'Last known OIDplus Version', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
  197.                                 // Nothing here yet
  198.                         });
  199.                         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) {
  200.                                 $good = true;
  201.                                 if (strpos($value,'/') !== false) $good = false;
  202.                                 if (strpos($value,'\\') !== false) $good = false;
  203.                                 if (strpos($value,'..') !== false) $good = false;
  204.                                 if (!$good) {
  205.                                         throw new OIDplusException(_L('Invalid auth plugin folder name. Do only enter a folder name, not an absolute or relative path'));
  206.                                 }
  207.  
  208.                                 if (!rec_is_dir(OIDplus::localpath().'plugins/'.'*'.'/auth/'.$value)) {
  209.                                         throw new OIDplusException(_L('The auth plugin "%1" does not exist in plugin directory %2',$value,'plugins/[vendorname]/auth/'));
  210.                                 }
  211.                         });
  212.                 }
  213.  
  214.                 return self::$config;
  215.         }
  216.  
  217.         private static $gui = null;
  218.         public static function gui() {
  219.                 if (is_null(self::$gui)) {
  220.                         self::$gui = new OIDplusGui();
  221.                 }
  222.                 return self::$gui;
  223.         }
  224.  
  225.         private static $authUtils = null;
  226.         public static function authUtils() {
  227.                 if (is_null(self::$authUtils)) {
  228.                         self::$authUtils = new OIDplusAuthUtils();
  229.                 }
  230.                 return self::$authUtils;
  231.         }
  232.  
  233.         private static $mailUtils = null;
  234.         public static function mailUtils() {
  235.                 if (is_null(self::$mailUtils)) {
  236.                         self::$mailUtils = new OIDplusMailUtils();
  237.                 }
  238.                 return self::$mailUtils;
  239.         }
  240.  
  241.         private static $cookieUtils = null;
  242.         public static function cookieUtils() {
  243.                 if (is_null(self::$cookieUtils)) {
  244.                         self::$cookieUtils = new OIDplusCookieUtils();
  245.                 }
  246.                 return self::$cookieUtils;
  247.         }
  248.  
  249.         private static $menuUtils = null;
  250.         public static function menuUtils() {
  251.                 if (is_null(self::$menuUtils)) {
  252.                         self::$menuUtils = new OIDplusMenuUtils();
  253.                 }
  254.                 return self::$menuUtils;
  255.         }
  256.  
  257.         private static $logger = null;
  258.         public static function logger() {
  259.                 if (is_null(self::$logger)) {
  260.                         self::$logger = new OIDplusLogger();
  261.                 }
  262.                 return self::$logger;
  263.         }
  264.  
  265.         # --- SQL slang plugin
  266.  
  267.         private static function registerSqlSlangPlugin(OIDplusSqlSlangPlugin $plugin) {
  268.                 $name = $plugin::id();
  269.                 if ($name === '') return false;
  270.  
  271.                 if (isset(self::$sqlSlangPlugins[$name])) {
  272.                         $plugintype_hf = _L('SQL slang');
  273.                         throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
  274.                 }
  275.  
  276.                 self::$sqlSlangPlugins[$name] = $plugin;
  277.  
  278.                 return true;
  279.         }
  280.  
  281.         public static function getSqlSlangPlugins() {
  282.                 return self::$sqlSlangPlugins;
  283.         }
  284.  
  285.         public static function getSqlSlangPlugin($id)/*: ?OIDplusSqlSlangPlugin*/ {
  286.                 if (isset(self::$sqlSlangPlugins[$id])) {
  287.                         return self::$sqlSlangPlugins[$id];
  288.                 } else {
  289.                         return null;
  290.                 }
  291.         }
  292.  
  293.         # --- Database plugin
  294.  
  295.         private static function registerDatabasePlugin(OIDplusDatabasePlugin $plugin) {
  296.                 $name = $plugin::id();
  297.                 if ($name === '') return false;
  298.  
  299.                 if (isset(self::$dbPlugins[$name])) {
  300.                         $plugintype_hf = _L('Database');
  301.                         throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
  302.                 }
  303.  
  304.                 self::$dbPlugins[$name] = $plugin;
  305.  
  306.                 return true;
  307.         }
  308.  
  309.         public static function getDatabasePlugins() {
  310.                 return self::$dbPlugins;
  311.         }
  312.  
  313.         public static function getActiveDatabasePlugin() {
  314.                 $db_plugin_name = OIDplus::baseConfig()->getValue('DATABASE_PLUGIN','');
  315.                 if ($db_plugin_name === '') {
  316.                         throw new OIDplusConfigInitializationException(_L('No database plugin selected in config file'));
  317.                 }
  318.                 if (!isset(self::$dbPlugins[$db_plugin_name])) {
  319.                         throw new OIDplusConfigInitializationException(_L('Database plugin "%1" not found',$db_plugin_name));
  320.                 }
  321.                 return self::$dbPlugins[$db_plugin_name];
  322.         }
  323.  
  324.         private static $dbMainSession = null;
  325.         public static function db() {
  326.                 if (is_null(self::$dbMainSession)) {
  327.                         self::$dbMainSession = self::getActiveDatabasePlugin()->newConnection();
  328.                 }
  329.                 if (!self::$dbMainSession->isConnected()) self::$dbMainSession->connect();
  330.                 return self::$dbMainSession;
  331.         }
  332.  
  333.         private static $dbIsolatedSession = null;
  334.         public static function dbIsolated() {
  335.                 if (is_null(self::$dbIsolatedSession)) {
  336.                         self::$dbIsolatedSession = self::getActiveDatabasePlugin()->newConnection();
  337.                 }
  338.                 if (!self::$dbIsolatedSession->isConnected()) self::$dbIsolatedSession->connect();
  339.                 return self::$dbIsolatedSession;
  340.         }
  341.  
  342.         # --- CAPTCHA plugin
  343.  
  344.         private static function registerCaptchaPlugin(OIDplusCaptchaPlugin $plugin) {
  345.                 $name = $plugin::id();
  346.                 if ($name === '') return false;
  347.  
  348.                 if (isset(self::$captchaPlugins[$name])) {
  349.                         $plugintype_hf = _L('CAPTCHA');
  350.                         throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
  351.                 }
  352.  
  353.                 self::$captchaPlugins[$name] = $plugin;
  354.  
  355.                 return true;
  356.         }
  357.  
  358.         public static function getCaptchaPlugins() {
  359.                 return self::$captchaPlugins;
  360.         }
  361.  
  362.         public static function getActiveCaptchaPluginId() {
  363.                 $captcha_plugin_name = OIDplus::baseConfig()->getValue('CAPTCHA_PLUGIN', '');
  364.  
  365.                 if (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false) && ($captcha_plugin_name === '')) {
  366.                         // Legacy config file support!
  367.                         $captcha_plugin_name = 'ReCAPTCHA';
  368.                 }
  369.  
  370.                 if ($captcha_plugin_name === '') $captcha_plugin_name = 'None'; // the "None" plugin is a must-have!
  371.  
  372.                 return $captcha_plugin_name;
  373.         }
  374.  
  375.         public static function getActiveCaptchaPlugin() {
  376.                 $captcha_plugin_name = OIDplus::getActiveCaptchaPluginId();
  377.  
  378.                 if (!isset(self::$captchaPlugins[$captcha_plugin_name])) {
  379.                         throw new OIDplusConfigInitializationException(_L('CAPTCHA plugin "%1" not found',$captcha_plugin_name));
  380.                 }
  381.                 return self::$captchaPlugins[$captcha_plugin_name];
  382.         }
  383.  
  384.         # --- Page plugin
  385.  
  386.         private static function registerPagePlugin(OIDplusPagePlugin $plugin) {
  387.                 self::$pagePlugins[] = $plugin;
  388.  
  389.                 return true;
  390.         }
  391.  
  392.         public static function getPagePlugins() {
  393.                 return self::$pagePlugins;
  394.         }
  395.  
  396.         # --- Auth plugin
  397.  
  398.         private static function registerAuthPlugin(OIDplusAuthPlugin $plugin) {
  399.                 if (OIDplus::baseConfig()->getValue('DEBUG')) {
  400.                         $password = generateRandomString(25);
  401.  
  402.                         try {
  403.                                 $authInfo = $plugin->generate($password);
  404.                         } catch (OIDplusException $e) {
  405.                                 // This can happen when the AuthKey or Salt is too long
  406.                                 throw new OIDplusException(_L('Auth plugin "%1" is erroneous: %2',basename($plugin->getPluginDirectory()),$e->getMessage()));
  407.                         }
  408.                         $salt = $authInfo->getSalt();
  409.                         $authKey = $authInfo->getAuthKey();
  410.  
  411.                         $authInfo_SaltDiff = clone $authInfo;
  412.                         $authInfo_SaltDiff->setSalt(strrev($authInfo_SaltDiff->getSalt()));
  413.  
  414.                         $authInfo_AuthKeyDiff = clone $authInfo;
  415.                         $authInfo_AuthKeyDiff->setAuthKey(strrev($authInfo_AuthKeyDiff->getAuthKey()));
  416.  
  417.                         if ((!$plugin->verify($authInfo,$password)) ||
  418.                            (!empty($salt) && $plugin->verify($authInfo_SaltDiff,$password)) ||
  419.                            ($plugin->verify($authInfo_AuthKeyDiff,$password)) ||
  420.                            ($plugin->verify($authInfo,$password.'x'))) {
  421.                                 throw new OIDplusException(_L('Auth plugin "%1" is erroneous: Generate/Verify self test failed',basename($plugin->getPluginDirectory())));
  422.                         }
  423.                 }
  424.  
  425.                 self::$authPlugins[] = $plugin;
  426.                 return true;
  427.         }
  428.  
  429.         public static function getAuthPlugins() {
  430.                 return self::$authPlugins;
  431.         }
  432.  
  433.         # --- Language plugin
  434.  
  435.         private static function registerLanguagePlugin(OIDplusLanguagePlugin $plugin) {
  436.                 self::$languagePlugins[] = $plugin;
  437.                 return true;
  438.         }
  439.  
  440.         public static function getLanguagePlugins() {
  441.                 return self::$languagePlugins;
  442.         }
  443.  
  444.         # --- Design plugin
  445.  
  446.         private static function registerDesignPlugin(OIDplusDesignPlugin $plugin) {
  447.                 self::$designPlugins[] = $plugin;
  448.                 return true;
  449.         }
  450.  
  451.         public static function getDesignPlugins() {
  452.                 return self::$designPlugins;
  453.         }
  454.  
  455.         # --- Logger plugin
  456.  
  457.         private static function registerLoggerPlugin(OIDplusLoggerPlugin $plugin) {
  458.                 self::$loggerPlugins[] = $plugin;
  459.                 return true;
  460.         }
  461.  
  462.         public static function getLoggerPlugins() {
  463.                 return self::$loggerPlugins;
  464.         }
  465.  
  466.         # --- Object type plugin
  467.  
  468.         private static function registerObjectTypePlugin(OIDplusObjectTypePlugin $plugin) {
  469.                 self::$objectTypePlugins[] = $plugin;
  470.  
  471.                 $ot = $plugin::getObjectTypeClassName();
  472.                 self::registerObjectType($ot);
  473.  
  474.                 return true;
  475.         }
  476.  
  477.         private static function registerObjectType($ot) {
  478.                 $ns = $ot::ns();
  479.  
  480.                 if (empty($ns)) throw new OIDplusException(_L('Attention: Empty NS at %1',$ot));
  481.  
  482.                 $ns_found = false;
  483.                 foreach (array_merge(OIDplus::getEnabledObjectTypes(), OIDplus::getDisabledObjectTypes()) as $test_ot) {
  484.                         if ($test_ot::ns() == $ns) {
  485.                                 $ns_found = true;
  486.                                 break;
  487.                         }
  488.                 }
  489.                 if ($ns_found) {
  490.                         throw new OIDplusException(_L('Attention: Two objectType plugins use the same namespace "%1"!',$ns));
  491.                 }
  492.  
  493.                 $init = OIDplus::config()->getValue("objecttypes_initialized");
  494.                 $init_ary = empty($init) ? array() : explode(';', $init);
  495.                 $init_ary = array_map('trim', $init_ary);
  496.  
  497.                 $enabled = OIDplus::config()->getValue("objecttypes_enabled");
  498.                 $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
  499.                 $enabled_ary = array_map('trim', $enabled_ary);
  500.  
  501.                 $do_enable = false;
  502.                 if (in_array($ns, $enabled_ary)) {
  503.                         // If it is in the list of enabled object types, it is enabled (obviously)
  504.                         $do_enable = true;
  505.                 } else {
  506.                         if (!OIDplus::config()->getValue('oobe_objects_done')) {
  507.                                 // If the OOBE wizard is NOT done, then just enable the "oid" object type by default
  508.                                 $do_enable = $ns == 'oid';
  509.                         } else {
  510.                                 // If the OOBE wizard was done (once), then
  511.                                 // we will enable all object types which were never initialized
  512.                                 // (i.e. a plugin folder was freshly added)
  513.                                 $do_enable = !in_array($ns, $init_ary);
  514.                         }
  515.                 }
  516.  
  517.                 if ($do_enable) {
  518.                         self::$enabledObjectTypes[] = $ot;
  519.                         usort(self::$enabledObjectTypes, function($a, $b) {
  520.                                 $enabled = OIDplus::config()->getValue("objecttypes_enabled");
  521.                                 $enabled_ary = explode(';', $enabled);
  522.  
  523.                                 $idx_a = array_search($a::ns(), $enabled_ary);
  524.                                 $idx_b = array_search($b::ns(), $enabled_ary);
  525.  
  526.                                 if ($idx_a == $idx_b) {
  527.                                     return 0;
  528.                                 }
  529.                                 return ($idx_a > $idx_b) ? +1 : -1;
  530.                         });
  531.                 } else {
  532.                         self::$disabledObjectTypes[] = $ot;
  533.                 }
  534.  
  535.                 if (!in_array($ns, $init_ary)) {
  536.                         // Was never initialized before, so we add it to the list of enabled object types once
  537.  
  538.                         if ($do_enable) {
  539.                                 $enabled_ary[] = $ns;
  540.                                 // Important: Don't validate the input, because the other object types might not be initialized yet! So use setValueNoCallback() instead setValue().
  541.                                 OIDplus::config()->setValueNoCallback("objecttypes_enabled", implode(';', $enabled_ary));
  542.                         }
  543.  
  544.                         $init_ary[] = $ns;
  545.                         OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
  546.                 }
  547.         }
  548.  
  549.         public static function getObjectTypePlugins() {
  550.                 return self::$objectTypePlugins;
  551.         }
  552.  
  553.         public static function getObjectTypePluginsEnabled() {
  554.                 $res = array();
  555.                 foreach (self::$objectTypePlugins as $plugin) {
  556.                         $ot = $plugin::getObjectTypeClassName();
  557.                         if (in_array($ot, self::$enabledObjectTypes)) $res[] = $plugin;
  558.                 }
  559.                 return $res;
  560.         }
  561.  
  562.         public static function getObjectTypePluginsDisabled() {
  563.                 $res = array();
  564.                 foreach (self::$objectTypePlugins as $plugin) {
  565.                         $ot = $plugin::getObjectTypeClassName();
  566.                         if (in_array($ot, self::$disabledObjectTypes)) $res[] = $plugin;
  567.                 }
  568.                 return $res;
  569.         }
  570.  
  571.         public static function getEnabledObjectTypes() {
  572.                 return self::$enabledObjectTypes;
  573.         }
  574.  
  575.         public static function getDisabledObjectTypes() {
  576.                 return self::$disabledObjectTypes;
  577.         }
  578.  
  579.         # --- Plugin handling functions
  580.  
  581.         public static function getAllPlugins()/*: array*/ {
  582.                 $res = array();
  583.                 $res = array_merge($res, self::$pagePlugins);
  584.                 $res = array_merge($res, self::$authPlugins);
  585.                 $res = array_merge($res, self::$loggerPlugins);
  586.                 $res = array_merge($res, self::$objectTypePlugins);
  587.                 $res = array_merge($res, self::$dbPlugins);
  588.                 $res = array_merge($res, self::$captchaPlugins);
  589.                 $res = array_merge($res, self::$sqlSlangPlugins);
  590.                 $res = array_merge($res, self::$languagePlugins);
  591.                 $res = array_merge($res, self::$designPlugins);
  592.                 return $res;
  593.         }
  594.  
  595.         public static function getPluginByOid($oid)/*: ?OIDplusPlugin*/ {
  596.                 $plugins = self::getAllPlugins();
  597.                 foreach ($plugins as $plugin) {
  598.                         if (oid_dotnotation_equal($plugin->getManifest()->getOid(), $oid)) {
  599.                                 return $plugin;
  600.                         }
  601.                 }
  602.                 return null;
  603.         }
  604.  
  605.         public static function getPluginByClassName($classname)/*: ?OIDplusPlugin*/ {
  606.                 $plugins = self::getAllPlugins();
  607.                 foreach ($plugins as $plugin) {
  608.                         if (get_class($plugin) === $classname) {
  609.                                 return $plugin;
  610.                         }
  611.                 }
  612.                 return null;
  613.         }
  614.  
  615.         /**
  616.         * @return array<OIDplusPluginManifest>|array<string,array<string,OIDplusPluginManifest>>
  617.         */
  618.         public static function getAllPluginManifests($pluginFolderMasks='*', $flat=true): array {
  619.                 $out = array();
  620.                 // Note: glob() will sort by default, so we do not need a page priority attribute.
  621.                 //       So you just need to use a numeric plugin directory prefix (padded).
  622.                 $ary = array();
  623.                 foreach (explode(',',$pluginFolderMasks) as $pluginFolderMask) {
  624.                         $ary = array_merge($ary,glob(OIDplus::localpath().'plugins/'.'*'.'/'.$pluginFolderMask.'/'.'*'.'/manifest.xml'));
  625.                 }
  626.  
  627.                 // Sort the plugins by their type and name, as if they would be in a single vendor-folder!
  628.                 uasort($ary, function($a,$b) {
  629.                         if ($a == $b) return 0;
  630.  
  631.                         $ary = explode('/',$a);
  632.                         $bry = explode('/',$b);
  633.  
  634.                         // First sort by type (publicPage, auth, database, language, ...)
  635.                         $a_type = $ary[count($ary)-1-2];
  636.                         $b_type = $bry[count($bry)-1-2];
  637.                         if ($a_type < $b_type) return -1;
  638.                         if ($a_type > $b_type) return 1;
  639.  
  640.                         // Then sort by name (090_login, 100_whois, etc.)
  641.                         $a_name = $ary[count($ary)-1-1];
  642.                         $b_name = $bry[count($bry)-1-1];
  643.                         if ($a_name < $b_name) return -1;
  644.                         if ($a_name > $b_name) return 1;
  645.  
  646.                         // If it is still equal, then finally sort by vendorname
  647.                         $a_vendor = $ary[count($ary)-1-3];
  648.                         $b_vendor = $bry[count($bry)-1-3];
  649.                         if ($a_vendor < $b_vendor) return -1;
  650.                         if ($a_vendor > $b_vendor) return 1;
  651.                         return 0;
  652.                 });
  653.  
  654.                 foreach ($ary as $ini) {
  655.                         if (!file_exists($ini)) continue;
  656.  
  657.                         $manifest = new OIDplusPluginManifest();
  658.                         $manifest->loadManifest($ini);
  659.  
  660.                         $class_name = $manifest->getPhpMainClass();
  661.                         if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
  662.                                 continue;
  663.                         }
  664.  
  665.                         if ($flat) {
  666.                                 $out[] = $manifest;
  667.                         } else {
  668.                                 $plugintype_folder = basename(dirname(dirname($ini)));
  669.                                 $pluginname_folder = basename(dirname($ini));
  670.  
  671.                                 if (!isset($out[$plugintype_folder])) $out[$plugintype_folder] = array();
  672.                                 if (!isset($out[$plugintype_folder][$pluginname_folder])) $out[$plugintype_folder][$pluginname_folder] = array();
  673.                                 $out[$plugintype_folder][$pluginname_folder] = $manifest;
  674.                         }
  675.                 }
  676.                 return $out;
  677.         }
  678.  
  679.         /**
  680.         * @return array<string>
  681.         */
  682.         public static function registerAllPlugins($pluginDirName, $expectedPluginClass, $registerCallback): array {
  683.                 $out = array();
  684.                 if (is_array($pluginDirName)) {
  685.                         $ary = array();
  686.                         foreach ($pluginDirName as $pluginDirName_) {
  687.                                 $ary = array_merge($ary, self::getAllPluginManifests($pluginDirName_, false));
  688.                         }
  689.                 } else {
  690.                         $ary = self::getAllPluginManifests($pluginDirName, false);
  691.                 }
  692.                 $known_plugin_oids = array();
  693.                 if (OIDplus::baseConfig()->getValue('DEBUG')) {
  694.                         $fake_feature = uuid_to_oid(gen_uuid());
  695.                 } else {
  696.                         $fake_feature = null;
  697.                 }
  698.                 foreach ($ary as $plugintype_folder => $bry) {
  699.                         foreach ($bry as $pluginname_folder => $manifest) {
  700.                                 $class_name = $manifest->getPhpMainClass();
  701.  
  702.                                 // Before we load the plugin, we want to make some checks to confirm
  703.                                 // that the plugin is working correctly.
  704.  
  705.                                 if (!$class_name) {
  706.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Manifest does not declare a PHP main class'));
  707.                                 }
  708.                                 if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
  709.                                         continue;
  710.                                 }
  711.                                 if (!class_exists($class_name)) {
  712.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Manifest declares PHP main class as "%1", but it could not be found',$class_name));
  713.                                 }
  714.                                 if (!is_subclass_of($class_name, $expectedPluginClass)) {
  715.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Plugin main class "%1" is expected to be a subclass of "%2"',$class_name,$expectedPluginClass));
  716.                                 }
  717.                                 if (($class_name!=$manifest->getTypeClass()) && (!is_subclass_of($class_name,$manifest->getTypeClass()))) {
  718.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Plugin main class "%1" is expected to be a subclass of "%2", according to type declared in manifest',$class_name,$manifest->getTypeClass()));
  719.                                 }
  720.                                 if (($manifest->getTypeClass()!=$expectedPluginClass) && (!is_subclass_of($manifest->getTypeClass(),$expectedPluginClass))) {
  721.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Class declared in manifest is "%1" does not fit expected class for this plugin type "%2"',$manifest->getTypeClass(),$expectedPluginClass));
  722.                                 }
  723.  
  724.                                 $plugin_oid = $manifest->getOid();
  725.                                 if (!$plugin_oid) {
  726.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Does not have an OID'));
  727.                                 }
  728.                                 if (!oid_valid_dotnotation($plugin_oid, false, false, 2)) {
  729.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Plugin OID "%1" is invalid (needs to be valid dot-notation)',$plugin_oid));
  730.                                 }
  731.                                 if (isset($known_plugin_oids[$plugin_oid])) {
  732.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('The OID "%1" is already used by the plugin "%2"',$plugin_oid,$known_plugin_oids[$plugin_oid]));
  733.                                 }
  734.  
  735.                                 $full_plugin_dir = dirname($manifest->getManifestFile());
  736.                                 $full_plugin_dir = substr($full_plugin_dir, strlen(OIDplus::localpath()));
  737.                                 // { iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) 37476 products(2) oidplus(5) v2(2) plugins(4) }
  738.                                 if (str_starts_with($full_plugin_dir, 'plugins/viathinksoft/') != str_starts_with($plugin_oid, '1.3.6.1.4.1.37476.2.5.2.4.')) {
  739.                                         throw new OIDplusException(_L('Plugin "%1/%2" is misplaced',$plugintype_folder,$pluginname_folder).': '._L('The plugin is in the wrong folder. The folder %1 can only be used by official ViaThinkSoft plugins','plugins/viathinksoft/'));
  740.                                 }
  741.  
  742.                                 $known_plugin_oids[$plugin_oid] = $plugintype_folder.'/'.$pluginname_folder;
  743.  
  744.                                 $obj = new $class_name();
  745.  
  746.                                 if (OIDplus::baseConfig()->getValue('DEBUG')) {
  747.                                         if ($obj->implementsFeature($fake_feature)) {
  748.                                                 // see https://devblogs.microsoft.com/oldnewthing/20040211-00/?p=40663
  749.                                                 throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('implementsFeature() always returns true'));
  750.                                         }
  751.                                 }
  752.  
  753.                                 // TODO: Maybe as additional plugin-test, we should also check if plugins are allowed to define CSS/JS (since only page plugins may have them!)
  754.                                 $tmp = array_merge(
  755.                                         $manifest->getJSFiles(),
  756.                                         $manifest->getCSSFiles(),
  757.                                         $manifest->getJSFilesSetup(),
  758.                                         $manifest->getCSSFilesSetup()
  759.                                 );
  760.                                 foreach ($tmp as $file) {
  761.                                         if (!file_exists($file)) {
  762.                                                 throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('File %1 was defined in manifest, but it is not existing',$file));
  763.                                         }
  764.                                 }
  765.  
  766.                                 // Now we can continue
  767.  
  768.                                 $out[] = $class_name;
  769.                                 if (!is_null($registerCallback)) {
  770.                                         call_user_func($registerCallback, $obj);
  771.  
  772.                                         // Alternative approaches:
  773.                                         //$registerCallback[0]::{$registerCallback[1]}($obj);
  774.                                         // or:
  775.                                         //forward_static_call($registerCallback, $obj);
  776.                                 }
  777.                         }
  778.  
  779.                 }
  780.                 return $out;
  781.         }
  782.  
  783.         # --- Initialization of OIDplus
  784.  
  785.         public static function init($html=true, $keepBaseConfig=true) {
  786.                 self::$html = $html;
  787.  
  788.                 // Reset internal state, so we can re-init verything if required
  789.  
  790.                 if (self::$old_config_format) {
  791.                         // Note: This can only happen in very special cases (e.g. test cases) where you call init() twice
  792.                         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.'));
  793.                 }
  794.  
  795.                 self::$config = null;
  796.                 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
  797.                 self::$gui = null;
  798.                 self::$authUtils = null;
  799.                 self::$mailUtils = null;
  800.                 self::$menuUtils = null;
  801.                 self::$logger = null;
  802.                 self::$dbMainSession = null;
  803.                 self::$dbIsolatedSession = null;
  804.                 self::$pagePlugins = array();
  805.                 self::$authPlugins = array();
  806.                 self::$loggerPlugins = array();
  807.                 self::$objectTypePlugins = array();
  808.                 self::$enabledObjectTypes = array();
  809.                 self::$disabledObjectTypes = array();
  810.                 self::$dbPlugins = array();
  811.                 self::$captchaPlugins = array();
  812.                 self::$sqlSlangPlugins = array();
  813.                 self::$languagePlugins = array();
  814.                 self::$designPlugins = array();
  815.                 self::$system_id_cache = null;
  816.                 self::$sslAvailableCache = null;
  817.                 self::$translationArray = array();
  818.  
  819.                 // Continue...
  820.  
  821.                 OIDplus::baseConfig(); // this loads the base configuration located in userdata/baseconfig/config.inc.php (once!)
  822.                                        // You can do changes to the configuration afterwards using OIDplus::baseConfig()->...
  823.  
  824.                 // Register database types (highest priority)
  825.  
  826.                 // SQL slangs
  827.  
  828.                 self::registerAllPlugins('sqlSlang', 'OIDplusSqlSlangPlugin', array('OIDplus','registerSqlSlangPlugin'));
  829.                 foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
  830.                         $plugin->init($html);
  831.                 }
  832.  
  833.                 // Database providers
  834.  
  835.                 self::registerAllPlugins('database', 'OIDplusDatabasePlugin', array('OIDplus','registerDatabasePlugin'));
  836.                 foreach (OIDplus::getDatabasePlugins() as $plugin) {
  837.                         $plugin->init($html);
  838.                 }
  839.  
  840.                 // CAPTCHA plugins
  841.  
  842.                 self::registerAllPlugins('captcha', 'OIDplusCaptchaPlugin', array('OIDplus','registerCaptchaPlugin'));
  843.                 foreach (OIDplus::getCaptchaPlugins() as $plugin) {
  844.                         $plugin->init($html);
  845.                 }
  846.  
  847.                 // Do redirect stuff etc.
  848.  
  849.                 self::isSslAvailable(); // This function does automatic redirects
  850.  
  851.                 // Construct the configuration manager
  852.  
  853.                 OIDplus::config(); // During the construction, various system settings are prepared if required
  854.  
  855.                 // Initialize public / private keys
  856.  
  857.                 OIDplus::getPkiStatus(true);
  858.  
  859.                 // Register non-DB plugins
  860.  
  861.                 self::registerAllPlugins(array('publicPages', 'raPages', 'adminPages'), 'OIDplusPagePlugin', array('OIDplus','registerPagePlugin'));
  862.                 self::registerAllPlugins('auth', 'OIDplusAuthPlugin', array('OIDplus','registerAuthPlugin'));
  863.                 self::registerAllPlugins('logger', 'OIDplusLoggerPlugin', array('OIDplus','registerLoggerPlugin'));
  864.                 self::registerAllPlugins('objectTypes', 'OIDplusObjectTypePlugin', array('OIDplus','registerObjectTypePlugin'));
  865.                 self::registerAllPlugins('language', 'OIDplusLanguagePlugin', array('OIDplus','registerLanguagePlugin'));
  866.                 self::registerAllPlugins('design', 'OIDplusDesignPlugin', array('OIDplus','registerDesignPlugin'));
  867.  
  868.                 // Initialize non-DB plugins
  869.  
  870.                 foreach (OIDplus::getPagePlugins() as $plugin) {
  871.                         $plugin->init($html);
  872.                 }
  873.                 foreach (OIDplus::getAuthPlugins() as $plugin) {
  874.                         $plugin->init($html);
  875.                 }
  876.                 foreach (OIDplus::getLoggerPlugins() as $plugin) {
  877.                         $plugin->init($html);
  878.                 }
  879.                 foreach (OIDplus::getObjectTypePlugins() as $plugin) {
  880.                         $plugin->init($html);
  881.                 }
  882.                 foreach (OIDplus::getLanguagePlugins() as $plugin) {
  883.                         $plugin->init($html);
  884.                 }
  885.                 foreach (OIDplus::getDesignPlugins() as $plugin) {
  886.                         $plugin->init($html);
  887.                 }
  888.  
  889.                 // Initialize other stuff (i.e. things which require the logger!)
  890.  
  891.                 OIDplus::recognizeSystemUrl(); // Make sure "last_known_system_url" is set
  892.                 OIDplus::recognizeVersion(); // Make sure "last_known_version" is set and a log entry is created
  893.         }
  894.  
  895.         # --- System URL, System ID, PKI, and other functions
  896.  
  897.         private static function recognizeSystemUrl() {
  898.                 try {
  899.                         $url = OIDplus::webpath();
  900.                         OIDplus::config()->setValue('last_known_system_url', $url);
  901.                 } catch (Exception $e) {
  902.                 }
  903.         }
  904.  
  905.         private static function getExecutingScriptPathDepth() {
  906.                 if (PHP_SAPI == 'cli') {
  907.                         global $argv;
  908.                         $test_dir = dirname(realpath($argv[0]));
  909.                 } else {
  910.                         if (!isset($_SERVER["SCRIPT_FILENAME"])) return false;
  911.                         $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
  912.                 }
  913.                 $test_dir = str_replace('\\', '/', $test_dir);
  914.                 $steps_up = 0;
  915.                 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 subsequent directory!
  916.                         $test_dir = dirname($test_dir);
  917.                         $steps_up++;
  918.                         if ($steps_up == 1000) return false; // to make sure there will never be an infinite loop
  919.                 }
  920.                 return $steps_up;
  921.         }
  922.  
  923.         public static function isSSL() {
  924.                 return isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
  925.         }
  926.  
  927.         private static function getSystemUrl($relative=false) {
  928.                 if (!$relative) {
  929.                         $res = OIDplus::baseConfig()->getValue('EXPLICIT_ABSOLUTE_SYSTEM_URL', '');
  930.                         if ($res !== '') {
  931.                                 return rtrim($res,'/').'/';
  932.                         }
  933.                         if (PHP_SAPI == 'cli') {
  934.                                 try {
  935.                                         return OIDplus::config()->getValue('last_known_system_url', false);
  936.                                 } catch (Exception $e) {
  937.                                         return false;
  938.                                 }
  939.                         }
  940.                 }
  941.  
  942.                 // First, try to find out how many levels we need to go up
  943.                 $steps_up = self::getExecutingScriptPathDepth();
  944.                 if ($steps_up === false) return false;
  945.  
  946.                 // Now go up these amount of levels, based on SCRIPT_NAME/argv[0]
  947.                 if (PHP_SAPI == 'cli') {
  948.                         if ($relative) {
  949.                                 return str_repeat('../',$steps_up);
  950.                         } else {
  951.                                 return false;
  952.                         }
  953.                 } else {
  954.                         $res = dirname($_SERVER['SCRIPT_NAME'].'index.php'); // This fake 'index.php' ensures that SCRIPT_NAME does not end with '/', which would make dirname() fail
  955.                         for ($i=0; $i<$steps_up; $i++) {
  956.                                 $res = dirname($res);
  957.                         }
  958.                         $res = str_replace('\\', '/', $res);
  959.                         if ($res == '/') $res = '';
  960.                         $res .= '/';
  961.  
  962.                         // Do we want to have an absolute URI?
  963.                         if (!$relative) {
  964.                                 $is_ssl = self::isSSL();
  965.                                 $protocol = $is_ssl ? 'https' : 'http'; // do not translate
  966.                                 $host = $_SERVER['HTTP_HOST']; // includes port if it is not 80/443
  967.                                 $res = $protocol.'://'.$host.$res;
  968.                         }
  969.  
  970.                         return $res;
  971.                 }
  972.         }
  973.  
  974.         private static $system_id_cache = null;
  975.         public static function getSystemId($oid=false) {
  976.                 if (!is_null(self::$system_id_cache)) {
  977.                         $out = self::$system_id_cache;
  978.                 } else {
  979.                         $out = false;
  980.  
  981.                         if (self::getPkiStatus(true)) {
  982.                                 $pubKey = OIDplus::config()->getValue('oidplus_public_key');
  983.                                 $m = array();
  984.                                 if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
  985.                                         $out = smallhash(base64_decode($m[1]));
  986.                                 }
  987.                         }
  988.                         self::$system_id_cache = $out;
  989.                 }
  990.                 if (!$out) return false;
  991.                 return ($oid ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
  992.         }
  993.  
  994.         public static function getPkiStatus($try_generate=true) {
  995.                 if (!function_exists('openssl_pkey_new')) return false;
  996.  
  997.                 $privKey = OIDplus::config()->getValue('oidplus_private_key');
  998.                 $pubKey = OIDplus::config()->getValue('oidplus_public_key');
  999.  
  1000.                 if ($try_generate && !verify_private_public_key($privKey, $pubKey)) {
  1001.                         $pkey_config = array(
  1002.                             "digest_alg" => "sha512",
  1003.                             "private_key_bits" => 2048,
  1004.                             "private_key_type" => OPENSSL_KEYTYPE_RSA,
  1005.                         );
  1006.  
  1007.                         // Create the private and public key
  1008.                         $res = openssl_pkey_new($pkey_config);
  1009.  
  1010.                         if (!$res) return false;
  1011.  
  1012.                         // Extract the private key from $res to $privKey
  1013.                         openssl_pkey_export($res, $privKey);
  1014.  
  1015.                         // Extract the public key from $res to $pubKey
  1016.                         $pubKey = openssl_pkey_get_details($res)["key"];
  1017.  
  1018.                         // Log
  1019.                         OIDplus::logger()->log("[INFO]A!", "Generating new SystemID using a new key pair");
  1020.  
  1021.                         // Save the key pair to database
  1022.                         OIDplus::config()->setValue('oidplus_private_key', $privKey);
  1023.                         OIDplus::config()->setValue('oidplus_public_key', $pubKey);
  1024.  
  1025.                         // Log the new system ID
  1026.                         $m = array();
  1027.                         if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
  1028.                                 $system_id = smallhash(base64_decode($m[1]));
  1029.                                 OIDplus::logger()->log("[INFO]A!", "Your SystemID is now $system_id");
  1030.                         }
  1031.                 }
  1032.  
  1033.                 return verify_private_public_key($privKey, $pubKey);
  1034.         }
  1035.  
  1036.         public static function getInstallType() {
  1037.                 $counter = 0;
  1038.  
  1039.                 if ($new_version_file_exists = file_exists(OIDplus::localpath().'.version.php')) {
  1040.                         $counter++;
  1041.                 }
  1042.                 if ($old_version_file_exists = file_exists(OIDplus::localpath().'oidplus_version.txt')) {
  1043.                         $counter++;
  1044.                 }
  1045.                 $version_file_exists = $old_version_file_exists | $new_version_file_exists;
  1046.                 if ($svn_dir_exists = (is_dir(OIDplus::localpath().'.svn') ||
  1047.                                        is_dir(OIDplus::localpath().'../.svn'))) { // in case we checked out the root instead of the "trunk"
  1048.                         $counter++;
  1049.                 }
  1050.                 // if ($git_dir_exists = is_dir(OIDplus::localpath().'.git')) {
  1051.                 if ($git_dir_exists = (OIDplus::findGitFolder() !== false)) {
  1052.                         $counter++;
  1053.                 }
  1054.  
  1055.                 if ($counter === 0) {
  1056.                         return 'unknown'; // do not translate
  1057.                 }
  1058.                 else if ($counter > 1) {
  1059.                         return 'ambigous'; // do not translate
  1060.                 }
  1061.                 else if ($svn_dir_exists) {
  1062.                         return 'svn-wc'; // do not translate
  1063.                 }
  1064.                 else if ($git_dir_exists) {
  1065.                         return 'git-wc'; // do not translate
  1066.                 }
  1067.                 else if ($version_file_exists) {
  1068.                         return 'svn-snapshot'; // do not translate
  1069.                 }
  1070.         }
  1071.  
  1072.         private static function recognizeVersion() {
  1073.                 try {
  1074.                         $ver_prev = OIDplus::config()->getValue("last_known_version");
  1075.                         $ver_now = OIDplus::getVersion();
  1076.                         if (($ver_now != '') && ($ver_prev != '') && ($ver_now != $ver_prev)) {
  1077.                                 // TODO: Problem: When the system was updated using SVN, then the IP address of the next random visitor of the website is logged!
  1078.                                 OIDplus::logger()->log("[INFO]A!", "System version changed from '$ver_prev' to '$ver_now'");
  1079.                         }
  1080.                         OIDplus::config()->setValue("last_known_version", $ver_now);
  1081.                 } catch (Exception $e) {
  1082.                 }
  1083.         }
  1084.  
  1085.         public static function getVersion() {
  1086.                 static $cachedVersion = null;
  1087.                 if (!is_null($cachedVersion)) {
  1088.                         return $cachedVersion;
  1089.                 }
  1090.  
  1091.                 $installType = OIDplus::getInstallType();
  1092.  
  1093.                 if ($installType === 'svn-wc') {
  1094.                         $ver = get_svn_revision(OIDplus::localpath());
  1095.                         if ($ver)
  1096.                                 return ($cachedVersion = 'svn-'.$ver);
  1097.                         $ver = get_svn_revision(OIDplus::localpath().'../'); // in case we checked out the root instead of the "trunk"
  1098.                         if ($ver)
  1099.                                 return ($cachedVersion = 'svn-'.$ver);
  1100.                 }
  1101.  
  1102.                 if ($installType === 'git-wc') {
  1103.                         $ver = OIDplus::getGitsvnRevision(OIDplus::localpath());
  1104.                         if ($ver)
  1105.                                 return ($cachedVersion = 'svn-'.$ver);
  1106.                 }
  1107.  
  1108.                 if ($installType === 'svn-snapshot') {
  1109.                         $cont = '';
  1110.                         if (file_exists($filename = OIDplus::localpath().'oidplus_version.txt'))
  1111.                                 $cont = file_get_contents($filename);
  1112.                         if (file_exists($filename = OIDplus::localpath().'.version.php'))
  1113.                                 $cont = file_get_contents($filename);
  1114.                         $m = array();
  1115.                         if (preg_match('@Revision (\d+)@', $cont, $m)) // do not translate
  1116.                                 return ($cachedVersion = 'svn-'.$m[1]); // do not translate
  1117.                 }
  1118.  
  1119.                 return ($cachedVersion = false); // version ambigous or unknown
  1120.         }
  1121.  
  1122.         private static $sslAvailableCache = null;
  1123.         public static function isSslAvailable() {
  1124.                 if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
  1125.  
  1126.                 if (PHP_SAPI == 'cli') {
  1127.                         self::$sslAvailableCache = false;
  1128.                         return false;
  1129.                 }
  1130.  
  1131.                 $timeout = 2;
  1132.                 $already_ssl = self::isSSL();
  1133.                 $ssl_port = 443;
  1134.  
  1135.                 $mode = OIDplus::baseConfig()->getValue('ENFORCE_SSL', 2/*auto*/);
  1136.  
  1137.                 if ($mode == 0) {
  1138.                         // No SSL available
  1139.                         self::$sslAvailableCache = $already_ssl;
  1140.                         return $already_ssl;
  1141.                 }
  1142.  
  1143.                 if ($mode == 1) {
  1144.                         // Force SSL
  1145.                         if ($already_ssl) {
  1146.                                 self::$sslAvailableCache = true;
  1147.                                 return true;
  1148.                         } else {
  1149.                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  1150.                                 header('Location:'.$location);
  1151.                                 die(_L('Redirecting to HTTPS...'));
  1152.                                 #self::$sslAvailableCache = true;
  1153.                                 #return true;
  1154.                         }
  1155.                 }
  1156.  
  1157.                 if ($mode == 2) {
  1158.                         // Automatic SSL detection
  1159.  
  1160.                         if ($already_ssl) {
  1161.                                 // we are already on HTTPS
  1162.                                 OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, false);
  1163.                                 self::$sslAvailableCache = true;
  1164.                                 return true;
  1165.                         } else {
  1166.                                 if (isset($_COOKIE['SSL_CHECK'])) {
  1167.                                         // We already had the HTTPS detection done before.
  1168.                                         if ($_COOKIE['SSL_CHECK']) {
  1169.                                                 // HTTPS was detected before, but we are HTTP. Redirect now
  1170.                                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  1171.                                                 header('Location:'.$location);
  1172.                                                 die(_L('Redirecting to HTTPS...'));
  1173.                                                 #self::$sslAvailableCache = true;
  1174.                                                 #return true;
  1175.                                         } else {
  1176.                                                 // No HTTPS available. Do nothing.
  1177.                                                 self::$sslAvailableCache = false;
  1178.                                                 return false;
  1179.                                         }
  1180.                                 } else {
  1181.                                         // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
  1182.                                         $errno = -1;
  1183.                                         $errstr = '';
  1184.                                         if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
  1185.                                                 // HTTPS detected. Redirect now, and remember that we had detected HTTPS
  1186.                                                 OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, false);
  1187.                                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  1188.                                                 header('Location:'.$location);
  1189.                                                 die(_L('Redirecting to HTTPS...'));
  1190.                                                 #self::$sslAvailableCache = true;
  1191.                                                 #return true;
  1192.                                         } else {
  1193.                                                 // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
  1194.                                                 OIDplus::cookieUtils()->setcookie('SSL_CHECK', '0', 0, false);
  1195.                                                 self::$sslAvailableCache = false;
  1196.                                                 return false;
  1197.                                         }
  1198.                                 }
  1199.                         }
  1200.                 }
  1201.         }
  1202.  
  1203.         /**
  1204.          * Gets a local path pointing to a resource
  1205.          * @param string $target Target resource (file or directory must exist), or null to get the OIDplus base directory
  1206.          * @param boolean $relative If true, the returning path is relative to the currently executed PHP file (not the CLI working directory)
  1207.          * @return string|false The local path, with guaranteed trailing path delimiter for directories
  1208.          */
  1209.         public static function localpath($target=null, $relative=false) {
  1210.                 if (is_null($target)) {
  1211.                         $target = __DIR__.'/../../';
  1212.                 }
  1213.  
  1214.                 if ($relative) {
  1215.                         // First, try to find out how many levels we need to go up
  1216.                         $steps_up = self::getExecutingScriptPathDepth();
  1217.                         if ($steps_up === false) return false;
  1218.  
  1219.                         // Virtually go back from the executing PHP script to the OIDplus base path
  1220.                         $res = str_repeat('../',$steps_up);
  1221.  
  1222.                         // Then go to the desired location
  1223.                         $basedir = realpath(__DIR__.'/../../');
  1224.                         $target = realpath($target);
  1225.                         if ($target === false) return false;
  1226.                         $res .= substr($target, strlen($basedir)+1);
  1227.                         $res = rtrim($res,'/'); // avoid '..//' for localpath(null,true)
  1228.                 } else {
  1229.                         $res = realpath($target);
  1230.                 }
  1231.  
  1232.                 if (is_dir($target)) $res .= DIRECTORY_SEPARATOR;
  1233.  
  1234.                 return $res;
  1235.         }
  1236.  
  1237.         /**
  1238.          * Gets a URL pointing to a resource
  1239.          * @param string $target Target resource (file or directory must exist), or null to get the OIDplus base directory
  1240.          * @param boolean $relative If true, the returning path is relative to the currently executed PHP script (i.e. index.php , not the plugin PHP script!)
  1241.          * @return string|false The URL, with guaranteed trailing path delimiter for directories
  1242.          */
  1243.         public static function webpath($target=null, $relative=false) {
  1244.                 $res = self::getSystemUrl($relative); // Note: already contains a trailing path delimiter
  1245.                 if (!$res) return false;
  1246.  
  1247.                 if (!is_null($target)) {
  1248.                         $basedir = realpath(__DIR__.'/../../');
  1249.                         $target = realpath($target);
  1250.                         if ($target === false) return false;
  1251.                         $tmp = substr($target, strlen($basedir)+1);
  1252.                         $res .= str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
  1253.                         if (is_dir($target)) $res .= '/';
  1254.                 }
  1255.  
  1256.                 return $res;
  1257.         }
  1258.  
  1259.         private static $shutdown_functions = array();
  1260.         public static function register_shutdown_function($func) {
  1261.                 self::$shutdown_functions[] = $func;
  1262.         }
  1263.  
  1264.         public static function invoke_shutdown() {
  1265.                 foreach (self::$shutdown_functions as $func) {
  1266.                         $func();
  1267.                 }
  1268.         }
  1269.  
  1270.         public static function getAvailableLangs() {
  1271.                 $langs = array();
  1272.                 foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
  1273.                         $code = $pluginManifest->getLanguageCode();
  1274.                         $langs[] = $code;
  1275.                 }
  1276.                 return $langs;
  1277.         }
  1278.  
  1279.         public static function getCurrentLang() {
  1280.                 if (isset($_GET['lang'])) {
  1281.                         $lang = $_GET['lang'];
  1282.                 } else if (isset($_POST['lang'])) {
  1283.                         $lang = $_POST['lang'];
  1284.                 } else if (isset($_COOKIE['LANGUAGE'])) {
  1285.                         $lang = $_COOKIE['LANGUAGE'];
  1286.                 } else {
  1287.                         $lang = self::DEFAULT_LANGUAGE;
  1288.                 }
  1289.                 $lang = substr(preg_replace('@[^a-z]@ismU', '', $lang),0,4); // sanitize
  1290.                 return $lang;
  1291.         }
  1292.  
  1293.         public static function handleLangArgument() {
  1294.                 if (isset($_GET['lang'])) {
  1295.                         // The "?lang=" argument is only for NoScript-Browsers/SearchEngines
  1296.                         // In case someone who has JavaScript clicks a ?lang= link, they should get
  1297.                         // the page in that language, but the cookie must be set, otherwise
  1298.                         // the menu and other stuff would be in their cookie-based-language and not the
  1299.                         // argument-based-language.
  1300.                         OIDplus::cookieUtils()->setcookie('LANGUAGE', $_GET['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
  1301.                 } else if (isset($_POST['lang'])) {
  1302.                         OIDplus::cookieUtils()->setcookie('LANGUAGE', $_POST['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
  1303.                 }
  1304.         }
  1305.  
  1306.         private static $translationArray = array();
  1307.         protected static function getTranslationFileContents($translation_file) {
  1308.                 // First, try the cache
  1309.                 $cache_file = __DIR__ . '/../../userdata/cache/translation_'.md5($translation_file).'.ser';
  1310.                 if (file_exists($cache_file) && (filemtime($cache_file) == filemtime($translation_file))) {
  1311.                         $cac = @unserialize(file_get_contents($cache_file));
  1312.                         if ($cac) return $cac;
  1313.                 }
  1314.  
  1315.                 // If not successful, then load the XML file
  1316.                 $xml = @simplexml_load_string(file_get_contents($translation_file));
  1317.                 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
  1318.                 $cac = array();
  1319.                 foreach ($xml->message as $msg) {
  1320.                         $src = trim($msg->source->__toString());
  1321.                         $dst = trim($msg->target->__toString());
  1322.                         $cac[$src] = $dst;
  1323.                 }
  1324.                 @file_put_contents($cache_file,serialize($cac));
  1325.                 @touch($cache_file,filemtime($translation_file));
  1326.                 return $cac;
  1327.         }
  1328.         public static function getTranslationArray($requested_lang='*') {
  1329.                 foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
  1330.                         $lang = $pluginManifest->getLanguageCode();
  1331.                         if (strpos($lang,'/') !== false) continue; // just to be sure
  1332.                         if (strpos($lang,'\\') !== false) continue; // just to be sure
  1333.                         if (strpos($lang,'..') !== false) continue; // just to be sure
  1334.  
  1335.                         if (($requested_lang != '*') && ($lang != $requested_lang)) continue;
  1336.  
  1337.                         if (!isset(self::$translationArray[$lang])) {
  1338.                                 self::$translationArray[$lang] = array();
  1339.  
  1340.                                 $wildcard = $pluginManifest->getLanguageMessages();
  1341.                                 if (strpos($wildcard,'/') !== false) continue; // just to be sure
  1342.                                 if (strpos($wildcard,'\\') !== false) continue; // just to be sure
  1343.                                 if (strpos($wildcard,'..') !== false) continue; // just to be sure
  1344.  
  1345.                                 $translation_files = glob(__DIR__.'/../../plugins/'.'*'.'/language/'.$lang.'/'.$wildcard);
  1346.                                 sort($translation_files);
  1347.                                 foreach ($translation_files as $translation_file) {
  1348.                                         if (!file_exists($translation_file)) continue;
  1349.                                         $cac = self::getTranslationFileContents($translation_file);
  1350.                                         foreach ($cac as $src => $dst) {
  1351.                                                 self::$translationArray[$lang][$src] = $dst;
  1352.                                         }
  1353.                                 }
  1354.                         }
  1355.                 }
  1356.                 return self::$translationArray;
  1357.         }
  1358.  
  1359.         public static function getEditionInfo() {
  1360.                 return @parse_ini_file(__DIR__.'/../edition.ini', true)['Edition'];
  1361.         }
  1362.  
  1363.         public static function findGitFolder() {
  1364.                 // Git command line saves git information in folder ".git"
  1365.                 // Plesk git saves git information in folder "../../../git/oidplus/" (or similar)
  1366.                 $dir = realpath(__DIR__);
  1367.                 if (is_dir($dir.'/.git')) return $dir.'/.git';
  1368.                 $i = 0;
  1369.                 do {
  1370.                         if (is_dir($dir.'/git')) {
  1371.                                 $confs = glob($dir.'/git/'.'*'.'/config');
  1372.                                 foreach ($confs as $conf) {
  1373.                                         $cont = file_get_contents($conf);
  1374.                                         if (isset(OIDplus::getEditionInfo()['gitrepo']) && (OIDplus::getEditionInfo()['gitrepo'] != '') && (strpos($cont, OIDplus::getEditionInfo()['gitrepo']) !== false)) {
  1375.                                                 return dirname($conf);
  1376.                                         }
  1377.                                 }
  1378.                         }
  1379.                         $i++;
  1380.                 } while (($i<100) && ($dir != ($new_dir = realpath($dir.'/../'))) && ($dir = $new_dir));
  1381.                 return false;
  1382.         }
  1383.  
  1384.         public static function getGitsvnRevision($dir='') {
  1385.                 try {
  1386.                         // tries command line and binary parsing
  1387.                         // requires vendor/danielmarschall/git_utils.inc.php
  1388.                         $git_dir = OIDplus::findGitFolder();
  1389.                         if ($git_dir === false) return false;
  1390.                         $commit_msg = git_get_latest_commit_message($git_dir);
  1391.                 } catch (Exception $e) {
  1392.                         return false;
  1393.                 }
  1394.  
  1395.                 $m = array();
  1396.                 if (preg_match('%git-svn-id: (.+)@(\\d+) %ismU', $commit_msg, $m)) {
  1397.                         return $m[2];
  1398.                 } else {
  1399.                         return false;
  1400.                 }
  1401.         }
  1402.  
  1403. }
  1404.