Subversion Repositories oidplus

Rev

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

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