Subversion Repositories oidplus

Rev

Rev 315 | Rev 320 | 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
 
307 daniel-mar 441
        public static function getPluginManifest($class_name)/*: ?OIDplusPluginManifest*/ {
277 daniel-mar 442
                $reflector = new ReflectionClass($class_name);
308 daniel-mar 443
                $ini = dirname($reflector->getFileName()).'/manifest.xml';
307 daniel-mar 444
                $manifest = new OIDplusPluginManifest();
445
                return $manifest->loadManifest($ini) ? $manifest : null;
277 daniel-mar 446
        }
447
 
307 daniel-mar 448
        public static function getAllPluginManifests($pluginFolderMask='*', $flat=true): array {
277 daniel-mar 449
                $out = array();
279 daniel-mar 450
                // Note: glob() will sort by default, so we do not need a page priority attribute.
451
                //       So you just need to use a numeric plugin directory prefix (padded).
308 daniel-mar 452
                $ary = glob(OIDplus::basePath().'/plugins/'.$pluginFolderMask.'/'.'*'.'/manifest.xml');
277 daniel-mar 453
                foreach ($ary as $ini) {
454
                        if (!file_exists($ini)) continue;
455
 
307 daniel-mar 456
                        $manifest = new OIDplusPluginManifest();
457
                        $manifest->loadManifest($ini);
277 daniel-mar 458
 
307 daniel-mar 459
                        if ($flat) {
460
                                $out[] = $manifest;
461
                        } else {
462
                                $plugintype_folder = basename(dirname(dirname($ini)));
463
                                $pluginname_folder = basename(dirname($ini));
464
 
465
                                if (!isset($out[$plugintype_folder])) $out[$plugintype_folder] = array();
466
                                if (!isset($out[$plugintype_folder][$pluginname_folder])) $out[$plugintype_folder][$pluginname_folder] = array();
467
                                $out[$plugintype_folder][$pluginname_folder] = $manifest;
468
                        }
277 daniel-mar 469
                }
470
                return $out;
471
        }
472
 
473
        public static function registerAllPlugins($pluginDirName, $expectedPluginClass, $registerCallback): array {
474
                $out = array();
307 daniel-mar 475
                $ary = self::getAllPluginManifests($pluginDirName, false);
277 daniel-mar 476
                foreach ($ary as $plugintype_folder => $bry) {
477
                        foreach ($bry as $pluginname_folder => $cry) {
307 daniel-mar 478
                                $class_name = $cry->getPhpMainClass();
479
                                if (!$class_name) {
480
                                        throw new OIDplusException("Plugin '$plugintype_folder/$pluginname_folder' is errornous: Manifest does not declare a PHP main class");
277 daniel-mar 481
                                }
297 daniel-mar 482
                                if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
483
                                        continue;
484
                                }
292 daniel-mar 485
                                if (!class_exists($class_name)) {
307 daniel-mar 486
                                        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 487
                                }
279 daniel-mar 488
                                if (!is_subclass_of($class_name, $expectedPluginClass)) {
307 daniel-mar 489
                                        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 490
                                }
308 daniel-mar 491
                                if (($class_name!=$cry->getTypeClass()) && (!is_subclass_of($class_name,$cry->getTypeClass()))) {
492
                                        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");
493
                                }
494
                                if (($cry->getTypeClass()!=$expectedPluginClass) && (!is_subclass_of($cry->getTypeClass(),$expectedPluginClass))) {
495
                                        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'");
496
                                }
497
 
279 daniel-mar 498
                                $out[] = $class_name;
499
                                if (!is_null($registerCallback)) {
500
                                        call_user_func($registerCallback, new $class_name());
501
                                }
277 daniel-mar 502
                        }
503
 
504
                }
505
                return $out;
506
        }
507
 
227 daniel-mar 508
        # --- Initialization of OIDplus
206 daniel-mar 509
 
