Subversion Repositories oidplus

Rev

Rev 1049 | Rev 1051 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 1049 Rev 1050
1
<?php
1
<?php
2
 
2
 
3
/*
3
/*
4
 * OIDplus 2.0
4
 * OIDplus 2.0
5
 * Copyright 2019 - 2022 Daniel Marschall, ViaThinkSoft
5
 * Copyright 2019 - 2022 Daniel Marschall, ViaThinkSoft
6
 *
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with 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
9
 * You may obtain a copy of the License at
10
 *
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
17
 * limitations under the License.
18
 */
18
 */
19
 
19
 
20
if (!defined('INSIDE_OIDPLUS')) die();
20
namespace ViaThinkSoft\OIDplus;
21
 
21
 
22
class OIDplus extends OIDplusBaseClass {
22
class OIDplus extends OIDplusBaseClass {
23
        private static /*OIDplusPagePlugin[]*/ $pagePlugins = array();
23
        private static /*OIDplusPagePlugin[]*/ $pagePlugins = array();
24
        private static /*OIDplusAuthPlugin[]*/ $authPlugins = array();
24
        private static /*OIDplusAuthPlugin[]*/ $authPlugins = array();
25
        private static /*OIDplusLoggerPlugin[]*/ $loggerPlugins = array();
25
        private static /*OIDplusLoggerPlugin[]*/ $loggerPlugins = array();
26
        private static /*OIDplusObjectTypePlugin[]*/ $objectTypePlugins = array();
26
        private static /*OIDplusObjectTypePlugin[]*/ $objectTypePlugins = array();
27
        private static /*string[]*/ $enabledObjectTypes = array();
27
        private static /*string[]*/ $enabledObjectTypes = array();
28
        private static /*string[]*/ $disabledObjectTypes = array();
28
        private static /*string[]*/ $disabledObjectTypes = array();
29
        private static /*OIDplusDatabasePlugin[]*/ $dbPlugins = array();
29
        private static /*OIDplusDatabasePlugin[]*/ $dbPlugins = array();
30
        private static /*OIDplusCaptchaPlugin[]*/ $captchaPlugins = array();
30
        private static /*OIDplusCaptchaPlugin[]*/ $captchaPlugins = array();
31
        private static /*OIDplusSqlSlangPlugin[]*/ $sqlSlangPlugins = array();
31
        private static /*OIDplusSqlSlangPlugin[]*/ $sqlSlangPlugins = array();
32
        private static /*OIDplusLanguagePlugin[]*/ $languagePlugins = array();
32
        private static /*OIDplusLanguagePlugin[]*/ $languagePlugins = array();
33
        private static /*OIDplusDesignPlugin[]*/ $designPlugins = array();
33
        private static /*OIDplusDesignPlugin[]*/ $designPlugins = array();
34
 
34
 
35
        protected static $html = true;
35
        protected static $html = true;
36
 
36
 
37
        /*public*/ const PATH_RELATIVE = 1;                   // e.g. "../"
37
        /*public*/ const PATH_RELATIVE = 1;                   // e.g. "../"
38
        /*public*/ const PATH_ABSOLUTE = 2;                   // e.g. "http://www.example.com/oidplus/"
38
        /*public*/ const PATH_ABSOLUTE = 2;                   // e.g. "http://www.example.com/oidplus/"
39
        /*public*/ const PATH_ABSOLUTE_CANONICAL = 3;         // e.g. "http://www.example.org/oidplus/" (if baseconfig CANONICAL_SYSTEM_URL is set)
39
        /*public*/ const PATH_ABSOLUTE_CANONICAL = 3;         // e.g. "http://www.example.org/oidplus/" (if baseconfig CANONICAL_SYSTEM_URL is set)
40
        /*public*/ const PATH_RELATIVE_TO_ROOT = 4;           // e.g. "/oidplus/"
40
        /*public*/ const PATH_RELATIVE_TO_ROOT = 4;           // e.g. "/oidplus/"
41
        /*public*/ const PATH_RELATIVE_TO_ROOT_CANONICAL = 5; // e.g. "/oidplus/" (if baseconfig CANONICAL_SYSTEM_URL is set)
41
        /*public*/ const PATH_RELATIVE_TO_ROOT_CANONICAL = 5; // e.g. "/oidplus/" (if baseconfig CANONICAL_SYSTEM_URL is set)
42
 
42
 
43
        // These plugin types can contain HTML code and therefore may
43
        // These plugin types can contain HTML code and therefore may
44
        // emit (non-setup) CSS/JS code via their manifest.
44
        // emit (non-setup) CSS/JS code via their manifest.
45
        /*public*/ const INTERACTIVE_PLUGIN_TYPES = array(
45
        /*public*/ const INTERACTIVE_PLUGIN_TYPES = array(
46
                'publicPages',
46
                'publicPages',
47
                'raPages',
47
                'raPages',
48
                'adminPages',
48
                'adminPages',
49
                'objectTypes',
49
                'objectTypes',
50
                'captcha'
50
                'captcha'
51
        );
51
        );
52
 
52
 
53
        private function __construct() {
53
        private function __construct() {
54
        }
54
        }
55
 
55
 
56
        # --- Static classes
56
        // --- Static classes
57
 
57
 
58
        private static $baseConfig = null;
58
        private static $baseConfig = null;
59
        private static $old_config_format = false;
59
        private static $oldConfigFormatLoaded = false;
60
        public static function baseConfig() {
60
        public static function baseConfig() {
61
                $first_init = false;
61
                $first_init = false;
62
 
62
 
63
                if ($first_init = is_null(self::$baseConfig)) {
63
                if ($first_init = is_null(self::$baseConfig)) {
64
                        self::$baseConfig = new OIDplusBaseConfig();
64
                        self::$baseConfig = new OIDplusBaseConfig();
65
                }
65
                }
66
 
66
 
67
                if ($first_init) {
67
                if ($first_init) {
68
                        // Include a file containing various size/depth limitations of OIDs
68
                        // Include a file containing various size/depth limitations of OIDs
69
                        // It is important to include it before userdata/baseconfig/config.inc.php was included,
69
                        // It is important to include it before userdata/baseconfig/config.inc.php was included,
70
                        // so we can give userdata/baseconfig/config.inc.php the chance to override the values.
70
                        // so we can give userdata/baseconfig/config.inc.php the chance to override the values.
71
 
71
 
72
                        include OIDplus::localpath().'includes/oidplus_limits.inc.php';
72
                        include OIDplus::localpath().'includes/oidplus_limits.inc.php';
73
 
73
 
74
                        // Include config file
74
                        // Include config file
75
 
75
 
76
                        $config_file = OIDplus::localpath() . 'userdata/baseconfig/config.inc.php';
76
                        $config_file = OIDplus::localpath() . 'userdata/baseconfig/config.inc.php';
77
                        $config_file_old = OIDplus::localpath() . 'includes/config.inc.php'; // backwards compatibility
77
                        $config_file_old = OIDplus::localpath() . 'includes/config.inc.php'; // backwards compatibility
78
 
78
 
79
                        if (!file_exists($config_file) && file_exists($config_file_old)) {
79
                        if (!file_exists($config_file) && file_exists($config_file_old)) {
80
                                $config_file = $config_file_old;
80
                                $config_file = $config_file_old;
81
                        }
81
                        }
82
 
82
 
83
                        if (file_exists($config_file)) {
83
                        if (file_exists($config_file)) {
84
                                if (self::$old_config_format) {
84
                                if (self::$oldConfigFormatLoaded) {
85
                                        // Note: We may only include it once due to backwards compatibility,
85
                                        // Note: We may only include it once due to backwards compatibility,
86
                                        //       since in version 2.0, the configuration was defined using define() statements
86
                                        //       since in version 2.0, the configuration was defined using define() statements
87
                                        // Attention: This does mean that a full re-init (e.g. for test cases) is not possible
87
                                        // Attention: This does mean that a full re-init (e.g. for test cases) is not possible
88
                                        //            if a version 2.0 config is used!
88
                                        //            if a version 2.0 config is used!
-
 
89
 
-
 
90
                                        // We need to do this, because define() cannot be undone
-
 
91
                                        // Note: This can only happen in very special cases (e.g. test cases) where you call init() twice
-
 
92
                                        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.'));
-
 
93
                                } else {
-
 
94
                                        $tmp = file_get_contents($config_file);
-
 
95
                                        $ns = "ViaThinkSoft\OIDplus\OIDplus";
-
 
96
                                        $uses = "use $ns;";
-
 
97
                                        if ((strpos($tmp,'OIDplus::') !== false) && (strpos($tmp,$uses) === false)) {
-
 
98
                                                // Migrate config file to namespace class names
-
 
99
                                                // Note: Only config files version 2.1 are affected. Not 2.0 ones
-
 
100
 
-
 
101
                                                $tmp = "<?php\r\n\r\n$uses /* Automatically added by migration procedure */\r\n?>$tmp";
-
 
102
                                                $tmp = str_replace('?><?php', '', $tmp);
-
 
103
 
-
 
104
                                                $tmp = str_replace("\$ns\OIDplusCaptchaPluginRecaptcha::", "OIDplusCaptchaPluginRecaptcha::", $tmp);
-
 
105
                                                $tmp = str_replace("OIDplusCaptchaPluginRecaptcha::", "\$ns\OIDplusCaptchaPluginRecaptcha::", $tmp);
-
 
106
 
-
 
107
                                                $tmp = str_replace('DISABLE_PLUGIN_OIDplusPagePublicRdap',
-
 
108
                                                                   'DISABLE_PLUGIN_Frdlweb\OIDplus\OIDplusPagePublicRdap', $tmp);
-
 
109
                                                $tmp = str_replace('DISABLE_PLUGIN_OIDplusPagePublicAltIds',
-
 
110
                                                                   'DISABLE_PLUGIN_Frdlweb\OIDplus\OIDplusPagePublicAltIds', $tmp);
-
 
111
                                                $tmp = str_replace('DISABLE_PLUGIN_OIDplus',
-
 
112
                                                                   'DISABLE_PLUGIN_ViaThinkSoft\OIDplus\OIDplus', $tmp);
-
 
113
                                                $tmp = str_replace('DISABLE_PLUGIN_OIDplusPagePublicUITweaks',
-
 
114
                                                                   'DISABLE_PLUGIN_TushevOrg\OIDplus\OIDplusPagePublicUITweaks', $tmp);
-
 
115
 
-
 
116
                                                if (@file_put_contents($config_file, $tmp) === false) {
-
 
117
                                                        eval('?>'.$tmp);
-
 
118
                                                } else {
89
                                        include_once $config_file;
119
                                                        include $config_file;
-
 
120
                                                }
90
                                } else {
121
                                        } else {
91
                                        include $config_file;
122
                                                include $config_file;
92
                                }
123
                                        }
-
 
124
                                }
93
 
125
 
94
                                if (defined('OIDPLUS_CONFIG_VERSION') && (OIDPLUS_CONFIG_VERSION == 2.0)) {
126
                                if (defined('OIDPLUS_CONFIG_VERSION') && (OIDPLUS_CONFIG_VERSION == 2.0)) {
95
                                        self::$old_config_format = true;
127
                                        self::$oldConfigFormatLoaded = true;
96
 
128
 
97
                                        // Backwards compatibility 2.0 => 2.1
129
                                        // Backwards compatibility 2.0 => 2.1
98
                                        foreach (get_defined_constants(true)['user'] as $name => $value) {
130
                                        foreach (get_defined_constants(true)['user'] as $name => $value) {
99
                                                $name = str_replace('OIDPLUS_', '', $name);
131
                                                $name = str_replace('OIDPLUS_', '', $name);
100
                                                if ($name == 'SESSION_SECRET') $name = 'SERVER_SECRET';
132
                                                if ($name == 'SESSION_SECRET') $name = 'SERVER_SECRET';
101
                                                if ($name == 'MYSQL_QUERYLOG') $name = 'QUERY_LOGFILE';
133
                                                if ($name == 'MYSQL_QUERYLOG') $name = 'QUERY_LOGFILE';
-
 
134
                                                $name = str_replace('DISABLE_PLUGIN_OIDplusPagePublicRdap',
-
 
135
                                                                    'DISABLE_PLUGIN_Frdlweb\OIDplus\OIDplusPagePublicRdap', $name);
-
 
136
                                                $name = str_replace('DISABLE_PLUGIN_OIDplusPagePublicAltIds',
-
 
137
                                                                    'DISABLE_PLUGIN_Frdlweb\OIDplus\OIDplusPagePublicAltIds', $name);
-
 
138
                                                $name = str_replace('DISABLE_PLUGIN_OIDplus',
-
 
139
                                                                    'DISABLE_PLUGIN_ViaThinkSoft\OIDplus\OIDplus', $name);
-
 
140
                                                $name = str_replace('DISABLE_PLUGIN_OIDplusPagePublicUITweaks',
-
 
141
                                                                    'DISABLE_PLUGIN_TushevOrg\OIDplus\OIDplusPagePublicUITweaks', $name);
102
                                                if (($name == 'MYSQL_PASSWORD') || ($name == 'ODBC_PASSWORD') || ($name == 'PDO_PASSWORD') || ($name == 'PGSQL_PASSWORD')) {
142
                                                if (($name == 'MYSQL_PASSWORD') || ($name == 'ODBC_PASSWORD') || ($name == 'PDO_PASSWORD') || ($name == 'PGSQL_PASSWORD')) {
103
                                                        self::$baseConfig->setValue($name, base64_decode($value));
143
                                                        self::$baseConfig->setValue($name, base64_decode($value));
104
                                                } else {
144
                                                } else {
105
                                                        if ($name == 'CONFIG_VERSION') $value = 2.1;
145
                                                        if ($name == 'CONFIG_VERSION') $value = 2.1;
106
                                                        self::$baseConfig->setValue($name, $value);
146
                                                        self::$baseConfig->setValue($name, $value);
107
                                                }
147
                                                }
108
                                        }
148
                                        }
109
                                }
149
                                }
110
                        } else {
150
                        } else {
111
                                if (!is_dir(OIDplus::localpath().'setup')) {
151
                                if (!is_dir(OIDplus::localpath().'setup')) {
112
                                        throw new OIDplusConfigInitializationException(_L('File %1 is missing, but setup can\'t be started because its directory missing.','userdata/baseconfig/config.inc.php'));
152
                                        throw new OIDplusConfigInitializationException(_L('File %1 is missing, but setup can\'t be started because its directory missing.',$config_file));
113
                                } else {
153
                                } else {
114
                                        if (self::$html) {
154
                                        if (self::$html) {
115
                                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE_TO_ROOT).'setup/') !== 0) {
155
                                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE_TO_ROOT).'setup/') !== 0) {
116
                                                        header('Location:'.OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/');
156
                                                        header('Location:'.OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/');
117
                                                        die(_L('Redirecting to setup...'));
157
                                                        die(_L('Redirecting to setup...'));
118
                                                } else {
158
                                                } else {
119
                                                        return self::$baseConfig;
159
                                                        return self::$baseConfig;
120
                                                }
160
                                                }
121
                                        } else {
161
                                        } else {
122
                                                // This can be displayed in e.g. ajax.php
162
                                                // This can be displayed in e.g. ajax.php
123
                                                throw new OIDplusConfigInitializationException(_L('File %1 is missing. Please run setup again.','userdata/baseconfig/config.inc.php'));
163
                                                throw new OIDplusConfigInitializationException(_L('File %1 is missing. Please run setup again.',$config_file));
124
                                        }
164
                                        }
125
                                }
165
                                }
126
                        }
166
                        }
127
 
167
 
128
                        // Check important config settings
168
                        // Check important config settings
129
 
169
 
130
                        if (self::$baseConfig->getValue('CONFIG_VERSION') != 2.1) {
170
                        if (self::$baseConfig->getValue('CONFIG_VERSION') != 2.1) {
131
                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/') !== 0) {
171
                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/') !== 0) {
132
                                        throw new OIDplusConfigInitializationException(_L("The information located in %1 is outdated.",realpath($config_file)));
172
                                        throw new OIDplusConfigInitializationException(_L("The information located in %1 is outdated.",realpath($config_file)));
133
                                }
173
                                }
134
                        }
174
                        }
135
 
175
 
136
                        if (self::$baseConfig->getValue('SERVER_SECRET', '') === '') {
176
                        if (self::$baseConfig->getValue('SERVER_SECRET', '') === '') {
137
                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/') !== 0) {
177
                                if (strpos($_SERVER['REQUEST_URI'], OIDplus::webpath(null,OIDplus::PATH_RELATIVE).'setup/') !== 0) {
138
                                        throw new OIDplusConfigInitializationException(_L("You must set a value for SERVER_SECRET in %1 for the system to operate secure.",realpath($config_file)));
178
                                        throw new OIDplusConfigInitializationException(_L("You must set a value for SERVER_SECRET in %1 for the system to operate secure.",realpath($config_file)));
139
                                }
179
                                }
140
                        }
180
                        }
141
                }
181
                }
142
 
182
 
143
                return self::$baseConfig;
183
                return self::$baseConfig;
144
        }
184
        }
145
 
185
 
146
        private static $config = null;
186
        private static $config = null;
147
        public static function config() {
187
        public static function config() {
148
                if ($first_init = is_null(self::$config)) {
188
                if ($first_init = is_null(self::$config)) {
149
                        self::$config = new OIDplusConfig();
189
                        self::$config = new OIDplusConfig();
150
                }
190
                }
151
 
191
 
152
                if ($first_init) {
192
                if ($first_init) {
153
                        // These are important settings for base functionalities and therefore are not inside plugins
193
                        // These are important settings for base functionalities and therefore are not inside plugins
154
                        self::$config->prepareConfigKey('system_title', 'What is the name of your RA?', 'OIDplus 2.0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
194
                        self::$config->prepareConfigKey('system_title', 'What is the name of your RA?', 'OIDplus 2.0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
155
                                if (empty($value)) {
195
                                if (empty($value)) {
156
                                        throw new OIDplusException(_L('Please enter a value for the system title.'));
196
                                        throw new OIDplusException(_L('Please enter a value for the system title.'));
157
                                }
197
                                }
158
                        });
198
                        });
159
                        self::$config->prepareConfigKey('admin_email', 'E-Mail address of the system administrator', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
199
                        self::$config->prepareConfigKey('admin_email', 'E-Mail address of the system administrator', '', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
160
                                if (!empty($value) && !OIDplus::mailUtils()->validMailAddress($value)) {
200
                                if (!empty($value) && !OIDplus::mailUtils()->validMailAddress($value)) {
161
                                        throw new OIDplusException(_L('This is not a correct email address'));
201
                                        throw new OIDplusException(_L('This is not a correct email address'));
162
                                }
202
                                }
163
                        });
203
                        });
164
                        self::$config->prepareConfigKey('global_cc', 'Global CC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function(&$value) {
204
                        self::$config->prepareConfigKey('global_cc', 'Global CC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function(&$value) {
165
                                $value = trim($value);
205
                                $value = trim($value);
166
                                if ($value === '') return;
206
                                if ($value === '') return;
167
                                $addrs = explode(';', $value);
207
                                $addrs = explode(';', $value);
168
                                foreach ($addrs as $addr) {
208
                                foreach ($addrs as $addr) {
169
                                        $addr = trim($addr);
209
                                        $addr = trim($addr);
170
                                        if (!empty($addr) && !OIDplus::mailUtils()->validMailAddress($addr)) {
210
                                        if (!empty($addr) && !OIDplus::mailUtils()->validMailAddress($addr)) {
171
                                                throw new OIDplusException(_L('%1 is not a correct email address',$addr));
211
                                                throw new OIDplusException(_L('%1 is not a correct email address',$addr));
172
                                        }
212
                                        }
173
                                }
213
                                }
174
                        });
214
                        });
175
                        self::$config->prepareConfigKey('global_bcc', 'Global BCC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function(&$value) {
215
                        self::$config->prepareConfigKey('global_bcc', 'Global BCC for all outgoing emails?', '', OIDplusConfig::PROTECTION_EDITABLE, function(&$value) {
176
                                $value = trim($value);
216
                                $value = trim($value);
177
                                if ($value === '') return;
217
                                if ($value === '') return;
178
                                $addrs = explode(';', $value);
218
                                $addrs = explode(';', $value);
179
                                foreach ($addrs as $addr) {
219
                                foreach ($addrs as $addr) {
180
                                        $addr = trim($addr);
220
                                        $addr = trim($addr);
181
                                        if (!empty($addr) && !OIDplus::mailUtils()->validMailAddress($addr)) {
221
                                        if (!empty($addr) && !OIDplus::mailUtils()->validMailAddress($addr)) {
182
                                                throw new OIDplusException(_L('%1 is not a correct email address',$addr));
222
                                                throw new OIDplusException(_L('%1 is not a correct email address',$addr));
183
                                        }
223
                                        }
184
                                }
224
                                }
185
                        });
225
                        });
