Subversion Repositories oidplus

Rev

Rev 148 | Rev 159 | 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. if (!defined('IN_OIDPLUS')) die();
  21.  
  22. class OIDplus {
  23.         private static /*OIDplusPagePlugin[][]*/ $pagePlugins = array();
  24.         private static /*OIDplusObject[]*/ $objectTypes = array();
  25.         private static /*OIDplusObject[]*/ $disabledObjectTypes = array();
  26.         private static /*OIDplusDatabase[]*/ $dbPlugins = array();
  27.  
  28.         private function __construct() {
  29.         }
  30.  
  31.         public static function db() {
  32.                 if (!isset(self::$dbPlugins[OIDPLUS_DATABASE_PLUGIN])) {
  33.                         throw new Exception("Database plugin '".htmlentities(OIDPLUS_DATABASE_PLUGIN)."' not found. Please check config.inc.php or run <a href=\"setup/\">setup</a> again.");
  34.                 }
  35.                 $obj = self::$dbPlugins[OIDPLUS_DATABASE_PLUGIN];
  36.                 if (!$obj->isConnected()) $obj->connect();
  37.                 return $obj;
  38.         }
  39.  
  40.         public static function config() {
  41.                 static $config = null;
  42.                 if (is_null($config)) {
  43.                         $config = new OIDplusConfig();
  44.                 }
  45.                 return $config;
  46.         }
  47.  
  48.         public static function gui() {
  49.                 static $gui = null;
  50.                 if (is_null($gui)) {
  51.                         $gui = new OIDplusGui();
  52.                 }
  53.                 return $gui;
  54.         }
  55.  
  56.         public static function authUtils() {
  57.                 static $authUtils = null;
  58.                 if (is_null($authUtils)) {
  59.                         $authUtils = new OIDplusAuthUtils();
  60.                 }
  61.                 return $authUtils;
  62.         }
  63.  
  64.         public static function logger() {
  65.                 static $logger = null;
  66.                 if (is_null($logger)) {
  67.                         $logger = new OIDplusLogger();
  68.                 }
  69.                 return $logger;
  70.         }
  71.  
  72.         public static function sesHandler() {
  73.                 static $sesHandler = null;
  74.                 if (is_null($sesHandler)) {
  75.                         $sesHandler = new OIDplusSessionHandler(OIDPLUS_SESSION_SECRET);
  76.                 }
  77.                 return $sesHandler;
  78.         }
  79.  
  80.         public static function system_url($relative=false) {
  81.                 if (!isset($_SERVER["REQUEST_URI"])) return false;
  82.  
  83.                 $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
  84.                 $c = 0;
  85.                 while (!file_exists($test_dir.'/oidplus.js')) {
  86.                         $test_dir = dirname($test_dir);
  87.                         $c++;
  88.                         if ($c == 1000) return false;
  89.                 }
  90.  
  91.                 $res = dirname($_SERVER['REQUEST_URI'].'xxx');
  92.  
  93.                 for ($i=1; $i<=$c; $i++) {
  94.                         $res = dirname($res);
  95.                 }
  96.  
  97.                 $res .= '/';
  98.  
  99.                 if (!$relative) {
  100.                         $res = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . $res; // TODO: also add port?
  101.                 }
  102.  
  103.                 return $res;
  104.         }
  105.  
  106.         public static function registerDatabasePlugin(OIDplusDatabase $plugin) {
  107.                 $name = $plugin->name();
  108.                 if ($name === false) return false;
  109.  
  110.                 self::$dbPlugins[$name] = $plugin;
  111.  
  112.                 return true;
  113.         }
  114.  
  115.         public static function getDatabasePlugins() {
  116.                 return self::$dbPlugins;
  117.         }
  118.  
  119.         public static function registerPagePlugin(OIDplusPagePlugin $plugin) {
  120.                 $type = $plugin->type();
  121.                 if ($type === false) return false;
  122.  
  123.                 $prio = $plugin->priority();
  124.                 if ($prio === false) return false;
  125.  
  126.                 if (!isset(self::$pagePlugins[$type])) self::$pagePlugins[$type] = array();
  127.                 self::$pagePlugins[$type][$prio] = $plugin;
  128.  
  129.                 return true;
  130.         }
  131.  
  132.         public static function getPagePlugins($type) {
  133.                 if ($type == '*') {
  134.                         $res = array();
  135.                         foreach (self::$pagePlugins as $data) {
  136.                                 $res = array_merge($res, $data);
  137.                         }
  138.                 } else {
  139.                         $res = isset(self::$pagePlugins[$type]) ? self::$pagePlugins[$type] : array();
  140.                 }
  141.                 ksort($res);
  142.                 return $res;
  143.         }
  144.  
  145.         public static function registerObjectType($ot) {
  146.                 $ns = $ot::ns();
  147.  
  148.                 if (empty($ns)) die("Attention: Empty NS at $ot\n");
  149.  
  150.                 $ns_found = false;
  151.                 foreach (OIDplus::getRegisteredObjectTypes() as $test_ot) {
  152.                         if ($test_ot::ns() == $ns) {
  153.                                 $ns_found = true;
  154.                                 break;
  155.                         }
  156.                 }
  157.                 if ($ns_found) {
  158.                         throw new Exception("Attention: Two objectType plugins use the same namespace \"$ns\"!");
  159.                 }
  160.  
  161.                 $init = OIDplus::config()->getValue("objecttypes_initialized");
  162.                 $init_ary = empty($init) ? array() : explode(';', $init);
  163.                 $init_ary = array_map('trim', $init_ary);
  164.  
  165.                 $enabled = OIDplus::config()->getValue("objecttypes_enabled");
  166.                 $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
  167.                 $enabled_ary = array_map('trim', $enabled_ary);
  168.  
  169.                 $do_enable = false;
  170.                 if (in_array($ns, $enabled_ary)) {
  171.                         $do_enable = true;
  172.                 } else {
  173.                         if (!OIDplus::config()->getValue('registration_done')) {
  174.                                 $do_enable = $ns == 'oid';
  175.                         } else {
  176.                                 $do_enable = !in_array($ns, $init_ary);
  177.                         }
  178.                 }
  179.  
  180.                 if ($do_enable) {
  181.                         self::$objectTypes[] = $ot;
  182.                         usort(self::$objectTypes, function($a, $b) {
  183.                                 $enabled = OIDplus::config()->getValue("objecttypes_enabled");
  184.                                 $enabled_ary = explode(';', $enabled);
  185.  
  186.                                 $idx_a = array_search($a::ns(), $enabled_ary);
  187.                                 $idx_b = array_search($b::ns(), $enabled_ary);
  188.  
  189.                                 if ($idx_a == $idx_b) {
  190.                                     return 0;
  191.                                 }
  192.                                 return ($idx_a > $idx_b) ? +1 : -1;
  193.                         });
  194.                 } else {
  195.                         self::$disabledObjectTypes[] = $ot;
  196.                 }
  197.  
  198.                 if (!in_array($ns, $init_ary)) {
  199.                         // Was never initialized before, so we add it to the list of enabled object types once
  200.  
  201.                         if ($do_enable) {
  202.                                 $enabled_ary[] = $ns;
  203.                                 OIDplus::config()->setValue("objecttypes_enabled", implode(';', $enabled_ary));
  204.                         }
  205.  
  206.                         $init_ary[] = $ns;
  207.                         OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
  208.                 }
  209.         }
  210.  
  211.         public static function getRegisteredObjectTypes() {
  212.                 return self::$objectTypes;
  213.         }
  214.  
  215.         public static function getDisabledObjectTypes() {
  216.                 return self::$disabledObjectTypes;
  217.         }
  218.  
  219.         private static $system_id_cache = null;
  220.         public static function system_id($oid=false) {
  221.                 if (!is_null(self::$system_id_cache)) {
  222.                         $out = self::$system_id_cache;
  223.                 } else {
  224.                         $out = false;
  225.  
  226.                         if (self::pkiStatus(true)) {
  227.                                 $pubKey = OIDplus::config()->getValue('oidplus_public_key');
  228.                                 if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
  229.                                         $out = smallhash(base64_decode($m[1]));
  230.                                 }
  231.                         }
  232.                         self::$system_id_cache = $out;
  233.                 }
  234.                 return ($oid ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
  235.         }
  236.  
  237.         public static function pkiStatus($try_generate=true) {
  238.                 if (!function_exists('openssl_pkey_new')) return false;
  239.  
  240.                 $privKey = OIDplus::config()->getValue('oidplus_private_key');
  241.                 $pubKey = OIDplus::config()->getValue('oidplus_public_key');
  242.  
  243.                 if ($try_generate && !verify_private_public_key($privKey, $pubKey)) {
  244.                         $config = array(
  245.                             "digest_alg" => "sha512",
  246.                             "private_key_bits" => 2048,
  247.                             "private_key_type" => OPENSSL_KEYTYPE_RSA,
  248.                         );
  249.  
  250.                         // Create the private and public key
  251.                         $res = openssl_pkey_new($config);
  252.  
  253.                         // Extract the private key from $res to $privKey
  254.                         openssl_pkey_export($res, $privKey);
  255.  
  256.                         OIDplus::config()->setValue('oidplus_private_key', $privKey);
  257.  
  258.                         // Extract the public key from $res to $pubKey
  259.                         $pubKey = openssl_pkey_get_details($res);
  260.                         $pubKey = $pubKey["key"];
  261.  
  262.                         OIDplus::config()->setValue('oidplus_public_key', $pubKey);
  263.                 }
  264.  
  265.                 return verify_private_public_key($privKey, $pubKey);
  266.         }
  267.  
  268.         public static function init($html=true) {
  269.                 define('OIDPLUS_HTML_OUTPUT', $html);
  270.  
  271.                 // Include config file
  272.  
  273.                 if (file_exists(__DIR__ . '/../config.inc.php')) {
  274.                         include_once __DIR__ . '/../config.inc.php';
  275.                 } else {
  276.                         if ($html) {
  277.                                 if (!is_dir('setup')) {
  278.                                         echo 'Error: Setup directory missing.';
  279.                                 } else {
  280.                                         header('Location:setup/');
  281.                                 }
  282.                         } else {
  283.                                 echo 'Error: Setup directory missing!';
  284.                         }
  285.                         die();
  286.                 }
  287.  
  288.                 // Auto-fill non-existing config values
  289.  
  290.                 if (!defined('OIDPLUS_CONFIG_VERSION'))   define('OIDPLUS_CONFIG_VERSION',   0.0);
  291.                 if (!defined('OIDPLUS_ADMIN_PASSWORD'))   define('OIDPLUS_ADMIN_PASSWORD',   '');
  292.                 if (!defined('OIDPLUS_DATABASE_PLUGIN'))  define('OIDPLUS_DATABASE_PLUGIN',  'MySQL');
  293.                 if (!defined('OIDPLUS_MYSQL_HOST'))       define('OIDPLUS_MYSQL_HOST',       'localhost');
  294.                 if (!defined('OIDPLUS_MYSQL_USERNAME'))   define('OIDPLUS_MYSQL_USERNAME',   'root');
  295.                 if (!defined('OIDPLUS_MYSQL_PASSWORD'))   define('OIDPLUS_MYSQL_PASSWORD',   ''); // base64 encoded
  296.                 if (!defined('OIDPLUS_MYSQL_DATABASE'))   define('OIDPLUS_MYSQL_DATABASE',   'oidplus');
  297.                 if (!defined('OIDPLUS_TABLENAME_PREFIX')) define('OIDPLUS_TABLENAME_PREFIX', '');
  298.                 if (!defined('OIDPLUS_SESSION_SECRET'))   define('OIDPLUS_SESSION_SECRET',   '');
  299.                 if (!defined('RECAPTCHA_ENABLED'))        define('RECAPTCHA_ENABLED',        false);
  300.                 if (!defined('RECAPTCHA_PUBLIC'))         define('RECAPTCHA_PUBLIC',         '');
  301.                 if (!defined('RECAPTCHA_PRIVATE'))        define('RECAPTCHA_PRIVATE',        '');
  302.                 if (!defined('OIDPLUS_ENFORCE_SSL'))      define('OIDPLUS_ENFORCE_SSL',      2 /* Auto */);
  303.  
  304.                 // Check version of the config file
  305.  
  306.                 if (OIDPLUS_CONFIG_VERSION != 2.0) {
  307.                         if ($html) {
  308.                                 echo '<h1>Error</h1><p>The information located in <b>includes/config.inc.php</b> is outdated.</p><p>Please run <a href="setup/">setup</a> again.</p>';
  309.                         } else {
  310.                                 echo 'The information located in includes/config.inc.php is outdated. Please run setup again.';
  311.                         }
  312.                         die();
  313.                 }
  314.  
  315.                 // Register database types (highest priority)
  316.  
  317.                 $ary = glob(__DIR__ . '/../../plugins/database/'.'*'.'/plugin.inc.php');
  318.                 foreach ($ary as $a) include $a;
  319.  
  320.                 // Do redirect stuff etc.
  321.  
  322.                 define('OIDPLUS_SSL_AVAILABLE', self::isSslAvailable());
  323.  
  324.                 // System config settings
  325.  
  326.                 OIDplus::config()->prepareConfigKey('objecttypes_initialized', 'List of object type plugins that were initialized once', '', 1, 1);
  327.                 OIDplus::config()->prepareConfigKey('objecttypes_enabled', 'Enabled object types and their order, separated with a semicolon (please reload the page so that the change is applied)', '', 0, 1);
  328.  
  329.                 OIDplus::config()->prepareConfigKey('oidplus_private_key', 'Private key for this system', '', 1, 0);
  330.                 OIDplus::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.', '', 1, 1);
  331.  
  332.                 // Initialize public / private keys
  333.  
  334.                 OIDplus::pkiStatus(true);
  335.  
  336.                 // Register plugins
  337.  
  338.                 $ary = glob(__DIR__ . '/../../plugins/objectTypes/'.'*'.'/*.class.php');
  339.                 foreach ($ary as $a) include $a;
  340.  
  341.                 $ary = glob(__DIR__ . '/../../plugins/publicPages/'.'*'.'/plugin.inc.php');
  342.                 foreach ($ary as $a) include $a;
  343.                 $ary = glob(__DIR__ . '/../../plugins/raPages/'.'*'.'/plugin.inc.php');
  344.                 foreach ($ary as $a) include $a;
  345.                 $ary = glob(__DIR__ . '/../../plugins/adminPages/'.'*'.'/plugin.inc.php');
  346.                 foreach ($ary as $a) include $a;
  347.  
  348.                 // Initialize plugins
  349.  
  350.                 foreach (OIDplus::getPagePlugins('*') as $plugin) {
  351.                         $plugin->init($html);
  352.                 }
  353.         }
  354.  
  355.         public static function getVersion() {
  356.                 $status = @shell_exec('svnversion '.realpath(__FILE__));
  357.                 if (preg_match('/\d+/', $status, $match)) {
  358.                         return 'svn-'.$match[0];
  359.                 } else {
  360.                         return false;
  361.                 }
  362.         }
  363.  
  364.         private static function isSslAvailable() {
  365.                 $timeout = 2;
  366.                 $already_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == "on");
  367.                 $ssl_port = 443;
  368.                 $cookie_path = OIDplus::system_url(true);
  369.                 if (empty($cookie_path)) $cookie_path = '/';
  370.  
  371.                 if (php_sapi_name() == 'cli') return false;
  372.  
  373.                 if (OIDPLUS_ENFORCE_SSL == 0) {
  374.                         // No SSL available
  375.                         return $already_ssl;
  376.                 }
  377.  
  378.                 if (OIDPLUS_ENFORCE_SSL == 1) {
  379.                         // Force SSL
  380.                         if ($already_ssl) {
  381.                                 return true;
  382.                         } else {
  383.                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  384.                                 header('Location:'.$location);
  385.                                 die('Redirect to HTTPS');
  386.                                 return true;
  387.                         }
  388.                 }
  389.  
  390.                 if (OIDPLUS_ENFORCE_SSL == 2) {
  391.                         // Automatic SSL detection
  392.  
  393.                         if ($already_ssl) {
  394.                                 // we are already on HTTPS
  395.                                 setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
  396.                                 return true;
  397.                         } else {
  398.                                 if (isset($_COOKIE['SSL_CHECK'])) {
  399.                                         // We already had the HTTPS detection done before.
  400.                                         if ($_COOKIE['SSL_CHECK']) {
  401.                                                 // HTTPS was detected before, but we are HTTP. Redirect now
  402.                                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  403.                                                 header('Location:'.$location);
  404.                                                 die('Redirect to HTTPS');
  405.                                                 return true;
  406.                                         } else {
  407.                                                 // No HTTPS available. Do nothing.
  408.                                                 return false;
  409.                                         }
  410.                                 } else {
  411.                                         // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
  412.                                         if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
  413.                                                 // HTTPS detected. Redirect now, and remember that we had detected HTTPS
  414.                                                 setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
  415.                                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  416.                                                 header('Location:'.$location);
  417.                                                 die('Redirect to HTTPS');
  418.                                                 return true;
  419.                                         } else {
  420.                                                 // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
  421.                                                 setcookie('SSL_CHECK', '0', 0, $cookie_path, '', false, true);
  422.                                                 return false;
  423.                                         }
  424.                                 }
  425.                         }
  426.                 }
  427.         }
  428. }
  429.