Subversion Repositories oidplus

Rev

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