Subversion Repositories oidplus

Rev

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