Subversion Repositories oidplus

Rev

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

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