Subversion Repositories oidplus

Rev

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