Subversion Repositories oidplus

Rev

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