Subversion Repositories oidplus

Rev

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