Subversion Repositories oidplus

Rev

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

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