Subversion Repositories oidplus

Rev

Rev 1117 | Rev 1123 | 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
1073 daniel-mar 5
 * Copyright 2019 - 2023 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
 
1050 daniel-mar 20
namespace ViaThinkSoft\OIDplus;
511 daniel-mar 21
 
1086 daniel-mar 22
// phpcs:disable PSR1.Files.SideEffects
23
\defined('INSIDE_OIDPLUS') or die;
24
// phpcs:enable PSR1.Files.SideEffects
25
 
730 daniel-mar 26
class OIDplus extends OIDplusBaseClass {
1116 daniel-mar 27
        /**
28
         * @var OIDplusPagePlugin[]
29
         */
281 daniel-mar 30
        private static /*OIDplusPagePlugin[]*/ $pagePlugins = array();
1116 daniel-mar 31
        /**
32
         * @var OIDplusAuthPlugin[]
33
         */
281 daniel-mar 34
        private static /*OIDplusAuthPlugin[]*/ $authPlugins = array();
1116 daniel-mar 35
        /**
36
         * @var OIDplusLoggerPlugin[]
37
         */
289 daniel-mar 38
        private static /*OIDplusLoggerPlugin[]*/ $loggerPlugins = array();
1116 daniel-mar 39
        /**
40
         * @var OIDplusObjectTypePlugin[]
41
         */
227 daniel-mar 42
        private static /*OIDplusObjectTypePlugin[]*/ $objectTypePlugins = array();
1116 daniel-mar 43
        /**
44
         * @var string[]|OIDplusObject[] Classnames of OIDplusObject classes
45
         */
227 daniel-mar 46
        private static /*string[]*/ $enabledObjectTypes = array();
1116 daniel-mar 47
        /**
48
         * @var string[]|OIDplusObject[] Classnames of OIDplusObject classes
49
         */
227 daniel-mar 50
        private static /*string[]*/ $disabledObjectTypes = array();
1116 daniel-mar 51
        /**
52
         * @var OIDplusDatabasePlugin[]
53
         */
227 daniel-mar 54
        private static /*OIDplusDatabasePlugin[]*/ $dbPlugins = array();
1116 daniel-mar 55
        /**
56
         * @var OIDplusCaptchaPlugin[]
57
         */
702 daniel-mar 58
        private static /*OIDplusCaptchaPlugin[]*/ $captchaPlugins = array();
1116 daniel-mar 59
        /**
60
         * @var OIDplusSqlSlangPlugin[]
61
         */
274 daniel-mar 62
        private static /*OIDplusSqlSlangPlugin[]*/ $sqlSlangPlugins = array();
1116 daniel-mar 63
        /**
64
         * @var OIDplusLanguagePlugin[]
65
         */
355 daniel-mar 66
        private static /*OIDplusLanguagePlugin[]*/ $languagePlugins = array();
1116 daniel-mar 67
        /**
68
         * @var OIDplusDesignPlugin[]
69
         */
449 daniel-mar 70
        private static /*OIDplusDesignPlugin[]*/ $designPlugins = array();
2 daniel-mar 71
 
1116 daniel-mar 72
        /**
73
         * @var bool
74
         */
280 daniel-mar 75
        protected static $html = true;
236 daniel-mar 76
 
1116 daniel-mar 77
        /**
78
         * e.g. "../"
79
         */
80
        /*public*/ const PATH_RELATIVE = 1;
801 daniel-mar 81
 
1116 daniel-mar 82
        /**
83
         * e.g. "http://www.example.com/oidplus/"
84
         */
85
        /*public*/ const PATH_ABSOLUTE = 2;
86
 
87
        /**
88
         * e.g. "http://www.example.org/oidplus/" (if baseconfig CANONICAL_SYSTEM_URL is set)
89
         */
90
        /*public*/ const PATH_ABSOLUTE_CANONICAL = 3;
91
 
92
        /**
93
         * e.g. "/oidplus/"
94
         */
95
        /*public*/ const PATH_RELATIVE_TO_ROOT = 4;
96
 
97
        /**
98
         * e.g. "/oidplus/" (if baseconfig CANONICAL_SYSTEM_URL is set)
99
         */
100
        /*public*/ const PATH_RELATIVE_TO_ROOT_CANONICAL = 5;
101
 
102
        /**
103
         * These plugin types can contain HTML code and therefore may
104
         * emit (non-setup) CSS/JS code via their manifest.
105
         * Note that design plugins may only output CSS, not JS.
106
         */
778 daniel-mar 107
        /*public*/ const INTERACTIVE_PLUGIN_TYPES = array(
1122 daniel-mar 108
        'publicPages',
109
        'raPages',
110
        'adminPages',
111
        'objectTypes',
112
        'captcha'
113
);
778 daniel-mar 114
 
1073 daniel-mar 115
        const UUID_NAMEBASED_NS_Base64PubKey = 'fd16965c-8bab-11ed-8744-3c4a92df8582';
116
 
1116 daniel-mar 117
        /**
118
         * Private constructor (Singleton)
119
         */
2 daniel-mar 120
        private function __construct() {
121
        }
295 daniel-mar 122
 
1116 daniel-mar 123
        /**
124
         * @return bool
125
         * @throws OIDplusException
126
         */
1068 daniel-mar 127
        private static function insideSetup(): bool {
128
                if (PHP_SAPI == 'cli') return false;
129
                if (!isset($_SERVER['REQUEST_URI'])) return false;
1055 daniel-mar 130
                return (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE_TO_ROOT).'setup/') === 0);
131
        }
132
 
1050 daniel-mar 133
        // --- Static classes
274 daniel-mar 134
 
263 daniel-mar 135
        private static $baseConfig = null;
1050 daniel-mar 136
        private static $oldConfigFormatLoaded = false;
274 daniel-mar 137
 
1116 daniel-mar 138
        /**
139
         * @return OIDplusBaseConfig
140
         * @throws OIDplusException, OIDplusConfigInitializationException
141
         */
142
        public static function baseConfig(): OIDplusBaseConfig {
263 daniel-mar 143
                if ($first_init = is_null(self::$baseConfig)) {
144
                        self::$baseConfig = new OIDplusBaseConfig();
261 daniel-mar 145
                }
146
 
1055 daniel-mar 147
                if (self::insideSetup()) return self::$baseConfig;
148
                if ((basename($_SERVER['SCRIPT_NAME']) === 'oidplus.min.js.php') && isset($_REQUEST['noBaseConfig']) && ($_REQUEST['noBaseConfig'] == '1')) return self::$baseConfig;
149
                if ((basename($_SERVER['SCRIPT_NAME']) === 'oidplus.min.css.php') && isset($_REQUEST['noBaseConfig']) && ($_REQUEST['noBaseConfig'] == '1')) return self::$baseConfig;
150
 
263 daniel-mar 151
                if ($first_init) {
261 daniel-mar 152
                        // Include a file containing various size/depth limitations of OIDs
294 daniel-mar 153
                        // It is important to include it before userdata/baseconfig/config.inc.php was included,
154
                        // so we can give userdata/baseconfig/config.inc.php the chance to override the values.
261 daniel-mar 155
 
496 daniel-mar 156
                        include OIDplus::localpath().'includes/oidplus_limits.inc.php';
261 daniel-mar 157
 
158
                        // Include config file
295 daniel-mar 159
 
496 daniel-mar 160
                        $config_file = OIDplus::localpath() . 'userdata/baseconfig/config.inc.php';
161
                        $config_file_old = OIDplus::localpath() . 'includes/config.inc.php'; // backwards compatibility
295 daniel-mar 162
 
294 daniel-mar 163
                        if (!file_exists($config_file) && file_exists($config_file_old)) {
164
                                $config_file = $config_file_old;
165
                        }
261 daniel-mar 166
 
294 daniel-mar 167
                        if (file_exists($config_file)) {
1050 daniel-mar 168
                                if (self::$oldConfigFormatLoaded) {
263 daniel-mar 169
                                        // Note: We may only include it once due to backwards compatibility,
170
                                        //       since in version 2.0, the configuration was defined using define() statements
171
                                        // Attention: This does mean that a full re-init (e.g. for test cases) is not possible
172
                                        //            if a version 2.0 config is used!
1050 daniel-mar 173
 
174
                                        // We need to do this, because define() cannot be undone
175
                                        // Note: This can only happen in very special cases (e.g. test cases) where you call init() twice
176
                                        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 177
                                } else {
1050 daniel-mar 178
                                        $tmp = file_get_contents($config_file);
179
                                        $ns = "ViaThinkSoft\OIDplus\OIDplus";
180
                                        $uses = "use $ns;";
181
                                        if ((strpos($tmp,'OIDplus::') !== false) && (strpos($tmp,$uses) === false)) {
182
                                                // Migrate config file to namespace class names
183
                                                // Note: Only config files version 2.1 are affected. Not 2.0 ones
184
 
185
                                                $tmp = "<?php\r\n\r\n$uses /* Automatically added by migration procedure */\r\n?>$tmp";
186
                                                $tmp = str_replace('?><?php', '', $tmp);
187
 
188
                                                $tmp = str_replace("\$ns\OIDplusCaptchaPluginRecaptcha::", "OIDplusCaptchaPluginRecaptcha::", $tmp);
189
                                                $tmp = str_replace("OIDplusCaptchaPluginRecaptcha::", "\$ns\OIDplusCaptchaPluginRecaptcha::", $tmp);
190
 
191
                                                $tmp = str_replace('DISABLE_PLUGIN_OIDplusPagePublicRdap',
1122 daniel-mar 192
                                                        'DISABLE_PLUGIN_Frdlweb\OIDplus\OIDplusPagePublicRdap', $tmp);
1050 daniel-mar 193
                                                $tmp = str_replace('DISABLE_PLUGIN_OIDplusPagePublicAltIds',
1122 daniel-mar 194
                                                        'DISABLE_PLUGIN_Frdlweb\OIDplus\OIDplusPagePublicAltIds', $tmp);
1051 daniel-mar 195
                                                $tmp = str_replace('DISABLE_PLUGIN_OIDplusPagePublicUITweaks',
1122 daniel-mar 196
                                                        'DISABLE_PLUGIN_TushevOrg\OIDplus\OIDplusPagePublicUITweaks', $tmp);
1050 daniel-mar 197
                                                $tmp = str_replace('DISABLE_PLUGIN_OIDplus',
1122 daniel-mar 198
                                                        'DISABLE_PLUGIN_ViaThinkSoft\OIDplus\OIDplus', $tmp);
1050 daniel-mar 199
 
200
                                                if (@file_put_contents($config_file, $tmp) === false) {
201
                                                        eval('?>'.$tmp);
202
                                                } else {
203
                                                        include $config_file;
204
                                                }
205
                                        } else {
206
                                                include $config_file;
207
                                        }
263 daniel-mar 208
                                }
261 daniel-mar 209
 
1055 daniel-mar 210
                                // Backwards compatibility 2.0 => 2.1
261 daniel-mar 211
                                if (defined('OIDPLUS_CONFIG_VERSION') && (OIDPLUS_CONFIG_VERSION == 2.0)) {
1050 daniel-mar 212
                                        self::$oldConfigFormatLoaded = true;
261 daniel-mar 213
                                        foreach (get_defined_constants(true)['user'] as $name => $value) {
214
                                                $name = str_replace('OIDPLUS_', '', $name);
215
                                                if ($name == 'SESSION_SECRET') $name = 'SERVER_SECRET';
216
                                                if ($name == 'MYSQL_QUERYLOG') $name = 'QUERY_LOGFILE';
1050 daniel-mar 217
                                                $name = str_replace('DISABLE_PLUGIN_OIDplusPagePublicRdap',
1122 daniel-mar 218
                                                        'DISABLE_PLUGIN_Frdlweb\OIDplus\OIDplusPagePublicRdap', $name);
1050 daniel-mar 219
                                                $name = str_replace('DISABLE_PLUGIN_OIDplusPagePublicAltIds',
1122 daniel-mar 220
                                                        'DISABLE_PLUGIN_Frdlweb\OIDplus\OIDplusPagePublicAltIds', $name);
1051 daniel-mar 221
                                                $name = str_replace('DISABLE_PLUGIN_OIDplusPagePublicUITweaks',
1122 daniel-mar 222
                                                        'DISABLE_PLUGIN_TushevOrg\OIDplus\OIDplusPagePublicUITweaks', $name);
1050 daniel-mar 223
                                                $name = str_replace('DISABLE_PLUGIN_OIDplus',
1122 daniel-mar 224
                                                        'DISABLE_PLUGIN_ViaThinkSoft\OIDplus\OIDplus', $name);
1055 daniel-mar 225
                                                if ($name == 'CONFIG_VERSION') {
226
                                                        $value = 2.1;
227
                                                } else if (($name == 'MYSQL_PASSWORD') || ($name == 'ODBC_PASSWORD') || ($name == 'PDO_PASSWORD') || ($name == 'PGSQL_PASSWORD')) {
228
                                                        $value = base64_decode($value);
261 daniel-mar 229
                                                }
1055 daniel-mar 230
                                                self::$baseConfig->setValue($name, $value);
261 daniel-mar 231
                                        }
232
                                }
233
                        } else {
496 daniel-mar 234
                                if (!is_dir(OIDplus::localpath().'setup')) {
1050 daniel-mar 235
                                        throw new OIDplusConfigInitializationException(_L('File %1 is missing, but setup can\'t be started because its directory missing.',$config_file));
261 daniel-mar 236
                                } else {
280 daniel-mar 237
                                        if (self::$html) {
1055 daniel-mar 238
                                                if (!self::insideSetup()) {
801 daniel-mar 239
                                                        header('Location:'.OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/');
360 daniel-mar 240
                                                        die(_L('Redirecting to setup...'));
349 daniel-mar 241
                                                } else {
242
                                                        return self::$baseConfig;
243
                                                }
261 daniel-mar 244
                                        } else {
245
                                                // This can be displayed in e.g. ajax.php
1050 daniel-mar 246
                                                throw new OIDplusConfigInitializationException(_L('File %1 is missing. Please run setup again.',$config_file));
261 daniel-mar 247
                                        }
248
                                }
249
                        }
250
 
251
                        // Check important config settings
252
 
263 daniel-mar 253
                        if (self::$baseConfig->getValue('CONFIG_VERSION') != 2.1) {
801 daniel-mar 254
                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/') !== 0) {
503 daniel-mar 255
                                        throw new OIDplusConfigInitializationException(_L("The information located in %1 is outdated.",realpath($config_file)));
256
                                }
261 daniel-mar 257
                        }
258
 
263 daniel-mar 259
                        if (self::$baseConfig->getValue('SERVER_SECRET', '') === '') {
801 daniel-mar 260
                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/') !== 0) {
503 daniel-mar 261
                                        throw new OIDplusConfigInitializationException(_L("You must set a value for SERVER_SECRET in %1 for the system to operate secure.",realpath($config_file)));
262
                                }
261 daniel-mar 263
                        }
264
                }
265
 
263 daniel-mar 266
                return self::$baseConfig;
261 daniel-mar 267
        }
268
 
263 daniel-mar 269
        private static $config = null;
1116 daniel-mar 270
 
271
        /**
272
         * @return OIDplusConfig
273
         * @throws OIDplusException
274
         */
