Subversion Repositories oidplus

Rev

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

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