Subversion Repositories oidplus

Rev

Rev 1001 | Rev 1016 | 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
778 daniel-mar 5
 * Copyright 2019 - 2022 Daniel Marschall, ViaThinkSoft
2 daniel-mar 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
 
511 daniel-mar 20
if (!defined('INSIDE_OIDPLUS')) die();
21
 
730 daniel-mar 22
class OIDplus extends OIDplusBaseClass {
281 daniel-mar 23
        private static /*OIDplusPagePlugin[]*/ $pagePlugins = array();
24
        private static /*OIDplusAuthPlugin[]*/ $authPlugins = array();
289 daniel-mar 25
        private static /*OIDplusLoggerPlugin[]*/ $loggerPlugins = array();
227 daniel-mar 26
        private static /*OIDplusObjectTypePlugin[]*/ $objectTypePlugins = array();
27
        private static /*string[]*/ $enabledObjectTypes = array();
28
        private static /*string[]*/ $disabledObjectTypes = array();
29
        private static /*OIDplusDatabasePlugin[]*/ $dbPlugins = array();
702 daniel-mar 30
        private static /*OIDplusCaptchaPlugin[]*/ $captchaPlugins = array();
274 daniel-mar 31
        private static /*OIDplusSqlSlangPlugin[]*/ $sqlSlangPlugins = array();
355 daniel-mar 32
        private static /*OIDplusLanguagePlugin[]*/ $languagePlugins = array();
449 daniel-mar 33
        private static /*OIDplusDesignPlugin[]*/ $designPlugins = array();
2 daniel-mar 34
 
280 daniel-mar 35
        protected static $html = true;
236 daniel-mar 36
 
362 daniel-mar 37
        /*public*/ const DEFAULT_LANGUAGE = 'enus'; // the language of the source code
355 daniel-mar 38
 
812 daniel-mar 39
        /*public*/ const PATH_RELATIVE = 1;                   // e.g. "../"
40
        /*public*/ const PATH_ABSOLUTE = 2;                   // e.g. "http://www.example.com/oidplus/"
41
        /*public*/ const PATH_ABSOLUTE_CANONICAL = 3;         // e.g. "http://www.example.org/oidplus/" (if baseconfig CANONICAL_SYSTEM_URL is set)
42
        /*public*/ const PATH_RELATIVE_TO_ROOT = 4;           // e.g. "/oidplus/"
43
        /*public*/ const PATH_RELATIVE_TO_ROOT_CANONICAL = 5; // e.g. "/oidplus/" (if baseconfig CANONICAL_SYSTEM_URL is set)
801 daniel-mar 44
 
778 daniel-mar 45
        // These plugin types can contain HTML code and therefore may
46
        // emit (non-setup) CSS/JS code via their manifest.
47
        /*public*/ const INTERACTIVE_PLUGIN_TYPES = array(
48
                'publicPages',
49
                'raPages',
50
                'adminPages',
51
                'objectTypes',
52
                'captcha'
53
        );
54
 
2 daniel-mar 55
        private function __construct() {
56
        }
295 daniel-mar 57
 
263 daniel-mar 58
        # --- Static classes
274 daniel-mar 59
 
263 daniel-mar 60
        private static $baseConfig = null;
61
        private static $old_config_format = false;
261 daniel-mar 62
        public static function baseConfig() {
263 daniel-mar 63
                $first_init = false;
274 daniel-mar 64
 
263 daniel-mar 65
                if ($first_init = is_null(self::$baseConfig)) {
66
                        self::$baseConfig = new OIDplusBaseConfig();
261 daniel-mar 67
                }
68
 
263 daniel-mar 69
                if ($first_init) {
261 daniel-mar 70
                        // Include a file containing various size/depth limitations of OIDs
294 daniel-mar 71
                        // It is important to include it before userdata/baseconfig/config.inc.php was included,
72
                        // so we can give userdata/baseconfig/config.inc.php the chance to override the values.
261 daniel-mar 73
 
496 daniel-mar 74
                        include OIDplus::localpath().'includes/oidplus_limits.inc.php';
261 daniel-mar 75
 
76
                        // Include config file
295 daniel-mar 77
 
496 daniel-mar 78
                        $config_file = OIDplus::localpath() . 'userdata/baseconfig/config.inc.php';
79
                        $config_file_old = OIDplus::localpath() . 'includes/config.inc.php'; // backwards compatibility
295 daniel-mar 80
 
294 daniel-mar 81
                        if (!file_exists($config_file) && file_exists($config_file_old)) {
82
                                $config_file = $config_file_old;
83
                        }
261 daniel-mar 84
 
294 daniel-mar 85
                        if (file_exists($config_file)) {
263 daniel-mar 86
                                if (self::$old_config_format) {
87
                                        // Note: We may only include it once due to backwards compatibility,
88
                                        //       since in version 2.0, the configuration was defined using define() statements
89
                                        // Attention: This does mean that a full re-init (e.g. for test cases) is not possible
90
                                        //            if a version 2.0 config is used!
294 daniel-mar 91
                                        include_once $config_file;
263 daniel-mar 92
                                } else {
294 daniel-mar 93
                                        include $config_file;
263 daniel-mar 94
                                }
261 daniel-mar 95
 
96
                                if (defined('OIDPLUS_CONFIG_VERSION') && (OIDPLUS_CONFIG_VERSION == 2.0)) {
263 daniel-mar 97
                                        self::$old_config_format = true;
274 daniel-mar 98
 
261 daniel-mar 99
                                        // Backwards compatibility 2.0 => 2.1
100
                                        foreach (get_defined_constants(true)['user'] as $name => $value) {
101
                                                $name = str_replace('OIDPLUS_', '', $name);
102
                                                if ($name == 'SESSION_SECRET') $name = 'SERVER_SECRET';
103
                                                if ($name == 'MYSQL_QUERYLOG') $name = 'QUERY_LOGFILE';
104
                                                if (($name == 'MYSQL_PASSWORD') || ($name == 'ODBC_PASSWORD') || ($name == 'PDO_PASSWORD') || ($name == 'PGSQL_PASSWORD')) {
263 daniel-mar 105
                                                        self::$baseConfig->setValue($name, base64_decode($value));
261 daniel-mar 106
                                                } else {
107
                                                        if ($name == 'CONFIG_VERSION') $value = 2.1;
263 daniel-mar 108
                                                        self::$baseConfig->setValue($name, $value);
261 daniel-mar 109
                                                }
110
                                        }
111
                                }
112
                        } else {
496 daniel-mar 113
                                if (!is_dir(OIDplus::localpath().'setup')) {
360 daniel-mar 114
                                        throw new OIDplusConfigInitializationException(_L('File %1 is missing, but setup can\'t be started because its directory missing.','userdata/baseconfig/config.inc.php'));
261 daniel-mar 115
                                } else {
280 daniel-mar 116
                                        if (self::$html) {
811 daniel-mar 117
                                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE_TO_ROOT).'setup/') !== 0) {
801 daniel-mar 118
                                                        header('Location:'.OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/');
360 daniel-mar 119
                                                        die(_L('Redirecting to setup...'));
349 daniel-mar 120
                                                } else {
121
                                                        return self::$baseConfig;
122
                                                }
261 daniel-mar 123
                                        } else {
124
                                                // This can be displayed in e.g. ajax.php
360 daniel-mar 125
                                                throw new OIDplusConfigInitializationException(_L('File %1 is missing. Please run setup again.','userdata/baseconfig/config.inc.php'));
261 daniel-mar 126
                                        }
127
                                }
128
                        }
129
 
130
                        // Check important config settings
131
 
263 daniel-mar 132
                        if (self::$baseConfig->getValue('CONFIG_VERSION') != 2.1) {
801 daniel-mar 133
                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/') !== 0) {
503 daniel-mar 134
                                        throw new OIDplusConfigInitializationException(_L("The information located in %1 is outdated.",realpath($config_file)));
135
                                }
261 daniel-mar 136
                        }
137
 
263 daniel-mar 138
                        if (self::$baseConfig->getValue('SERVER_SECRET', '') === '') {
801 daniel-mar 139
                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/') !== 0) {
503 daniel-mar 140
                                        throw new OIDplusConfigInitializationException(_L("You must set a value for SERVER_SECRET in %1 for the system to operate secure.",realpath($config_file)));
141
                                }
261 daniel-mar 142
                        }
143
                }
144
 
263 daniel-mar 145
                return self::$baseConfig;
261 daniel-mar 146
        }
147
 
263 daniel-mar 148
        private static $config = null;
2 daniel-mar 149
        public static function config() {
263 daniel-mar 150
                if ($first_init = is_null(self::$config)) {
151
                        self::$config = new OIDplusConfig();
2 daniel-mar 152
                }
263 daniel-mar 153
 
154
                if ($first_init) {
155
                        // These are important settings for base functionalities and therefore are not inside plugins
156
                        self::$config->prepareConfigKey('system_title', 'What is the name of your RA?', 'OIDplus 2.0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
157
                                if (empty($value)) {
360 daniel-mar 158
                                        throw new OIDplusException(_L('Please enter a value for the system title.'));
263 daniel-mar 159
                                }
160
                        });
161
                        self::$config->prepareConfigKey('admin_email', 'E-Mail address of the system administrator', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
162
                                if (!empty($value) && !OIDplus::mailUtils()->validMailAddress($value)) {
360 daniel-mar 163
                                        throw new OIDplusException(_L('This is not a correct email address'));
263 daniel-mar 164
                                }
165
                        });
875 daniel-mar 166
                        self::$config->prepareConfigKey('global_cc', 'Global CC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function(&$value) {
167
                                $value = trim($value);
168
                                if ($value === '') return;
169
                                $addrs = explode(';', $value);
170
                                foreach ($addrs as $addr) {
171
                                        $addr = trim($addr);
172
                                        if (!empty($addr) && !OIDplus::mailUtils()->validMailAddress($addr)) {
173
                                                throw new OIDplusException(_L('%1 is not a correct email address',$addr));
174
                                        }
263 daniel-mar 175
                                }
176
                        });
875 daniel-mar 177
                        self::$config->prepareConfigKey('global_bcc', 'Global BCC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function(&$value) {
178
                                $value = trim($value);
179
                                if ($value === '') return;
180
                                $addrs = explode(';', $value);
181
                                foreach ($addrs as $addr) {
182
                                        $addr = trim($addr);
183
                                        if (!empty($addr) && !OIDplus::mailUtils()->validMailAddress($addr)) {
184
                                                throw new OIDplusException(_L('%1 is not a correct email address',$addr));
185
                                        }
186
                                }
187
                        });
263 daniel-mar 188
                        self::$config->prepareConfigKey('objecttypes_initialized', 'List of object type plugins that were initialized once', '', OIDplusConfig::PROTECTION_READONLY, function($value) {
189
                                // Nothing here yet
190
                        });
191
                        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) {
192
                                # 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?
193
 
194
                                $ary = explode(';',$value);
195
                                $uniq_ary = array_unique($ary);
196
 
197
                                if (count($ary) != count($uniq_ary)) {
360 daniel-mar 198
                                        throw new OIDplusException(_L('Please check your input. Some object types are double.'));
263 daniel-mar 199
                                }
200
 
201
                                foreach ($ary as $ot_check) {
202
                                        $ns_found = false;
203
                                        foreach (OIDplus::getEnabledObjectTypes() as $ot) {
204
                                                if ($ot::ns() == $ot_check) {
205
                                                        $ns_found = true;
206
                                                        break;
207
                                                }
208
                                        }
209
                                        foreach (OIDplus::getDisabledObjectTypes() as $ot) {
210
                                                if ($ot::ns() == $ot_check) {
211
                                                        $ns_found = true;
212
                                                        break;
213
                                                }
214
                                        }
215
                                        if (!$ns_found) {
360 daniel-mar 216
                                                throw new OIDplusException(_L('Please check your input. Namespace "%1" is not found',$ot_check));
263 daniel-mar 217
                                        }
218
                                }
219
                        });
