Subversion Repositories oidplus

Rev

Rev 274 | Rev 277 | 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();
274 daniel-mar 29
        private static /*OIDplusSqlSlangPlugin[]*/ $sqlSlangPlugins = array();
2 daniel-mar 30
 
236 daniel-mar 31
        protected static $html = null;
32
 
2 daniel-mar 33
        private function __construct() {
34
        }
256 daniel-mar 35
 
263 daniel-mar 36
        # --- Static classes
274 daniel-mar 37
 
263 daniel-mar 38
        private static $baseConfig = null;
39
        private static $old_config_format = false;
261 daniel-mar 40
        public static function baseConfig() {
263 daniel-mar 41
                $first_init = false;
274 daniel-mar 42
 
263 daniel-mar 43
                if ($first_init = is_null(self::$baseConfig)) {
44
                        self::$baseConfig = new OIDplusBaseConfig();
261 daniel-mar 45
                }
46
 
263 daniel-mar 47
                if ($first_init) {
261 daniel-mar 48
                        // Include a file containing various size/depth limitations of OIDs
49
                        // It is important to include it before config.inc.php was included,
50
                        // so we can give config.inc.php the chance to override the values.
51
 
263 daniel-mar 52
                        include __DIR__ . '/../limits.inc.php';
261 daniel-mar 53
 
54
                        // Include config file
55
 
56
                        if (file_exists(__DIR__ . '/../config.inc.php')) {
263 daniel-mar 57
                                if (self::$old_config_format) {
58
                                        // Note: We may only include it once due to backwards compatibility,
59
                                        //       since in version 2.0, the configuration was defined using define() statements
60
                                        // Attention: This does mean that a full re-init (e.g. for test cases) is not possible
61
                                        //            if a version 2.0 config is used!
62
                                        include_once __DIR__ . '/../config.inc.php';
63
                                } else {
64
                                        include __DIR__ . '/../config.inc.php';
65
                                }
261 daniel-mar 66
 
67
                                if (defined('OIDPLUS_CONFIG_VERSION') && (OIDPLUS_CONFIG_VERSION == 2.0)) {
263 daniel-mar 68
                                        self::$old_config_format = true;
274 daniel-mar 69
 
261 daniel-mar 70
                                        // Backwards compatibility 2.0 => 2.1
71
                                        foreach (get_defined_constants(true)['user'] as $name => $value) {
72
                                                $name = str_replace('OIDPLUS_', '', $name);
73
                                                if ($name == 'SESSION_SECRET') $name = 'SERVER_SECRET';
74
                                                if ($name == 'MYSQL_QUERYLOG') $name = 'QUERY_LOGFILE';
75
                                                if (($name == 'MYSQL_PASSWORD') || ($name == 'ODBC_PASSWORD') || ($name == 'PDO_PASSWORD') || ($name == 'PGSQL_PASSWORD')) {
263 daniel-mar 76
                                                        self::$baseConfig->setValue($name, base64_decode($value));
261 daniel-mar 77
                                                } else {
78
                                                        if ($name == 'CONFIG_VERSION') $value = 2.1;
263 daniel-mar 79
                                                        self::$baseConfig->setValue($name, $value);
261 daniel-mar 80
                                                }
81
                                        }
82
                                }
83
                        } else {
84
                                if (!is_dir(__DIR__.'/../../setup')) {
85
                                        throw new OIDplusConfigInitializationException('File includes/config.inc.php is missing, but setup can\'t be started because its directory missing.');
86
                                } else {
87
                                        if ($html) {
88
                                                header('Location:'.OIDplus::getSystemUrl().'setup/');
89
                                                die('Redirecting to setup...');
90
                                        } else {
91
                                                // This can be displayed in e.g. ajax.php
92
                                                throw new OIDplusConfigInitializationException('File includes/config.inc.php is missing. Please run setup again.');
93
                                        }
94
                                }
95
                        }
96
 
97
                        // Check important config settings
98
 
263 daniel-mar 99
                        if (self::$baseConfig->getValue('CONFIG_VERSION') != 2.1) {
261 daniel-mar 100
                                throw new OIDplusConfigInitializationException("The information located in includes/config.inc.php is outdated.");
101
                        }
102
 
263 daniel-mar 103
                        if (self::$baseConfig->getValue('SERVER_SECRET', '') === '') {
261 daniel-mar 104
                                throw new OIDplusConfigInitializationException("You must set a value for SERVER_SECRET in includes/config.inc.php for the system to operate secure.");
105
                        }
106
                }
107
 
263 daniel-mar 108
                return self::$baseConfig;
261 daniel-mar 109
        }
