Subversion Repositories oidplus

Rev

Rev 292 | Rev 295 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

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