Subversion Repositories oidplus

Rev

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