110
 
263 daniel-mar 111
        private static $config = null;
2 daniel-mar 112
        public static function config() {
263 daniel-mar 113
                if ($first_init = is_null(self::$config)) {
114
                        self::$config = new OIDplusConfig();
2 daniel-mar 115
                }
263 daniel-mar 116
 
117
                if ($first_init) {
118
                        // These are important settings for base functionalities and therefore are not inside plugins
119
                        self::$config->prepareConfigKey('system_title', 'What is the name of your RA?', 'OIDplus 2.0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
120
                                if (empty($value)) {
121
                                        throw new OIDplusException("Please enter a value for the system title.");
122
                                }
123
                        });
124
                        self::$config->prepareConfigKey('admin_email', 'E-Mail address of the system administrator', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
125
                                if (!empty($value) && !OIDplus::mailUtils()->validMailAddress($value)) {
126
                                        throw new OIDplusException("This is not a correct email address");
127
                                }
128
                        });
129
                        self::$config->prepareConfigKey('global_cc', 'Global CC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
130
                                if (!empty($value) && !OIDplus::mailUtils()->validMailAddress($value)) {
131
                                        throw new OIDplusException("This is not a correct email address");
132
                                }
133
                        });
134
                        self::$config->prepareConfigKey('objecttypes_initialized', 'List of object type plugins that were initialized once', '', OIDplusConfig::PROTECTION_READONLY, function($value) {
135
                                // Nothing here yet
136
                        });
137
                        self::$config->prepareConfigKey('objecttypes_enabled', 'Enabled object types and their order, separated with a semicolon (please reload the page so that the change is applied)', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
138
                                # TODO: when objecttypes_enabled is changed at the admin control panel, we need to do a reload of the page, so that jsTree will be updated. Is there anything we can do?
139
 
140
                                $ary = explode(';',$value);
141
                                $uniq_ary = array_unique($ary);
142
 
143
                                if (count($ary) != count($uniq_ary)) {
144
                                        throw new OIDplusException("Please check your input. Some object types are double.");
145
                                }
146
 
147
                                foreach ($ary as $ot_check) {
148
                                        $ns_found = false;
149
                                        foreach (OIDplus::getEnabledObjectTypes() as $ot) {
150
                                                if ($ot::ns() == $ot_check) {
151
                                                        $ns_found = true;
152
                                                        break;
153
                                                }
154
                                        }
155
                                        foreach (OIDplus::getDisabledObjectTypes() as $ot) {
156
                                                if ($ot::ns() == $ot_check) {
157
                                                        $ns_found = true;
158
                                                        break;
159
                                                }
160
                                        }
161
                                        if (!$ns_found) {
162
                                                throw new OIDplusException("Please check your input. Namespace \"$ot_check\" is not found");
163
                                        }
164
                                }
165
                        });
166
                        self::$config->prepareConfigKey('oidplus_private_key', 'Private key for this system', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
167
                                // Nothing here yet
168
                        });
169
                        self::$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.', '', OIDplusConfig::PROTECTION_READONLY, function($value) {
170
                                // Nothing here yet
171
                        });
172
 
173
                }
174
 
175
                return self::$config;
2 daniel-mar 176
        }
177
 
263 daniel-mar 178
        private static $gui = null;
2 daniel-mar 179
        public static function gui() {
263 daniel-mar 180
                if (is_null(self::$gui)) {
181
                        self::$gui = new OIDplusGui();
86 daniel-mar 182
                }
263 daniel-mar 183
                return self::$gui;
2 daniel-mar 184
        }
185
 
263 daniel-mar 186
        private static $authUtils = null;
2 daniel-mar 187
        public static function authUtils() {
263 daniel-mar 188
                if (is_null(self::$authUtils)) {
189
                        self::$authUtils = new OIDplusAuthUtils();
86 daniel-mar 190
                }
263 daniel-mar 191
                return self::$authUtils;
2 daniel-mar 192
        }
193
 
263 daniel-mar 194
        private static $mailUtils = null;
250 daniel-mar 195
        public static function mailUtils() {
263 daniel-mar 196
                if (is_null(self::$mailUtils)) {
197
                        self::$mailUtils = new OIDplusMailUtils();
250 daniel-mar 198
                }
263 daniel-mar 199
                return self::$mailUtils;
250 daniel-mar 200
        }
