Subversion Repositories oidplus

Rev

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