220
                        self::$config->prepareConfigKey('oidplus_private_key', 'Private key for this system', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
221
                                // Nothing here yet
222
                        });
223
                        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) {
224
                                // Nothing here yet
225
                        });
324 daniel-mar 226
                        self::$config->prepareConfigKey('last_known_system_url', 'Last known System URL', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
227
                                // Nothing here yet
228
                        });
412 daniel-mar 229
                        self::$config->prepareConfigKey('last_known_version', 'Last known OIDplus Version', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
230
                                // Nothing here yet
231
                        });
635 daniel-mar 232
                        self::$config->prepareConfigKey('default_ra_auth_method', 'Default auth method used for generating password of RAs (must exist in plugins/[vendorname]/auth/)?', 'A3_bcrypt', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
453 daniel-mar 233
                                $good = true;
234
                                if (strpos($value,'/') !== false) $good = false;
235
                                if (strpos($value,'\\') !== false) $good = false;
236
                                if (strpos($value,'..') !== false) $good = false;
237
                                if (!$good) {
238
                                        throw new OIDplusException(_L('Invalid auth plugin folder name. Do only enter a folder name, not an absolute or relative path'));
239
                                }
240
 
926 daniel-mar 241
                                if (!wildcard_is_dir(OIDplus::localpath().'plugins/'.'*'.'/auth/'.$value)) {
635 daniel-mar 242
                                        throw new OIDplusException(_L('The auth plugin "%1" does not exist in plugin directory %2',$value,'plugins/[vendorname]/auth/'));
453 daniel-mar 243
                                }
244
                        });
263 daniel-mar 245
                }
246
 
247
                return self::$config;
2 daniel-mar 248
        }
249
 
263 daniel-mar 250
        private static $gui = null;
2 daniel-mar 251
        public static function gui() {
263 daniel-mar 252
                if (is_null(self::$gui)) {
253
                        self::$gui = new OIDplusGui();
86 daniel-mar 254
                }
263 daniel-mar 255
                return self::$gui;
2 daniel-mar 256
        }
257
 
263 daniel-mar 258
        private static $authUtils = null;
2 daniel-mar 259
        public static function authUtils() {
263 daniel-mar 260
                if (is_null(self::$authUtils)) {
261
                        self::$authUtils = new OIDplusAuthUtils();
86 daniel-mar 262
                }
263 daniel-mar 263
                return self::$authUtils;
2 daniel-mar 264
        }
265
 
263 daniel-mar 266
        private static $mailUtils = null;
250 daniel-mar 267
        public static function mailUtils() {
263 daniel-mar 268
                if (is_null(self::$mailUtils)) {
269
                        self::$mailUtils = new OIDplusMailUtils();
250 daniel-mar 270
                }
263 daniel-mar 271
                return self::$mailUtils;
250 daniel-mar 272
        }
273
 
557 daniel-mar 274
        private static $cookieUtils = null;
275
        public static function cookieUtils() {
276
                if (is_null(self::$cookieUtils)) {
277
                        self::$cookieUtils = new OIDplusCookieUtils();
278
                }
279
                return self::$cookieUtils;
280
        }
281
 
263 daniel-mar 282
        private static $menuUtils = null;
250 daniel-mar 283
        public static function menuUtils() {
263 daniel-mar 284
                if (is_null(self::$menuUtils)) {
285
                        self::$menuUtils = new OIDplusMenuUtils();
250 daniel-mar 286
                }
263 daniel-mar 287
                return self::$menuUtils;
250 daniel-mar 288
        }
289
 
263 daniel-mar 290
        private static $logger = null;
115 daniel-mar 291
        public static function logger() {
263 daniel-mar 292
                if (is_null(self::$logger)) {
293
                        self::$logger = new OIDplusLogger();
115 daniel-mar 294
                }
263 daniel-mar 295
                return self::$logger;
115 daniel-mar 296
        }
297
 
274 daniel-mar 298
        # --- SQL slang plugin
299
 
300
        private static function registerSqlSlangPlugin(OIDplusSqlSlangPlugin $plugin) {
301
                $name = $plugin::id();
591 daniel-mar 302
                if ($name === '') return false;
274 daniel-mar 303
 
449 daniel-mar 304
                if (isset(self::$sqlSlangPlugins[$name])) {
451 daniel-mar 305
                        $plugintype_hf = _L('SQL slang');
592 daniel-mar 306
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
449 daniel-mar 307
                }
308
 
274 daniel-mar 309
                self::$sqlSlangPlugins[$name] = $plugin;
310
 
311
                return true;
312
        }
313
 
314
        public static function getSqlSlangPlugins() {
315
                return self::$sqlSlangPlugins;
316
        }
317
 
318 daniel-mar 318
        public static function getSqlSlangPlugin($id)/*: ?OIDplusSqlSlangPlugin*/ {
319
                if (isset(self::$sqlSlangPlugins[$id])) {
320
                        return self::$sqlSlangPlugins[$id];
321
                } else {
322
                        return null;
323
                }
324
        }
325
 
230 daniel-mar 326
        # --- Database plugin
74 daniel-mar 327
 
227 daniel-mar 328
        private static function registerDatabasePlugin(OIDplusDatabasePlugin $plugin) {
275 daniel-mar 329
                $name = $plugin::id();
591 daniel-mar 330
                if ($name === '') return false;
150 daniel-mar 331
 
449 daniel-mar 332
                if (isset(self::$dbPlugins[$name])) {
333
                        $plugintype_hf = _L('Database');
592 daniel-mar 334
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
449 daniel-mar 335
                }
336
 
150 daniel-mar 337
                self::$dbPlugins[$name] = $plugin;
338
 
339
                return true;
340
        }
341
 
342
        public static function getDatabasePlugins() {
343
                return self::$dbPlugins;
344
        }
345
 
295 daniel-mar 346
        public static function getActiveDatabasePlugin() {
702 daniel-mar 347
                $db_plugin_name = OIDplus::baseConfig()->getValue('DATABASE_PLUGIN','');
348
                if ($db_plugin_name === '') {
360 daniel-mar 349
                        throw new OIDplusConfigInitializationException(_L('No database plugin selected in config file'));
260 daniel-mar 350
                }
702 daniel-mar 351
                if (!isset(self::$dbPlugins[$db_plugin_name])) {
360 daniel-mar 352
                        throw new OIDplusConfigInitializationException(_L('Database plugin "%1" not found',$db_plugin_name));
227 daniel-mar 353
                }
702 daniel-mar 354
                return self::$dbPlugins[$db_plugin_name];
227 daniel-mar 355
        }
356
 
295 daniel-mar 357
        private static $dbMainSession = null;
358
        public static function db() {
359
                if (is_null(self::$dbMainSession)) {
360
                        self::$dbMainSession = self::getActiveDatabasePlugin()->newConnection();
361
                }
362
                if (!self::$dbMainSession->isConnected()) self::$dbMainSession->connect();
363
                return self::$dbMainSession;
364
        }
365
 
366
        private static $dbIsolatedSession = null;
367
        public static function dbIsolated() {
368
                if (is_null(self::$dbIsolatedSession)) {
369
                        self::$dbIsolatedSession = self::getActiveDatabasePlugin()->newConnection();
370
                }
371
                if (!self::$dbIsolatedSession->isConnected()) self::$dbIsolatedSession->connect();
372
                return self::$dbIsolatedSession;
373
        }
374
 
702 daniel-mar 375
        # --- CAPTCHA plugin
376
 
377
        private static function registerCaptchaPlugin(OIDplusCaptchaPlugin $plugin) {
378
                $name = $plugin::id();
379
                if ($name === '') return false;
380
 
381
                if (isset(self::$captchaPlugins[$name])) {
382
                        $plugintype_hf = _L('CAPTCHA');
383
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
384
                }
385
 
386
                self::$captchaPlugins[$name] = $plugin;
387
 
388
                return true;
389
        }
390
 
391
        public static function getCaptchaPlugins() {
392
                return self::$captchaPlugins;
393
        }
394
 
704 daniel-mar 395
        public static function getActiveCaptchaPluginId() {
702 daniel-mar 396
                $captcha_plugin_name = OIDplus::baseConfig()->getValue('CAPTCHA_PLUGIN', '');
397
 
398
                if (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false) && ($captcha_plugin_name === '')) {
399
                        // Legacy config file support!
400
                        $captcha_plugin_name = 'ReCAPTCHA';
401
                }
402
 
704 daniel-mar 403
                if ($captcha_plugin_name === '') $captcha_plugin_name = 'None'; // the "None" plugin is a must-have!
702 daniel-mar 404
 
704 daniel-mar 405
                return $captcha_plugin_name;
406
        }
407
 
408
        public static function getActiveCaptchaPlugin() {
409
                $captcha_plugin_name = OIDplus::getActiveCaptchaPluginId();
410
 
702 daniel-mar 411
                if (!isset(self::$captchaPlugins[$captcha_plugin_name])) {
412
                        throw new OIDplusConfigInitializationException(_L('CAPTCHA plugin "%1" not found',$captcha_plugin_name));
413
                }
414
                return self::$captchaPlugins[$captcha_plugin_name];
415
        }
416
 
227 daniel-mar 417
        # --- Page plugin
418
 
224 daniel-mar 419
        private static function registerPagePlugin(OIDplusPagePlugin $plugin) {
281 daniel-mar 420
                self::$pagePlugins[] = $plugin;
61 daniel-mar 421
 
422
                return true;
423
        }
424
 
281 daniel-mar 425
        public static function getPagePlugins() {
426
                return self::$pagePlugins;
61 daniel-mar 427
        }
428
 
227 daniel-mar 429
        # --- Auth plugin
430
 
431
        private static function registerAuthPlugin(OIDplusAuthPlugin $plugin) {
456 daniel-mar 432
                if (OIDplus::baseConfig()->getValue('DEBUG')) {
433
                        $password = generateRandomString(25);
459 daniel-mar 434
 
461 daniel-mar 435
                        try {
436
                                $authInfo = $plugin->generate($password);
437
                        } catch (OIDplusException $e) {
438
                                // This can happen when the AuthKey or Salt is too long
439
                                throw new OIDplusException(_L('Auth plugin "%1" is erroneous: %2',basename($plugin->getPluginDirectory()),$e->getMessage()));
440
                        }
459 daniel-mar 441
                        $salt = $authInfo->getSalt();
461 daniel-mar 442
                        $authKey = $authInfo->getAuthKey();
459 daniel-mar 443
 
461 daniel-mar 444
                        $authInfo_SaltDiff = clone $authInfo;
445
                        $authInfo_SaltDiff->setSalt(strrev($authInfo_SaltDiff->getSalt()));
446
 
447
                        $authInfo_AuthKeyDiff = clone $authInfo;
448
                        $authInfo_AuthKeyDiff->setAuthKey(strrev($authInfo_AuthKeyDiff->getAuthKey()));
449
 
450
                        if ((!$plugin->verify($authInfo,$password)) ||
451
                           (!empty($salt) && $plugin->verify($authInfo_SaltDiff,$password)) ||
452
                           ($plugin->verify($authInfo_AuthKeyDiff,$password)) ||
453
                           ($plugin->verify($authInfo,$password.'x'))) {
456 daniel-mar 454
                                throw new OIDplusException(_L('Auth plugin "%1" is erroneous: Generate/Verify self test failed',basename($plugin->getPluginDirectory())));
455
                        }
453 daniel-mar 456
                }
457
 
227 daniel-mar 458
                self::$authPlugins[] = $plugin;
459
                return true;
460
        }
461
 
221 daniel-mar 462
        public static function getAuthPlugins() {
463
                return self::$authPlugins;
464
        }
465
 
355 daniel-mar 466
        # --- Language plugin
467
 
468
        private static function registerLanguagePlugin(OIDplusLanguagePlugin $plugin) {
469
                self::$languagePlugins[] = $plugin;
470
                return true;
471
        }
472
 
473
        public static function getLanguagePlugins() {
474
                return self::$languagePlugins;
475
        }