201
 
263 daniel-mar 202
        private static $menuUtils = null;
250 daniel-mar 203
        public static function menuUtils() {
263 daniel-mar 204
                if (is_null(self::$menuUtils)) {
205
                        self::$menuUtils = new OIDplusMenuUtils();
250 daniel-mar 206
                }
263 daniel-mar 207
                return self::$menuUtils;
250 daniel-mar 208
        }
209
 
263 daniel-mar 210
        private static $logger = null;
115 daniel-mar 211
        public static function logger() {
263 daniel-mar 212
                if (is_null(self::$logger)) {
213
                        self::$logger = new OIDplusLogger();
115 daniel-mar 214
                }
263 daniel-mar 215
                return self::$logger;
115 daniel-mar 216
        }
217
 
263 daniel-mar 218
        private static $sesHandler = null;
86 daniel-mar 219
        public static function sesHandler() {
263 daniel-mar 220
                if (is_null(self::$sesHandler)) {
221
                        self::$sesHandler = new OIDplusSessionHandler();
86 daniel-mar 222
                }
263 daniel-mar 223
                return self::$sesHandler;
86 daniel-mar 224
        }
225
 
274 daniel-mar 226
        # --- SQL slang plugin
227
 
228
        private static function registerSqlSlangPlugin(OIDplusSqlSlangPlugin $plugin) {
229
                $name = $plugin::id();
230
                if ($name === false) return false;
231
 
232
                self::$sqlSlangPlugins[$name] = $plugin;
233
 
234
                return true;
235
        }
236
 
237
        public static function getSqlSlangPlugins() {
238
                return self::$sqlSlangPlugins;
239
        }
240
 
230 daniel-mar 241
        # --- Database plugin
74 daniel-mar 242
 
227 daniel-mar 243
        private static function registerDatabasePlugin(OIDplusDatabasePlugin $plugin) {
275 daniel-mar 244
                $name = $plugin::id();
150 daniel-mar 245
                if ($name === false) return false;
246
 
247
                self::$dbPlugins[$name] = $plugin;
248
 
249
                return true;
250
        }
251
 
252
        public static function getDatabasePlugins() {
253
                return self::$dbPlugins;
254
        }
255
 
227 daniel-mar 256
        public static function db() {
261 daniel-mar 257
                if (OIDplus::baseConfig()->getValue('DATABASE_PLUGIN', '') === '') {
260 daniel-mar 258
                        throw new OIDplusConfigInitializationException("No database plugin selected in config file");
259
                }
261 daniel-mar 260
                if (!isset(self::$dbPlugins[OIDplus::baseConfig()->getValue('DATABASE_PLUGIN')])) {
261
                        throw new OIDplusConfigInitializationException("Database plugin '".OIDplus::baseConfig()->getValue('DATABASE_PLUGIN')."' not found");
227 daniel-mar 262
                }
261 daniel-mar 263
                $obj = self::$dbPlugins[OIDplus::baseConfig()->getValue('DATABASE_PLUGIN')];
227 daniel-mar 264
                if (!$obj->isConnected()) $obj->connect();
265
                return $obj;
266
        }
267
 
268
        # --- Page plugin
269
 
224 daniel-mar 270
        private static function registerPagePlugin(OIDplusPagePlugin $plugin) {
61 daniel-mar 271
                $type = $plugin->type();
272
                if ($type === false) return false;
273
 
274
                $prio = $plugin->priority();
256 daniel-mar 275
                if (!is_numeric($prio)) throw new OIDplusException('Errornous plugin "'.get_class($plugin).'": Invalid priority');
276
                if ($prio <   0) throw new OIDplusException('Errornous plugin "'.get_class($plugin).'": Invalid priority');
277
                if ($prio > 999) throw new OIDplusException('Errornous plugin "'.get_class($plugin).'": Invalid priority');
61 daniel-mar 278
 
279
                if (!isset(self::$pagePlugins[$type])) self::$pagePlugins[$type] = array();
256 daniel-mar 280
                self::$pagePlugins[$type][str_pad($prio, 3, '0', STR_PAD_LEFT).get_class($plugin)] = $plugin;
61 daniel-mar 281
 
282
                return true;
283
        }
284
 