275
        public static function config(): OIDplusConfig {
263 daniel-mar 276
                if ($first_init = is_null(self::$config)) {
277
                        self::$config = new OIDplusConfig();
2 daniel-mar 278
                }
263 daniel-mar 279
 
280
                if ($first_init) {
281
                        // These are important settings for base functionalities and therefore are not inside plugins
282
                        self::$config->prepareConfigKey('system_title', 'What is the name of your RA?', 'OIDplus 2.0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
283
                                if (empty($value)) {
360 daniel-mar 284
                                        throw new OIDplusException(_L('Please enter a value for the system title.'));
263 daniel-mar 285
                                }
286
                        });
287
                        self::$config->prepareConfigKey('admin_email', 'E-Mail address of the system administrator', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
288
                                if (!empty($value) && !OIDplus::mailUtils()->validMailAddress($value)) {
360 daniel-mar 289
                                        throw new OIDplusException(_L('This is not a correct email address'));
263 daniel-mar 290
                                }
291
                        });
875 daniel-mar 292
                        self::$config->prepareConfigKey('global_cc', 'Global CC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function(&$value) {
293
                                $value = trim($value);
294
                                if ($value === '') return;
295
                                $addrs = explode(';', $value);
296
                                foreach ($addrs as $addr) {
297
                                        $addr = trim($addr);
298
                                        if (!empty($addr) && !OIDplus::mailUtils()->validMailAddress($addr)) {
299
                                                throw new OIDplusException(_L('%1 is not a correct email address',$addr));
300
                                        }
263 daniel-mar 301
                                }
302
                        });
875 daniel-mar 303
                        self::$config->prepareConfigKey('global_bcc', 'Global BCC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function(&$value) {
304
                                $value = trim($value);
305
                                if ($value === '') return;
306
                                $addrs = explode(';', $value);
307
                                foreach ($addrs as $addr) {
308
                                        $addr = trim($addr);
309
                                        if (!empty($addr) && !OIDplus::mailUtils()->validMailAddress($addr)) {
310
                                                throw new OIDplusException(_L('%1 is not a correct email address',$addr));
311
                                        }
312
                                }
313
                        });
263 daniel-mar 314
                        self::$config->prepareConfigKey('objecttypes_initialized', 'List of object type plugins that were initialized once', '', OIDplusConfig::PROTECTION_READONLY, function($value) {
315
                                // Nothing here yet
316
                        });
317
                        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) {
1050 daniel-mar 318
                                // 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?
263 daniel-mar 319
 
320
                                $ary = explode(';',$value);
321
                                $uniq_ary = array_unique($ary);
322
 
323
                                if (count($ary) != count($uniq_ary)) {
360 daniel-mar 324
                                        throw new OIDplusException(_L('Please check your input. Some object types are double.'));
263 daniel-mar 325
                                }
326
 
327
                                foreach ($ary as $ot_check) {
328
                                        $ns_found = false;
329
                                        foreach (OIDplus::getEnabledObjectTypes() as $ot) {
330
                                                if ($ot::ns() == $ot_check) {
331
                                                        $ns_found = true;
332
                                                        break;
333
                                                }
334
                                        }
335
                                        foreach (OIDplus::getDisabledObjectTypes() as $ot) {
336
                                                if ($ot::ns() == $ot_check) {
337
                                                        $ns_found = true;
338
                                                        break;
339
                                                }
340
                                        }
341
                                        if (!$ns_found) {
360 daniel-mar 342
                                                throw new OIDplusException(_L('Please check your input. Namespace "%1" is not found',$ot_check));
263 daniel-mar 343
                                        }
344
                                }
345
                        });
346
                        self::$config->prepareConfigKey('oidplus_private_key', 'Private key for this system', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
347
                                // Nothing here yet
348
                        });
349
                        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) {
350
                                // Nothing here yet
351
                        });
324 daniel-mar 352
                        self::$config->prepareConfigKey('last_known_system_url', 'Last known System URL', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
353
                                // Nothing here yet
354
                        });
412 daniel-mar 355
                        self::$config->prepareConfigKey('last_known_version', 'Last known OIDplus Version', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
356
                                // Nothing here yet
357
                        });
1088 daniel-mar 358
                        self::$config->prepareConfigKey('default_ra_auth_method', 'Default auth method used for generating password of RAs (must exist in plugins/[vendorname]/auth/)? Empty = OIDplus decides.', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
359
                                if (trim($value) === '') return; // OIDplus decides
360
 
453 daniel-mar 361
                                $good = true;
362
                                if (strpos($value,'/') !== false) $good = false;
363
                                if (strpos($value,'\\') !== false) $good = false;
364
                                if (strpos($value,'..') !== false) $good = false;
365
                                if (!$good) {
366
                                        throw new OIDplusException(_L('Invalid auth plugin folder name. Do only enter a folder name, not an absolute or relative path'));
367
                                }
368
 
1099 daniel-mar 369
                                OIDplus::checkRaAuthPluginAvailable($value, true);
453 daniel-mar 370
                        });
263 daniel-mar 371
                }
372
 
373
                return self::$config;
2 daniel-mar 374
        }
375
 
263 daniel-mar 376
        private static $gui = null;
1116 daniel-mar 377
 
378
        /**
379
         * @return OIDplusGui
380
         */
381
        public static function gui(): OIDplusGui {
263 daniel-mar 382
                if (is_null(self::$gui)) {
383
                        self::$gui = new OIDplusGui();
86 daniel-mar 384
                }
263 daniel-mar 385
                return self::$gui;
2 daniel-mar 386
        }
387
 
263 daniel-mar 388
        private static $authUtils = null;
1116 daniel-mar 389
 
390
        /**
391
         * @return OIDplusAuthUtils
392
         */
393
        public static function authUtils(): OIDplusAuthUtils {
263 daniel-mar 394
                if (is_null(self::$authUtils)) {
395
                        self::$authUtils = new OIDplusAuthUtils();
86 daniel-mar 396
                }
263 daniel-mar 397
                return self::$authUtils;
2 daniel-mar 398
        }
399
 
263 daniel-mar 400
        private static $mailUtils = null;
1116 daniel-mar 401
 
402
        /**
403
         * @return OIDplusMailUtils
404
         */
405
        public static function mailUtils(): OIDplusMailUtils {
263 daniel-mar 406
                if (is_null(self::$mailUtils)) {
407
                        self::$mailUtils = new OIDplusMailUtils();
250 daniel-mar 408
                }
263 daniel-mar 409
                return self::$mailUtils;
250 daniel-mar 410
        }
411
 
557 daniel-mar 412
        private static $cookieUtils = null;
1116 daniel-mar 413
 
414
        /**
415
         * @return OIDplusCookieUtils
416
         */
417
        public static function cookieUtils(): OIDplusCookieUtils {
557 daniel-mar 418
                if (is_null(self::$cookieUtils)) {
419
                        self::$cookieUtils = new OIDplusCookieUtils();
420
                }
421
                return self::$cookieUtils;
422
        }
423
 
263 daniel-mar 424
        private static $menuUtils = null;
1116 daniel-mar 425
 
426
        /**
427
         * @return OIDplusMenuUtils
428
         */
429
        public static function menuUtils(): OIDplusMenuUtils {
263 daniel-mar 430
                if (is_null(self::$menuUtils)) {
431
                        self::$menuUtils = new OIDplusMenuUtils();
250 daniel-mar 432
                }
263 daniel-mar 433
                return self::$menuUtils;
250 daniel-mar 434
        }
435
 
263 daniel-mar 436
        private static $logger = null;
1116 daniel-mar 437
 
438
        /**
439
         * @return OIDplusLogger
440
         */
441
        public static function logger(): OIDplusLogger {
263 daniel-mar 442
                if (is_null(self::$logger)) {
443
                        self::$logger = new OIDplusLogger();
115 daniel-mar 444
                }
263 daniel-mar 445
                return self::$logger;
115 daniel-mar 446
        }
447
 
1050 daniel-mar 448
        // --- SQL slang plugin
274 daniel-mar 449
 
1112 daniel-mar 450
        /**
1116 daniel-mar 451
         * @param OIDplusSqlSlangPlugin $plugin
452
         * @return void
453
         * @throws OIDplusException
454
         */
274 daniel-mar 455
        private static function registerSqlSlangPlugin(OIDplusSqlSlangPlugin $plugin) {
456
                $name = $plugin::id();
457
 
1112 daniel-mar 458
                if ($name === '') {
459
                        throw new OIDplusException(_L('Plugin %1 cannot be registered because it does not return a valid ID', $plugin->getPluginDirectory()));
460
                }
461
 
449 daniel-mar 462
                if (isset(self::$sqlSlangPlugins[$name])) {
451 daniel-mar 463
                        $plugintype_hf = _L('SQL slang');
592 daniel-mar 464
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
449 daniel-mar 465
                }
466
 
274 daniel-mar 467
                self::$sqlSlangPlugins[$name] = $plugin;
468
        }
469
 
1116 daniel-mar 470
        /**
471
         * @return OIDplusSqlSlangPlugin[]
472
         */
473
        public static function getSqlSlangPlugins(): array {
274 daniel-mar 474
                return self::$sqlSlangPlugins;
475
        }
476
 
1116 daniel-mar 477
        /**
478
         * @param string $id
479
         * @return OIDplusSqlSlangPlugin|null
480
         */
481
        public static function getSqlSlangPlugin(string $id)/*: ?OIDplusSqlSlangPlugin*/ {
318 daniel-mar 482
                if (isset(self::$sqlSlangPlugins[$id])) {
483
                        return self::$sqlSlangPlugins[$id];
484
                } else {
485
                        return null;
486
                }
487
        }
488
 
1050 daniel-mar 489
        // --- Database plugin
74 daniel-mar 490
 
1112 daniel-mar 491
        /**
1116 daniel-mar 492
         * @param OIDplusDatabasePlugin $plugin
493
         * @return void
494
         * @throws OIDplusException
495
         */
227 daniel-mar 496
        private static function registerDatabasePlugin(OIDplusDatabasePlugin $plugin) {
275 daniel-mar 497
                $name = $plugin::id();
150 daniel-mar 498
 
1112 daniel-mar 499
                if ($name === '') {
500
                        throw new OIDplusException(_L('Plugin %1 cannot be registered because it does not return a valid ID', $plugin->getPluginDirectory()));
501
                }
502
 
449 daniel-mar 503
                if (isset(self::$dbPlugins[$name])) {
504
                        $plugintype_hf = _L('Database');
592 daniel-mar 505
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
449 daniel-mar 506
                }
507
 
150 daniel-mar 508
                self::$dbPlugins[$name] = $plugin;
509
        }
510
 
1116 daniel-mar 511
        /**
512
         * @return OIDplusDatabasePlugin[]
513
         */
514
        public static function getDatabasePlugins(): array {
150 daniel-mar 515
                return self::$dbPlugins;
516
        }
517
 
1116 daniel-mar 518
        /**
519
         * @return OIDplusDatabasePlugin
520
         * @throws OIDplusException, OIDplusConfigInitializationException
521
         */
522
        public static function getActiveDatabasePlugin(): OIDplusDatabasePlugin {
702 daniel-mar 523
                $db_plugin_name = OIDplus::baseConfig()->getValue('DATABASE_PLUGIN','');
524
                if ($db_plugin_name === '') {
360 daniel-mar 525
                        throw new OIDplusConfigInitializationException(_L('No database plugin selected in config file'));
260 daniel-mar 526
                }
1016 daniel-mar 527
                foreach (self::$dbPlugins as $name => $plugin) {
528
                        if (strtolower($name) == strtolower($db_plugin_name)) {
529
                                return $plugin;
530
                        }
227 daniel-mar 531
                }
1016 daniel-mar 532
                throw new OIDplusConfigInitializationException(_L('Database plugin "%1" not found',$db_plugin_name));
227 daniel-mar 533
        }
534
 
1116 daniel-mar 535
        /**
536
         * @var OIDplusDatabaseConnection|null
537
         */
295 daniel-mar 538
        private static $dbMainSession = null;
1116 daniel-mar 539
 
540
        /**
541
         * @return OIDplusDatabaseConnection
542
         * @throws OIDplusException, OIDplusConfigInitializationException
543
         */
544
        public static function db(): OIDplusDatabaseConnection {
295 daniel-mar 545
                if (is_null(self::$dbMainSession)) {
546
                        self::$dbMainSession = self::getActiveDatabasePlugin()->newConnection();
547
                }
548
                if (!self::$dbMainSession->isConnected()) self::$dbMainSession->connect();
549
                return self::$dbMainSession;
550
        }
551
 
1116 daniel-mar 552
        /**
553
         * @var OIDplusDatabaseConnection|null
554
         */
295 daniel-mar 555
        private static $dbIsolatedSession = null;
1116 daniel-mar 556
 
557
        /**
558
         * @return OIDplusDatabaseConnection
559
         * @throws OIDplusException, OIDplusConfigInitializationException
560
         */
561
        public static function dbIsolated(): OIDplusDatabaseConnection {
295 daniel-mar 562
                if (is_null(self::$dbIsolatedSession)) {
563
                        self::$dbIsolatedSession = self::getActiveDatabasePlugin()->newConnection();
564
                }
565
                if (!self::$dbIsolatedSession->isConnected()) self::$dbIsolatedSession->connect();
566
                return self::$dbIsolatedSession;
567
        }
568
 
1050 daniel-mar 569
        // --- CAPTCHA plugin
702 daniel-mar 570
 
1112 daniel-mar 571
        /**
1116 daniel-mar 572
         * @param OIDplusCaptchaPlugin $plugin
573
         * @return void
574
         * @throws OIDplusException
575
         */
702 daniel-mar 576
        private static function registerCaptchaPlugin(OIDplusCaptchaPlugin $plugin) {
577
                $name = $plugin::id();
578
 
1112 daniel-mar 579
                if ($name === '') {
580
                        throw new OIDplusException(_L('Plugin %1 cannot be registered because it does not return a valid ID', $plugin->getPluginDirectory()));
581
                }
582
 
702 daniel-mar 583
                if (isset(self::$captchaPlugins[$name])) {
584
                        $plugintype_hf = _L('CAPTCHA');
585
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
586
                }
587
 
588
                self::$captchaPlugins[$name] = $plugin;
589
        }
590
 
1116 daniel-mar 591
        /**
592
         * @return OIDplusCaptchaPlugin[]
593
         */
594
        public static function getCaptchaPlugins(): array {
702 daniel-mar 595
                return self::$captchaPlugins;
596
        }
597
 
1116 daniel-mar 598
        /**
599
         * @return string
600
         * @throws OIDplusException, OIDplusConfigInitializationException
601
         */
602
        public static function getActiveCaptchaPluginId(): string {
702 daniel-mar 603
                $captcha_plugin_name = OIDplus::baseConfig()->getValue('CAPTCHA_PLUGIN', '');
604
 
605
                if (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false) && ($captcha_plugin_name === '')) {
606
                        // Legacy config file support!
1016 daniel-mar 607
                        $captcha_plugin_name = 'reCAPTCHA';
702 daniel-mar 608
                }
609
 
704 daniel-mar 610
                if ($captcha_plugin_name === '') $captcha_plugin_name = 'None'; // the "None" plugin is a must-have!
702 daniel-mar 611
 
704 daniel-mar 612
                return $captcha_plugin_name;
613
        }
614
 
1116 daniel-mar 615
        /**
616
         * @return OIDplusCaptchaPlugin
617
         * @throws OIDplusException, OIDplusConfigInitializationException
618
         */
619
        public static function getActiveCaptchaPlugin(): OIDplusCaptchaPlugin {
704 daniel-mar 620
                $captcha_plugin_name = OIDplus::getActiveCaptchaPluginId();
1016 daniel-mar 621
                foreach (self::$captchaPlugins as $name => $plugin) {
622
                        if (strtolower($name) == strtolower($captcha_plugin_name)) {
623
                                return $plugin;
624
                        }
702 daniel-mar 625
                }
1016 daniel-mar 626
                throw new OIDplusConfigInitializationException(_L('CAPTCHA plugin "%1" not found',$captcha_plugin_name));
702 daniel-mar 627
        }
