Subversion Repositories oidplus

Rev

Rev 275 | Rev 278 | 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
 
236 daniel-mar 29
        protected static $html = null;
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 {
85
                                        if ($html) {
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
                $prio = $plugin->priority();
256 daniel-mar 273
                if (!is_numeric($prio)) throw new OIDplusException('Errornous plugin "'.get_class($plugin).'": Invalid priority');
274
                if ($prio <   0) throw new OIDplusException('Errornous plugin "'.get_class($plugin).'": Invalid priority');
275
                if ($prio > 999) throw new OIDplusException('Errornous plugin "'.get_class($plugin).'": Invalid priority');
61 daniel-mar 276
 
277
                if (!isset(self::$pagePlugins[$type])) self::$pagePlugins[$type] = array();
256 daniel-mar 278
                self::$pagePlugins[$type][str_pad($prio, 3, '0', STR_PAD_LEFT).get_class($plugin)] = $plugin;
61 daniel-mar 279
 
280
                return true;
281
        }
282
 
230 daniel-mar 283
        public static function getPagePlugins($type='*') {
284
                if ($type === '*') {
61 daniel-mar 285
                        $res = array();
286
                        foreach (self::$pagePlugins as $data) {
287
                                $res = array_merge($res, $data);
288
                        }
289
                } else {
230 daniel-mar 290
                        $types = explode(',', $type);
291
                        foreach ($types as $type) {
292
                                $res = isset(self::$pagePlugins[$type]) ? self::$pagePlugins[$type] : array();
293
                        }
61 daniel-mar 294
                }
295
                ksort($res);
296
                return $res;
297
        }
298
 
227 daniel-mar 299
        # --- Auth plugin
300
 
301
        private static function registerAuthPlugin(OIDplusAuthPlugin $plugin) {
302
                self::$authPlugins[] = $plugin;
303
                return true;
304
        }
305
 
221 daniel-mar 306
        public static function getAuthPlugins() {
307
                return self::$authPlugins;
308
        }
309
 
227 daniel-mar 310
        # --- Object type plugin
311
 
312
        private static function registerObjectTypePlugin(OIDplusObjectTypePlugin $plugin) {
313
                self::$objectTypePlugins[] = $plugin;
314
 
315
                $ot = $plugin::getObjectTypeClassName();
316
                self::registerObjectType($ot);
317
 
318
                return true;
319
        }
320
 
224 daniel-mar 321
        private static function registerObjectType($ot) {
66 daniel-mar 322
                $ns = $ot::ns();
323
 
250 daniel-mar 324
                if (empty($ns)) throw new OIDplusException("Attention: Empty NS at $ot\n");
66 daniel-mar 325
 
326
                $ns_found = false;
227 daniel-mar 327
                foreach (array_merge(OIDplus::getEnabledObjectTypes(), OIDplus::getDisabledObjectTypes()) as $test_ot) {
66 daniel-mar 328
                        if ($test_ot::ns() == $ns) {
329
                                $ns_found = true;
330
                                break;
331
                        }
332
                }
333
                if ($ns_found) {
250 daniel-mar 334
                        throw new OIDplusException("Attention: Two objectType plugins use the same namespace \"$ns\"!");
66 daniel-mar 335
                }
336
 
337
                $init = OIDplus::config()->getValue("objecttypes_initialized");
338
                $init_ary = empty($init) ? array() : explode(';', $init);
70 daniel-mar 339
                $init_ary = array_map('trim', $init_ary);
66 daniel-mar 340
 
341
                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
342
                $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
70 daniel-mar 343
                $enabled_ary = array_map('trim', $enabled_ary);
66 daniel-mar 344
 
79 daniel-mar 345
                $do_enable = false;
346
                if (in_array($ns, $enabled_ary)) {
347
                        $do_enable = true;
348
                } else {
349
                        if (!OIDplus::config()->getValue('registration_done')) {
350
                                $do_enable = $ns == 'oid';
351
                        } else {
352
                                $do_enable = !in_array($ns, $init_ary);
353
                        }
354
                }
355
 
356
                if ($do_enable) {
227 daniel-mar 357
                        self::$enabledObjectTypes[] = $ot;
358
                        usort(self::$enabledObjectTypes, function($a, $b) {
66 daniel-mar 359
                                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
360
                                $enabled_ary = explode(';', $enabled);
361
 
362
                                $idx_a = array_search($a::ns(), $enabled_ary);
363
                                $idx_b = array_search($b::ns(), $enabled_ary);
364
 
365
                                if ($idx_a == $idx_b) {
366
                                    return 0;
367
                                }
368
                                return ($idx_a > $idx_b) ? +1 : -1;
369
                        });
74 daniel-mar 370
                } else {
371
                        self::$disabledObjectTypes[] = $ot;
66 daniel-mar 372
                }
373
 
374
                if (!in_array($ns, $init_ary)) {
375
                        // Was never initialized before, so we add it to the list of enabled object types once
376
 
79 daniel-mar 377
                        if ($do_enable) {
378
                                $enabled_ary[] = $ns;
379
                                OIDplus::config()->setValue("objecttypes_enabled", implode(';', $enabled_ary));
380
                        }
66 daniel-mar 381
 
382
                        $init_ary[] = $ns;
383
                        OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
384
                }
61 daniel-mar 385
        }
386
 
227 daniel-mar 387
        public static function getObjectTypePlugins() {
388
                return self::$objectTypePlugins;
61 daniel-mar 389
        }
390
 
227 daniel-mar 391
        public static function getObjectTypePluginsEnabled() {
392
                $res = array();
393
                foreach (self::$objectTypePlugins as $plugin) {
394
                        $ot = $plugin::getObjectTypeClassName();
395
                        if (in_array($ot, self::$enabledObjectTypes)) $res[] = $plugin;
396
                }
397
                return $res;
74 daniel-mar 398
        }
399
 
227 daniel-mar 400
        public static function getObjectTypePluginsDisabled() {
401
                $res = array();
402
                foreach (self::$objectTypePlugins as $plugin) {
403
                        $ot = $plugin::getObjectTypeClassName();
404
                        if (in_array($ot, self::$disabledObjectTypes)) $res[] = $plugin;
74 daniel-mar 405
                }
227 daniel-mar 406
                return $res;
74 daniel-mar 407
        }
408
 
227 daniel-mar 409
        public static function getEnabledObjectTypes() {
410
                return self::$enabledObjectTypes;
411
        }
74 daniel-mar 412
 
227 daniel-mar 413
        public static function getDisabledObjectTypes() {
414
                return self::$disabledObjectTypes;
415
        }
74 daniel-mar 416
 
277 daniel-mar 417
        # --- Plugin handling functions
418
 
419
        public static function getPluginInfo($class_name): array {
420
                $reflector = new ReflectionClass($class_name);
421
                $ini = dirname($reflector->getFileName()).'/manifest.ini';
422
                if (!file_exists($ini)) return array();
423
                $bry = parse_ini_file($ini, true, INI_SCANNER_TYPED);
424
                if (!isset($bry['Plugin'])) return array();
425
                return $bry['Plugin'];
426
        }
427
 
428
        public static function getAllPluginManifests($pluginFolderMask='*'): array {
429
                static $cache = null;
430
                if (!is_null($cache)) return $cache;
431
 
432
                $out = array();
433
                $ary = glob(__DIR__ . '/../../plugins/'.$pluginFolderMask.'/'.'*'.'/manifest.ini');
434
                foreach ($ary as $ini) {
435
                        if (!file_exists($ini)) continue;
436
                        $bry = parse_ini_file($ini, true, INI_SCANNER_TYPED);
437
 
438
                        $plugintype_folder = basename(dirname(dirname($ini)));
439
                        $pluginname_folder = basename(dirname($ini));
440
 
441
                        if (!isset($out[$plugintype_folder])) $out[$plugintype_folder] = array();
442
                        if (!isset($out[$plugintype_folder][$pluginname_folder])) $out[$plugintype_folder][$pluginname_folder] = array();
443
                        $out[$plugintype_folder][$pluginname_folder] = $bry;
444
                }
445
 
446
                $cache = $out;
447
                return $out;
448
        }
449
 
450
        public static function registerAllPlugins($pluginDirName, $expectedPluginClass, $registerCallback): array {
451
                $out = array();
452
                $ary = self::getAllPluginManifests();
453
                foreach ($ary as $plugintype_folder => $bry) {
454
                        foreach ($bry as $pluginname_folder => $cry) {
455
                                if (!isset($cry['PHP'])) continue;
456
                                if (!isset($cry['PHP']['class'])) continue;
457
                                foreach ($cry['PHP']['class'] as $class_name) {
458
                                        class_exists($class_name); // force autoloader to load the class
459
                                        if (!is_null($registerCallback) &&
460
                                            !(new ReflectionClass($class_name))->isAbstract() &&
461
                                             ($class_name != $expectedPluginClass) &&
462
                                             is_subclass_of($class_name, $expectedPluginClass))
463
                                        {
464
                                                $out[] = $class_name;
465
                                                call_user_func($registerCallback, new $class_name());
466
                                        }
467
                                }
468
                        }
469
 
470
                }
471
                return $out;
472
        }
473
 
227 daniel-mar 474
        # --- Initialization of OIDplus
206 daniel-mar 475
 
2 daniel-mar 476
        public static function init($html=true) {
236 daniel-mar 477
                self::$html = $html;
478
 
263 daniel-mar 479
                // Reset internal state, so we can re-init verything if required
274 daniel-mar 480
 
263 daniel-mar 481
                if (self::$old_config_format) {
482
                        // Note: This can only happen in very special cases (e.g. test cases) where you call init() twice
483
                        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.');
484
                }
274 daniel-mar 485
 
263 daniel-mar 486
                self::$config = null;
487
                self::$baseConfig = null;
488
                self::$gui = null;
489
                self::$authUtils = null;
490
                self::$mailUtils = null;
491
                self::$menuUtils = null;
492
                self::$logger = null;
493
                self::$sesHandler = null;
494
                self::$pagePlugins = array();
495
                self::$authPlugins = array();
496
                self::$objectTypePlugins = array();
497
                self::$enabledObjectTypes = array();
498
                self::$disabledObjectTypes = array();
499
                self::$dbPlugins = array();
274 daniel-mar 500
                self::$sqlSlangPlugins = array();
263 daniel-mar 501
                self::$system_id_cache = null;
502
                self::$sslAvailableCache = null;
74 daniel-mar 503
 
263 daniel-mar 504
                // Continue...
505
 
506
                OIDplus::baseConfig(); // this loads the base configuration located in config.inc.php (once!)
507
                                       // You can do changes to the configuration afterwards using OIDplus::baseConfig()->...
508
 
150 daniel-mar 509
                // Register database types (highest priority)
510
 
274 daniel-mar 511
                // SQL slangs
512
 
277 daniel-mar 513
                self::registerAllPlugins('sql_slang', 'OIDplusSqlSlangPlugin', array('OIDplus','registerSqlSlangPlugin'));
274 daniel-mar 514
                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
515
                        $plugin->init($html);
516
                }
517
 
518
                // Database providers
519
 
277 daniel-mar 520
                self::registerAllPlugins('database', 'OIDplusDatabasePlugin', array('OIDplus','registerDatabasePlugin'));
237 daniel-mar 521
                foreach (OIDplus::getDatabasePlugins() as $plugin) {
522
                        $plugin->init($html);
523
                }
524
 
42 daniel-mar 525
                // Do redirect stuff etc.
74 daniel-mar 526
 
230 daniel-mar 527
                self::isSslAvailable(); // This function does automatic redirects
61 daniel-mar 528
 
263 daniel-mar 529
                // Construct the configuration manager
66 daniel-mar 530
 
263 daniel-mar 531
                OIDplus::config(); // During the construction, various system settings are prepared if required
66 daniel-mar 532
 
74 daniel-mar 533
                // Initialize public / private keys
534
 
227 daniel-mar 535
                OIDplus::getPkiStatus(true);
74 daniel-mar 536
 
237 daniel-mar 537
                // Register non-DB plugins
74 daniel-mar 538
 
277 daniel-mar 539
                self::registerAllPlugins('*Pages', 'OIDplusPagePlugin', array('OIDplus','registerPagePlugin'));
540
                self::registerAllPlugins('auth', 'OIDplusAuthPlugin', array('OIDplus','registerAuthPlugin'));
541
                self::registerAllPlugins('objectTypes', 'OIDplusObjectTypePlugin', array('OIDplus','registerObjectTypePlugin'));
150 daniel-mar 542
 
237 daniel-mar 543
                // Initialize non-DB plugins
224 daniel-mar 544
 
74 daniel-mar 545
                foreach (OIDplus::getPagePlugins('*') as $plugin) {
546
                        $plugin->init($html);
547
                }
230 daniel-mar 548
                foreach (OIDplus::getAuthPlugins() as $plugin) {
549
                        $plugin->init($html);
550
                }
551
                foreach (OIDplus::getObjectTypePlugins() as $plugin) {
552
                        $plugin->init($html);
553
                }
2 daniel-mar 554
        }