230 daniel-mar 285
        public static function getPagePlugins($type='*') {
286
                if ($type === '*') {
61 daniel-mar 287
                        $res = array();
288
                        foreach (self::$pagePlugins as $data) {
289
                                $res = array_merge($res, $data);
290
                        }
291
                } else {
230 daniel-mar 292
                        $types = explode(',', $type);
293
                        foreach ($types as $type) {
294
                                $res = isset(self::$pagePlugins[$type]) ? self::$pagePlugins[$type] : array();
295
                        }
61 daniel-mar 296
                }
297
                ksort($res);
298
                return $res;
299
        }
300
 
227 daniel-mar 301
        # --- Auth plugin
302
 
303
        private static function registerAuthPlugin(OIDplusAuthPlugin $plugin) {
304
                self::$authPlugins[] = $plugin;
305
                return true;
306
        }
307
 
221 daniel-mar 308
        public static function getAuthPlugins() {
309
                return self::$authPlugins;
310
        }
311
 
227 daniel-mar 312
        # --- Object type plugin
313
 
314
        private static function registerObjectTypePlugin(OIDplusObjectTypePlugin $plugin) {
315
                self::$objectTypePlugins[] = $plugin;
316
 
317
                $ot = $plugin::getObjectTypeClassName();
318
                self::registerObjectType($ot);
319
 
320
                return true;
321
        }
322
 
224 daniel-mar 323
        private static function registerObjectType($ot) {
66 daniel-mar 324
                $ns = $ot::ns();
325
 
250 daniel-mar 326
                if (empty($ns)) throw new OIDplusException("Attention: Empty NS at $ot\n");
66 daniel-mar 327
 
328
                $ns_found = false;
227 daniel-mar 329
                foreach (array_merge(OIDplus::getEnabledObjectTypes(), OIDplus::getDisabledObjectTypes()) as $test_ot) {
66 daniel-mar 330
                        if ($test_ot::ns() == $ns) {
331
                                $ns_found = true;
332
                                break;
333
                        }
334
                }
335
                if ($ns_found) {
250 daniel-mar 336
                        throw new OIDplusException("Attention: Two objectType plugins use the same namespace \"$ns\"!");
66 daniel-mar 337
                }
338
 
339
                $init = OIDplus::config()->getValue("objecttypes_initialized");
340
                $init_ary = empty($init) ? array() : explode(';', $init);
70 daniel-mar 341
                $init_ary = array_map('trim', $init_ary);
66 daniel-mar 342
 
343
                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
344
                $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
70 daniel-mar 345
                $enabled_ary = array_map('trim', $enabled_ary);
66 daniel-mar 346
 
79 daniel-mar 347
                $do_enable = false;
348
                if (in_array($ns, $enabled_ary)) {
349
                        $do_enable = true;
350
                } else {
351
                        if (!OIDplus::config()->getValue('registration_done')) {
352
                                $do_enable = $ns == 'oid';
353
                        } else {
354
                                $do_enable = !in_array($ns, $init_ary);
355
                        }
356
                }
357
 
358
                if ($do_enable) {
227 daniel-mar 359
                        self::$enabledObjectTypes[] = $ot;
360
                        usort(self::$enabledObjectTypes, function($a, $b) {
66 daniel-mar 361
                                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
362
                                $enabled_ary = explode(';', $enabled);
363
 
364
                                $idx_a = array_search($a::ns(), $enabled_ary);
365
                                $idx_b = array_search($b::ns(), $enabled_ary);
366
 
367
                                if ($idx_a == $idx_b) {
368
                                    return 0;
369
                                }
370
                                return ($idx_a > $idx_b) ? +1 : -1;
371
                        });
74 daniel-mar 372
                } else {
373
                        self::$disabledObjectTypes[] = $ot;
66 daniel-mar 374
                }
375
 
376
                if (!in_array($ns, $init_ary)) {
377
                        // Was never initialized before, so we add it to the list of enabled object types once
378
 
79 daniel-mar 379
                        if ($do_enable) {
380
                                $enabled_ary[] = $ns;
381
                                OIDplus::config()->setValue("objecttypes_enabled", implode(';', $enabled_ary));
382
                        }
66 daniel-mar 383
 
384
                        $init_ary[] = $ns;
385
                        OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
386
                }
61 daniel-mar 387
        }
388
 
227 daniel-mar 389
        public static function getObjectTypePlugins() {
390
                return self::$objectTypePlugins;
61 daniel-mar 391
        }
392
 
