Subversion Repositories oidplus

Rev

Rev 225 | Rev 228 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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