2 daniel-mar 510
        public static function init($html=true) {
236 daniel-mar 511
                self::$html = $html;
512
 
263 daniel-mar 513
                // Reset internal state, so we can re-init verything if required
274 daniel-mar 514
 
263 daniel-mar 515
                if (self::$old_config_format) {
516
                        // Note: This can only happen in very special cases (e.g. test cases) where you call init() twice
517
                        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.');
518
                }
274 daniel-mar 519
 
263 daniel-mar 520
                self::$config = null;
521
                self::$baseConfig = null;
522
                self::$gui = null;
523
                self::$authUtils = null;
524
                self::$mailUtils = null;
525
                self::$menuUtils = null;
526
                self::$logger = null;
527
                self::$sesHandler = null;
295 daniel-mar 528
                self::$dbMainSession = null;
529
                self::$dbIsolatedSession = null;
263 daniel-mar 530
                self::$pagePlugins = array();
531
                self::$authPlugins = array();
289 daniel-mar 532
                self::$loggerPlugins = array();
263 daniel-mar 533
                self::$objectTypePlugins = array();
534
                self::$enabledObjectTypes = array();
535
                self::$disabledObjectTypes = array();
536
                self::$dbPlugins = array();
274 daniel-mar 537
                self::$sqlSlangPlugins = array();
263 daniel-mar 538
                self::$system_id_cache = null;
539
                self::$sslAvailableCache = null;
74 daniel-mar 540
 
263 daniel-mar 541
                // Continue...
542
 
294 daniel-mar 543
                OIDplus::baseConfig(); // this loads the base configuration located in userdata/baseconfig/config.inc.php (once!)
263 daniel-mar 544
                                       // You can do changes to the configuration afterwards using OIDplus::baseConfig()->...
545
 
150 daniel-mar 546
                // Register database types (highest priority)
547
 
274 daniel-mar 548
                // SQL slangs
549
 
294 daniel-mar 550
                self::registerAllPlugins('sqlSlang', 'OIDplusSqlSlangPlugin', array('OIDplus','registerSqlSlangPlugin'));
274 daniel-mar 551
                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
552
                        $plugin->init($html);
553
                }
554
 
555
                // Database providers
556
 
277 daniel-mar 557
                self::registerAllPlugins('database', 'OIDplusDatabasePlugin', array('OIDplus','registerDatabasePlugin'));
237 daniel-mar 558
                foreach (OIDplus::getDatabasePlugins() as $plugin) {
559
                        $plugin->init($html);
560
                }
561
 
42 daniel-mar 562
                // Do redirect stuff etc.
74 daniel-mar 563
 
230 daniel-mar 564
                self::isSslAvailable(); // This function does automatic redirects
61 daniel-mar 565
 
263 daniel-mar 566
                // Construct the configuration manager
66 daniel-mar 567
 
263 daniel-mar 568
                OIDplus::config(); // During the construction, various system settings are prepared if required
66 daniel-mar 569
 
74 daniel-mar 570
                // Initialize public / private keys
571
 
227 daniel-mar 572
                OIDplus::getPkiStatus(true);
74 daniel-mar 573
 
237 daniel-mar 574
                // Register non-DB plugins
74 daniel-mar 575
 
277 daniel-mar 576
                self::registerAllPlugins('*Pages', 'OIDplusPagePlugin', array('OIDplus','registerPagePlugin'));
577
                self::registerAllPlugins('auth', 'OIDplusAuthPlugin', array('OIDplus','registerAuthPlugin'));
289 daniel-mar 578
                self::registerAllPlugins('logger', 'OIDplusLoggerPlugin', array('OIDplus','registerLoggerPlugin'));
277 daniel-mar 579
                self::registerAllPlugins('objectTypes', 'OIDplusObjectTypePlugin', array('OIDplus','registerObjectTypePlugin'));
150 daniel-mar 580
 
237 daniel-mar 581
                // Initialize non-DB plugins
224 daniel-mar 582
 
281 daniel-mar 583
                foreach (OIDplus::getPagePlugins() as $plugin) {
74 daniel-mar 584
                        $plugin->init($html);
585
                }
230 daniel-mar 586
                foreach (OIDplus::getAuthPlugins() as $plugin) {
587
                        $plugin->init($html);
588
                }
289 daniel-mar 589
                foreach (OIDplus::getLoggerPlugins() as $plugin) {
590
                        $plugin->init($html);
591
                }
230 daniel-mar 592
                foreach (OIDplus::getObjectTypePlugins() as $plugin) {
593
                        $plugin->init($html);
594
                }
2 daniel-mar 595
        }
