Subversion Repositories oidplus

Rev

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