476
 
449 daniel-mar 477
        # --- Design plugin
478
 
479
        private static function registerDesignPlugin(OIDplusDesignPlugin $plugin) {
480
                self::$designPlugins[] = $plugin;
481
                return true;
482
        }
483
 
484
        public static function getDesignPlugins() {
485
                return self::$designPlugins;
486
        }
487
 
819 daniel-mar 488
        public static function getActiveDesignPlugin() {
489
                $plugins = OIDplus::getDesignPlugins();
490
                foreach ($plugins as $plugin) {
491
                        if ((basename($plugin->getPluginDirectory())) == OIDplus::config()->getValue('design','default')) {
492
                                return $plugin;
493
                        }
494
                }
495
                return null;
496
        }
497
 
289 daniel-mar 498
        # --- Logger plugin
499
 
500
        private static function registerLoggerPlugin(OIDplusLoggerPlugin $plugin) {
501
                self::$loggerPlugins[] = $plugin;
502
                return true;
503
        }
504
 
505
        public static function getLoggerPlugins() {
506
                return self::$loggerPlugins;
507
        }
508
 
227 daniel-mar 509
        # --- Object type plugin
510
 
511
        private static function registerObjectTypePlugin(OIDplusObjectTypePlugin $plugin) {
512
                self::$objectTypePlugins[] = $plugin;
513
 
514
                $ot = $plugin::getObjectTypeClassName();
515
                self::registerObjectType($ot);
516
 
517
                return true;
518
        }
519
 
224 daniel-mar 520
        private static function registerObjectType($ot) {
66 daniel-mar 521
                $ns = $ot::ns();
860 daniel-mar 522
                if (empty($ns)) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Namespace must not be empty',$ot));
66 daniel-mar 523
 
860 daniel-mar 524
                // Currently, we must enforce that namespaces in objectType plugins are lowercase, because prefilterQuery() makes all namespaces lowercase and the DBMS should be case-sensitive
525
                if ($ns != strtolower($ns)) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Namespace %2 must be lower-case',$ot,$ns));
66 daniel-mar 526
 
860 daniel-mar 527
                $root = $ot::root();
528
                if (!str_starts_with($root,$ns.':')) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Root node (%2) is in wrong namespace (needs starts with %3)!',$ot,$root,$ns.':'));
529
 
66 daniel-mar 530
                $ns_found = false;
227 daniel-mar 531
                foreach (array_merge(OIDplus::getEnabledObjectTypes(), OIDplus::getDisabledObjectTypes()) as $test_ot) {
66 daniel-mar 532
                        if ($test_ot::ns() == $ns) {
533
                                $ns_found = true;
534
                                break;
535
                        }
536
                }
537
                if ($ns_found) {
360 daniel-mar 538
                        throw new OIDplusException(_L('Attention: Two objectType plugins use the same namespace "%1"!',$ns));
66 daniel-mar 539
                }
540
 
541
                $init = OIDplus::config()->getValue("objecttypes_initialized");
542
                $init_ary = empty($init) ? array() : explode(';', $init);
70 daniel-mar 543
                $init_ary = array_map('trim', $init_ary);
66 daniel-mar 544
 
545
                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
546
                $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
70 daniel-mar 547
                $enabled_ary = array_map('trim', $enabled_ary);
66 daniel-mar 548
 
79 daniel-mar 549
                $do_enable = false;
550
                if (in_array($ns, $enabled_ary)) {
447 daniel-mar 551
                        // If it is in the list of enabled object types, it is enabled (obviously)
79 daniel-mar 552
                        $do_enable = true;
553
                } else {
447 daniel-mar 554
                        if (!OIDplus::config()->getValue('oobe_objects_done')) {
555
                                // If the OOBE wizard is NOT done, then just enable the "oid" object type by default
79 daniel-mar 556
                                $do_enable = $ns == 'oid';
557
                        } else {
447 daniel-mar 558
                                // If the OOBE wizard was done (once), then
559
                                // we will enable all object types which were never initialized
560
                                // (i.e. a plugin folder was freshly added)
79 daniel-mar 561
                                $do_enable = !in_array($ns, $init_ary);
562
                        }
563
                }
564
 
565
                if ($do_enable) {
227 daniel-mar 566
                        self::$enabledObjectTypes[] = $ot;
567
                        usort(self::$enabledObjectTypes, function($a, $b) {
66 daniel-mar 568
                                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
569
                                $enabled_ary = explode(';', $enabled);
570
 
571
                                $idx_a = array_search($a::ns(), $enabled_ary);
572
                                $idx_b = array_search($b::ns(), $enabled_ary);
573
 
574
                                if ($idx_a == $idx_b) {
575
                                    return 0;
576
                                }
577
                                return ($idx_a > $idx_b) ? +1 : -1;
578
                        });
74 daniel-mar 579
                } else {
580
                        self::$disabledObjectTypes[] = $ot;
66 daniel-mar 581
                }
582
 
583
                if (!in_array($ns, $init_ary)) {
584
                        // Was never initialized before, so we add it to the list of enabled object types once
585
 
79 daniel-mar 586
                        if ($do_enable) {
587
                                $enabled_ary[] = $ns;
672 daniel-mar 588
                                // Important: Don't validate the input, because the other object types might not be initialized yet! So use setValueNoCallback() instead setValue().
589
                                OIDplus::config()->setValueNoCallback("objecttypes_enabled", implode(';', $enabled_ary));
79 daniel-mar 590
                        }
66 daniel-mar 591
 
592
                        $init_ary[] = $ns;
593
                        OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
594
                }
61 daniel-mar 595
        }
596
 
227 daniel-mar 597
        public static function getObjectTypePlugins() {
598
                return self::$objectTypePlugins;
61 daniel-mar 599
        }
600
 
227 daniel-mar 601
        public static function getObjectTypePluginsEnabled() {
602
                $res = array();
603
                foreach (self::$objectTypePlugins as $plugin) {
604
                        $ot = $plugin::getObjectTypeClassName();
605
                        if (in_array($ot, self::$enabledObjectTypes)) $res[] = $plugin;
606
                }
607
                return $res;
74 daniel-mar 608
        }
609
 
227 daniel-mar 610
        public static function getObjectTypePluginsDisabled() {
611
                $res = array();
612
                foreach (self::$objectTypePlugins as $plugin) {
613
                        $ot = $plugin::getObjectTypeClassName();
614
                        if (in_array($ot, self::$disabledObjectTypes)) $res[] = $plugin;
74 daniel-mar 615
                }
227 daniel-mar 616
                return $res;
74 daniel-mar 617
        }
618
 
227 daniel-mar 619
        public static function getEnabledObjectTypes() {
620
                return self::$enabledObjectTypes;
621
        }
74 daniel-mar 622
 
227 daniel-mar 623
        public static function getDisabledObjectTypes() {
624
                return self::$disabledObjectTypes;
625
        }
74 daniel-mar 626
 
277 daniel-mar 627
        # --- Plugin handling functions
628
 
320 daniel-mar 629
        public static function getAllPlugins()/*: array*/ {
630
                $res = array();
631
                $res = array_merge($res, self::$pagePlugins);
632
                $res = array_merge($res, self::$authPlugins);
633
                $res = array_merge($res, self::$loggerPlugins);
634
                $res = array_merge($res, self::$objectTypePlugins);
635
                $res = array_merge($res, self::$dbPlugins);
702 daniel-mar 636
                $res = array_merge($res, self::$captchaPlugins);
320 daniel-mar 637
                $res = array_merge($res, self::$sqlSlangPlugins);
355 daniel-mar 638
                $res = array_merge($res, self::$languagePlugins);
449 daniel-mar 639
                $res = array_merge($res, self::$designPlugins);
320 daniel-mar 640
                return $res;
641
        }
642
 
321 daniel-mar 643
        public static function getPluginByOid($oid)/*: ?OIDplusPlugin*/ {
320 daniel-mar 644
                $plugins = self::getAllPlugins();
321 daniel-mar 645
                foreach ($plugins as $plugin) {
646
                        if (oid_dotnotation_equal($plugin->getManifest()->getOid(), $oid)) {
647
                                return $plugin;
320 daniel-mar 648
                        }
649
                }
650
                return null;
651
        }
652
 
380 daniel-mar 653
        public static function getPluginByClassName($classname)/*: ?OIDplusPlugin*/ {
654
                $plugins = self::getAllPlugins();
655
                foreach ($plugins as $plugin) {
656
                        if (get_class($plugin) === $classname) {
657
                                return $plugin;
658
                        }
659
                }
660
                return null;
277 daniel-mar 661
        }
662
 
594 daniel-mar 663
        /**
664
        * @return array<OIDplusPluginManifest>|array<string,array<string,OIDplusPluginManifest>>
665
        */
693 daniel-mar 666
        public static function getAllPluginManifests($pluginFolderMasks='*', $flat=true): array {
277 daniel-mar 667
                $out = array();
279 daniel-mar 668
                // Note: glob() will sort by default, so we do not need a page priority attribute.
669
                //       So you just need to use a numeric plugin directory prefix (padded).
693 daniel-mar 670
                $ary = array();
671
                foreach (explode(',',$pluginFolderMasks) as $pluginFolderMask) {
672
                        $ary = array_merge($ary,glob(OIDplus::localpath().'plugins/'.'*'.'/'.$pluginFolderMask.'/'.'*'.'/manifest.xml'));
673
                }
646 daniel-mar 674
 
675
                // Sort the plugins by their type and name, as if they would be in a single vendor-folder!
676
                uasort($ary, function($a,$b) {
677
                        if ($a == $b) return 0;
678
 
679
                        $ary = explode('/',$a);
680
                        $bry = explode('/',$b);
681
 
682
                        // First sort by type (publicPage, auth, database, language, ...)
683
                        $a_type = $ary[count($ary)-1-2];
684
                        $b_type = $bry[count($bry)-1-2];
685
                        if ($a_type < $b_type) return -1;
686
                        if ($a_type > $b_type) return 1;
687
 
688
                        // Then sort by name (090_login, 100_whois, etc.)
689
                        $a_name = $ary[count($ary)-1-1];
690
                        $b_name = $bry[count($bry)-1-1];
691
                        if ($a_name < $b_name) return -1;
692
                        if ($a_name > $b_name) return 1;
693
 
694
                        // If it is still equal, then finally sort by vendorname
695
                        $a_vendor = $ary[count($ary)-1-3];
696
                        $b_vendor = $bry[count($bry)-1-3];
697
                        if ($a_vendor < $b_vendor) return -1;
698
                        if ($a_vendor > $b_vendor) return 1;
699
                        return 0;
700
                });
701
 
277 daniel-mar 702
                foreach ($ary as $ini) {
703
                        if (!file_exists($ini)) continue;
704
 
307 daniel-mar 705
                        $manifest = new OIDplusPluginManifest();
706
                        $manifest->loadManifest($ini);
277 daniel-mar 707
 
473 daniel-mar 708
                        $class_name = $manifest->getPhpMainClass();
709
                        if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
710
                                continue;
711
                        }
712
 
307 daniel-mar 713
                        if ($flat) {
714
                                $out[] = $manifest;
715
                        } else {
716
                                $plugintype_folder = basename(dirname(dirname($ini)));
717
                                $pluginname_folder = basename(dirname($ini));
718
 
719
                                if (!isset($out[$plugintype_folder])) $out[$plugintype_folder] = array();
720
                                if (!isset($out[$plugintype_folder][$pluginname_folder])) $out[$plugintype_folder][$pluginname_folder] = array();
721
                                $out[$plugintype_folder][$pluginname_folder] = $manifest;
722
                        }
277 daniel-mar 723
                }
724
                return $out;
725
        }
726
 
594 daniel-mar 727
        /**
728
        * @return array<string>
729
        */