227 daniel-mar 393
        public static function getObjectTypePluginsEnabled() {
394
                $res = array();
395
                foreach (self::$objectTypePlugins as $plugin) {
396
                        $ot = $plugin::getObjectTypeClassName();
397
                        if (in_array($ot, self::$enabledObjectTypes)) $res[] = $plugin;
398
                }
399
                return $res;
74 daniel-mar 400
        }
401
 
227 daniel-mar 402
        public static function getObjectTypePluginsDisabled() {
403
                $res = array();
404
                foreach (self::$objectTypePlugins as $plugin) {
405
                        $ot = $plugin::getObjectTypeClassName();
406
                        if (in_array($ot, self::$disabledObjectTypes)) $res[] = $plugin;
74 daniel-mar 407
                }
227 daniel-mar 408
                return $res;
74 daniel-mar 409
        }
410
 
227 daniel-mar 411
        public static function getEnabledObjectTypes() {
412
                return self::$enabledObjectTypes;
413
        }
74 daniel-mar 414
 
227 daniel-mar 415
        public static function getDisabledObjectTypes() {
416
                return self::$disabledObjectTypes;
417
        }
74 daniel-mar 418
 
227 daniel-mar 419
        # --- Initialization of OIDplus
206 daniel-mar 420
 
2 daniel-mar 421
        public static function init($html=true) {
236 daniel-mar 422
                self::$html = $html;
423
 
263 daniel-mar 424
                // Reset internal state, so we can re-init verything if required
274 daniel-mar 425
 
263 daniel-mar 426
                if (self::$old_config_format) {
427
                        // Note: This can only happen in very special cases (e.g. test cases) where you call init() twice
428
                        throw new OIDplusConfigInitializationException('A full re-initialization is not possible if a version 2.0 config file (containing "defines") is used. Please update to a config 2.1 file by running setup again.');
429
                }
274 daniel-mar 430
 
263 daniel-mar 431
                self::$config = null;
432
                self::$baseConfig = null;
433
                self::$gui = null;
434
                self::$authUtils = null;
435
                self::$mailUtils = null;
436
                self::$menuUtils = null;
437
                self::$logger = null;
438
                self::$sesHandler = null;
439
                self::$pagePlugins = array();
440
                self::$authPlugins = array();
441
                self::$objectTypePlugins = array();
442
                self::$enabledObjectTypes = array();
443
                self::$disabledObjectTypes = array();
444
                self::$dbPlugins = array();
274 daniel-mar 445
                self::$sqlSlangPlugins = array();
263 daniel-mar 446
                self::$system_id_cache = null;
447
                self::$sslAvailableCache = null;
74 daniel-mar 448
 
263 daniel-mar 449
                // Continue...
450
 
451
                OIDplus::baseConfig(); // this loads the base configuration located in config.inc.php (once!)
452
                                       // You can do changes to the configuration afterwards using OIDplus::baseConfig()->...
453
 
150 daniel-mar 454
                // Register database types (highest priority)
455
 
274 daniel-mar 456
                // SQL slangs
457
 
458
                $ary = glob(__DIR__ . '/../../plugins/sql_slang/'.'*'.'/plugin.inc.php');
459
                foreach ($ary as $a) include $a;
460
 
461
                foreach (get_declared_classes() as $c) {
462
                        if (is_subclass_of($c, 'OIDplusSqlSlangPlugin')) {
463
                                self::registerSqlSlangPlugin(new $c());
464
                        }
465
                }
466
 
467
                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
468
                        $plugin->init($html);
469
                }
470
 
471
                // Database providers
472
 
150 daniel-mar 473
                $ary = glob(__DIR__ . '/../../plugins/database/'.'*'.'/plugin.inc.php');
474
                foreach ($ary as $a) include $a;
475
 
224 daniel-mar 476
                foreach (get_declared_classes() as $c) {
246 daniel-mar 477
                        if (is_subclass_of($c, 'OIDplusDatabasePlugin')) {
224 daniel-mar 478
                                self::registerDatabasePlugin(new $c());
479
                        }
480
                }
481
 
237 daniel-mar 482
                foreach (OIDplus::getDatabasePlugins() as $plugin) {
483
                        $plugin->init($html);
484
                }
485
 
42 daniel-mar 486
                // Do redirect stuff etc.
74 daniel-mar 487
 
230 daniel-mar 488
                self::isSslAvailable(); // This function does automatic redirects
61 daniel-mar 489
 
263 daniel-mar 490
                // Construct the configuration manager
