Subversion Repositories oidplus

Rev

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