42 daniel-mar 555
 
227 daniel-mar 556
        # --- System URL, System ID, PKI, and other functions
557
 
558
        public static function getSystemUrl($relative=false) {
559
                if (!isset($_SERVER["SCRIPT_NAME"])) return false;
560
 
561
                $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
269 daniel-mar 562
                $test_dir = str_replace('\\', '/', $test_dir);
227 daniel-mar 563
                $c = 0;
564
                while (!file_exists($test_dir.'/oidplus_base.js')) {
565
                        $test_dir = dirname($test_dir);
566
                        $c++;
567
                        if ($c == 1000) return false;
568
                }
569
 
570
                $res = dirname($_SERVER['SCRIPT_NAME'].'xxx');
571
 
572
                for ($i=1; $i<=$c; $i++) {
573
                        $res = dirname($res);
574
                }
575
 
269 daniel-mar 576
                $res = str_replace('\\', '/', $res);
227 daniel-mar 577
                if ($res == '/') $res = '';
578
                $res .= '/';
579
 
580
                if (!$relative) {
228 daniel-mar 581
                        $is_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
582
                        $protocol = $is_ssl ? 'https' : 'http';
583
                        $host = $_SERVER['HTTP_HOST'];
584
                        $port = $_SERVER['SERVER_PORT'];
585
                        if ($is_ssl && ($port != 443)) {
586
                                $port_add = ":$port";
587
                        } else if (!$is_ssl && ($port != 80)) {
588
                                $port_add = ":$port";
589
                        } else {
590
                                $port_add = "";
591
                        }
592
                        $res = $protocol.'://'.$host.$port_add.$res;
227 daniel-mar 593
                }
594
 
595
                return $res;
596
        }
