Subversion Repositories oidplus

Rev

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