Subversion Repositories oidplus

Rev

Rev 380 | Rev 389 | 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'; // the language of the source code
  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/oidplus_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(_L('File %1 is missing, but setup can\'t be started because its directory missing.','userdata/baseconfig/config.inc.php'));
  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(_L('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(_L('File %1 is missing. Please run setup again.','userdata/baseconfig/config.inc.php'));
  106.                                         }
  107.                                 }
  108.                         }
  109.  
  110.                         // Check important config settings
  111.  
  112.                         if (self::$baseConfig->getValue('CONFIG_VERSION') != 2.1) {
  113.                                 throw new OIDplusConfigInitializationException(_L("The information located in %1 is outdated.",$config_file));
  114.                         }
  115.  
  116.                         if (self::$baseConfig->getValue('SERVER_SECRET', '') === '') {
  117.                                 throw new OIDplusConfigInitializationException(_L("You must set a value for SERVER_SECRET in %1 for the system to operate secure.",$config_file));
  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(_L('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(_L('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(_L('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(_L('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(_L('Please check your input. Namespace "%1" is not found',$ot_check));
  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(_L('No database plugin selected in config file'));
  282.                 }
  283.                 if (!isset(self::$dbPlugins[OIDplus::baseConfig()->getValue('DATABASE_PLUGIN')])) {
  284.                         $db_plugin_name = OIDplus::baseConfig()->getValue('DATABASE_PLUGIN');
  285.                         throw new OIDplusConfigInitializationException(_L('Database plugin "%1" not found',$db_plugin_name));
  286.                 }
  287.                 return self::$dbPlugins[OIDplus::baseConfig()->getValue('DATABASE_PLUGIN')];
  288.         }
  289.  
  290.         private static $dbMainSession = null;
  291.         public static function db() {
  292.                 if (is_null(self::$dbMainSession)) {
  293.                         self::$dbMainSession = self::getActiveDatabasePlugin()->newConnection();
  294.                 }
  295.                 if (!self::$dbMainSession->isConnected()) self::$dbMainSession->connect();
  296.                 return self::$dbMainSession;
  297.         }
  298.  
  299.         private static $dbIsolatedSession = null;
  300.         public static function dbIsolated() {
  301.                 if (is_null(self::$dbIsolatedSession)) {
  302.                         self::$dbIsolatedSession = self::getActiveDatabasePlugin()->newConnection();
  303.                 }
  304.                 if (!self::$dbIsolatedSession->isConnected()) self::$dbIsolatedSession->connect();
  305.                 return self::$dbIsolatedSession;
  306.         }
  307.  
  308.         # --- Page plugin
  309.  
  310.         private static function registerPagePlugin(OIDplusPagePlugin $plugin) {
  311.                 self::$pagePlugins[] = $plugin;
  312.  
  313.                 return true;
  314.         }
  315.  
  316.         public static function getPagePlugins() {
  317.                 return self::$pagePlugins;
  318.         }
  319.  
  320.         # --- Auth plugin
  321.  
  322.         private static function registerAuthPlugin(OIDplusAuthPlugin $plugin) {
  323.                 self::$authPlugins[] = $plugin;
  324.                 return true;
  325.         }
  326.  
  327.         public static function getAuthPlugins() {
  328.                 return self::$authPlugins;
  329.         }
  330.  
  331.         # --- Language plugin
  332.  
  333.         private static function registerLanguagePlugin(OIDplusLanguagePlugin $plugin) {
  334.                 self::$languagePlugins[] = $plugin;
  335.                 return true;
  336.         }
  337.  
  338.         public static function getLanguagePlugins() {
  339.                 return self::$languagePlugins;
  340.         }
  341.  
  342.         # --- Logger plugin
  343.  
  344.         private static function registerLoggerPlugin(OIDplusLoggerPlugin $plugin) {
  345.                 self::$loggerPlugins[] = $plugin;
  346.                 return true;
  347.         }
  348.  
  349.         public static function getLoggerPlugins() {
  350.                 return self::$loggerPlugins;
  351.         }
  352.  
  353.         # --- Object type plugin
  354.  
  355.         private static function registerObjectTypePlugin(OIDplusObjectTypePlugin $plugin) {
  356.                 self::$objectTypePlugins[] = $plugin;
  357.  
  358.                 $ot = $plugin::getObjectTypeClassName();
  359.                 self::registerObjectType($ot);
  360.  
  361.                 return true;
  362.         }
  363.  
  364.         private static function registerObjectType($ot) {
  365.                 $ns = $ot::ns();
  366.  
  367.                 if (empty($ns)) throw new OIDplusException(_L('Attention: Empty NS at %1',$ot));
  368.  
  369.                 $ns_found = false;
  370.                 foreach (array_merge(OIDplus::getEnabledObjectTypes(), OIDplus::getDisabledObjectTypes()) as $test_ot) {
  371.                         if ($test_ot::ns() == $ns) {
  372.                                 $ns_found = true;
  373.                                 break;
  374.                         }
  375.                 }
  376.                 if ($ns_found) {
  377.                         throw new OIDplusException(_L('Attention: Two objectType plugins use the same namespace "%1"!',$ns));
  378.                 }
  379.  
  380.                 $init = OIDplus::config()->getValue("objecttypes_initialized");
  381.                 $init_ary = empty($init) ? array() : explode(';', $init);
  382.                 $init_ary = array_map('trim', $init_ary);
  383.  
  384.                 $enabled = OIDplus::config()->getValue("objecttypes_enabled");
  385.                 $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
  386.                 $enabled_ary = array_map('trim', $enabled_ary);
  387.  
  388.                 $do_enable = false;
  389.                 if (in_array($ns, $enabled_ary)) {
  390.                         $do_enable = true;
  391.                 } else {
  392.                         if (!OIDplus::config()->getValue('registration_done')) {
  393.                                 $do_enable = $ns == 'oid';
  394.                         } else {
  395.                                 $do_enable = !in_array($ns, $init_ary);
  396.                         }
  397.                 }
  398.  
  399.                 if ($do_enable) {
  400.                         self::$enabledObjectTypes[] = $ot;
  401.                         usort(self::$enabledObjectTypes, function($a, $b) {
  402.                                 $enabled = OIDplus::config()->getValue("objecttypes_enabled");
  403.                                 $enabled_ary = explode(';', $enabled);
  404.  
  405.                                 $idx_a = array_search($a::ns(), $enabled_ary);
  406.                                 $idx_b = array_search($b::ns(), $enabled_ary);
  407.  
  408.                                 if ($idx_a == $idx_b) {
  409.                                     return 0;
  410.                                 }
  411.                                 return ($idx_a > $idx_b) ? +1 : -1;
  412.                         });
  413.                 } else {
  414.                         self::$disabledObjectTypes[] = $ot;
  415.                 }
  416.  
  417.                 if (!in_array($ns, $init_ary)) {
  418.                         // Was never initialized before, so we add it to the list of enabled object types once
  419.  
  420.                         if ($do_enable) {
  421.                                 $enabled_ary[] = $ns;
  422.                                 OIDplus::config()->setValue("objecttypes_enabled", implode(';', $enabled_ary));
  423.                         }
  424.  
  425.                         $init_ary[] = $ns;
  426.                         OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
  427.                 }
  428.         }
  429.  
  430.         public static function getObjectTypePlugins() {
  431.                 return self::$objectTypePlugins;
  432.         }
  433.  
  434.         public static function getObjectTypePluginsEnabled() {
  435.                 $res = array();
  436.                 foreach (self::$objectTypePlugins as $plugin) {
  437.                         $ot = $plugin::getObjectTypeClassName();
  438.                         if (in_array($ot, self::$enabledObjectTypes)) $res[] = $plugin;
  439.                 }
  440.                 return $res;
  441.         }
  442.  
  443.         public static function getObjectTypePluginsDisabled() {
  444.                 $res = array();
  445.                 foreach (self::$objectTypePlugins as $plugin) {
  446.                         $ot = $plugin::getObjectTypeClassName();
  447.                         if (in_array($ot, self::$disabledObjectTypes)) $res[] = $plugin;
  448.                 }
  449.                 return $res;
  450.         }
  451.  
  452.         public static function getEnabledObjectTypes() {
  453.                 return self::$enabledObjectTypes;
  454.         }
  455.  
  456.         public static function getDisabledObjectTypes() {
  457.                 return self::$disabledObjectTypes;
  458.         }
  459.  
  460.         # --- Plugin handling functions
  461.  
  462.         public static function getAllPlugins()/*: array*/ {
  463.                 $res = array();
  464.                 $res = array_merge($res, self::$pagePlugins);
  465.                 $res = array_merge($res, self::$authPlugins);
  466.                 $res = array_merge($res, self::$loggerPlugins);
  467.                 $res = array_merge($res, self::$objectTypePlugins);
  468.                 $res = array_merge($res, self::$dbPlugins);
  469.                 $res = array_merge($res, self::$sqlSlangPlugins);
  470.                 $res = array_merge($res, self::$languagePlugins);
  471.                 return $res;
  472.         }
  473.  
  474.         public static function getPluginByOid($oid)/*: ?OIDplusPlugin*/ {
  475.                 $plugins = self::getAllPlugins();
  476.                 foreach ($plugins as $plugin) {
  477.                         if (oid_dotnotation_equal($plugin->getManifest()->getOid(), $oid)) {
  478.                                 return $plugin;
  479.                         }
  480.                 }
  481.                 return null;
  482.         }
  483.  
  484.         public static function getPluginByClassName($classname)/*: ?OIDplusPlugin*/ {
  485.                 $plugins = self::getAllPlugins();
  486.                 foreach ($plugins as $plugin) {
  487.                         if (get_class($plugin) === $classname) {
  488.                                 return $plugin;
  489.                         }
  490.                 }
  491.                 return null;
  492.         }
  493.  
  494.         public static function getAllPluginManifests($pluginFolderMask='*', $flat=true): array {
  495.                 $out = array();
  496.                 // Note: glob() will sort by default, so we do not need a page priority attribute.
  497.                 //       So you just need to use a numeric plugin directory prefix (padded).
  498.                 $ary = glob(OIDplus::basePath().'/plugins/'.$pluginFolderMask.'/'.'*'.'/manifest.xml');
  499.                 foreach ($ary as $ini) {
  500.                         if (!file_exists($ini)) continue;
  501.  
  502.                         $manifest = new OIDplusPluginManifest();
  503.                         $manifest->loadManifest($ini);
  504.  
  505.                         if ($flat) {
  506.                                 $out[] = $manifest;
  507.                         } else {
  508.                                 $plugintype_folder = basename(dirname(dirname($ini)));
  509.                                 $pluginname_folder = basename(dirname($ini));
  510.  
  511.                                 if (!isset($out[$plugintype_folder])) $out[$plugintype_folder] = array();
  512.                                 if (!isset($out[$plugintype_folder][$pluginname_folder])) $out[$plugintype_folder][$pluginname_folder] = array();
  513.                                 $out[$plugintype_folder][$pluginname_folder] = $manifest;
  514.                         }
  515.                 }
  516.                 return $out;
  517.         }
  518.  
  519.         public static function registerAllPlugins($pluginDirName, $expectedPluginClass, $registerCallback): array {
  520.                 $out = array();
  521.                 $ary = self::getAllPluginManifests($pluginDirName, false);
  522.                 $known_plugin_oids = array();
  523.                 foreach ($ary as $plugintype_folder => $bry) {
  524.                         foreach ($bry as $pluginname_folder => $cry) {
  525.                                 $class_name = $cry->getPhpMainClass();
  526.                                 if (!$class_name) {
  527.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous').': '._L('Manifest does not declare a PHP main class',$plugintype_folder,$pluginname_folder));
  528.                                 }
  529.                                 if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
  530.                                         continue;
  531.                                 }
  532.                                 if (!class_exists($class_name)) {
  533.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous').': '._L('Manifest declares PHP main class as "%1", but it could not be found',$plugintype_folder,$pluginname_folder,$class_name));
  534.                                 }
  535.                                 if (!is_subclass_of($class_name, $expectedPluginClass)) {
  536.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous').': '._L('Plugin main class "%1" is expected to be a subclass of "%2"',$plugintype_folder,$pluginname_folder,$class_name,$expectedPluginClass));
  537.                                 }
  538.                                 if (($class_name!=$cry->getTypeClass()) && (!is_subclass_of($class_name,$cry->getTypeClass()))) {
  539.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous').': '._L('Plugin main class "%1" is expected to be a subclass of "%2", according to type declared in manifest',$plugintype_folder,$pluginname_folder,$class_name,$cry->getTypeClass()));
  540.                                 }
  541.                                 if (($cry->getTypeClass()!=$expectedPluginClass) && (!is_subclass_of($cry->getTypeClass(),$expectedPluginClass))) {
  542.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous').': '._L('Class declared in manifest is "%1" does not fit expected class for this plugin type "%2"',$plugintype_folder,$pluginname_folder,$cry->getTypeClass(),$expectedPluginClass));
  543.                                 }
  544.  
  545.                                 $plugin_oid = $cry->getOid();
  546.                                 if (!$plugin_oid) {
  547.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous').': '._L('Does not have an OID',$plugintype_folder,$pluginname_folder));
  548.                                 }
  549.                                 if (!oid_valid_dotnotation($plugin_oid, false, false, 2)) {
  550.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous').': '._L('Plugin OID "%1" is invalid (needs to be valid dot-notation)',$plugintype_folder,$pluginname_folder,$plugin_oid));
  551.                                 }
  552.                                 if (isset($known_plugin_oids[$plugin_oid])) {
  553.                                         throw new OIDplusException(_L('Plugin "%1/%2" is erroneous').': '._L('The OID "%1" is already used by the plugin "%2"',$plugintype_folder,$pluginname_folder,$plugin_oid,$known_plugin_oids[$plugin_oid]));
  554.                                 } else {
  555.                                         $known_plugin_oids[$plugin_oid] = $plugintype_folder.'/'.$pluginname_folder;
  556.                                 }
  557.  
  558.                                 $out[] = $class_name;
  559.                                 if (!is_null($registerCallback)) {
  560.                                         call_user_func($registerCallback, new $class_name());
  561.                                 }
  562.                         }
  563.  
  564.                 }
  565.                 return $out;
  566.         }
  567.  
  568.         # --- Initialization of OIDplus
  569.  
  570.         public static function init($html=true, $keepBaseConfig=true) {
  571.                 self::$html = $html;
  572.  
  573.                 // Reset internal state, so we can re-init verything if required
  574.  
  575.                 if (self::$old_config_format) {
  576.                         // Note: This can only happen in very special cases (e.g. test cases) where you call init() twice
  577.                         throw new OIDplusConfigInitializationException(_L('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.'));
  578.                 }
  579.  
  580.                 self::$config = null;
  581.                 if (!$keepBaseConfig) self::$baseConfig = null;  // for test cases we need to be able to control base config and setting values manually, so $keepBaseConfig needs to be true
  582.                 self::$gui = null;
  583.                 self::$authUtils = null;
  584.                 self::$mailUtils = null;
  585.                 self::$menuUtils = null;
  586.                 self::$logger = null;
  587.                 self::$sesHandler = null;
  588.                 self::$dbMainSession = null;
  589.                 self::$dbIsolatedSession = null;
  590.                 self::$pagePlugins = array();
  591.                 self::$authPlugins = array();
  592.                 self::$loggerPlugins = array();
  593.                 self::$objectTypePlugins = array();
  594.                 self::$enabledObjectTypes = array();
  595.                 self::$disabledObjectTypes = array();
  596.                 self::$dbPlugins = array();
  597.                 self::$sqlSlangPlugins = array();
  598.                 self::$languagePlugins = array();
  599.                 self::$system_id_cache = null;
  600.                 self::$sslAvailableCache = null;
  601.  
  602.                 // Continue...
  603.  
  604.                 OIDplus::baseConfig(); // this loads the base configuration located in userdata/baseconfig/config.inc.php (once!)
  605.                                        // You can do changes to the configuration afterwards using OIDplus::baseConfig()->...
  606.  
  607.                 // Register database types (highest priority)
  608.  
  609.                 // SQL slangs
  610.  
  611.                 self::registerAllPlugins('sqlSlang', 'OIDplusSqlSlangPlugin', array('OIDplus','registerSqlSlangPlugin'));
  612.                 foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
  613.                         $plugin->init($html);
  614.                 }
  615.  
  616.                 // Database providers
  617.  
  618.                 self::registerAllPlugins('database', 'OIDplusDatabasePlugin', array('OIDplus','registerDatabasePlugin'));
  619.                 foreach (OIDplus::getDatabasePlugins() as $plugin) {
  620.                         $plugin->init($html);
  621.                 }
  622.  
  623.                 // Do redirect stuff etc.
  624.  
  625.                 self::isSslAvailable(); // This function does automatic redirects
  626.  
  627.                 // Construct the configuration manager
  628.  
  629.                 OIDplus::config(); // During the construction, various system settings are prepared if required
  630.  
  631.                 // Initialize public / private keys
  632.  
  633.                 OIDplus::getPkiStatus(true);
  634.  
  635.                 // Register non-DB plugins
  636.  
  637.                 self::registerAllPlugins('*Pages', 'OIDplusPagePlugin', array('OIDplus','registerPagePlugin'));
  638.                 self::registerAllPlugins('auth', 'OIDplusAuthPlugin', array('OIDplus','registerAuthPlugin'));
  639.                 self::registerAllPlugins('logger', 'OIDplusLoggerPlugin', array('OIDplus','registerLoggerPlugin'));
  640.                 self::registerAllPlugins('objectTypes', 'OIDplusObjectTypePlugin', array('OIDplus','registerObjectTypePlugin'));
  641.                 self::registerAllPlugins('language', 'OIDplusLanguagePlugin', array('OIDplus','registerLanguagePlugin'));
  642.  
  643.                 // Initialize non-DB plugins
  644.  
  645.                 foreach (OIDplus::getPagePlugins() as $plugin) {
  646.                         $plugin->init($html);
  647.                 }
  648.                 foreach (OIDplus::getAuthPlugins() as $plugin) {
  649.                         $plugin->init($html);
  650.                 }
  651.                 foreach (OIDplus::getLoggerPlugins() as $plugin) {
  652.                         $plugin->init($html);
  653.                 }
  654.                 foreach (OIDplus::getObjectTypePlugins() as $plugin) {
  655.                         $plugin->init($html);
  656.                 }
  657.                 foreach (OIDplus::getLanguagePlugins() as $plugin) {
  658.                         $plugin->init($html);
  659.                 }
  660.         }
  661.  
  662.         # --- System URL, System ID, PKI, and other functions
  663.  
  664.         public static function basePath() {
  665.                 return realpath(__DIR__ . '/../../');
  666.         }
  667.  
  668.         public static function getSystemUrl($relative=false) {
  669.                 if (!$relative) {
  670.                         $res = OIDplus::baseConfig()->getValue('EXPLICIT_ABSOLUTE_SYSTEM_URL', '');
  671.                         if ($res !== '') {
  672.                                 try {
  673.                                         OIDplus::config()->setValue('last_known_system_url', $res);
  674.                                         return $res;
  675.                                 } catch (Exception $e) {
  676.                                 }
  677.                         }
  678.                 }
  679.  
  680.                 if (!isset($_SERVER["SCRIPT_NAME"])) return false;
  681.  
  682.                 $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
  683.                 $test_dir = str_replace('\\', '/', $test_dir);
  684.                 $c = 0;
  685.                 while (!file_exists($test_dir.'/oidplus_base.js')) {
  686.                         $test_dir = dirname($test_dir);
  687.                         $c++;
  688.                         if ($c == 1000) return false;
  689.                 }
  690.  
  691.                 $res = dirname($_SERVER['SCRIPT_NAME'].'xxx');
  692.  
  693.                 for ($i=1; $i<=$c; $i++) {
  694.                         $res = dirname($res);
  695.                 }
  696.  
  697.                 $res = str_replace('\\', '/', $res);
  698.                 if ($res == '/') $res = '';
  699.                 $res .= '/';
  700.  
  701.                 if (!$relative) {
  702.                         if (php_sapi_name() == 'cli') {
  703.                                 try {
  704.                                         return OIDplus::config()->getValue('last_known_system_url', false);
  705.                                 } catch (Exception $e) {
  706.                                 }
  707.                         }
  708.  
  709.                         $is_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
  710.                         $protocol = $is_ssl ? 'https' : 'http'; // do not translate
  711.                         $host = $_SERVER['HTTP_HOST']; // includes port if it is not 80/443
  712.                         $res = $protocol.'://'.$host.$res;
  713.  
  714.                         try {
  715.                                 OIDplus::config()->setValue('last_known_system_url', $res);
  716.                         } catch (Exception $e) {
  717.                         }
  718.                 }
  719.  
  720.                 return $res;
  721.         }
  722.  
  723.         private static $system_id_cache = null;
  724.         public static function getSystemId($oid=false) {
  725.                 if (!is_null(self::$system_id_cache)) {
  726.                         $out = self::$system_id_cache;
  727.                 } else {
  728.                         $out = false;
  729.  
  730.                         if (self::getPkiStatus(true)) {
  731.                                 $pubKey = OIDplus::config()->getValue('oidplus_public_key');
  732.                                 $m = array();
  733.                                 if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
  734.                                         $out = smallhash(base64_decode($m[1]));
  735.                                 }
  736.                         }
  737.                         self::$system_id_cache = $out;
  738.                 }
  739.                 if (!$out) return false;
  740.                 return ($oid ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
  741.         }
  742.  
  743.         public static function getPkiStatus($try_generate=true) {
  744.                 if (!function_exists('openssl_pkey_new')) return false;
  745.  
  746.                 $privKey = OIDplus::config()->getValue('oidplus_private_key');
  747.                 $pubKey = OIDplus::config()->getValue('oidplus_public_key');
  748.  
  749.                 if ($try_generate && !verify_private_public_key($privKey, $pubKey)) {
  750.                         $pkey_config = array(
  751.                             "digest_alg" => "sha512",
  752.                             "private_key_bits" => 2048,
  753.                             "private_key_type" => OPENSSL_KEYTYPE_RSA,
  754.                         );
  755.  
  756.                         // Create the private and public key
  757.                         $res = openssl_pkey_new($pkey_config);
  758.  
  759.                         if (!$res) return false;
  760.  
  761.                         // Extract the private key from $res to $privKey
  762.                         openssl_pkey_export($res, $privKey);
  763.  
  764.                         // Extract the public key from $res to $pubKey
  765.                         $pubKey = openssl_pkey_get_details($res)["key"];
  766.  
  767.                         // Log
  768.                         OIDplus::logger()->log("[INFO]A!", "Generating new SystemID using a new key pair");
  769.  
  770.                         // Save the key pair to database
  771.                         OIDplus::config()->setValue('oidplus_private_key', $privKey);
  772.                         OIDplus::config()->setValue('oidplus_public_key', $pubKey);
  773.  
  774.                         // Log the new system ID
  775.                         $m = array();
  776.                         if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
  777.                                 $system_id = smallhash(base64_decode($m[1]));
  778.                                 OIDplus::logger()->log("[INFO]A!", "Your SystemID is now $system_id");
  779.                         }
  780.                 }
  781.  
  782.                 return verify_private_public_key($privKey, $pubKey);
  783.         }
  784.  
  785.         public static function getInstallType() {
  786.                 if (!file_exists(OIDplus::basePath().'/oidplus_version.txt') && !is_dir(OIDplus::basePath().'/.svn')) {
  787.                         return 'unknown'; // do not translate
  788.                 }
  789.                 if (file_exists(OIDplus::basePath().'/oidplus_version.txt') && is_dir(OIDplus::basePath().'/.svn')) {
  790.                         return 'ambigous'; // do not translate
  791.                 }
  792.                 if (is_dir(OIDplus::basePath().'/.svn')) {
  793.                         return 'svn-wc'; // do not translate
  794.                 }
  795.                 if (file_exists(OIDplus::basePath().'/oidplus_version.txt')) {
  796.                         return 'svn-snapshot'; // do not translate
  797.                 }
  798.         }
  799.  
  800.         public static function getVersion() {
  801.                 if (file_exists(OIDplus::basePath().'/oidplus_version.txt') && is_dir(OIDplus::basePath().'/.svn')) {
  802.                         return false; // version is ambiguous
  803.                 }
  804.  
  805.                 if (is_dir(OIDplus::basePath().'/.svn')) {
  806.                         // Try to get the version via SQLite3
  807.                         if (class_exists('SQLite3')) {
  808.                                 try {
  809.                                         $db = new SQLite3(OIDplus::basePath().'/.svn/wc.db');
  810.                                         $results = $db->query('SELECT MIN(revision) AS rev FROM NODES_BASE');
  811.                                         while ($row = $results->fetchArray()) {
  812.                                                 return 'svn-'.$row['rev']; // do not translate
  813.                                         }
  814.                                         $db->close();
  815.                                         $db = null;
  816.                                 } catch (Exception $e) {
  817.                                 }
  818.                         }
  819.                         if (class_exists('PDO')) {
  820.                                 try {
  821.                                         $pdo = new PDO('sqlite:' . OIDplus::basePath().'/.svn/wc.db');
  822.                                         $res = $pdo->query('SELECT MIN(revision) AS rev FROM NODES_BASE');
  823.                                         $row = $res->fetch();
  824.                                         if ($row !== false) return 'svn-'.$row['rev']; // do not translate
  825.                                         $pdo = null;
  826.                                 } catch (Exception $e) {
  827.                                 }
  828.                         }
  829.  
  830.                         // Try to find out the SVN version using the shell
  831.                         // We don't prioritize this method, because a failed shell access will flood the apache error log with STDERR messages
  832.                         $output = @shell_exec('svnversion '.escapeshellarg(OIDplus::basePath()));
  833.                         $match = array();
  834.                         if (preg_match('/\d+/', $output, $match)) {
  835.                                 return 'svn-'.$match[0]; // do not translate
  836.                         }
  837.  
  838.                         $output = @shell_exec('svn info '.escapeshellarg(OIDplus::basePath()));
  839.                         if (preg_match('/Revision:\s*(\d+)/m', $output, $match)) { // do not translate
  840.                                 return 'svn-'.$match[1]; // do not translate
  841.                         }
  842.                 }
  843.  
  844.                 if (file_exists(OIDplus::basePath().'/oidplus_version.txt')) {
  845.                         $cont = file_get_contents(OIDplus::basePath().'/oidplus_version.txt');
  846.                         $m = array();
  847.                         if (preg_match('@Revision (\d+)@', $cont, $m)) // do not translate
  848.                                 return 'svn-'.$m[1]; // do not translate
  849.                 }
  850.  
  851.                 return false;
  852.         }
  853.  
  854.         private static $sslAvailableCache = null;
  855.         public static function isSslAvailable() {
  856.                 if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
  857.  
  858.                 if (php_sapi_name() == 'cli') {
  859.                         self::$sslAvailableCache = false;
  860.                         return false;
  861.                 }
  862.  
  863.                 $timeout = 2;
  864.                 $already_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == "on");
  865.                 $ssl_port = 443;
  866.                 $cookie_path = OIDplus::getSystemUrl(true);
  867.                 if (empty($cookie_path)) $cookie_path = '/';
  868.  
  869.                 $mode = OIDplus::baseConfig()->getValue('ENFORCE_SSL', 2/*auto*/);
  870.  
  871.                 if ($mode == 0) {
  872.                         // No SSL available
  873.                         self::$sslAvailableCache = $already_ssl;
  874.                         return $already_ssl;
  875.                 }
  876.  
  877.                 if ($mode == 1) {
  878.                         // Force SSL
  879.                         if ($already_ssl) {
  880.                                 self::$sslAvailableCache = true;
  881.                                 return true;
  882.                         } else {
  883.                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  884.                                 header('Location:'.$location);
  885.                                 die(_L('Redirecting to HTTPS...'));
  886.                                 self::$sslAvailableCache = true;
  887.                                 return true;
  888.                         }
  889.                 }
  890.  
  891.                 if ($mode == 2) {
  892.                         // Automatic SSL detection
  893.  
  894.                         if ($already_ssl) {
  895.                                 // we are already on HTTPS
  896.                                 setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
  897.                                 self::$sslAvailableCache = true;
  898.                                 return true;
  899.                         } else {
  900.                                 if (isset($_COOKIE['SSL_CHECK'])) {
  901.                                         // We already had the HTTPS detection done before.
  902.                                         if ($_COOKIE['SSL_CHECK']) {
  903.                                                 // HTTPS was detected before, but we are HTTP. Redirect now
  904.                                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  905.                                                 header('Location:'.$location);
  906.                                                 die(_L('Redirecting to HTTPS...'));
  907.                                                 self::$sslAvailableCache = true;
  908.                                                 return true;
  909.                                         } else {
  910.                                                 // No HTTPS available. Do nothing.
  911.                                                 self::$sslAvailableCache = false;
  912.                                                 return false;
  913.                                         }
  914.                                 } else {
  915.                                         // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
  916.                                         $errno = -1;
  917.                                         $errstr = '';
  918.                                         if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
  919.                                                 // HTTPS detected. Redirect now, and remember that we had detected HTTPS
  920.                                                 setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
  921.                                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  922.                                                 header('Location:'.$location);
  923.                                                 die(_L('Redirecting to HTTPS...'));
  924.                                                 self::$sslAvailableCache = true;
  925.                                                 return true;
  926.                                         } else {
  927.                                                 // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
  928.                                                 setcookie('SSL_CHECK', '0', 0, $cookie_path, '', false, true);
  929.                                                 self::$sslAvailableCache = false;
  930.                                                 return false;
  931.                                         }
  932.                                 }
  933.                         }
  934.                 }
  935.         }
  936.  
  937.         public static function webpath($target) {
  938.                 $dir = __DIR__;
  939.                 $dir = dirname($dir);
  940.                 $dir = dirname($dir);
  941.                 $target = substr($target, strlen($dir)+1, strlen($target)-strlen($dir)-1);
  942.                 if ($target != '') {
  943.                         $target = str_replace('\\','/',$target).'/';
  944.                 }
  945.                 return $target;
  946.         }
  947.  
  948.         public static function getAvailableLangs() {
  949.                 $langs = array();
  950.                 foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
  951.                         $xmldata = $pluginManifest->getRawXml();
  952.                         $code = $xmldata->language->code->__toString();
  953.                         $langs[] = $code;
  954.                 }
  955.                 return $langs;
  956.         }
  957.  
  958.         public static function getCurrentLang() {
  959.                 if (isset($_GET['lang'])) {
  960.                         $lang = $_GET['lang'];
  961.                 } else if (isset($_POST['lang'])) {
  962.                         $lang = $_POST['lang'];
  963.                 } else if (isset($_COOKIE['LANGUAGE'])) {
  964.                         $lang = $_COOKIE['LANGUAGE'];
  965.                 } else {
  966.                         $lang = self::DEFAULT_LANGUAGE;
  967.                 }
  968.                 $lang = substr(preg_replace('@[^a-z]@ismU', '', $lang),0,4); // sanitize
  969.                 return $lang;
  970.         }
  971.  
  972.         public static function handleLangArgument() {
  973.                 if (isset($_GET['lang'])) {
  974.                         // The "?lang=" argument is only for NoScript-Browsers/SearchEngines
  975.                         // In case someone who has JavaScript clicks a ?lang= link, they should get
  976.                         // the page in that language, but the cookie must be set, otherwise
  977.                         // the menu and other stuff would be in their cookie-based-language and not the
  978.                         // argument-based-language.
  979.                         $cookie_path = OIDplus::getSystemUrl(true);
  980.                         if (empty($cookie_path)) $cookie_path = '/';
  981.                         setcookie('LANGUAGE', $_GET['lang'], 0, $cookie_path, '', false, false/*HttpOnly off, because JavaScript also needs translation*/);
  982.                 } else if (isset($_POST['lang'])) {
  983.                         $cookie_path = OIDplus::getSystemUrl(true);
  984.                         if (empty($cookie_path)) $cookie_path = '/';
  985.                         setcookie('LANGUAGE', $_POST['lang'], 0, $cookie_path, '', false, false/*HttpOnly off, because JavaScript also needs translation*/);
  986.                 }
  987.         }
  988.  
  989.         public static function getTranslationArray() {
  990.                 $translation_array = array();
  991.                 foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
  992.                         $xmldata = $pluginManifest->getRawXml();
  993.                         $lang = $xmldata->language->code->__toString();
  994.                         $translation_array[$lang] = array();
  995.                         if (strpos($lang,'/') !== false) continue; // just to be sure
  996.                         if (strpos($lang,'\\') !== false) continue; // just to be sure
  997.                         if (strpos($lang,'..') !== false) continue; // just to be sure
  998.                         $translation_file = __DIR__.'/../../plugins/language/'.$lang.'/messages.xml';
  999.                         if (!file_exists($translation_file)) continue;
  1000.                         $xml = @simplexml_load_string(file_get_contents($translation_file));
  1001.                         if (!$xml) continue; // if there is an UTF-8 or parsing error, don't output any errors, otherwise the JavaScript is corrupt and the page won't render correctly
  1002.                         foreach ($xml->message as $msg) {
  1003.                                 $src = trim($msg->source->__toString());
  1004.                                 $dst = trim($msg->target->__toString());
  1005.                                 $translation_array[$lang][$src] = $dst;
  1006.                         }
  1007.                 }
  1008.                 return $translation_array;
  1009.         }
  1010.  
  1011. }
  1012.