186
                        self::$config->prepareConfigKey('objecttypes_initialized', 'List of object type plugins that were initialized once', '', OIDplusConfig::PROTECTION_READONLY, function($value) {
226
                        self::$config->prepareConfigKey('objecttypes_initialized', 'List of object type plugins that were initialized once', '', OIDplusConfig::PROTECTION_READONLY, function($value) {
187
                                // Nothing here yet
227
                                // Nothing here yet
188
                        });
228
                        });
189
                        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) {
229
                        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) {
190
                                # 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?
230
                                // 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?
191
 
231
 
192
                                $ary = explode(';',$value);
232
                                $ary = explode(';',$value);
193
                                $uniq_ary = array_unique($ary);
233
                                $uniq_ary = array_unique($ary);
194
 
234
 
195
                                if (count($ary) != count($uniq_ary)) {
235
                                if (count($ary) != count($uniq_ary)) {
196
                                        throw new OIDplusException(_L('Please check your input. Some object types are double.'));
236
                                        throw new OIDplusException(_L('Please check your input. Some object types are double.'));
197
                                }
237
                                }
198
 
238
 
199
                                foreach ($ary as $ot_check) {
239
                                foreach ($ary as $ot_check) {
200
                                        $ns_found = false;
240
                                        $ns_found = false;
201
                                        foreach (OIDplus::getEnabledObjectTypes() as $ot) {
241
                                        foreach (OIDplus::getEnabledObjectTypes() as $ot) {
202
                                                if ($ot::ns() == $ot_check) {
242
                                                if ($ot::ns() == $ot_check) {
203
                                                        $ns_found = true;
243
                                                        $ns_found = true;
204
                                                        break;
244
                                                        break;
205
                                                }
245
                                                }
206
                                        }
246
                                        }
207
                                        foreach (OIDplus::getDisabledObjectTypes() as $ot) {
247
                                        foreach (OIDplus::getDisabledObjectTypes() as $ot) {
208
                                                if ($ot::ns() == $ot_check) {
248
                                                if ($ot::ns() == $ot_check) {
209
                                                        $ns_found = true;
249
                                                        $ns_found = true;
210
                                                        break;
250
                                                        break;
211
                                                }
251
                                                }
212
                                        }
252
                                        }
213
                                        if (!$ns_found) {
253
                                        if (!$ns_found) {
214
                                                throw new OIDplusException(_L('Please check your input. Namespace "%1" is not found',$ot_check));
254
                                                throw new OIDplusException(_L('Please check your input. Namespace "%1" is not found',$ot_check));
215
                                        }
255
                                        }
216
                                }
256
                                }
217
                        });
257
                        });
218
                        self::$config->prepareConfigKey('oidplus_private_key', 'Private key for this system', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
258
                        self::$config->prepareConfigKey('oidplus_private_key', 'Private key for this system', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
219
                                // Nothing here yet
259
                                // Nothing here yet
220
                        });
260
                        });
221
                        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) {
261
                        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) {
222
                                // Nothing here yet
262
                                // Nothing here yet
223
                        });
263
                        });
224
                        self::$config->prepareConfigKey('last_known_system_url', 'Last known System URL', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
264
                        self::$config->prepareConfigKey('last_known_system_url', 'Last known System URL', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
225
                                // Nothing here yet
265
                                // Nothing here yet
226
                        });
266
                        });
227
                        self::$config->prepareConfigKey('last_known_version', 'Last known OIDplus Version', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
267
                        self::$config->prepareConfigKey('last_known_version', 'Last known OIDplus Version', '', OIDplusConfig::PROTECTION_HIDDEN, function($value) {
228
                                // Nothing here yet
268
                                // Nothing here yet
229
                        });
269
                        });
230
                        self::$config->prepareConfigKey('default_ra_auth_method', 'Default auth method used for generating password of RAs (must exist in plugins/[vendorname]/auth/)?', 'A3_bcrypt', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
270
                        self::$config->prepareConfigKey('default_ra_auth_method', 'Default auth method used for generating password of RAs (must exist in plugins/[vendorname]/auth/)?', 'A3_bcrypt', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
231
                                $good = true;
271
                                $good = true;
232
                                if (strpos($value,'/') !== false) $good = false;
272
                                if (strpos($value,'/') !== false) $good = false;
233
                                if (strpos($value,'\\') !== false) $good = false;
273
                                if (strpos($value,'\\') !== false) $good = false;
234
                                if (strpos($value,'..') !== false) $good = false;
274
                                if (strpos($value,'..') !== false) $good = false;
235
                                if (!$good) {
275
                                if (!$good) {
236
                                        throw new OIDplusException(_L('Invalid auth plugin folder name. Do only enter a folder name, not an absolute or relative path'));
276
                                        throw new OIDplusException(_L('Invalid auth plugin folder name. Do only enter a folder name, not an absolute or relative path'));
237
                                }
277
                                }
238
 
278
 
239
                                if (!wildcard_is_dir(OIDplus::localpath().'plugins/'.'*'.'/auth/'.$value)) {
279
                                if (!wildcard_is_dir(OIDplus::localpath().'plugins/'.'*'.'/auth/'.$value)) {
240
                                        throw new OIDplusException(_L('The auth plugin "%1" does not exist in plugin directory %2',$value,'plugins/[vendorname]/auth/'));
280
                                        throw new OIDplusException(_L('The auth plugin "%1" does not exist in plugin directory %2',$value,'plugins/[vendorname]/auth/'));
241
                                }
281
                                }
242
                        });
282
                        });
243
                }
283
                }
244
 
284
 
245
                return self::$config;
285
                return self::$config;
246
        }
286
        }
247
 
287
 
248
        private static $gui = null;
288
        private static $gui = null;
249
        public static function gui() {
289
        public static function gui() {
250
                if (is_null(self::$gui)) {
290
                if (is_null(self::$gui)) {
251
                        self::$gui = new OIDplusGui();
291
                        self::$gui = new OIDplusGui();
252
                }
292
                }
253
                return self::$gui;
293
                return self::$gui;
254
        }
294
        }
255
 
295
 
256
        private static $authUtils = null;
296
        private static $authUtils = null;
257
        public static function authUtils() {
297
        public static function authUtils() {
258
                if (is_null(self::$authUtils)) {
298
                if (is_null(self::$authUtils)) {
259
                        self::$authUtils = new OIDplusAuthUtils();
299
                        self::$authUtils = new OIDplusAuthUtils();
260
                }
300
                }
261
                return self::$authUtils;
301
                return self::$authUtils;
262
        }
302
        }
263
 
303
 
264
        private static $mailUtils = null;
304
        private static $mailUtils = null;
265
        public static function mailUtils() {
305
        public static function mailUtils() {
266
                if (is_null(self::$mailUtils)) {
306
                if (is_null(self::$mailUtils)) {
267
                        self::$mailUtils = new OIDplusMailUtils();
307
                        self::$mailUtils = new OIDplusMailUtils();
268
                }
308
                }
269
                return self::$mailUtils;
309
                return self::$mailUtils;
270
        }
310
        }
271
 
311
 
272
        private static $cookieUtils = null;
312
        private static $cookieUtils = null;
273
        public static function cookieUtils() {
313
        public static function cookieUtils() {
274
                if (is_null(self::$cookieUtils)) {
314
                if (is_null(self::$cookieUtils)) {
275
                        self::$cookieUtils = new OIDplusCookieUtils();
315
                        self::$cookieUtils = new OIDplusCookieUtils();
276
                }
316
                }
277
                return self::$cookieUtils;
317
                return self::$cookieUtils;
278
        }
318
        }
279
 
319
 
280
        private static $menuUtils = null;
320
        private static $menuUtils = null;
281
        public static function menuUtils() {
321
        public static function menuUtils() {
282
                if (is_null(self::$menuUtils)) {
322
                if (is_null(self::$menuUtils)) {
283
                        self::$menuUtils = new OIDplusMenuUtils();
323
                        self::$menuUtils = new OIDplusMenuUtils();
284
                }
324
                }
285
                return self::$menuUtils;
325
                return self::$menuUtils;
286
        }
326
        }
287
 
327
 
288
        private static $logger = null;
328
        private static $logger = null;
289
        public static function logger() {
329
        public static function logger() {
290
                if (is_null(self::$logger)) {
330
                if (is_null(self::$logger)) {
291
                        self::$logger = new OIDplusLogger();
331
                        self::$logger = new OIDplusLogger();
292
                }
332
                }
293
                return self::$logger;
333
                return self::$logger;
294
        }
334
        }
295
 
335
 
296
        # --- SQL slang plugin
336
        // --- SQL slang plugin
297
 
337
 
298
        private static function registerSqlSlangPlugin(OIDplusSqlSlangPlugin $plugin) {
338
        private static function registerSqlSlangPlugin(OIDplusSqlSlangPlugin $plugin) {
299
                $name = $plugin::id();
339
                $name = $plugin::id();
300
                if ($name === '') return false;
340
                if ($name === '') return false;
301
 
341
 
302
                if (isset(self::$sqlSlangPlugins[$name])) {
342
                if (isset(self::$sqlSlangPlugins[$name])) {
303
                        $plugintype_hf = _L('SQL slang');
343
                        $plugintype_hf = _L('SQL slang');
304
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
344
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
305
                }
345
                }
306
 
346
 
307
                self::$sqlSlangPlugins[$name] = $plugin;
347
                self::$sqlSlangPlugins[$name] = $plugin;
308
 
348
 
309
                return true;
349
                return true;
310
        }
350
        }
311
 
351
 
312
        public static function getSqlSlangPlugins() {
352
        public static function getSqlSlangPlugins() {
313
                return self::$sqlSlangPlugins;
353
                return self::$sqlSlangPlugins;
314
        }
354
        }
315
 
355
 
316
        public static function getSqlSlangPlugin($id)/*: ?OIDplusSqlSlangPlugin*/ {
356
        public static function getSqlSlangPlugin($id)/*: ?OIDplusSqlSlangPlugin*/ {
317
                if (isset(self::$sqlSlangPlugins[$id])) {
357
                if (isset(self::$sqlSlangPlugins[$id])) {
318
                        return self::$sqlSlangPlugins[$id];
358
                        return self::$sqlSlangPlugins[$id];
319
                } else {
359
                } else {
320
                        return null;
360
                        return null;
321
                }
361
                }
322
        }
362
        }
323
 
363
 
324
        # --- Database plugin
364
        // --- Database plugin
325
 
365
 
326
        private static function registerDatabasePlugin(OIDplusDatabasePlugin $plugin) {
366
        private static function registerDatabasePlugin(OIDplusDatabasePlugin $plugin) {
327
                $name = $plugin::id();
367
                $name = $plugin::id();
328
                if ($name === '') return false;
368
                if ($name === '') return false;
329
 
369
 
330
                if (isset(self::$dbPlugins[$name])) {
370
                if (isset(self::$dbPlugins[$name])) {
331
                        $plugintype_hf = _L('Database');
371
                        $plugintype_hf = _L('Database');
332
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
372
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
333
                }
373
                }
334
 
374
 
335
                self::$dbPlugins[$name] = $plugin;
375
                self::$dbPlugins[$name] = $plugin;
336
 
376
 
337
                return true;
377
                return true;
338
        }
378
        }
339
 
379
 
340
        public static function getDatabasePlugins() {
380
        public static function getDatabasePlugins() {
341
                return self::$dbPlugins;
381
                return self::$dbPlugins;
342
        }
382
        }
343
 
383
 
344
        public static function getActiveDatabasePlugin() {
384
        public static function getActiveDatabasePlugin() {
345
                $db_plugin_name = OIDplus::baseConfig()->getValue('DATABASE_PLUGIN','');
385
                $db_plugin_name = OIDplus::baseConfig()->getValue('DATABASE_PLUGIN','');
346
                if ($db_plugin_name === '') {
386
                if ($db_plugin_name === '') {
347
                        throw new OIDplusConfigInitializationException(_L('No database plugin selected in config file'));
387
                        throw new OIDplusConfigInitializationException(_L('No database plugin selected in config file'));
348
                }
388
                }
349
                foreach (self::$dbPlugins as $name => $plugin) {
389
                foreach (self::$dbPlugins as $name => $plugin) {
350
                        if (strtolower($name) == strtolower($db_plugin_name)) {
390
                        if (strtolower($name) == strtolower($db_plugin_name)) {
351
                                return $plugin;
391
                                return $plugin;
352
                        }
392
                        }
353
                }
393
                }
354
                throw new OIDplusConfigInitializationException(_L('Database plugin "%1" not found',$db_plugin_name));
394
                throw new OIDplusConfigInitializationException(_L('Database plugin "%1" not found',$db_plugin_name));
355
        }
395
        }
356
 
396
 
357
        private static $dbMainSession = null;
397
        private static $dbMainSession = null;
358
        public static function db() {
398
        public static function db() {
359
                if (is_null(self::$dbMainSession)) {
399
                if (is_null(self::$dbMainSession)) {
360
                        self::$dbMainSession = self::getActiveDatabasePlugin()->newConnection();
400
                        self::$dbMainSession = self::getActiveDatabasePlugin()->newConnection();
361
                }
401
                }
362
                if (!self::$dbMainSession->isConnected()) self::$dbMainSession->connect();
402
                if (!self::$dbMainSession->isConnected()) self::$dbMainSession->connect();
363
                return self::$dbMainSession;
403
                return self::$dbMainSession;
364
        }
404
        }
365
 
405
 
366
        private static $dbIsolatedSession = null;
406
        private static $dbIsolatedSession = null;
367
        public static function dbIsolated() {
407
        public static function dbIsolated() {
368
                if (is_null(self::$dbIsolatedSession)) {
408
                if (is_null(self::$dbIsolatedSession)) {
369
                        self::$dbIsolatedSession = self::getActiveDatabasePlugin()->newConnection();
409
                        self::$dbIsolatedSession = self::getActiveDatabasePlugin()->newConnection();
370
                }
410
                }
371
                if (!self::$dbIsolatedSession->isConnected()) self::$dbIsolatedSession->connect();
411
                if (!self::$dbIsolatedSession->isConnected()) self::$dbIsolatedSession->connect();
372
                return self::$dbIsolatedSession;
412
                return self::$dbIsolatedSession;
373
        }
413
        }
374
 
414
 
375
        # --- CAPTCHA plugin
415
        // --- CAPTCHA plugin
376
 
416
 
377
        private static function registerCaptchaPlugin(OIDplusCaptchaPlugin $plugin) {
417
        private static function registerCaptchaPlugin(OIDplusCaptchaPlugin $plugin) {
378
                $name = $plugin::id();
418
                $name = $plugin::id();
379
                if ($name === '') return false;
419
                if ($name === '') return false;
380
 
420
 
381
                if (isset(self::$captchaPlugins[$name])) {
421
                if (isset(self::$captchaPlugins[$name])) {
382
                        $plugintype_hf = _L('CAPTCHA');
422
                        $plugintype_hf = _L('CAPTCHA');
383
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
423
                        throw new OIDplusException(_L('Multiple %1 plugins use the ID %2', $plugintype_hf, $name));
384
                }
424
                }
385
 
425
 
386
                self::$captchaPlugins[$name] = $plugin;
426
                self::$captchaPlugins[$name] = $plugin;
387
 
427
 
388
                return true;
428
                return true;
389
        }
429
        }
390
 
430
 
391
        public static function getCaptchaPlugins() {
431
        public static function getCaptchaPlugins() {
392
                return self::$captchaPlugins;
432
                return self::$captchaPlugins;
393
        }
433
        }
394
 
434
 
395
        public static function getActiveCaptchaPluginId() {
435
        public static function getActiveCaptchaPluginId() {
396
                $captcha_plugin_name = OIDplus::baseConfig()->getValue('CAPTCHA_PLUGIN', '');
436
                $captcha_plugin_name = OIDplus::baseConfig()->getValue('CAPTCHA_PLUGIN', '');
397
 
437
 
398
                if (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false) && ($captcha_plugin_name === '')) {
438
                if (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false) && ($captcha_plugin_name === '')) {
399
                        // Legacy config file support!
439
                        // Legacy config file support!
400
                        $captcha_plugin_name = 'reCAPTCHA';
440
                        $captcha_plugin_name = 'reCAPTCHA';
401
                }
441
                }
402
 
442
 
403
                if ($captcha_plugin_name === '') $captcha_plugin_name = 'None'; // the "None" plugin is a must-have!
443
                if ($captcha_plugin_name === '') $captcha_plugin_name = 'None'; // the "None" plugin is a must-have!
404
 
444
 
405
                return $captcha_plugin_name;
445
                return $captcha_plugin_name;
406
        }
446
        }
407
 
447
 
408
        public static function getActiveCaptchaPlugin() {
448
        public static function getActiveCaptchaPlugin() {
409
                $captcha_plugin_name = OIDplus::getActiveCaptchaPluginId();
449
                $captcha_plugin_name = OIDplus::getActiveCaptchaPluginId();
410
                foreach (self::$captchaPlugins as $name => $plugin) {
450
                foreach (self::$captchaPlugins as $name => $plugin) {
411
                        if (strtolower($name) == strtolower($captcha_plugin_name)) {
451
                        if (strtolower($name) == strtolower($captcha_plugin_name)) {
412
                                return $plugin;
452
                                return $plugin;
413
                        }
453
                        }
414
                }
454
                }
415
                throw new OIDplusConfigInitializationException(_L('CAPTCHA plugin "%1" not found',$captcha_plugin_name));
455
                throw new OIDplusConfigInitializationException(_L('CAPTCHA plugin "%1" not found',$captcha_plugin_name));
416
        }
456
        }
417
 
457
 
418
        # --- Page plugin
458
        // --- Page plugin
419
 
459
 
420
        private static function registerPagePlugin(OIDplusPagePlugin $plugin) {
460
        private static function registerPagePlugin(OIDplusPagePlugin $plugin) {
421
                self::$pagePlugins[] = $plugin;
461
                self::$pagePlugins[] = $plugin;
422
 
462
 
423
                return true;
463
                return true;
424
        }
464
        }
425
 
465
 
426
        public static function getPagePlugins() {
466
        public static function getPagePlugins() {
427
                return self::$pagePlugins;
467
                return self::$pagePlugins;
428
        }
468
        }
429
 
469
 
430
        # --- Auth plugin
470
        // --- Auth plugin
431
 
471
 
432
        private static function registerAuthPlugin(OIDplusAuthPlugin $plugin) {
472
        private static function registerAuthPlugin(OIDplusAuthPlugin $plugin) {
433
                if (OIDplus::baseConfig()->getValue('DEBUG')) {
473
                if (OIDplus::baseConfig()->getValue('DEBUG')) {
434
                        $password = generateRandomString(25);
474
                        $password = generateRandomString(25);
435
 
475
 
436
                        try {
476
                        try {
437
                                $authInfo = $plugin->generate($password);
477
                                $authInfo = $plugin->generate($password);
438
                        } catch (OIDplusException $e) {
478
                        } catch (OIDplusException $e) {
439
                                // This can happen when the AuthKey or Salt is too long
479
                                // This can happen when the AuthKey or Salt is too long
440
                                throw new OIDplusException(_L('Auth plugin "%1" is erroneous: %2',basename($plugin->getPluginDirectory()),$e->getMessage()));
480
                                throw new OIDplusException(_L('Auth plugin "%1" is erroneous: %2',basename($plugin->getPluginDirectory()),$e->getMessage()));
441
                        }
481
                        }
442
                        $salt = $authInfo->getSalt();
482
                        $salt = $authInfo->getSalt();
443
                        $authKey = $authInfo->getAuthKey();
483
                        $authKey = $authInfo->getAuthKey();
444
 
484
 
445
                        $authInfo_SaltDiff = clone $authInfo;
485
                        $authInfo_SaltDiff = clone $authInfo;
446
                        $authInfo_SaltDiff->setSalt(strrev($authInfo_SaltDiff->getSalt()));
486
                        $authInfo_SaltDiff->setSalt(strrev($authInfo_SaltDiff->getSalt()));
447
 
487
 
448
                        $authInfo_AuthKeyDiff = clone $authInfo;
488
                        $authInfo_AuthKeyDiff = clone $authInfo;
449
                        $authInfo_AuthKeyDiff->setAuthKey(strrev($authInfo_AuthKeyDiff->getAuthKey()));
489
                        $authInfo_AuthKeyDiff->setAuthKey(strrev($authInfo_AuthKeyDiff->getAuthKey()));
450
 
490
 
451
                        if ((!$plugin->verify($authInfo,$password)) ||
491
                        if ((!$plugin->verify($authInfo,$password)) ||
452
                           (!empty($salt) && $plugin->verify($authInfo_SaltDiff,$password)) ||
492
                           (!empty($salt) && $plugin->verify($authInfo_SaltDiff,$password)) ||
453
                           ($plugin->verify($authInfo_AuthKeyDiff,$password)) ||
493
                           ($plugin->verify($authInfo_AuthKeyDiff,$password)) ||
454
                           ($plugin->verify($authInfo,$password.'x'))) {
494
                           ($plugin->verify($authInfo,$password.'x'))) {
455
                                throw new OIDplusException(_L('Auth plugin "%1" is erroneous: Generate/Verify self test failed',basename($plugin->getPluginDirectory())));
495
                                throw new OIDplusException(_L('Auth plugin "%1" is erroneous: Generate/Verify self test failed',basename($plugin->getPluginDirectory())));
456
                        }
496
                        }
457
                }
497
                }
458
 
498
 
459
                self::$authPlugins[] = $plugin;
499
                self::$authPlugins[] = $plugin;
460
                return true;
500
                return true;
461
        }
501
        }