628
 
1050 daniel-mar 629
        // --- Page plugin
227 daniel-mar 630
 
1112 daniel-mar 631
        /**
1116 daniel-mar 632
         * @param OIDplusPagePlugin $plugin
633
         * @return void
634
         */
224 daniel-mar 635
        private static function registerPagePlugin(OIDplusPagePlugin $plugin) {
281 daniel-mar 636
                self::$pagePlugins[] = $plugin;
61 daniel-mar 637
        }
638
 
1116 daniel-mar 639
        /**
640
         * @return OIDplusPagePlugin[]
641
         */
642
        public static function getPagePlugins(): array {
281 daniel-mar 643
                return self::$pagePlugins;
61 daniel-mar 644
        }
645
 
1050 daniel-mar 646
        // --- Auth plugin
227 daniel-mar 647
 
1116 daniel-mar 648
        /**
649
         * @param string $foldername
650
         * @return OIDplusAuthPlugin|null
651
         */
652
        public static function getAuthPluginByFoldername(string $foldername)/*: ?OIDplusAuthPlugin*/ {
1088 daniel-mar 653
                $plugins = OIDplus::getAuthPlugins();
654
                foreach ($plugins as $plugin) {
655
                        if (basename($plugin->getPluginDirectory()) === $foldername) {
656
                                return $plugin;
657
                        }
658
                }
659
                return null;
660
        }
661
 
1116 daniel-mar 662
        /**
663
         * @param string $plugin_foldername
664
         * @param bool $must_hash
665
         * @return void
666
         * @throws OIDplusException
667
         */
668
        private static function checkRaAuthPluginAvailable(string $plugin_foldername, bool $must_hash) {
1122 daniel-mar 669
                // if (!wildcard_is_dir(OIDplus::localpath().'plugins/'.'*'.'/auth/'.$plugin_foldername)) {
670
                $plugin = OIDplus::getAuthPluginByFoldername($plugin_foldername);
671
                if (is_null($plugin)) {
672
                        throw new OIDplusException(_L('The auth plugin "%1" does not exist in plugin directory %2',$plugin_foldername,'plugins/[vendorname]/auth/'));
673
                }
1088 daniel-mar 674
 
1122 daniel-mar 675
                $reason = '';
676
                if (!$plugin->availableForVerify($reason)) {
677
                        throw new OIDplusException(trim(_L('The auth plugin "%1" is not available for password verification on this system.',$plugin_foldername).' '.$reason));
678
                }
679
                if ($must_hash && !$plugin->availableForHash($reason)) {
680
                        throw new OIDplusException(trim(_L('The auth plugin "%1" is not available for hashing on this system.',$plugin_foldername).' '.$reason));
681
                }
1088 daniel-mar 682
        }
683
 
1116 daniel-mar 684
        /**
685
         * @param bool $must_hash
686
         * @return OIDplusAuthPlugin|null
687
         * @throws OIDplusException
688
         */
689
        public static function getDefaultRaAuthPlugin(bool $must_hash)/*: OIDplusAuthPlugin*/ {
1088 daniel-mar 690
                // 1. Priority: Use the auth plugin the user prefers
691
                $def_plugin_foldername = OIDplus::config()->getValue('default_ra_auth_method');
692
                if (trim($def_plugin_foldername) !== '') {
1099 daniel-mar 693
                        OIDplus::checkRaAuthPluginAvailable($def_plugin_foldername, $must_hash);
1116 daniel-mar 694
                        return OIDplus::getAuthPluginByFoldername($def_plugin_foldername);
1088 daniel-mar 695
                }
696
 
697
                // 2. Priority: If empty (i.e. OIDplus may decide), choose the best ViaThinkSoft plugin that is supported on this system
698
                $preferred_auth_plugins = array(
1099 daniel-mar 699
                        // Sorted by preference
700
                        'A4_argon2',  // usually Salted Argon2id
701
                        'A3_bcrypt',  // usually Salted BCrypt
702
                        'A5_vts_mcf', // usually SHA3-512-HMAC
703
                        'A6_crypt'    // usually Salted SHA512 with 5000 rounds
1088 daniel-mar 704
                );
705
                foreach ($preferred_auth_plugins as $plugin_foldername) {
706
                        $plugin = OIDplus::getAuthPluginByFoldername($plugin_foldername);
707
                        if (is_null($plugin)) continue;
708
 
709
                        $reason = '';
1099 daniel-mar 710
                        if (!$plugin->availableForHash($reason)) continue;
711
                        if ($must_hash && !$plugin->availableForVerify($reason)) continue;
1088 daniel-mar 712
                        return $plugin;
713
                }
714
 
715
                // 3. Priority: If nothing found, take the first found plugin
716
                $plugins = OIDplus::getAuthPlugins();
1099 daniel-mar 717
                foreach ($plugins as $plugin) {
718
                        $reason = '';
719
                        if (!$plugin->availableForHash($reason)) continue;
720
                        if ($must_hash && !$plugin->availableForVerify($reason)) continue;
721
                        return $plugin;
1088 daniel-mar 722
                }
723
 
724
                // 4. Priority: We must deny the creation of the password because we have no auth plugin!
725
                throw new OIDplusException(_L('Could not find a fitting auth plugin!'));
726
        }
727
 
1112 daniel-mar 728
        /**
1116 daniel-mar 729
         * @param OIDplusAuthPlugin $plugin
730
         * @return void
731
         * @throws OIDplusConfigInitializationException
732
         * @throws OIDplusException
733
         */
227 daniel-mar 734
        private static function registerAuthPlugin(OIDplusAuthPlugin $plugin) {
1089 daniel-mar 735
                $reason = '';
1099 daniel-mar 736
                if (OIDplus::baseConfig()->getValue('DEBUG') && $plugin->availableForHash($reason) && $plugin->availableForVerify($reason)) {
456 daniel-mar 737
                        $password = generateRandomString(25);
459 daniel-mar 738
 
461 daniel-mar 739
                        try {
740
                                $authInfo = $plugin->generate($password);
741
                        } catch (OIDplusException $e) {
1090 daniel-mar 742
                                // This can happen when the AuthKey is too long for the database field
1088 daniel-mar 743
                                // Note: The constructor and setters of OIDplusRAAuthInfo() already check for length and null/false values.
461 daniel-mar 744
                                throw new OIDplusException(_L('Auth plugin "%1" is erroneous: %2',basename($plugin->getPluginDirectory()),$e->getMessage()));
745
                        }
1088 daniel-mar 746
 
461 daniel-mar 747
                        $authInfo_AuthKeyDiff = clone $authInfo;
748
                        $authInfo_AuthKeyDiff->setAuthKey(strrev($authInfo_AuthKeyDiff->getAuthKey()));
749
 
750
                        if ((!$plugin->verify($authInfo,$password)) ||
1122 daniel-mar 751
                                ($plugin->verify($authInfo_AuthKeyDiff,$password)) ||
752
                                ($plugin->verify($authInfo,$password.'x'))) {
1088 daniel-mar 753
                                throw new OIDplusException(_L('Auth plugin "%1" is erroneous: Generate/Verify self-test failed',basename($plugin->getPluginDirectory())));
456 daniel-mar 754
                        }
453 daniel-mar 755
                }
756
 
227 daniel-mar 757
                self::$authPlugins[] = $plugin;
758
        }
759
 
1116 daniel-mar 760
        /**
761
         * @return OIDplusAuthPlugin[]
762
         */
763
        public static function getAuthPlugins(): array {
221 daniel-mar 764
                return self::$authPlugins;
765
        }
766
 
1050 daniel-mar 767
        // --- Language plugin
355 daniel-mar 768
 
1112 daniel-mar 769
        /**
1116 daniel-mar 770
         * @param OIDplusLanguagePlugin $plugin
771
         * @return void
772
         */
355 daniel-mar 773
        private static function registerLanguagePlugin(OIDplusLanguagePlugin $plugin) {
774
                self::$languagePlugins[] = $plugin;
775
        }
776
 
1116 daniel-mar 777
        /**
778
         * @return OIDplusLanguagePlugin[]
779
         */
780
        public static function getLanguagePlugins(): array {
355 daniel-mar 781
                return self::$languagePlugins;
782
        }
783
 
1050 daniel-mar 784
        // --- Design plugin
449 daniel-mar 785
 
1112 daniel-mar 786
        /**
1116 daniel-mar 787
         * @param OIDplusDesignPlugin $plugin
788
         * @return void
789
         */
449 daniel-mar 790
        private static function registerDesignPlugin(OIDplusDesignPlugin $plugin) {
791
                self::$designPlugins[] = $plugin;
792
        }
793
 
1116 daniel-mar 794
        /**
795
         * @return OIDplusDesignPlugin[]
796
         */
797
        public static function getDesignPlugins(): array {
449 daniel-mar 798
                return self::$designPlugins;
799
        }
800
 
1116 daniel-mar 801
        /**
802
         * @return OIDplusDesignPlugin|null
803
         * @throws OIDplusException
804
         */
805
        public static function getActiveDesignPlugin()/*: ?OIDplusDesignPlugin*/ {
819 daniel-mar 806
                $plugins = OIDplus::getDesignPlugins();
807
                foreach ($plugins as $plugin) {
808
                        if ((basename($plugin->getPluginDirectory())) == OIDplus::config()->getValue('design','default')) {
809
                                return $plugin;
810
                        }
811
                }
812
                return null;
813
        }
814
 
1050 daniel-mar 815
        // --- Logger plugin
289 daniel-mar 816
 
1112 daniel-mar 817
        /**
1116 daniel-mar 818
         * @param OIDplusLoggerPlugin $plugin
819
         * @return void
820
         */
289 daniel-mar 821
        private static function registerLoggerPlugin(OIDplusLoggerPlugin $plugin) {
822
                self::$loggerPlugins[] = $plugin;
823
        }
824
 
1116 daniel-mar 825
        /**
826
         * @return OIDplusLoggerPlugin[]
827
         */
828
        public static function getLoggerPlugins(): array {
289 daniel-mar 829
                return self::$loggerPlugins;
830
        }
831
 
1050 daniel-mar 832
        // --- Object type plugin
227 daniel-mar 833
 
1112 daniel-mar 834
        /**
1116 daniel-mar 835
         * @param OIDplusObjectTypePlugin $plugin
836
         * @return void
837
         * @throws OIDplusException
838
         */
227 daniel-mar 839
        private static function registerObjectTypePlugin(OIDplusObjectTypePlugin $plugin) {
840
                self::$objectTypePlugins[] = $plugin;
841
 
842
                $ot = $plugin::getObjectTypeClassName();
843
                self::registerObjectType($ot);
844
        }
845
 
1112 daniel-mar 846
        /**
1116 daniel-mar 847
         * @param string|OIDplusObject $ot Object type class name (OIDplusObject)
848
         * @return void
849
         * @throws OIDplusException
850
         */
224 daniel-mar 851
        private static function registerObjectType($ot) {
66 daniel-mar 852
                $ns = $ot::ns();
860 daniel-mar 853
                if (empty($ns)) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Namespace must not be empty',$ot));
66 daniel-mar 854
 
860 daniel-mar 855
                // Currently, we must enforce that namespaces in objectType plugins are lowercase, because prefilterQuery() makes all namespaces lowercase and the DBMS should be case-sensitive
856
                if ($ns != strtolower($ns)) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Namespace %2 must be lower-case',$ot,$ns));
66 daniel-mar 857
 
860 daniel-mar 858
                $root = $ot::root();
859
                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.':'));
860
 
66 daniel-mar 861
                $ns_found = false;
227 daniel-mar 862
                foreach (array_merge(OIDplus::getEnabledObjectTypes(), OIDplus::getDisabledObjectTypes()) as $test_ot) {
66 daniel-mar 863
                        if ($test_ot::ns() == $ns) {
864
                                $ns_found = true;
865
                                break;
866
                        }
867
                }
868
                if ($ns_found) {
360 daniel-mar 869
                        throw new OIDplusException(_L('Attention: Two objectType plugins use the same namespace "%1"!',$ns));
66 daniel-mar 870
                }
871
 
872
                $init = OIDplus::config()->getValue("objecttypes_initialized");
873
                $init_ary = empty($init) ? array() : explode(';', $init);
70 daniel-mar 874
                $init_ary = array_map('trim', $init_ary);
66 daniel-mar 875
 
876
                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
877
                $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
70 daniel-mar 878
                $enabled_ary = array_map('trim', $enabled_ary);
66 daniel-mar 879
 
79 daniel-mar 880
                if (in_array($ns, $enabled_ary)) {
447 daniel-mar 881
                        // If it is in the list of enabled object types, it is enabled (obviously)
79 daniel-mar 882
                        $do_enable = true;
883
                } else {
447 daniel-mar 884
                        if (!OIDplus::config()->getValue('oobe_objects_done')) {
885
                                // If the OOBE wizard is NOT done, then just enable the "oid" object type by default
79 daniel-mar 886
                                $do_enable = $ns == 'oid';
887
                        } else {
447 daniel-mar 888
                                // If the OOBE wizard was done (once), then
889
                                // we will enable all object types which were never initialized
890
                                // (i.e. a plugin folder was freshly added)
79 daniel-mar 891
                                $do_enable = !in_array($ns, $init_ary);
892
                        }
893
                }
894
 
895
                if ($do_enable) {
227 daniel-mar 896
                        self::$enabledObjectTypes[] = $ot;
897
                        usort(self::$enabledObjectTypes, function($a, $b) {
66 daniel-mar 898
                                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
899
                                $enabled_ary = explode(';', $enabled);
900
 
901
                                $idx_a = array_search($a::ns(), $enabled_ary);
902
                                $idx_b = array_search($b::ns(), $enabled_ary);
903
 
1112 daniel-mar 904
                                if ($idx_a == $idx_b) return 0;
905
                                return ($idx_a > $idx_b) ? +1 : -1;
66 daniel-mar 906
                        });
74 daniel-mar 907
                } else {
908
                        self::$disabledObjectTypes[] = $ot;
66 daniel-mar 909
                }
910
 
911
                if (!in_array($ns, $init_ary)) {
912
                        // Was never initialized before, so we add it to the list of enabled object types once
913
 
79 daniel-mar 914
                        if ($do_enable) {
915
                                $enabled_ary[] = $ns;
672 daniel-mar 916
                                // Important: Don't validate the input, because the other object types might not be initialized yet! So use setValueNoCallback() instead setValue().
917
                                OIDplus::config()->setValueNoCallback("objecttypes_enabled", implode(';', $enabled_ary));
79 daniel-mar 918
                        }
66 daniel-mar 919
 
920
                        $init_ary[] = $ns;
921
                        OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
922
                }
61 daniel-mar 923
        }
924
 
1116 daniel-mar 925
        /**
926
         * @return OIDplusObjectTypePlugin[]
927
         */
928
        public static function getObjectTypePlugins(): array {
227 daniel-mar 929
                return self::$objectTypePlugins;
61 daniel-mar 930
        }
931
 
1116 daniel-mar 932
        /**
933
         * @return OIDplusObjectTypePlugin[]
934
         */
935
        public static function getObjectTypePluginsEnabled(): array {
227 daniel-mar 936
                $res = array();
937
                foreach (self::$objectTypePlugins as $plugin) {
938
                        $ot = $plugin::getObjectTypeClassName();
939
                        if (in_array($ot, self::$enabledObjectTypes)) $res[] = $plugin;
940
                }
941
                return $res;
74 daniel-mar 942
        }