277 daniel-mar 730
        public static function registerAllPlugins($pluginDirName, $expectedPluginClass, $registerCallback): array {
731
                $out = array();
525 daniel-mar 732
                if (is_array($pluginDirName)) {
733
                        $ary = array();
734
                        foreach ($pluginDirName as $pluginDirName_) {
735
                                $ary = array_merge($ary, self::getAllPluginManifests($pluginDirName_, false));
736
                        }
737
                } else {
738
                        $ary = self::getAllPluginManifests($pluginDirName, false);
739
                }
320 daniel-mar 740
                $known_plugin_oids = array();
456 daniel-mar 741
                if (OIDplus::baseConfig()->getValue('DEBUG')) {
742
                        $fake_feature = uuid_to_oid(gen_uuid());
588 daniel-mar 743
                } else {
744
                        $fake_feature = null;
456 daniel-mar 745
                }
277 daniel-mar 746
                foreach ($ary as $plugintype_folder => $bry) {
438 daniel-mar 747
                        foreach ($bry as $pluginname_folder => $manifest) {
748
                                $class_name = $manifest->getPhpMainClass();
749
 
750
                                // Before we load the plugin, we want to make some checks to confirm
751
                                // that the plugin is working correctly.
752
 
307 daniel-mar 753
                                if (!$class_name) {
438 daniel-mar 754
                                        throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Manifest does not declare a PHP main class'));
277 daniel-mar 755
                                }
297 daniel-mar 756
                                if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
757
                                        continue;
758
                                }
292 daniel-mar 759
                                if (!class_exists($class_name)) {
438 daniel-mar 760
                                        throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Manifest declares PHP main class as "%1", but it could not be found',$class_name));
292 daniel-mar 761
                                }
279 daniel-mar 762
                                if (!is_subclass_of($class_name, $expectedPluginClass)) {
438 daniel-mar 763
                                        throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Plugin main class "%1" is expected to be a subclass of "%2"',$class_name,$expectedPluginClass));
279 daniel-mar 764
                                }
438 daniel-mar 765
                                if (($class_name!=$manifest->getTypeClass()) && (!is_subclass_of($class_name,$manifest->getTypeClass()))) {
766
                                        throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Plugin main class "%1" is expected to be a subclass of "%2", according to type declared in manifest',$class_name,$manifest->getTypeClass()));
308 daniel-mar 767
                                }
438 daniel-mar 768
                                if (($manifest->getTypeClass()!=$expectedPluginClass) && (!is_subclass_of($manifest->getTypeClass(),$expectedPluginClass))) {
769
                                        throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Class declared in manifest is "%1" does not fit expected class for this plugin type "%2"',$manifest->getTypeClass(),$expectedPluginClass));
308 daniel-mar 770
                                }
771
 
438 daniel-mar 772
                                $plugin_oid = $manifest->getOid();
320 daniel-mar 773
                                if (!$plugin_oid) {
438 daniel-mar 774
                                        throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Does not have an OID'));
320 daniel-mar 775
                                }
776
                                if (!oid_valid_dotnotation($plugin_oid, false, false, 2)) {
438 daniel-mar 777
                                        throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Plugin OID "%1" is invalid (needs to be valid dot-notation)',$plugin_oid));
320 daniel-mar 778
                                }
779
                                if (isset($known_plugin_oids[$plugin_oid])) {
438 daniel-mar 780
                                        throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('The OID "%1" is already used by the plugin "%2"',$plugin_oid,$known_plugin_oids[$plugin_oid]));
320 daniel-mar 781
                                }
646 daniel-mar 782
 
632 daniel-mar 783
                                $full_plugin_dir = dirname($manifest->getManifestFile());
784
                                $full_plugin_dir = substr($full_plugin_dir, strlen(OIDplus::localpath()));
988 daniel-mar 785
 
786
                                $dir_is_viathinksoft = str_starts_with($full_plugin_dir, 'plugins/viathinksoft/') || str_starts_with($full_plugin_dir, 'plugins\\viathinksoft\\');
787
                                $oid_is_viathinksoft = str_starts_with($plugin_oid, '1.3.6.1.4.1.37476.2.5.2.4.'); // { iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) 37476 products(2) oidplus(5) v2(2) plugins(4) }
788
                                if ($dir_is_viathinksoft != $oid_is_viathinksoft) {
635 daniel-mar 789
                                        throw new OIDplusException(_L('Plugin "%1/%2" is misplaced',$plugintype_folder,$pluginname_folder).': '._L('The plugin is in the wrong folder. The folder %1 can only be used by official ViaThinkSoft plugins','plugins/viathinksoft/'));
632 daniel-mar 790
                                }
320 daniel-mar 791
 
632 daniel-mar 792
                                $known_plugin_oids[$plugin_oid] = $plugintype_folder.'/'.$pluginname_folder;
793
 
438 daniel-mar 794
                                $obj = new $class_name();
456 daniel-mar 795
 
796
                                if (OIDplus::baseConfig()->getValue('DEBUG')) {
797
                                        if ($obj->implementsFeature($fake_feature)) {
798
                                                // see https://devblogs.microsoft.com/oldnewthing/20040211-00/?p=40663
799
                                                throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('implementsFeature() always returns true'));
800
                                        }
438 daniel-mar 801
                                }
802
 
778 daniel-mar 803
                                // TODO: Maybe as additional plugin-test, we should also check if plugins are allowed to define CSS/JS, i.e. the plugin type is element of OIDplus::INTERACTIVE_PLUGIN_TYPES
988 daniel-mar 804
                                $tmp = $manifest->getManifestLinkedFiles();
438 daniel-mar 805
                                foreach ($tmp as $file) {
806
                                        if (!file_exists($file)) {
807
                                                throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('File %1 was defined in manifest, but it is not existing',$file));
808
                                        }
809
                                }
810
 
811
                                // Now we can continue
812
 
279 daniel-mar 813
                                $out[] = $class_name;
814
                                if (!is_null($registerCallback)) {
438 daniel-mar 815
                                        call_user_func($registerCallback, $obj);
444 daniel-mar 816
 
817
                                        // Alternative approaches:
818
                                        //$registerCallback[0]::{$registerCallback[1]}($obj);
819
                                        // or:
820
                                        //forward_static_call($registerCallback, $obj);
279 daniel-mar 821
                                }
277 daniel-mar 822
                        }
823
 
824
                }
825
                return $out;
826
        }
827
 
227 daniel-mar 828
        # --- Initialization of OIDplus
206 daniel-mar 829
 
374 daniel-mar 830
        public static function init($html=true, $keepBaseConfig=true) {
236 daniel-mar 831
                self::$html = $html;
832
 
263 daniel-mar 833
                // Reset internal state, so we can re-init verything if required
274 daniel-mar 834
 
263 daniel-mar 835
                if (self::$old_config_format) {
778 daniel-mar 836
                        // We need to do this, because define() cannot be undone
263 daniel-mar 837
                        // Note: This can only happen in very special cases (e.g. test cases) where you call init() twice
360 daniel-mar 838
                        throw new OIDplusConfigInitializationException(_L('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.'));
263 daniel-mar 839
                }
274 daniel-mar 840
 
263 daniel-mar 841
                self::$config = null;
374 daniel-mar 842
                if (!$keepBaseConfig) self::$baseConfig = null;  // for test cases we need to be able to control base config and setting values manually, so $keepBaseConfig needs to be true
263 daniel-mar 843
                self::$gui = null;
844
                self::$authUtils = null;
845
                self::$mailUtils = null;
846
                self::$menuUtils = null;
847
                self::$logger = null;
295 daniel-mar 848
                self::$dbMainSession = null;
849
                self::$dbIsolatedSession = null;
263 daniel-mar 850
                self::$pagePlugins = array();
851
                self::$authPlugins = array();
289 daniel-mar 852
                self::$loggerPlugins = array();
263 daniel-mar 853
                self::$objectTypePlugins = array();
854
                self::$enabledObjectTypes = array();
855
                self::$disabledObjectTypes = array();
856
                self::$dbPlugins = array();
702 daniel-mar 857
                self::$captchaPlugins = array();
274 daniel-mar 858
                self::$sqlSlangPlugins = array();
355 daniel-mar 859
                self::$languagePlugins = array();
449 daniel-mar 860
                self::$designPlugins = array();
263 daniel-mar 861
                self::$system_id_cache = null;
862
                self::$sslAvailableCache = null;
468 daniel-mar 863
                self::$translationArray = array();
74 daniel-mar 864
 
263 daniel-mar 865
                // Continue...
866
 
294 daniel-mar 867
                OIDplus::baseConfig(); // this loads the base configuration located in userdata/baseconfig/config.inc.php (once!)
263 daniel-mar 868
                                       // You can do changes to the configuration afterwards using OIDplus::baseConfig()->...
869
 
150 daniel-mar 870
                // Register database types (highest priority)
871
 
274 daniel-mar 872
                // SQL slangs
873
 
294 daniel-mar 874
                self::registerAllPlugins('sqlSlang', 'OIDplusSqlSlangPlugin', array('OIDplus','registerSqlSlangPlugin'));
274 daniel-mar 875
                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
876
                        $plugin->init($html);
877
                }
878
 
879
                // Database providers
880
 
277 daniel-mar 881
                self::registerAllPlugins('database', 'OIDplusDatabasePlugin', array('OIDplus','registerDatabasePlugin'));
237 daniel-mar 882
                foreach (OIDplus::getDatabasePlugins() as $plugin) {
883
                        $plugin->init($html);
884
                }
885
 
42 daniel-mar 886
                // Do redirect stuff etc.
74 daniel-mar 887
 
230 daniel-mar 888
                self::isSslAvailable(); // This function does automatic redirects
61 daniel-mar 889
 
263 daniel-mar 890
                // Construct the configuration manager
66 daniel-mar 891
 
263 daniel-mar 892
                OIDplus::config(); // During the construction, various system settings are prepared if required
66 daniel-mar 893
 
74 daniel-mar 894
                // Initialize public / private keys
895
 
227 daniel-mar 896
                OIDplus::getPkiStatus(true);
74 daniel-mar 897
 
237 daniel-mar 898
                // Register non-DB plugins
74 daniel-mar 899
 
525 daniel-mar 900
                self::registerAllPlugins(array('publicPages', 'raPages', 'adminPages'), 'OIDplusPagePlugin', array('OIDplus','registerPagePlugin'));
277 daniel-mar 901
                self::registerAllPlugins('auth', 'OIDplusAuthPlugin', array('OIDplus','registerAuthPlugin'));
289 daniel-mar 902
                self::registerAllPlugins('logger', 'OIDplusLoggerPlugin', array('OIDplus','registerLoggerPlugin'));
825 daniel-mar 903
                OIDplusLogger::reLogMissing(); // Some previous plugins might have tried to log. Repeat that now.
277 daniel-mar 904
                self::registerAllPlugins('objectTypes', 'OIDplusObjectTypePlugin', array('OIDplus','registerObjectTypePlugin'));
355 daniel-mar 905
                self::registerAllPlugins('language', 'OIDplusLanguagePlugin', array('OIDplus','registerLanguagePlugin'));
449 daniel-mar 906
                self::registerAllPlugins('design', 'OIDplusDesignPlugin', array('OIDplus','registerDesignPlugin'));
778 daniel-mar 907
                self::registerAllPlugins('captcha', 'OIDplusCaptchaPlugin', array('OIDplus','registerCaptchaPlugin'));
150 daniel-mar 908
 
237 daniel-mar 909
                // Initialize non-DB plugins
224 daniel-mar 910
 
281 daniel-mar 911
                foreach (OIDplus::getPagePlugins() as $plugin) {
74 daniel-mar 912
                        $plugin->init($html);
913
                }
230 daniel-mar 914
                foreach (OIDplus::getAuthPlugins() as $plugin) {
915
                        $plugin->init($html);
916
                }
289 daniel-mar 917
                foreach (OIDplus::getLoggerPlugins() as $plugin) {
918
                        $plugin->init($html);
919
                }
230 daniel-mar 920
                foreach (OIDplus::getObjectTypePlugins() as $plugin) {
921
                        $plugin->init($html);
922
                }