42 daniel-mar 596
 
227 daniel-mar 597
        # --- System URL, System ID, PKI, and other functions
598
 
294 daniel-mar 599
        public static function basePath() {
600
                return realpath(__DIR__ . '/../../');
601
        }
602
 
227 daniel-mar 603
        public static function getSystemUrl($relative=false) {
604
                if (!isset($_SERVER["SCRIPT_NAME"])) return false;
605
 
606
                $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
269 daniel-mar 607
                $test_dir = str_replace('\\', '/', $test_dir);
227 daniel-mar 608
                $c = 0;
609
                while (!file_exists($test_dir.'/oidplus_base.js')) {
610
                        $test_dir = dirname($test_dir);
611
                        $c++;
612
                        if ($c == 1000) return false;
613
                }
614
 
615
                $res = dirname($_SERVER['SCRIPT_NAME'].'xxx');
616
 
617
                for ($i=1; $i<=$c; $i++) {
618
                        $res = dirname($res);
619
                }
620
 
269 daniel-mar 621
                $res = str_replace('\\', '/', $res);
227 daniel-mar 622
                if ($res == '/') $res = '';
623
                $res .= '/';
624
 
625
                if (!$relative) {
315 daniel-mar 626
                        if (php_sapi_name() == 'cli') {
627
                                // TODO: what should we do???
628
                                return false;
629
                        }
630
 
228 daniel-mar 631
                        $is_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
632
                        $protocol = $is_ssl ? 'https' : 'http';
633
                        $host = $_SERVER['HTTP_HOST'];
634
                        $port = $_SERVER['SERVER_PORT'];
635
                        if ($is_ssl && ($port != 443)) {
636
                                $port_add = ":$port";
637
                        } else if (!$is_ssl && ($port != 80)) {
638
                                $port_add = ":$port";
639
                        } else {
640
                                $port_add = "";
641
                        }
642
                        $res = $protocol.'://'.$host.$port_add.$res;
227 daniel-mar 643
                }
644
 
645
                return $res;
646
        }
647
 
648
        private static $system_id_cache = null;
649
        public static function getSystemId($oid=false) {
650
                if (!is_null(self::$system_id_cache)) {
651
                        $out = self::$system_id_cache;
652
                } else {
653
                        $out = false;
654
 
655
                        if (self::getPkiStatus(true)) {
656
                                $pubKey = OIDplus::config()->getValue('oidplus_public_key');
657
                                if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
658
                                        $out = smallhash(base64_decode($m[1]));
659
                                }
660
                        }
661
                        self::$system_id_cache = $out;
662
                }
291 daniel-mar 663
                return ($oid ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
227 daniel-mar 664
        }
665
 
666
        public static function getPkiStatus($try_generate=true) {
667
                if (!function_exists('openssl_pkey_new')) return false;
668
 
669
                $privKey = OIDplus::config()->getValue('oidplus_private_key');
670
                $pubKey = OIDplus::config()->getValue('oidplus_public_key');
671
 
672
                if ($try_generate && !verify_private_public_key($privKey, $pubKey)) {
263 daniel-mar 673
                        $pkey_config = array(
227 daniel-mar 674
                            "digest_alg" => "sha512",
675
                            "private_key_bits" => 2048,
676
                            "private_key_type" => OPENSSL_KEYTYPE_RSA,
677
                        );
678
 
679
                        // Create the private and public key
263 daniel-mar 680
                        $res = openssl_pkey_new($pkey_config);
256 daniel-mar 681
 
239 daniel-mar 682
                        if (!$res) return false;
227 daniel-mar 683
 
684
                        // Extract the private key from $res to $privKey
685
                        openssl_pkey_export($res, $privKey);
686
 
687
                        // Extract the public key from $res to $pubKey
688
                        $pubKey = openssl_pkey_get_details($res)["key"];
689
 
239 daniel-mar 690
                        // Log
288 daniel-mar 691
                        OIDplus::logger()->log("[INFO]A!", "Generating new SystemID using a new key pair");
239 daniel-mar 692
 
227 daniel-mar 693
                        // Save the key pair to database
694
                        OIDplus::config()->setValue('oidplus_private_key', $privKey);
695
                        OIDplus::config()->setValue('oidplus_public_key', $pubKey);
696
 
697
                        // Log the new system ID
698
                        if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
699
                                $system_id = smallhash(base64_decode($m[1]));
288 daniel-mar 700
                                OIDplus::logger()->log("[INFO]A!", "Your SystemID is now $system_id");
227 daniel-mar 701
                        }
702
                }
