Subversion Repositories oidplus

Rev

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