Subversion Repositories oidplus

Rev

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