462
 
502
 
463
        public static function getAuthPlugins() {
503
        public static function getAuthPlugins() {
464
                return self::$authPlugins;
504
                return self::$authPlugins;
465
        }
505
        }
466
 
506
 
467
        # --- Language plugin
507
        // --- Language plugin
468
 
508
 
469
        private static function registerLanguagePlugin(OIDplusLanguagePlugin $plugin) {
509
        private static function registerLanguagePlugin(OIDplusLanguagePlugin $plugin) {
470
                self::$languagePlugins[] = $plugin;
510
                self::$languagePlugins[] = $plugin;
471
                return true;
511
                return true;
472
        }
512
        }
473
 
513
 
474
        public static function getLanguagePlugins() {
514
        public static function getLanguagePlugins() {
475
                return self::$languagePlugins;
515
                return self::$languagePlugins;
476
        }
516
        }
477
 
517
 
478
        # --- Design plugin
518
        // --- Design plugin
479
 
519
 
480
        private static function registerDesignPlugin(OIDplusDesignPlugin $plugin) {
520
        private static function registerDesignPlugin(OIDplusDesignPlugin $plugin) {
481
                self::$designPlugins[] = $plugin;
521
                self::$designPlugins[] = $plugin;
482
                return true;
522
                return true;
483
        }
523
        }
484
 
524
 
485
        public static function getDesignPlugins() {
525
        public static function getDesignPlugins() {
486
                return self::$designPlugins;
526
                return self::$designPlugins;
487
        }
527
        }
488
 
528
 
489
        public static function getActiveDesignPlugin() {
529
        public static function getActiveDesignPlugin() {
490
                $plugins = OIDplus::getDesignPlugins();
530
                $plugins = OIDplus::getDesignPlugins();
491
                foreach ($plugins as $plugin) {
531
                foreach ($plugins as $plugin) {
492
                        if ((basename($plugin->getPluginDirectory())) == OIDplus::config()->getValue('design','default')) {
532
                        if ((basename($plugin->getPluginDirectory())) == OIDplus::config()->getValue('design','default')) {
493
                                return $plugin;
533
                                return $plugin;
494
                        }
534
                        }
495
                }
535
                }
496
                return null;
536
                return null;
497
        }
537
        }
498
 
538
 
499
        # --- Logger plugin
539
        // --- Logger plugin
500
 
540
 
501
        private static function registerLoggerPlugin(OIDplusLoggerPlugin $plugin) {
541
        private static function registerLoggerPlugin(OIDplusLoggerPlugin $plugin) {
502
                self::$loggerPlugins[] = $plugin;
542
                self::$loggerPlugins[] = $plugin;
503
                return true;
543
                return true;
504
        }
544
        }
505
 
545
 
506
        public static function getLoggerPlugins() {
546
        public static function getLoggerPlugins() {
507
                return self::$loggerPlugins;
547
                return self::$loggerPlugins;
508
        }
548
        }
509
 
549
 
510
        # --- Object type plugin
550
        // --- Object type plugin
511
 
551
 
512
        private static function registerObjectTypePlugin(OIDplusObjectTypePlugin $plugin) {
552
        private static function registerObjectTypePlugin(OIDplusObjectTypePlugin $plugin) {
513
                self::$objectTypePlugins[] = $plugin;
553
                self::$objectTypePlugins[] = $plugin;
514
 
554
 
515
                $ot = $plugin::getObjectTypeClassName();
555
                $ot = $plugin::getObjectTypeClassName();
516
                self::registerObjectType($ot);
556
                self::registerObjectType($ot);
517
 
557
 
518
                return true;
558
                return true;
519
        }
559
        }
520
 
560
 
521
        private static function registerObjectType($ot) {
561
        private static function registerObjectType($ot) {
522
                $ns = $ot::ns();
562
                $ns = $ot::ns();
523
                if (empty($ns)) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Namespace must not be empty',$ot));
563
                if (empty($ns)) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Namespace must not be empty',$ot));
524
 
564
 
525
                // Currently, we must enforce that namespaces in objectType plugins are lowercase, because prefilterQuery() makes all namespaces lowercase and the DBMS should be case-sensitive
565
                // Currently, we must enforce that namespaces in objectType plugins are lowercase, because prefilterQuery() makes all namespaces lowercase and the DBMS should be case-sensitive
526
                if ($ns != strtolower($ns)) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Namespace %2 must be lower-case',$ot,$ns));
566
                if ($ns != strtolower($ns)) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Namespace %2 must be lower-case',$ot,$ns));
527
 
567
 
528
                $root = $ot::root();
568
                $root = $ot::root();
529
                if (!str_starts_with($root,$ns.':')) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Root node (%2) is in wrong namespace (needs starts with %3)!',$ot,$root,$ns.':'));
569
                if (!str_starts_with($root,$ns.':')) throw new OIDplusException(_L('ObjectType plugin %1 is erroneous: Root node (%2) is in wrong namespace (needs starts with %3)!',$ot,$root,$ns.':'));
530
 
570
 
531
                $ns_found = false;
571
                $ns_found = false;
532
                foreach (array_merge(OIDplus::getEnabledObjectTypes(), OIDplus::getDisabledObjectTypes()) as $test_ot) {
572
                foreach (array_merge(OIDplus::getEnabledObjectTypes(), OIDplus::getDisabledObjectTypes()) as $test_ot) {
533
                        if ($test_ot::ns() == $ns) {
573
                        if ($test_ot::ns() == $ns) {
534
                                $ns_found = true;
574
                                $ns_found = true;
535
                                break;
575
                                break;
536
                        }
576
                        }
537
                }
577
                }
538
                if ($ns_found) {
578
                if ($ns_found) {
539
                        throw new OIDplusException(_L('Attention: Two objectType plugins use the same namespace "%1"!',$ns));
579
                        throw new OIDplusException(_L('Attention: Two objectType plugins use the same namespace "%1"!',$ns));
540
                }
580
                }
541
 
581
 
542
                $init = OIDplus::config()->getValue("objecttypes_initialized");
582
                $init = OIDplus::config()->getValue("objecttypes_initialized");
543
                $init_ary = empty($init) ? array() : explode(';', $init);
583
                $init_ary = empty($init) ? array() : explode(';', $init);
544
                $init_ary = array_map('trim', $init_ary);
584
                $init_ary = array_map('trim', $init_ary);
545
 
585
 
546
                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
586
                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
547
                $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
587
                $enabled_ary = empty($enabled) ? array() : explode(';', $enabled);
548
                $enabled_ary = array_map('trim', $enabled_ary);
588
                $enabled_ary = array_map('trim', $enabled_ary);
549
 
589
 
550
                $do_enable = false;
590
                $do_enable = false;
551
                if (in_array($ns, $enabled_ary)) {
591
                if (in_array($ns, $enabled_ary)) {
552
                        // If it is in the list of enabled object types, it is enabled (obviously)
592
                        // If it is in the list of enabled object types, it is enabled (obviously)
553
                        $do_enable = true;
593
                        $do_enable = true;
554
                } else {
594
                } else {
555
                        if (!OIDplus::config()->getValue('oobe_objects_done')) {
595
                        if (!OIDplus::config()->getValue('oobe_objects_done')) {
556
                                // If the OOBE wizard is NOT done, then just enable the "oid" object type by default
596
                                // If the OOBE wizard is NOT done, then just enable the "oid" object type by default
557
                                $do_enable = $ns == 'oid';
597
                                $do_enable = $ns == 'oid';
558
                        } else {
598
                        } else {
559
                                // If the OOBE wizard was done (once), then
599
                                // If the OOBE wizard was done (once), then
560
                                // we will enable all object types which were never initialized
600
                                // we will enable all object types which were never initialized
561
                                // (i.e. a plugin folder was freshly added)
601
                                // (i.e. a plugin folder was freshly added)
562
                                $do_enable = !in_array($ns, $init_ary);
602
                                $do_enable = !in_array($ns, $init_ary);
563
                        }
603
                        }
564
                }
604
                }
565
 
605
 
566
                if ($do_enable) {
606
                if ($do_enable) {
567
                        self::$enabledObjectTypes[] = $ot;
607
                        self::$enabledObjectTypes[] = $ot;
568
                        usort(self::$enabledObjectTypes, function($a, $b) {
608
                        usort(self::$enabledObjectTypes, function($a, $b) {
569
                                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
609
                                $enabled = OIDplus::config()->getValue("objecttypes_enabled");
570
                                $enabled_ary = explode(';', $enabled);
610
                                $enabled_ary = explode(';', $enabled);
571
 
611
 
572
                                $idx_a = array_search($a::ns(), $enabled_ary);
612
                                $idx_a = array_search($a::ns(), $enabled_ary);
573
                                $idx_b = array_search($b::ns(), $enabled_ary);
613
                                $idx_b = array_search($b::ns(), $enabled_ary);
574
 
614
 
575
                                if ($idx_a == $idx_b) {
615
                                if ($idx_a == $idx_b) {
576
                                    return 0;
616
                                    return 0;
577
                                }
617
                                }
578
                                return ($idx_a > $idx_b) ? +1 : -1;
618
                                return ($idx_a > $idx_b) ? +1 : -1;
579
                        });
619
                        });
580
                } else {
620
                } else {
581
                        self::$disabledObjectTypes[] = $ot;
621
                        self::$disabledObjectTypes[] = $ot;
582
                }
622
                }
583
 
623
 
584
                if (!in_array($ns, $init_ary)) {
624
                if (!in_array($ns, $init_ary)) {
585
                        // Was never initialized before, so we add it to the list of enabled object types once
625
                        // Was never initialized before, so we add it to the list of enabled object types once
586
 
626
 
587
                        if ($do_enable) {
627
                        if ($do_enable) {
588
                                $enabled_ary[] = $ns;
628
                                $enabled_ary[] = $ns;
589
                                // Important: Don't validate the input, because the other object types might not be initialized yet! So use setValueNoCallback() instead setValue().
629
                                // Important: Don't validate the input, because the other object types might not be initialized yet! So use setValueNoCallback() instead setValue().
590
                                OIDplus::config()->setValueNoCallback("objecttypes_enabled", implode(';', $enabled_ary));
630
                                OIDplus::config()->setValueNoCallback("objecttypes_enabled", implode(';', $enabled_ary));
591
                        }
631
                        }
592
 
632
 
593
                        $init_ary[] = $ns;
633
                        $init_ary[] = $ns;
594
                        OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
634
                        OIDplus::config()->setValue("objecttypes_initialized", implode(';', $init_ary));
595
                }
635
                }
596
        }
636
        }
597
 
637
 
598
        public static function getObjectTypePlugins() {
638
        public static function getObjectTypePlugins() {
599
                return self::$objectTypePlugins;
639
                return self::$objectTypePlugins;
600
        }
640
        }
601
 
641
 
602
        public static function getObjectTypePluginsEnabled() {
642
        public static function getObjectTypePluginsEnabled() {
603
                $res = array();
643
                $res = array();
604
                foreach (self::$objectTypePlugins as $plugin) {
644
                foreach (self::$objectTypePlugins as $plugin) {
605
                        $ot = $plugin::getObjectTypeClassName();
645
                        $ot = $plugin::getObjectTypeClassName();
606
                        if (in_array($ot, self::$enabledObjectTypes)) $res[] = $plugin;
646
                        if (in_array($ot, self::$enabledObjectTypes)) $res[] = $plugin;
607
                }
647
                }
608
                return $res;
648
                return $res;
609
        }
649
        }
610
 
650
 
611
        public static function getObjectTypePluginsDisabled() {
651
        public static function getObjectTypePluginsDisabled() {
612
                $res = array();
652
                $res = array();
613
                foreach (self::$objectTypePlugins as $plugin) {
653
                foreach (self::$objectTypePlugins as $plugin) {
614
                        $ot = $plugin::getObjectTypeClassName();
654
                        $ot = $plugin::getObjectTypeClassName();
615
                        if (in_array($ot, self::$disabledObjectTypes)) $res[] = $plugin;
655
                        if (in_array($ot, self::$disabledObjectTypes)) $res[] = $plugin;
616
                }
656
                }
617
                return $res;
657
                return $res;
618
        }
658
        }
619
 
659
 
620
        public static function getEnabledObjectTypes() {
660
        public static function getEnabledObjectTypes() {
621
                return self::$enabledObjectTypes;
661
                return self::$enabledObjectTypes;
622
        }
662
        }
623
 
663
 
624
        public static function getDisabledObjectTypes() {
664
        public static function getDisabledObjectTypes() {
625
                return self::$disabledObjectTypes;
665
                return self::$disabledObjectTypes;
626
        }
666
        }
627
 
667
 
628
        # --- Plugin handling functions
668
        // --- Plugin handling functions
629
 
669
 
630
        public static function getAllPlugins()/*: array*/ {
670
        public static function getAllPlugins()/*: array*/ {
631
                $res = array();
671
                $res = array();
632
                $res = array_merge($res, self::$pagePlugins);
672
                $res = array_merge($res, self::$pagePlugins);
633
                $res = array_merge($res, self::$authPlugins);
673
                $res = array_merge($res, self::$authPlugins);
634
                $res = array_merge($res, self::$loggerPlugins);
674
                $res = array_merge($res, self::$loggerPlugins);
635
                $res = array_merge($res, self::$objectTypePlugins);
675
                $res = array_merge($res, self::$objectTypePlugins);
636
                $res = array_merge($res, self::$dbPlugins);
676
                $res = array_merge($res, self::$dbPlugins);
637
                $res = array_merge($res, self::$captchaPlugins);
677
                $res = array_merge($res, self::$captchaPlugins);
638
                $res = array_merge($res, self::$sqlSlangPlugins);
678
                $res = array_merge($res, self::$sqlSlangPlugins);
639
                $res = array_merge($res, self::$languagePlugins);
679
                $res = array_merge($res, self::$languagePlugins);
640
                $res = array_merge($res, self::$designPlugins);
680
                $res = array_merge($res, self::$designPlugins);
641
                return $res;
681
                return $res;
642
        }
682
        }
643
 
683
 
644
        public static function getPluginByOid($oid)/*: ?OIDplusPlugin*/ {
684
        public static function getPluginByOid($oid)/*: ?OIDplusPlugin*/ {
645
                $plugins = self::getAllPlugins();
685
                $plugins = self::getAllPlugins();
646
                foreach ($plugins as $plugin) {
686
                foreach ($plugins as $plugin) {
647
                        if (oid_dotnotation_equal($plugin->getManifest()->getOid(), $oid)) {
687
                        if (oid_dotnotation_equal($plugin->getManifest()->getOid(), $oid)) {
648
                                return $plugin;
688
                                return $plugin;
649
                        }
689
                        }
650
                }
690
                }
651
                return null;
691
                return null;
652
        }
692
        }
653
 
693
 
654
        public static function getPluginByClassName($classname)/*: ?OIDplusPlugin*/ {
694
        public static function getPluginByClassName($classname)/*: ?OIDplusPlugin*/ {
655
                $plugins = self::getAllPlugins();
695
                $plugins = self::getAllPlugins();
656
                foreach ($plugins as $plugin) {
696
                foreach ($plugins as $plugin) {
657
                        if (get_class($plugin) === $classname) {
697
                        if (get_class($plugin) === $classname) {
658
                                return $plugin;
698
                                return $plugin;
659
                        }
699
                        }
660
                }
700
                }
661
                return null;
701
                return null;
662
        }
702
        }
663
 
703
 
664
        /**
704
        /**
-
 
705
        * Checks if the plugin is disabled
-
 
706
        * @return boolean true if plugin is enabled, false if plugin is disabled
-
 
707
        * @throws OIDplusException if the class name or config file (disabled setting) does not contain a namespace
-
 
708
        */
-
 
709
        private static function pluginCheckDisabled($class_name): bool {
-
 
710
                $path = explode('\\', $class_name);
-
 
711
 
-
 
712
                if (count($path) == 1) {
-
 
713
                        throw new OIDplusException(_L('Plugin "%1" is erroneous',$class_name).': '._L('The plugin uses no namespaces. The new version of OIDplus requires plugin class files to be in a namespace. Please notify your plugin author and ask for an update.'));
-
 
714
                }
-
 
715
 
-
 
716
                $class_end = end($path);
-
 
717
                if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_end, false)) {
-
 
718
                        throw new OIDplusConfigInitializationException(_L('Your base configuration file is outdated. Please change "%1" to "%2".','DISABLE_PLUGIN_'.$class_end,'DISABLE_PLUGIN_'.$class_name));
-
 
719
                }
-
 
720
 
-
 
721
                if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
-
 
722
                        return false;
-
 
723
                }
-
 
724
 
-
 
725
                return true;
-
 
726
        }
-
 
727
 
-
 
728
        /**
665
        * @return array<OIDplusPluginManifest>|array<string,array<string,OIDplusPluginManifest>>
729
        * @return array<OIDplusPluginManifest>|array<string,array<string,OIDplusPluginManifest>>
666
        */
730
        */
667
        public static function getAllPluginManifests($pluginFolderMasks='*', $flat=true): array {
731
        public static function getAllPluginManifests($pluginFolderMasks='*', $flat=true): array {
668
                $out = array();
732
                $out = array();
669
                // Note: glob() will sort by default, so we do not need a page priority attribute.
733
                // Note: glob() will sort by default, so we do not need a page priority attribute.
670
                //       So you just need to use a numeric plugin directory prefix (padded).
734
                //       So you just need to use a numeric plugin directory prefix (padded).
671
                $ary = array();
735
                $ary = array();
672
                foreach (explode(',',$pluginFolderMasks) as $pluginFolderMask) {
736
                foreach (explode(',',$pluginFolderMasks) as $pluginFolderMask) {
673
                        $ary = array_merge($ary,glob(OIDplus::localpath().'plugins/'.'*'.'/'.$pluginFolderMask.'/'.'*'.'/manifest.xml'));
737
                        $ary = array_merge($ary,glob(OIDplus::localpath().'plugins/'.'*'.'/'.$pluginFolderMask.'/'.'*'.'/manifest.xml'));
674
                }
738
                }
675
 
739
 
676
                // Sort the plugins by their type and name, as if they would be in a single vendor-folder!
740
                // Sort the plugins by their type and name, as if they would be in a single vendor-folder!
677
                uasort($ary, function($a,$b) {
741
                uasort($ary, function($a,$b) {
678
                        if ($a == $b) return 0;
742
                        if ($a == $b) return 0;
679
 
743
 
680
                        $ary = explode('/',$a);
744
                        $ary = explode('/',$a);
681
                        $bry = explode('/',$b);
745
                        $bry = explode('/',$b);
682
 
746
 
683
                        // First sort by type (publicPage, auth, database, language, ...)
747
                        // First sort by type (publicPage, auth, database, language, ...)
684
                        $a_type = $ary[count($ary)-1-2];
748
                        $a_type = $ary[count($ary)-1-2];
685
                        $b_type = $bry[count($bry)-1-2];
749
                        $b_type = $bry[count($bry)-1-2];
686
                        if ($a_type < $b_type) return -1;
750
                        if ($a_type < $b_type) return -1;
687
                        if ($a_type > $b_type) return 1;
751
                        if ($a_type > $b_type) return 1;
688
 
752
 
689
                        // Then sort by name (090_login, 100_whois, etc.)
753
                        // Then sort by name (090_login, 100_whois, etc.)
690
                        $a_name = $ary[count($ary)-1-1];
754
                        $a_name = $ary[count($ary)-1-1];
691
                        $b_name = $bry[count($bry)-1-1];
755
                        $b_name = $bry[count($bry)-1-1];
692
                        if ($a_name < $b_name) return -1;
756
                        if ($a_name < $b_name) return -1;
693
                        if ($a_name > $b_name) return 1;
757
                        if ($a_name > $b_name) return 1;
694
 
758
 
695
                        // If it is still equal, then finally sort by vendorname
759
                        // If it is still equal, then finally sort by vendorname
696
                        $a_vendor = $ary[count($ary)-1-3];
760
                        $a_vendor = $ary[count($ary)-1-3];
697
                        $b_vendor = $bry[count($bry)-1-3];
761
                        $b_vendor = $bry[count($bry)-1-3];
698
                        if ($a_vendor < $b_vendor) return -1;
762
                        if ($a_vendor < $b_vendor) return -1;
699
                        if ($a_vendor > $b_vendor) return 1;
763
                        if ($a_vendor > $b_vendor) return 1;
700
                        return 0;
764
                        return 0;
701
                });
765
                });
702
 
766
 
703
                foreach ($ary as $ini) {
767
                foreach ($ary as $ini) {
704
                        if (!file_exists($ini)) continue;
768
                        if (!file_exists($ini)) continue;
705
 
769
 
706
                        $manifest = new OIDplusPluginManifest();
770
                        $manifest = new OIDplusPluginManifest();
707
                        $manifest->loadManifest($ini);
771
                        $manifest->loadManifest($ini);
708
 
772
 
709
                        $class_name = $manifest->getPhpMainClass();
773
                        $class_name = $manifest->getPhpMainClass();
710
                        if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
774
                        if ($class_name) if (!self::pluginCheckDisabled($class_name)) continue;
711
                                continue;
-
 
712
                        }
-
 
713
 
775
 
714
                        if ($flat) {
776
                        if ($flat) {
715
                                $out[] = $manifest;
777
                                $out[] = $manifest;
716
                        } else {
778
                        } else {
717
                                $plugintype_folder = basename(dirname(dirname($ini)));
779
                                $plugintype_folder = basename(dirname(dirname($ini)));
718
                                $pluginname_folder = basename(dirname($ini));
780
                                $pluginname_folder = basename(dirname($ini));
719
 
781
 
720
                                if (!isset($out[$plugintype_folder])) $out[$plugintype_folder] = array();
782
                                if (!isset($out[$plugintype_folder])) $out[$plugintype_folder] = array();
721
                                if (!isset($out[$plugintype_folder][$pluginname_folder])) $out[$plugintype_folder][$pluginname_folder] = array();
783
                                if (!isset($out[$plugintype_folder][$pluginname_folder])) $out[$plugintype_folder][$pluginname_folder] = array();
722
                                $out[$plugintype_folder][$pluginname_folder] = $manifest;
784
                                $out[$plugintype_folder][$pluginname_folder] = $manifest;
723
                        }
785
                        }
724
                }
786
                }
725
                return $out;
787
                return $out;
726
        }