597
 
598
        private static $system_id_cache = null;
599
        public static function getSystemId($oid=false) {
600
                if (!is_null(self::$system_id_cache)) {
601
                        $out = self::$system_id_cache;
602
                } else {
603
                        $out = false;
604
 
605
                        if (self::getPkiStatus(true)) {
606
                                $pubKey = OIDplus::config()->getValue('oidplus_public_key');
607
                                if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
608
                                        $out = smallhash(base64_decode($m[1]));
609
                                }
610
                        }
611
                        self::$system_id_cache = $out;
612
                }
239 daniel-mar 613
                return ($out ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
227 daniel-mar 614
        }
615
 
616
        public static function getPkiStatus($try_generate=true) {
617
                if (!function_exists('openssl_pkey_new')) return false;
618
 
619
                $privKey = OIDplus::config()->getValue('oidplus_private_key');
620
                $pubKey = OIDplus::config()->getValue('oidplus_public_key');
621
 
622
                if ($try_generate && !verify_private_public_key($privKey, $pubKey)) {
263 daniel-mar 623
                        $pkey_config = array(
227 daniel-mar 624
                            "digest_alg" => "sha512",
625
                            "private_key_bits" => 2048,
626
                            "private_key_type" => OPENSSL_KEYTYPE_RSA,
627
                        );
628
 
629
                        // Create the private and public key
263 daniel-mar 630
                        $res = openssl_pkey_new($pkey_config);
256 daniel-mar 631
 
239 daniel-mar 632
                        if (!$res) return false;
227 daniel-mar 633
 
634
                        // Extract the private key from $res to $privKey
635
                        openssl_pkey_export($res, $privKey);
636
 
637
                        // Extract the public key from $res to $pubKey
638
                        $pubKey = openssl_pkey_get_details($res)["key"];
639
 
239 daniel-mar 640
                        // Log
641
                        OIDplus::logger()->log("A!", "Generating new SystemID using a new key pair");
642
 
227 daniel-mar 643
                        // Save the key pair to database
644
                        OIDplus::config()->setValue('oidplus_private_key', $privKey);
645
                        OIDplus::config()->setValue('oidplus_public_key', $pubKey);
646
 
647
                        // Log the new system ID
648
                        if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
649
                                $system_id = smallhash(base64_decode($m[1]));
650
                                OIDplus::logger()->log("A!", "Your SystemID is now $system_id");
651
                        }
652
                }