943
 
1116 daniel-mar 944
        /**
945
         * @return OIDplusObjectTypePlugin[]
946
         */
947
        public static function getObjectTypePluginsDisabled(): array {
227 daniel-mar 948
                $res = array();
949
                foreach (self::$objectTypePlugins as $plugin) {
950
                        $ot = $plugin::getObjectTypeClassName();
951
                        if (in_array($ot, self::$disabledObjectTypes)) $res[] = $plugin;
74 daniel-mar 952
                }
227 daniel-mar 953
                return $res;
74 daniel-mar 954
        }
955
 
1116 daniel-mar 956
        /**
957
         * @return string[]|OIDplusObject[] Classname of a OIDplusObject class
958
         */
959
        public static function getEnabledObjectTypes(): array {
227 daniel-mar 960
                return self::$enabledObjectTypes;
961
        }
74 daniel-mar 962
 
1116 daniel-mar 963
        /**
964
         * @return string[]|OIDplusObject[] Classname of a OIDplusObject class
965
         */
966
        public static function getDisabledObjectTypes(): array {
227 daniel-mar 967
                return self::$disabledObjectTypes;
968
        }
74 daniel-mar 969
 
1050 daniel-mar 970
        // --- Plugin handling functions
277 daniel-mar 971
 
1116 daniel-mar 972
        /**
973
         * @return OIDplusPlugin[]
974
         */
975
        public static function getAllPlugins(): array {
320 daniel-mar 976
                $res = array();
977
                $res = array_merge($res, self::$pagePlugins);
978
                $res = array_merge($res, self::$authPlugins);
979
                $res = array_merge($res, self::$loggerPlugins);
980
                $res = array_merge($res, self::$objectTypePlugins);
981
                $res = array_merge($res, self::$dbPlugins);
702 daniel-mar 982
                $res = array_merge($res, self::$captchaPlugins);
320 daniel-mar 983
                $res = array_merge($res, self::$sqlSlangPlugins);
355 daniel-mar 984
                $res = array_merge($res, self::$languagePlugins);
1116 daniel-mar 985
                return array_merge($res, self::$designPlugins);
320 daniel-mar 986
        }
987
 
1116 daniel-mar 988
        /**
989
         * @param string $oid
990
         * @return OIDplusPlugin|null
991
         */
992
        public static function getPluginByOid(string $oid)/*: ?OIDplusPlugin*/ {
320 daniel-mar 993
                $plugins = self::getAllPlugins();
321 daniel-mar 994
                foreach ($plugins as $plugin) {
995
                        if (oid_dotnotation_equal($plugin->getManifest()->getOid(), $oid)) {
996
                                return $plugin;
320 daniel-mar 997
                        }
998
                }
999
                return null;
1000
        }
1001
 
1116 daniel-mar 1002
        /**
1003
         * @param string $classname
1004
         * @return OIDplusPlugin|null
1005
         */
1006
        public static function getPluginByClassName(string $classname)/*: ?OIDplusPlugin*/ {
380 daniel-mar 1007
                $plugins = self::getAllPlugins();
1008
                foreach ($plugins as $plugin) {
1009
                        if (get_class($plugin) === $classname) {
1010
                                return $plugin;
1011
                        }
1012
                }
1013
                return null;
277 daniel-mar 1014
        }
1015
 
594 daniel-mar 1016
        /**
1122 daniel-mar 1017
         * Checks if the plugin is disabled
1018
         * @return bool true if plugin is enabled, false if plugin is disabled
1019
         * @throws OIDplusException if the class name or config file (disabled setting) does not contain a namespace
1020
         */
1050 daniel-mar 1021
        private static function pluginCheckDisabled($class_name): bool {
1022
                $path = explode('\\', $class_name);
1023
 
1024
                if (count($path) == 1) {
1025
                        throw new OIDplusException(_L('Plugin "%1" is erroneous',$class_name).': '._L('The plugin uses no namespaces. The new version of OIDplus requires plugin class files to be in a namespace. Please notify your plugin author and ask for an update.'));
1026
                }
1027
 
1028
                $class_end = end($path);
1029
                if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_end, false)) {
1030
                        throw new OIDplusConfigInitializationException(_L('Your base configuration file is outdated. Please change "%1" to "%2".','DISABLE_PLUGIN_'.$class_end,'DISABLE_PLUGIN_'.$class_name));
1031
                }
1032
 
1033
                if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
1034
                        return false;
1035
                }
1036
 
1037
                return true;
1038
        }
1039
 
1040
        /**
1116 daniel-mar 1041
         * @param string $pluginFolderMasks
1042
         * @param bool $flat
1043
         * @return OIDplusPluginManifest[]|array<string,array<string,OIDplusPluginManifest>>
1044
         * @throws OIDplusException
1045
         */
1046
        public static function getAllPluginManifests(string $pluginFolderMasks='*', bool $flat=true): array {
277 daniel-mar 1047
                $out = array();
279 daniel-mar 1048
                // Note: glob() will sort by default, so we do not need a page priority attribute.
1049
                //       So you just need to use a numeric plugin directory prefix (padded).
693 daniel-mar 1050
                $ary = array();
1051
                foreach (explode(',',$pluginFolderMasks) as $pluginFolderMask) {
1052
                        $ary = array_merge($ary,glob(OIDplus::localpath().'plugins/'.'*'.'/'.$pluginFolderMask.'/'.'*'.'/manifest.xml'));
1053
                }
646 daniel-mar 1054
 
1055
                // Sort the plugins by their type and name, as if they would be in a single vendor-folder!
1056
                uasort($ary, function($a,$b) {
1057
                        if ($a == $b) return 0;
1058
 
1122 daniel-mar 1059
                        $a = str_replace('\\', '/', $a);
646 daniel-mar 1060
                        $ary = explode('/',$a);
1061
                        $bry = explode('/',$b);
1062
 
1063
                        // First sort by type (publicPage, auth, database, language, ...)
1064
                        $a_type = $ary[count($ary)-1-2];
1065
                        $b_type = $bry[count($bry)-1-2];
1066
                        if ($a_type < $b_type) return -1;
1067
                        if ($a_type > $b_type) return 1;
1068
 
1069
                        // Then sort by name (090_login, 100_whois, etc.)
1070
                        $a_name = $ary[count($ary)-1-1];
1071
                        $b_name = $bry[count($bry)-1-1];
1072
                        if ($a_name < $b_name) return -1;
1073
                        if ($a_name > $b_name) return 1;
1074
 
1075
                        // If it is still equal, then finally sort by vendorname
1076
                        $a_vendor = $ary[count($ary)-1-3];
1077
                        $b_vendor = $bry[count($bry)-1-3];
1078
                        if ($a_vendor < $b_vendor) return -1;
1079
                        if ($a_vendor > $b_vendor) return 1;
1080
                        return 0;
1081
                });
1082
 
277 daniel-mar 1083
                foreach ($ary as $ini) {
1084
                        if (!file_exists($ini)) continue;
1085
 
307 daniel-mar 1086
                        $manifest = new OIDplusPluginManifest();
1087
                        $manifest->loadManifest($ini);
277 daniel-mar 1088
 
473 daniel-mar 1089
                        $class_name = $manifest->getPhpMainClass();
1050 daniel-mar 1090
                        if ($class_name) if (!self::pluginCheckDisabled($class_name)) continue;
473 daniel-mar 1091
 
307 daniel-mar 1092
                        if ($flat) {
1093
                                $out[] = $manifest;
1094
                        } else {
1122 daniel-mar 1095
                                $vendor_folder = basename(dirname($ini, 3));
1116 daniel-mar 1096
                                $plugintype_folder = basename(dirname($ini, 2));
307 daniel-mar 1097
                                $pluginname_folder = basename(dirname($ini));
1098
 
1099
                                if (!isset($out[$plugintype_folder])) $out[$plugintype_folder] = array();
1122 daniel-mar 1100
                                if (!isset($out[$plugintype_folder][$vendor_folder])) $out[$plugintype_folder][$vendor_folder] = array();
1101
                                $out[$plugintype_folder][$vendor_folder][$pluginname_folder] = $manifest;
307 daniel-mar 1102
                        }
277 daniel-mar 1103
                }
1104
                return $out;
1105
        }
1106
 
594 daniel-mar 1107
        /**
1116 daniel-mar 1108
         * @param $pluginDirName
1109
         * @param $expectedPluginClass
1110
         * @param $registerCallback
1111
         * @return string[]
1112
         * @throws OIDplusConfigInitializationException
1113
         * @throws OIDplusException
1114
         * @throws \ReflectionException
1115
         */
277 daniel-mar 1116
        public static function registerAllPlugins($pluginDirName, $expectedPluginClass, $registerCallback): array {
1117
                $out = array();
525 daniel-mar 1118
                if (is_array($pluginDirName)) {
1119
                        $ary = array();
1120
                        foreach ($pluginDirName as $pluginDirName_) {
1121
                                $ary = array_merge($ary, self::getAllPluginManifests($pluginDirName_, false));
1122
                        }
1123
                } else {
1124
                        $ary = self::getAllPluginManifests($pluginDirName, false);
1125
                }
320 daniel-mar 1126
                $known_plugin_oids = array();
456 daniel-mar 1127
                if (OIDplus::baseConfig()->getValue('DEBUG')) {
1128
                        $fake_feature = uuid_to_oid(gen_uuid());
588 daniel-mar 1129
                } else {
1130
                        $fake_feature = null;
456 daniel-mar 1131
                }
277 daniel-mar 1132
                foreach ($ary as $plugintype_folder => $bry) {
1122 daniel-mar 1133
                        foreach ($bry as $vendor_folder => $cry) {
1134
                                foreach ($cry as $pluginname_folder => $manifest) {
1135
                                        $class_name = $manifest->getPhpMainClass();
438 daniel-mar 1136
 
1122 daniel-mar 1137
                                        // Before we load the plugin, we want to make some checks to confirm
1138
                                        // that the plugin is working correctly.
438 daniel-mar 1139
 
1122 daniel-mar 1140
                                        if (!$class_name) {
1141
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('Manifest does not declare a PHP main class'));
1142
                                        }
1143
                                        if (!self::pluginCheckDisabled($class_name)) {
1144
                                                continue; // Plugin is disabled
1145
                                        }
1072 daniel-mar 1146
 
1122 daniel-mar 1147
                                        // Do some basic checks on the plugin PHP main class
1148
                                        if (!class_exists($class_name)) {
1149
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('Manifest declares PHP main class as "%1", but it could not be found', $class_name));
1150
                                        }
1151
                                        if (!is_subclass_of($class_name, $expectedPluginClass)) {
1152
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('Plugin main class "%1" is expected to be a subclass of "%2"', $class_name, $expectedPluginClass));
1153
                                        }
1154
                                        if (($class_name != $manifest->getTypeClass()) && (!is_subclass_of($class_name, $manifest->getTypeClass()))) {
1155
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $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()));
1156
                                        }
1157
                                        if (($manifest->getTypeClass() != $expectedPluginClass) && (!is_subclass_of($manifest->getTypeClass(), $expectedPluginClass))) {
1158
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('Class declared in manifest is "%1" does not fit expected class for this plugin type "%2"', $manifest->getTypeClass(), $expectedPluginClass));
1159
                                        }
308 daniel-mar 1160
 
1122 daniel-mar 1161
                                        // Do some basic checks on the plugin OID
1162
                                        $plugin_oid = $manifest->getOid();
1163
                                        if (!$plugin_oid) {
1164
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('Does not have an OID'));
1165
                                        }
1166
                                        if (!oid_valid_dotnotation($plugin_oid, false, false, 2)) {
1167
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('Plugin OID "%1" is invalid (needs to be valid dot-notation)', $plugin_oid));
1168
                                        }
1169
                                        if (isset($known_plugin_oids[$plugin_oid])) {
1170
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('The OID "%1" is already used by the plugin "%2"', $plugin_oid, $known_plugin_oids[$plugin_oid]));
1171
                                        }
646 daniel-mar 1172
 
1122 daniel-mar 1173
                                        // Additional check: Are third-party plugins using ViaThinkSoft plugin folders, OIDs or class namespaces?
1174
                                        $full_plugin_dir = dirname($manifest->getManifestFile());
1175
                                        $full_plugin_dir = substr($full_plugin_dir, strlen(OIDplus::localpath()));
1176
                                        $dir_is_viathinksoft = str_starts_with($full_plugin_dir, 'plugins/viathinksoft/') || str_starts_with($full_plugin_dir, 'plugins\\viathinksoft\\');
1177
                                        $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) }
1178
                                        $class_is_viathinksoft = str_starts_with($class_name, 'ViaThinkSoft\\');
1179
                                        if ($oid_is_viathinksoft != $class_is_viathinksoft) {
1180
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('Third-party plugins must not use the ViaThinkSoft PHP namespace. Please use your own vendor namespace.'));
1181
                                        }
1182
                                        $plugin_is_viathinksoft = $oid_is_viathinksoft && $class_is_viathinksoft;
1183
                                        if ($dir_is_viathinksoft != $plugin_is_viathinksoft) {
1184
                                                throw new OIDplusException(_L('Plugin "%1" is misplaced', $vendor_folder . '/' . $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/'));
1185
                                        }
1072 daniel-mar 1186
 
1122 daniel-mar 1187
                                        // Additional check: does the plugin define JS/CSS although it is not an interactive plugin type?
1188
                                        $has_js = $manifest->getJSFiles();
1189
                                        $has_css = $manifest->getCSSFiles();
1190
                                        $is_interactive = in_array(basename($plugintype_folder), OIDplus::INTERACTIVE_PLUGIN_TYPES);
1191
                                        $is_design = basename($plugintype_folder) === 'design';
1192
                                        if (!$is_interactive && $has_js) {
1193
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('%1 files are included in the manifest XML, but this plugin type does not allow such files.', 'JavaScript'));
1194
                                        }
1195
                                        if (!$is_interactive && !$is_design && $has_css) {
1196
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('%1 files are included in the manifest XML, but this plugin type does not allow such files.', 'CSS'));
1197
                                        }
320 daniel-mar 1198
 
1122 daniel-mar 1199
                                        // Additional check: Check "Setup CSS" and "Setup JS" (Allowed for plugin types: database, captcha)
1200
                                        $has_js_setup = $manifest->getJSFilesSetup();
1201
                                        $has_css_setup = $manifest->getCSSFilesSetup();
1202
                                        $is_database = basename($plugintype_folder) === 'database';
1203
                                        $is_captcha = basename($plugintype_folder) === 'captcha';
1204
                                        if (!$is_database && !$is_captcha && $has_js_setup) {
1205
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('%1 files are included in the manifest XML, but this plugin type does not allow such files.', 'Setup JavaScript'));
1206
                                        }
1207
                                        if (!$is_database && !$is_captcha && $has_css_setup) {
1208
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('%1 files are included in the manifest XML, but this plugin type does not allow such files.', 'Setup CSS'));
1209
                                        }
632 daniel-mar 1210
 
1122 daniel-mar 1211
                                        // Additional check: Are all CSS/JS files there?
1212
                                        $tmp = $manifest->getManifestLinkedFiles();
1213
                                        foreach ($tmp as $file) {
1214
                                                if (!file_exists($file)) {
1215
                                                        throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('File %1 was defined in manifest, but it is not existing', $file));
1216
                                                }
1072 daniel-mar 1217
                                        }
1218
 
1122 daniel-mar 1219
                                        // For the next check, we need an instance of the object