788
        }
727
 
789
 
728
        /**
790
        /**
729
        * @return array<string>
791
        * @return array<string>
730
        */
792
        */
731
        public static function registerAllPlugins($pluginDirName, $expectedPluginClass, $registerCallback): array {
793
        public static function registerAllPlugins($pluginDirName, $expectedPluginClass, $registerCallback): array {
732
                $out = array();
794
                $out = array();
733
                if (is_array($pluginDirName)) {
795
                if (is_array($pluginDirName)) {
734
                        $ary = array();
796
                        $ary = array();
735
                        foreach ($pluginDirName as $pluginDirName_) {
797
                        foreach ($pluginDirName as $pluginDirName_) {
736
                                $ary = array_merge($ary, self::getAllPluginManifests($pluginDirName_, false));
798
                                $ary = array_merge($ary, self::getAllPluginManifests($pluginDirName_, false));
737
                        }
799
                        }
738
                } else {
800
                } else {
739
                        $ary = self::getAllPluginManifests($pluginDirName, false);
801
                        $ary = self::getAllPluginManifests($pluginDirName, false);
740
                }
802
                }
741
                $known_plugin_oids = array();
803
                $known_plugin_oids = array();
742
                if (OIDplus::baseConfig()->getValue('DEBUG')) {
804
                if (OIDplus::baseConfig()->getValue('DEBUG')) {
743
                        $fake_feature = uuid_to_oid(gen_uuid());
805
                        $fake_feature = uuid_to_oid(gen_uuid());
744
                } else {
806
                } else {
745
                        $fake_feature = null;
807
                        $fake_feature = null;
746
                }
808
                }
747
                foreach ($ary as $plugintype_folder => $bry) {
809
                foreach ($ary as $plugintype_folder => $bry) {
748
                        foreach ($bry as $pluginname_folder => $manifest) {
810
                        foreach ($bry as $pluginname_folder => $manifest) {
749
                                $class_name = $manifest->getPhpMainClass();
811
                                $class_name = $manifest->getPhpMainClass();
750
 
812
 
751
                                // Before we load the plugin, we want to make some checks to confirm
813
                                // Before we load the plugin, we want to make some checks to confirm
752
                                // that the plugin is working correctly.
814
                                // that the plugin is working correctly.
753
 
815
 
754
                                if (!$class_name) {
816
                                if (!$class_name) {
755
                                        throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Manifest does not declare a PHP main class'));
817
                                        throw new OIDplusException(_L('Plugin "%1" is erroneous',$plugintype_folder.'/'.$pluginname_folder).': '._L('Manifest does not declare a PHP main class'));
756
                                }
818
                                }
757
                                if (OIDplus::baseConfig()->getValue('DISABLE_PLUGIN_'.$class_name, false)) {
819
                                if (!self::pluginCheckDisabled($class_name)) {
758
                                        continue;
820
                                        continue; // Plugin is disabled
759
                                }
821
                                }
760
                                if (!class_exists($class_name)) {
822
                                if (!class_exists($class_name)) {
761
                                        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));
823
                                        throw new OIDplusException(_L('Plugin "%1" is erroneous',$plugintype_folder.'/'.$pluginname_folder).': '._L('Manifest declares PHP main class as "%1", but it could not be found',$class_name));
762
                                }
824
                                }
763
                                if (!is_subclass_of($class_name, $expectedPluginClass)) {
825
                                if (!is_subclass_of($class_name, $expectedPluginClass)) {
764
                                        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));
826
                                        throw new OIDplusException(_L('Plugin "%1" is erroneous',$plugintype_folder.'/'.$pluginname_folder).': '._L('Plugin main class "%1" is expected to be a subclass of "%2"',$class_name,$expectedPluginClass));
765
                                }
827
                                }
766
                                if (($class_name!=$manifest->getTypeClass()) && (!is_subclass_of($class_name,$manifest->getTypeClass()))) {
828
                                if (($class_name!=$manifest->getTypeClass()) && (!is_subclass_of($class_name,$manifest->getTypeClass()))) {
767
                                        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()));
829
                                        throw new OIDplusException(_L('Plugin "%1" 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()));
768
                                }
830
                                }
769
                                if (($manifest->getTypeClass()!=$expectedPluginClass) && (!is_subclass_of($manifest->getTypeClass(),$expectedPluginClass))) {
831
                                if (($manifest->getTypeClass()!=$expectedPluginClass) && (!is_subclass_of($manifest->getTypeClass(),$expectedPluginClass))) {
770
                                        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));
832
                                        throw new OIDplusException(_L('Plugin "%1" 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));
771
                                }
833
                                }
772
 
834
 
773
                                $plugin_oid = $manifest->getOid();
835
                                $plugin_oid = $manifest->getOid();
774
                                if (!$plugin_oid) {
836
                                if (!$plugin_oid) {
775
                                        throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('Does not have an OID'));
837
                                        throw new OIDplusException(_L('Plugin "%1" is erroneous',$plugintype_folder.'/'.$pluginname_folder).': '._L('Does not have an OID'));
776
                                }
838
                                }
777
                                if (!oid_valid_dotnotation($plugin_oid, false, false, 2)) {
839
                                if (!oid_valid_dotnotation($plugin_oid, false, false, 2)) {
778
                                        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));
840
                                        throw new OIDplusException(_L('Plugin "%1" is erroneous',$plugintype_folder.'/'.$pluginname_folder).': '._L('Plugin OID "%1" is invalid (needs to be valid dot-notation)',$plugin_oid));
779
                                }
841
                                }
780
                                if (isset($known_plugin_oids[$plugin_oid])) {
842
                                if (isset($known_plugin_oids[$plugin_oid])) {
781
                                        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]));
843
                                        throw new OIDplusException(_L('Plugin "%1" is erroneous',$plugintype_folder.'/'.$pluginname_folder).': '._L('The OID "%1" is already used by the plugin "%2"',$plugin_oid,$known_plugin_oids[$plugin_oid]));
782
                                }
844
                                }
783
 
845
 
784
                                $full_plugin_dir = dirname($manifest->getManifestFile());
846
                                $full_plugin_dir = dirname($manifest->getManifestFile());
785
                                $full_plugin_dir = substr($full_plugin_dir, strlen(OIDplus::localpath()));
847
                                $full_plugin_dir = substr($full_plugin_dir, strlen(OIDplus::localpath()));
786
 
848
 
787
                                $dir_is_viathinksoft = str_starts_with($full_plugin_dir, 'plugins/viathinksoft/') || str_starts_with($full_plugin_dir, 'plugins\\viathinksoft\\');
849
                                $dir_is_viathinksoft = str_starts_with($full_plugin_dir, 'plugins/viathinksoft/') || str_starts_with($full_plugin_dir, 'plugins\\viathinksoft\\');
788
                                $oid_is_viathinksoft = str_starts_with($plugin_oid, '1.3.6.1.4.1.37476.2.5.2.4.'); // { iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) 37476 products(2) oidplus(5) v2(2) plugins(4) }
850
                                $oid_is_viathinksoft = str_starts_with($plugin_oid, '1.3.6.1.4.1.37476.2.5.2.4.'); // { iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) 37476 products(2) oidplus(5) v2(2) plugins(4) }
-
 
851
                                $class_is_viathinksoft = str_starts_with($class_name, 'ViaThinkSoft\\');
789
                                if ($dir_is_viathinksoft != $oid_is_viathinksoft) {
852
                                if ($dir_is_viathinksoft != $oid_is_viathinksoft) {
790
                                        throw new OIDplusException(_L('Plugin "%1/%2" is misplaced',$plugintype_folder,$pluginname_folder).': '._L('The plugin is in the wrong folder. The folder %1 can only be used by official ViaThinkSoft plugins','plugins/viathinksoft/'));
853
                                        throw new OIDplusException(_L('Plugin "%1" is misplaced',$plugintype_folder.'/'.$pluginname_folder).': '._L('The plugin is in the wrong folder. The folder %1 can only be used by official ViaThinkSoft plugins','plugins/viathinksoft/'));
-
 
854
                                }
-
 
855
                                if ($dir_is_viathinksoft != $class_is_viathinksoft) {
-
 
856
                                        throw new OIDplusException(_L('Plugin "%1" is erroneous',$plugintype_folder.'/'.$pluginname_folder).': '._L('Third-party plugins must not use the ViaThinkSoft PHP namespace. Please use your own vendor namespace.'));
791
                                }
857
                                }
792
 
858
 
793
                                $known_plugin_oids[$plugin_oid] = $plugintype_folder.'/'.$pluginname_folder;
859
                                $known_plugin_oids[$plugin_oid] = $plugintype_folder.'/'.$pluginname_folder;
794
 
860
 
795
                                $obj = new $class_name();
861
                                $obj = new $class_name();
796
 
862
 
797
                                if (OIDplus::baseConfig()->getValue('DEBUG')) {
863
                                if (OIDplus::baseConfig()->getValue('DEBUG')) {
798
                                        if ($obj->implementsFeature($fake_feature)) {
864
                                        if ($obj->implementsFeature($fake_feature)) {
799
                                                // see https://devblogs.microsoft.com/oldnewthing/20040211-00/?p=40663
865
                                                // see https://devblogs.microsoft.com/oldnewthing/20040211-00/?p=40663
800
                                                throw new OIDplusException(_L('Plugin "%1/%2" is erroneous',$plugintype_folder,$pluginname_folder).': '._L('implementsFeature() always returns true'));
866
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous',$plugintype_folder.'/'.$pluginname_folder).': '._L('implementsFeature() always returns true'));
801
                                        }
867
                                        }
802
                                }
868
                                }
803
 
869
 
804
                                // TODO: Maybe as additional plugin-test, we should also check if plugins are allowed to define CSS/JS, i.e. the plugin type is element of OIDplus::INTERACTIVE_PLUGIN_TYPES
870
                                // TODO: Maybe as additional plugin-test, we should also check if plugins are allowed to define CSS/JS, i.e. the plugin type is element of OIDplus::INTERACTIVE_PLUGIN_TYPES
805
                                $tmp = $manifest->getManifestLinkedFiles();
871
                                $tmp = $manifest->getManifestLinkedFiles();
806
                                foreach ($tmp as $file) {
872
                                foreach ($tmp as $file) {
807
                                        if (!file_exists($file)) {
873
                                        if (!file_exists($file)) {
808
                                                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));
874
                                                throw new OIDplusException(_L('Plugin "%1" is erroneous',$plugintype_folder.'/'.$pluginname_folder).': '._L('File %1 was defined in manifest, but it is not existing',$file));
809
                                        }
875
                                        }
810
                                }
876
                                }
811
 
877
 
812
                                // Now we can continue
878
                                // Now we can continue
813
 
879
 
814
                                $out[] = $class_name;
880
                                $out[] = $class_name;
815
                                if (!is_null($registerCallback)) {
881
                                if (!is_null($registerCallback)) {
816
                                        call_user_func($registerCallback, $obj);
882
                                        call_user_func($registerCallback, $obj);
817
 
883
 
818
                                        // Alternative approaches:
884
                                        // Alternative approaches:
819
                                        //$registerCallback[0]::{$registerCallback[1]}($obj);
885
                                        //$registerCallback[0]::{$registerCallback[1]}($obj);
820
                                        // or:
886
                                        // or:
821
                                        //forward_static_call($registerCallback, $obj);
887
                                        //forward_static_call($registerCallback, $obj);
822
                                }
888
                                }
823
                        }
889
                        }
824
 
890
 
825
                }
891
                }
826
                return $out;
892
                return $out;
827
        }
893
        }
828
 
894
 
829
        # --- Initialization of OIDplus
895
        // --- Initialization of OIDplus
830
 
896
 
831
        public static function init($html=true, $keepBaseConfig=true) {
897
        public static function init($html=true, $keepBaseConfig=true) {
832
                self::$html = $html;
898
                self::$html = $html;
833
 
899
 
834
                // Reset internal state, so we can re-init verything if required
900
                // Reset internal state, so we can re-init verything if required
835
 
901
 
836
                if (self::$old_config_format) {
-
 
837
                        // We need to do this, because define() cannot be undone
-
 
838
                        // Note: This can only happen in very special cases (e.g. test cases) where you call init() twice
-
 
839
                        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.'));
-
 
840
                }
-
 
841
 
-
 
842
                self::$config = null;
902
                self::$config = null;
843
                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
903
                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
844
                self::$gui = null;
904
                self::$gui = null;
845
                self::$authUtils = null;
905
                self::$authUtils = null;
846
                self::$mailUtils = null;
906
                self::$mailUtils = null;
847
                self::$menuUtils = null;
907
                self::$menuUtils = null;
848
                self::$logger = null;
908
                self::$logger = null;
849
                self::$dbMainSession = null;
909
                self::$dbMainSession = null;
850
                self::$dbIsolatedSession = null;
910
                self::$dbIsolatedSession = null;
851
                self::$pagePlugins = array();
911
                self::$pagePlugins = array();
852
                self::$authPlugins = array();
912
                self::$authPlugins = array();
853
                self::$loggerPlugins = array();
913
                self::$loggerPlugins = array();
854
                self::$objectTypePlugins = array();
914
                self::$objectTypePlugins = array();
855
                self::$enabledObjectTypes = array();
915
                self::$enabledObjectTypes = array();
856
                self::$disabledObjectTypes = array();
916
                self::$disabledObjectTypes = array();
857
                self::$dbPlugins = array();
917
                self::$dbPlugins = array();
858
                self::$captchaPlugins = array();
918
                self::$captchaPlugins = array();
859
                self::$sqlSlangPlugins = array();
919
                self::$sqlSlangPlugins = array();
860
                self::$languagePlugins = array();
920
                self::$languagePlugins = array();
861
                self::$designPlugins = array();
921
                self::$designPlugins = array();
862
                self::$system_id_cache = null;
922
                self::$system_id_cache = null;
863
                self::$sslAvailableCache = null;
923
                self::$sslAvailableCache = null;
864
                self::$translationArray = array();
924
                self::$translationArray = array();
865
 
925
 
866
                // Continue...
926
                // Continue...
867
 
927
 
868
                OIDplus::baseConfig(); // this loads the base configuration located in userdata/baseconfig/config.inc.php (once!)
928
                OIDplus::baseConfig(); // this loads the base configuration located in userdata/baseconfig/config.inc.php (once!)
869
                                       // You can do changes to the configuration afterwards using OIDplus::baseConfig()->...
929
                                       // You can do changes to the configuration afterwards using OIDplus::baseConfig()->...
870
 
930
 
871
                // Register database types (highest priority)
931
                // Register database types (highest priority)
872
 
932
 
873
                // SQL slangs
933
                // SQL slangs
874
 
934
 
875
                self::registerAllPlugins('sqlSlang', 'OIDplusSqlSlangPlugin', array('OIDplus','registerSqlSlangPlugin'));
935
                self::registerAllPlugins('sqlSlang', OIDplusSqlSlangPlugin::class, array(OIDplus::class,'registerSqlSlangPlugin'));
876
                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
936
                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
877
                        $plugin->init($html);
937
                        $plugin->init($html);
878
                }
938
                }
879
 
939
 
880
                // Database providers
940
                // Database providers
881
 
941
 
882
                self::registerAllPlugins('database', 'OIDplusDatabasePlugin', array('OIDplus','registerDatabasePlugin'));
942
                self::registerAllPlugins('database', OIDplusDatabasePlugin::class, array(OIDplus::class,'registerDatabasePlugin'));
883
                foreach (OIDplus::getDatabasePlugins() as $plugin) {
943
                foreach (OIDplus::getDatabasePlugins() as $plugin) {
884
                        $plugin->init($html);
944
                        $plugin->init($html);
885
                }
945
                }
886
 
946
 
887
                // Do redirect stuff etc.
947
                // Do redirect stuff etc.
888
 
948
 
889
                self::isSslAvailable(); // This function does automatic redirects
949
                self::isSslAvailable(); // This function does automatic redirects
890
 
950
 
891
                // Construct the configuration manager
951
                // Construct the configuration manager
892
 
952
 
893
                OIDplus::config(); // During the construction, various system settings are prepared if required
953
                OIDplus::config(); // During the construction, various system settings are prepared if required
894
 
954
 
895
                // Initialize public / private keys
955
                // Initialize public / private keys
896
 
956
 
897
                OIDplus::getPkiStatus(true);
957
                OIDplus::getPkiStatus(true);
898
 
958
 
899
                // Register non-DB plugins
959
                // Register non-DB plugins
900
 
960
 
901
                self::registerAllPlugins(array('publicPages', 'raPages', 'adminPages'), 'OIDplusPagePlugin', array('OIDplus','registerPagePlugin'));
961
                self::registerAllPlugins(array('publicPages', 'raPages', 'adminPages'), OIDplusPagePlugin::class, array(OIDplus::class,'registerPagePlugin'));
902
                self::registerAllPlugins('auth', 'OIDplusAuthPlugin', array('OIDplus','registerAuthPlugin'));
962
                self::registerAllPlugins('auth', OIDplusAuthPlugin::class, array(OIDplus::class,'registerAuthPlugin'));
903
                self::registerAllPlugins('logger', 'OIDplusLoggerPlugin', array('OIDplus','registerLoggerPlugin'));
963
                self::registerAllPlugins('logger', OIDplusLoggerPlugin::class, array(OIDplus::class,'registerLoggerPlugin'));
904
                OIDplusLogger::reLogMissing(); // Some previous plugins might have tried to log. Repeat that now.
964
                OIDplusLogger::reLogMissing(); // Some previous plugins might have tried to log. Repeat that now.
905
                self::registerAllPlugins('objectTypes', 'OIDplusObjectTypePlugin', array('OIDplus','registerObjectTypePlugin'));
965
                self::registerAllPlugins('objectTypes', OIDplusObjectTypePlugin::class, array(OIDplus::class,'registerObjectTypePlugin'));
906
                self::registerAllPlugins('language', 'OIDplusLanguagePlugin', array('OIDplus','registerLanguagePlugin'));
966
                self::registerAllPlugins('language', OIDplusLanguagePlugin::class, array(OIDplus::class,'registerLanguagePlugin'));
907
                self::registerAllPlugins('design', 'OIDplusDesignPlugin', array('OIDplus','registerDesignPlugin'));
967
                self::registerAllPlugins('design', OIDplusDesignPlugin::class, array(OIDplus::class,'registerDesignPlugin'));
908
                self::registerAllPlugins('captcha', 'OIDplusCaptchaPlugin', array('OIDplus','registerCaptchaPlugin'));
968
                self::registerAllPlugins('captcha', OIDplusCaptchaPlugin::class, array(OIDplus::class,'registerCaptchaPlugin'));
909
 
969
 
910
                // Initialize non-DB plugins
970
                // Initialize non-DB plugins
911
 
971
 
912
                foreach (OIDplus::getPagePlugins() as $plugin) {
972
                foreach (OIDplus::getPagePlugins() as $plugin) {
913
                        $plugin->init($html);
973
                        $plugin->init($html);
914
                }
974
                }
915
                foreach (OIDplus::getAuthPlugins() as $plugin) {
975
                foreach (OIDplus::getAuthPlugins() as $plugin) {
916
                        $plugin->init($html);
976
                        $plugin->init($html);
917
                }
977
                }
918
                foreach (OIDplus::getLoggerPlugins() as $plugin) {
978
                foreach (OIDplus::getLoggerPlugins() as $plugin) {
919
                        $plugin->init($html);
979
                        $plugin->init($html);
920
                }
980
                }
