Subversion Repositories oidplus

Rev

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