1220
                                        $obj = new $class_name();
456 daniel-mar 1221
 
1122 daniel-mar 1222
                                        // Additional check: Does the plugin misuse implementsFeature()?
1223
                                        // This is not enabled b default, because the GUID generation is slow on some machines.
1224
                                        // Also, it is very unlikely that someone misuses implementsFeature().
1225
                                        if (OIDplus::baseConfig()->getValue('DEBUG')) {
1226
                                                if ($obj->implementsFeature($fake_feature)) {
1227
                                                        // see https://devblogs.microsoft.com/oldnewthing/20040211-00/?p=40663
1228
                                                        throw new OIDplusException(_L('Plugin "%1" is erroneous', $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder) . ': ' . _L('implementsFeature() always returns true'));
1229
                                                }
456 daniel-mar 1230
                                        }
438 daniel-mar 1231
 
1122 daniel-mar 1232
                                        // Now we can continue
1233
                                        $known_plugin_oids[$plugin_oid] = $vendor_folder . '/' . $plugintype_folder . '/' . $pluginname_folder;
1234
                                        $out[] = $class_name;
1235
                                        if (!is_null($registerCallback)) {
1236
                                                call_user_func($registerCallback, $obj);
444 daniel-mar 1237
 
1122 daniel-mar 1238
                                                // Alternative approaches:
1239
                                                //$registerCallback[0]::{$registerCallback[1]}($obj);
1240
                                                // or:
1241
                                                //forward_static_call($registerCallback, $obj);
1242
                                        }
279 daniel-mar 1243
                                }
277 daniel-mar 1244
                        }
1245
                }
1246
                return $out;
1247
        }
1248
 
1050 daniel-mar 1249
        // --- Initialization of OIDplus
206 daniel-mar 1250
 
1116 daniel-mar 1251
        /**
1252
         * @param bool $html
1253
         * @param bool $keepBaseConfig
1254
         * @return void
1255
         * @throws OIDplusConfigInitializationException
1256
         * @throws OIDplusException
1257
         */
1258
        public static function init(bool $html=true, bool $keepBaseConfig=true) {
236 daniel-mar 1259
                self::$html = $html;
1260
 
263 daniel-mar 1261
                // Reset internal state, so we can re-init verything if required
274 daniel-mar 1262
 
263 daniel-mar 1263
                self::$config = null;
374 daniel-mar 1264
                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 1265
                self::$gui = null;
1266
                self::$authUtils = null;
1267
                self::$mailUtils = null;
1268
                self::$menuUtils = null;
1269
                self::$logger = null;
295 daniel-mar 1270
                self::$dbMainSession = null;
1271
                self::$dbIsolatedSession = null;
263 daniel-mar 1272
                self::$pagePlugins = array();
1273
                self::$authPlugins = array();
289 daniel-mar 1274
                self::$loggerPlugins = array();
263 daniel-mar 1275
                self::$objectTypePlugins = array();
1276
                self::$enabledObjectTypes = array();
1277
                self::$disabledObjectTypes = array();
1278
                self::$dbPlugins = array();
702 daniel-mar 1279
                self::$captchaPlugins = array();
274 daniel-mar 1280
                self::$sqlSlangPlugins = array();
355 daniel-mar 1281
                self::$languagePlugins = array();
449 daniel-mar 1282
                self::$designPlugins = array();
263 daniel-mar 1283
                self::$system_id_cache = null;
1284
                self::$sslAvailableCache = null;
468 daniel-mar 1285
                self::$translationArray = array();
74 daniel-mar 1286
 
263 daniel-mar 1287
                // Continue...
1288
 
294 daniel-mar 1289
                OIDplus::baseConfig(); // this loads the base configuration located in userdata/baseconfig/config.inc.php (once!)
1122 daniel-mar 1290
                // You can do changes to the configuration afterwards using OIDplus::baseConfig()->...
263 daniel-mar 1291
 
150 daniel-mar 1292
                // Register database types (highest priority)
1293
 
274 daniel-mar 1294
                // SQL slangs
1295
 
1050 daniel-mar 1296
                self::registerAllPlugins('sqlSlang', OIDplusSqlSlangPlugin::class, array(OIDplus::class,'registerSqlSlangPlugin'));
274 daniel-mar 1297
                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
1298
                        $plugin->init($html);
1299
                }
1300
 
1301
                // Database providers
1302
 
1050 daniel-mar 1303
                self::registerAllPlugins('database', OIDplusDatabasePlugin::class, array(OIDplus::class,'registerDatabasePlugin'));
237 daniel-mar 1304
                foreach (OIDplus::getDatabasePlugins() as $plugin) {
1305
                        $plugin->init($html);
1306
                }
1307
 
42 daniel-mar 1308
                // Do redirect stuff etc.
74 daniel-mar 1309
 
230 daniel-mar 1310
                self::isSslAvailable(); // This function does automatic redirects
61 daniel-mar 1311
 
263 daniel-mar 1312
                // Construct the configuration manager
66 daniel-mar 1313
 
263 daniel-mar 1314
                OIDplus::config(); // During the construction, various system settings are prepared if required
66 daniel-mar 1315
 
74 daniel-mar 1316
                // Initialize public / private keys
1317
 
227 daniel-mar 1318
                OIDplus::getPkiStatus(true);
74 daniel-mar 1319
 
237 daniel-mar 1320
                // Register non-DB plugins
74 daniel-mar 1321
 
1050 daniel-mar 1322
                self::registerAllPlugins(array('publicPages', 'raPages', 'adminPages'), OIDplusPagePlugin::class, array(OIDplus::class,'registerPagePlugin'));
1323
                self::registerAllPlugins('auth', OIDplusAuthPlugin::class, array(OIDplus::class,'registerAuthPlugin'));
1324
                self::registerAllPlugins('logger', OIDplusLoggerPlugin::class, array(OIDplus::class,'registerLoggerPlugin'));
825 daniel-mar 1325
                OIDplusLogger::reLogMissing(); // Some previous plugins might have tried to log. Repeat that now.
1050 daniel-mar 1326
                self::registerAllPlugins('objectTypes', OIDplusObjectTypePlugin::class, array(OIDplus::class,'registerObjectTypePlugin'));
1327
                self::registerAllPlugins('language', OIDplusLanguagePlugin::class, array(OIDplus::class,'registerLanguagePlugin'));
1328
                self::registerAllPlugins('design', OIDplusDesignPlugin::class, array(OIDplus::class,'registerDesignPlugin'));
1329
                self::registerAllPlugins('captcha', OIDplusCaptchaPlugin::class, array(OIDplus::class,'registerCaptchaPlugin'));
150 daniel-mar 1330
 
237 daniel-mar 1331
                // Initialize non-DB plugins
224 daniel-mar 1332
 
281 daniel-mar 1333
                foreach (OIDplus::getPagePlugins() as $plugin) {
74 daniel-mar 1334
                        $plugin->init($html);
1335
                }
230 daniel-mar 1336
                foreach (OIDplus::getAuthPlugins() as $plugin) {
1337
                        $plugin->init($html);
1338
                }
289 daniel-mar 1339
                foreach (OIDplus::getLoggerPlugins() as $plugin) {
1340
                        $plugin->init($html);
1341
                }
230 daniel-mar 1342
                foreach (OIDplus::getObjectTypePlugins() as $plugin) {
1343
                        $plugin->init($html);
1344
                }
355 daniel-mar 1345
                foreach (OIDplus::getLanguagePlugins() as $plugin) {
1346
                        $plugin->init($html);
1347
                }
449 daniel-mar 1348
                foreach (OIDplus::getDesignPlugins() as $plugin) {
1349
                        $plugin->init($html);
1350
                }
778 daniel-mar 1351
                foreach (OIDplus::getCaptchaPlugins() as $plugin) {
1352
                        $plugin->init($html);
1353
                }
412 daniel-mar 1354
 
778 daniel-mar 1355
                if (PHP_SAPI != 'cli') {
1356
 
1357
                        // Prepare some security related response headers (default values)
1358
 
1359
                        $content_language =
1360
                                strtolower(substr(OIDplus::getCurrentLang(),0,2)) . '-' .
1361
                                strtoupper(substr(OIDplus::getCurrentLang(),2,2)); // e.g. 'en-US'
1362
 
1363
                        $http_headers = array(
1364
                                "X-Content-Type-Options" => "nosniff",
1365
                                "X-XSS-Protection" => "1; mode=block",
1366
                                "X-Frame-Options" => "SAMEORIGIN",
1367
                                "Referrer-Policy" => array(
1368
                                        "no-referrer-when-downgrade"
1369
                                ),
1370
                                "Cache-Control" => array(
1371
                                        "no-cache",
1372
                                        "no-store",
1373
                                        "must-revalidate"
1374
                                ),
1375
                                "Pragma" => "no-cache",
1376
                                "Content-Language" => $content_language,
1377
                                "Expires" => "0",
1378
                                "Content-Security-Policy" => array(
1001 daniel-mar 1379
                                        // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
1380
 
1381
                                        // --- Fetch directives ---
1382
                                        "child-src" => array(
1383
                                                "'self'",
1384
                                                "blob:"
1385
                                        ),
1386
                                        "connect-src" => array(
1387
                                                "'self'",
1388
                                                "blob:"
1389
                                        ),
778 daniel-mar 1390
                                        "default-src" => array(
1391
                                                "'self'",
1392
                                                "blob:",
1393
                                                "https://cdnjs.cloudflare.com/"
1394
                                        ),
1001 daniel-mar 1395
                                        "font-src" => array(
778 daniel-mar 1396
                                                "'self'",
1001 daniel-mar 1397
                                                "blob:"
778 daniel-mar 1398
                                        ),
1001 daniel-mar 1399
                                        "frame-src" => array(
1400
                                                "'self'",
1401
                                                "blob:"
1402
                                        ),
778 daniel-mar 1403
                                        "img-src" => array(
1001 daniel-mar 1404
                                                "blob:",
778 daniel-mar 1405
                                                "data:",
1406
                                                "http:",
1407
                                                "https:"
1408
                                        ),
1001 daniel-mar 1409
                                        "manifest-src" => array(
1410
                                                "'self'",
1411
                                                "blob:"
1412
                                        ),
1413
                                        "media-src" => array(
1414
                                                "'self'",
1415
                                                "blob:"
1416
                                        ),
1417
                                        "object-src" => array(
1418
                                                "'none'"
1419
                                        ),
1420
                                        "prefetch-src" => array(
1421
                                                "'self'",
1422
                                                "blob:"
1423
                                        ),
778 daniel-mar 1424
                                        "script-src" => array(
1425
                                                "'self'",
1426
                                                "'unsafe-inline'",
1427
                                                "'unsafe-eval'",
1428
                                                "blob:",
1429
                                                "https://cdnjs.cloudflare.com/",
1430
                                                "https://polyfill.io/"
1431
                                        ),
1001 daniel-mar 1432
                                        // script-src-elem not used
1433
                                        // script-src-attr not used
1434
                                        "style-src" => array(
1435
                                                "'self'",
1436
                                                "'unsafe-inline'",
1437
                                                "https://cdnjs.cloudflare.com/"
1438
                                        ),
1439
                                        // style-src-elem not used
1440
                                        // style-src-attr not used
1441
                                        "worker-src" => array(
1442
                                                "'self'",
1443
                                                "blob:"
1444
                                        ),
1445
 
1446
                                        // --- Navigation directives ---
778 daniel-mar 1447
                                        "frame-ancestors" => array(
1112 daniel-mar 1448
                                                "'none'"
778 daniel-mar 1449
                                        ),
1450
                                )
1451
                        );
1452
 
780 daniel-mar 1453
                        // Give plugins the opportunity to manipulate/extend the headers
778 daniel-mar 1454
 
1455
                        foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
1456
                                $plugin->httpHeaderCheck($http_headers);
1457
                        }
1015 daniel-mar 1458
                        //foreach (OIDplus::getDatabasePlugins() as $plugin) {
1459
                        if ($plugin = OIDplus::getActiveDatabasePlugin()) {
778 daniel-mar 1460
                                $plugin->httpHeaderCheck($http_headers);
1461
                        }
1462
                        foreach (OIDplus::getPagePlugins() as $plugin) {
1463
                                $plugin->httpHeaderCheck($http_headers);
1464
                        }
1465
                        foreach (OIDplus::getAuthPlugins() as $plugin) {
1466
                                $plugin->httpHeaderCheck($http_headers);
1467
                        }
1468
                        foreach (OIDplus::getLoggerPlugins() as $plugin) {
1469
                                $plugin->httpHeaderCheck($http_headers);
1470
                        }
1471
                        foreach (OIDplus::getObjectTypePlugins() as $plugin) {
1472
                                $plugin->httpHeaderCheck($http_headers);
1473
                        }
1474
                        foreach (OIDplus::getLanguagePlugins() as $plugin) {
1475
                                $plugin->httpHeaderCheck($http_headers);
1476
                        }
1477
                        foreach (OIDplus::getDesignPlugins() as $plugin) {
1478
                                $plugin->httpHeaderCheck($http_headers);
1479
                        }
1015 daniel-mar 1480
                        //foreach (OIDplus::getCaptchaPlugins() as $plugin) {
1481
                        if ($plugin = OIDplus::getActiveCaptchaPlugin()) {
778 daniel-mar 1482
                                $plugin->httpHeaderCheck($http_headers);
1483
                        }
1484
 
1485
                        // Prepare to send the headers to the client
1486
                        // The headers are sent automatically when the first output comes or the script ends
1487
 
1488
                        foreach ($http_headers as $name => $val) {
1489
 
1490
                                // Plugins can remove standard OIDplus headers by setting the value to null.
1116 daniel-mar 1491
                                if (is_null($val)) continue;
778 daniel-mar 1492
 
1493
                                // Some headers can be written as arrays to make it easier for plugin authors
1494
                                // to manipulate/extend the contents.
1495
                                if (is_array($val)) {
1496
                                        if ((strtolower($name) == 'cache-control') ||
1122 daniel-mar 1497
                                                (strtolower($name) == 'referrer-policy'))
778 daniel-mar 1498
                                        {
1499
                                                if (count($val) == 0) continue;
1500
                                                $val = implode(', ', $val);
1501
                                        } else if (strtolower($name) == 'content-security-policy') {
1502
                                                if (count($val) == 0) continue;
780 daniel-mar 1503
                                                foreach ($val as $tmp1 => &$tmp2) {
1504
                                                        $tmp2 = array_unique($tmp2);
1505
                                                        $tmp2 = $tmp1.' '.implode(' ', $tmp2);
1506
                                                }
778 daniel-mar 1507
                                                $val = implode('; ', $val);
1508
                                        } else {
779 daniel-mar 1509
                                                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 1510
                                        }
1511
                                }
1512
 
1513
                                if (is_string($val)) {
1514
                                        header("$name: $val");
1515
                                }
1516
                        }
1517
 
1518
                } // endif (PHP_SAPI != 'cli')
1519
 
412 daniel-mar 1520
                // Initialize other stuff (i.e. things which require the logger!)
1521
 
1522
                OIDplus::recognizeSystemUrl(); // Make sure "last_known_system_url" is set
1523
                OIDplus::recognizeVersion(); // Make sure "last_known_version" is set and a log entry is created
2 daniel-mar 1524
        }
42 daniel-mar 1525
 
1050 daniel-mar 1526
        // --- System URL, System ID, PKI, and other functions
227 daniel-mar 1527
 
1116 daniel-mar 1528
        /**
1529
         * @return void
1530
         */