66 daniel-mar 491
 
263 daniel-mar 492
                OIDplus::config(); // During the construction, various system settings are prepared if required
66 daniel-mar 493
 
74 daniel-mar 494
                // Initialize public / private keys
495
 
227 daniel-mar 496
                OIDplus::getPkiStatus(true);
74 daniel-mar 497
 
237 daniel-mar 498
                // Register non-DB plugins
74 daniel-mar 499
 
222 daniel-mar 500
                $ary = glob(__DIR__ . '/../../plugins/objectTypes/'.'*'.'/plugin.inc.php');
150 daniel-mar 501
                foreach ($ary as $a) include $a;
502
 
256 daniel-mar 503
                $ary = glob(__DIR__ . '/../../plugins/*Pages/'.'*'.'/plugin.inc.php');
61 daniel-mar 504
                foreach ($ary as $a) include $a;
74 daniel-mar 505
 
221 daniel-mar 506
                $ary = glob(__DIR__ . '/../../plugins/auth/'.'*'.'/plugin.inc.php');
507
                foreach ($ary as $a) include $a;
508
 
224 daniel-mar 509
                foreach (get_declared_classes() as $c) {
256 daniel-mar 510
                        if (!(new ReflectionClass($c))->isAbstract()) {
511
                                if (is_subclass_of($c, 'OIDplusPagePlugin')) {
263 daniel-mar 512
                                        self::registerPagePlugin(new $c());
256 daniel-mar 513
                                }
514
                                if (is_subclass_of($c, 'OIDplusAuthPlugin')) {
515
                                        self::registerAuthPlugin(new $c());
516
                                }
517
                                if (is_subclass_of($c, 'OIDplusObjectTypePlugin')) {
518
                                        self::registerObjectTypePlugin(new $c());
519
                                }
224 daniel-mar 520
                        }
521
                }
74 daniel-mar 522
 
237 daniel-mar 523
                // Initialize non-DB plugins
224 daniel-mar 524
 
74 daniel-mar 525
                foreach (OIDplus::getPagePlugins('*') as $plugin) {
526
                        $plugin->init($html);
527
                }
230 daniel-mar 528
                foreach (OIDplus::getAuthPlugins() as $plugin) {
529
                        $plugin->init($html);
530
                }
531
                foreach (OIDplus::getObjectTypePlugins() as $plugin) {
532
                        $plugin->init($html);
533
                }
2 daniel-mar 534
        }
42 daniel-mar 535
 
227 daniel-mar 536
        # --- System URL, System ID, PKI, and other functions
537
 
538
        public static function getSystemUrl($relative=false) {
539
                if (!isset($_SERVER["SCRIPT_NAME"])) return false;
540
 
541
                $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
269 daniel-mar 542
                $test_dir = str_replace('\\', '/', $test_dir);
227 daniel-mar 543
                $c = 0;
544
                while (!file_exists($test_dir.'/oidplus_base.js')) {
545
                        $test_dir = dirname($test_dir);
546
                        $c++;
547
                        if ($c == 1000) return false;
548
                }
549
 
550
                $res = dirname($_SERVER['SCRIPT_NAME'].'xxx');
551
 
552
                for ($i=1; $i<=$c; $i++) {
553
                        $res = dirname($res);
554
                }
555
 
269 daniel-mar 556
                $res = str_replace('\\', '/', $res);
227 daniel-mar 557
                if ($res == '/') $res = '';
558
                $res .= '/';
559
 
560
                if (!$relative) {
228 daniel-mar 561
                        $is_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
562
                        $protocol = $is_ssl ? 'https' : 'http';
563
                        $host = $_SERVER['HTTP_HOST'];
564
                        $port = $_SERVER['SERVER_PORT'];
565
                        if ($is_ssl && ($port != 443)) {
566
                                $port_add = ":$port";
567
                        } else if (!$is_ssl && ($port != 80)) {
568
                                $port_add = ":$port";
569
                        } else {
570
                                $port_add = "";
571
                        }
572
                        $res = $protocol.'://'.$host.$port_add.$res;
227 daniel-mar 573
                }
574
 
575
                return $res;
576
        }
577
 
578
        private static $system_id_cache = null;