921
                foreach (OIDplus::getObjectTypePlugins() as $plugin) {
981
                foreach (OIDplus::getObjectTypePlugins() as $plugin) {
922
                        $plugin->init($html);
982
                        $plugin->init($html);
923
                }
983
                }
924
                foreach (OIDplus::getLanguagePlugins() as $plugin) {
984
                foreach (OIDplus::getLanguagePlugins() as $plugin) {
925
                        $plugin->init($html);
985
                        $plugin->init($html);
926
                }
986
                }
927
                foreach (OIDplus::getDesignPlugins() as $plugin) {
987
                foreach (OIDplus::getDesignPlugins() as $plugin) {
928
                        $plugin->init($html);
988
                        $plugin->init($html);
929
                }
989
                }
930
                foreach (OIDplus::getCaptchaPlugins() as $plugin) {
990
                foreach (OIDplus::getCaptchaPlugins() as $plugin) {
931
                        $plugin->init($html);
991
                        $plugin->init($html);
932
                }
992
                }
933
 
993
 
934
                if (PHP_SAPI != 'cli') {
994
                if (PHP_SAPI != 'cli') {
935
 
995
 
936
                        // Prepare some security related response headers (default values)
996
                        // Prepare some security related response headers (default values)
937
 
997
 
938
                        $content_language =
998
                        $content_language =
939
                                strtolower(substr(OIDplus::getCurrentLang(),0,2)) . '-' .
999
                                strtolower(substr(OIDplus::getCurrentLang(),0,2)) . '-' .
940
                                strtoupper(substr(OIDplus::getCurrentLang(),2,2)); // e.g. 'en-US'
1000
                                strtoupper(substr(OIDplus::getCurrentLang(),2,2)); // e.g. 'en-US'
941
 
1001
 
942
                        $http_headers = array(
1002
                        $http_headers = array(
943
                                "X-Content-Type-Options" => "nosniff",
1003
                                "X-Content-Type-Options" => "nosniff",
944
                                "X-XSS-Protection" => "1; mode=block",
1004
                                "X-XSS-Protection" => "1; mode=block",
945
                                "X-Frame-Options" => "SAMEORIGIN",
1005
                                "X-Frame-Options" => "SAMEORIGIN",
946
                                "Referrer-Policy" => array(
1006
                                "Referrer-Policy" => array(
947
                                        "no-referrer-when-downgrade"
1007
                                        "no-referrer-when-downgrade"
948
                                ),
1008
                                ),
949
                                "Cache-Control" => array(
1009
                                "Cache-Control" => array(
950
                                        "no-cache",
1010
                                        "no-cache",
951
                                        "no-store",
1011
                                        "no-store",
952
                                        "must-revalidate"
1012
                                        "must-revalidate"
953
                                ),
1013
                                ),
954
                                "Pragma" => "no-cache",
1014
                                "Pragma" => "no-cache",
955
                                "Content-Language" => $content_language,
1015
                                "Content-Language" => $content_language,
956
                                "Expires" => "0",
1016
                                "Expires" => "0",
957
                                "Content-Security-Policy" => array(
1017
                                "Content-Security-Policy" => array(
958
                                        // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
1018
                                        // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
959
 
1019
 
960
                                        // --- Fetch directives ---
1020
                                        // --- Fetch directives ---
961
                                        "child-src" => array(
1021
                                        "child-src" => array(
962
                                                "'self'",
1022
                                                "'self'",
963
                                                "blob:"
1023
                                                "blob:"
964
                                        ),
1024
                                        ),
965
                                        "connect-src" => array(
1025
                                        "connect-src" => array(
966
                                                "'self'",
1026
                                                "'self'",
967
                                                "blob:"
1027
                                                "blob:"
968
                                        ),
1028
                                        ),
969
                                        "default-src" => array(
1029
                                        "default-src" => array(
970
                                                "'self'",
1030
                                                "'self'",
971
                                                "blob:",
1031
                                                "blob:",
972
                                                "https://cdnjs.cloudflare.com/"
1032
                                                "https://cdnjs.cloudflare.com/"
973
                                        ),
1033
                                        ),
974
                                        "font-src" => array(
1034
                                        "font-src" => array(
975
                                                "'self'",
1035
                                                "'self'",
976
                                                "blob:"
1036
                                                "blob:"
977
                                        ),
1037
                                        ),
978
                                        "frame-src" => array(
1038
                                        "frame-src" => array(
979
                                                "'self'",
1039
                                                "'self'",
980
                                                "blob:"
1040
                                                "blob:"
981
                                        ),
1041
                                        ),
982
                                        "img-src" => array(
1042
                                        "img-src" => array(
983
                                                "blob:",
1043
                                                "blob:",
984
                                                "data:",
1044
                                                "data:",
985
                                                "http:",
1045
                                                "http:",
986
                                                "https:"
1046
                                                "https:"
987
                                        ),
1047
                                        ),
988
                                        "manifest-src" => array(
1048
                                        "manifest-src" => array(
989
                                                "'self'",
1049
                                                "'self'",
990
                                                "blob:"
1050
                                                "blob:"
991
                                        ),
1051
                                        ),
992
                                        "media-src" => array(
1052
                                        "media-src" => array(
993
                                                "'self'",
1053
                                                "'self'",
994
                                                "blob:"
1054
                                                "blob:"
995
                                        ),
1055
                                        ),
996
                                        "object-src" => array(
1056
                                        "object-src" => array(
997
                                                "'none'"
1057
                                                "'none'"
998
                                        ),
1058
                                        ),
999
                                        "prefetch-src" => array(
1059
                                        "prefetch-src" => array(
1000
                                                "'self'",
1060
                                                "'self'",
1001
                                                "blob:"
1061
                                                "blob:"
1002
                                        ),
1062
                                        ),
1003
                                        "script-src" => array(
1063
                                        "script-src" => array(
1004
                                                "'self'",
1064
                                                "'self'",
1005
                                                "'unsafe-inline'",
1065
                                                "'unsafe-inline'",
1006
                                                "'unsafe-eval'",
1066
                                                "'unsafe-eval'",
1007
                                                "blob:",
1067
                                                "blob:",
1008
                                                "https://cdnjs.cloudflare.com/",
1068
                                                "https://cdnjs.cloudflare.com/",
1009
                                                "https://polyfill.io/"
1069
                                                "https://polyfill.io/"
1010
                                        ),
1070
                                        ),
1011
                                        // script-src-elem not used
1071
                                        // script-src-elem not used
1012
                                        // script-src-attr not used
1072
                                        // script-src-attr not used
1013
                                        "style-src" => array(
1073
                                        "style-src" => array(
1014
                                                "'self'",
1074
                                                "'self'",
1015
                                                "'unsafe-inline'",
1075
                                                "'unsafe-inline'",
1016
                                                "https://cdnjs.cloudflare.com/"
1076
                                                "https://cdnjs.cloudflare.com/"
1017
                                        ),
1077
                                        ),
1018
                                        // style-src-elem not used
1078
                                        // style-src-elem not used
1019
                                        // style-src-attr not used
1079
                                        // style-src-attr not used
1020
                                        "worker-src" => array(
1080
                                        "worker-src" => array(
1021
                                                "'self'",
1081
                                                "'self'",
1022
                                                "blob:"
1082
                                                "blob:"
1023
                                        ),
1083
                                        ),
1024
 
1084
 
1025
                                        // --- Navigation directives ---
1085
                                        // --- Navigation directives ---
1026
                                        "frame-ancestors" => array(
1086
                                        "frame-ancestors" => array(
1027
                                               "'none'"
1087
                                               "'none'"
1028
                                        ),
1088
                                        ),
1029
                                )
1089
                                )
1030
                        );
1090
                        );
1031
 
1091
 
1032
                        // Give plugins the opportunity to manipulate/extend the headers
1092
                        // Give plugins the opportunity to manipulate/extend the headers
1033
 
1093
 
1034
                        foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
1094
                        foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
1035
                                $plugin->httpHeaderCheck($http_headers);
1095
                                $plugin->httpHeaderCheck($http_headers);
1036
                        }
1096
                        }
1037
                        //foreach (OIDplus::getDatabasePlugins() as $plugin) {
1097
                        //foreach (OIDplus::getDatabasePlugins() as $plugin) {
1038
                        if ($plugin = OIDplus::getActiveDatabasePlugin()) {
1098
                        if ($plugin = OIDplus::getActiveDatabasePlugin()) {
1039
                                $plugin->httpHeaderCheck($http_headers);
1099
                                $plugin->httpHeaderCheck($http_headers);
1040
                        }
1100
                        }
1041
                        foreach (OIDplus::getPagePlugins() as $plugin) {
1101
                        foreach (OIDplus::getPagePlugins() as $plugin) {
1042
                                $plugin->httpHeaderCheck($http_headers);
1102
                                $plugin->httpHeaderCheck($http_headers);
1043
                        }
1103
                        }
1044
                        foreach (OIDplus::getAuthPlugins() as $plugin) {
1104
                        foreach (OIDplus::getAuthPlugins() as $plugin) {
1045
                                $plugin->httpHeaderCheck($http_headers);
1105
                                $plugin->httpHeaderCheck($http_headers);
1046
                        }
1106
                        }
1047
                        foreach (OIDplus::getLoggerPlugins() as $plugin) {
1107
                        foreach (OIDplus::getLoggerPlugins() as $plugin) {
1048
                                $plugin->httpHeaderCheck($http_headers);
1108
                                $plugin->httpHeaderCheck($http_headers);
1049
                        }
1109
                        }
1050
                        foreach (OIDplus::getObjectTypePlugins() as $plugin) {
1110
                        foreach (OIDplus::getObjectTypePlugins() as $plugin) {
1051
                                $plugin->httpHeaderCheck($http_headers);
1111
                                $plugin->httpHeaderCheck($http_headers);
1052
                        }
1112
                        }
1053
                        foreach (OIDplus::getLanguagePlugins() as $plugin) {
1113
                        foreach (OIDplus::getLanguagePlugins() as $plugin) {
1054
                                $plugin->httpHeaderCheck($http_headers);
1114
                                $plugin->httpHeaderCheck($http_headers);
1055
                        }
1115
                        }
1056
                        foreach (OIDplus::getDesignPlugins() as $plugin) {
1116
                        foreach (OIDplus::getDesignPlugins() as $plugin) {
1057
                                $plugin->httpHeaderCheck($http_headers);
1117
                                $plugin->httpHeaderCheck($http_headers);
1058
                        }
1118
                        }
1059
                        //foreach (OIDplus::getCaptchaPlugins() as $plugin) {
1119
                        //foreach (OIDplus::getCaptchaPlugins() as $plugin) {
1060
                        if ($plugin = OIDplus::getActiveCaptchaPlugin()) {
1120
                        if ($plugin = OIDplus::getActiveCaptchaPlugin()) {
1061
                                $plugin->httpHeaderCheck($http_headers);
1121
                                $plugin->httpHeaderCheck($http_headers);
1062
                        }
1122
                        }
1063
 
1123
 
1064
                        // Prepare to send the headers to the client
1124
                        // Prepare to send the headers to the client
1065
                        // The headers are sent automatically when the first output comes or the script ends
1125
                        // The headers are sent automatically when the first output comes or the script ends
1066
 
1126
 
1067
                        foreach ($http_headers as $name => $val) {
1127
                        foreach ($http_headers as $name => $val) {
1068
 
1128
 
1069
                                // Plugins can remove standard OIDplus headers by setting the value to null.
1129
                                // Plugins can remove standard OIDplus headers by setting the value to null.
1070
                                if (is_null($val)) continue; /** @phpstan-ignore-line */
1130
                                if (is_null($val)) continue; /** @phpstan-ignore-line */
1071
 
1131
 
1072
                                // Some headers can be written as arrays to make it easier for plugin authors
1132
                                // Some headers can be written as arrays to make it easier for plugin authors
1073
                                // to manipulate/extend the contents.
1133
                                // to manipulate/extend the contents.
1074
                                if (is_array($val)) {
1134
                                if (is_array($val)) {
1075
                                        if ((strtolower($name) == 'cache-control') ||
1135
                                        if ((strtolower($name) == 'cache-control') ||
1076
                                            (strtolower($name) == 'referrer-policy'))
1136
                                            (strtolower($name) == 'referrer-policy'))
1077
                                        {
1137
                                        {
1078
                                                if (count($val) == 0) continue;
1138
                                                if (count($val) == 0) continue;
1079
                                                $val = implode(', ', $val);
1139
                                                $val = implode(', ', $val);
1080
                                        } else if (strtolower($name) == 'content-security-policy') {
1140
                                        } else if (strtolower($name) == 'content-security-policy') {
1081
                                                if (count($val) == 0) continue;
1141
                                                if (count($val) == 0) continue;
1082
                                                foreach ($val as $tmp1 => &$tmp2) {
1142
                                                foreach ($val as $tmp1 => &$tmp2) {
1083
                                                        $tmp2 = array_unique($tmp2);
1143
                                                        $tmp2 = array_unique($tmp2);
1084
                                                        $tmp2 = $tmp1.' '.implode(' ', $tmp2);
1144
                                                        $tmp2 = $tmp1.' '.implode(' ', $tmp2);
1085
                                                }
1145
                                                }
1086
                                                $val = implode('; ', $val);
1146
                                                $val = implode('; ', $val);
1087
                                        } else {
1147
                                        } else {
1088
                                                throw new OIDplusException(_L('HTTP header "%1" cannot be written as array. A newly installed plugin is probably misusing the method "%2".',$name,'httpHeaderCheck'));
1148
                                                throw new OIDplusException(_L('HTTP header "%1" cannot be written as array. A newly installed plugin is probably misusing the method "%2".',$name,'httpHeaderCheck'));
1089
                                        }
1149
                                        }
1090
                                }
1150
                                }
1091
 
1151
 
1092
                                if (is_string($val)) {
1152
                                if (is_string($val)) {
1093
                                        header("$name: $val");
1153
                                        header("$name: $val");
1094
                                }
1154
                                }
1095
                        }
1155
                        }
1096
 
1156
 
1097
                } // endif (PHP_SAPI != 'cli')
1157
                } // endif (PHP_SAPI != 'cli')
1098
 
1158
 
1099
                // Initialize other stuff (i.e. things which require the logger!)
1159
                // Initialize other stuff (i.e. things which require the logger!)
1100
 
1160
 
1101
                OIDplus::recognizeSystemUrl(); // Make sure "last_known_system_url" is set
1161
                OIDplus::recognizeSystemUrl(); // Make sure "last_known_system_url" is set
1102
                OIDplus::recognizeVersion(); // Make sure "last_known_version" is set and a log entry is created
1162
                OIDplus::recognizeVersion(); // Make sure "last_known_version" is set and a log entry is created
1103
        }
1163
        }
1104
 
1164
 
1105
        # --- System URL, System ID, PKI, and other functions
1165
        // --- System URL, System ID, PKI, and other functions
1106
 
1166
 
1107
        private static function recognizeSystemUrl() {
1167
        private static function recognizeSystemUrl() {
1108
                try {
1168
                try {
1109
                        $url = OIDplus::webpath(null,self::PATH_ABSOLUTE_CANONICAL); // TODO: canonical or not?
1169
                        $url = OIDplus::webpath(null,self::PATH_ABSOLUTE_CANONICAL); // TODO: canonical or not?
1110
                        OIDplus::config()->setValue('last_known_system_url', $url);
1170
                        OIDplus::config()->setValue('last_known_system_url', $url);
1111
                } catch (Exception $e) {
1171
                } catch (\Exception $e) {
1112
                }
1172
                }
1113
        }
1173
        }
1114
 
1174
 
1115
        private static function getExecutingScriptPathDepth() {
1175
        private static function getExecutingScriptPathDepth() {
1116
                if (PHP_SAPI == 'cli') {
1176
                if (PHP_SAPI == 'cli') {
1117
                        global $argv;
1177
                        global $argv;
1118
                        $test_dir = dirname(realpath($argv[0]));
1178
                        $test_dir = dirname(realpath($argv[0]));
1119
                } else {
1179
                } else {
1120
                        if (!isset($_SERVER["SCRIPT_FILENAME"])) return false;
1180
                        if (!isset($_SERVER["SCRIPT_FILENAME"])) return false;
1121
                        $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
1181
                        $test_dir = dirname($_SERVER['SCRIPT_FILENAME']);
1122
                }
1182
                }
1123
                $test_dir = str_replace('\\', '/', $test_dir);
1183
                $test_dir = str_replace('\\', '/', $test_dir);
1124
                $steps_up = 0;
1184
                $steps_up = 0;
1125
                while (!file_exists($test_dir.'/oidplus.min.css.php')) { // We just assume that only the OIDplus base directory contains "oidplus.min.css.php" and not any subordinate directory!
1185
                while (!file_exists($test_dir.'/oidplus.min.css.php')) { // We just assume that only the OIDplus base directory contains "oidplus.min.css.php" and not any subordinate directory!
1126
                        $test_dir = dirname($test_dir);
1186
                        $test_dir = dirname($test_dir);
1127
                        $steps_up++;
1187
                        $steps_up++;
1128
                        if ($steps_up == 1000) return false; // to make sure there will never be an infinite loop
1188
                        if ($steps_up == 1000) return false; // to make sure there will never be an infinite loop
1129
                }
1189
                }
1130
                return $steps_up;
1190
                return $steps_up;
1131
        }
1191
        }
1132
 
1192
 
1133
        public static function isSSL() {
1193
        public static function isSSL() {
1134
                return isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
1194
                return isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on');
1135
        }
1195
        }
1136
 
1196
 
1137
        /**
1197
        /**
1138
         * Returns the URL of the system.
1198
         * Returns the URL of the system.
1139
         * @param int $mode If true or OIDplus::PATH_RELATIVE, the returning path is relative to the currently executed
1199
         * @param int $mode If true or OIDplus::PATH_RELATIVE, the returning path is relative to the currently executed
1140
         *                  PHP script (i.e. index.php , not the plugin PHP script!). False or OIDplus::PATH_ABSOLUTE is
1200
         *                  PHP script (i.e. index.php , not the plugin PHP script!). False or OIDplus::PATH_ABSOLUTE is
1141
         *                  results in an absolute URL. OIDplus::PATH_ABSOLUTE_CANONICAL is an absolute URL,
1201
         *                  results in an absolute URL. OIDplus::PATH_ABSOLUTE_CANONICAL is an absolute URL,
1142
         *                  but a canonical path (set by base config setting CANONICAL_SYSTEM_URL) is preferred.
1202
         *                  but a canonical path (set by base config setting CANONICAL_SYSTEM_URL) is preferred.
1143
         * @return string|false The URL, with guaranteed trailing path delimiter for directories
1203
         * @return string|false The URL, with guaranteed trailing path delimiter for directories
1144
         */
1204
         */
1145
        private static function getSystemUrl($mode) {
1205
        private static function getSystemUrl($mode) {
1146
                if ($mode === self::PATH_RELATIVE) {
1206
                if ($mode === self::PATH_RELATIVE) {
1147
                        $steps_up = self::getExecutingScriptPathDepth();
1207
                        $steps_up = self::getExecutingScriptPathDepth();
1148
                        if ($steps_up === false) {
1208
                        if ($steps_up === false) {
1149
                                return false;
1209
                                return false;
1150
                        } else {
1210
                        } else {
1151
                                return str_repeat('../', $steps_up);
1211
                                return str_repeat('../', $steps_up);
1152
                        }
1212
                        }
1153
                } else {
1213
                } else {
1154
                        if ($mode === self::PATH_ABSOLUTE_CANONICAL) {
1214
                        if ($mode === self::PATH_ABSOLUTE_CANONICAL) {
1155
                                $tmp = OIDplus::baseConfig()->getValue('CANONICAL_SYSTEM_URL', '');
1215
                                $tmp = OIDplus::baseConfig()->getValue('CANONICAL_SYSTEM_URL', '');
1156
                                if ($tmp) {
1216
                                if ($tmp) {
1157
                                        return rtrim($tmp,'/').'/';
1217
                                        return rtrim($tmp,'/').'/';
1158
                                }
1218
                                }
1159
                        }
1219
                        }
1160
 
1220
 
1161
                        if (PHP_SAPI == 'cli') {
1221
                        if (PHP_SAPI == 'cli') {
1162
                                try {
1222
                                try {
1163
                                        return OIDplus::config()->getValue('last_known_system_url', false);
1223
                                        return OIDplus::config()->getValue('last_known_system_url', false);
1164
                                } catch (Exception $e) {
1224
                                } catch (\Exception $e) {
1165
                                        return false;
1225
                                        return false;
1166
                                }
1226
                                }
1167
                        } else {
1227
                        } else {
1168
                                // First, try to find out how many levels we need to go up
1228
                                // First, try to find out how many levels we need to go up
1169
                                $steps_up = self::getExecutingScriptPathDepth();
1229
                                $steps_up = self::getExecutingScriptPathDepth();
1170
 
1230
 
1171
                                // Then go up these amount of levels, based on SCRIPT_NAME/argv[0]
1231
                                // Then go up these amount of levels, based on SCRIPT_NAME/argv[0]
1172
                                $res = dirname($_SERVER['SCRIPT_NAME'].'index.php'); // This fake 'index.php' ensures that SCRIPT_NAME does not end with '/', which would make dirname() fail
1232
                                $res = dirname($_SERVER['SCRIPT_NAME'].'index.php'); // This fake 'index.php' ensures that SCRIPT_NAME does not end with '/', which would make dirname() fail
1173
                                for ($i=0; $i<$steps_up; $i++) {
1233
                                for ($i=0; $i<$steps_up; $i++) {
1174
                                        $res = dirname($res);
1234
                                        $res = dirname($res);
1175
                                }
1235
                                }
1176
                                $res = str_replace('\\', '/', $res);
1236
                                $res = str_replace('\\', '/', $res);
1177
                                if ($res == '/') $res = '';
1237
                                if ($res == '/') $res = '';
1178
 
1238
 
1179
                                // Add protocol and hostname
1239
                                // Add protocol and hostname
1180
                                $is_ssl = self::isSSL();
1240
                                $is_ssl = self::isSSL();
1181
                                $protocol = $is_ssl ? 'https' : 'http'; // do not translate
1241
                                $protocol = $is_ssl ? 'https' : 'http'; // do not translate
1182
                                $host = $_SERVER['HTTP_HOST']; // includes port if it is not 80/443
1242
                                $host = $_SERVER['HTTP_HOST']; // includes port if it is not 80/443
1183
 
1243
 
1184
                                return $protocol.'://'.$host.$res.'/';
1244
                                return $protocol.'://'.$host.$res.'/';
1185
                        }
1245
                        }
1186
                }
1246
                }
1187
        }
1247
        }