653
 
654
                return verify_private_public_key($privKey, $pubKey);
655
        }
656
 
170 daniel-mar 657
        public static function getInstallType() {
658
                if (!file_exists(__DIR__ . '/../../oidplus_version.txt') && !is_dir(__DIR__ . '/../../.svn')) {
659
                        return 'unknown';
660
                }
661
                if (file_exists(__DIR__ . '/../../oidplus_version.txt') && is_dir(__DIR__ . '/../../.svn')) {
662
                        return 'ambigous';
663
                }
664
                if (is_dir(__DIR__ . '/../../.svn')) {
665
                        return 'svn-wc';
666
                }
667
                if (file_exists(__DIR__ . '/../../oidplus_version.txt')) {
668
                        return 'svn-snapshot';
669
                }
670
        }
671
 
111 daniel-mar 672
        public static function getVersion() {
162 daniel-mar 673
                if (file_exists(__DIR__ . '/../../oidplus_version.txt') && is_dir(__DIR__ . '/../../.svn')) {
239 daniel-mar 674
                        return false; // version is ambigous
111 daniel-mar 675
                }
162 daniel-mar 676
 
677
                if (is_dir(__DIR__ . '/../../.svn')) {
678
                        // Try to find out the SVN version using the shell
239 daniel-mar 679
                        // TODO: das müllt die log files voll!
162 daniel-mar 680
                        $status = @shell_exec('svnversion '.realpath(__FILE__));
681
                        if (preg_match('/\d+/', $status, $match)) {
239 daniel-mar 682
                                return 'svn-'.$match[0];
162 daniel-mar 683
                        }
684
 
685
                        // If that failed, try to get the version via SQLite3
239 daniel-mar 686
                        if (class_exists('SQLite3')) {
162 daniel-mar 687
                                $db = new SQLite3(__DIR__ . '/../../.svn/wc.db');
688
                                $results = $db->query('SELECT MIN(revision) AS rev FROM NODES_BASE');
689
                                while ($row = $results->fetchArray()) {
239 daniel-mar 690
                                        return 'svn-'.$row['rev'];
162 daniel-mar 691
                                }
692
                        }
693
                }
694
 
695
                if (file_exists(__DIR__ . '/../../oidplus_version.txt')) {
696
                        $cont = file_get_contents(__DIR__ . '/../../oidplus_version.txt');
239 daniel-mar 697
                        if (preg_match('@Revision (\d+)@', $cont, $m))
698
                                return 'svn-'.$m[1];
162 daniel-mar 699
                }
700
 
239 daniel-mar 701
                return false;
111 daniel-mar 702
        }