579
        public static function getSystemId($oid=false) {
580
                if (!is_null(self::$system_id_cache)) {
581
                        $out = self::$system_id_cache;
582
                } else {
583
                        $out = false;
584
 
585
                        if (self::getPkiStatus(true)) {
586
                                $pubKey = OIDplus::config()->getValue('oidplus_public_key');
587
                                if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
588
                                        $out = smallhash(base64_decode($m[1]));
589
                                }
590
                        }
591
                        self::$system_id_cache = $out;
592
                }
239 daniel-mar 593
                return ($out ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
227 daniel-mar 594
        }
595
 
596
        public static function getPkiStatus($try_generate=true) {
597
                if (!function_exists('openssl_pkey_new')) return false;
598
 
599
                $privKey = OIDplus::config()->getValue('oidplus_private_key');
600
                $pubKey = OIDplus::config()->getValue('oidplus_public_key');
601
 
602
                if ($try_generate && !verify_private_public_key($privKey, $pubKey)) {
263 daniel-mar 603
                        $pkey_config = array(
227 daniel-mar 604
                            "digest_alg" => "sha512",
605
                            "private_key_bits" => 2048,
606
                            "private_key_type" => OPENSSL_KEYTYPE_RSA,
607
                        );
608
 
609
                        // Create the private and public key
263 daniel-mar 610
                        $res = openssl_pkey_new($pkey_config);
256 daniel-mar 611
 
239 daniel-mar 612
                        if (!$res) return false;
227 daniel-mar 613
 
614
                        // Extract the private key from $res to $privKey
615
                        openssl_pkey_export($res, $privKey);
616
 
617
                        // Extract the public key from $res to $pubKey
618
                        $pubKey = openssl_pkey_get_details($res)["key"];
619
 
239 daniel-mar 620
                        // Log
621
                        OIDplus::logger()->log("A!", "Generating new SystemID using a new key pair");
622
 
227 daniel-mar 623
                        // Save the key pair to database
624
                        OIDplus::config()->setValue('oidplus_private_key', $privKey);
625
                        OIDplus::config()->setValue('oidplus_public_key', $pubKey);
626
 
627
                        // Log the new system ID
628
                        if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
629
                                $system_id = smallhash(base64_decode($m[1]));
630
                                OIDplus::logger()->log("A!", "Your SystemID is now $system_id");
631
                        }
632
                }
633
 
634
                return verify_private_public_key($privKey, $pubKey);
635
        }
636
 
170 daniel-mar 637
        public static function getInstallType() {
638
                if (!file_exists(__DIR__ . '/../../oidplus_version.txt') && !is_dir(__DIR__ . '/../../.svn')) {
639
                        return 'unknown';
640
                }
641
                if (file_exists(__DIR__ . '/../../oidplus_version.txt') && is_dir(__DIR__ . '/../../.svn')) {
642
                        return 'ambigous';
643
                }
644
                if (is_dir(__DIR__ . '/../../.svn')) {
645
                        return 'svn-wc';
646
                }
647
                if (file_exists(__DIR__ . '/../../oidplus_version.txt')) {
648
                        return 'svn-snapshot';
649
                }
650
        }
651
 
111 daniel-mar 652
        public static function getVersion() {
162 daniel-mar 653
                if (file_exists(__DIR__ . '/../../oidplus_version.txt') && is_dir(__DIR__ . '/../../.svn')) {
239 daniel-mar 654
                        return false; // version is ambigous
111 daniel-mar 655
                }
162 daniel-mar 656
 
657
                if (is_dir(__DIR__ . '/../../.svn')) {
658
                        // Try to find out the SVN version using the shell
239 daniel-mar 659
                        // TODO: das müllt die log files voll!
162 daniel-mar 660
                        $status = @shell_exec('svnversion '.realpath(__FILE__));
661
                        if (preg_match('/\d+/', $status, $match)) {
239 daniel-mar 662
                                return 'svn-'.$match[0];
162 daniel-mar 663
                        }
664
 
665
                        // If that failed, try to get the version via SQLite3
239 daniel-mar 666
                        if (class_exists('SQLite3')) {
162 daniel-mar 667
                                $db = new SQLite3(__DIR__ . '/../../.svn/wc.db');
668
                                $results = $db->query('SELECT MIN(revision) AS rev FROM NODES_BASE');
669
                                while ($row = $results->fetchArray()) {
239 daniel-mar 670
                                        return 'svn-'.$row['rev'];
162 daniel-mar 671
                                }
672
                        }
673
                }
674
 
675
                if (file_exists(__DIR__ . '/../../oidplus_version.txt')) {
676
                        $cont = file_get_contents(__DIR__ . '/../../oidplus_version.txt');
239 daniel-mar 677
                        if (preg_match('@Revision (\d+)@', $cont, $m))
678
                                return 'svn-'.$m[1];
162 daniel-mar 679
                }
680
 
239 daniel-mar 681
                return false;
111 daniel-mar 682
        }