703
 
704
                return verify_private_public_key($privKey, $pubKey);
705
        }
706
 
170 daniel-mar 707
        public static function getInstallType() {
294 daniel-mar 708
                if (!file_exists(OIDplus::basePath().'/oidplus_version.txt') && !is_dir(OIDplus::basePath().'/.svn')) {
170 daniel-mar 709
                        return 'unknown';
710
                }
294 daniel-mar 711
                if (file_exists(OIDplus::basePath().'/oidplus_version.txt') && is_dir(OIDplus::basePath().'/.svn')) {
170 daniel-mar 712
                        return 'ambigous';
713
                }
294 daniel-mar 714
                if (is_dir(OIDplus::basePath().'/.svn')) {
170 daniel-mar 715
                        return 'svn-wc';
716
                }
294 daniel-mar 717
                if (file_exists(OIDplus::basePath().'/oidplus_version.txt')) {
170 daniel-mar 718
                        return 'svn-snapshot';
719
                }
720
        }
721
 
111 daniel-mar 722
        public static function getVersion() {
294 daniel-mar 723
                if (file_exists(OIDplus::basePath().'/oidplus_version.txt') && is_dir(OIDplus::basePath().'/.svn')) {
239 daniel-mar 724
                        return false; // version is ambigous
111 daniel-mar 725
                }
162 daniel-mar 726
 
294 daniel-mar 727
                if (is_dir(OIDplus::basePath().'/.svn')) {
285 daniel-mar 728
                        // Try to get the version via SQLite3
729
                        if (class_exists('SQLite3')) {
730
                                try {
294 daniel-mar 731
                                        $db = new SQLite3(OIDplus::basePath().'/.svn/wc.db');
285 daniel-mar 732
                                        $results = $db->query('SELECT MIN(revision) AS rev FROM NODES_BASE');
733
                                        while ($row = $results->fetchArray()) {
734
                                                return 'svn-'.$row['rev'];
735
                                        }
736
                                        $db->close();
737
                                        $db = null;
738
                                } catch (Exception $e) {
739
                                }
740
                        }
741
                        if (class_exists('PDO')) {
742
                                try {
294 daniel-mar 743
                                        $pdo = new PDO('sqlite:' . OIDplus::basePath().'/.svn/wc.db');
285 daniel-mar 744
                                        $res = $pdo->query('SELECT MIN(revision) AS rev FROM NODES_BASE');
745
                                        $row = $res->fetch();
746
                                        if ($row !== false) return 'svn-'.$row['rev'];
747
                                        $pdo = null;
748
                                } catch (Exception $e) {
749
                                }
750
                        }
751
 
162 daniel-mar 752
                        // Try to find out the SVN version using the shell
285 daniel-mar 753
                        // We don't prioritize this method, because a failed shell access will flood the apache error log with STDERR messages
294 daniel-mar 754
                        $output = @shell_exec('svnversion '.escapeshellarg(OIDplus::basePath()));
285 daniel-mar 755
                        if (preg_match('/\d+/', $output, $match)) {
239 daniel-mar 756
                                return 'svn-'.$match[0];
162 daniel-mar 757
                        }
758
 
294 daniel-mar 759
                        $output = @shell_exec('svn info '.escapeshellarg(OIDplus::basePath()));
285 daniel-mar 760
                        if (preg_match('/Revision:\s*(\d+)/m', $output, $match)) {
761
                                return 'svn-'.$match[1];
162 daniel-mar 762
                        }
763
                }
764
 
294 daniel-mar 765
                if (file_exists(OIDplus::basePath().'/oidplus_version.txt')) {
766
                        $cont = file_get_contents(OIDplus::basePath().'/oidplus_version.txt');
239 daniel-mar 767
                        if (preg_match('@Revision (\d+)@', $cont, $m))
768
                                return 'svn-'.$m[1];
162 daniel-mar 769
                }
770
 
239 daniel-mar 771
                return false;
111 daniel-mar 772
        }
