Subversion Repositories oidplus

Rev

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

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