683
 
230 daniel-mar 684
        private static $sslAvailableCache = null;
685
        public static function isSslAvailable() {
686
                if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
256 daniel-mar 687
 
230 daniel-mar 688
                if (php_sapi_name() == 'cli') {
689
                        self::$sslAvailableCache = false;
690
                        return false;
691
                }
692
 
49 daniel-mar 693
                $timeout = 2;
80 daniel-mar 694
                $already_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == "on");
695
                $ssl_port = 443;
227 daniel-mar 696
                $cookie_path = OIDplus::getSystemUrl(true);
83 daniel-mar 697
                if (empty($cookie_path)) $cookie_path = '/';
42 daniel-mar 698
 
261 daniel-mar 699
                $mode = OIDplus::baseConfig()->getValue('ENFORCE_SSL', 2/*auto*/);
700
 
701
                if ($mode == 0) {
80 daniel-mar 702
                        // No SSL available
230 daniel-mar 703
                        self::$sslAvailableCache = $already_ssl;
80 daniel-mar 704
                        return $already_ssl;
705
                }
706
 
261 daniel-mar 707
                if ($mode == 1) {
80 daniel-mar 708
                        // Force SSL
709
                        if ($already_ssl) {
230 daniel-mar 710
                                self::$sslAvailableCache = true;
80 daniel-mar 711
                                return true;
42 daniel-mar 712
                        } else {
80 daniel-mar 713
                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
714
                                header('Location:'.$location);
240 daniel-mar 715
                                die('Redirecting to HTTPS...');
230 daniel-mar 716
                                self::$sslAvailableCache = true;
80 daniel-mar 717
                                return true;
718
                        }
719
                }
720
 
261 daniel-mar 721
                if ($mode == 2) {
80 daniel-mar 722
                        // Automatic SSL detection
723
 
724
                        if ($already_ssl) {
725
                                // we are already on HTTPS
83 daniel-mar 726
                                setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
230 daniel-mar 727
                                self::$sslAvailableCache = true;
80 daniel-mar 728
                                return true;
729
                        } else {
730
                                if (isset($_COOKIE['SSL_CHECK'])) {
731
                                        // We already had the HTTPS detection done before.
732
                                        if ($_COOKIE['SSL_CHECK']) {
733
                                                // HTTPS was detected before, but we are HTTP. Redirect now
734
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
735
                                                header('Location:'.$location);
240 daniel-mar 736
                                                die('Redirecting to HTTPS...');
230 daniel-mar 737
                                                self::$sslAvailableCache = true;
80 daniel-mar 738
                                                return true;
739
                                        } else {
740
                                                // No HTTPS available. Do nothing.
230 daniel-mar 741
                                                self::$sslAvailableCache = false;
80 daniel-mar 742
                                                return false;
743
                                        }
49 daniel-mar 744
                                } else {
80 daniel-mar 745
                                        // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
746
                                        if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
747
                                                // HTTPS detected. Redirect now, and remember that we had detected HTTPS
83 daniel-mar 748
                                                setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
80 daniel-mar 749
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
750
                                                header('Location:'.$location);
240 daniel-mar 751
                                                die('Redirecting to HTTPS...');
230 daniel-mar 752
                                                self::$sslAvailableCache = true;
80 daniel-mar 753
                                                return true;
754
                                        } else {
755
                                                // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
83 daniel-mar 756
                                                setcookie('SSL_CHECK', '0', 0, $cookie_path, '', false, true);
230 daniel-mar 757
                                                self::$sslAvailableCache = false;
80 daniel-mar 758
                                                return false;
759
                                        }
49 daniel-mar 760
                                }
42 daniel-mar 761
                        }
762
                }
763
        }
241 daniel-mar 764
 
765
        public static function webpath($target) {
766
                $dir = __DIR__;
767
                $dir = dirname($dir);
768
                $dir = dirname($dir);
769
                $target = substr($target, strlen($dir)+1, strlen($target)-strlen($dir)-1);
770
                if ($target != '') {
771
                        $target = str_replace('\\','/',$target).'/';
772
                }
773
                return $target;
774
        }
2 daniel-mar 775
}