703
 
230 daniel-mar 704
        private static $sslAvailableCache = null;
705
        public static function isSslAvailable() {
706
                if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
256 daniel-mar 707
 
230 daniel-mar 708
                if (php_sapi_name() == 'cli') {
709
                        self::$sslAvailableCache = false;
710
                        return false;
711
                }
712
 
49 daniel-mar 713
                $timeout = 2;
80 daniel-mar 714
                $already_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == "on");
715
                $ssl_port = 443;
227 daniel-mar 716
                $cookie_path = OIDplus::getSystemUrl(true);
83 daniel-mar 717
                if (empty($cookie_path)) $cookie_path = '/';
42 daniel-mar 718
 
261 daniel-mar 719
                $mode = OIDplus::baseConfig()->getValue('ENFORCE_SSL', 2/*auto*/);
720
 
721
                if ($mode == 0) {
80 daniel-mar 722
                        // No SSL available
230 daniel-mar 723
                        self::$sslAvailableCache = $already_ssl;
80 daniel-mar 724
                        return $already_ssl;
725
                }
726
 
261 daniel-mar 727
                if ($mode == 1) {
80 daniel-mar 728
                        // Force SSL
729
                        if ($already_ssl) {
230 daniel-mar 730
                                self::$sslAvailableCache = true;
80 daniel-mar 731
                                return true;
42 daniel-mar 732
                        } else {
80 daniel-mar 733
                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
734
                                header('Location:'.$location);
240 daniel-mar 735
                                die('Redirecting to HTTPS...');
230 daniel-mar 736
                                self::$sslAvailableCache = true;
80 daniel-mar 737
                                return true;
738
                        }
739
                }
