Subversion Repositories oidplus

Rev

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