412 daniel-mar 1531
        private static function recognizeSystemUrl() {
1532
                try {
1072 daniel-mar 1533
                        $url = OIDplus::webpath(null,self::PATH_ABSOLUTE_CANONICAL);
412 daniel-mar 1534
                        OIDplus::config()->setValue('last_known_system_url', $url);
1050 daniel-mar 1535
                } catch (\Exception $e) {
412 daniel-mar 1536
                }
1537
        }
497 daniel-mar 1538
 
1116 daniel-mar 1539
        /**
1540
         * @return false|int
1541
         */
496 daniel-mar 1542
        private static function getExecutingScriptPathDepth() {
1543
                if (PHP_SAPI == 'cli') {
1544
                        global $argv;
1545
                        $test_dir = dirname(realpath($argv[0]));
1546
                } else {
1547
                        if (!isset($_SERVER["SCRIPT_FILENAME"])) return false;
1548
                        $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
1549
                }
1550
                $test_dir = str_replace('\\', '/', $test_dir);
1551
                $steps_up = 0;
928 daniel-mar 1552
                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 1553
                        $test_dir = dirname($test_dir);
1554
                        $steps_up++;
1555
                        if ($steps_up == 1000) return false; // to make sure there will never be an infinite loop
1556
                }
1557
                return $steps_up;
1558
        }
632 daniel-mar 1559
 
1116 daniel-mar 1560
        /**
1561
         * @return bool
1562
         */
1563
        public static function isSSL(): bool {
580 daniel-mar 1564
                return isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
1565
        }
412 daniel-mar 1566
 
806 daniel-mar 1567
        /**
1568
         * Returns the URL of the system.
1569
         * @param int $mode If true or OIDplus::PATH_RELATIVE, the returning path is relative to the currently executed
1570
         *                  PHP script (i.e. index.php , not the plugin PHP script!). False or OIDplus::PATH_ABSOLUTE is
1571
         *                  results in an absolute URL. OIDplus::PATH_ABSOLUTE_CANONICAL is an absolute URL,
1572
         *                  but a canonical path (set by base config setting CANONICAL_SYSTEM_URL) is preferred.
1573
         * @return string|false The URL, with guaranteed trailing path delimiter for directories
1116 daniel-mar 1574
         * @throws OIDplusException
806 daniel-mar 1575
         */
1116 daniel-mar 1576
        private static function getSystemUrl(int $mode) {
806 daniel-mar 1577
                if ($mode === self::PATH_RELATIVE) {
778 daniel-mar 1578
                        $steps_up = self::getExecutingScriptPathDepth();
1579
                        if ($steps_up === false) {
1580
                                return false;
1581
                        } else {
1582
                                return str_repeat('../', $steps_up);
1583
                        }
1584
                } else {
806 daniel-mar 1585
                        if ($mode === self::PATH_ABSOLUTE_CANONICAL) {
1586
                                $tmp = OIDplus::baseConfig()->getValue('CANONICAL_SYSTEM_URL', '');
1587
                                if ($tmp) {
1588
                                        return rtrim($tmp,'/').'/';
1589
                                }
326 daniel-mar 1590
                        }
778 daniel-mar 1591
 
495 daniel-mar 1592
                        if (PHP_SAPI == 'cli') {
494 daniel-mar 1593
                                try {
1594
                                        return OIDplus::config()->getValue('last_known_system_url', false);
1050 daniel-mar 1595
                                } catch (\Exception $e) {
494 daniel-mar 1596
                                        return false;
1597
                                }
778 daniel-mar 1598
                        } else {
1599
                                // First, try to find out how many levels we need to go up
1600
                                $steps_up = self::getExecutingScriptPathDepth();
326 daniel-mar 1601
 
778 daniel-mar 1602
                                // Then go up these amount of levels, based on SCRIPT_NAME/argv[0]
1603
                                $res = dirname($_SERVER['SCRIPT_NAME'].'index.php'); // This fake 'index.php' ensures that SCRIPT_NAME does not end with '/', which would make dirname() fail
1604
                                for ($i=0; $i<$steps_up; $i++) {
1605
                                        $res = dirname($res);
1606
                                }
1607
                                $res = str_replace('\\', '/', $res);
1608
                                if ($res == '/') $res = '';
227 daniel-mar 1609
 
778 daniel-mar 1610
                                // Add protocol and hostname
580 daniel-mar 1611
                                $is_ssl = self::isSSL();
495 daniel-mar 1612
                                $protocol = $is_ssl ? 'https' : 'http'; // do not translate
1613
                                $host = $_SERVER['HTTP_HOST']; // includes port if it is not 80/443
778 daniel-mar 1614
 
1615
                                return $protocol.'://'.$host.$res.'/';
495 daniel-mar 1616
                        }
227 daniel-mar 1617
                }
1618
        }
1619
 
1116 daniel-mar 1620
        /**
1621
         * @param $pubKey
1622
         * @return false|string
1623
         */
