Subversion Repositories oidplus

Rev

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