740
 
261 daniel-mar 741
                if ($mode == 2) {
80 daniel-mar 742
                        // Automatic SSL detection
743
 
744
                        if ($already_ssl) {
745
                                // we are already on HTTPS
83 daniel-mar 746
                                setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
230 daniel-mar 747
                                self::$sslAvailableCache = true;
80 daniel-mar 748
                                return true;
749
                        } else {
750
                                if (isset($_COOKIE['SSL_CHECK'])) {
751
                                        // We already had the HTTPS detection done before.
752
                                        if ($_COOKIE['SSL_CHECK']) {
753
                                                // HTTPS was detected before, but we are HTTP. Redirect now
754
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
755
                                                header('Location:'.$location);
240 daniel-mar 756
                                                die('Redirecting to HTTPS...');
230 daniel-mar 757
                                                self::$sslAvailableCache = true;
80 daniel-mar 758
                                                return true;
759
                                        } else {
760
                                                // No HTTPS available. Do nothing.
230 daniel-mar 761
                                                self::$sslAvailableCache = false;
80 daniel-mar 762
                                                return false;
763
                                        }
49 daniel-mar 764
                                } else {
80 daniel-mar 765
                                        // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
766
                                        if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
767
                                                // HTTPS detected. Redirect now, and remember that we had detected HTTPS
83 daniel-mar 768
                                                setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
80 daniel-mar 769
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
770
                                                header('Location:'.$location);
240 daniel-mar 771
                                                die('Redirecting to HTTPS...');
230 daniel-mar 772
                                                self::$sslAvailableCache = true;
80 daniel-mar 773
                                                return true;
774
                                        } else {
775
                                                // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
83 daniel-mar 776
                                                setcookie('SSL_CHECK', '0', 0, $cookie_path, '', false, true);
230 daniel-mar 777
                                                self::$sslAvailableCache = false;
80 daniel-mar 778
                                                return false;
779
                                        }
49 daniel-mar 780
                                }
42 daniel-mar 781
                        }
782
                }
783
        }
241 daniel-mar 784
 
785
        public static function webpath($target) {
786
                $dir = __DIR__;
787
                $dir = dirname($dir);
788
                $dir = dirname($dir);
789
                $target = substr($target, strlen($dir)+1, strlen($target)-strlen($dir)-1);
790
                if ($target != '') {
791
                        $target = str_replace('\\','/',$target).'/';
792
                }
793
                return $target;
794
        }
2 daniel-mar 795
}