1073 daniel-mar 1624
        private static function pubKeyToRaw($pubKey) {
827 daniel-mar 1625
                $m = array();
1073 daniel-mar 1626
                if (preg_match('@BEGIN PUBLIC KEY\\-+([^\\-]+)\\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
1627
                        return base64_decode($m[1], false);
827 daniel-mar 1628
                }
1629
                return false;
1630
        }
1631
 
1116 daniel-mar 1632
        /**
1633
         * @param $pubKey
1634
         * @return false|int
1635
         */
1073 daniel-mar 1636
        private static function getSystemIdFromPubKey($pubKey) {
1637
                $rawData = self::pubKeyToRaw($pubKey);
1638
                if ($rawData === false) return false;
1639
                return smallhash($rawData);
1640
        }
1641
 
1116 daniel-mar 1642
        /**
1643
         * @param $pubKey
1644
         * @return false|string
1645
         */
1073 daniel-mar 1646
        private static function getSystemGuidFromPubKey($pubKey) {
1647
                $rawData = self::pubKeyToRaw($pubKey);
1648
                if ($rawData === false) return false;
1649
                $normalizedBase64 = base64_encode($rawData);
1650
                return gen_uuid_sha1_namebased(self::UUID_NAMEBASED_NS_Base64PubKey, $normalizedBase64);
1651
        }
1652
 
227 daniel-mar 1653
        private static $system_id_cache = null;
1116 daniel-mar 1654
 
1655
        /**
1656
         * @param bool $oid
1657
         * @return false|string
1658
         * @throws OIDplusException
1659
         */
1660
        public static function getSystemId(bool $oid=false) {
227 daniel-mar 1661
                if (!is_null(self::$system_id_cache)) {
1662
                        $out = self::$system_id_cache;
1663
                } else {
1664
                        $out = false;
1665
 
1666
                        if (self::getPkiStatus(true)) {
830 daniel-mar 1667
                                $pubKey = OIDplus::getSystemPublicKey();
827 daniel-mar 1668
                                $out = self::getSystemIdFromPubKey($pubKey);
227 daniel-mar 1669
                        }
1670
                        self::$system_id_cache = $out;
1671
                }
350 daniel-mar 1672
                if (!$out) return false;
291 daniel-mar 1673
                return ($oid ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
227 daniel-mar 1674
        }
1675
 
1073 daniel-mar 1676
        private static $system_guid_cache = null;
1116 daniel-mar 1677
 
1678
        /**
1679
         * @return false|string
1680
         * @throws OIDplusException
1681
         */
1073 daniel-mar 1682
        public static function getSystemGuid() {
1683
                if (!is_null(self::$system_guid_cache)) {
1684
                        $out = self::$system_guid_cache;
1685
                } else {
1686
                        $out = false;
1687
 
1688
                        if (self::getPkiStatus(true)) {
1689
                                $pubKey = OIDplus::getSystemPublicKey();
1690
                                $out = self::getSystemGuidFromPubKey($pubKey);
1691
                        }
1692
                        self::$system_guid_cache = $out;
1693
                }
1694
                if (!$out) return false;
1695
                return $out;
1696
        }
1697
 
1116 daniel-mar 1698
        /**
1699
         * @return array|string
1700
         */
825 daniel-mar 1701
        public static function getOpenSslCnf() {
1702
                // The following functions need a config file, otherway they don't work
1703
                // - openssl_csr_new
1704
                // - openssl_csr_sign
1705
                // - openssl_pkey_export
1706
                // - openssl_pkey_export_to_file
1707
                // - openssl_pkey_new
1708
                $tmp = @getenv('OPENSSL_CONF');
1709
                if ($tmp && file_exists($tmp)) return $tmp;
1710
 
1711
                // OpenSSL in XAMPP does not work OOBE, since the OPENSSL_CONF is
1712
                // C:/xampp/apache/bin/openssl.cnf and not C:/xampp/apache/conf/openssl.cnf
1713
                // Bug reports are more than 10 years old and nobody cares...
1714
                // Use our own config file
1715
                return __DIR__.'/../../vendor/phpseclib/phpseclib/phpseclib/openssl.cnf';
1716
        }
1717
 
1116 daniel-mar 1718
        /**
1719
         * @return string
1720
         */
1721
        private static function getPrivKeyPassphraseFilename(): string {
830 daniel-mar 1722
                return OIDplus::localpath() . 'userdata/privkey_secret.php';
1723
        }
227 daniel-mar 1724
 
1116 daniel-mar 1725
        /**
1726
         * @return void
1727
         */
830 daniel-mar 1728
        private static function tryCreatePrivKeyPassphrase() {
1729
                $file = self::getPrivKeyPassphraseFilename();
827 daniel-mar 1730
 
830 daniel-mar 1731
                $passphrase = generateRandomString(64);
1732
                $cont = "<?php\n";
1733
                $cont .= "// ATTENTION! This file was automatically generated by OIDplus to encrypt the private key\n";
1734
                $cont .= "// that is located in your database configuration table. DO NOT ALTER OR DELETE THIS FILE,\n";
1735
                $cont .= "// otherwise you will lose your OIDplus System-ID and all services connected with it!\n";
831 daniel-mar 1736
                $cont .= "// If multiple systems access the same database, then this file must be synchronous\n";
1737
                $cont .= "// between all systems, otherwise you will lose your system ID, too!\n";
830 daniel-mar 1738
                $cont .= "\$passphrase = '$passphrase';\n";
1739
                $cont .= "// End of file\n";
1740
 
1741
                @file_put_contents($file, $cont);
1742
        }
1743
 
1116 daniel-mar 1744
        /**
1745
         * @return string|false
1746
         */
830 daniel-mar 1747
        private static function getPrivKeyPassphrase() {
1748
                $file = self::getPrivKeyPassphraseFilename();
1749
                if (!file_exists($file)) return false;
1750
                $cont = file_get_contents($file);
1751
                $m = array();
1752
                if (!preg_match("@'(.+)'@isU", $cont, $m)) return false;
1753
                return $m[1];
1754
        }
1755
 
1116 daniel-mar 1756
        /**
1757
         * @return string|false
1758
         * @throws OIDplusException
1759
         */
830 daniel-mar 1760
        public static function getSystemPrivateKey() {
227 daniel-mar 1761
                $privKey = OIDplus::config()->getValue('oidplus_private_key');
830 daniel-mar 1762
                if ($privKey == '') return false;
1763
 
1764
                $passphrase = self::getPrivKeyPassphrase();
1765
                if ($passphrase !== false) {
1766
                        $privKey = decrypt_private_key($privKey, $passphrase);
1767
                }
1768
 
1769
                if (is_privatekey_encrypted($privKey)) {
1770
                        // This can happen if the key file has vanished
1771
                        return false;
1772
                }
1773
 
1774
                return $privKey;
1775
        }
1776
 
1116 daniel-mar 1777
        /**
1778
         * @return string|false
1779
         * @throws OIDplusException
1780
         */
830 daniel-mar 1781
        public static function getSystemPublicKey() {
227 daniel-mar 1782
                $pubKey = OIDplus::config()->getValue('oidplus_public_key');
830 daniel-mar 1783
                if ($pubKey == '') return false;
1784
                return $pubKey;
1785
        }
227 daniel-mar 1786
 
1116 daniel-mar 1787
        /**
1788
         * @param bool $try_generate
1789
         * @return bool
1790
         * @throws OIDplusException
1791
         */
1792
        public static function getPkiStatus(bool $try_generate=false): bool {
830 daniel-mar 1793
                if (!function_exists('openssl_pkey_new')) return false;
227 daniel-mar 1794
 
830 daniel-mar 1795
                if ($try_generate) {
1796
                        // For debug purposes: Invalidate current key once:
1797
                        //OIDplus::config()->setValue('oidplus_private_key', '');
256 daniel-mar 1798
 
830 daniel-mar 1799
                        $privKey = OIDplus::getSystemPrivateKey();
1800
                        $pubKey = OIDplus::getSystemPublicKey();
1801
                        if (!verify_private_public_key($privKey, $pubKey)) {
1802
                                if ($pubKey) {
1803
                                        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.");
1804
                                }
227 daniel-mar 1805
 
830 daniel-mar 1806
                                $pkey_config = array(
1116 daniel-mar 1807
                                        "digest_alg" => "sha512",
1808
                                        "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
1809
                                        "private_key_type" => OPENSSL_KEYTYPE_RSA,
1810
                                        "config" => OIDplus::getOpenSslCnf()
830 daniel-mar 1811
                                );
227 daniel-mar 1812
 
830 daniel-mar 1813
                                // Create the private and public key
1814
                                $res = openssl_pkey_new($pkey_config);
1815
                                if ($res === false) return false;
239 daniel-mar 1816
 
830 daniel-mar 1817
                                // Extract the private key from $res to $privKey
1818
                                if (openssl_pkey_export($res, $privKey, null, $pkey_config) === false) return false;
227 daniel-mar 1819
 
830 daniel-mar 1820
                                // Extract the public key from $res to $pubKey
1821
                                $tmp = openssl_pkey_get_details($res);
1822
                                if ($tmp === false) return false;
1823
                                $pubKey = $tmp["key"];
1824
 
1825
                                // encrypt new keys using a passphrase stored in a secret file
1826
                                self::tryCreatePrivKeyPassphrase(); // *try* (re)generate this file
1827
                                $passphrase = self::getPrivKeyPassphrase();
1828
                                if ($passphrase !== false) {
1829
                                        $privKey = encrypt_private_key($privKey, $passphrase);
1830
                                }
1831
 
1832
                                // Calculate the system ID from the public key
1833
                                $system_id = self::getSystemIdFromPubKey($pubKey);
1834
                                if ($system_id !== false) {
1835
                                        // Save the key pair to database
1836
                                        OIDplus::config()->setValue('oidplus_private_key', $privKey);
1837
                                        OIDplus::config()->setValue('oidplus_public_key', $pubKey);
1838
 
1839
                                        // Log the new system ID
1840
                                        OIDplus::logger()->log("[INFO]A!", "A new private/public key-pair for your system had been generated. Your SystemID is now $system_id");
1841
                                }
1842
                        } else {
1843
                                $passphrase = self::getPrivKeyPassphrase();
831 daniel-mar 1844
                                $rawPrivKey = OIDplus::config()->getValue('oidplus_private_key');
1845
                                if (($passphrase === false) || !is_privatekey_encrypted($rawPrivKey)) {
830 daniel-mar 1846
                                        // Upgrade to new encrypted keys
1847
                                        self::tryCreatePrivKeyPassphrase(); // *try* generate this file
1848
                                        $passphrase = self::getPrivKeyPassphrase();
1849
                                        if ($passphrase !== false) {
1850
                                                $privKey = encrypt_private_key($privKey, $passphrase);
1851
                                                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());
1852
                                                OIDplus::config()->setValue('oidplus_private_key', $privKey);
1853
                                        }
1854
                                }
227 daniel-mar 1855
                        }
1856
                }
1857
 
830 daniel-mar 1858
                $privKey = OIDplus::getSystemPrivateKey();
1859
                $pubKey = OIDplus::getSystemPublicKey();
227 daniel-mar 1860
                return verify_private_public_key($privKey, $pubKey);
1861
        }
1862
 
1116 daniel-mar 1863
        /**
1864
         * @return string|void
1865
         */
170 daniel-mar 1866
        public static function getInstallType() {
486 daniel-mar 1867
                $counter = 0;
1868
 
661 daniel-mar 1869
                if ($new_version_file_exists = file_exists(OIDplus::localpath().'.version.php')) {
486 daniel-mar 1870
                        $counter++;
591 daniel-mar 1871
                }
661 daniel-mar 1872
                if ($old_version_file_exists = file_exists(OIDplus::localpath().'oidplus_version.txt')) {
1873
                        $counter++;
1874
                }
1875
                $version_file_exists = $old_version_file_exists | $new_version_file_exists;
681 daniel-mar 1876
                if ($svn_dir_exists = (is_dir(OIDplus::localpath().'.svn') ||
1122 daniel-mar 1877
                        is_dir(OIDplus::localpath().'../.svn'))) { // in case we checked out the root instead of the "trunk"
486 daniel-mar 1878
                        $counter++;
591 daniel-mar 1879
                }
681 daniel-mar 1880
                // if ($git_dir_exists = is_dir(OIDplus::localpath().'.git')) {
698 daniel-mar 1881
                if ($git_dir_exists = (OIDplus::findGitFolder() !== false)) {
486 daniel-mar 1882
                        $counter++;
591 daniel-mar 1883
                }
486 daniel-mar 1884
 
1885
                if ($counter === 0) {
360 daniel-mar 1886
                        return 'unknown'; // do not translate
170 daniel-mar 1887
                }
591 daniel-mar 1888
                else if ($counter > 1) {
360 daniel-mar 1889
                        return 'ambigous'; // do not translate
170 daniel-mar 1890
                }
591 daniel-mar 1891
                else if ($svn_dir_exists) {
360 daniel-mar 1892
                        return 'svn-wc'; // do not translate
170 daniel-mar 1893
                }
591 daniel-mar 1894
                else if ($git_dir_exists) {
486 daniel-mar 1895
                        return 'git-wc'; // do not translate
1896
                }
591 daniel-mar 1897
                else if ($version_file_exists) {
360 daniel-mar 1898
                        return 'svn-snapshot'; // do not translate
170 daniel-mar 1899
                }
1900
        }
1901
 
1116 daniel-mar 1902
        /**
1903
         * @return void
1904
         */
412 daniel-mar 1905
        private static function recognizeVersion() {
1906
                try {
1907
                        $ver_prev = OIDplus::config()->getValue("last_known_version");
1908
                        $ver_now = OIDplus::getVersion();
1909
                        if (($ver_now != '') && ($ver_prev != '') && ($ver_now != $ver_prev)) {
455 daniel-mar 1910
                                // TODO: Problem: When the system was updated using SVN, then the IP address of the next random visitor of the website is logged!
1072 daniel-mar 1911
                                OIDplus::logger()->log("[INFO]A!", "Detected system version change from '$ver_prev' to '$ver_now'");
856 daniel-mar 1912
 
1913
                                // Just to be sure, recanonize objects (we don't do it at every page visit due to performance reasons)
857 daniel-mar 1914
                                self::recanonizeObjects();
412 daniel-mar 1915
                        }
1916
                        OIDplus::config()->setValue("last_known_version", $ver_now);
1050 daniel-mar 1917
                } catch (\Exception $e) {
412 daniel-mar 1918
                }
1919
        }
1920
 
1116 daniel-mar 1921
        /**
1922
         * @return false|string|null
1923
         */
111 daniel-mar 1924
        public static function getVersion() {
412 daniel-mar 1925
                static $cachedVersion = null;
1926
                if (!is_null($cachedVersion)) {
1927
                        return $cachedVersion;
1928
                }
1929
 
486 daniel-mar 1930
                $installType = OIDplus::getInstallType();
1931
 
1932
                if ($installType === 'svn-wc') {
496 daniel-mar 1933
                        $ver = get_svn_revision(OIDplus::localpath());
486 daniel-mar 1934
                        if ($ver)
1935
                                return ($cachedVersion = 'svn-'.$ver);
558 daniel-mar 1936
                        $ver = get_svn_revision(OIDplus::localpath().'../'); // in case we checked out the root instead of the "trunk"
1937
                        if ($ver)
1938
                                return ($cachedVersion = 'svn-'.$ver);
111 daniel-mar 1939
                }
162 daniel-mar 1940
 
486 daniel-mar 1941
                if ($installType === 'git-wc') {
1116 daniel-mar 1942
                        $ver = OIDplus::getGitsvnRevision();
486 daniel-mar 1943
                        if ($ver)
1944
                                return ($cachedVersion = 'svn-'.$ver);
162 daniel-mar 1945
                }
1946
 
486 daniel-mar 1947
                if ($installType === 'svn-snapshot') {
661 daniel-mar 1948
                        $cont = '';
1949
                        if (file_exists($filename = OIDplus::localpath().'oidplus_version.txt'))
1950
                                $cont = file_get_contents($filename);
1951
                        if (file_exists($filename = OIDplus::localpath().'.version.php'))
1952
                                $cont = file_get_contents($filename);
386 daniel-mar 1953
                        $m = array();
360 daniel-mar 1954
                        if (preg_match('@Revision (\d+)@', $cont, $m)) // do not translate
412 daniel-mar 1955
                                return ($cachedVersion = 'svn-'.$m[1]); // do not translate
162 daniel-mar 1956
                }
1957
 
486 daniel-mar 1958
                return ($cachedVersion = false); // version ambigous or unknown
111 daniel-mar 1959
        }
1960
 
974 daniel-mar 1961
        const ENFORCE_SSL_NO   = 0;
1962
        const ENFORCE_SSL_YES  = 1;
1963
        const ENFORCE_SSL_AUTO = 2;
1117 daniel-mar 1964
 
1965
        /**
1966
         * @var bool|null
1967
         */
230 daniel-mar 1968
        private static $sslAvailableCache = null;
1116 daniel-mar 1969
 
1970
        /**
1117 daniel-mar 1971
         * @return bool
1116 daniel-mar 1972
         * @throws OIDplusException, OIDplusConfigInitializationException
1973
         */
1117 daniel-mar 1974
        public static function isSslAvailable(): bool {
230 daniel-mar 1975
                if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
256 daniel-mar 1976
 
495 daniel-mar 1977
                if (PHP_SAPI == 'cli') {
230 daniel-mar 1978
                        self::$sslAvailableCache = false;
1979
                        return false;
1980
                }
1981
 
49 daniel-mar 1982
                $timeout = 2;
580 daniel-mar 1983
                $already_ssl = self::isSSL();
80 daniel-mar 1984
                $ssl_port = 443;
1059 daniel-mar 1985
                $host_with_port = $_SERVER['HTTP_HOST'];
1986
                $host_no_port = explode(':',$host_with_port)[0];
1117 daniel-mar 1987
                $host_ssl = $host_no_port . ($ssl_port != 443 ? ':'.$ssl_port : '');
42 daniel-mar 1988
 
974 daniel-mar 1989
                if ($already_ssl) {
1059 daniel-mar 1990
                        OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, true/*allowJS*/, null/*samesite*/, true/*forceInsecure*/);
974 daniel-mar 1991
                        self::$sslAvailableCache = true;
1992
                        return true;
1993
                } else {
1994
                        if (isset($_COOKIE['SSL_CHECK']) && ($_COOKIE['SSL_CHECK'] == '1')) {
1995
                                // The cookie "SSL_CHECK" is set once a website was loaded with HTTPS.
1996
                                // It forces subsequent HTTP calls to redirect to HTTPS (like HSTS).
1997
                                // The reason is the following problem:
1998
                                // If you open the page with HTTPS first, then the CSRF token cookies will get the "secure" flag
1999
                                // If you open the page then with HTTP, the HTTP cannot access the secure CSRF cookies,
2000
                                // Chrome will then block "Set-Cookie" since the HTTP cookie would overwrite the HTTPS cookie.
1059 daniel-mar 2001
                                // So we MUST redirect, even if the Mode is ENFORCE_SSL_NO.
974 daniel-mar 2002
                                // Note: SSL_CHECK is NOT a replacement for HSTS! You should use HSTS,
1059 daniel-mar 2003
                                //       because on there your browser ensures that HTTPS is called, before the server
2004
                                //       is even contacted (and therefore, no HTTP connection can be hacked).
974 daniel-mar 2005
                                $mode = OIDplus::ENFORCE_SSL_YES;
2006
                        } else {
2007
                                $mode = OIDplus::baseConfig()->getValue('ENFORCE_SSL', OIDplus::ENFORCE_SSL_AUTO);
2008
                        }
261 daniel-mar 2009
 
974 daniel-mar 2010
                        if ($mode == OIDplus::ENFORCE_SSL_NO) {
2011
                                // No SSL available
2012
                                self::$sslAvailableCache = false;
2013
                                return false;
2014
                        } else if ($mode == OIDplus::ENFORCE_SSL_YES) {
2015
                                // Force SSL
1059 daniel-mar 2016
                                $location = 'https://' . $host_ssl . $_SERVER['REQUEST_URI'];
80 daniel-mar 2017
                                header('Location:'.$location);
360 daniel-mar 2018
                                die(_L('Redirecting to HTTPS...'));
974 daniel-mar 2019
                        } else if ($mode == OIDplus::ENFORCE_SSL_AUTO) {
2020
                                // Automatic SSL detection
80 daniel-mar 2021
                                if (isset($_COOKIE['SSL_CHECK'])) {
2022
                                        // We already had the HTTPS detection done before.
974 daniel-mar 2023
                                        if ($_COOKIE['SSL_CHECK'] == '1') {
80 daniel-mar 2024
                                                // HTTPS was detected before, but we are HTTP. Redirect now
1059 daniel-mar 2025
                                                $location = 'https://' . $host_ssl . $_SERVER['REQUEST_URI'];
80 daniel-mar 2026
                                                header('Location:'.$location);
360 daniel-mar 2027
                                                die(_L('Redirecting to HTTPS...'));
80 daniel-mar 2028
                                        } else {
2029
                                                // No HTTPS available. Do nothing.
230 daniel-mar 2030
                                                self::$sslAvailableCache = false;
80 daniel-mar 2031
                                                return false;
2032
                                        }
49 daniel-mar 2033
                                } else {
80 daniel-mar 2034
                                        // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
386 daniel-mar 2035
                                        $errno = -1;
2036
                                        $errstr = '';
1059 daniel-mar 2037
                                        if (@fsockopen($host_no_port, $ssl_port, $errno, $errstr, $timeout)) {
80 daniel-mar 2038
                                                // HTTPS detected. Redirect now, and remember that we had detected HTTPS
1059 daniel-mar 2039
                                                OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, true/*allowJS*/, null/*samesite*/, true/*forceInsecure*/);
2040
                                                $location = 'https://' . $host_ssl . $_SERVER['REQUEST_URI'];
80 daniel-mar 2041
                                                header('Location:'.$location);
360 daniel-mar 2042
                                                die(_L('Redirecting to HTTPS...'));
80 daniel-mar 2043
                                        } else {
2044
                                                // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
1059 daniel-mar 2045
                                                OIDplus::cookieUtils()->setcookie('SSL_CHECK', '0', 0, true/*allowJS*/, null/*samesite*/, true/*forceInsecure*/);
230 daniel-mar 2046
                                                self::$sslAvailableCache = false;
80 daniel-mar 2047
                                                return false;
2048
                                        }
49 daniel-mar 2049
                                }
1117 daniel-mar 2050
                        } else {
2051
                                assert(false);
2052
                                return false;
42 daniel-mar 2053
                        }
2054
                }
2055
        }
497 daniel-mar 2056
 
496 daniel-mar 2057
        /**
2058
         * Gets a local path pointing to a resource
1116 daniel-mar 2059
         * @param string|null $target Target resource (file or directory must exist), or null to get the OIDplus base directory
2060
         * @param bool $relative If true, the returning path is relative to the currently executed PHP file (not the CLI working directory)
590 daniel-mar 2061
         * @return string|false The local path, with guaranteed trailing path delimiter for directories
496 daniel-mar 2062
         */
1116 daniel-mar 2063
        public static function localpath(string $target=null, bool $relative=false) {
496 daniel-mar 2064
                if (is_null($target)) {
2065
                        $target = __DIR__.'/../../';
2066
                }
241 daniel-mar 2067
 
496 daniel-mar 2068
                if ($relative) {
2069
                        // First, try to find out how many levels we need to go up
2070
                        $steps_up = self::getExecutingScriptPathDepth();
2071
                        if ($steps_up === false) return false;
497 daniel-mar 2072
 
496 daniel-mar 2073
                        // Virtually go back from the executing PHP script to the OIDplus base path
2074
                        $res = str_repeat('../',$steps_up);
497 daniel-mar 2075
 
496 daniel-mar 2076
                        // Then go to the desired location
2077
                        $basedir = realpath(__DIR__.'/../../');
2078
                        $target = realpath($target);
500 daniel-mar 2079
                        if ($target === false) return false;
496 daniel-mar 2080
                        $res .= substr($target, strlen($basedir)+1);
2081
                        $res = rtrim($res,'/'); // avoid '..//' for localpath(null,true)
2082
                } else {
2083
                        $res = realpath($target);
241 daniel-mar 2084
                }
497 daniel-mar 2085
 
801 daniel-mar 2086
                if (is_dir($target)) $res .= '/';
497 daniel-mar 2087
 
1116 daniel-mar 2088
                return str_replace('/', DIRECTORY_SEPARATOR, $res);
241 daniel-mar 2089
        }
355 daniel-mar 2090
 
496 daniel-mar 2091
        /**
2092
         * Gets a URL pointing to a resource
1116 daniel-mar 2093
         * @param string|null $target Target resource (file or directory must exist), or null to get the OIDplus base directory
2094
         * @param int|bool $mode If true or OIDplus::PATH_RELATIVE, the returning path is relative to the currently executed
806 daniel-mar 2095
         *                          PHP script (i.e. index.php , not the plugin PHP script!). False or OIDplus::PATH_ABSOLUTE is
2096
         *                          results in an absolute URL. OIDplus::PATH_ABSOLUTE_CANONICAL is an absolute URL,
2097
         *                          but a canonical path (set by base config setting CANONICAL_SYSTEM_URL) is preferred.
590 daniel-mar 2098
         * @return string|false The URL, with guaranteed trailing path delimiter for directories
1116 daniel-mar 2099
         * @throws OIDplusException
496 daniel-mar 2100
         */
