Subversion Repositories oidplus

Rev

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

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