Subversion Repositories oidplus

Rev

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