1188
 
1248
 
1189
        private static function getSystemIdFromPubKey($pubKey) {
1249
        private static function getSystemIdFromPubKey($pubKey) {
1190
                $m = array();
1250
                $m = array();
1191
                if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
1251
                if (preg_match('@BEGIN PUBLIC KEY\-+(.+)\-+END PUBLIC KEY@ismU', $pubKey, $m)) {
1192
                        return smallhash(base64_decode($m[1]));
1252
                        return smallhash(base64_decode($m[1]));
1193
                }
1253
                }
1194
                return false;
1254
                return false;
1195
        }
1255
        }
1196
 
1256
 
1197
        private static $system_id_cache = null;
1257
        private static $system_id_cache = null;
1198
        public static function getSystemId($oid=false) {
1258
        public static function getSystemId($oid=false) {
1199
                if (!is_null(self::$system_id_cache)) {
1259
                if (!is_null(self::$system_id_cache)) {
1200
                        $out = self::$system_id_cache;
1260
                        $out = self::$system_id_cache;
1201
                } else {
1261
                } else {
1202
                        $out = false;
1262
                        $out = false;
1203
 
1263
 
1204
                        if (self::getPkiStatus(true)) {
1264
                        if (self::getPkiStatus(true)) {
1205
                                $pubKey = OIDplus::getSystemPublicKey();
1265
                                $pubKey = OIDplus::getSystemPublicKey();
1206
                                $out = self::getSystemIdFromPubKey($pubKey);
1266
                                $out = self::getSystemIdFromPubKey($pubKey);
1207
                        }
1267
                        }
1208
                        self::$system_id_cache = $out;
1268
                        self::$system_id_cache = $out;
1209
                }
1269
                }
1210
                if (!$out) return false;
1270
                if (!$out) return false;
1211
                return ($oid ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
1271
                return ($oid ? '1.3.6.1.4.1.37476.30.9.' : '').$out;
1212
        }
1272
        }
1213
 
1273
 
1214
        public static function getOpenSslCnf() {
1274
        public static function getOpenSslCnf() {
1215
                // The following functions need a config file, otherway they don't work
1275
                // The following functions need a config file, otherway they don't work
1216
                // - openssl_csr_new
1276
                // - openssl_csr_new
1217
                // - openssl_csr_sign
1277
                // - openssl_csr_sign
1218
                // - openssl_pkey_export
1278
                // - openssl_pkey_export
1219
                // - openssl_pkey_export_to_file
1279
                // - openssl_pkey_export_to_file
1220
                // - openssl_pkey_new
1280
                // - openssl_pkey_new
1221
                $tmp = @getenv('OPENSSL_CONF');
1281
                $tmp = @getenv('OPENSSL_CONF');
1222
                if ($tmp && file_exists($tmp)) return $tmp;
1282
                if ($tmp && file_exists($tmp)) return $tmp;
1223
 
1283
 
1224
                // OpenSSL in XAMPP does not work OOBE, since the OPENSSL_CONF is
1284
                // OpenSSL in XAMPP does not work OOBE, since the OPENSSL_CONF is
1225
                // C:/xampp/apache/bin/openssl.cnf and not C:/xampp/apache/conf/openssl.cnf
1285
                // C:/xampp/apache/bin/openssl.cnf and not C:/xampp/apache/conf/openssl.cnf
1226
                // Bug reports are more than 10 years old and nobody cares...
1286
                // Bug reports are more than 10 years old and nobody cares...
1227
                // Use our own config file
1287
                // Use our own config file
1228
                return __DIR__.'/../../vendor/phpseclib/phpseclib/phpseclib/openssl.cnf';
1288
                return __DIR__.'/../../vendor/phpseclib/phpseclib/phpseclib/openssl.cnf';
1229
        }
1289
        }
1230
 
1290
 
1231
        private static function getPrivKeyPassphraseFilename() {
1291
        private static function getPrivKeyPassphraseFilename() {
1232
                return OIDplus::localpath() . 'userdata/privkey_secret.php';
1292
                return OIDplus::localpath() . 'userdata/privkey_secret.php';
1233
        }
1293
        }
1234
 
1294
 
1235
        private static function tryCreatePrivKeyPassphrase() {
1295
        private static function tryCreatePrivKeyPassphrase() {
1236
                $file = self::getPrivKeyPassphraseFilename();
1296
                $file = self::getPrivKeyPassphraseFilename();
1237
 
1297
 
1238
                $passphrase = generateRandomString(64);
1298
                $passphrase = generateRandomString(64);
1239
                $cont = "<?php\n";
1299
                $cont = "<?php\n";
1240
                $cont .= "// ATTENTION! This file was automatically generated by OIDplus to encrypt the private key\n";
1300
                $cont .= "// ATTENTION! This file was automatically generated by OIDplus to encrypt the private key\n";
1241
                $cont .= "// that is located in your database configuration table. DO NOT ALTER OR DELETE THIS FILE,\n";
1301
                $cont .= "// that is located in your database configuration table. DO NOT ALTER OR DELETE THIS FILE,\n";
1242
                $cont .= "// otherwise you will lose your OIDplus System-ID and all services connected with it!\n";
1302
                $cont .= "// otherwise you will lose your OIDplus System-ID and all services connected with it!\n";
1243
                $cont .= "// If multiple systems access the same database, then this file must be synchronous\n";
1303
                $cont .= "// If multiple systems access the same database, then this file must be synchronous\n";
1244
                $cont .= "// between all systems, otherwise you will lose your system ID, too!\n";
1304
                $cont .= "// between all systems, otherwise you will lose your system ID, too!\n";
1245
                $cont .= "\$passphrase = '$passphrase';\n";
1305
                $cont .= "\$passphrase = '$passphrase';\n";
1246
                $cont .= "// End of file\n";
1306
                $cont .= "// End of file\n";
1247
 
1307
 
1248
                @file_put_contents($file, $cont);
1308
                @file_put_contents($file, $cont);
1249
        }
1309
        }
1250
 
1310
 
1251
        private static function getPrivKeyPassphrase() {
1311
        private static function getPrivKeyPassphrase() {
1252
                $file = self::getPrivKeyPassphraseFilename();
1312
                $file = self::getPrivKeyPassphraseFilename();
1253
                if (!file_exists($file)) return false;
1313
                if (!file_exists($file)) return false;
1254
                $cont = file_get_contents($file);
1314
                $cont = file_get_contents($file);
1255
                $m = array();
1315
                $m = array();
1256
                if (!preg_match("@'(.+)'@isU", $cont, $m)) return false;
1316
                if (!preg_match("@'(.+)'@isU", $cont, $m)) return false;
1257
                return $m[1];
1317
                return $m[1];
1258
        }
1318
        }
1259
 
1319
 
1260
        public static function getSystemPrivateKey() {
1320
        public static function getSystemPrivateKey() {
1261
                $privKey = OIDplus::config()->getValue('oidplus_private_key');
1321
                $privKey = OIDplus::config()->getValue('oidplus_private_key');
1262
                if ($privKey == '') return false;
1322
                if ($privKey == '') return false;
1263
 
1323
 
1264
                $passphrase = self::getPrivKeyPassphrase();
1324
                $passphrase = self::getPrivKeyPassphrase();
1265
                if ($passphrase !== false) {
1325
                if ($passphrase !== false) {
1266
                        $privKey = decrypt_private_key($privKey, $passphrase);
1326
                        $privKey = decrypt_private_key($privKey, $passphrase);
1267
                }
1327
                }
1268
 
1328
 
1269
                if (is_privatekey_encrypted($privKey)) {
1329
                if (is_privatekey_encrypted($privKey)) {
1270
                        // This can happen if the key file has vanished
1330
                        // This can happen if the key file has vanished
1271
                        return false;
1331
                        return false;
1272
                }
1332
                }
1273
 
1333
 
1274
                return $privKey;
1334
                return $privKey;
1275
        }
1335
        }
1276
 
1336
 
1277
        public static function getSystemPublicKey() {
1337
        public static function getSystemPublicKey() {
1278
                $pubKey = OIDplus::config()->getValue('oidplus_public_key');
1338
                $pubKey = OIDplus::config()->getValue('oidplus_public_key');
1279
                if ($pubKey == '') return false;
1339
                if ($pubKey == '') return false;
1280
                return $pubKey;
1340
                return $pubKey;
1281
        }
1341
        }
1282
 
1342
 
1283
        public static function getPkiStatus($try_generate=false) {
1343
        public static function getPkiStatus($try_generate=false) {
1284
                if (!function_exists('openssl_pkey_new')) return false;
1344
                if (!function_exists('openssl_pkey_new')) return false;
1285
 
1345
 
1286
                if ($try_generate) {
1346
                if ($try_generate) {
1287
                        // For debug purposes: Invalidate current key once:
1347
                        // For debug purposes: Invalidate current key once:
1288
                        //OIDplus::config()->setValue('oidplus_private_key', '');
1348
                        //OIDplus::config()->setValue('oidplus_private_key', '');
1289
 
1349
 
1290
                        $privKey = OIDplus::getSystemPrivateKey();
1350
                        $privKey = OIDplus::getSystemPrivateKey();
1291
                        $pubKey = OIDplus::getSystemPublicKey();
1351
                        $pubKey = OIDplus::getSystemPublicKey();
1292
                        if (!verify_private_public_key($privKey, $pubKey)) {
1352
                        if (!verify_private_public_key($privKey, $pubKey)) {
1293
                                if ($pubKey) {
1353
                                if ($pubKey) {
1294
                                        OIDplus::logger()->log("[WARN]A!", "The private/public key-pair is broken. A new key-pair will now be generated for your system. Your System-ID will change.");
1354
                                        OIDplus::logger()->log("[WARN]A!", "The private/public key-pair is broken. A new key-pair will now be generated for your system. Your System-ID will change.");
1295
                                }
1355
                                }
1296
 
1356
 
1297
                                $pkey_config = array(
1357
                                $pkey_config = array(
1298
                                    "digest_alg" => "sha512",
1358
                                    "digest_alg" => "sha512",
1299
                                    "private_key_bits" => defined('OPENSSL_SUPPLEMENT') ? 1024 : 2048, // openssl_supplement.inc.php is based on phpseclib, which is very slow. So we use 1024 bits instead of 2048 bits
1359
                                    "private_key_bits" => defined('OPENSSL_SUPPLEMENT') ? 1024 : 2048, // openssl_supplement.inc.php is based on phpseclib, which is very slow. So we use 1024 bits instead of 2048 bits
1300
                                    "private_key_type" => OPENSSL_KEYTYPE_RSA,
1360
                                    "private_key_type" => OPENSSL_KEYTYPE_RSA,
1301
                                    "config" => OIDplus::getOpenSslCnf()
1361
                                    "config" => OIDplus::getOpenSslCnf()
1302
                                );
1362
                                );
1303
 
1363
 
1304
                                // Create the private and public key
1364
                                // Create the private and public key
1305
                                $res = openssl_pkey_new($pkey_config);
1365
                                $res = openssl_pkey_new($pkey_config);
1306
                                if ($res === false) return false;
1366
                                if ($res === false) return false;
1307
 
1367
 
1308
                                // Extract the private key from $res to $privKey
1368
                                // Extract the private key from $res to $privKey
1309
                                if (openssl_pkey_export($res, $privKey, null, $pkey_config) === false) return false;
1369
                                if (openssl_pkey_export($res, $privKey, null, $pkey_config) === false) return false;
1310
 
1370
 
1311
                                // Extract the public key from $res to $pubKey
1371
                                // Extract the public key from $res to $pubKey
1312
                                $tmp = openssl_pkey_get_details($res);
1372
                                $tmp = openssl_pkey_get_details($res);
1313
                                if ($tmp === false) return false;
1373
                                if ($tmp === false) return false;
1314
                                $pubKey = $tmp["key"];
1374
                                $pubKey = $tmp["key"];
1315
 
1375
 
1316
                                // encrypt new keys using a passphrase stored in a secret file
1376
                                // encrypt new keys using a passphrase stored in a secret file
1317
                                self::tryCreatePrivKeyPassphrase(); // *try* (re)generate this file
1377
                                self::tryCreatePrivKeyPassphrase(); // *try* (re)generate this file
1318
                                $passphrase = self::getPrivKeyPassphrase();
1378
                                $passphrase = self::getPrivKeyPassphrase();
1319
                                if ($passphrase !== false) {
1379
                                if ($passphrase !== false) {
1320
                                        $privKey = encrypt_private_key($privKey, $passphrase);
1380
                                        $privKey = encrypt_private_key($privKey, $passphrase);
1321
                                }
1381
                                }
1322
 
1382
 
1323
                                // Calculate the system ID from the public key
1383
                                // Calculate the system ID from the public key
1324
                                $system_id = self::getSystemIdFromPubKey($pubKey);
1384
                                $system_id = self::getSystemIdFromPubKey($pubKey);
1325
                                if ($system_id !== false) {
1385
                                if ($system_id !== false) {
1326
                                        // Save the key pair to database
1386
                                        // Save the key pair to database
1327
                                        OIDplus::config()->setValue('oidplus_private_key', $privKey);
1387
                                        OIDplus::config()->setValue('oidplus_private_key', $privKey);
1328
                                        OIDplus::config()->setValue('oidplus_public_key', $pubKey);
1388
                                        OIDplus::config()->setValue('oidplus_public_key', $pubKey);
1329
 
1389
 
1330
                                        // Log the new system ID
1390
                                        // Log the new system ID
1331
                                        OIDplus::logger()->log("[INFO]A!", "A new private/public key-pair for your system had been generated. Your SystemID is now $system_id");
1391
                                        OIDplus::logger()->log("[INFO]A!", "A new private/public key-pair for your system had been generated. Your SystemID is now $system_id");
1332
                                }
1392
                                }
1333
                        } else {
1393
                        } else {
1334
                                $passphrase = self::getPrivKeyPassphrase();
1394
                                $passphrase = self::getPrivKeyPassphrase();
1335
                                $rawPrivKey = OIDplus::config()->getValue('oidplus_private_key');
1395
                                $rawPrivKey = OIDplus::config()->getValue('oidplus_private_key');
1336
                                if (($passphrase === false) || !is_privatekey_encrypted($rawPrivKey)) {
1396
                                if (($passphrase === false) || !is_privatekey_encrypted($rawPrivKey)) {
1337
                                        // Upgrade to new encrypted keys
1397
                                        // Upgrade to new encrypted keys
1338
                                        self::tryCreatePrivKeyPassphrase(); // *try* generate this file
1398
                                        self::tryCreatePrivKeyPassphrase(); // *try* generate this file
1339
                                        $passphrase = self::getPrivKeyPassphrase();
1399
                                        $passphrase = self::getPrivKeyPassphrase();
1340
                                        if ($passphrase !== false) {
1400
                                        if ($passphrase !== false) {
1341
                                                $privKey = encrypt_private_key($privKey, $passphrase);
1401
                                                $privKey = encrypt_private_key($privKey, $passphrase);
1342
                                                OIDplus::logger()->log("[INFO]A!", "The private/public key-pair has been upgraded to an encrypted key-pair. The key is saved in ".self::getPrivKeyPassphraseFilename());
1402
                                                OIDplus::logger()->log("[INFO]A!", "The private/public key-pair has been upgraded to an encrypted key-pair. The key is saved in ".self::getPrivKeyPassphraseFilename());
1343
                                                OIDplus::config()->setValue('oidplus_private_key', $privKey);
1403
                                                OIDplus::config()->setValue('oidplus_private_key', $privKey);
1344
                                        }
1404
                                        }
1345
                                }
1405
                                }
1346
                        }
1406
                        }
1347
                }
1407
                }
1348
 
1408
 
1349
                $privKey = OIDplus::getSystemPrivateKey();
1409
                $privKey = OIDplus::getSystemPrivateKey();
1350
                $pubKey = OIDplus::getSystemPublicKey();
1410
                $pubKey = OIDplus::getSystemPublicKey();
1351
                return verify_private_public_key($privKey, $pubKey);
1411
                return verify_private_public_key($privKey, $pubKey);
1352
        }
1412
        }
1353
 
1413
 
1354
        public static function getInstallType() {
1414
        public static function getInstallType() {
1355
                $counter = 0;
1415
                $counter = 0;
1356
 
1416
 
1357
                if ($new_version_file_exists = file_exists(OIDplus::localpath().'.version.php')) {
1417
                if ($new_version_file_exists = file_exists(OIDplus::localpath().'.version.php')) {
1358
                        $counter++;
1418
                        $counter++;
1359
                }
1419
                }
1360
                if ($old_version_file_exists = file_exists(OIDplus::localpath().'oidplus_version.txt')) {
1420
                if ($old_version_file_exists = file_exists(OIDplus::localpath().'oidplus_version.txt')) {
1361
                        $counter++;
1421
                        $counter++;
1362
                }
1422
                }
1363
                $version_file_exists = $old_version_file_exists | $new_version_file_exists;
1423
                $version_file_exists = $old_version_file_exists | $new_version_file_exists;
1364
                if ($svn_dir_exists = (is_dir(OIDplus::localpath().'.svn') ||
1424
                if ($svn_dir_exists = (is_dir(OIDplus::localpath().'.svn') ||
1365
                                       is_dir(OIDplus::localpath().'../.svn'))) { // in case we checked out the root instead of the "trunk"
1425
                                       is_dir(OIDplus::localpath().'../.svn'))) { // in case we checked out the root instead of the "trunk"
1366
                        $counter++;
1426
                        $counter++;
1367
                }
1427
                }
1368
                // if ($git_dir_exists = is_dir(OIDplus::localpath().'.git')) {
1428
                // if ($git_dir_exists = is_dir(OIDplus::localpath().'.git')) {
1369
                if ($git_dir_exists = (OIDplus::findGitFolder() !== false)) {
1429
                if ($git_dir_exists = (OIDplus::findGitFolder() !== false)) {
1370
                        $counter++;
1430
                        $counter++;
1371
                }
1431
                }
1372
 
1432
 
1373
                if ($counter === 0) {
1433
                if ($counter === 0) {
1374
                        return 'unknown'; // do not translate
1434
                        return 'unknown'; // do not translate
1375
                }
1435
                }
1376
                else if ($counter > 1) {
1436
                else if ($counter > 1) {
1377
                        return 'ambigous'; // do not translate
1437
                        return 'ambigous'; // do not translate
1378
                }
1438
                }
1379
                else if ($svn_dir_exists) {
1439
                else if ($svn_dir_exists) {
1380
                        return 'svn-wc'; // do not translate
1440
                        return 'svn-wc'; // do not translate
1381
                }
1441
                }
1382
                else if ($git_dir_exists) {
1442
                else if ($git_dir_exists) {
1383
                        return 'git-wc'; // do not translate
1443
                        return 'git-wc'; // do not translate
1384
                }
1444
                }
1385
                else if ($version_file_exists) {
1445
                else if ($version_file_exists) {
1386
                        return 'svn-snapshot'; // do not translate
1446
                        return 'svn-snapshot'; // do not translate
1387
                }
1447
                }
1388
        }
1448
        }
1389
 
1449
 
1390
        private static function recognizeVersion() {
1450
        private static function recognizeVersion() {
1391
                try {
1451
                try {
1392
                        $ver_prev = OIDplus::config()->getValue("last_known_version");
1452
                        $ver_prev = OIDplus::config()->getValue("last_known_version");
1393
                        $ver_now = OIDplus::getVersion();
1453
                        $ver_now = OIDplus::getVersion();
1394
                        if (($ver_now != '') && ($ver_prev != '') && ($ver_now != $ver_prev)) {
1454
                        if (($ver_now != '') && ($ver_prev != '') && ($ver_now != $ver_prev)) {
1395
                                // TODO: Problem: When the system was updated using SVN, then the IP address of the next random visitor of the website is logged!
1455
                                // TODO: Problem: When the system was updated using SVN, then the IP address of the next random visitor of the website is logged!
1396
                                OIDplus::logger()->log("[INFO]A!", "System version changed from '$ver_prev' to '$ver_now'");
1456
                                OIDplus::logger()->log("[INFO]A!", "System version changed from '$ver_prev' to '$ver_now'");
1397
 
1457
 
1398
                                // Just to be sure, recanonize objects (we don't do it at every page visit due to performance reasons)
1458
                                // Just to be sure, recanonize objects (we don't do it at every page visit due to performance reasons)
1399
                                self::recanonizeObjects();
1459
                                self::recanonizeObjects();
1400
                        }
1460
                        }
1401
                        OIDplus::config()->setValue("last_known_version", $ver_now);
1461
                        OIDplus::config()->setValue("last_known_version", $ver_now);
1402
                } catch (Exception $e) {
1462
                } catch (\Exception $e) {
1403
                }
1463
                }
1404
        }
1464
        }
1405
 
1465
 
1406
        public static function getVersion() {
1466
        public static function getVersion() {
1407
                static $cachedVersion = null;
1467
                static $cachedVersion = null;
1408
                if (!is_null($cachedVersion)) {
1468
                if (!is_null($cachedVersion)) {
1409
                        return $cachedVersion;
1469
                        return $cachedVersion;
1410
                }
1470
                }
1411
 
1471
 
1412
                $installType = OIDplus::getInstallType();
1472
                $installType = OIDplus::getInstallType();
1413
 
1473
 
1414
                if ($installType === 'svn-wc') {
1474
                if ($installType === 'svn-wc') {
1415
                        $ver = get_svn_revision(OIDplus::localpath());
1475
                        $ver = get_svn_revision(OIDplus::localpath());
1416
                        if ($ver)
1476
                        if ($ver)
1417
                                return ($cachedVersion = 'svn-'.$ver);
1477
                                return ($cachedVersion = 'svn-'.$ver);
1418
                        $ver = get_svn_revision(OIDplus::localpath().'../'); // in case we checked out the root instead of the "trunk"
1478
                        $ver = get_svn_revision(OIDplus::localpath().'../'); // in case we checked out the root instead of the "trunk"
1419
                        if ($ver)
1479
                        if ($ver)
1420
                                return ($cachedVersion = 'svn-'.$ver);
1480
                                return ($cachedVersion = 'svn-'.$ver);
1421
                }
1481
                }
1422
 
1482
 
1423
                if ($installType === 'git-wc') {
1483
                if ($installType === 'git-wc') {
1424
                        $ver = OIDplus::getGitsvnRevision(OIDplus::localpath());
1484
                        $ver = OIDplus::getGitsvnRevision(OIDplus::localpath());
1425
                        if ($ver)
1485
                        if ($ver)
1426
                                return ($cachedVersion = 'svn-'.$ver);
1486
                                return ($cachedVersion = 'svn-'.$ver);
1427
                }
1487
                }
1428
 
1488
 
1429
                if ($installType === 'svn-snapshot') {
1489
                if ($installType === 'svn-snapshot') {
1430
                        $cont = '';
1490
                        $cont = '';
1431
                        if (file_exists($filename = OIDplus::localpath().'oidplus_version.txt'))
1491
                        if (file_exists($filename = OIDplus::localpath().'oidplus_version.txt'))
1432
                                $cont = file_get_contents($filename);
1492
                                $cont = file_get_contents($filename);
1433
                        if (file_exists($filename = OIDplus::localpath().'.version.php'))
1493
                        if (file_exists($filename = OIDplus::localpath().'.version.php'))
1434
                                $cont = file_get_contents($filename);
1494
                                $cont = file_get_contents($filename);
1435
                        $m = array();
1495
                        $m = array();
1436
                        if (preg_match('@Revision (\d+)@', $cont, $m)) // do not translate
1496
                        if (preg_match('@Revision (\d+)@', $cont, $m)) // do not translate
1437
                                return ($cachedVersion = 'svn-'.$m[1]); // do not translate
1497
                                return ($cachedVersion = 'svn-'.$m[1]); // do not translate
1438
                }
1498
                }
1439
 
1499
 
1440
                return ($cachedVersion = false); // version ambigous or unknown
1500
                return ($cachedVersion = false); // version ambigous or unknown
1441
        }
1501
        }
1442
 
1502
 
1443
        const ENFORCE_SSL_NO   = 0;
1503
        const ENFORCE_SSL_NO   = 0;
1444
        const ENFORCE_SSL_YES  = 1;
1504
        const ENFORCE_SSL_YES  = 1;
1445
        const ENFORCE_SSL_AUTO = 2;
1505
        const ENFORCE_SSL_AUTO = 2;
1446
        private static $sslAvailableCache = null;
1506
        private static $sslAvailableCache = null;
1447
        public static function isSslAvailable() {
1507
        public static function isSslAvailable() {
1448
                if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
1508
                if (!is_null(self::$sslAvailableCache)) return self::$sslAvailableCache;
1449
 
1509
 
1450
                if (PHP_SAPI == 'cli') {
1510
                if (PHP_SAPI == 'cli') {
1451
                        self::$sslAvailableCache = false;
1511
                        self::$sslAvailableCache = false;
1452
                        return false;
1512
                        return false;
1453
                }
1513
                }
1454
 
1514
 
1455
                $timeout = 2;
1515
                $timeout = 2;
1456
                $already_ssl = self::isSSL();
1516
                $already_ssl = self::isSSL();
1457
                $ssl_port = 443;
1517
                $ssl_port = 443;
1458
 
1518
 
1459
                if ($already_ssl) {
1519
                if ($already_ssl) {
1460
                        OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, false, null, true/*forceInsecure*/);
1520
                        OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, false, null, true/*forceInsecure*/);
1461
                        self::$sslAvailableCache = true;
1521
                        self::$sslAvailableCache = true;
1462
                        return true;
1522
                        return true;
1463
                } else {
1523
                } else {
1464
                        if (isset($_COOKIE['SSL_CHECK']) && ($_COOKIE['SSL_CHECK'] == '1')) {
1524
                        if (isset($_COOKIE['SSL_CHECK']) && ($_COOKIE['SSL_CHECK'] == '1')) {
1465
                                // The cookie "SSL_CHECK" is set once a website was loaded with HTTPS.
1525
                                // The cookie "SSL_CHECK" is set once a website was loaded with HTTPS.
1466
                                // It forces subsequent HTTP calls to redirect to HTTPS (like HSTS).
1526
                                // It forces subsequent HTTP calls to redirect to HTTPS (like HSTS).
1467
                                // The reason is the following problem:
1527
                                // The reason is the following problem:
1468
                                // If you open the page with HTTPS first, then the CSRF token cookies will get the "secure" flag
1528
                                // If you open the page with HTTPS first, then the CSRF token cookies will get the "secure" flag
1469
                                // If you open the page then with HTTP, the HTTP cannot access the secure CSRF cookies,
1529
                                // If you open the page then with HTTP, the HTTP cannot access the secure CSRF cookies,
1470
                                // Chrome will then block "Set-Cookie" since the HTTP cookie would overwrite the HTTPS cookie.
1530
                                // Chrome will then block "Set-Cookie" since the HTTP cookie would overwrite the HTTPS cookie.
1471
                                // Note: SSL_CHECK is NOT a replacement for HSTS! You should use HSTS,
1531
                                // Note: SSL_CHECK is NOT a replacement for HSTS! You should use HSTS,
1472
                                // because on there your browser ensures that HTTPS is called, before the server
1532
                                // because on there your browser ensures that HTTPS is called, before the server
1473
                                // is even contacted (and therefore, no HTTP connection can be hacked).
1533
                                // is even contacted (and therefore, no HTTP connection can be hacked).
1474
                                $mode = OIDplus::ENFORCE_SSL_YES;
1534
                                $mode = OIDplus::ENFORCE_SSL_YES;
1475
                        } else {
1535
                        } else {
1476
                                $mode = OIDplus::baseConfig()->getValue('ENFORCE_SSL', OIDplus::ENFORCE_SSL_AUTO);
1536
                                $mode = OIDplus::baseConfig()->getValue('ENFORCE_SSL', OIDplus::ENFORCE_SSL_AUTO);
1477
                        }
1537
                        }
1478
 
1538
 
1479
                        if ($mode == OIDplus::ENFORCE_SSL_NO) {
1539
                        if ($mode == OIDplus::ENFORCE_SSL_NO) {
1480
                                // No SSL available
1540
                                // No SSL available
1481
                                self::$sslAvailableCache = false;
1541
                                self::$sslAvailableCache = false;
1482
                                return false;
1542
                                return false;
1483
                        } else if ($mode == OIDplus::ENFORCE_SSL_YES) {
1543
                        } else if ($mode == OIDplus::ENFORCE_SSL_YES) {
1484
                                // Force SSL
1544
                                // Force SSL
1485
                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1545
                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1486
                                header('Location:'.$location);
1546
                                header('Location:'.$location);
1487
                                die(_L('Redirecting to HTTPS...'));
1547
                                die(_L('Redirecting to HTTPS...'));
1488
                        } else if ($mode == OIDplus::ENFORCE_SSL_AUTO) {
1548
                        } else if ($mode == OIDplus::ENFORCE_SSL_AUTO) {
1489
                                // Automatic SSL detection
1549
                                // Automatic SSL detection
1490
                                if (isset($_COOKIE['SSL_CHECK'])) {
1550
                                if (isset($_COOKIE['SSL_CHECK'])) {
1491
                                        // We already had the HTTPS detection done before.
1551
                                        // We already had the HTTPS detection done before.
1492
                                        if ($_COOKIE['SSL_CHECK'] == '1') {
1552
                                        if ($_COOKIE['SSL_CHECK'] == '1') {
1493
                                                // HTTPS was detected before, but we are HTTP. Redirect now
1553
                                                // HTTPS was detected before, but we are HTTP. Redirect now
1494
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1554
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1495
                                                header('Location:'.$location);
1555
                                                header('Location:'.$location);
1496
                                                die(_L('Redirecting to HTTPS...'));
1556
                                                die(_L('Redirecting to HTTPS...'));
1497
                                        } else {
1557
                                        } else {
1498
                                                // No HTTPS available. Do nothing.
1558
                                                // No HTTPS available. Do nothing.
1499
                                                self::$sslAvailableCache = false;
1559
                                                self::$sslAvailableCache = false;
1500
                                                return false;
1560
                                                return false;
1501
                                        }
1561
                                        }
1502
                                } else {
1562
                                } else {
1503
                                        // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
1563
                                        // This is our first check (or the browser didn't accept the SSL_CHECK cookie)
1504
                                        $errno = -1;
1564
                                        $errno = -1;
1505
                                        $errstr = '';
1565
                                        $errstr = '';
1506
                                        if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
1566
                                        if (@fsockopen($_SERVER['HTTP_HOST'], $ssl_port, $errno, $errstr, $timeout)) {
1507
                                                // HTTPS detected. Redirect now, and remember that we had detected HTTPS
1567
                                                // HTTPS detected. Redirect now, and remember that we had detected HTTPS
1508
                                                OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, false, null, true/*forceInsecure*/);
1568
                                                OIDplus::cookieUtils()->setcookie('SSL_CHECK', '1', 0, false, null, true/*forceInsecure*/);
1509
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1569
                                                $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1510
                                                header('Location:'.$location);
1570
                                                header('Location:'.$location);
1511
                                                die(_L('Redirecting to HTTPS...'));
1571
                                                die(_L('Redirecting to HTTPS...'));
1512
                                        } else {
1572
                                        } else {
1513
                                                // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
1573
                                                // No HTTPS detected. Do nothing, and next time, don't try to detect HTTPS again.
1514
                                                OIDplus::cookieUtils()->setcookie('SSL_CHECK', '0', 0, false, null, true/*forceInsecure*/);
1574
                                                OIDplus::cookieUtils()->setcookie('SSL_CHECK', '0', 0, false, null, true/*forceInsecure*/);
1515
                                                self::$sslAvailableCache = false;
1575
                                                self::$sslAvailableCache = false;
1516
                                                return false;
1576
                                                return false;
1517
                                        }
1577
                                        }
1518
                                }
1578
                                }
1519
                        }
1579
                        }
1520
                }
