Subversion Repositories oidplus

Rev

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

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