Subversion Repositories oidplus

Rev

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