Subversion Repositories oidplus

Rev

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