Subversion Repositories oidplus

Rev

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