1580
                }
1521
        }
1581
        }
1522
 
1582
 
1523
        /**
1583
        /**
1524
         * Gets a local path pointing to a resource
1584
         * Gets a local path pointing to a resource
1525
         * @param string $target Target resource (file or directory must exist), or null to get the OIDplus base directory
1585
         * @param string $target Target resource (file or directory must exist), or null to get the OIDplus base directory
1526
         * @param boolean $relative If true, the returning path is relative to the currently executed PHP file (not the CLI working directory)
1586
         * @param boolean $relative If true, the returning path is relative to the currently executed PHP file (not the CLI working directory)
1527
         * @return string|false The local path, with guaranteed trailing path delimiter for directories
1587
         * @return string|false The local path, with guaranteed trailing path delimiter for directories
1528
         */
1588
         */
1529
        public static function localpath($target=null, $relative=false) {
1589
        public static function localpath($target=null, $relative=false) {
1530
                if (is_null($target)) {
1590
                if (is_null($target)) {
1531
                        $target = __DIR__.'/../../';
1591
                        $target = __DIR__.'/../../';
1532
                }
1592
                }
1533
 
1593
 
1534
                if ($relative) {
1594
                if ($relative) {
1535
                        // First, try to find out how many levels we need to go up
1595
                        // First, try to find out how many levels we need to go up
1536
                        $steps_up = self::getExecutingScriptPathDepth();
1596
                        $steps_up = self::getExecutingScriptPathDepth();
1537
                        if ($steps_up === false) return false;
1597
                        if ($steps_up === false) return false;
1538
 
1598
 
1539
                        // Virtually go back from the executing PHP script to the OIDplus base path
1599
                        // Virtually go back from the executing PHP script to the OIDplus base path
1540
                        $res = str_repeat('../',$steps_up);
1600
                        $res = str_repeat('../',$steps_up);
1541
 
1601
 
1542
                        // Then go to the desired location
1602
                        // Then go to the desired location
1543
                        $basedir = realpath(__DIR__.'/../../');
1603
                        $basedir = realpath(__DIR__.'/../../');
1544
                        $target = realpath($target);
1604
                        $target = realpath($target);
1545
                        if ($target === false) return false;
1605
                        if ($target === false) return false;
1546
                        $res .= substr($target, strlen($basedir)+1);
1606
                        $res .= substr($target, strlen($basedir)+1);
1547
                        $res = rtrim($res,'/'); // avoid '..//' for localpath(null,true)
1607
                        $res = rtrim($res,'/'); // avoid '..//' for localpath(null,true)
1548
                } else {
1608
                } else {
1549
                        $res = realpath($target);
1609
                        $res = realpath($target);
1550
                }
1610
                }
1551
 
1611
 
1552
                if (is_dir($target)) $res .= '/';
1612
                if (is_dir($target)) $res .= '/';
1553
 
1613
 
1554
                $res = str_replace('/', DIRECTORY_SEPARATOR, $res);
1614
                $res = str_replace('/', DIRECTORY_SEPARATOR, $res);
1555
 
1615
 
1556
                return $res;
1616
                return $res;
1557
        }
1617
        }
1558
 
1618
 
1559
        /**
1619
        /**
1560
         * Gets a URL pointing to a resource
1620
         * Gets a URL pointing to a resource
1561
         * @param string $target Target resource (file or directory must exist), or null to get the OIDplus base directory
1621
         * @param string $target Target resource (file or directory must exist), or null to get the OIDplus base directory
1562
         * @param int|boolean $mode If true or OIDplus::PATH_RELATIVE, the returning path is relative to the currently executed
1622
         * @param int|boolean $mode If true or OIDplus::PATH_RELATIVE, the returning path is relative to the currently executed
1563
         *                          PHP script (i.e. index.php , not the plugin PHP script!). False or OIDplus::PATH_ABSOLUTE is
1623
         *                          PHP script (i.e. index.php , not the plugin PHP script!). False or OIDplus::PATH_ABSOLUTE is
1564
         *                          results in an absolute URL. OIDplus::PATH_ABSOLUTE_CANONICAL is an absolute URL,
1624
         *                          results in an absolute URL. OIDplus::PATH_ABSOLUTE_CANONICAL is an absolute URL,
1565
         *                          but a canonical path (set by base config setting CANONICAL_SYSTEM_URL) is preferred.
1625
         *                          but a canonical path (set by base config setting CANONICAL_SYSTEM_URL) is preferred.
1566
         * @return string|false The URL, with guaranteed trailing path delimiter for directories
1626
         * @return string|false The URL, with guaranteed trailing path delimiter for directories
1567
         */
1627
         */
1568
        public static function webpath($target=null, $mode=self::PATH_ABSOLUTE_CANONICAL) {
1628
        public static function webpath($target=null, $mode=self::PATH_ABSOLUTE_CANONICAL) {
1569
                // backwards compatibility
1629
                // backwards compatibility
1570
                if ($mode === true) $mode = self::PATH_RELATIVE;
1630
                if ($mode === true) $mode = self::PATH_RELATIVE;
1571
                if ($mode === false) $mode = self::PATH_ABSOLUTE;
1631
                if ($mode === false) $mode = self::PATH_ABSOLUTE;
1572
 
1632
 
1573
                if ($mode == OIDplus::PATH_RELATIVE_TO_ROOT) {
1633
                if ($mode == OIDplus::PATH_RELATIVE_TO_ROOT) {
1574
                        $tmp = OIDplus::webpath($target,OIDplus::PATH_ABSOLUTE);
1634
                        $tmp = OIDplus::webpath($target,OIDplus::PATH_ABSOLUTE);
1575
                        if ($tmp === false) return false;
1635
                        if ($tmp === false) return false;
1576
                        $tmp = parse_url($tmp);
1636
                        $tmp = parse_url($tmp);
1577
                        if ($tmp === false) return false;
1637
                        if ($tmp === false) return false;
1578
                        if (!isset($tmp['path'])) return false;
1638
                        if (!isset($tmp['path'])) return false;
1579
                        return $tmp['path'];
1639
                        return $tmp['path'];
1580
                }
1640
                }
1581
 
1641
 
1582
                if ($mode == OIDplus::PATH_RELATIVE_TO_ROOT_CANONICAL) {
1642
                if ($mode == OIDplus::PATH_RELATIVE_TO_ROOT_CANONICAL) {
1583
                        $tmp = OIDplus::webpath($target,OIDplus::PATH_ABSOLUTE_CANONICAL);
1643
                        $tmp = OIDplus::webpath($target,OIDplus::PATH_ABSOLUTE_CANONICAL);
1584
                        if ($tmp === false) return false;
1644
                        if ($tmp === false) return false;
1585
                        $tmp = parse_url($tmp);
1645
                        $tmp = parse_url($tmp);
1586
                        if ($tmp === false) return false;
1646
                        if ($tmp === false) return false;
1587
                        if (!isset($tmp['path'])) return false;
1647
                        if (!isset($tmp['path'])) return false;
1588
                        return $tmp['path'];
1648
                        return $tmp['path'];
1589
                }
1649
                }
1590
 
1650
 
1591
                $res = self::getSystemUrl($mode); // Note: already contains a trailing path delimiter
1651
                $res = self::getSystemUrl($mode); // Note: already contains a trailing path delimiter
1592
                if ($res === false) return false;
1652
                if ($res === false) return false;
1593
 
1653
 
1594
                if (!is_null($target)) {
1654
                if (!is_null($target)) {
1595
                        $basedir = realpath(__DIR__.'/../../');
1655
                        $basedir = realpath(__DIR__.'/../../');
1596
                        $target = realpath($target);
1656
                        $target = realpath($target);
1597
                        if ($target === false) return false;
1657
                        if ($target === false) return false;
1598
                        $tmp = substr($target, strlen($basedir)+1);
1658
                        $tmp = substr($target, strlen($basedir)+1);
1599
                        $res .= str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
1659
                        $res .= str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
1600
                        if (is_dir($target)) $res .= '/';
1660
                        if (is_dir($target)) $res .= '/';
1601
                }
1661
                }
1602
 
1662
 
1603
                return $res;
1663
                return $res;
1604
        }
1664
        }
1605
 
1665
 