773
 
230 daniel-mar 774
        private static $sslAvailableCache = null;
775
        public static function isSslAvailable() {
776
                if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
256 daniel-mar 777
 
230 daniel-mar 778
                if (php_sapi_name() == 'cli') {
779
                        self::$sslAvailableCache = false;
780
                        return false;
781
                }
782
 
49 daniel-mar 783
                $timeout = 2;
80 daniel-mar 784
                $already_ssl = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == "on");
785
                $ssl_port = 443;
227 daniel-mar 786
                $cookie_path = OIDplus::getSystemUrl(true);
83 daniel-mar 787
                if (empty($cookie_path)) $cookie_path = '/';
42 daniel-mar 788
 
261 daniel-mar 789
                $mode = OIDplus::baseConfig()->getValue('ENFORCE_SSL', 2/*auto*/);
790
 
791
                if ($mode == 0) {
80 daniel-mar 792
                        // No SSL available
230 daniel-mar 793
                        self::$sslAvailableCache = $already_ssl;
80 daniel-mar 794
                        return $already_ssl;
795
                }
796
 
261 daniel-mar 797
                if ($mode == 1) {
80 daniel-mar 798
                        // Force SSL
799
                        if ($already_ssl) {
230 daniel-mar 800
                                self::$sslAvailableCache = true;
80 daniel-mar 801
                                return true;
42 daniel-mar 802
                        } else {
80 daniel-mar 803
                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
804
                                header('Location:'.$location);
240 daniel-mar 805
                                die('Redirecting to HTTPS...');
230 daniel-mar 806
                                self::$sslAvailableCache = true;
80 daniel-mar 807
                                return true;
808
                        }
809
                }
810
 
261 daniel-mar 811
                if ($mode == 2) {
80 daniel-mar 812
                        // Automatic SSL detection
813
 
814
                        if ($already_ssl) {
815
                                // we are already on HTTPS
83 daniel-mar 816
                                setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
230 daniel-mar 817
                                self::$sslAvailableCache = true;
80 daniel-mar 818
                                return true;
819
                        } else {
820
                                if (isset($_COOKIE['SSL_CHECK'])) {
821
                                        // We already had the HTTPS detection done before.
822
                                        if ($_COOKIE['SSL_CHECK']) {
823
                                                // HTTPS was detected before, but we are HTTP. Redirect now
824
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
825
                                                header('Location:'.$location);
240 daniel-mar 826
                                                die('Redirecting to HTTPS...');
230 daniel-mar 827
                                                self::$sslAvailableCache = true;
80 daniel-mar 828
                                                return true;
829
                                        } else {
830
                                                // No HTTPS available. Do nothing.
230 daniel-mar 831
                                                self::$sslAvailableCache = false;
80 daniel-mar 832
                                                return false;
833
                                        }
49 daniel-mar 834
                                } else {
80 daniel-mar 835
                                        // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
836
                                        if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
837
                                                // HTTPS detected. Redirect now, and remember that we had detected HTTPS
83 daniel-mar 838
                                                setcookie('SSL_CHECK', '1', 0, $cookie_path, '', false, true);
80 daniel-mar 839
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
840
                                                header('Location:'.$location);
240 daniel-mar 841
                                                die('Redirecting to HTTPS...');
230 daniel-mar 842
                                                self::$sslAvailableCache = true;
80 daniel-mar 843
                                                return true;
844
                                        } else {
845
                                                // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
83 daniel-mar 846
                                                setcookie('SSL_CHECK', '0', 0, $cookie_path, '', false, true);
230 daniel-mar 847
                                                self::$sslAvailableCache = false;
80 daniel-mar 848
                                                return false;
849
                                        }
49 daniel-mar 850
                                }
42 daniel-mar 851
                        }
852
                }
853
        }
241 daniel-mar 854
 
855
        public static function webpath($target) {
856
                $dir = __DIR__;
857
                $dir = dirname($dir);
858
                $dir = dirname($dir);
859
                $target = substr($target, strlen($dir)+1, strlen($target)-strlen($dir)-1);
860
                if ($target != '') {
861
                        $target = str_replace('\\','/',$target).'/';
862
                }
863
                return $target;
864
        }
2 daniel-mar 865
}