1116 daniel-mar 2101
        public static function webpath(string $target=null, $mode=self::PATH_ABSOLUTE_CANONICAL) {
801 daniel-mar 2102
                // backwards compatibility
2103
                if ($mode === true) $mode = self::PATH_RELATIVE;
2104
                if ($mode === false) $mode = self::PATH_ABSOLUTE;
2105
 
811 daniel-mar 2106
                if ($mode == OIDplus::PATH_RELATIVE_TO_ROOT) {
812 daniel-mar 2107
                        $tmp = OIDplus::webpath($target,OIDplus::PATH_ABSOLUTE);
2108
                        if ($tmp === false) return false;
2109
                        $tmp = parse_url($tmp);
2110
                        if ($tmp === false) return false;
2111
                        if (!isset($tmp['path'])) return false;
2112
                        return $tmp['path'];
811 daniel-mar 2113
                }
2114
 
812 daniel-mar 2115
                if ($mode == OIDplus::PATH_RELATIVE_TO_ROOT_CANONICAL) {
2116
                        $tmp = OIDplus::webpath($target,OIDplus::PATH_ABSOLUTE_CANONICAL);
2117
                        if ($tmp === false) return false;
2118
                        $tmp = parse_url($tmp);
2119
                        if ($tmp === false) return false;
2120
                        if (!isset($tmp['path'])) return false;
2121
                        return $tmp['path'];
2122
                }
2123
 
801 daniel-mar 2124
                $res = self::getSystemUrl($mode); // Note: already contains a trailing path delimiter
778 daniel-mar 2125
                if ($res === false) return false;
497 daniel-mar 2126
 
496 daniel-mar 2127
                if (!is_null($target)) {
2128
                        $basedir = realpath(__DIR__.'/../../');
2129
                        $target = realpath($target);
500 daniel-mar 2130
                        if ($target === false) return false;
496 daniel-mar 2131
                        $tmp = substr($target, strlen($basedir)+1);
500 daniel-mar 2132
                        $res .= str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
497 daniel-mar 2133
                        if (is_dir($target)) $res .= '/';
496 daniel-mar 2134
                }
497 daniel-mar 2135
 
496 daniel-mar 2136
                return $res;
2137
        }
497 daniel-mar 2138
 
1116 daniel-mar 2139
        /**
2140
         * @return false|string
2141
         * @throws OIDplusException
2142
         */
778 daniel-mar 2143
        public static function canonicalURL() {
2144
                // First part: OIDplus system URL (or canonical system URL)
801 daniel-mar 2145
                $sysurl = OIDplus::getSystemUrl(self::PATH_ABSOLUTE_CANONICAL);
778 daniel-mar 2146
 
2147
                // Second part: Directory
2148
                $basedir = realpath(__DIR__.'/../../');
2149
                $target = realpath('.');
2150
                if ($target === false) return false;
2151
                $tmp = substr($target, strlen($basedir)+1);
2152
                $res = str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
780 daniel-mar 2153
                if (is_dir($target) && ($res != '')) $res .= '/';
778 daniel-mar 2154
 
2155
                // Third part: File name
2156
                $tmp = explode('/',$_SERVER['SCRIPT_NAME']);
2157
                $tmp = end($tmp);
2158
 
2159
                // Fourth part: Query string (ordered)
2160
                $tmp2 = getSortedQuery();
2161
                if ($tmp2 != '') $tmp2 = '?'.$tmp2;
2162
 
2163
                return $sysurl.$res.$tmp.$tmp2;
2164
        }
2165
 
639 daniel-mar 2166
        private static $shutdown_functions = array();
1116 daniel-mar 2167
 
2168
        /**
2169
         * @param $func
2170
         * @return void
2171
         */
639 daniel-mar 2172
        public static function register_shutdown_function($func) {
2173
                self::$shutdown_functions[] = $func;
2174
        }
2175
 
1116 daniel-mar 2176
        /**
2177
         * @return void
2178
         */
639 daniel-mar 2179
        public static function invoke_shutdown() {
2180
                foreach (self::$shutdown_functions as $func) {
2181
                        $func();
2182
                }
2183
        }
2184
 
1116 daniel-mar 2185
        /**
2186
         * @return string[]
2187
         * @throws OIDplusException
2188
         */
2189
        public static function getAvailableLangs(): array {
360 daniel-mar 2190
                $langs = array();
2191
                foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
389 daniel-mar 2192
                        $code = $pluginManifest->getLanguageCode();
360 daniel-mar 2193
                        $langs[] = $code;
2194
                }
2195
                return $langs;
2196
        }
2197
 
1116 daniel-mar 2198
        /**
2199
         * @return string
2200
         * @throws OIDplusConfigInitializationException
2201
         * @throws OIDplusException
2202
         */
2203
        public static function getDefaultLang(): string {
1041 daniel-mar 2204
                static $thrownOnce = false; // avoid endless loop inside OIDplusConfigInitializationException
2205
 
1049 daniel-mar 2206
                $lang = self::baseConfig()->getValue('DEFAULT_LANGUAGE', 'enus');
1041 daniel-mar 2207
 
2208
                if (!in_array($lang,self::getAvailableLangs())) {
2209
                        if (!$thrownOnce) {
2210
                                $thrownOnce = true;
1048 daniel-mar 2211
                                throw new OIDplusConfigInitializationException(_L('DEFAULT_LANGUAGE points to an invalid language plugin. (Consider setting to "enus" = "English USA".)'));
1041 daniel-mar 2212
                        } else {
2213
                                return 'enus';
2214
                        }
2215
                }
2216
 
2217
                return $lang;
2218
        }
2219
 
1116 daniel-mar 2220
        /**
2221
         * @return false|string
2222
         * @throws OIDplusConfigInitializationException
2223
         * @throws OIDplusException
2224
         */
355 daniel-mar 2225
        public static function getCurrentLang() {
360 daniel-mar 2226
                if (isset($_GET['lang'])) {
2227
                        $lang = $_GET['lang'];
2228
                } else if (isset($_POST['lang'])) {
2229
                        $lang = $_POST['lang'];
2230
                } else if (isset($_COOKIE['LANGUAGE'])) {
2231
                        $lang = $_COOKIE['LANGUAGE'];
2232
                } else {
1041 daniel-mar 2233
                        $lang = self::getDefaultLang();
360 daniel-mar 2234
                }
1116 daniel-mar 2235
                return substr(preg_replace('@[^a-z]@ismU', '', $lang),0,4); // sanitize
355 daniel-mar 2236
        }
2237
 
1116 daniel-mar 2238
        /**
2239
         * @return void
2240
         * @throws OIDplusException
2241
         */
362 daniel-mar 2242
        public static function handleLangArgument() {
2243
                if (isset($_GET['lang'])) {
2244
                        // The "?lang=" argument is only for NoScript-Browsers/SearchEngines
2245
                        // In case someone who has JavaScript clicks a ?lang= link, they should get
2246
                        // the page in that language, but the cookie must be set, otherwise
2247
                        // the menu and other stuff would be in their cookie-based-language and not the
2248
                        // argument-based-language.
557 daniel-mar 2249
                        OIDplus::cookieUtils()->setcookie('LANGUAGE', $_GET['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
362 daniel-mar 2250
                } else if (isset($_POST['lang'])) {
557 daniel-mar 2251
                        OIDplus::cookieUtils()->setcookie('LANGUAGE', $_POST['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
362 daniel-mar 2252
                }
2253
        }
2254
 
468 daniel-mar 2255
        private static $translationArray = array();
1116 daniel-mar 2256
 
2257
        /**
2258
         * @param $translation_file
2259
         * @return array|mixed
2260
         */
469 daniel-mar 2261
        protected static function getTranslationFileContents($translation_file) {
2262
                // First, try the cache
481 daniel-mar 2263
                $cache_file = __DIR__ . '/../../userdata/cache/translation_'.md5($translation_file).'.ser';
469 daniel-mar 2264
                if (file_exists($cache_file) && (filemtime($cache_file) == filemtime($translation_file))) {
2265
                        $cac = @unserialize(file_get_contents($cache_file));
2266
                        if ($cac) return $cac;
2267
                }
481 daniel-mar 2268
 
469 daniel-mar 2269
                // If not successful, then load the XML file
2270
                $xml = @simplexml_load_string(file_get_contents($translation_file));
2271
                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
2272
                $cac = array();
2273
                foreach ($xml->message as $msg) {
2274
                        $src = trim($msg->source->__toString());
2275
                        $dst = trim($msg->target->__toString());
2276
                        $cac[$src] = $dst;
2277
                }
2278
                @file_put_contents($cache_file,serialize($cac));
2279
                @touch($cache_file,filemtime($translation_file));
2280
                return $cac;
2281
        }
1116 daniel-mar 2282
 
2283
        /**
2284
         * @param string $requested_lang
2285
         * @return array
2286
         * @throws OIDplusException
2287
         */
2288
        public static function getTranslationArray(string $requested_lang='*'): array {
362 daniel-mar 2289
                foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
389 daniel-mar 2290
                        $lang = $pluginManifest->getLanguageCode();
362 daniel-mar 2291
                        if (strpos($lang,'/') !== false) continue; // just to be sure
2292
                        if (strpos($lang,'\\') !== false) continue; // just to be sure
2293
                        if (strpos($lang,'..') !== false) continue; // just to be sure
401 daniel-mar 2294
 
468 daniel-mar 2295
                        if (($requested_lang != '*') && ($lang != $requested_lang)) continue;
401 daniel-mar 2296
 
468 daniel-mar 2297
                        if (!isset(self::$translationArray[$lang])) {
2298
                                self::$translationArray[$lang] = array();
2299
 
2300
                                $wildcard = $pluginManifest->getLanguageMessages();
2301
                                if (strpos($wildcard,'/') !== false) continue; // just to be sure
2302
                                if (strpos($wildcard,'\\') !== false) continue; // just to be sure
2303
                                if (strpos($wildcard,'..') !== false) continue; // just to be sure
2304
 
635 daniel-mar 2305
                                $translation_files = glob(__DIR__.'/../../plugins/'.'*'.'/language/'.$lang.'/'.$wildcard);
468 daniel-mar 2306
                                sort($translation_files);
2307
                                foreach ($translation_files as $translation_file) {
2308
                                        if (!file_exists($translation_file)) continue;
469 daniel-mar 2309
                                        $cac = self::getTranslationFileContents($translation_file);
2310
                                        foreach ($cac as $src => $dst) {
2311
                                                self::$translationArray[$lang][$src] = $dst;
468 daniel-mar 2312
                                        }
401 daniel-mar 2313
                                }
362 daniel-mar 2314
                        }
2315
                }
468 daniel-mar 2316
                return self::$translationArray;
362 daniel-mar 2317
        }
2318
 
1116 daniel-mar 2319
        /**
2320
         * @return mixed
2321
         */
699 daniel-mar 2322
        public static function getEditionInfo() {
2323
                return @parse_ini_file(__DIR__.'/../edition.ini', true)['Edition'];
2324
        }
2325
 
1116 daniel-mar 2326
        /**
2327
         * @return false|string
2328
         */
698 daniel-mar 2329
        public static function findGitFolder() {
2330
                // Git command line saves git information in folder ".git"
2331
                // Plesk git saves git information in folder "../../../git/oidplus/" (or similar)
727 daniel-mar 2332
                $dir = OIDplus::localpath();
698 daniel-mar 2333
                if (is_dir($dir.'/.git')) return $dir.'/.git';
2334
                $i = 0;
2335
                do {
2336
                        if (is_dir($dir.'/git')) {
719 daniel-mar 2337
                                $confs = @glob($dir.'/git/'.'*'.'/config');
2338
                                if ($confs) foreach ($confs as $conf) {
698 daniel-mar 2339
                                        $cont = file_get_contents($conf);
699 daniel-mar 2340
                                        if (isset(OIDplus::getEditionInfo()['gitrepo']) && (OIDplus::getEditionInfo()['gitrepo'] != '') && (strpos($cont, OIDplus::getEditionInfo()['gitrepo']) !== false)) {
698 daniel-mar 2341
                                                return dirname($conf);
2342
                                        }
2343
                                }
2344
                        }
2345
                        $i++;
719 daniel-mar 2346
                } while (($i<100) && ($dir != ($new_dir = @realpath($dir.'/../'))) && ($dir = $new_dir));
698 daniel-mar 2347
                return false;
2348
        }
2349
 
1116 daniel-mar 2350
        /**
2351
         * @return false|string
2352
         */
2353
        public static function getGitsvnRevision() {
698 daniel-mar 2354
                try {
2355
                        // tries command line and binary parsing
699 daniel-mar 2356
                        // requires vendor/danielmarschall/git_utils.inc.php
698 daniel-mar 2357
                        $git_dir = OIDplus::findGitFolder();
2358
                        if ($git_dir === false) return false;
2359
                        $commit_msg = git_get_latest_commit_message($git_dir);
1050 daniel-mar 2360
                } catch (\Exception $e) {
698 daniel-mar 2361
                        return false;
2362
                }
2363
 
2364
                $m = array();
2365
                if (preg_match('%git-svn-id: (.+)@(\\d+) %ismU', $commit_msg, $m)) {
2366
                        return $m[2];
2367
                } else {
2368
                        return false;
2369
                }
2370
        }
2371
 
1116 daniel-mar 2372
        /**
2373
         * @param string $static_node_id
2374
         * @param bool $throw_exception
2375
         * @return string
2376
         */
2377
        public static function prefilterQuery(string $static_node_id, bool $throw_exception): string {
775 daniel-mar 2378
                // Let namespace be case-insensitive
2379
                $ary = explode(':', $static_node_id, 2);
2380
                $ary[0] = strtolower($ary[0]);
2381
                $static_node_id = implode(':', $ary);
2382
 
889 daniel-mar 2383
                // Ask plugins if they want to change the node id
2384
                foreach (OIDplus::getObjectTypePluginsEnabled() as $plugin) {
2385
                        $static_node_id = $plugin->prefilterQuery($static_node_id, $throw_exception);
775 daniel-mar 2386
                }
2387
 
2388
                return $static_node_id;
2389
        }
849 daniel-mar 2390
 
1116 daniel-mar 2391
        /**
2392
         * @return bool
2393
         */
2394
        public static function isCronjob(): bool {
849 daniel-mar 2395
                return explode('.',basename($_SERVER['SCRIPT_NAME']))[0] === 'cron';
2396
        }
856 daniel-mar 2397
 
1116 daniel-mar 2398
        /**
2399
         * Since OIDplus svn-184, entries in the database need to have a canonical ID
2400
         * If the ID is not canonical (e.g. GUIDs missing hyphens), the object cannot be opened in OIDplus
2401
         * This script re-canonizes the object IDs if required.
2402
         * In SVN Rev 856, the canonization for GUID, IPv4 and IPv6 have changed, requiring another
2403
         * re-canonization
2404
         * @return void
2405
         * @throws OIDplusException
2406
         */
857 daniel-mar 2407
        private static function recanonizeObjects() {
856 daniel-mar 2408
                $res = OIDplus::db()->query("select id from ###objects");
2409
                while ($row = $res->fetch_array()) {
2410
                        $ida = $row['id'];
857 daniel-mar 2411
                        $obj = OIDplusObject::parse($ida);
2412
                        if (!$obj) continue;
2413
                        $idb = $obj->nodeId();
856 daniel-mar 2414
                        if (($idb) && ($ida != $idb)) {
2415
                                OIDplus::db()->transaction_begin();
2416
                                OIDplus::db()->query("update ###objects set id = ? where id = ?", array($idb, $ida));
2417
                                OIDplus::db()->query("update ###asn1id set oid = ? where oid = ?", array($idb, $ida));
2418
                                OIDplus::db()->query("update ###iri set oid = ? where oid = ?", array($idb, $ida));
2419
                                OIDplus::db()->query("update ###log_object set id = ? where id = ?", array($idb, $ida));
2420
                                OIDplus::logger()->log("[INFO]A!", "Object name '$ida' has been changed to '$idb' during re-canonization");
2421
                                OIDplus::db()->transaction_commit();
978 daniel-mar 2422
                                OIDplusObject::resetObjectInformationCache();
856 daniel-mar 2423
                        }
2424
                }
2425
        }
2426
 
374 daniel-mar 2427
}