1606
        public static function canonicalURL() {
1666
        public static function canonicalURL() {
1607
                // First part: OIDplus system URL (or canonical system URL)
1667
                // First part: OIDplus system URL (or canonical system URL)
1608
                $sysurl = OIDplus::getSystemUrl(self::PATH_ABSOLUTE_CANONICAL);
1668
                $sysurl = OIDplus::getSystemUrl(self::PATH_ABSOLUTE_CANONICAL);
1609
 
1669
 
1610
                // Second part: Directory
1670
                // Second part: Directory
1611
                $basedir = realpath(__DIR__.'/../../');
1671
                $basedir = realpath(__DIR__.'/../../');
1612
                $target = realpath('.');
1672
                $target = realpath('.');
1613
                if ($target === false) return false;
1673
                if ($target === false) return false;
1614
                $tmp = substr($target, strlen($basedir)+1);
1674
                $tmp = substr($target, strlen($basedir)+1);
1615
                $res = str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
1675
                $res = str_replace(DIRECTORY_SEPARATOR,'/',$tmp); // remove OS specific path delimiters introduced by realpath()
1616
                if (is_dir($target) && ($res != '')) $res .= '/';
1676
                if (is_dir($target) && ($res != '')) $res .= '/';
1617
 
1677
 
1618
                // Third part: File name
1678
                // Third part: File name
1619
                $tmp = explode('/',$_SERVER['SCRIPT_NAME']);
1679
                $tmp = explode('/',$_SERVER['SCRIPT_NAME']);
1620
                $tmp = end($tmp);
1680
                $tmp = end($tmp);
1621
 
1681
 
1622
                // Fourth part: Query string (ordered)
1682
                // Fourth part: Query string (ordered)
1623
                $tmp2 = getSortedQuery();
1683
                $tmp2 = getSortedQuery();
1624
                if ($tmp2 != '') $tmp2 = '?'.$tmp2;
1684
                if ($tmp2 != '') $tmp2 = '?'.$tmp2;
1625
 
1685
 
1626
                return $sysurl.$res.$tmp.$tmp2;
1686
                return $sysurl.$res.$tmp.$tmp2;
1627
        }
1687
        }
1628
 
1688
 
1629
        private static $shutdown_functions = array();
1689
        private static $shutdown_functions = array();
1630
        public static function register_shutdown_function($func) {
1690
        public static function register_shutdown_function($func) {
1631
                self::$shutdown_functions[] = $func;
1691
                self::$shutdown_functions[] = $func;
1632
        }
1692
        }
1633
 
1693
 
1634
        public static function invoke_shutdown() {
1694
        public static function invoke_shutdown() {
1635
                foreach (self::$shutdown_functions as $func) {
1695
                foreach (self::$shutdown_functions as $func) {
1636
                        $func();
1696
                        $func();
1637
                }
1697
                }
1638
        }
1698
        }
1639
 
1699
 
1640
        public static function getAvailableLangs() {
1700
        public static function getAvailableLangs() {
1641
                $langs = array();
1701
                $langs = array();
1642
                foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
1702
                foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
1643
                        $code = $pluginManifest->getLanguageCode();
1703
                        $code = $pluginManifest->getLanguageCode();
1644
                        $langs[] = $code;
1704
                        $langs[] = $code;
1645
                }
1705
                }
1646
                return $langs;
1706
                return $langs;
1647
        }
1707
        }
1648
 
1708
 
1649
        public static function getDefaultLang() {
1709
        public static function getDefaultLang() {
1650
                static $thrownOnce = false; // avoid endless loop inside OIDplusConfigInitializationException
1710
                static $thrownOnce = false; // avoid endless loop inside OIDplusConfigInitializationException
1651
 
1711
 
1652
                $lang = self::baseConfig()->getValue('DEFAULT_LANGUAGE', 'enus');
1712
                $lang = self::baseConfig()->getValue('DEFAULT_LANGUAGE', 'enus');
1653
 
1713
 
1654
                if (!in_array($lang,self::getAvailableLangs())) {
1714
                if (!in_array($lang,self::getAvailableLangs())) {
1655
                        if (!$thrownOnce) {
1715
                        if (!$thrownOnce) {
1656
                                $thrownOnce = true;
1716
                                $thrownOnce = true;
1657
                                throw new OIDplusConfigInitializationException(_L('DEFAULT_LANGUAGE points to an invalid language plugin. (Consider setting to "enus" = "English USA".)'));
1717
                                throw new OIDplusConfigInitializationException(_L('DEFAULT_LANGUAGE points to an invalid language plugin. (Consider setting to "enus" = "English USA".)'));
1658
                        } else {
1718
                        } else {
1659
                                return 'enus';
1719
                                return 'enus';
1660
                        }
1720
                        }
1661
                }
1721
                }
1662
 
1722
 
1663
                return $lang;
1723
                return $lang;
1664
        }
1724
        }
1665
 
1725
 
1666
        public static function getCurrentLang() {
1726
        public static function getCurrentLang() {
1667
                if (isset($_GET['lang'])) {
1727
                if (isset($_GET['lang'])) {
1668
                        $lang = $_GET['lang'];
1728
                        $lang = $_GET['lang'];
1669
                } else if (isset($_POST['lang'])) {
1729
                } else if (isset($_POST['lang'])) {
1670
                        $lang = $_POST['lang'];
1730
                        $lang = $_POST['lang'];
1671
                } else if (isset($_COOKIE['LANGUAGE'])) {
1731
                } else if (isset($_COOKIE['LANGUAGE'])) {
1672
                        $lang = $_COOKIE['LANGUAGE'];
1732
                        $lang = $_COOKIE['LANGUAGE'];
1673
                } else {
1733
                } else {
1674
                        $lang = self::getDefaultLang();
1734
                        $lang = self::getDefaultLang();
1675
                }
1735
                }
1676
                $lang = substr(preg_replace('@[^a-z]@ismU', '', $lang),0,4); // sanitize
1736
                $lang = substr(preg_replace('@[^a-z]@ismU', '', $lang),0,4); // sanitize
1677
                return $lang;
1737
                return $lang;
1678
        }
1738
        }
1679
 
1739
 
1680
        public static function handleLangArgument() {
1740
        public static function handleLangArgument() {
1681
                if (isset($_GET['lang'])) {
1741
                if (isset($_GET['lang'])) {
1682
                        // The "?lang=" argument is only for NoScript-Browsers/SearchEngines
1742
                        // The "?lang=" argument is only for NoScript-Browsers/SearchEngines
1683
                        // In case someone who has JavaScript clicks a ?lang= link, they should get
1743
                        // In case someone who has JavaScript clicks a ?lang= link, they should get
1684
                        // the page in that language, but the cookie must be set, otherwise
1744
                        // the page in that language, but the cookie must be set, otherwise
1685
                        // the menu and other stuff would be in their cookie-based-language and not the
1745
                        // the menu and other stuff would be in their cookie-based-language and not the
1686
                        // argument-based-language.
1746
                        // argument-based-language.
1687
                        OIDplus::cookieUtils()->setcookie('LANGUAGE', $_GET['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
1747
                        OIDplus::cookieUtils()->setcookie('LANGUAGE', $_GET['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
1688
                } else if (isset($_POST['lang'])) {
1748
                } else if (isset($_POST['lang'])) {
1689
                        OIDplus::cookieUtils()->setcookie('LANGUAGE', $_POST['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
1749
                        OIDplus::cookieUtils()->setcookie('LANGUAGE', $_POST['lang'], 0, true/*HttpOnly off, because JavaScript also needs translation*/);
1690
                }
1750
                }
1691
        }
1751
        }
1692
 
1752
 
1693
        private static $translationArray = array();
1753
        private static $translationArray = array();
1694
        protected static function getTranslationFileContents($translation_file) {
1754
        protected static function getTranslationFileContents($translation_file) {
1695
                // First, try the cache
1755
                // First, try the cache
1696
                $cache_file = __DIR__ . '/../../userdata/cache/translation_'.md5($translation_file).'.ser';
1756
                $cache_file = __DIR__ . '/../../userdata/cache/translation_'.md5($translation_file).'.ser';
1697
                if (file_exists($cache_file) && (filemtime($cache_file) == filemtime($translation_file))) {
1757
                if (file_exists($cache_file) && (filemtime($cache_file) == filemtime($translation_file))) {
1698
                        $cac = @unserialize(file_get_contents($cache_file));
1758
                        $cac = @unserialize(file_get_contents($cache_file));
1699
                        if ($cac) return $cac;
1759
                        if ($cac) return $cac;
1700
                }
1760
                }
1701
 
1761
 
1702
                // If not successful, then load the XML file
1762
                // If not successful, then load the XML file
1703
                $xml = @simplexml_load_string(file_get_contents($translation_file));
1763
                $xml = @simplexml_load_string(file_get_contents($translation_file));
1704
                if (!$xml) return array(); // if there is an UTF-8 or parsing error, don't output any errors, otherwise the JavaScript is corrupt and the page won't render correctly
1764
                if (!$xml) return array(); // if there is an UTF-8 or parsing error, don't output any errors, otherwise the JavaScript is corrupt and the page won't render correctly
1705
                $cac = array();
1765
                $cac = array();
1706
                foreach ($xml->message as $msg) {
1766
                foreach ($xml->message as $msg) {
1707
                        $src = trim($msg->source->__toString());
1767
                        $src = trim($msg->source->__toString());
1708
                        $dst = trim($msg->target->__toString());
1768
                        $dst = trim($msg->target->__toString());
1709
                        $cac[$src] = $dst;
1769
                        $cac[$src] = $dst;
1710
                }
1770
                }
1711
                @file_put_contents($cache_file,serialize($cac));
1771
                @file_put_contents($cache_file,serialize($cac));
1712
                @touch($cache_file,filemtime($translation_file));
1772
                @touch($cache_file,filemtime($translation_file));
1713
                return $cac;
1773
                return $cac;
1714
        }
1774
        }
1715
        public static function getTranslationArray($requested_lang='*') {
1775
        public static function getTranslationArray($requested_lang='*') {
1716
                foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
1776
                foreach (OIDplus::getAllPluginManifests('language') as $pluginManifest) {
1717
                        $lang = $pluginManifest->getLanguageCode();
1777
                        $lang = $pluginManifest->getLanguageCode();
1718
                        if (strpos($lang,'/') !== false) continue; // just to be sure
1778
                        if (strpos($lang,'/') !== false) continue; // just to be sure
1719
                        if (strpos($lang,'\\') !== false) continue; // just to be sure
1779
                        if (strpos($lang,'\\') !== false) continue; // just to be sure
1720
                        if (strpos($lang,'..') !== false) continue; // just to be sure
1780
                        if (strpos($lang,'..') !== false) continue; // just to be sure
1721
 
1781
 
1722
                        if (($requested_lang != '*') && ($lang != $requested_lang)) continue;
1782
                        if (($requested_lang != '*') && ($lang != $requested_lang)) continue;
1723
 
1783
 
1724
                        if (!isset(self::$translationArray[$lang])) {
1784
                        if (!isset(self::$translationArray[$lang])) {
1725
                                self::$translationArray[$lang] = array();
1785
                                self::$translationArray[$lang] = array();
1726
 
1786
 
1727
                                $wildcard = $pluginManifest->getLanguageMessages();
1787
                                $wildcard = $pluginManifest->getLanguageMessages();
1728
                                if (strpos($wildcard,'/') !== false) continue; // just to be sure
1788
                                if (strpos($wildcard,'/') !== false) continue; // just to be sure
1729
                                if (strpos($wildcard,'\\') !== false) continue; // just to be sure
1789
                                if (strpos($wildcard,'\\') !== false) continue; // just to be sure
1730
                                if (strpos($wildcard,'..') !== false) continue; // just to be sure
1790
                                if (strpos($wildcard,'..') !== false) continue; // just to be sure
1731
 
1791
 
1732
                                $translation_files = glob(__DIR__.'/../../plugins/'.'*'.'/language/'.$lang.'/'.$wildcard);
1792
                                $translation_files = glob(__DIR__.'/../../plugins/'.'*'.'/language/'.$lang.'/'.$wildcard);
1733
                                sort($translation_files);
1793
                                sort($translation_files);
1734
                                foreach ($translation_files as $translation_file) {
1794
                                foreach ($translation_files as $translation_file) {
1735
                                        if (!file_exists($translation_file)) continue;
1795
                                        if (!file_exists($translation_file)) continue;
1736
                                        $cac = self::getTranslationFileContents($translation_file);
1796
                                        $cac = self::getTranslationFileContents($translation_file);
1737
                                        foreach ($cac as $src => $dst) {
1797
                                        foreach ($cac as $src => $dst) {
1738
                                                self::$translationArray[$lang][$src] = $dst;
1798
                                                self::$translationArray[$lang][$src] = $dst;
1739
                                        }
1799
                                        }
1740
                                }
1800
                                }
1741
                        }
1801
                        }
1742
                }
1802
                }
1743
                return self::$translationArray;
1803
                return self::$translationArray;
1744
        }
1804
        }
1745
 
1805
 
1746
        public static function getEditionInfo() {
1806
        public static function getEditionInfo() {
1747
                return @parse_ini_file(__DIR__.'/../edition.ini', true)['Edition'];
1807
                return @parse_ini_file(__DIR__.'/../edition.ini', true)['Edition'];
1748
        }
1808
        }
1749
 
1809
 
1750
        public static function findGitFolder() {
1810
        public static function findGitFolder() {
1751
                // Git command line saves git information in folder ".git"
1811
                // Git command line saves git information in folder ".git"
1752
                // Plesk git saves git information in folder "../../../git/oidplus/" (or similar)
1812
                // Plesk git saves git information in folder "../../../git/oidplus/" (or similar)
1753
                $dir = OIDplus::localpath();
1813
                $dir = OIDplus::localpath();
1754
                if (is_dir($dir.'/.git')) return $dir.'/.git';
1814
                if (is_dir($dir.'/.git')) return $dir.'/.git';
1755
                $i = 0;
1815
                $i = 0;
1756
                do {
1816
                do {
1757
                        if (is_dir($dir.'/git')) {
1817
                        if (is_dir($dir.'/git')) {
1758
                                $confs = @glob($dir.'/git/'.'*'.'/config');
1818
                                $confs = @glob($dir.'/git/'.'*'.'/config');
1759
                                if ($confs) foreach ($confs as $conf) {
1819
                                if ($confs) foreach ($confs as $conf) {
1760
                                        $cont = file_get_contents($conf);
1820
                                        $cont = file_get_contents($conf);
1761
                                        if (isset(OIDplus::getEditionInfo()['gitrepo']) && (OIDplus::getEditionInfo()['gitrepo'] != '') && (strpos($cont, OIDplus::getEditionInfo()['gitrepo']) !== false)) {
1821
                                        if (isset(OIDplus::getEditionInfo()['gitrepo']) && (OIDplus::getEditionInfo()['gitrepo'] != '') && (strpos($cont, OIDplus::getEditionInfo()['gitrepo']) !== false)) {
1762
                                                return dirname($conf);
1822
                                                return dirname($conf);
1763
                                        }
1823
                                        }
1764
                                }
1824
                                }
1765
                        }
1825
                        }
1766
                        $i++;
1826
                        $i++;
1767
                } while (($i<100) && ($dir != ($new_dir = @realpath($dir.'/../'))) && ($dir = $new_dir));
1827
                } while (($i<100) && ($dir != ($new_dir = @realpath($dir.'/../'))) && ($dir = $new_dir));
1768
                return false;
1828
                return false;
1769
        }
1829
        }
1770
 
1830
 
1771
        public static function getGitsvnRevision($dir='') {
1831
        public static function getGitsvnRevision($dir='') {
1772
                try {
1832
                try {
1773
                        // tries command line and binary parsing
1833
                        // tries command line and binary parsing
1774
                        // requires vendor/danielmarschall/git_utils.inc.php
1834
                        // requires vendor/danielmarschall/git_utils.inc.php
1775
                        $git_dir = OIDplus::findGitFolder();
1835
                        $git_dir = OIDplus::findGitFolder();
1776
                        if ($git_dir === false) return false;
1836
                        if ($git_dir === false) return false;
1777
                        $commit_msg = git_get_latest_commit_message($git_dir);
1837
                        $commit_msg = git_get_latest_commit_message($git_dir);
1778
                } catch (Exception $e) {
1838
                } catch (\Exception $e) {
1779
                        return false;
1839
                        return false;
1780
                }
1840
                }
1781
 
1841
 
1782
                $m = array();
1842
                $m = array();
1783
                if (preg_match('%git-svn-id: (.+)@(\\d+) %ismU', $commit_msg, $m)) {
1843
                if (preg_match('%git-svn-id: (.+)@(\\d+) %ismU', $commit_msg, $m)) {
1784
                        return $m[2];
1844
                        return $m[2];
1785
                } else {
1845
                } else {
1786
                        return false;
1846
                        return false;
1787
                }
1847
                }
1788
        }
1848
        }
1789
 
1849
 
1790
        public static function prefilterQuery($static_node_id, $throw_exception) {
1850
        public static function prefilterQuery($static_node_id, $throw_exception) {
1791
                // Let namespace be case-insensitive
1851
                // Let namespace be case-insensitive
1792
                $ary = explode(':', $static_node_id, 2);
1852
                $ary = explode(':', $static_node_id, 2);
1793
                $ary[0] = strtolower($ary[0]);
1853
                $ary[0] = strtolower($ary[0]);
1794
                $static_node_id = implode(':', $ary);
1854
                $static_node_id = implode(':', $ary);
1795
 
1855
 
1796
                // Ask plugins if they want to change the node id
1856
                // Ask plugins if they want to change the node id
1797
                foreach (OIDplus::getObjectTypePluginsEnabled() as $plugin) {
1857
                foreach (OIDplus::getObjectTypePluginsEnabled() as $plugin) {
1798
                        $static_node_id = $plugin->prefilterQuery($static_node_id, $throw_exception);
1858
                        $static_node_id = $plugin->prefilterQuery($static_node_id, $throw_exception);
1799
                }
1859
                }
1800
 
1860
 
1801
                return $static_node_id;
1861
                return $static_node_id;
1802
        }
1862
        }
1803
 
1863
 
1804
        public static function isCronjob() {
1864
        public static function isCronjob() {
1805
                return explode('.',basename($_SERVER['SCRIPT_NAME']))[0] === 'cron';
1865
                return explode('.',basename($_SERVER['SCRIPT_NAME']))[0] === 'cron';
1806
        }
1866
        }
1807
 
1867
 
1808
        private static function recanonizeObjects() {
1868
        private static function recanonizeObjects() {
1809
                #
1869
                //
1810
                # Since OIDplus svn-184, entries in the database need to have a canonical ID
1870
                // Since OIDplus svn-184, entries in the database need to have a canonical ID
1811
                # If the ID is not canonical (e.g. GUIDs missing hyphens), the object cannot be opened in OIDplus
1871
                // If the ID is not canonical (e.g. GUIDs missing hyphens), the object cannot be opened in OIDplus
1812
                # This script re-canonizes the object IDs if required.
1872
                // This script re-canonizes the object IDs if required.
1813
                # In SVN Rev 856, the canonization for GUID, IPv4 and IPv6 have changed, requiring another
1873
                // In SVN Rev 856, the canonization for GUID, IPv4 and IPv6 have changed, requiring another
1814
                # re-canonization
1874
                // re-canonization
1815
                #
1875
                //
1816
                $res = OIDplus::db()->query("select id from ###objects");
1876
                $res = OIDplus::db()->query("select id from ###objects");
1817
                while ($row = $res->fetch_array()) {
1877
                while ($row = $res->fetch_array()) {
1818
                        $ida = $row['id'];
1878
                        $ida = $row['id'];
1819
                        $obj = OIDplusObject::parse($ida);
1879
                        $obj = OIDplusObject::parse($ida);
1820
                        if (!$obj) continue;
1880
                        if (!$obj) continue;
1821
                        $idb = $obj->nodeId();
1881
                        $idb = $obj->nodeId();
1822
                        if (($idb) && ($ida != $idb)) {
1882
                        if (($idb) && ($ida != $idb)) {
1823
                                OIDplus::db()->transaction_begin();
1883
                                OIDplus::db()->transaction_begin();
1824
                                OIDplus::db()->query("update ###objects set id = ? where id = ?", array($idb, $ida));
1884
                                OIDplus::db()->query("update ###objects set id = ? where id = ?", array($idb, $ida));
1825
                                OIDplus::db()->query("update ###asn1id set oid = ? where oid = ?", array($idb, $ida));
1885
                                OIDplus::db()->query("update ###asn1id set oid = ? where oid = ?", array($idb, $ida));
1826
                                OIDplus::db()->query("update ###iri set oid = ? where oid = ?", array($idb, $ida));
1886
                                OIDplus::db()->query("update ###iri set oid = ? where oid = ?", array($idb, $ida));
1827
                                OIDplus::db()->query("update ###log_object set id = ? where id = ?", array($idb, $ida));
1887
                                OIDplus::db()->query("update ###log_object set id = ? where id = ?", array($idb, $ida));
1828
                                OIDplus::logger()->log("[INFO]A!", "Object name '$ida' has been changed to '$idb' during re-canonization");
1888
                                OIDplus::logger()->log("[INFO]A!", "Object name '$ida' has been changed to '$idb' during re-canonization");
1829
                                OIDplus::db()->transaction_commit();
1889
                                OIDplus::db()->transaction_commit();
1830
                                OIDplusObject::resetObjectInformationCache();
1890
                                OIDplusObject::resetObjectInformationCache();
1831
                        }
1891
                        }
1832
                }
1892
                }
1833
        }
1893
        }
1834
 
1894
 
1835
}
1895
}
1836
 
1896