355 daniel-mar 923
                foreach (OIDplus::getLanguagePlugins() as $plugin) {
924
                        $plugin->init($html);
925
                }
449 daniel-mar 926
                foreach (OIDplus::getDesignPlugins() as $plugin) {
927
                        $plugin->init($html);
928
                }
778 daniel-mar 929
                foreach (OIDplus::getCaptchaPlugins() as $plugin) {
930
                        $plugin->init($html);
931
                }
412 daniel-mar 932
 
778 daniel-mar 933
                if (PHP_SAPI != 'cli') {
934
 
935
                        // Prepare some security related response headers (default values)
936
 
937
                        $content_language =
938
                                strtolower(substr(OIDplus::getCurrentLang(),0,2)) . '-' .
939
                                strtoupper(substr(OIDplus::getCurrentLang(),2,2)); // e.g. 'en-US'
940
 
941
                        $http_headers = array(
942
                                "X-Content-Type-Options" => "nosniff",
943
                                "X-XSS-Protection" => "1; mode=block",
944
                                "X-Frame-Options" => "SAMEORIGIN",
945
                                "Referrer-Policy" => array(
946
                                        "no-referrer-when-downgrade"
947
                                ),
948
                                "Cache-Control" => array(
949
                                        "no-cache",
950
                                        "no-store",
951
                                        "must-revalidate"
952
                                ),
953
                                "Pragma" => "no-cache",
954
                                "Content-Language" => $content_language,
955
                                "Expires" => "0",
956
                                "Content-Security-Policy" => array(
1001 daniel-mar 957
                                        // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
958
 
959
                                        // --- Fetch directives ---
960
                                        "child-src" => array(
961
                                                "'self'",
962
                                                "blob:"
963
                                        ),
964
                                        "connect-src" => array(
965
                                                "'self'",
966
                                                "blob:"
967
                                        ),
778 daniel-mar 968
                                        "default-src" => array(
969
                                                "'self'",
970
                                                "blob:",
971
                                                "https://cdnjs.cloudflare.com/"
972
                                        ),
1001 daniel-mar 973
                                        "font-src" => array(
778 daniel-mar 974
                                                "'self'",
1001 daniel-mar 975
                                                "blob:"
778 daniel-mar 976
                                        ),
1001 daniel-mar 977
                                        "frame-src" => array(
978
                                                "'self'",
979
                                                "blob:"
980
                                        ),
778 daniel-mar 981
                                        "img-src" => array(
1001 daniel-mar 982
                                                "blob:",
778 daniel-mar 983
                                                "data:",
984
                                                "http:",
985
                                                "https:"
986
                                        ),
1001 daniel-mar 987
                                        "manifest-src" => array(
988
                                                "'self'",
989
                                                "blob:"
990
                                        ),
991
                                        "media-src" => array(
992
                                                "'self'",
993
                                                "blob:"
994
                                        ),
995
                                        "object-src" => array(
996
                                                "'none'"
997
                                        ),
998
                                        "prefetch-src" => array(
999
                                                "'self'",
1000
                                                "blob:"
1001
                                        ),
778 daniel-mar 1002
                                        "script-src" => array(
1003
                                                "'self'",
1004
                                                "'unsafe-inline'",
1005
                                                "'unsafe-eval'",
1006
                                                "blob:",
1007
                                                "https://cdnjs.cloudflare.com/",
1008
                                                "https://polyfill.io/"
1009
                                        ),
1001 daniel-mar 1010
                                        // script-src-elem not used
1011
                                        // script-src-attr not used
1012
                                        "style-src" => array(
1013
                                                "'self'",
1014
                                                "'unsafe-inline'",
1015
                                                "https://cdnjs.cloudflare.com/"
1016
                                        ),
1017
                                        // style-src-elem not used
1018
                                        // style-src-attr not used
1019
                                        "worker-src" => array(
1020
                                                "'self'",
1021
                                                "blob:"
1022
                                        ),
1023
 
1024
                                        // --- Navigation directives ---
778 daniel-mar 1025
                                        "frame-ancestors" => array(
1026
                                               "'none'"
1027
                                        ),
1028
                                )
1029
                        );
1030
 
780 daniel-mar 1031
                        // Give plugins the opportunity to manipulate/extend the headers
778 daniel-mar 1032
 
1033
                        foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
1034
                                $plugin->httpHeaderCheck($http_headers);
1035
                        }
1015 daniel-mar 1036
                        //foreach (OIDplus::getDatabasePlugins() as $plugin) {
1037
                        if ($plugin = OIDplus::getActiveDatabasePlugin()) {
778 daniel-mar 1038
                                $plugin->httpHeaderCheck($http_headers);
1039
                        }
1040
                        foreach (OIDplus::getPagePlugins() as $plugin) {
1041
                                $plugin->httpHeaderCheck($http_headers);
1042
                        }
1043
                        foreach (OIDplus::getAuthPlugins() as $plugin) {
1044
                                $plugin->httpHeaderCheck($http_headers);
1045
                        }
1046
                        foreach (OIDplus::getLoggerPlugins() as $plugin) {
1047
                                $plugin->httpHeaderCheck($http_headers);
1048
                        }
1049
                        foreach (OIDplus::getObjectTypePlugins() as $plugin) {
1050
                                $plugin->httpHeaderCheck($http_headers);
1051
                        }
1052
                        foreach (OIDplus::getLanguagePlugins() as $plugin) {
1053
                                $plugin->httpHeaderCheck($http_headers);
1054
                        }
1055
                        foreach (OIDplus::getDesignPlugins() as $plugin) {
1056
                                $plugin->httpHeaderCheck($http_headers);
1057
                        }
1015 daniel-mar 1058
                        //foreach (OIDplus::getCaptchaPlugins() as $plugin) {
1059
                        if ($plugin = OIDplus::getActiveCaptchaPlugin()) {
778 daniel-mar 1060
                                $plugin->httpHeaderCheck($http_headers);
1061
                        }
1062
 
1063
                        // Prepare to send the headers to the client
1064
                        // The headers are sent automatically when the first output comes or the script ends
1065
 
1066
                        foreach ($http_headers as $name => $val) {
1067
 
1068
                                // Plugins can remove standard OIDplus headers by setting the value to null.
1069
                                if (is_null($val)) continue; /** @phpstan-ignore-line */
1070
 
1071
                                // Some headers can be written as arrays to make it easier for plugin authors
1072
                                // to manipulate/extend the contents.
1073
                                if (is_array($val)) {
1074
                                        if ((strtolower($name) == 'cache-control') ||
1075
                                            (strtolower($name) == 'referrer-policy'))
1076
                                        {
1077
                                                if (count($val) == 0) continue;
1078
                                                $val = implode(', ', $val);
1079
                                        } else if (strtolower($name) == 'content-security-policy') {
1080
                                                if (count($val) == 0) continue;
780 daniel-mar 1081
                                                foreach ($val as $tmp1 => &$tmp2) {
1082
                                                        $tmp2 = array_unique($tmp2);
1083
                                                        $tmp2 = $tmp1.' '.implode(' ', $tmp2);
1084
                                                }
778 daniel-mar 1085
                                                $val = implode('; ', $val);
1086
                                        } else {
779 daniel-mar 1087
                                                throw new OIDplusException(_L('HTTP header "%1" cannot be written as array. A newly installed plugin is probably misusing the method "%2".',$name,'httpHeaderCheck'));
778 daniel-mar 1088
                                        }
1089
                                }
1090
 
1091
                                if (is_string($val)) {
1092
                                        header("$name: $val");
1093
                                }
1094
                        }
1095
 
1096
                } // endif (PHP_SAPI != 'cli')
1097
 
412 daniel-mar 1098
                // Initialize other stuff (i.e. things which require the logger!)
1099
 
1100
                OIDplus::recognizeSystemUrl(); // Make sure "last_known_system_url" is set
1101
                OIDplus::recognizeVersion(); // Make sure "last_known_version" is set and a log entry is created
2 daniel-mar 1102
        }
42 daniel-mar 1103
 
227 daniel-mar 1104
        # --- System URL, System ID, PKI, and other functions
1105
 
412 daniel-mar 1106
        private static function recognizeSystemUrl() {
1107
                try {
801 daniel-mar 1108
                        $url = OIDplus::webpath(null,self::PATH_ABSOLUTE_CANONICAL); // TODO: canonical or not?
412 daniel-mar 1109
                        OIDplus::config()->setValue('last_known_system_url', $url);
1110
                } catch (Exception $e) {
1111
                }
1112
        }
497 daniel-mar 1113
 
496 daniel-mar 1114
        private static function getExecutingScriptPathDepth() {
1115
                if (PHP_SAPI == 'cli') {
1116
                        global $argv;
1117
                        $test_dir = dirname(realpath($argv[0]));
1118
                } else {
1119
                        if (!isset($_SERVER["SCRIPT_FILENAME"])) return false;
1120
                        $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
1121
                }
1122
                $test_dir = str_replace('\\', '/', $test_dir);
1123
                $steps_up = 0;
928 daniel-mar 1124
                while (!file_exists($test_dir.'/oidplus.min.css.php')) { // We just assume that only the OIDplus base directory contains "oidplus.min.css.php" and not any subordinate directory!
496 daniel-mar 1125
                        $test_dir = dirname($test_dir);
1126
                        $steps_up++;
1127
                        if ($steps_up == 1000) return false; // to make sure there will never be an infinite loop
1128
                }
1129
                return $steps_up;
1130
        }
632 daniel-mar 1131
 
580 daniel-mar 1132
        public static function isSSL() {
1133
                return isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
1134
        }
412 daniel-mar 1135
 
806 daniel-mar 1136
        /**
1137
         * Returns the URL of the system.
1138
         * @param int $mode If true or OIDplus::PATH_RELATIVE, the returning path is relative to the currently executed
1139
         *                  PHP script (i.e. index.php , not the plugin PHP script!). False or OIDplus::PATH_ABSOLUTE is
1140
         *                  results in an absolute URL. OIDplus::PATH_ABSOLUTE_CANONICAL is an absolute URL,
1141
         *                  but a canonical path (set by base config setting CANONICAL_SYSTEM_URL) is preferred.
1142
         * @return string|false The URL, with guaranteed trailing path delimiter for directories
1143
         */
801 daniel-mar 1144
        private static function getSystemUrl($mode) {
806 daniel-mar 1145
                if ($mode === self::PATH_RELATIVE) {
778 daniel-mar 1146
                        $steps_up = self::getExecutingScriptPathDepth();
1147
                        if ($steps_up === false) {
1148
                                return false;
1149
                        } else {
1150
                                return str_repeat('../', $steps_up);
1151
                        }
1152
                } else {
806 daniel-mar 1153
                        if ($mode === self::PATH_ABSOLUTE_CANONICAL) {
1154
                                $tmp = OIDplus::baseConfig()->getValue('CANONICAL_SYSTEM_URL', '');
1155
                                if ($tmp) {
1156
                                        return rtrim($tmp,'/').'/';
1157
                                }
326 daniel-mar 1158
                        }
778 daniel-mar 1159
 
495 daniel-mar 1160
                        if (PHP_SAPI == 'cli') {
494 daniel-mar 1161
                                try {
1162
                                        return OIDplus::config()->getValue('last_known_system_url', false);
1163
                                } catch (Exception $e) {
1164
                                        return false;
1165
                                }
778 daniel-mar 1166
                        } else {
1167
                                // First, try to find out how many levels we need to go up
1168
                                $steps_up = self::getExecutingScriptPathDepth();
326 daniel-mar 1169
 
778 daniel-mar 1170
                                // Then go up these amount of levels, based on SCRIPT_NAME/argv[0]
1171
                                $res = dirname($_SERVER['SCRIPT_NAME'].'index.php'); // This fake 'index.php' ensures that SCRIPT_NAME does not end with '/', which would make dirname() fail
1172
                                for ($i=0; $i<$steps_up; $i++) {
1173
                                        $res = dirname($res);
1174
                                }
1175
                                $res = str_replace('\\', '/', $res);
1176
                                if ($res == '/') $res = '';
227 daniel-mar 1177
 
778 daniel-mar 1178
                                // Add protocol and hostname
580 daniel-mar 1179
                                $is_ssl = self::isSSL();
495 daniel-mar 1180
                                $protocol = $is_ssl ? 'https' : 'http'; // do not translate
1181
                                $host = $_SERVER['HTTP_HOST']; // includes port if it is not 80/443
778 daniel-mar 1182
 
1183
                                return $protocol.'://'.$host.$res.'/';
495 daniel-mar 1184
                        }
227 daniel-mar 1185
                }
1186
        }
