Subversion Repositories oidplus

Rev

Rev 449 | Rev 453 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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