Subversion Repositories oidplus

Rev

Rev 228 | Rev 236 | 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 /*OIDplusAuthPlugin[][]*/ $authPlugins = array();
  25.         private static /*OIDplusObjectTypePlugin[]*/ $objectTypePlugins = array();
  26.         private static /*string[]*/ $enabledObjectTypes = array();
  27.         private static /*string[]*/ $disabledObjectTypes = array();
  28.         private static /*OIDplusDatabasePlugin[]*/ $dbPlugins = array();
  29.  
  30.         private function __construct() {
  31.         }
  32.  
  33.         # --- Singleton classes
  34.  
  35.         public static function config() {
  36.                 static $config = null;
  37.                 if (is_null($config)) {
  38.                         $config = new OIDplusConfig();
  39.                 }
  40.                 return $config;
  41.         }
  42.  
  43.         public static function gui() {
  44.                 static $gui = null;
  45.                 if (is_null($gui)) {
  46.                         $gui = new OIDplusGui();
  47.                 }
  48.                 return $gui;
  49.         }
  50.  
  51.         public static function authUtils() {
  52.                 static $authUtils = null;
  53.                 if (is_null($authUtils)) {
  54.                         $authUtils = new OIDplusAuthUtils();
  55.                 }
  56.                 return $authUtils;
  57.         }
  58.  
  59.         public static function logger() {
  60.                 static $logger = null;
  61.                 if (is_null($logger)) {
  62.                         $logger = new OIDplusLogger();
  63.                 }
  64.                 return $logger;
  65.         }
  66.  
  67.         public static function sesHandler() {
  68.                 static $sesHandler = null;
  69.                 if (is_null($sesHandler)) {
  70.                         $sesHandler = new OIDplusSessionHandler(OIDPLUS_SESSION_SECRET);
  71.                 }
  72.                 return $sesHandler;
  73.         }
  74.  
  75.         # --- Database plugin
  76.  
  77.         private static function registerDatabasePlugin(OIDplusDatabasePlugin $plugin) {
  78.                 $name = $plugin->name();
  79.                 if ($name === false) return false;
  80.  
  81.                 self::$dbPlugins[$name] = $plugin;
  82.  
  83.                 return true;
  84.         }
  85.  
  86.         public static function getDatabasePlugins() {
  87.                 return self::$dbPlugins;
  88.         }
  89.  
  90.         public static function db() {
  91.                 if (!isset(self::$dbPlugins[OIDPLUS_DATABASE_PLUGIN])) {
  92.                         throw new Exception("Database plugin '".htmlentities(OIDPLUS_DATABASE_PLUGIN)."' not found. Please check config.inc.php or run <a href=\"setup/\">setup</a> again.");
  93.                 }
  94.                 $obj = self::$dbPlugins[OIDPLUS_DATABASE_PLUGIN];
  95.                 if (!$obj->isConnected()) $obj->connect();
  96.                 return $obj;
  97.         }
  98.  
  99.         # --- Page plugin
  100.  
  101.         private static function registerPagePlugin(OIDplusPagePlugin $plugin) {
  102.                 $type = $plugin->type();
  103.                 if ($type === false) return false;
  104.  
  105.                 $prio = $plugin->priority();
  106.                 if ($prio === false) return false;
  107.  
  108.                 if (!isset(self::$pagePlugins[$type])) self::$pagePlugins[$type] = array();
  109.                 self::$pagePlugins[$type][$prio] = $plugin;
  110.  
  111.                 return true;
  112.         }
  113.  
  114.         public static function getPagePlugins($type='*') {
  115.                 if ($type === '*') {
  116.                         $res = array();
  117.                         foreach (self::$pagePlugins as $data) {
  118.                                 $res = array_merge($res, $data);
  119.                         }
  120.                 } else {
  121.                         $types = explode(',', $type);
  122.                         foreach ($types as $type) {
  123.                                 $res = isset(self::$pagePlugins[$type]) ? self::$pagePlugins[$type] : array();
  124.                         }
  125.                 }
  126.                 ksort($res);
  127.                 return $res;
  128.         }
  129.  
  130.         # --- Auth plugin
  131.  
  132.         private static function registerAuthPlugin(OIDplusAuthPlugin $plugin) {
  133.                 self::$authPlugins[] = $plugin;
  134.                 return true;
  135.         }
  136.  
  137.         public static function getAuthPlugins() {
  138.                 return self::$authPlugins;
  139.         }
  140.  
  141.         # --- Object type plugin
  142.  
  143.         private static function registerObjectTypePlugin(OIDplusObjectTypePlugin $plugin) {
  144.                 self::$objectTypePlugins[] = $plugin;
  145.  
  146.                 $ot = $plugin::getObjectTypeClassName();
  147.                 self::registerObjectType($ot);
  148.  
  149.                 return true;
  150.         }
  151.  
  152.         private static function registerObjectType($ot) {
  153.                 $ns = $ot::ns();
  154.  
  155.                 if (empty($ns)) die("Attention: Empty NS at $ot\n");
  156.  
  157.                 $ns_found = false;
  158.                 foreach (array_merge(OIDplus::getEnabledObjectTypes(), OIDplus::getDisabledObjectTypes()) as $test_ot) {
  159.                         if ($test_ot::ns() == $ns) {
  160.                                 $ns_found = true;
  161.                                 break;
  162.                         }
  163.                 }
  164.                 if ($ns_found) {
  165.                         throw new Exception("Attention: Two objectType plugins use the same namespace \"$ns\"!");
  166.                 }
  167.  
  168.                 $init = OIDplus::config()->getValue("objecttypes_initialized");
  169.                 $init_ary = empty($init) ? array() : explode(';', $init);
  170.                 $init_ary = array_map('trim', $init_ary);
  171.  
  172.                 $enabled = OIDplus::config()->getValue("objecttypes_enabled");
  173.                 $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
  174.                 $enabled_ary = array_map('trim', $enabled_ary);
  175.  
  176.                 $do_enable = false;
  177.                 if (in_array($ns, $enabled_ary)) {
  178.                         $do_enable = true;
  179.                 } else {
  180.                         if (!OIDplus::config()->getValue('registration_done')) {
  181.                                 $do_enable = $ns == 'oid';
  182.                         } else {
  183.                                 $do_enable = !in_array($ns, $init_ary);
  184.                         }
  185.                 }
  186.  
  187.                 if ($do_enable) {
  188.                         self::$enabledObjectTypes[] = $ot;
  189.                         usort(self::$enabledObjectTypes, function($a, $b) {
  190.                                 $enabled = OIDplus::config()->getValue("objecttypes_enabled");
  191.                                 $enabled_ary = explode(';', $enabled);
  192.  
  193.                                 $idx_a = array_search($a::ns(), $enabled_ary);
  194.                                 $idx_b = array_search($b::ns(), $enabled_ary);
  195.  
  196.                                 if ($idx_a == $idx_b) {
  197.                                     return 0;
  198.                                 }
  199.                                 return ($idx_a > $idx_b) ? +1 : -1;
  200.                         });
  201.                 } else {
  202.                         self::$disabledObjectTypes[] = $ot;
  203.                 }
  204.  
  205.                 if (!in_array($ns, $init_ary)) {
  206.                         // Was never initialized before, so we add it to the list of enabled object types once
  207.  
  208.                         if ($do_enable) {
  209.                                 $enabled_ary[] = $ns;
  210.                                 OIDplus::config()->setValue("objecttypes_enabled", implode(';', $enabled_ary));
  211.                         }
  212.  
  213.                         $init_ary[] = $ns;
  214.                         OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
  215.                 }
  216.         }
  217.  
  218.         public static function getObjectTypePlugins() {
  219.                 return self::$objectTypePlugins;
  220.         }
  221.  
  222.         public static function getObjectTypePluginsEnabled() {
  223.                 $res = array();
  224.                 foreach (self::$objectTypePlugins as $plugin) {
  225.                         $ot = $plugin::getObjectTypeClassName();
  226.                         if (in_array($ot, self::$enabledObjectTypes)) $res[] = $plugin;
  227.                 }
  228.                 return $res;
  229.         }
  230.  
  231.         public static function getObjectTypePluginsDisabled() {
  232.                 $res = array();
  233.                 foreach (self::$objectTypePlugins as $plugin) {
  234.                         $ot = $plugin::getObjectTypeClassName();
  235.                         if (in_array($ot, self::$disabledObjectTypes)) $res[] = $plugin;
  236.                 }
  237.                 return $res;
  238.         }
  239.  
  240.         public static function getEnabledObjectTypes() {
  241.                 return self::$enabledObjectTypes;
  242.         }
  243.  
  244.         public static function getDisabledObjectTypes() {
  245.                 return self::$disabledObjectTypes;
  246.         }
  247.  
  248.         # --- Initialization of OIDplus
  249.  
  250.         public static function init($html=true) {
  251.                 // Include config file
  252.  
  253.                 if (file_exists(__DIR__ . '/../config.inc.php')) {
  254.                         include_once __DIR__ . '/../config.inc.php';
  255.                 } else {
  256.                         if ($html) {
  257.                                 if (!is_dir('setup')) {
  258.                                         echo 'Error: Setup directory missing.';
  259.                                 } else {
  260.                                         header('Location:setup/');
  261.                                 }
  262.                         } else {
  263.                                 echo 'Error: Setup directory missing!';
  264.                         }
  265.                         die();
  266.                 }
  267.  
  268.                 // Auto-fill non-existing config values, so that there won't be any PHP errors
  269.                 // if something would be missing in config.inc.php (which should not happen!)
  270.  
  271.                 if (!defined('OIDPLUS_CONFIG_VERSION'))   define('OIDPLUS_CONFIG_VERSION',   0.0);
  272.                 if (!defined('OIDPLUS_ADMIN_PASSWORD'))   define('OIDPLUS_ADMIN_PASSWORD',   '');
  273.                 if (!defined('OIDPLUS_DATABASE_PLUGIN'))  define('OIDPLUS_DATABASE_PLUGIN',  'MySQL');
  274.                 if (!defined('OIDPLUS_MYSQL_HOST'))       define('OIDPLUS_MYSQL_HOST',       'localhost');
  275.                 if (!defined('OIDPLUS_MYSQL_USERNAME'))   define('OIDPLUS_MYSQL_USERNAME',   'root');
  276.                 if (!defined('OIDPLUS_MYSQL_PASSWORD'))   define('OIDPLUS_MYSQL_PASSWORD',   ''); // base64 encoded
  277.                 if (!defined('OIDPLUS_MYSQL_DATABASE'))   define('OIDPLUS_MYSQL_DATABASE',   'oidplus');
  278.                 if (!defined('OIDPLUS_TABLENAME_PREFIX')) define('OIDPLUS_TABLENAME_PREFIX', '');
  279.                 if (!defined('OIDPLUS_SESSION_SECRET'))   define('OIDPLUS_SESSION_SECRET',   '');
  280.                 if (!defined('RECAPTCHA_ENABLED'))        define('RECAPTCHA_ENABLED',        false);
  281.                 if (!defined('RECAPTCHA_PUBLIC'))         define('RECAPTCHA_PUBLIC',         '');
  282.                 if (!defined('RECAPTCHA_PRIVATE'))        define('RECAPTCHA_PRIVATE',        '');
  283.                 if (!defined('OIDPLUS_ENFORCE_SSL'))      define('OIDPLUS_ENFORCE_SSL',      2 /* Auto */);
  284.  
  285.                 // Check version of the config file
  286.  
  287.                 if (OIDPLUS_CONFIG_VERSION != 2.0) {
  288.                         if ($html) {
  289.                                 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>';
  290.                         } else {
  291.                                 echo 'The information located in includes/config.inc.php is outdated. Please run setup again.';
  292.                         }
  293.                         die();
  294.                 }
  295.  
  296.                 // Register database types (highest priority)
  297.  
  298.                 $ary = glob(__DIR__ . '/../../plugins/database/'.'*'.'/plugin.inc.php');
  299.                 foreach ($ary as $a) include $a;
  300.  
  301.                 foreach (get_declared_classes() as $c) {
  302.                         if (is_subclass_of($c, 'OIDplusDataBasePlugin')) {
  303.                                 self::registerDatabasePlugin(new $c());
  304.                         }
  305.                 }
  306.  
  307.                 // Do redirect stuff etc.
  308.  
  309.                 self::isSslAvailable(); // This function does automatic redirects
  310.  
  311.                 // System config settings
  312.  
  313.                 OIDplus::config()->prepareConfigKey('objecttypes_initialized', 'List of object type plugins that were initialized once', '', 1, 1);
  314.                 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);
  315.  
  316.                 OIDplus::config()->prepareConfigKey('oidplus_private_key', 'Private key for this system', '', 1, 0);
  317.                 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);
  318.  
  319.                 // Initialize public / private keys
  320.  
  321.                 OIDplus::getPkiStatus(true);
  322.  
  323.                 // Register other plugins
  324.  
  325.                 $ary = glob(__DIR__ . '/../../plugins/objectTypes/'.'*'.'/plugin.inc.php');
  326.                 foreach ($ary as $a) include $a;
  327.  
  328.                 $ary = glob(__DIR__ . '/../../plugins/publicPages/'.'*'.'/plugin.inc.php');
  329.                 foreach ($ary as $a) include $a;
  330.                 $ary = glob(__DIR__ . '/../../plugins/raPages/'.'*'.'/plugin.inc.php');
  331.                 foreach ($ary as $a) include $a;
  332.                 $ary = glob(__DIR__ . '/../../plugins/adminPages/'.'*'.'/plugin.inc.php');
  333.                 foreach ($ary as $a) include $a;
  334.  
  335.                 $ary = glob(__DIR__ . '/../../plugins/auth/'.'*'.'/plugin.inc.php');
  336.                 foreach ($ary as $a) include $a;
  337.  
  338.                 foreach (get_declared_classes() as $c) {
  339.                         if (is_subclass_of($c, 'OIDplusPagePlugin')) {
  340.                                 self::registerPagePlugin(new $c());
  341.                         }
  342.                         if (is_subclass_of($c, 'OIDplusAuthPlugin')) {
  343.                                 self::registerAuthPlugin(new $c());
  344.                         }
  345.                         if (is_subclass_of($c, 'OIDplusObjectTypePlugin')) {
  346.                                 self::registerObjectTypePlugin(new $c());
  347.                         }
  348.                 }
  349.  
  350.                 // Initialize plugins
  351.  
  352.                 foreach (OIDplus::getDatabasePlugins() as $plugin) {
  353.                         $plugin->init($html);
  354.                 }
  355.                 foreach (OIDplus::getPagePlugins('*') as $plugin) {
  356.                         $plugin->init($html);
  357.                 }
  358.                 foreach (OIDplus::getAuthPlugins() as $plugin) {
  359.                         $plugin->init($html);
  360.                 }
  361.                 foreach (OIDplus::getObjectTypePlugins() as $plugin) {
  362.                         $plugin->init($html);
  363.                 }
  364.         }
  365.  
  366.         # --- System URL, System ID, PKI, and other functions
  367.  
  368.         public static function getSystemUrl($relative=false) {
  369.                 if (!isset($_SERVER["SCRIPT_NAME"])) return false;
  370.  
  371.                 $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
  372.                 $c = 0;
  373.                 while (!file_exists($test_dir.'/oidplus_base.js')) {
  374.                         $test_dir = dirname($test_dir);
  375.                         $c++;
  376.                         if ($c == 1000) return false;
  377.                 }
  378.  
  379.                 $res = dirname($_SERVER['SCRIPT_NAME'].'xxx');
  380.  
  381.                 for ($i=1; $i<=$c; $i++) {
  382.                         $res = dirname($res);
  383.                 }
  384.  
  385.                 if ($res == '/') $res = '';
  386.                 $res .= '/';
  387.  
  388.                 if (!$relative) {
  389.                         $is_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
  390.                         $protocol = $is_ssl ? 'https' : 'http';
  391.                         $host = $_SERVER['HTTP_HOST'];
  392.                         $port = $_SERVER['SERVER_PORT'];
  393.                         if ($is_ssl && ($port != 443)) {
  394.                                 $port_add = ":$port";
  395.                         } else if (!$is_ssl && ($port != 80)) {
  396.                                 $port_add = ":$port";
  397.                         } else {
  398.                                 $port_add = "";
  399.                         }
  400.                         $res = $protocol.'://'.$host.$port_add.$res;
  401.                 }
  402.  
  403.                 return $res;
  404.         }
  405.  
  406.         private static $system_id_cache = null;
  407.         public static function getSystemId($oid=false) {
  408.                 if (!is_null(self::$system_id_cache)) {
  409.                         $out = self::$system_id_cache;
  410.                 } else {
  411.                         $out = false;
  412.  
  413.                         if (self::getPkiStatus(true)) {
  414.                                 $pubKey = OIDplus::config()->getValue('oidplus_public_key');
  415.                                 if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
  416.                                         $out = smallhash(base64_decode($m[1]));
  417.                                 }
  418.                         }
  419.                         self::$system_id_cache = $out;
  420.                 }
  421.                 return ($oid ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
  422.         }
  423.  
  424.         public static function getPkiStatus($try_generate=true) {
  425.                 if (!function_exists('openssl_pkey_new')) return false;
  426.  
  427.                 $privKey = OIDplus::config()->getValue('oidplus_private_key');
  428.                 $pubKey = OIDplus::config()->getValue('oidplus_public_key');
  429.  
  430.                 if ($try_generate && !verify_private_public_key($privKey, $pubKey)) {
  431.                         OIDplus::logger()->log("A!", "Generating new SystemID using a new key pair");
  432.  
  433.                         $config = array(
  434.                             "digest_alg" => "sha512",
  435.                             "private_key_bits" => 2048,
  436.                             "private_key_type" => OPENSSL_KEYTYPE_RSA,
  437.                         );
  438.  
  439.                         // Create the private and public key
  440.                         $res = openssl_pkey_new($config);
  441.  
  442.                         // Extract the private key from $res to $privKey
  443.                         openssl_pkey_export($res, $privKey);
  444.  
  445.                         // Extract the public key from $res to $pubKey
  446.                         $pubKey = openssl_pkey_get_details($res)["key"];
  447.  
  448.                         // Save the key pair to database
  449.                         OIDplus::config()->setValue('oidplus_private_key', $privKey);
  450.                         OIDplus::config()->setValue('oidplus_public_key', $pubKey);
  451.  
  452.                         // Log the new system ID
  453.                         if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
  454.                                 $system_id = smallhash(base64_decode($m[1]));
  455.                                 OIDplus::logger()->log("A!", "Your SystemID is now $system_id");
  456.                         }
  457.                 }
  458.  
  459.                 return verify_private_public_key($privKey, $pubKey);
  460.         }
  461.  
  462.         public static function getInstallType() {
  463.                 if (!file_exists(__DIR__ . '/../../oidplus_version.txt') && !is_dir(__DIR__ . '/../../.svn')) {
  464.                         return 'unknown';
  465.                 }
  466.                 if (file_exists(__DIR__ . '/../../oidplus_version.txt') && is_dir(__DIR__ . '/../../.svn')) {
  467.                         return 'ambigous';
  468.                 }
  469.                 if (is_dir(__DIR__ . '/../../.svn')) {
  470.                         return 'svn-wc';
  471.                 }
  472.                 if (file_exists(__DIR__ . '/../../oidplus_version.txt')) {
  473.                         return 'svn-snapshot';
  474.                 }
  475.         }
  476.  
  477.         public static function getVersion() {
  478.                 $svn_version = null;
  479.  
  480.                 if (file_exists(__DIR__ . '/../../oidplus_version.txt') && is_dir(__DIR__ . '/../../.svn')) {
  481.                         return false; // ambigous
  482.                 }
  483.  
  484.                 if (is_dir(__DIR__ . '/../../.svn')) {
  485.                         // Try to find out the SVN version using the shell
  486.                         $status = @shell_exec('svnversion '.realpath(__FILE__));
  487.                         if (preg_match('/\d+/', $status, $match)) {
  488.                                 $svn_version = 'svn-'.$match[0];
  489.                         }
  490.  
  491.                         // If that failed, try to get the version via SQLite3
  492.                         if (is_null($svn_version)) {
  493.                                 $db = new SQLite3(__DIR__ . '/../../.svn/wc.db');
  494.                                 $results = $db->query('SELECT MIN(revision) AS rev FROM NODES_BASE');
  495.                                 while ($row = $results->fetchArray()) {
  496.                                         $svn_version = 'svn-'.$row['rev'];
  497.                                 }
  498.                         }
  499.                 }
  500.  
  501.                 if (file_exists(__DIR__ . '/../../oidplus_version.txt')) {
  502.                         $cont = file_get_contents(__DIR__ . '/../../oidplus_version.txt');
  503.                         if (!preg_match('@Revision (\d+)@', $cont, $m))
  504.                                 return false; // File has unknown format
  505.                         $svn_version = 'svn-'.$m[1];
  506.                 }
  507.  
  508.                 return $svn_version;
  509.         }
  510.  
  511.         private static $sslAvailableCache = null;
  512.         public static function isSslAvailable() {
  513.                 if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
  514.        
  515.                 if (php_sapi_name() == 'cli') {
  516.                         self::$sslAvailableCache = false;
  517.                         return false;
  518.                 }
  519.  
  520.                 $timeout = 2;
  521.                 $already_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == "on");
  522.                 $ssl_port = 443;
  523.                 $cookie_path = OIDplus::getSystemUrl(true);
  524.                 if (empty($cookie_path)) $cookie_path = '/';
  525.  
  526.                 if (OIDPLUS_ENFORCE_SSL == 0) {
  527.                         // No SSL available
  528.                         self::$sslAvailableCache = $already_ssl;
  529.                         return $already_ssl;
  530.                 }
  531.  
  532.                 if (OIDPLUS_ENFORCE_SSL == 1) {
  533.                         // Force SSL
  534.                         if ($already_ssl) {
  535.                                 self::$sslAvailableCache = true;
  536.                                 return true;
  537.                         } else {
  538.                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  539.                                 header('Location:'.$location);
  540.                                 die('Redirect to HTTPS');
  541.                                 self::$sslAvailableCache = true;
  542.                                 return true;
  543.                         }
  544.                 }
  545.  
  546.                 if (OIDPLUS_ENFORCE_SSL == 2) {
  547.                         // Automatic SSL detection
  548.  
  549.                         if ($already_ssl) {
  550.                                 // we are already on HTTPS
  551.                                 setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
  552.                                 self::$sslAvailableCache = true;
  553.                                 return true;
  554.                         } else {
  555.                                 if (isset($_COOKIE['SSL_CHECK'])) {
  556.                                         // We already had the HTTPS detection done before.
  557.                                         if ($_COOKIE['SSL_CHECK']) {
  558.                                                 // HTTPS was detected before, but we are HTTP. Redirect now
  559.                                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  560.                                                 header('Location:'.$location);
  561.                                                 die('Redirect to HTTPS');
  562.                                                 self::$sslAvailableCache = true;
  563.                                                 return true;
  564.                                         } else {
  565.                                                 // No HTTPS available. Do nothing.
  566.                                                 self::$sslAvailableCache = false;
  567.                                                 return false;
  568.                                         }
  569.                                 } else {
  570.                                         // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
  571.                                         if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
  572.                                                 // HTTPS detected. Redirect now, and remember that we had detected HTTPS
  573.                                                 setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
  574.                                                 $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  575.                                                 header('Location:'.$location);
  576.                                                 die('Redirect to HTTPS');
  577.                                                 self::$sslAvailableCache = true;
  578.                                                 return true;
  579.                                         } else {
  580.                                                 // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
  581.                                                 setcookie('SSL_CHECK', '0', 0, $cookie_path, '', false, true);
  582.                                                 self::$sslAvailableCache = false;
  583.                                                 return false;
  584.                                         }
  585.                                 }
  586.                         }
  587.                 }
  588.         }
  589. }
  590.