1187
 
827 daniel-mar 1188
        private static function getSystemIdFromPubKey($pubKey) {
1189
                $m = array();
1190
                if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
1191
                        return smallhash(base64_decode($m[1]));
1192
                }
1193
                return false;
1194
        }
1195
 
227 daniel-mar 1196
        private static $system_id_cache = null;
1197
        public static function getSystemId($oid=false) {
1198
                if (!is_null(self::$system_id_cache)) {
1199
                        $out = self::$system_id_cache;
1200
                } else {
1201
                        $out = false;
1202
 
1203
                        if (self::getPkiStatus(true)) {
830 daniel-mar 1204
                                $pubKey = OIDplus::getSystemPublicKey();
827 daniel-mar 1205
                                $out = self::getSystemIdFromPubKey($pubKey);
227 daniel-mar 1206
                        }
1207
                        self::$system_id_cache = $out;
1208
                }
350 daniel-mar 1209
                if (!$out) return false;
291 daniel-mar 1210
                return ($oid ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
227 daniel-mar 1211
        }
1212
 
825 daniel-mar 1213
        public static function getOpenSslCnf() {
1214
                // The following functions need a config file, otherway they don't work
1215
                // - openssl_csr_new
1216
                // - openssl_csr_sign
1217
                // - openssl_pkey_export
1218
                // - openssl_pkey_export_to_file
1219
                // - openssl_pkey_new
1220
                $tmp = @getenv('OPENSSL_CONF');
1221
                if ($tmp && file_exists($tmp)) return $tmp;
1222
 
1223
                // OpenSSL in XAMPP does not work OOBE, since the OPENSSL_CONF is
1224
                // C:/xampp/apache/bin/openssl.cnf and not C:/xampp/apache/conf/openssl.cnf
1225
                // Bug reports are more than 10 years old and nobody cares...
1226
                // Use our own config file
1227
                return __DIR__.'/../../vendor/phpseclib/phpseclib/phpseclib/openssl.cnf';
1228
        }
1229
 
830 daniel-mar 1230
        private static function getPrivKeyPassphraseFilename() {
1231
                return OIDplus::localpath() . 'userdata/privkey_secret.php';
1232
        }
227 daniel-mar 1233
 
830 daniel-mar 1234
        private static function tryCreatePrivKeyPassphrase() {
1235
                $file = self::getPrivKeyPassphraseFilename();
827 daniel-mar 1236
 
830 daniel-mar 1237
                $passphrase = generateRandomString(64);
1238
                $cont = "<?php\n";
1239
                $cont .= "// ATTENTION! This file was automatically generated by OIDplus to encrypt the private key\n";
1240
                $cont .= "// that is located in your database configuration table. DO NOT ALTER OR DELETE THIS FILE,\n";
1241
                $cont .= "// otherwise you will lose your OIDplus System-ID and all services connected with it!\n";
831 daniel-mar 1242
                $cont .= "// If multiple systems access the same database, then this file must be synchronous\n";
1243
                $cont .= "// between all systems, otherwise you will lose your system ID, too!\n";
830 daniel-mar 1244
                $cont .= "\$passphrase = '$passphrase';\n";
1245
                $cont .= "// End of file\n";
1246
 
1247
                @file_put_contents($file, $cont);
1248
        }
1249
 
1250
        private static function getPrivKeyPassphrase() {
1251
                $file = self::getPrivKeyPassphraseFilename();
1252
                if (!file_exists($file)) return false;
1253
                $cont = file_get_contents($file);
1254
                $m = array();
1255
                if (!preg_match("@'(.+)'@isU", $cont, $m)) return false;
1256
                return $m[1];
1257
        }
1258
 
1259
        public static function getSystemPrivateKey() {
227 daniel-mar 1260
                $privKey = OIDplus::config()->getValue('oidplus_private_key');
830 daniel-mar 1261
                if ($privKey == '') return false;
1262
 
1263
                $passphrase = self::getPrivKeyPassphrase();
1264
                if ($passphrase !== false) {
1265
                        $privKey = decrypt_private_key($privKey, $passphrase);
1266
                }
1267
 
1268
                if (is_privatekey_encrypted($privKey)) {
1269
                        // This can happen if the key file has vanished
1270
                        return false;
1271
                }
1272
 
1273
                return $privKey;
1274
        }
1275
 
1276
        public static function getSystemPublicKey() {
227 daniel-mar 1277
                $pubKey = OIDplus::config()->getValue('oidplus_public_key');
830 daniel-mar 1278
                if ($pubKey == '') return false;
1279
                return $pubKey;
1280
        }
227 daniel-mar 1281
 
830 daniel-mar 1282
        public static function getPkiStatus($try_generate=false) {
1283
                if (!function_exists('openssl_pkey_new')) return false;
227 daniel-mar 1284
 
830 daniel-mar 1285
                if ($try_generate) {
1286
                        // For debug purposes: Invalidate current key once:
1287
                        //OIDplus::config()->setValue('oidplus_private_key', '');
256 daniel-mar 1288
 
830 daniel-mar 1289
                        $privKey = OIDplus::getSystemPrivateKey();
1290
                        $pubKey = OIDplus::getSystemPublicKey();
1291
                        if (!verify_private_public_key($privKey, $pubKey)) {
1292
                                if ($pubKey) {
1293
                                        OIDplus::logger()->log("[WARN]A!", "The private/public key-pair is broken. A new key-pair will now be generated for your system. Your System-ID will change.");
1294
                                }
227 daniel-mar 1295
 
830 daniel-mar 1296
                                $pkey_config = array(
1297
                                    "digest_alg" => "sha512",
1298
                                    "private_key_bits" => defined('OPENSSL_SUPPLEMENT') ? 1024 : 2048, // openssl_supplement.inc.php is based on phpseclib, which is very slow. So we use 1024 bits instead of 2048 bits
1299
                                    "private_key_type" => OPENSSL_KEYTYPE_RSA,
1300
                                    "config" => OIDplus::getOpenSslCnf()
1301
                                );
227 daniel-mar 1302
 
830 daniel-mar 1303
                                // Create the private and public key
1304
                                $res = openssl_pkey_new($pkey_config);
1305
                                if ($res === false) return false;
239 daniel-mar 1306
 
830 daniel-mar 1307
                                // Extract the private key from $res to $privKey
1308
                                if (openssl_pkey_export($res, $privKey, null, $pkey_config) === false) return false;
227 daniel-mar 1309
 
830 daniel-mar 1310
                                // Extract the public key from $res to $pubKey
1311
                                $tmp = openssl_pkey_get_details($res);
1312
                                if ($tmp === false) return false;
1313
                                $pubKey = $tmp["key"];
1314
 
1315
                                // encrypt new keys using a passphrase stored in a secret file
1316
                                self::tryCreatePrivKeyPassphrase(); // *try* (re)generate this file
1317
                                $passphrase = self::getPrivKeyPassphrase();
1318
                                if ($passphrase !== false) {
1319
                                        $privKey = encrypt_private_key($privKey, $passphrase);
1320
                                }
1321
 
1322
                                // Calculate the system ID from the public key
1323
                                $system_id = self::getSystemIdFromPubKey($pubKey);
1324
                                if ($system_id !== false) {
1325
                                        // Save the key pair to database
1326
                                        OIDplus::config()->setValue('oidplus_private_key', $privKey);
1327
                                        OIDplus::config()->setValue('oidplus_public_key', $pubKey);
1328
 
1329
                                        // Log the new system ID
1330
                                        OIDplus::logger()->log("[INFO]A!", "A new private/public key-pair for your system had been generated. Your SystemID is now $system_id");
1331
                                }
1332
                        } else {
1333
                                $passphrase = self::getPrivKeyPassphrase();
831 daniel-mar 1334
                                $rawPrivKey = OIDplus::config()->getValue('oidplus_private_key');
1335
                                if (($passphrase === false) || !is_privatekey_encrypted($rawPrivKey)) {
830 daniel-mar 1336
                                        // Upgrade to new encrypted keys
1337
                                        self::tryCreatePrivKeyPassphrase(); // *try* generate this file
1338
                                        $passphrase = self::getPrivKeyPassphrase();
1339
                                        if ($passphrase !== false) {
1340
                                                $privKey = encrypt_private_key($privKey, $passphrase);
1341
                                                OIDplus::logger()->log("[INFO]A!", "The private/public key-pair has been upgraded to an encrypted key-pair. The key is saved in ".self::getPrivKeyPassphraseFilename());
1342
                                                OIDplus::config()->setValue('oidplus_private_key', $privKey);
1343
                                        }
1344
                                }
227 daniel-mar 1345
                        }
1346
                }
1347
 
830 daniel-mar 1348
                $privKey = OIDplus::getSystemPrivateKey();
1349
                $pubKey = OIDplus::getSystemPublicKey();
227 daniel-mar 1350
                return verify_private_public_key($privKey, $pubKey);
1351
        }
1352
 
170 daniel-mar 1353
        public static function getInstallType() {
486 daniel-mar 1354
                $counter = 0;
1355
 
661 daniel-mar 1356
                if ($new_version_file_exists = file_exists(OIDplus::localpath().'.version.php')) {
486 daniel-mar 1357
                        $counter++;
591 daniel-mar 1358
                }
661 daniel-mar 1359
                if ($old_version_file_exists = file_exists(OIDplus::localpath().'oidplus_version.txt')) {
1360
                        $counter++;
1361
                }
1362
                $version_file_exists = $old_version_file_exists | $new_version_file_exists;
681 daniel-mar 1363
                if ($svn_dir_exists = (is_dir(OIDplus::localpath().'.svn') ||
1364
                                       is_dir(OIDplus::localpath().'../.svn'))) { // in case we checked out the root instead of the "trunk"
486 daniel-mar 1365
                        $counter++;
591 daniel-mar 1366
                }
681 daniel-mar 1367
                // if ($git_dir_exists = is_dir(OIDplus::localpath().'.git')) {
698 daniel-mar 1368
                if ($git_dir_exists = (OIDplus::findGitFolder() !== false)) {
486 daniel-mar 1369
                        $counter++;
591 daniel-mar 1370
                }
486 daniel-mar 1371
 
1372
                if ($counter === 0) {
360 daniel-mar 1373
                        return 'unknown'; // do not translate
170 daniel-mar 1374
                }
591 daniel-mar 1375
                else if ($counter > 1) {
360 daniel-mar 1376
                        return 'ambigous'; // do not translate
170 daniel-mar 1377
                }
591 daniel-mar 1378
                else if ($svn_dir_exists) {
360 daniel-mar 1379
                        return 'svn-wc'; // do not translate
170 daniel-mar 1380
                }
591 daniel-mar 1381
                else if ($git_dir_exists) {
486 daniel-mar 1382
                        return 'git-wc'; // do not translate
1383
                }
591 daniel-mar 1384
                else if ($version_file_exists) {
360 daniel-mar 1385
                        return 'svn-snapshot'; // do not translate
170 daniel-mar 1386
                }
1387
        }
1388
 
412 daniel-mar 1389
        private static function recognizeVersion() {
1390
                try {
1391
                        $ver_prev = OIDplus::config()->getValue("last_known_version");
1392
                        $ver_now = OIDplus::getVersion();
1393
                        if (($ver_now != '') && ($ver_prev != '') && ($ver_now != $ver_prev)) {
455 daniel-mar 1394
                                // TODO: Problem: When the system was updated using SVN, then the IP address of the next random visitor of the website is logged!
412 daniel-mar 1395
                                OIDplus::logger()->log("[INFO]A!", "System version changed from '$ver_prev' to '$ver_now'");
856 daniel-mar 1396
 
1397
                                // Just to be sure, recanonize objects (we don't do it at every page visit due to performance reasons)
857 daniel-mar 1398
                                self::recanonizeObjects();
412 daniel-mar 1399
                        }
1400
                        OIDplus::config()->setValue("last_known_version", $ver_now);
1401
                } catch (Exception $e) {
1402
                }
1403
        }
1404
 
111 daniel-mar 1405
        public static function getVersion() {
412 daniel-mar 1406
                static $cachedVersion = null;
1407
                if (!is_null($cachedVersion)) {
1408
                        return $cachedVersion;
1409
                }
1410
 
486 daniel-mar 1411
                $installType = OIDplus::getInstallType();
1412
 
1413
                if ($installType === 'svn-wc') {
496 daniel-mar 1414
                        $ver = get_svn_revision(OIDplus::localpath());
486 daniel-mar 1415
                        if ($ver)
1416
                                return ($cachedVersion = 'svn-'.$ver);
558 daniel-mar 1417
                        $ver = get_svn_revision(OIDplus::localpath().'../'); // in case we checked out the root instead of the "trunk"
1418
                        if ($ver)
1419
                                return ($cachedVersion = 'svn-'.$ver);
111 daniel-mar 1420
                }
162 daniel-mar 1421
 
486 daniel-mar 1422
                if ($installType === 'git-wc') {
698 daniel-mar 1423
                        $ver = OIDplus::getGitsvnRevision(OIDplus::localpath());
486 daniel-mar 1424
                        if ($ver)
1425
                                return ($cachedVersion = 'svn-'.$ver);
162 daniel-mar 1426
                }
1427
 
486 daniel-mar 1428
                if ($installType === 'svn-snapshot') {
661 daniel-mar 1429
                        $cont = '';
1430
                        if (file_exists($filename = OIDplus::localpath().'oidplus_version.txt'))
1431
                                $cont = file_get_contents($filename);
1432
                        if (file_exists($filename = OIDplus::localpath().'.version.php'))
1433
                                $cont = file_get_contents($filename);
386 daniel-mar 1434
                        $m = array();
360 daniel-mar 1435
                        if (preg_match('@Revision (\d+)@', $cont, $m)) // do not translate
412 daniel-mar 1436
                                return ($cachedVersion = 'svn-'.$m[1]); // do not translate
162 daniel-mar 1437
                }
1438
 
486 daniel-mar 1439
                return ($cachedVersion = false); // version ambigous or unknown
111 daniel-mar 1440
        }
1441
 
974 daniel-mar 1442
        const ENFORCE_SSL_NO   = 0;
1443
        const ENFORCE_SSL_YES  = 1;
1444
        const ENFORCE_SSL_AUTO = 2;
230 daniel-mar 1445
        private static $sslAvailableCache = null;
1446
        public static function isSslAvailable() {
1447
                if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
256 daniel-mar 1448
 
495 daniel-mar 1449
                if (PHP_SAPI == 'cli') {
230 daniel-mar 1450
                        self::$sslAvailableCache = false;
1451
                        return false;
1452
                }
1453
 
49 daniel-mar 1454
                $timeout = 2;
580 daniel-mar 1455
                $already_ssl = self::isSSL();
80 daniel-mar 1456
                $ssl_port = 443;
42 daniel-mar 1457
 
974 daniel-mar 1458
                if ($already_ssl) {
1459
                        OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, false, null, true/*forceInsecure*/);
1460
                        self::$sslAvailableCache = true;
1461
                        return true;
1462
                } else {
1463
                        if (isset($_COOKIE['SSL_CHECK']) && ($_COOKIE['SSL_CHECK'] == '1')) {
1464
                                // The cookie "SSL_CHECK" is set once a website was loaded with HTTPS.
1465
                                // It forces subsequent HTTP calls to redirect to HTTPS (like HSTS).
1466
                                // The reason is the following problem:
1467
                                // If you open the page with HTTPS first, then the CSRF token cookies will get the "secure" flag
1468
                                // If you open the page then with HTTP, the HTTP cannot access the secure CSRF cookies,
1469
                                // Chrome will then block "Set-Cookie" since the HTTP cookie would overwrite the HTTPS cookie.
1470
                                // Note: SSL_CHECK is NOT a replacement for HSTS! You should use HSTS,
1471
                                // because on there your browser ensures that HTTPS is called, before the server
1472
                                // is even contacted (and therefore, no HTTP connection can be hacked).
1473
                                $mode = OIDplus::ENFORCE_SSL_YES;
1474
                        } else {
1475
                                $mode = OIDplus::baseConfig()->getValue('ENFORCE_SSL', OIDplus::ENFORCE_SSL_AUTO);
1476
                        }
261 daniel-mar 1477
 
974 daniel-mar 1478
                        if ($mode == OIDplus::ENFORCE_SSL_NO) {
1479
                                // No SSL available
1480
                                self::$sslAvailableCache = false;
1481
                                return false;
1482
                        } else if ($mode == OIDplus::ENFORCE_SSL_YES) {
1483
                                // Force SSL
80 daniel-mar 1484
                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1485
                                header('Location:'.$location);
360 daniel-mar 1486
                                die(_L('Redirecting to HTTPS...'));
974 daniel-mar 1487
                        } else if ($mode == OIDplus::ENFORCE_SSL_AUTO) {
1488
                                // Automatic SSL detection
80 daniel-mar 1489
                                if (isset($_COOKIE['SSL_CHECK'])) {
1490
                                        // We already had the HTTPS detection done before.
974 daniel-mar 1491
                                        if ($_COOKIE['SSL_CHECK'] == '1') {
80 daniel-mar 1492
                                                // HTTPS was detected before, but we are HTTP. Redirect now
1493
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1494
                                                header('Location:'.$location);
360 daniel-mar 1495
                                                die(_L('Redirecting to HTTPS...'));
80 daniel-mar 1496
                                        } else {
1497
                                                // No HTTPS available. Do nothing.
230 daniel-mar 1498
                                                self::$sslAvailableCache = false;
80 daniel-mar 1499
                                                return false;
1500
                                        }
49 daniel-mar 1501
                                } else {
80 daniel-mar 1502
                                        // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
386 daniel-mar 1503
                                        $errno = -1;
1504
                                        $errstr = '';
80 daniel-mar 1505
                                        if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
1506
                                                // HTTPS detected. Redirect now, and remember that we had detected HTTPS
974 daniel-mar 1507
                                                OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, false, null, true/*forceInsecure*/);
80 daniel-mar 1508
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1509
                                                header('Location:'.$location);
360 daniel-mar 1510
                                                die(_L('Redirecting to HTTPS...'));
80 daniel-mar 1511
                                        } else {
1512
                                                // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
974 daniel-mar 1513
                                                OIDplus::cookieUtils()->setcookie('SSL_CHECK', '0', 0, false, null, true/*forceInsecure*/);
230 daniel-mar 1514
                                                self::$sslAvailableCache = false;
80 daniel-mar 1515
                                                return false;
1516
                                        }
49 daniel-mar 1517
                                }
42 daniel-mar 1518
                        }
