Subversion Repositories oidplus

Rev

Rev 1068 | Rev 1073 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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