Subversion Repositories oidplus

Rev

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