1519
                }
1520
        }
497 daniel-mar 1521
 
496 daniel-mar 1522
        /**
1523
         * Gets a local path pointing to a resource
1524
         * @param string $target Target resource (file or directory must exist), or null to get the OIDplus base directory
1525
         * @param boolean $relative If true, the returning path is relative to the currently executed PHP file (not the CLI working directory)
590 daniel-mar 1526
         * @return string|false The local path, with guaranteed trailing path delimiter for directories
496 daniel-mar 1527
         */
1528
        public static function localpath($target=null, $relative=false) {
1529
                if (is_null($target)) {
1530
                        $target = __DIR__.'/../../';
1531
                }
241 daniel-mar 1532
 
496 daniel-mar 1533
                if ($relative) {
1534
                        // First, try to find out how many levels we need to go up
1535
                        $steps_up = self::getExecutingScriptPathDepth();
1536
                        if ($steps_up === false) return false;
497 daniel-mar 1537
 
496 daniel-mar 1538
                        // Virtually go back from the executing PHP script to the OIDplus base path
1539
                        $res = str_repeat('../',$steps_up);
497 daniel-mar 1540
 
496 daniel-mar 1541
                        // Then go to the desired location
1542
                        $basedir = realpath(__DIR__.'/../../');
1543
                        $target = realpath($target);
500 daniel-mar 1544
                        if ($target === false) return false;
496 daniel-mar 1545
                        $res .= substr($target, strlen($basedir)+1);
1546
                        $res = rtrim($res,'/'); // avoid '..//' for localpath(null,true)
1547
                } else {
1548
                        $res = realpath($target);
241 daniel-mar 1549
                }
497 daniel-mar 1550
 
801 daniel-mar 1551
                if (is_dir($target)) $res .= '/';
497 daniel-mar 1552
 
801 daniel-mar 1553
                $res = str_replace('/', DIRECTORY_SEPARATOR, $res);
1554
 
496 daniel-mar 1555
                return $res;
241 daniel-mar 1556
        }
355 daniel-mar 1557
 
496 daniel-mar 1558
        /**
1559
         * Gets a URL pointing to a resource
1560
         * @param string $target Target resource (file or directory must exist), or null to get the OIDplus base directory
806 daniel-mar 1561
         * @param int|boolean $mode If true or OIDplus::PATH_RELATIVE, the returning path is relative to the currently executed
1562
         *                          PHP script (i.e. index.php , not the plugin PHP script!). False or OIDplus::PATH_ABSOLUTE is
1563
         *                          results in an absolute URL. OIDplus::PATH_ABSOLUTE_CANONICAL is an absolute URL,
1564
         *                          but a canonical path (set by base config setting CANONICAL_SYSTEM_URL) is preferred.
590 daniel-mar 1565
         * @return string|false The URL, with guaranteed trailing path delimiter for directories
496 daniel-mar 1566
         */
806 daniel-mar 1567
        public static function webpath($target=null, $mode=self::PATH_ABSOLUTE_CANONICAL) {
801 daniel-mar 1568
                // backwards compatibility
1569
                if ($mode === true) $mode = self::PATH_RELATIVE;
1570
                if ($mode === false) $mode = self::PATH_ABSOLUTE;
1571
 
811 daniel-mar 1572
                if ($mode == OIDplus::PATH_RELATIVE_TO_ROOT) {
812 daniel-mar 1573
                        $tmp = OIDplus::webpath($target,OIDplus::PATH_ABSOLUTE);
1574
                        if ($tmp === false) return false;
1575
                        $tmp = parse_url($tmp);
1576
                        if ($tmp === false) return false;
1577
                        if (!isset($tmp['path'])) return false;
1578
                        return $tmp['path'];
811 daniel-mar 1579
                }
1580
 
812 daniel-mar 1581
                if ($mode == OIDplus::PATH_RELATIVE_TO_ROOT_CANONICAL) {
1582
                        $tmp = OIDplus::webpath($target,OIDplus::PATH_ABSOLUTE_CANONICAL);
1583
                        if ($tmp === false) return false;
1584
                        $tmp = parse_url($tmp);
1585
                        if ($tmp === false) return false;
1586
                        if (!isset($tmp['path'])) return false;
1587
                        return $tmp['path'];
1588
                }
1589
 
801 daniel-mar 1590
                $res = self::getSystemUrl($mode); // Note: already contains a trailing path delimiter
778 daniel-mar 1591
                if ($res === false) return false;
497 daniel-mar 1592
 
496 daniel-mar 1593
                if (!is_null($target)) {
1594
                        $basedir = realpath(__DIR__.'/../../');
1595
                        $target = realpath($target);
500 daniel-mar 1596
                        if ($target === false) return false;
496 daniel-mar 1597
                        $tmp = substr($target, strlen($basedir)+1);
500 daniel-mar 1598
                        $res .= str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
497 daniel-mar 1599
                        if (is_dir($target)) $res .= '/';
496 daniel-mar 1600
                }
497 daniel-mar 1601
 
496 daniel-mar 1602
                return $res;
1603
        }
