Subversion Repositories oidplus

Rev

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