497 daniel-mar 1604
 
778 daniel-mar 1605
        public static function canonicalURL() {
1606
                // First part: OIDplus system URL (or canonical system URL)
801 daniel-mar 1607
                $sysurl = OIDplus::getSystemUrl(self::PATH_ABSOLUTE_CANONICAL);
778 daniel-mar 1608
 
1609
                // Second part: Directory
1610
                $basedir = realpath(__DIR__.'/../../');
1611
                $target = realpath('.');
1612
                if ($target === false) return false;
1613
                $tmp = substr($target, strlen($basedir)+1);
1614
                $res = str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
780 daniel-mar 1615
                if (is_dir($target) && ($res != '')) $res .= '/';
778 daniel-mar 1616
 
1617
                // Third part: File name
1618
                $tmp = explode('/',$_SERVER['SCRIPT_NAME']);
1619
                $tmp = end($tmp);
1620
 
1621
                // Fourth part: Query string (ordered)
1622
                $tmp2 = getSortedQuery();
1623
                if ($tmp2 != '') $tmp2 = '?'.$tmp2;
1624
 
1625
                return $sysurl.$res.$tmp.$tmp2;
1626
        }
1627
 
639 daniel-mar 1628
        private static $shutdown_functions = array();
1629
        public static function register_shutdown_function($func) {
1630
                self::$shutdown_functions[] = $func;
1631
        }
1632
 
1633
        public static function invoke_shutdown() {
1634
                foreach (self::$shutdown_functions as $func) {
1635
                        $func();
1636
                }
1637
        }
1638
 
360 daniel-mar 1639
        public static function getAvailableLangs() {
1640
                $langs = array();
1641
                foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
389 daniel-mar 1642
                        $code = $pluginManifest->getLanguageCode();
360 daniel-mar 1643
                        $langs[] = $code;
1644
                }
1645
                return $langs;
1646
        }
1647
 
355 daniel-mar 1648
        public static function getCurrentLang() {
360 daniel-mar 1649
                if (isset($_GET['lang'])) {
1650
                        $lang = $_GET['lang'];
1651
                } else if (isset($_POST['lang'])) {
1652
                        $lang = $_POST['lang'];
1653
                } else if (isset($_COOKIE['LANGUAGE'])) {
1654
                        $lang = $_COOKIE['LANGUAGE'];
1655
                } else {
1656
                        $lang = self::DEFAULT_LANGUAGE;
1657
                }
1658
                $lang = substr(preg_replace('@[^a-z]@ismU', '', $lang),0,4); // sanitize
355 daniel-mar 1659
                return $lang;
1660
        }
1661
 
362 daniel-mar 1662
        public static function handleLangArgument() {
1663
                if (isset($_GET['lang'])) {
1664
                        // The "?lang=" argument is only for NoScript-Browsers/SearchEngines
1665
                        // In case someone who has JavaScript clicks a ?lang= link, they should get
1666
                        // the page in that language, but the cookie must be set, otherwise
1667
                        // the menu and other stuff would be in their cookie-based-language and not the
1668
                        // argument-based-language.
557 daniel-mar 1669
                        OIDplus::cookieUtils()->setcookie('LANGUAGE', $_GET['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
362 daniel-mar 1670
                } else if (isset($_POST['lang'])) {
557 daniel-mar 1671
                        OIDplus::cookieUtils()->setcookie('LANGUAGE', $_POST['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
362 daniel-mar 1672
                }
1673
        }
1674
 
468 daniel-mar 1675
        private static $translationArray = array();
469 daniel-mar 1676
        protected static function getTranslationFileContents($translation_file) {
1677
                // First, try the cache
481 daniel-mar 1678
                $cache_file = __DIR__ . '/../../userdata/cache/translation_'.md5($translation_file).'.ser';
469 daniel-mar 1679
                if (file_exists($cache_file) && (filemtime($cache_file) == filemtime($translation_file))) {
1680
                        $cac = @unserialize(file_get_contents($cache_file));
1681
                        if ($cac) return $cac;
1682
                }
481 daniel-mar 1683
 
469 daniel-mar 1684
                // If not successful, then load the XML file
1685
                $xml = @simplexml_load_string(file_get_contents($translation_file));
1686
                if (!$xml) return array(); // if there is an UTF-8 or parsing error, don't output any errors, otherwise the JavaScript is corrupt and the page won't render correctly
1687
                $cac = array();
1688
                foreach ($xml->message as $msg) {
1689
                        $src = trim($msg->source->__toString());
1690
                        $dst = trim($msg->target->__toString());
1691
                        $cac[$src] = $dst;
1692
                }
1693
                @file_put_contents($cache_file,serialize($cac));
1694
                @touch($cache_file,filemtime($translation_file));
1695
                return $cac;
1696
        }
468 daniel-mar 1697
        public static function getTranslationArray($requested_lang='*') {
362 daniel-mar 1698
                foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
389 daniel-mar 1699
                        $lang = $pluginManifest->getLanguageCode();
362 daniel-mar 1700
                        if (strpos($lang,'/') !== false) continue; // just to be sure
1701
                        if (strpos($lang,'\\') !== false) continue; // just to be sure
1702
                        if (strpos($lang,'..') !== false) continue; // just to be sure
401 daniel-mar 1703
 
468 daniel-mar 1704
                        if (($requested_lang != '*') && ($lang != $requested_lang)) continue;
401 daniel-mar 1705
 
468 daniel-mar 1706
                        if (!isset(self::$translationArray[$lang])) {
1707
                                self::$translationArray[$lang] = array();
1708
 
1709
                                $wildcard = $pluginManifest->getLanguageMessages();
1710
                                if (strpos($wildcard,'/') !== false) continue; // just to be sure
1711
                                if (strpos($wildcard,'\\') !== false) continue; // just to be sure
1712
                                if (strpos($wildcard,'..') !== false) continue; // just to be sure
1713
 
635 daniel-mar 1714
                                $translation_files = glob(__DIR__.'/../../plugins/'.'*'.'/language/'.$lang.'/'.$wildcard);
468 daniel-mar 1715
                                sort($translation_files);
1716
                                foreach ($translation_files as $translation_file) {
1717
                                        if (!file_exists($translation_file)) continue;
469 daniel-mar 1718
                                        $cac = self::getTranslationFileContents($translation_file);
1719
                                        foreach ($cac as $src => $dst) {
1720
                                                self::$translationArray[$lang][$src] = $dst;
468 daniel-mar 1721
                                        }
401 daniel-mar 1722
                                }
362 daniel-mar 1723
                        }
1724
                }
468 daniel-mar 1725
                return self::$translationArray;
362 daniel-mar 1726
        }
1727
 
699 daniel-mar 1728
        public static function getEditionInfo() {
1729
                return @parse_ini_file(__DIR__.'/../edition.ini', true)['Edition'];
1730
        }
1731
 
698 daniel-mar 1732
        public static function findGitFolder() {
1733
                // Git command line saves git information in folder ".git"
1734
                // Plesk git saves git information in folder "../../../git/oidplus/" (or similar)
727 daniel-mar 1735
                $dir = OIDplus::localpath();
698 daniel-mar 1736
                if (is_dir($dir.'/.git')) return $dir.'/.git';
1737
                $i = 0;
1738
                do {
1739
                        if (is_dir($dir.'/git')) {
719 daniel-mar 1740
                                $confs = @glob($dir.'/git/'.'*'.'/config');
1741
                                if ($confs) foreach ($confs as $conf) {
698 daniel-mar 1742
                                        $cont = file_get_contents($conf);
699 daniel-mar 1743
                                        if (isset(OIDplus::getEditionInfo()['gitrepo']) && (OIDplus::getEditionInfo()['gitrepo'] != '') && (strpos($cont, OIDplus::getEditionInfo()['gitrepo']) !== false)) {
698 daniel-mar 1744
                                                return dirname($conf);
1745
                                        }
1746
                                }
1747
                        }
1748
                        $i++;
719 daniel-mar 1749
                } while (($i<100) && ($dir != ($new_dir = @realpath($dir.'/../'))) && ($dir = $new_dir));
698 daniel-mar 1750
                return false;
1751
        }
1752
 
1753
        public static function getGitsvnRevision($dir='') {
1754
                try {
1755
                        // tries command line and binary parsing
699 daniel-mar 1756
                        // requires vendor/danielmarschall/git_utils.inc.php
698 daniel-mar 1757
                        $git_dir = OIDplus::findGitFolder();
1758
                        if ($git_dir === false) return false;
1759
                        $commit_msg = git_get_latest_commit_message($git_dir);
1760
                } catch (Exception $e) {
1761
                        return false;
1762
                }
1763
 
1764
                $m = array();
1765
                if (preg_match('%git-svn-id: (.+)@(\\d+) %ismU', $commit_msg, $m)) {
1766
                        return $m[2];
1767
                } else {
1768
                        return false;
1769
                }
1770
        }
1771
 
775 daniel-mar 1772
        public static function prefilterQuery($static_node_id, $throw_exception) {
1773
                // Let namespace be case-insensitive
1774
                $ary = explode(':', $static_node_id, 2);
1775
                $ary[0] = strtolower($ary[0]);
1776
                $static_node_id = implode(':', $ary);
1777
 
889 daniel-mar 1778
                // Ask plugins if they want to change the node id
1779
                foreach (OIDplus::getObjectTypePluginsEnabled() as $plugin) {
1780
                        $static_node_id = $plugin->prefilterQuery($static_node_id, $throw_exception);
775 daniel-mar 1781
                }
1782
 
1783
                return $static_node_id;
1784
        }
849 daniel-mar 1785
 
1786
        public static function isCronjob() {
1787
                return explode('.',basename($_SERVER['SCRIPT_NAME']))[0] === 'cron';
1788
        }
856 daniel-mar 1789
 
857 daniel-mar 1790
        private static function recanonizeObjects() {
856 daniel-mar 1791
                #
1792
                # Since OIDplus svn-184, entries in the database need to have a canonical ID
1793
                # If the ID is not canonical (e.g. GUIDs missing hyphens), the object cannot be opened in OIDplus
1794
                # This script re-canonizes the object IDs if required.
1795
                # In SVN Rev 856, the canonization for GUID, IPv4 and IPv6 have changed, requiring another
1796
                # re-canonization
1797
                #
1798
                $res = OIDplus::db()->query("select id from ###objects");
1799
                while ($row = $res->fetch_array()) {
1800
                        $ida = $row['id'];
857 daniel-mar 1801
                        $obj = OIDplusObject::parse($ida);
1802
                        if (!$obj) continue;
1803
                        $idb = $obj->nodeId();
856 daniel-mar 1804
                        if (($idb) && ($ida != $idb)) {
1805
                                OIDplus::db()->transaction_begin();
1806
                                OIDplus::db()->query("update ###objects set id = ? where id = ?", array($idb, $ida));
1807
                                OIDplus::db()->query("update ###asn1id set oid = ? where oid = ?", array($idb, $ida));
1808
                                OIDplus::db()->query("update ###iri set oid = ? where oid = ?", array($idb, $ida));
1809
                                OIDplus::db()->query("update ###log_object set id = ? where id = ?", array($idb, $ida));
1810
                                OIDplus::logger()->log("[INFO]A!", "Object name '$ida' has been changed to '$idb' during re-canonization");
1811
                                OIDplus::db()->transaction_commit();
978 daniel-mar 1812
                                OIDplusObject::resetObjectInformationCache();
856 daniel-mar 1813
                        }
1814
                }
1815
        }
1816
 
374 daniel-mar 1817
}