Subversion Repositories oidplus

Rev

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

Rev Author Line No. Line
635 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
1086 daniel-mar 5
 * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
635 daniel-mar 6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
 
1050 daniel-mar 20
namespace ViaThinkSoft\OIDplus;
635 daniel-mar 21
 
1086 daniel-mar 22
// phpcs:disable PSR1.Files.SideEffects
23
\defined('INSIDE_OIDPLUS') or die;
24
// phpcs:enable PSR1.Files.SideEffects
25
 
1131 daniel-mar 26
class OIDplusPagePublicObjects extends OIDplusPagePluginPublic
27
        implements INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_1, /* oobeEntry, oobeRequested */
1278 daniel-mar 28
                   INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_2, /* modifyContent */
1265 daniel-mar 29
                   INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_8, /* getNotifications */
1275 daniel-mar 30
                   INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_9  /* restApi* */
1131 daniel-mar 31
                   // Important: Do NOT implement INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_7, because our getAlternativesForQuery() is the one that calls others!
32
{
635 daniel-mar 33
 
1116 daniel-mar 34
        /**
1130 daniel-mar 35
         * @param string|OIDplusObject $ot
1116 daniel-mar 36
         * @return string|null
37
         */
38
        private function get_treeicon_root($ot)/*: ?string*/ {
1127 daniel-mar 39
                $root = $ot::parse($ot::root());
40
                if (!$root) return null;
41
                return $root->getIcon();
635 daniel-mar 42
        }
43
 
1116 daniel-mar 44
        /**
1130 daniel-mar 45
         * @param string $id
46
         * @param string $old_ra
47
         * @param string $new_ra
1116 daniel-mar 48
         * @return void
49
         * @throws OIDplusConfigInitializationException
50
         * @throws OIDplusException
51
         */
1130 daniel-mar 52
        private function ra_change_rec(string $id, string $old_ra, string $new_ra) {
635 daniel-mar 53
                OIDplus::db()->query("update ###objects set ra_email = ?, updated = ".OIDplus::db()->sqlDate()." where id = ? and ".OIDplus::db()->getSlang()->isNullFunction('ra_email',"''")." = ?", array($new_ra, $id, $old_ra));
978 daniel-mar 54
                OIDplusObject::resetObjectInformationCache();
635 daniel-mar 55
 
56
                $res = OIDplus::db()->query("select id from ###objects where parent = ? and ".OIDplus::db()->getSlang()->isNullFunction('ra_email',"''")." = ?", array($id, $old_ra));
57
                while ($row = $res->fetch_array()) {
58
                        $this->ra_change_rec($row['id'], $old_ra, $new_ra);
59
                }
60
        }
61
 
1116 daniel-mar 62
        /**
1278 daniel-mar 63
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_2
64
         * @param string $id
65
         * @param string $title
66
         * @param string $icon
67
         * @param string $text
68
         * @return void
69
         * @throws \ViaThinkSoft\OIDplus\OIDplusException
70
         */
71
        public function modifyContent(string $id, string &$title, string &$icon, string &$text) {
1375 daniel-mar 72
                $payload = '<br /> <a href="'.OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL)
1278 daniel-mar 73
                        .'rest/v1/objects/'.htmlentities($id).'" class="gray_footer_font" target="_blank">'._L('REST API').'</a> '
74
                        .'(<a '.OIDplus::gui()->link('oidplus:rest_api_information_admin$endpoints:1.3.6.1.4.1.37476.2.5.2.4.1.0').' class="gray_footer_font">'._L('Documentation').'</a>)';
1279 daniel-mar 75
 
76
                $text = str_replace('<!-- MARKER 6 -->', '<!-- MARKER 6 -->'.$payload, $text);
1278 daniel-mar 77
        }
78
 
79
        /**
1265 daniel-mar 80
         * @param string $endpoint
1275 daniel-mar 81
         * @param array $json_in
1295 daniel-mar 82
         * @return never-return
1265 daniel-mar 83
         */
1295 daniel-mar 84
        private function restApiCall_OPTIONS(string $endpoint, array $json_in) {
85
                header("access-control-allow-credentials: true");
86
                header("access-control-allow-headers: Keep-Alive,User-Agent,Authorization");
87
                header("access-control-allow-methods: GET, PUT, POST, DELETE, PATCH, OPTIONS");
88
                header("access-control-allow-origin: *");
89
                http_response_code(204/*No content*/);
90
                OIDplus::invoke_shutdown();
91
                die(); // return array();
92
        }
93
 
94
        /**
1299 daniel-mar 95
         * REST method for selecting
1295 daniel-mar 96
         * @param string $endpoint
97
         * @param array $json_in
98
         * @return array
99
         */
100
        private function restApiCall_GET(string $endpoint, array $json_in): array {
101
                $id = substr($endpoint, strlen('objects/'));
102
                $obj = OIDplusObject::findFitting($id);
103
                if (!$obj) throw new OIDplusException(_L('The object %1 was not found in this database.', $id), null, 404);
104
 
105
                if (!$obj->userHasReadRights()) throw new OIDplusException('Insufficient authorization to read information about this object.', null, 401);
106
 
107
                $output = array();
108
 
109
                $output['status'] = 0/*OK*/;
110
                $output['status_bits'] = [];
111
 
112
                //$output['id'] = $obj->nodeId(true);
113
                $output['ra_email'] = $obj->getRaMail();
114
                $output['comment'] = $obj->getComment();
115
                $output['confidential'] = $obj->isConfidential();
116
                $output['title'] = $obj->getTitle();
117
                $output['description'] = $obj->getDescription();
118
 
119
                if ($obj instanceof OIDplusOid) {
120
                        $output['asn1ids'] = array(); // TODO: Rename to oid-alphanum-id ?
121
                        foreach ($obj->getAsn1Ids() as $asn) {
122
                                $output['asn1ids'][] = $asn->getName();
1285 daniel-mar 123
                        }
1280 daniel-mar 124
 
1295 daniel-mar 125
                        $output['iris'] = array(); // TODO: Rename to oid-unicode-label ?
126
                        foreach ($obj->getIris() as $iri) {
127
                                $output['iris'][] = $iri->getName();
128
                        }
129
                }
1280 daniel-mar 130
 
1295 daniel-mar 131
                http_response_code(200);
132
                return $output;
133
        }
1271 daniel-mar 134
 
1295 daniel-mar 135
        /**
1299 daniel-mar 136
         * REST method for replacing (re-create)
1295 daniel-mar 137
         * @param string $endpoint
138
         * @param array $json_in
139
         * @return array
140
         */
141
        private function restApiCall_PUT(string $endpoint, array $json_in): array {
142
                $id = substr($endpoint, strlen('objects/'));
143
                $obj = OIDplusObject::parse($id);
144
                if (!$obj) throw new OIDplusException(_L('%1 action failed because object "%2" cannot be parsed!', 'PUT', $id), null, 400);
1271 daniel-mar 145
 
1299 daniel-mar 146
                // ATTENTION: Do *not* use $params=$json_in. We intentionally set $params to empty strings if the values do not exist in $json_in,
147
                //            because PUT is for re-creating the whole object!
1295 daniel-mar 148
                $params = array();
149
                $params['id'] = $id;
150
                $params['ra_email'] = $json_in['ra_email'] ?? '';
151
                $params['comment'] = $json_in['comment'] ?? '';
152
                $params['confidential'] = $json_in['confidential'] ?? false;
153
                $params['title'] = $json_in['title'] ?? '';
154
                $params['description'] = $json_in['description'] ?? '';
155
                $params['asn1ids'] = $json_in['asn1ids'] ?? array();
156
                $params['iris'] = $json_in['iris'] ?? array();
1271 daniel-mar 157
 
1295 daniel-mar 158
                if (OIDplusObject::exists($id)) {
159
                        // TODO: Problem: The superior RA cannot set title/description, so they cannot perform the PUT command!
160
                        $output = self::action_Update($params);
161
                } else {
162
                        $params['parent'] = $obj->getParent();
163
                        $params['id_fully_qualified'] = true;
164
                        $output = self::action_Insert($params);
165
                }
1271 daniel-mar 166
 
1295 daniel-mar 167
                $output['status_bits'] = [];
168
                if (($output['status'] & 1) == 1) $output['status_bits'][1] = 'RA is not registered, but it can be invited';
169
                if (($output['status'] & 2) == 2) $output['status_bits'][2] = 'RA is not registered and it cannot be invited';
170
                if (($output['status'] & 4) == 4) $output['status_bits'][4] = 'OID is a well-known OID, so RA, ASN.1, and IRI identifiers were reset';
171
                if (($output['status'] & 8) == 8) $output['status_bits'][8] = 'User has write rights to the freshly created OID';
1271 daniel-mar 172
 
1295 daniel-mar 173
                http_response_code(200);
174
                return $output;
175
        }
1271 daniel-mar 176
 
1295 daniel-mar 177
        /**
1299 daniel-mar 178
         * REST method for inserting (create)
1295 daniel-mar 179
         * @param string $endpoint
180
         * @param array $json_in
181
         * @return array
182
         */
183
        private function restApiCall_POST(string $endpoint, array $json_in): array {
184
                $id = substr($endpoint, strlen('objects/'));
185
                $obj = OIDplusObject::parse($id);
186
                if (!$obj) throw new OIDplusException(_L('%1 action failed because object "%2" cannot be parsed!', 'GET', $id), null, 400);
187
                $params = $json_in;
188
                $params['parent'] = $obj->getParent();
189
                $params['id_fully_qualified'] = true;
190
                $params['id'] = $id;
191
                $output = self::action_Insert($params);
1271 daniel-mar 192
 
1295 daniel-mar 193
                $output['status_bits'] = [];
194
                if (($output['status'] & 1) == 1) $output['status_bits'][1] = 'RA is not registered, but it can be invited';
195
                if (($output['status'] & 2) == 2) $output['status_bits'][2] = 'RA is not registered and it cannot be invited';
196
                if (($output['status'] & 4) == 4) $output['status_bits'][4] = 'OID is a well-known OID, so RA, ASN.1, and IRI identifiers were reset';
197
                if (($output['status'] & 8) == 8) $output['status_bits'][8] = 'User has write rights to the freshly created OID';
1276 daniel-mar 198
 
1295 daniel-mar 199
                http_response_code(200);
200
                return $output;
201
        }
1276 daniel-mar 202
 
1295 daniel-mar 203
        /**
1299 daniel-mar 204
         * REST method for modification
1295 daniel-mar 205
         * @param string $endpoint
206
         * @param array $json_in
207
         * @return array
208
         */
209
        private function restApiCall_PATCH(string $endpoint, array $json_in): array {
210
                $id = substr($endpoint, strlen('objects/'));
211
                $params = $json_in;
212
                $params['id'] = $id;
213
                $output = self::action_Update($params);
1276 daniel-mar 214
 
1295 daniel-mar 215
                $output['status_bits'] = [];
216
                if (($output['status'] & 1) == 1) $output['status_bits'][1] = 'RA is not registered, but it can be invited';
217
                if (($output['status'] & 2) == 2) $output['status_bits'][2] = 'RA is not registered and it cannot be invited';
218
                if (($output['status'] & 4) == 4) $output['status_bits'][4] = 'OID is a well-known OID, so RA, ASN.1, and IRI identifiers were reset';
219
                if (($output['status'] & 8) == 8) $output['status_bits'][8] = 'User has write rights to the freshly created OID';
1276 daniel-mar 220
 
1295 daniel-mar 221
                http_response_code(200);
222
                return $output;
223
        }
1276 daniel-mar 224
 
1295 daniel-mar 225
        /**
1299 daniel-mar 226
         * REST method for deleting
1295 daniel-mar 227
         * @param string $endpoint
228
         * @param array $json_in
229
         * @return array
230
         */
231
        private function restApiCall_DELETE(string $endpoint, array $json_in): array {
232
                $id = substr($endpoint, strlen('objects/'));
233
                $params = $json_in;
234
                $params['id'] = $id;
235
                $output = self::action_Delete($params);
1276 daniel-mar 236
 
1295 daniel-mar 237
                $output['status_bits'] = [];
1276 daniel-mar 238
 
1295 daniel-mar 239
                http_response_code(200);
240
                return $output;
241
        }
1276 daniel-mar 242
 
1295 daniel-mar 243
        /**
244
         * Implements INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_9
245
         * @param string $requestMethod
246
         * @param string $endpoint
247
         * @param array $json_in
248
         * @return array|false
249
         */
250
        public function restApiCall(string $requestMethod, string $endpoint, array $json_in) {
251
                if (str_starts_with($endpoint, 'objects/')) {
252
                        if ($requestMethod == "OPTIONS") {
1385 daniel-mar 253
                                // Note: On some web servers, the server software might catch OPTIONS and not forward it to PHP
1295 daniel-mar 254
                                $this->restApiCall_OPTIONS($endpoint, $json_in);
1299 daniel-mar 255
                        } else if ($requestMethod == "GET"/*Select*/) {
1295 daniel-mar 256
                                return $this->restApiCall_GET($endpoint, $json_in);
257
                        } else if ($requestMethod == "PUT"/*Replace*/) {
258
                                return $this->restApiCall_PUT($endpoint, $json_in);
259
                        } else if ($requestMethod == "POST"/*Insert*/) {
260
                                return $this->restApiCall_POST($endpoint, $json_in);
261
                        } else if ($requestMethod == "PATCH"/*Modify*/) {
262
                                return $this->restApiCall_PATCH($endpoint, $json_in);
263
                        } else if ($requestMethod == "DELETE"/*Delete*/) {
264
                                return $this->restApiCall_DELETE($endpoint, $json_in);
1265 daniel-mar 265
                        } else {
1271 daniel-mar 266
                                //throw new OIDplusException(_L("Not implemented"), null, 501);
267
                                throw new OIDplusException(_L("Unsupported request method"), null, 400);
1265 daniel-mar 268
                        }
269
                } else {
270
                        return false;
271
                }
272
        }
273
 
274
        /**
275
         * Implements INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_9
276
         * Outputs information about valid endpoints
277
         * @param string $kind Reserved for different kind of output format (i.e. OpenAPI "TODO"). Currently only 'html' is implemented
278
         * @return string
279
         */
280
        public function restApiInfo(string $kind='html'): string {
281
                if ($kind === 'html') {
1271 daniel-mar 282
                        $struct = [
1273 daniel-mar 283
                                _L('Receive') => [
284
                                        '<b>GET</b> '.OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL).'rest/v1/objects/<abbr title="'._L('e.g. %1', 'oid:2.999').'">[id]</abbr>',
1272 daniel-mar 285
                                        _L('Input parameters') => [
286
                                                '<i>'._L('None').'</i>'
1271 daniel-mar 287
                                        ],
1272 daniel-mar 288
                                        _L('Output parameters') => [
1275 daniel-mar 289
                                                'status ('._L('<0 is error, >=0 is success').')',
1276 daniel-mar 290
                                                'status_bits',
1275 daniel-mar 291
                                                'error ('._L('if an error occurred').')',
1272 daniel-mar 292
                                                'ra_email',
293
                                                'comment',
1280 daniel-mar 294
                                                'iris ('._L('for OID only').')',
295
                                                'asn1ids ('._L('for OID only').')',
1272 daniel-mar 296
                                                'confidential',
297
                                                'title',
298
                                                'description'
299
                                        ]
300
                                ],
1273 daniel-mar 301
                                _L('Re-Create') => [
302
                                        '<b>PUT</b> '.OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL).'rest/v1/objects/<abbr title="'._L('e.g. %1', 'oid:2.999').'">[id]</abbr>',
1272 daniel-mar 303
                                        _L('Input parameters') => [
304
                                                'ra_email ('._L('optional').')',
305
                                                'comment ('._L('optional').')',
306
                                                'iris ('._L('optional').')',
307
                                                'asn1ids ('._L('optional').')',
308
                                                'confidential ('._L('optional').')',
309
                                                'title ('._L('optional').')',
310
                                                'description ('._L('optional').')'
1271 daniel-mar 311
                                        ],
1272 daniel-mar 312
                                        _L('Output parameters') => [
1275 daniel-mar 313
                                                'status ('._L('<0 is error, >=0 is success').')',
1276 daniel-mar 314
                                                'status_bits',
1275 daniel-mar 315
                                                'error ('._L('if an error occurred').')',
1272 daniel-mar 316
                                                'inserted_id ('._L('if it was created').')'
317
                                        ]
318
                                ],
1273 daniel-mar 319
                                _L('Create') => [
320
                                        '<b>POST</b> '.OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL).'rest/v1/objects/<abbr title="'._L('e.g. %1', 'oid:2.999').'">[id]</abbr>',
1272 daniel-mar 321
                                        _L('Input parameters') => [
322
                                                'ra_email ('._L('optional').')',
323
                                                'comment ('._L('optional').')',
324
                                                'iris ('._L('optional').')',
325
                                                'asn1ids ('._L('optional').')',
326
                                                'confidential ('._L('optional').')',
327
                                                'title ('._L('optional').')',
328
                                                'description ('._L('optional').')'
1271 daniel-mar 329
                                        ],
1272 daniel-mar 330
                                        _L('Output parameters') => [
1275 daniel-mar 331
                                                'status ('._L('<0 is error, >=0 is success').')',
1276 daniel-mar 332
                                                'status_bits',
1275 daniel-mar 333
                                                'error ('._L('if an error occurred').')',
1272 daniel-mar 334
                                                'inserted_id'
335
                                        ]
336
                                ],
1273 daniel-mar 337
                                _L('Update') => [
338
                                        '<b>PATCH</b> '.OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL).'rest/v1/objects/<abbr title="'._L('e.g. %1', 'oid:2.999').'">[id]</abbr>',
1272 daniel-mar 339
                                        _L('Input parameters') => [
340
                                                'ra_email ('._L('optional').')',
341
                                                'comment ('._L('optional').')',
342
                                                'iris ('._L('optional').')',
343
                                                'asn1ids ('._L('optional').')',
344
                                                'confidential ('._L('optional').')',
345
                                                'title ('._L('optional').')',
346
                                                'description ('._L('optional').')'
1271 daniel-mar 347
                                        ],
1272 daniel-mar 348
                                        _L('Output parameters') => [
1275 daniel-mar 349
                                                'status ('._L('<0 is error, >=0 is success').')',
1276 daniel-mar 350
                                                'status_bits',
1275 daniel-mar 351
                                                'error ('._L('if an error occurred').')',
1271 daniel-mar 352
                                        ]
1272 daniel-mar 353
                                ],
1273 daniel-mar 354
                                _L('Remove') => [
1276 daniel-mar 355
                                        '<b>DELETE</b> '.OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL).'rest/v1/objects/<abbr title="'._L('e.g. %1', 'oid:2.999').'">[id]</abbr>',
1272 daniel-mar 356
                                        _L('Input parameters') => [
357
                                                '<i>'._L('None').'</i>'
358
                                        ],
359
                                        _L('Output parameters') => [
1275 daniel-mar 360
                                                'status ('._L('<0 is error, >=0 is success').')',
1276 daniel-mar 361
                                                'status_bits',
1275 daniel-mar 362
                                                'error ('._L('if an error occurred').')',
1272 daniel-mar 363
                                        ]
1271 daniel-mar 364
                                ]
365
                        ];
1276 daniel-mar 366
                        return array_to_html_ul_li($struct);
1265 daniel-mar 367
                } else {
1271 daniel-mar 368
                        throw new OIDplusException(_L('Invalid REST API information format'), null, 500);
1265 daniel-mar 369
                }
370
        }
371
 
372
        /**
1291 daniel-mar 373
         * @param array $params id
374
         * @return array status<0 Error, =0 Success
1116 daniel-mar 375
         * @throws OIDplusConfigInitializationException
376
         * @throws OIDplusException
377
         */
1291 daniel-mar 378
        private function action_Delete(array $params): array {
379
                _CheckParamExists($params, 'id');
380
                $id = $params['id'];
381
                $obj = OIDplusObject::parse($id);
382
                if (!$obj) throw new OIDplusException(_L('%1 action failed because object "%2" cannot be parsed!','DELETE',$id));
635 daniel-mar 383
 
1291 daniel-mar 384
                if (!OIDplusObject::exists($id)) {
385
                        throw new OIDplusException(_L('Object %1 does not exist',$id), null, 404);
386
                }
635 daniel-mar 387
 
1291 daniel-mar 388
                // Check if permitted
389
                if (!$obj->userHasParentalWriteRights()) throw new OIDplusException(_L('Authentication error. Please log in as the superior RA to delete this OID.'), null, 401);
635 daniel-mar 390
 
1291 daniel-mar 391
                foreach (OIDplus::getAllPlugins() as $plugin) {
392
                        if ($plugin instanceof INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3) {
393
                                $plugin->beforeObjectDelete($id);
635 daniel-mar 394
                        }
1291 daniel-mar 395
                }
635 daniel-mar 396
 
1291 daniel-mar 397
                OIDplus::logger()->log("V2:[WARN]OID(%1)+[OK/WARN]SUPOIDRA(%1)+[OK/INFO]A", "Object '%1' (recursively) deleted", $id);
398
                OIDplus::logger()->log("V2:[CRIT]OIDRA(%1)", "Lost ownership of object '%1' because it was deleted", $id);
635 daniel-mar 399
 
1291 daniel-mar 400
                if ($parentObj = $obj->getParent()) {
401
                        $parent_oid = $parentObj->nodeId();
402
                        OIDplus::logger()->log("V2:[WARN]OID(%2)", "Object '%1' (recursively) deleted", $id, $parent_oid);
403
                }
635 daniel-mar 404
 
1291 daniel-mar 405
                // Delete object
406
                OIDplus::db()->query("delete from ###objects where id = ?", array($id));
407
                OIDplusObject::resetObjectInformationCache();
635 daniel-mar 408
 
1291 daniel-mar 409
                // Delete orphan stuff
410
                foreach (OIDplus::getEnabledObjectTypes() as $ot) {
411
                        do {
412
                                $res = OIDplus::db()->query("select tchild.id from ###objects tchild " .
413
                                        "left join ###objects tparent on tparent.id = tchild.parent " .
414
                                        "where tchild.parent <> ? and tchild.id like ? and tparent.id is null;", array($ot::root(), $ot::root().'%'));
415
                                if (!$res->any()) break;
635 daniel-mar 416
 
1291 daniel-mar 417
                                while ($row = $res->fetch_array()) {
418
                                        $id_to_delete = $row['id'];
419
                                        OIDplus::logger()->log("V2:[CRIT]OIDRA(%2)", "Lost ownership of object '%2' because one of the superior objects ('%1') was recursively deleted", $id, $id_to_delete);
420
                                        OIDplus::db()->query("delete from ###objects where id = ?", array($id_to_delete));
421
                                        OIDplusObject::resetObjectInformationCache();
422
                                }
423
                        } while (true);
424
                }
425
                OIDplus::db()->query("delete from ###asn1id where well_known = ? and oid not in (select id from ###objects where id like 'oid:%')", array(false));
426
                OIDplus::db()->query("delete from ###iri    where well_known = ? and oid not in (select id from ###objects where id like 'oid:%')", array(false));
635 daniel-mar 427
 
1291 daniel-mar 428
                foreach (OIDplus::getAllPlugins() as $plugin) {
429
                        if ($plugin instanceof INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3) {
430
                                $plugin->afterObjectDelete($id);
635 daniel-mar 431
                        }
1291 daniel-mar 432
                }
635 daniel-mar 433
 
1291 daniel-mar 434
                return array("status" => 0);
435
        }
436
 
437
        /**
438
         * @param array $params id, ra_email, comment, iris, asn1ids, confidential, title, description
439
         * @return array status<0 Error, =0 Success, with the following bitfields for further information:
440
         *             x+1 = RA is not registered, but it can be invited
441
         *             x+2 = RA is not registered and it cannot be invited
442
         *             x+4 = OID is a well-known OID, so RA, ASN.1, and IRI identifiers were reset
443
         *             x+8 = User has write rights to the freshly created OID
444
         * @throws OIDplusConfigInitializationException
445
         * @throws OIDplusException
446
         */
1292 daniel-mar 447
        private function action_Update(array $params): array {
1291 daniel-mar 448
                _CheckParamExists($params, 'id');
449
                $id = $params['id'];
450
                $obj = OIDplusObject::parse($id);
451
                if (!$obj) throw new OIDplusException(_L('%1 action failed because object "%2" cannot be parsed!','UPDATE',$id));
452
 
453
                if (!OIDplusObject::exists($id)) {
454
                        throw new OIDplusException(_L('Object %1 does not exist',$id), null, 404);
635 daniel-mar 455
                }
456
 
1291 daniel-mar 457
                // Check if permitted
458
                if (isset($params['title']) || isset($params['description'])) {
459
                        if (!$obj->userHasWriteRights()) throw new OIDplusException(_L('Authentication error. Please log in as the RA to update this OID.'), null, 401);
460
                }
461
                if (isset($params['ra_email']) || isset($params['comment']) || isset($params['iris']) || isset($params['asn1ids']) || isset($params['confidential'])) {
462
                        if (!$obj->userHasParentalWriteRights()) throw new OIDplusException(_L('Authentication error. Please log in as the superior RA to update this OID.'), null, 401);
463
                }
635 daniel-mar 464
 
1291 daniel-mar 465
                foreach (OIDplus::getAllPlugins() as $plugin) {
466
                        if ($plugin instanceof INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3) {
467
                                $plugin->beforeObjectUpdateSuperior($id, $params);
635 daniel-mar 468
                        }
1291 daniel-mar 469
                }
635 daniel-mar 470
 
1291 daniel-mar 471
                // First, do a simulation for ASN.1 IDs and IRIs to check if there are any problems (then an Exception will be thrown)
472
                if ($obj::ns() == 'oid') {
473
                        assert($obj instanceof OIDplusOid); //assert(get_class($obj) === "ViaThinkSoft\OIDplus\OIDplusOid");
474
                        if (!$obj->isWellKnown()) {
475
                                if (isset($params['iris'])) {
476
                                        $ids = ($params['iris'] == '') ? array() : (is_array($params['iris']) ? $params['iris'] : explode(',',$params['iris']));
477
                                        $ids = array_map('trim',$ids);
478
                                        $obj->replaceIris($ids, true);
479
                                }
635 daniel-mar 480
 
1291 daniel-mar 481
                                if (isset($params['asn1ids'])) {
482
                                        $ids = ($params['asn1ids'] == '') ? array() : (is_array($params['asn1ids']) ? $params['asn1ids'] : explode(',',$params['asn1ids']));
483
                                        $ids = array_map('trim',$ids);
484
                                        $obj->replaceAsn1Ids($ids, true);
635 daniel-mar 485
                                }
486
                        }
1291 daniel-mar 487
                }
635 daniel-mar 488
 
1291 daniel-mar 489
                // RA E-Mail change
490
                if (isset($params['ra_email'])) {
491
                        // Validate RA email address
492
                        $new_ra = $params['ra_email'] ?? '';
635 daniel-mar 493
                        if ($obj::ns() == 'oid') {
1116 daniel-mar 494
                                assert($obj instanceof OIDplusOid); //assert(get_class($obj) === "ViaThinkSoft\OIDplus\OIDplusOid");
1291 daniel-mar 495
                                if ($obj->isWellKnown()) {
496
                                        $new_ra = '';
635 daniel-mar 497
                                }
498
                        }
1291 daniel-mar 499
                        if (!empty($new_ra) && !OIDplus::mailUtils()->validMailAddress($new_ra)) {
500
                                throw new OIDplusException(_L('Invalid RA email address'));
501
                        }
635 daniel-mar 502
 
1291 daniel-mar 503
                        // Change RA recursively
504
                        $current_ra = $obj->getRaMail() ?? '';
505
                        if ($new_ra != $current_ra) {
506
                                OIDplus::logger()->log("V2:[INFO]OID(%1)+[OK/INFO]SUPOIDRA(%1)+[OK/INFO]A", "RA of object '%1' changed from '%2' to '%3'", $id, $current_ra, $new_ra);
507
                                if (!empty($current_ra)) OIDplus::logger()->log("V2:[WARN]RA(%2)", "Lost ownership of object '%1' due to RA transfer of superior RA / admin.", $id, $current_ra, $new_ra);
508
                                if (!empty($new_ra)) OIDplus::logger()->log("V2:[INFO]RA(%3)", "Gained ownership of object '%1' due to RA transfer of superior RA / admin.", $id, $current_ra, $new_ra);
509
                                if ($parentObj = $obj->getParent()) {
510
                                        $parent_oid = $parentObj->nodeId();
511
                                        OIDplus::logger()->log("V2:[INFO]OID(%4)", "RA of object '%1' changed from '%2' to '%3'", $id, $current_ra, $new_ra, $parent_oid);
635 daniel-mar 512
                                }
1291 daniel-mar 513
                                $this->ra_change_rec($id, $current_ra, $new_ra); // Recursively change inherited RAs
635 daniel-mar 514
                        }
1291 daniel-mar 515
                }
635 daniel-mar 516
 
1291 daniel-mar 517
                // Log if confidentially flag was changed
518
                OIDplus::logger()->log("V2:[INFO]OID(%1)+[OK/INFO]SUPOIDRA(%1)+[OK/INFO]A", "Identifiers/Confidential flag of object '%1' updated", $id); // TODO: Check if they were ACTUALLY updated!
519
                if ($parentObj = $obj->getParent()) {
520
                        $parent_oid = $parentObj->nodeId();
521
                        OIDplus::logger()->log("V2:[INFO]OID(%2)", "Identifiers/Confidential flag of object '%1' updated", $id, $parent_oid); // TODO: Check if they were ACTUALLY updated!
522
                }
635 daniel-mar 523
 
1291 daniel-mar 524
                // Replace ASN.1 IDs und IRIs
525
                if ($obj::ns() == 'oid') {
526
                        assert($obj instanceof OIDplusOid); //assert(get_class($obj) === "ViaThinkSoft\OIDplus\OIDplusOid");
527
                        if (!$obj->isWellKnown()) {
528
                                if (isset($params['iris'])) {
529
                                        $ids = ($params['iris'] == '') ? array() : (is_array($params['iris']) ? $params['iris'] : explode(',',$params['iris']));
530
                                        $ids = array_map('trim',$ids);
531
                                        $obj->replaceIris($ids, false);
532
                                }
635 daniel-mar 533
 
1291 daniel-mar 534
                                if (isset($params['asn1ids'])) {
535
                                        $ids = ($params['asn1ids'] == '') ? array() : (is_array($params['asn1ids']) ? $params['asn1ids'] : explode(',',$params['asn1ids']));
536
                                        $ids = array_map('trim',$ids);
537
                                        $obj->replaceAsn1Ids($ids, false);
635 daniel-mar 538
                                }
539
                        }
540
 
1291 daniel-mar 541
                        // TODO: Check if any identifiers have been actually changed,
542
                        // and log it to OID($id), OID($parent), ... (see above)
543
                }
635 daniel-mar 544
 
1291 daniel-mar 545
                if (isset($params['confidential'])) {
1294 daniel-mar 546
                        $confidential = oidplus_is_true($params['confidential']);
1291 daniel-mar 547
                        OIDplus::db()->query("UPDATE ###objects SET confidential = ? WHERE id = ?", array($confidential, $id));
548
                        OIDplusObject::resetObjectInformationCache();
549
                }
635 daniel-mar 550
 
1291 daniel-mar 551
                if (isset($params['comment'])) {
552
                        $comment = $params['comment'];
553
                        OIDplus::db()->query("UPDATE ###objects SET comment = ? WHERE id = ?", array($comment, $id));
554
                        OIDplusObject::resetObjectInformationCache();
555
                }
1269 daniel-mar 556
 
1291 daniel-mar 557
                if (isset($params['title']) || isset($params['description'])) {
558
                        OIDplus::logger()->log("V2:[INFO]OID(%1)+[OK/INFO]OIDRA(%1)+[OK/INFO]A", "Title/Description of object '%1' updated", $id);
559
                }
1269 daniel-mar 560
 
1291 daniel-mar 561
                if (isset($params['title'])) {
562
                        $title = $params['title'];
563
                        OIDplus::db()->query("UPDATE ###objects SET title = ? WHERE id = ?", array($title, $id));
564
                        OIDplusObject::resetObjectInformationCache();
565
                }
1269 daniel-mar 566
 
1291 daniel-mar 567
                if (isset($params['description'])) {
568
                        $description = $params['description'];
569
                        OIDplus::db()->query("UPDATE ###objects SET description = ? WHERE id = ?", array($description, $id));
978 daniel-mar 570
                        OIDplusObject::resetObjectInformationCache();
1291 daniel-mar 571
                }
635 daniel-mar 572
 
1291 daniel-mar 573
                OIDplus::db()->query("UPDATE ###objects SET updated = ".OIDplus::db()->sqlDate()." WHERE id = ?", array($id));
574
                OIDplusObject::resetObjectInformationCache();
635 daniel-mar 575
 
1291 daniel-mar 576
                $status = 0;
635 daniel-mar 577
 
1291 daniel-mar 578
                if (!empty($new_ra)) {
579
                        $res = OIDplus::db()->query("select ra_name from ###ra where email = ?", array($new_ra));
580
                        $invitePlugin = OIDplus::getPluginByOid('1.3.6.1.4.1.37476.2.5.2.4.2.92'); // OIDplusPageRaInvite
581
                        if (!$res->any()) $status = !is_null($invitePlugin) && OIDplus::config()->getValue('ra_invitation_enabled') ? 1 : 2;
582
                }
635 daniel-mar 583
 
1291 daniel-mar 584
                if ($obj::ns() == 'oid') {
585
                        assert($obj instanceof OIDplusOid); //assert(get_class($obj) === "ViaThinkSoft\OIDplus\OIDplusOid");
586
                        if ($obj->isWellKnown()) {
587
                                $status += 4;
1269 daniel-mar 588
                        }
1291 daniel-mar 589
                }
1269 daniel-mar 590
 
1291 daniel-mar 591
                if ($obj->userHasWriteRights()) {
592
                        $status += 8;
635 daniel-mar 593
                }
594
 
1291 daniel-mar 595
                foreach (OIDplus::getAllPlugins() as $plugin) {
596
                        if ($plugin instanceof INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3) {
597
                                $plugin->afterObjectUpdateSuperior($id, $params);
598
                        }
635 daniel-mar 599
                }
600
 
1291 daniel-mar 601
                return array("status" => $status);
602
        }
635 daniel-mar 603
 
1291 daniel-mar 604
        /**
605
         * @param array $params parent, id (relative!), ra_email, comment, iris, asn1ids, confidential, title, description
606
         * @return array status=<0 Error, =0 Success, with the following bitfields for further information:
607
         *             x+1 = RA is not registered, but it can be invited
608
         *             x+2 = RA is not registered and it cannot be invited
609
         *             x+4 = OID is a well-known OID, so RA, ASN.1, and IRI identifiers were reset
610
         *             x+8 = User has write rights to the freshly created OID
611
         * @throws OIDplusConfigInitializationException
612
         * @throws OIDplusException
613
         */
1292 daniel-mar 614
        private function action_Insert(array $params): array {
1291 daniel-mar 615
                // Check if you have write rights on the parent (to create a new object)
616
                _CheckParamExists($params, 'parent');
617
                $objParent = OIDplusObject::parse($params['parent']);
618
                if (!$objParent) throw new OIDplusException(_L('%1 action failed because parent object "%2" cannot be parsed!','INSERT',$params['parent']));
619
 
620
                if (!$objParent->isRoot()) {
621
                        $idParent = $objParent->nodeId();
622
                        if (!OIDplusObject::exists($idParent)) {
623
                                throw new OIDplusException(_L('Parent object %1 does not exist',$idParent), null, 404);
635 daniel-mar 624
                        }
1291 daniel-mar 625
                }
635 daniel-mar 626
 
1291 daniel-mar 627
                if (!$objParent->userHasWriteRights()) throw new OIDplusException(_L('Authentication error. Please log in as the correct RA to insert an OID at this arc.'), null, 401);
635 daniel-mar 628
 
1291 daniel-mar 629
                // Check if the ID is valid
630
                _CheckParamExists($params, 'id');
631
                if ($params['id'] == '') throw new OIDplusException(_L('ID may not be empty'));
635 daniel-mar 632
 
1291 daniel-mar 633
                // For the root objects, let the user also enter a WEID
634
                if ($objParent::ns() == 'oid') {
635
                        assert($objParent instanceof OIDplusOid); //assert(get_class($objParent) === "ViaThinkSoft\OIDplus\OIDplusOid");
636
                        if (strtolower(substr(trim($params['id']),0,5)) === 'weid:') {
637
                                if ($objParent->isRoot()) {
638
                                        $params['id'] = \Frdl\Weid\WeidOidConverter::weid2oid($params['id']);
639
                                        if ($params['id'] === false) {
640
                                                throw new OIDplusException(_L('Invalid WEID'));
772 daniel-mar 641
                                        }
1291 daniel-mar 642
                                } else {
643
                                        throw new OIDplusException(_L('You can use the WEID syntax only at your object tree root.'));
772 daniel-mar 644
                                }
645
                        }
1291 daniel-mar 646
                }
772 daniel-mar 647
 
1291 daniel-mar 648
                // Determine absolute OID name
649
                // Note: At addString() and parse(), the syntax of the ID will be checked
1294 daniel-mar 650
                if (oidplus_is_true($params['id_fully_qualified'] ?? false)) {
1291 daniel-mar 651
                        // For REST API, the ID is absolute (because this is what is in the URL). We need to verify that ID and Parent matches.
652
                        $id = $params['id'];
653
                        $obj = OIDplusObject::parse($id);
654
                        $objParentTest = !$obj ? null : $obj->getParent();
655
                        if (!$objParentTest || !$objParentTest->equals($objParent)) throw new OIDplusException(_L('Cannot verify that %1 has parent %2', $obj->nodeId(), $objParent->nodeId()));
656
                } else {
657
                        // For AJAX/UI, the ID is relative to the parent. The absolute ID will be created by PHP's addString(), because JavaScript cannot know the syntax of the Object Type plugin
658
                        $id = $objParent->addString($params['id']);
659
                        $obj = OIDplusObject::parse($id);
660
                }
661
                if (!$obj) throw new OIDplusException(_L('%1 action failed because object "%2" cannot be parsed!','INSERT',$id));
635 daniel-mar 662
 
1291 daniel-mar 663
                // Check, if the OID exists
664
                if (OIDplusObject::exists($id)) {
665
                        throw new OIDplusException(_L('Object %1 already exists!',$id));
666
                }
635 daniel-mar 667
 
1291 daniel-mar 668
                foreach (OIDplus::getAllPlugins() as $plugin) {
669
                        if ($plugin instanceof INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3) {
670
                                $plugin->beforeObjectInsert($id, $params);
635 daniel-mar 671
                        }
1291 daniel-mar 672
                }
635 daniel-mar 673
 
1291 daniel-mar 674
                // First simulate if there are any problems of ASN.1 IDs und IRIs
675
                if ($obj::ns() == 'oid') {
676
                        assert($obj instanceof OIDplusOid); //assert(get_class($obj) === "ViaThinkSoft\OIDplus\OIDplusOid");
677
                        if (!$obj->isWellKnown()) {
678
                                if (isset($params['iris'])) {
679
                                        $ids = ($params['iris'] == '') ? array() : (is_array($params['iris']) ? $params['iris'] : explode(',',$params['iris']));
680
                                        $ids = array_map('trim',$ids);
681
                                        $obj->replaceIris($ids, true);
635 daniel-mar 682
                                }
683
 
1291 daniel-mar 684
                                if (isset($params['asn1ids'])) {
685
                                        $ids = ($params['asn1ids'] == '') ? array() : (is_array($params['asn1ids']) ? $params['asn1ids'] : explode(',',$params['asn1ids']));
686
                                        $ids = array_map('trim',$ids);
687
                                        $obj->replaceAsn1Ids($ids, true);
635 daniel-mar 688
                                }
689
                        }
1291 daniel-mar 690
                }
635 daniel-mar 691
 
1291 daniel-mar 692
                // Apply superior RA change
693
                $parent = $params['parent'];
694
                $ra_email = $params['ra_email'] ?? '';
695
                if ($obj::ns() == 'oid') {
696
                        assert($obj instanceof OIDplusOid); //assert(get_class($obj) === "ViaThinkSoft\OIDplus\OIDplusOid");
697
                        if ($obj->isWellKnown()) {
698
                                $ra_email = '';
1199 daniel-mar 699
                        }
1291 daniel-mar 700
                }
701
                if (!empty($ra_email) && !OIDplus::mailUtils()->validMailAddress($ra_email)) {
702
                        throw new OIDplusException(_L('Invalid RA email address'));
703
                }
635 daniel-mar 704
 
1291 daniel-mar 705
                if (empty($ra_email)) {
706
                        OIDplus::logger()->log("V2:[INFO]OID(%2)+[INFO]OID(%1)+[OK/INFO]OIDRA(%2)+[OK/INFO]A", "Object '%1' created, without defined RA, superior object is '%2'", $id, $parent);
707
                } else {
708
                        OIDplus::logger()->log("V2:[INFO]OID(%2)+[INFO]OID(%1)+[OK/INFO]OIDRA(%2)+[OK/INFO]A", "Object '%1' created, given to RA '%3', superior object is '%2'", $id, $parent, $ra_email);
709
                }
710
                if (!empty($ra_email)) {
711
                        OIDplus::logger()->log("V2:[INFO]RA(%2)", "Gained ownership of newly created object '%1'", $id, $ra_email);
712
                }
635 daniel-mar 713
 
1294 daniel-mar 714
                $confidential = oidplus_is_true($params['confidential'] ?? false);
1291 daniel-mar 715
                $comment = $params['comment'] ?? '';
716
                $title = $params['title'] ?? ''; // This is very special (only useable in REST API): The superior RA can set the title during creation, even if they lose their ownership by delegating afterwards!
717
                $description = $params['description'] ?? ''; // This is very special (only useable in REST API): The superior RA can set the title during creation, even if they lose their ownership by delegating afterwards!
635 daniel-mar 718
 
1291 daniel-mar 719
                if (strlen($id) > OIDplus::baseConfig()->getValue('LIMITS_MAX_ID_LENGTH')) {
720
                        $maxlen = OIDplus::baseConfig()->getValue('LIMITS_MAX_ID_LENGTH');
721
                        throw new OIDplusException(_L('The identifier %1 is too long (max allowed length: %2)',$id,$maxlen));
722
                }
635 daniel-mar 723
 
1291 daniel-mar 724
                OIDplus::db()->query("INSERT INTO ###objects (id, parent, ra_email, confidential, comment, created, title, description) VALUES (?, ?, ?, ?, ?, ".OIDplus::db()->sqlDate().", ?, ?)", array($id, $parent, $ra_email, $confidential, $comment, $title, $description));
725
                OIDplusObject::resetObjectInformationCache();
635 daniel-mar 726
 
1291 daniel-mar 727
                // Set ASN.1 IDs und IRIs
728
                if ($obj::ns() == 'oid') {
729
                        assert($obj instanceof OIDplusOid); //assert(get_class($obj) === "ViaThinkSoft\OIDplus\OIDplusOid");
730
                        if (!$obj->isWellKnown()) {
731
                                if (isset($params['iris'])) {
732
                                        $ids = ($params['iris'] == '') ? array() : (is_array($params['iris']) ? $params['iris'] : explode(',',$params['iris']));
733
                                        $ids = array_map('trim',$ids);
734
                                        $obj->replaceIris($ids, false);
635 daniel-mar 735
                                }
1291 daniel-mar 736
 
737
                                if (isset($params['asn1ids'])) {
738
                                        $ids = ($params['asn1ids'] == '') ? array() : (is_array($params['asn1ids']) ? $params['asn1ids'] : explode(',',$params['asn1ids']));
739
                                        $ids = array_map('trim',$ids);
740
                                        $obj->replaceAsn1Ids($ids, false);
741
                                }
635 daniel-mar 742
                        }
1291 daniel-mar 743
                }
635 daniel-mar 744
 
1291 daniel-mar 745
                $status = 0;
635 daniel-mar 746
 
1291 daniel-mar 747
                if (!empty($ra_email)) {
748
                        // Do we need to notify that the RA does not exist?
749
                        $res = OIDplus::db()->query("select ra_name from ###ra where email = ?", array($ra_email));
750
                        $invitePlugin = OIDplus::getPluginByOid('1.3.6.1.4.1.37476.2.5.2.4.2.92'); // OIDplusPageRaInvite
751
                        if (!$res->any()) $status = !is_null($invitePlugin) && OIDplus::config()->getValue('ra_invitation_enabled') ? 1 : 2;
752
                }
635 daniel-mar 753
 
1291 daniel-mar 754
                if ($obj::ns() == 'oid') {
755
                        assert($obj instanceof OIDplusOid); //assert(get_class($obj) === "ViaThinkSoft\OIDplus\OIDplusOid");
756
                        if ($obj->isWellKnown()) {
757
                                $status += 4;
635 daniel-mar 758
                        }
1291 daniel-mar 759
                }
635 daniel-mar 760
 
1291 daniel-mar 761
                if ($obj->userHasWriteRights()) {
762
                        $status += 8;
763
                }
1269 daniel-mar 764
 
1291 daniel-mar 765
                foreach (OIDplus::getAllPlugins() as $plugin) {
766
                        if ($plugin instanceof INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_3) {
767
                                $plugin->afterObjectInsert($id, $params);
635 daniel-mar 768
                        }
1291 daniel-mar 769
                }
635 daniel-mar 770
 
1291 daniel-mar 771
                return array(
772
                        "status" => $status,
773
                        "inserted_id" => $id
774
                );
775
        }
776
 
777
        /**
1292 daniel-mar 778
         * Generate UUID (will be used by a few plugins)
779
         * @param array $params Nothing
780
         * @return array status=0 success, status<0 error. If success, then also uuid, intval
781
         * @throws OIDplusConfigInitializationException
782
         * @throws OIDplusException
783
         */
784
        private function action_UuidGen(array $params): array {
1336 daniel-mar 785
                $uuid = gen_uuid(OIDplus::config()->getValue('uuidgen_expose_mac', '0') == '1');
1292 daniel-mar 786
                if (!$uuid) return array("status" => -1);
787
                return array(
788
                        "status" => 0,
789
                        "uuid" => $uuid,
790
                        "intval" => substr(uuid_to_oid($uuid),strlen('2.25.'))
791
                );
792
        }
793
 
794
        /**
1291 daniel-mar 795
         * @param string $actionID
796
         * @param array $params
797
         * @return array
798
         * @throws OIDplusConfigInitializationException
799
         * @throws OIDplusException
800
         */
801
        public function action(string $actionID, array $params): array {
802
                if ($actionID == 'Delete') {
803
                        return $this->action_Delete($params);
804
                } else if ($actionID == 'Update') {
805
                        return $this->action_Update($params);
806
                } else if ($actionID == 'Insert') {
807
                        return $this->action_Insert($params);
808
                } else if ($actionID == 'generate_uuid') {
1292 daniel-mar 809
                        return $this->action_UuidGen($params);
635 daniel-mar 810
                } else {
1116 daniel-mar 811
                        return parent::action($actionID, $params);
635 daniel-mar 812
                }
813
        }
814
 
1116 daniel-mar 815
        /**
816
         * @param bool $html
817
         * @return void
818
         * @throws OIDplusException
819
         */
820
        public function init(bool $html=true) {
635 daniel-mar 821
                OIDplus::config()->prepareConfigKey('oobe_objects_done', '"Out Of Box Experience" wizard for OIDplusPagePublicObjects done once?', '0', OIDplusConfig::PROTECTION_HIDDEN, function($value) {});
693 daniel-mar 822
                OIDplus::config()->prepareConfigKey('oid_grid_show_weid', 'Show WEID/Base36 column in CRUD grid of OIDs?', '1', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
823
                        if (!is_numeric($value) || ($value < 0) || ($value > 1)) {
824
                                throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
825
                        }
826
                });
1336 daniel-mar 827
                OIDplus::config()->delete('uuid_prefer_timebased'); // deprecated
828
                OIDplus::config()->prepareConfigKey('uuidgen_expose_mac', '1=UUID Generator may expose the MAC address of the system, 0=Use random bits instead of MAC address', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
829
                        if (!is_numeric($value) || ($value < 0) || ($value > 1)) {
830
                                throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
1259 daniel-mar 831
                        }
832
                });
635 daniel-mar 833
        }
834
 
1116 daniel-mar 835
        /**
1130 daniel-mar 836
         * @param string $id
837
         * @param array $out
1116 daniel-mar 838
         * @return array|false
839
         * @throws OIDplusException
840
         */
1130 daniel-mar 841
        private function tryObject(string $id, array &$out) {
951 daniel-mar 842
                $parent = null;
843
                $res = null;
844
                $row = null;
954 daniel-mar 845
                $obj = OIDplusObject::parse($id);
1116 daniel-mar 846
                if (!$obj) return false;
954 daniel-mar 847
                if ($obj->isRoot()) {
848
                        $obj->getContentPage($out['title'], $out['text'], $out['icon']);
977 daniel-mar 849
                        $objParent = null; // $obj->getParent();
954 daniel-mar 850
                } else {
977 daniel-mar 851
                        $obj = OIDplusObject::findFitting($id); // this time, the object will be found, not just the object type
852
                        if (!$obj) {
954 daniel-mar 853
                                return false;
854
                        } else {
855
                                $obj->getContentPage($out['title'], $out['text'], $out['icon']);
1261 daniel-mar 856
                                if (empty($out['title'])) $out['title'] = $obj->defaultTitle();
954 daniel-mar 857
                                if (empty($out['title'])) $out['title'] = explode(':',$obj->nodeId(),2)[1];
977 daniel-mar 858
                                $objParent = $obj->getParent();
953 daniel-mar 859
                        }
951 daniel-mar 860
                }
977 daniel-mar 861
                return array($id, $obj, $objParent);
951 daniel-mar 862
        }
863
 
1116 daniel-mar 864
        /**
1130 daniel-mar 865
         * @param string $id
1116 daniel-mar 866
         * @return array
867
         */
1130 daniel-mar 868
        public static function getAlternativesForQuery(string $id): array {
1131 daniel-mar 869
                // Attention: This is NOT an implementation of INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_7!
870
                //            This is the function that calls getAlternativesForQuery() of every plugin that implements INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_7
968 daniel-mar 871
 
951 daniel-mar 872
                // e.g. used for "Reverse Alt Id"
873
                $alternatives = array();
1005 daniel-mar 874
                foreach (OIDplus::getAllPlugins() as $plugin) {
1131 daniel-mar 875
                        if ($plugin instanceof INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_7) {
876
                                $tmp = $plugin->getAlternativesForQuery($id);
951 daniel-mar 877
                                if (is_array($tmp)) {
878
                                        $alternatives = array_merge($tmp, $alternatives);
879
                                }
880
                        }
881
                }
968 daniel-mar 882
 
883
                // If something is more than one time, remove it
951 daniel-mar 884
                $alternatives = array_unique($alternatives);
968 daniel-mar 885
 
886
                // If a plugin accidentally added the own ID, remove it. This function lists only alternatives, not the own ID
887
                $alternatives_tmp = array();
888
                foreach ($alternatives as $alt) {
889
                        if ($alt !== $id) $alternatives_tmp[] = $alt;
890
                }
1130 daniel-mar 891
                return $alternatives_tmp;
951 daniel-mar 892
        }
893
 
1116 daniel-mar 894
        /**
895
         * @param string $id
896
         * @param array $out
897
         * @param bool $handled
898
         * @return void
899
         * @throws OIDplusConfigInitializationException
900
         * @throws OIDplusException
901
         */
902
        public function gui(string $id, array &$out, bool &$handled) {
635 daniel-mar 903
                if ($id === 'oidplus:system') {
904
                        $handled = true;
905
 
906
                        $out['title'] = OIDplus::config()->getValue('system_title');
801 daniel-mar 907
                        $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon.png';
635 daniel-mar 908
 
909
                        if (file_exists(OIDplus::localpath() . 'userdata/welcome/welcome$'.OIDplus::getCurrentLang().'.html')) {
910
                                $cont = file_get_contents(OIDplus::localpath() . 'userdata/welcome/welcome$'.OIDplus::getCurrentLang().'.html');
911
                        } else if (file_exists(OIDplus::localpath() . 'userdata/welcome/welcome.html')) {
912
                                $cont = file_get_contents(OIDplus::localpath() . 'userdata/welcome/welcome.html');
913
                        } else if (file_exists(__DIR__ . '/welcome$'.OIDplus::getCurrentLang().'.html')) {
914
                                $cont = file_get_contents(__DIR__ . '/welcome$'.OIDplus::getCurrentLang().'.html');
915
                        } else if (file_exists(__DIR__ . '/welcome.html')) {
916
                                $cont = file_get_contents(__DIR__ . '/welcome.html');
917
                        } else {
918
                                $cont = '';
919
                        }
920
 
1143 daniel-mar 921
                        if ($cont) {
922
                                list($html, $js, $css) = extractHtmlContents($cont);
923
                                $cont = '';
924
                                if (!empty($js)) $cont .= "<script>\n$js\n</script>";
925
                                if (!empty($css)) $cont .= "<style>\n$css\n</style>";
926
                                $cont .= stripHtmlComments($html);
927
                        }
635 daniel-mar 928
 
929
                        $out['text'] = $cont;
930
 
931
                        if (strpos($out['text'], '%%OBJECT_TYPE_LIST%%') !== false) {
932
                                $tmp = '<ul>';
933
                                foreach (OIDplus::getEnabledObjectTypes() as $ot) {
934
                                        $tmp .= '<li><a '.OIDplus::gui()->link($ot::root()).'>'.htmlentities($ot::objectTypeTitle()).'</a></li>';
935
                                }
936
                                $tmp .= '</ul>';
937
                                $out['text'] = str_replace('%%OBJECT_TYPE_LIST%%', $tmp, $out['text']);
938
                        }
939
                }
940
 
957 daniel-mar 941
                // Never answer to an object type that is called 'oidplus:',
942
                // otherwise, an object type plugin could break the whole system!
943
                else if ((strpos($id,':') !== false) && (!str_starts_with($id,'oidplus:'))) {
635 daniel-mar 944
 
955 daniel-mar 945
                        // --- Try to find the object or an alternative
635 daniel-mar 946
 
951 daniel-mar 947
                        $test = $this->tryObject($id, $out);
948
                        if ($test === false) {
955 daniel-mar 949
                                // try to find an alternative
952 daniel-mar 950
                                $alternatives = $this->getAlternativesForQuery($id);
951 daniel-mar 951
                                foreach ($alternatives as $alternative) {
952
                                        $test = $this->tryObject($alternative, $out);
955 daniel-mar 953
                                        if ($test !== false) break; // found something
635 daniel-mar 954
                                }
955
                        }
955 daniel-mar 956
                        if ($test !== false) {
977 daniel-mar 957
                                list($id, $obj, $objParent) = $test;
1132 daniel-mar 958
                        } else {
959
                                $objParent = null; // to avoid warnings
955 daniel-mar 960
                        }
961
 
962
                        // --- If the object type is disabled or not an object at all (e.g. "oidplus:"), then $handled=false
963
                        //     If the object type is enabled but object not found, $handled=true
964
 
970 daniel-mar 965
                        $obj = OIDplusObject::parse($id);
955 daniel-mar 966
 
951 daniel-mar 967
                        if ($test === false) {
1116 daniel-mar 968
                                if (!$obj) {
955 daniel-mar 969
                                        // Object type disabled or not known (e.g. ObjectType "oidplus:").
970
                                        $handled = false;
971
                                        return;
972
                                } else {
973
                                        // Object type enabled but identifier not in database
974
                                        $handled = true;
975
                                        if (isset($_SERVER['SCRIPT_FILENAME']) && (strtolower(basename($_SERVER['SCRIPT_FILENAME'])) !== 'ajax.php')) { // don't send HTTP error codes in ajax.php, because we want a page and not a JavaScript alert box, when someone enters an invalid OID in the GoTo-Box
976
                                                http_response_code(404);
977
                                        }
1206 daniel-mar 978
                                        throw new OIDplusHtmlException(_L('The object %1 was not found in this database.','<code>'.htmlentities($id).'</code>'), _L('Object not found'));
955 daniel-mar 979
                                }
980
                        } else {
981
                                $handled = true;
982
                        }
983
 
984
                        unset($test);
985
 
986
                        // --- If found, do we have read rights?
987
 
988
                        if (!$obj->userHasReadRights()) {
843 daniel-mar 989
                                if (isset($_SERVER['SCRIPT_FILENAME']) && (strtolower(basename($_SERVER['SCRIPT_FILENAME'])) !== 'ajax.php')) { // don't send HTTP error codes in ajax.php, because we want a page and not a JavaScript alert box, when someone enters an invalid OID in the GoTo-Box
955 daniel-mar 990
                                        http_response_code(403);
843 daniel-mar 991
                                }
1266 daniel-mar 992
                                throw new OIDplusHtmlException(_L('Please <a %1>log in</a> to receive information about this object.',OIDplus::gui()->link('oidplus:login')), _L('Access denied'), 401);
635 daniel-mar 993
                        }
994
 
995
                        // ---
996
 
1279 daniel-mar 997
                        $out['text'] = '<!-- MARKER 1 -->' . $out['text']; // use this to better control modifyContent!
998
 
977 daniel-mar 999
                        if ($objParent) {
1000
                                if ($objParent->isRoot()) {
1001
                                        $parent_link_text = $objParent->objectTypeTitle();
1002
                                        $out['text'] = '<p><a '.OIDplus::gui()->link($objParent->root()).'><img src="img/arrow_back.png" width="16" alt="'._L('Go back').'"> '._L('Parent node: %1',htmlentities($parent_link_text)).'</a></p>' . $out['text'];
635 daniel-mar 1003
                                } else {
977 daniel-mar 1004
                                        $parent_title = $objParent->getTitle();
1005
                                        if (empty($parent_title) && ($objParent->ns() == 'oid')) {
1116 daniel-mar 1006
                                                assert($objParent instanceof OIDplusOid); //assert(get_class($objParent) === "ViaThinkSoft\OIDplus\OIDplusOid");
977 daniel-mar 1007
                                                // If not title is available, then use an ASN.1 identifier
1008
                                                $res_asn = OIDplus::db()->query("select name from ###asn1id where oid = ?", array($objParent->nodeId()));
1009
                                                if ($res_asn->any()) {
1010
                                                        $row_asn = $res_asn->fetch_array();
1011
                                                        $parent_title = $row_asn['name']; // TODO: multiple ASN1 ids?
635 daniel-mar 1012
                                                }
977 daniel-mar 1013
                                        }
635 daniel-mar 1014
 
977 daniel-mar 1015
                                        $parent_link_text = empty($parent_title) ? explode(':',$objParent->nodeId())[1] : $parent_title.' ('.explode(':',$objParent->nodeId())[1].')';
635 daniel-mar 1016
 
977 daniel-mar 1017
                                        $out['text'] = '<p><a '.OIDplus::gui()->link($objParent->nodeId()).'><img src="img/arrow_back.png" width="16" alt="'._L('Go back').'"> '._L('Parent node: %1',htmlentities($parent_link_text)).'</a></p>' . $out['text'];
635 daniel-mar 1018
                                }
1019
                        } else {
1020
                                $parent_link_text = _L('Go back to front page');
1021
                                $out['text'] = '<p><a '.OIDplus::gui()->link('oidplus:system').'><img src="img/arrow_back.png" width="16" alt="'._L('Go back').'"> '.htmlentities($parent_link_text).'</a></p>' . $out['text'];
1022
                        }
1023
 
1279 daniel-mar 1024
                        $out['text'] = '<!-- MARKER 0 -->' . $out['text']; // use this to better control modifyContent!
1025
 
635 daniel-mar 1026
                        // ---
1027
 
1279 daniel-mar 1028
                        $out['text'] .= '<!-- MARKER 2 -->'; // use this to better control modifyContent!
1029
 
977 daniel-mar 1030
                        if ($obj) {
1144 daniel-mar 1031
                                $title = $obj->getTitle() ?? '';
1032
                                $description = $obj->getDescription() ?? '';
999 daniel-mar 1033
                                if (empty(strip_tags($description)) && (stripos($description,'<img') === false)) {
977 daniel-mar 1034
                                        if (empty($title)) {
635 daniel-mar 1035
                                                $desc = '<p><i>'._L('No description for this object available').'</i></p>';
1036
                                        } else {
977 daniel-mar 1037
                                                $desc = $title;
635 daniel-mar 1038
                                        }
1039
                                } else {
977 daniel-mar 1040
                                        $desc = self::objDescription($description);
635 daniel-mar 1041
                                }
1042
 
1144 daniel-mar 1043
                                // $description is the description in the OID table (which the user edits)
1044
                                // $desc is the thing that is shown (it can be a title if no description is there, or an MCE editor if the user has write rights)
1045
 
635 daniel-mar 1046
                                if ($obj->userHasWriteRights()) {
1047
                                        $rand = ++self::$crudCounter;
1288 daniel-mar 1048
                                        $desc = '<noscript><p><font color="red">'._L('You need to enable JavaScript to edit title or description of this object.').'</font></p>'.$desc.'</noscript>';
635 daniel-mar 1049
                                        $desc .= '<div class="container box" style="display:none" id="descbox_'.$rand.'">';
977 daniel-mar 1050
                                        $desc .= _L('Title').': <input type="text" name="title" id="titleedit" value="'.htmlentities($title).'"><br><br>'._L('Description').':<br>';
1051
                                        $desc .= self::showMCE('description', $description);
1400 daniel-mar 1052
                                        $desc .= '<button type="button" name="update_desc" id="update_desc" class="btn btn-success btn-xs update" onclick="OIDplusPagePublicObjects.updateDesc('.js_escape($obj->nodeId()).')">'._L('Update description').'</button>';
635 daniel-mar 1053
                                        $desc .= '</div>';
1054
                                        $desc .= '<script>$("#descbox_'.$rand.'")[0].style.display = "block";</script>';
1055
                                }
1056
                        } else {
1057
                                $desc = '';
1058
                        }
1059
 
1060
                        // ---
1061
 
1279 daniel-mar 1062
                        if (strpos($out['text'], '%%DESC%%') !== false) {
1063
                                $out['text'] = str_replace('%%DESC%%', $desc, $out['text']);
1064
                        }
1065
                        if (strpos($out['text'], '%%CRUD%%') !== false) {
1066
                                $out['text'] = str_replace('%%CRUD%%', self::showCrud($obj->nodeId()), $out['text']);
1067
                        }
1068
                        if (strpos($out['text'], '%%RA_INFO%%') !== false) {
1410 daniel-mar 1069
                                $out['text'] = str_replace('%%RA_INFO%%', OIDplusPagePublicRaInfo::showRaInfo($obj->getRaMail(), $obj), $out['text']);
1279 daniel-mar 1070
                        }
635 daniel-mar 1071
 
1279 daniel-mar 1072
                        $out['text'] .= '<!-- MARKER 3 -->'; // use this to better control modifyContent!
1073
                        $out['text'] .= '<!-- MARKER 4 -->'; // use this to better control modifyContent!
1074
                        $out['text'] .= '<!-- MARKER 5 -->'; // use this to better control modifyContent!
635 daniel-mar 1075
                        $alt_ids = $obj->getAltIds();
1076
                        if (count($alt_ids) > 0) {
1077
                                $out['text'] .= '<h2>'._L('Alternative Identifiers').'</h2>';
1138 daniel-mar 1078
 
1079
                                // Sorty by namespace
1080
                                usort($alt_ids, function(OIDplusAltId $a, OIDplusAltId $b) {
1081
                                        if($a->getNamespace() > $b->getNamespace()) {
1082
                                                return 1;
1083
                                        }
1084
                                        elseif($a->getNamespace() < $b->getNamespace()) {
1085
                                                return -1;
1086
                                        }
1087
                                        else {
1088
                                                return 0;
1089
                                        }
1090
                                });
1091
 
1092
                                $out['text'] .= '<div class="container box"><div id="suboid_table" class="table-responsive">';
1093
                                $out['text'] .= '<table class="table table-bordered table-striped">';
1094
                                $out['text'] .= '<thead>';
1095
                                $out['text'] .= '<tr><th>'._L('Identifier').'</th><th>'._L('Description').'</th></tr>';
1096
                                $out['text'] .= '</thead>';
1097
                                $out['text'] .= '<tbody>';
635 daniel-mar 1098
                                foreach ($alt_ids as $alt_id) {
1099
                                        $ns = $alt_id->getNamespace();
1100
                                        $aid = $alt_id->getId();
1101
                                        $aiddesc = $alt_id->getDescription();
945 daniel-mar 1102
                                        $suffix = $alt_id->getSuffix();
1329 daniel-mar 1103
                                        $info = $alt_id->getMoreInfoUrl();
1404 daniel-mar 1104
 
1105
                                        // Note: &#8203; is to allow a word-break (see https://stackoverflow.com/questions/8186743/what-is-the-best-way-to-break-html-text-on-slashes)
1106
                                        //       This is important for the very long X.500 DN, e.g. "x500dn:/dc=com/dc=example/cn=oidplus/1.3.6.1.4.1.37476.2.5.2.9.4.1=1494410075/1.3.6.1.4.1.37476.2.5.2.9.4.2=1610822832"
1330 daniel-mar 1107
                                        if ($info) $info = ' <a href="'.$info.'" target="_blank"><img src="img/info.png" style="width:16px;height:16px" alt="'._L('More information').'"></a>';
1404 daniel-mar 1108
                                        $out['text'] .= '<tr><td>'.str_replace("/", "/&#8203;",htmlentities($ns.':'.$aid)).($suffix ? '<br/><font size="-1">'.htmlentities($suffix).'</font>' : '').'</td><td>'.htmlentities($aiddesc).$info.'</td></tr>';
635 daniel-mar 1109
                                }
1138 daniel-mar 1110
                                $out['text'] .= '</tbody>';
1111
                                $out['text'] .= '</table>';
1112
                                $out['text'] .= '</div></div>';
635 daniel-mar 1113
                        }
1114
 
1279 daniel-mar 1115
                        $out['text'] .= '<!-- MARKER 6 -->'; // use this to better control modifyContent!
1116
                        $out['text'] .= '<!-- MARKER 7 -->'; // use this to better control modifyContent!
1117
                        $out['text'] .= '<!-- MARKER 8 -->'; // use this to better control modifyContent!
1118
                        $out['text'] .= '<!-- MARKER 9 -->'; // use this to better control modifyContent!
1119
 
1005 daniel-mar 1120
                        foreach (OIDplus::getAllPlugins() as $plugin) {
1131 daniel-mar 1121
                                if ($plugin instanceof INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_2) {
1122
                                        $plugin->modifyContent($obj->nodeId(), $out['title'], $out['icon'], $out['text']);
635 daniel-mar 1123
                                }
1124
                        }
1279 daniel-mar 1125
 
1126
                        for ($i=0; $i<=9; $i++) $out['text'] = str_replace("<!-- MARKER $i -->", '', $out['text']);
635 daniel-mar 1127
                }
1128
        }
1129
 
1116 daniel-mar 1130
        /**
1130 daniel-mar 1131
         * @param array $json
1132
         * @param array $out
1116 daniel-mar 1133
         * @return void
1134
         */
1130 daniel-mar 1135
        private function publicSitemap_rec(array $json, array &$out) {
635 daniel-mar 1136
                foreach ($json as $x) {
1137
                        if (isset($x['id']) && $x['id']) {
1138
                                $out[] = $x['id'];
1139
                        }
1140
                        if (isset($x['children'])) {
1141
                                $this->publicSitemap_rec($x['children'], $out);
1142
                        }
1143
                }
1144
        }
1145
 
1116 daniel-mar 1146
        /**
1147
         * @param array $out
1148
         * @return void
1149
         */
1150
        public function publicSitemap(array &$out) {
635 daniel-mar 1151
                $json = array();
1116 daniel-mar 1152
                $this->tree($json, null/*RA EMail*/, false/*HTML tree algorithm*/, "*"/*display all*/);
635 daniel-mar 1153
                $this->publicSitemap_rec($json, $out);
1154
        }
1155
 
1116 daniel-mar 1156
        /**
1157
         * @param array $json
1158
         * @param string|null $ra_email
1159
         * @param bool $nonjs
1160
         * @param string $req_goto
1161
         * @return bool
1162
         * @throws OIDplusConfigInitializationException
1163
         * @throws OIDplusException
1164
         */
1165
        public function tree(array &$json, string $ra_email=null, bool $nonjs=false, string $req_goto=''): bool {
635 daniel-mar 1166
                if ($nonjs) {
1167
                        $json[] = array(
1168
                                'id' => 'oidplus:system',
801 daniel-mar 1169
                                'icon' => OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png',
635 daniel-mar 1170
                                'text' => _L('System')
1171
                        );
1172
 
977 daniel-mar 1173
                        $objGoto = OIDplusObject::findFitting($req_goto);
998 daniel-mar 1174
                        $objGotoParent = $objGoto ? $objGoto->getParent() : null;
977 daniel-mar 1175
                        $parent = $objGotoParent ? $objGotoParent->nodeId() : '';
635 daniel-mar 1176
 
1177
                        $objTypesChildren = array();
1178
                        foreach (OIDplus::getEnabledObjectTypes() as $ot) {
1179
                                $icon = $this->get_treeicon_root($ot);
1180
 
1181
                                $json[] = array(
1182
                                        'id' => $ot::root(),
1183
                                        'icon' => $icon,
1184
                                        'text' => $ot::objectTypeTitle()
1185
                                );
1186
 
954 daniel-mar 1187
                                $tmp = OIDplusObject::parse($req_goto);
1116 daniel-mar 1188
                                if ($tmp && ($ot == get_class($tmp))) {
635 daniel-mar 1189
                                        // TODO: Instead of just having 3 levels (parent, this and children), it would be better if we'd had a full tree of all parents
1190
                                        //       on the other hand, for giving search engines content, this is good enough
1191
                                        if (empty($parent)) {
1192
                                                $res = OIDplus::db()->query("select * from ###objects where " .
1193
                                                                            "parent = ? or " .
1148 daniel-mar 1194
                                                                            "id = ? ", array($req_goto, $req_goto));
635 daniel-mar 1195
                                        } else {
1196
                                                $res = OIDplus::db()->query("select * from ###objects where " .
1197
                                                                            "parent = ? or " .
1198
                                                                            "id = ? or " .
1148 daniel-mar 1199
                                                                            "id = ? ", array($req_goto, $req_goto, $parent));
635 daniel-mar 1200
                                        }
1156 daniel-mar 1201
                                        $res->naturalSortByField('id');
635 daniel-mar 1202
 
1203
                                        $z_used = 0;
1204
                                        $y_used = 0;
1205
                                        $x_used = 0;
1206
                                        $stufe = 0;
1207
                                        $menu_entries = array();
1208
                                        $stufen = array();
1209
                                        while ($row = $res->fetch_object()) {
1210
                                                $obj = OIDplusObject::parse($row->id);
1116 daniel-mar 1211
                                                if (!$obj) continue; // might happen if the objectType is not available/loaded
635 daniel-mar 1212
                                                if (!$obj->userHasReadRights()) continue;
1219 daniel-mar 1213
                                                $txt = ($row->title ?? '') == '' ? '' : ' -- '.htmlentities($row->title);
635 daniel-mar 1214
 
1215
                                                if ($row->id == $parent) { $stufe=0; $z_used++; }
1216
                                                if ($row->id == $req_goto) { $stufe=1; $y_used++; }
1217
                                                if ($row->parent == $req_goto) { $stufe=2; $x_used++; }
1218
 
1219
                                                $menu_entry = array('id' => $row->id, 'icon' => '', 'text' => $txt, 'indent' => 0);
1220
                                                $menu_entries[] = $menu_entry;
1221
                                                $stufen[] = $stufe;
1222
                                        }
1223
                                        if ($x_used) foreach ($menu_entries as $i => &$menu_entry) if ($stufen[$i] >= 2) $menu_entry['indent'] += 1;
1224
                                        if ($y_used) foreach ($menu_entries as $i => &$menu_entry) if ($stufen[$i] >= 1) $menu_entry['indent'] += 1;
1225
                                        if ($z_used) foreach ($menu_entries as $i => &$menu_entry) if ($stufen[$i] >= 0) $menu_entry['indent'] += 1;
1226
                                        $json = array_merge($json, $menu_entries);
1227
                                }
1228
                        }
1229
 
1230
                        return true;
1231
                } else {
1116 daniel-mar 1232
                        if ($req_goto === "*") {
635 daniel-mar 1233
                                $goto_path = true; // display everything recursively
1116 daniel-mar 1234
                        } else if ($req_goto !== "") {
635 daniel-mar 1235
                                $goto = $req_goto;
1236
                                $path = array();
1237
                                while (true) {
1238
                                        $path[] = $goto;
977 daniel-mar 1239
                                        $objGoto = OIDplusObject::findFitting($goto);
1240
                                        if (!$objGoto) break;
1241
                                        $objGotoParent = $objGoto->getParent();
1242
                                        $goto = $objGotoParent ? $objGotoParent->nodeId() : '';
635 daniel-mar 1243
                                        if ($goto == '') continue;
1244
                                }
1245
 
1246
                                $goto_path = array_reverse($path);
1247
                        } else {
1248
                                $goto_path = null;
1249
                        }
1250
 
1251
                        $objTypesChildren = array();
1252
                        foreach (OIDplus::getEnabledObjectTypes() as $ot) {
1253
                                $icon = $this->get_treeicon_root($ot);
1254
 
1255
                                $child = array('id' => $ot::root(),
1256
                                               'text' => $ot::objectTypeTitle(),
1257
                                               'state' => array("opened" => true),
1258
                                               'icon' => $icon,
1259
                                               'children' => OIDplus::menuUtils()->tree_populate($ot::root(), $goto_path)
1260
                                               );
1122 daniel-mar 1261
                                if ($child['icon'] && !file_exists($child['icon'])) $child['icon'] = null; // default icon (folder)
635 daniel-mar 1262
                                $objTypesChildren[] = $child;
1263
                        }
1264
 
1265
                        $json[] = array(
1266
                                'id' => "oidplus:system",
1267
                                'text' => _L('Objects'),
1268
                                'state' => array(
1269
                                        "opened" => true,
1270
                                        // "selected" => true)  // "selected" is buggy:
1271
                                        // 1) The select-event will not be triggered upon loading
1272
                                        // 2) The nodes directly blow cannot be opened (loading infinite time)
1273
                                ),
801 daniel-mar 1274
                                'icon' => OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png',
635 daniel-mar 1275
                                'children' => $objTypesChildren
1276
                        );
1277
 
1278
                        return true;
1279
                }
1280
        }
1281
 
1116 daniel-mar 1282
        /**
1283
         * @param string $request
1284
         * @return array|false
1285
         */
1286
        public function tree_search(string $request) {
635 daniel-mar 1287
                $ary = array();
951 daniel-mar 1288
                $found_leaf = false;
635 daniel-mar 1289
                if ($obj = OIDplusObject::parse($request)) {
951 daniel-mar 1290
                        $found_leaf = OIDplusObject::exists($request);
1291
                        do {
1292
                                if ($obj->userHasReadRights()) {
635 daniel-mar 1293
                                        $ary[] = $obj->nodeId();
951 daniel-mar 1294
                                }
1295
                        } while ($obj = $obj->getParent());
1296
                        $ary = array_reverse($ary);
1297
                }
1298
                if (!$found_leaf) {
952 daniel-mar 1299
                        $alternatives = $this->getAlternativesForQuery($request);
951 daniel-mar 1300
                        foreach ($alternatives as $alternative) {
1301
                                $ary_ = array();
1302
                                if ($obj = OIDplusObject::parse($alternative)) {
1303
                                        if ($obj->userHasReadRights() && OIDplusObject::exists($alternative)) {
1304
                                                do {
1305
                                                        $ary_[] = $obj->nodeId();
1306
                                                } while ($obj = $obj->getParent());
1307
                                                $ary_ = array_reverse($ary_);
1308
                                        }
1309
                                }
1310
                                if (!empty($ary_)) {
1311
                                        $ary = $ary_;
1312
                                        break;
1313
                                }
635 daniel-mar 1314
                        }
1315
                }
1316
                return $ary;
1317
        }
1318
 
1116 daniel-mar 1319
        /**
1320
         * @var int
1321
         */
635 daniel-mar 1322
        private static $crudCounter = 0;
1323
 
1116 daniel-mar 1324
        /**
1121 daniel-mar 1325
         * @param string $parent
1326
         * @return string
1116 daniel-mar 1327
         * @throws OIDplusConfigInitializationException
1328
         * @throws OIDplusException
1329
         */
1121 daniel-mar 1330
        protected static function showCrud(string $parent='oid:'): string {
635 daniel-mar 1331
                $items_total = 0;
1332
                $items_hidden = 0;
1333
 
1334
                $objParent = OIDplusObject::parse($parent);
1121 daniel-mar 1335
                if (!$objParent) return '';
635 daniel-mar 1336
                $parentNS = $objParent::ns();
1337
 
1371 daniel-mar 1338
                // http://oid-info.com/cgi-bin/display?a=list-by-category&category=Not%20allocating%20identifiers
635 daniel-mar 1339
                $no_asn1 = array(
1340
                        'oid:1.3.6.1.4.1',
1341
                        'oid:1.3.6.1.4.1.37476.9000',
1342
                        'oid:1.3.6.1.4.1.37553.8.8',
1343
                        'oid:2.16.276.1',
719 daniel-mar 1344
                        //'oid:2.25', // according to Olivier, it is OK that UUID owners define their own ASN.1 ID, since the ASN.1 ID is not required to be unique
1345
                        //'oid:1.2.840.113556.1.8000.2554' // Adhoc (GUID/UUID-based) customer use. It is probably the same case as the UUID OIDs, after all, these are UUIDs, too.
635 daniel-mar 1346
                );
1347
 
1371 daniel-mar 1348
                // http://oid-info.com/cgi-bin/display?a=list-by-category&category=Not%20allocating%20Unicode%20labels
635 daniel-mar 1349
                $no_iri = array(
1350
                        'oid:1.2.250.1',
1351
                        'oid:1.3.6.1.4.1',
1352
                        'oid:1.3.6.1.4.1.37476.9000',
1353
                        'oid:1.3.6.1.4.1.37553.8.8',
1354
                        'oid:2.16.276.1',
1355
                        'oid:2.25'
1356
                );
1357
 
1358
                $accepts_asn1 = ($parentNS == 'oid') && (!in_array($objParent->nodeId(), $no_asn1)) && (!is_uuid_oid($objParent->nodeId(),true));
1359
                $accepts_iri  = ($parentNS == 'oid') && (!in_array($objParent->nodeId(), $no_iri)) && (!is_uuid_oid($objParent->nodeId(),true));
1360
 
1361
                $result = OIDplus::db()->query("select o.*, r.ra_name " .
1362
                                               "from ###objects o " .
1363
                                               "left join ###ra r on r.email = o.ra_email " .
1148 daniel-mar 1364
                                               "where parent = ? ", array($parent));
1156 daniel-mar 1365
                $result->naturalSortByField('id');
635 daniel-mar 1366
 
693 daniel-mar 1367
                $rows = array();
1368
                while ($row = $result->fetch_object()) {
1369
                        $obj = OIDplusObject::parse($row->id);
1121 daniel-mar 1370
                        if ($obj) $rows[] = array($obj,$row);
693 daniel-mar 1371
                }
1372
 
1373
                $enable_weid_presentation = OIDplus::config()->getValue('oid_grid_show_weid');
1374
 
1116 daniel-mar 1375
                $output  = '<div class="container box"><div id="suboid_table" class="table-responsive">';
1259 daniel-mar 1376
                $output .= '<table id="crudTable" class="table table-bordered table-striped">';
1138 daniel-mar 1377
                $output .= '<thead>';
635 daniel-mar 1378
                $output .= '    <tr>';
1379
                $output .= '         <th>'._L('ID').(($parentNS == 'gs1') ? ' '._L('(without check digit)') : '').'</th>';
692 daniel-mar 1380
                if ($enable_weid_presentation && ($parentNS == 'oid') && !$objParent->isRoot()) {
693 daniel-mar 1381
                        $output .= '         <th><abbr title="'._L('Binary-to-text encoding used for WEIDs').'">'._L('Base36').'</abbr></th>';
1382
                }
635 daniel-mar 1383
                if ($parentNS == 'oid') {
1384
                        if ($accepts_asn1) $output .= '      <th>'._L('ASN.1 IDs (comma sep.)').'</th>';
1385
                        if ($accepts_iri)  $output .= '      <th>'._L('IRI IDs (comma sep.)').'</th>';
1386
                }
1387
                $output .= '         <th>'._L('RA').'</th>';
1388
                $output .= '         <th>'._L('Comment').'</th>';
1389
                if ($objParent->userHasWriteRights()) {
1390
                        $output .= '         <th>'._L('Hide').'</th>';
1391
                        $output .= '         <th>'._L('Update').'</th>';
1392
                        $output .= '         <th>'._L('Delete').'</th>';
1393
                }
1394
                $output .= '         <th>'._L('Created').'</th>';
1395
                $output .= '         <th>'._L('Updated').'</th>';
1396
                $output .= '    </tr>';
1138 daniel-mar 1397
                $output .= '</thead>';
1141 daniel-mar 1398
 
1138 daniel-mar 1399
                $output .= '<tbody>';
635 daniel-mar 1400
                foreach ($rows as list($obj,$row)) {
1401
                        $items_total++;
1402
                        if (!$obj->userHasReadRights()) {
1403
                                $items_hidden++;
1404
                                continue;
1405
                        }
1406
 
1407
                        $show_id = $obj->crudShowId($objParent);
1408
 
1409
                        $asn1ids = array();
1410
                        $res2 = OIDplus::db()->query("select name from ###asn1id where oid = ? order by lfd", array($row->id));
1411
                        while ($row2 = $res2->fetch_array()) {
1412
                                $asn1ids[] = $row2['name'];
1413
                        }
1414
 
1415
                        $iris = array();
1416
                        $res2 = OIDplus::db()->query("select name from ###iri where oid = ? order by lfd", array($row->id));
1417
                        while ($row2 = $res2->fetch_array()) {
1418
                                $iris[] = $row2['name'];
1419
                        }
1420
 
1058 daniel-mar 1421
                        $date_created = is_null($row->created) || (explode(' ', $row->created)[0] == '0000-00-00') ? '' : explode(' ', $row->created)[0];
1422
                        $date_updated = is_null($row->updated) || (explode(' ', $row->updated)[0] == '0000-00-00') ? '' : explode(' ', $row->updated)[0];
635 daniel-mar 1423
 
1424
                        $output .= '<tr>';
693 daniel-mar 1425
                        $output .= '     <td><a href="?goto='.urlencode($row->id).'" onclick="openAndSelectNode('.js_escape($row->id).', '.js_escape($parent).'); return false;">'.htmlentities($show_id).'</a>';
1426
                        if ($enable_weid_presentation && ($parentNS == 'oid') && $objParent->isRoot()) {
1427
                                // To save space horizontal space, the WEIDs were written below the OIDs
1116 daniel-mar 1428
                                assert($obj instanceof OIDplusOid); //assert(get_class($obj) === "ViaThinkSoft\OIDplus\OIDplusOid");
693 daniel-mar 1429
                                $output .= '<br>'.$obj->getWeidNotation(true);
1430
                        }
1431
                        $output .= '</td>';
1432
                        if ($enable_weid_presentation && ($parentNS == 'oid') && !$objParent->isRoot()) {
1116 daniel-mar 1433
                                assert($obj instanceof OIDplusOid); //assert(get_class($obj) === "ViaThinkSoft\OIDplus\OIDplusOid");
693 daniel-mar 1434
                                $output .= '    <td>'.htmlentities($obj->weidArc()).'</td>';
1435
                        }
635 daniel-mar 1436
                        if ($objParent->userHasWriteRights()) {
1437
                                if ($parentNS == 'oid') {
1438
                                        if ($accepts_asn1) $output .= '     <td><input type="text" id="asn1ids_'.$row->id.'" value="'.implode(', ', $asn1ids).'"></td>';
1439
                                        if ($accepts_iri)  $output .= '     <td><input type="text" id="iris_'.$row->id.'" value="'.implode(', ', $iris).'"></td>';
1440
                                }
1219 daniel-mar 1441
                                $output .= '     <td><input type="text" id="ra_email_'.$row->id.'" value="'.htmlentities($row->ra_email ?? '').'"></td>';
1442
                                $output .= '     <td><input type="text" id="comment_'.$row->id.'" value="'.htmlentities($row->comment ?? '').'"></td>';
635 daniel-mar 1443
                                $output .= '     <td><input type="checkbox" id="hide_'.$row->id.'" '.($row->confidential ? 'checked' : '').'></td>';
1444
                                $output .= '     <td><button type="button" name="update_'.$row->id.'" id="update_'.$row->id.'" class="btn btn-success btn-xs update" onclick="OIDplusPagePublicObjects.crudActionUpdate('.js_escape($row->id).', '.js_escape($parent).')">'._L('Update').'</button></td>';
1445
                                $output .= '     <td><button type="button" name="delete_'.$row->id.'" id="delete_'.$row->id.'" class="btn btn-danger btn-xs delete" onclick="OIDplusPagePublicObjects.crudActionDelete('.js_escape($row->id).', '.js_escape($parent).')">'._L('Delete').'</button></td>';
1446
                                $output .= '     <td>'.$date_created.'</td>';
1447
                                $output .= '     <td>'.$date_updated.'</td>';
1448
                        } else {
1449
                                if ($parentNS == 'oid') {
693 daniel-mar 1450
                                        if ($asn1ids == '') $asn1ids = '<i>'._L('(none)').'</i>';
1451
                                        if ($iris == '') $iris = '<i>'._L('(none)').'</i>';
635 daniel-mar 1452
                                        $asn1ids_ext = array();
1453
                                        foreach ($asn1ids as $asn1id) {
1454
                                                $asn1ids_ext[] = '<a href="?goto='.urlencode($row->id).'" onclick="openAndSelectNode('.js_escape($row->id).', '.js_escape($parent).'); return false;">'.$asn1id.'</a>';
1455
                                        }
1456
                                        if ($accepts_asn1) $output .= '     <td>'.implode(', ', $asn1ids_ext).'</td>';
1457
                                        if ($accepts_iri)  $output .= '     <td>'.implode(', ', $iris).'</td>';
1458
                                }
1219 daniel-mar 1459
                                $output .= '     <td><a '.OIDplus::gui()->link('oidplus:rainfo$'.str_replace('@','&',$row->ra_email??'')).'>'.htmlentities(empty($row->ra_name??'') ? str_replace('@','&',$row->ra_email??'') : $row->ra_name).'</a></td>';
1460
                                $output .= '     <td>'.htmlentities($row->comment ?? '').'</td>';
635 daniel-mar 1461
                                $output .= '     <td>'.$date_created.'</td>';
1462
                                $output .= '     <td>'.$date_updated.'</td>';
1463
                        }
1464
                        $output .= '</tr>';
1465
                }
1141 daniel-mar 1466
                $output .= '</tbody>';
635 daniel-mar 1467
 
1121 daniel-mar 1468
                $parent_ra_email = $objParent->getRaMail() ;
693 daniel-mar 1469
 
692 daniel-mar 1470
                // "Create OID" row
635 daniel-mar 1471
                if ($objParent->userHasWriteRights()) {
1141 daniel-mar 1472
                        $output .= '<tfoot>';
635 daniel-mar 1473
                        $output .= '<tr>';
1121 daniel-mar 1474
                        $prefix = $objParent->crudInsertPrefix();
693 daniel-mar 1475
 
1121 daniel-mar 1476
                        $suffix = $objParent->crudInsertSuffix();
693 daniel-mar 1477
                        foreach (OIDplus::getObjectTypePlugins() as $plugin) {
1137 daniel-mar 1478
                                if (($plugin instanceof INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_6) && ($plugin::getObjectTypeClassName()::ns() == $parentNS)) {
1131 daniel-mar 1479
                                        $suffix .= $plugin->gridGeneratorLinks($objParent);
693 daniel-mar 1480
                                }
1481
                        }
1482
 
1483
                        if ($parentNS == 'guid') {
695 daniel-mar 1484
                                $output .= '     <td>'.$prefix.' <input type="text" id="id" value="" style="width:100%;min-width:275px">'.$suffix.'</td>';
693 daniel-mar 1485
                        } else if ($parentNS == 'oid') {
635 daniel-mar 1486
                                // TODO: Idea: Give a class name, e.g. "OID" and then with a oid-specific CSS make the width individual. So, every plugin has more control over the appearance and widths of the input fields
693 daniel-mar 1487
                                if ($objParent->nodeId() === 'oid:2.25') {
695 daniel-mar 1488
                                        $output .= '     <td>'.$prefix.' <input type="text" id="id" value="" style="width:100%;min-width:345px">'.$suffix.'</td>';
693 daniel-mar 1489
                                        if ($enable_weid_presentation) $output .= '     <td>&nbsp;</td>'; // For UUID-OIDs, you must generate a valid one. Don't be tempted to create one using the Base36 input!
1490
                                } else if ($objParent->isRoot()) {
695 daniel-mar 1491
                                        $output .= '     <td>'.$prefix.' <input type="text" id="id" value="" style="width:100%;min-width:345px">'.$suffix.'</td>';
693 daniel-mar 1492
                                        if ($enable_weid_presentation) $output .= ''; // WEID-editor not available for root nodes at the moment. For the moment you need to enter the OID (TODO: Create JavaScript WEID encoder/decoder)
635 daniel-mar 1493
                                } else {
693 daniel-mar 1494
                                        if ($enable_weid_presentation) {
695 daniel-mar 1495
                                                $output .= '     <td>'.$prefix.' <input oninput="OIDplusPagePublicObjects.frdl_oidid_change()" type="text" id="id" value="" style="width:100%;min-width:100px">'.$suffix.'</td>';
693 daniel-mar 1496
                                                $output .= '     <td><input type="text" name="weid" id="weid" value="" oninput="OIDplusPagePublicObjects.frdl_weid_change()" style="width:100%;min-width:100px"></td>';
1497
                                        } else {
695 daniel-mar 1498
                                                $output .= '     <td>'.$prefix.' <input type="text" id="id" value="" style="width:100%;min-width:100px">'.$suffix.'</td>';
693 daniel-mar 1499
                                        }
635 daniel-mar 1500
                                }
1501
                        } else {
695 daniel-mar 1502
                                $output .= '     <td>'.$prefix.' <input type="text" id="id" value="" style="width:100%;min-width:100px">'.$suffix.'</td>';
635 daniel-mar 1503
                        }
1504
                        if ($accepts_asn1) $output .= '     <td><input type="text" id="asn1ids" value=""></td>';
1505
                        if ($accepts_iri)  $output .= '     <td><input type="text" id="iris" value=""></td>';
1137 daniel-mar 1506
                        $output .= '     <td><input type="text" id="ra_email" value="'.htmlentities($parent_ra_email ?? '').'"></td>';
635 daniel-mar 1507
                        $output .= '     <td><input type="text" id="comment" value=""></td>';
1508
                        $output .= '     <td><input type="checkbox" id="hide"></td>';
1509
                        $output .= '     <td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs update" onclick="OIDplusPagePublicObjects.crudActionInsert('.js_escape($parent).')">'._L('Insert').'</button></td>';
1510
                        $output .= '     <td></td>';
1511
                        $output .= '     <td></td>';
1512
                        $output .= '     <td></td>';
1513
                        $output .= '</tr>';
1141 daniel-mar 1514
                        $output .= '</tfoot>';
635 daniel-mar 1515
                } else {
1516
                        if ($items_total-$items_hidden == 0) {
1517
                                $cols = ($parentNS == 'oid') ? 7 : 5;
692 daniel-mar 1518
                                if ($enable_weid_presentation && ($parentNS == 'oid') && !$objParent->isRoot()) {
1519
                                        $cols++;
693 daniel-mar 1520
                                }
1138 daniel-mar 1521
                                $output .= '<tfoot>';
635 daniel-mar 1522
                                $output .= '<tr><td colspan="'.$cols.'">'._L('No items available').'</td></tr>';
1138 daniel-mar 1523
                                $output .= '</tfoot>';
635 daniel-mar 1524
                        }
1525
                }
1526
 
1527
                $output .= '</table>';
1528
                $output .= '</div></div>';
1529
 
1530
                if ($items_hidden == 1) {
1531
                        $output .= '<p>'._L('One item is hidden. Please <a %1>log in</a> to see it.',$items_hidden,OIDplus::gui()->link('oidplus:login')).'</p>';
1532
                } else if ($items_hidden > 1) {
1533
                        $output .= '<p>'._L('%1 items are hidden. Please <a %2>log in</a> to see them.',$items_hidden,OIDplus::gui()->link('oidplus:login')).'</p>';
1534
                }
1535
 
1536
                return $output;
1537
        }
1538
 
1116 daniel-mar 1539
        /**
1130 daniel-mar 1540
         * @param string $html
1541
         * @return string
1116 daniel-mar 1542
         */
1130 daniel-mar 1543
        protected static function objDescription(string $html): string {
635 daniel-mar 1544
                // We allow HTML, but no hacking
1545
                $html = anti_xss($html);
1546
 
1547
                return trim_br($html);
1548
        }
1549
 
1116 daniel-mar 1550
        /**
1551
         * 'quickbars' added 11 July 2019: Disabled because of two problems:
1552
         *                                 1. When you load TinyMCE via AJAX using the left menu, the quickbar is immediately shown, even if TinyMCE does not have the focus
1553
         *                                 2. When you load a page without TinyMCE using the left menu, the quickbar is still visible, although there is no edit
1554
         * 'colorpicker', 'textcolor' and 'contextmenu' added in 07 April 2020, because it is built in in the core.
1555
         * 'importcss' added 17 September 2020, because it breaks the "Format/Style" dropdown box ("styleselect" toolbar)
1556
         * 'legacyoutput' added 24 September 2021, because it is declared as deprecated
1557
         * 'spellchecker' added 6 October 2021, because it is declared as deprecated and marked for removal in TinyMCE 6.0
1558
         * 'imagetools' and 'toc' added 23 February 2022, because they are declared as deprecated and marked for removal in TinyMCE 6.0 ("moving to premium")
1559
         * @var string[]
1560
         */
753 daniel-mar 1561
        public static $exclude_tinymce_plugins = array('fullpage', 'bbcode', 'quickbars', 'colorpicker', 'textcolor', 'contextmenu', 'importcss', 'legacyoutput', 'spellchecker', 'imagetools', 'toc');
635 daniel-mar 1562
 
1116 daniel-mar 1563
        /**
1130 daniel-mar 1564
         * @param string $name
1565
         * @param string $content
1116 daniel-mar 1566
         * @return string
1567
         * @throws OIDplusConfigInitializationException
1568
         * @throws OIDplusException
1569
         */
1130 daniel-mar 1570
        protected static function showMCE(string $name, string $content): string {
635 daniel-mar 1571
                $mce_plugins = array();
1572
                foreach (glob(OIDplus::localpath().'vendor/tinymce/tinymce/plugins/*') as $m) { // */
1573
                        $mce_plugins[] = basename($m);
1574
                }
1575
 
1576
                foreach (self::$exclude_tinymce_plugins as $exclude) {
1577
                        $index = array_search($exclude, $mce_plugins);
1578
                        if ($index !== false) unset($mce_plugins[$index]);
1579
                }
1580
 
1581
                $oidplusLang = OIDplus::getCurrentLang();
1582
 
1583
                $langCandidates = array(
1584
                        strtolower(substr($oidplusLang,0,2)).'_'.strtoupper(substr($oidplusLang,2,2)), // de_DE
1585
                        strtolower(substr($oidplusLang,0,2)) // de
1586
                );
1587
                $tinyMCELang = '';
1588
                foreach ($langCandidates as $candidate) {
1589
                        if (file_exists(OIDplus::localpath().'vendor/tweeb/tinymce-i18n/langs/'.$candidate.'.js')) {
1590
                                $tinyMCELang = $candidate;
1591
                                break;
1592
                        }
1593
                }
1594
 
1595
                $out = '<script>
1596
                                tinymce.EditorManager.baseURL = "vendor/tinymce/tinymce";
1597
                                tinymce.init({
1381 daniel-mar 1598
                                        document_base_url: getSystemUrl(),
635 daniel-mar 1599
                                        selector: "#'.$name.'",
1600
                                        height: 200,
1601
                                        statusbar: false,
1602
//                                      menubar:false,
1603
//                                      toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table | fontsizeselect",
1604
                                        toolbar: "undo redo | styleselect | bold italic underline forecolor | bullist numlist | outdent indent | table | fontsizeselect",
1605
                                        plugins: "'.implode(' ', $mce_plugins).'",
1606
                                        mobile: {
1607
                                                theme: "mobile",
1608
                                                toolbar: "undo redo | styleselect | bold italic underline forecolor | bullist numlist | outdent indent | table | fontsizeselect",
1609
                                                plugins: "'.implode(' ', $mce_plugins).'"
1610
                                        }
1611
                                        '.($tinyMCELang == '' ? '' : ', language : "'.$tinyMCELang.'"').'
801 daniel-mar 1612
                                        '.($tinyMCELang == '' ? '' : ', language_url : "'.OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL).'vendor/tweeb/tinymce-i18n/langs/'.$tinyMCELang.'.js"').'
635 daniel-mar 1613
                                });
1614
 
1615
                                pageChangeRequestCallbacks.push([OIDplusPagePublicObjects.cbQueryTinyMCE, "#'.$name.'"]);
1616
                                pageChangeCallbacks.push([OIDplusPagePublicObjects.cbRemoveTinyMCE, "#'.$name.'"]);
1617
                        </script>';
1618
 
1619
                $content = htmlentities($content); // For some reason, if we want to display the text "<xyz>" in TinyMCE, we need to double-encode things! &lt; will not be accepted, we need &amp;lt; ... why?
1620
 
1621
                $out .= '<textarea name="'.htmlentities($name).'" id="'.htmlentities($name).'">'.trim($content).'</textarea><br>';
1622
 
1623
                return $out;
1624
        }
1625
 
1116 daniel-mar 1626
        /**
1131 daniel-mar 1627
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_1
1116 daniel-mar 1628
         * @return bool
1629
         * @throws OIDplusException
1630
         */
635 daniel-mar 1631
        public function oobeRequested(): bool {
1632
                return OIDplus::config()->getValue('oobe_objects_done') == '0';
1633
        }
1634
 
1116 daniel-mar 1635
        /**
1131 daniel-mar 1636
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_1
1125 daniel-mar 1637
         * @param int $step
1638
         * @param bool $do_edits
1639
         * @param bool $errors_happened
1116 daniel-mar 1640
         * @return void
1641
         */
1125 daniel-mar 1642
        public function oobeEntry(int $step, bool $do_edits, bool &$errors_happened)/*: void*/ {
1055 daniel-mar 1643
                echo '<h2>'._L('Step %1: Enable/Disable object type plugins',$step).'</h2>';
635 daniel-mar 1644
                echo '<p>'._L('Which object types do you want to manage using OIDplus?').'</p>';
1645
 
1646
                $enabled_ary = array();
1647
 
1648
                foreach (OIDplus::getEnabledObjectTypes() as $ot) {
1649
                        echo '<input type="checkbox" name="enable_ot_'.$ot::ns().'" id="enable_ot_'.$ot::ns().'"';
1033 daniel-mar 1650
                        if (isset($_POST['sent'])) {
1651
                                if (isset($_POST['enable_ot_'.$ot::ns()])) {
635 daniel-mar 1652
                                        echo ' checked';
1653
                                        $enabled_ary[] = $ot::ns();
1654
                                }
1655
                        } else {
1656
                                echo ' checked';
1657
                        }
1658
                        echo '> <label for="enable_ot_'.$ot::ns().'">'.htmlentities($ot::objectTypeTitle()).'</label><br>';
1659
                }
1660
 
1661
                foreach (OIDplus::getDisabledObjectTypes() as $ot) {
1662
                        echo '<input type="checkbox" name="enable_ot_'.$ot::ns().'" id="enable_ot_'.$ot::ns().'"';
1033 daniel-mar 1663
                        if (isset($_POST['sent'])) {
1664
                                if (isset($_POST['enable_ot_'.$ot::ns()])) {
635 daniel-mar 1665
                                        echo ' checked';
1666
                                        $enabled_ary[] = $ot::ns();
1667
                                }
1668
                        } else {
1669
                                echo ''; // <-- difference
1670
                        }
1671
                        echo '> <label for="enable_ot_'.$ot::ns().'">'.htmlentities($ot::objectTypeTitle()).'</label><br>';
1672
                }
1673
 
1201 daniel-mar 1674
                $htmlmsg = '';
635 daniel-mar 1675
                if ($do_edits) {
1676
                        try {
1677
                                OIDplus::config()->setValue('objecttypes_enabled', implode(';', $enabled_ary));
1678
                                OIDplus::config()->setValue('oobe_objects_done', '1');
1050 daniel-mar 1679
                        } catch (\Exception $e) {
1201 daniel-mar 1680
                                $htmlmsg = $e instanceof OIDplusException ? $e->getHtmlMessage() : htmlentities($e->getMessage());
635 daniel-mar 1681
                                $errors_happened = true;
1682
                        }
1683
                }
1684
 
1201 daniel-mar 1685
                echo ' <font color="red"><b>'.$htmlmsg.'</b></font>';
635 daniel-mar 1686
        }
1687
 
1116 daniel-mar 1688
        /**
1131 daniel-mar 1689
         * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_8
1130 daniel-mar 1690
         * @param string|null $user
1116 daniel-mar 1691
         * @return array
1692
         * @throws OIDplusException
1693
         */
1130 daniel-mar 1694
        public function getNotifications(string $user=null): array {
1000 daniel-mar 1695
                $notifications = array();
1148 daniel-mar 1696
                $res = OIDplus::db()->query("select id, title from ###objects");
1156 daniel-mar 1697
                $res->naturalSortByField('id');
1000 daniel-mar 1698
                if ($res->any()) {
1699
                        $is_admin_logged_in = OIDplus::authUtils()->isAdminLoggedIn(); // run just once, for performance
1700
                        while ($row = $res->fetch_array()) {
1701
                                if (empty($row['title'])) {
1702
                                        if ($user === 'admin') {
1703
                                                $accept = $is_admin_logged_in;
1704
                                        } else {
1705
                                                $accept = false;
1706
                                                if ($obj = OIDplusObject::parse($row['id'])) {
1707
                                                        if ($obj->userHasWriteRights($user)) {
1708
                                                                $accept = true;
1709
                                                        }
1710
                                                }
1711
                                        }
1712
 
1713
                                        if ($accept) {
1202 daniel-mar 1714
                                                $notifications[] = new OIDplusNotification('WARN', _L('Object %1 has no title.', '<a '.OIDplus::gui()->link($row['id']).'>'.htmlentities($row['id']).'</a>'));
1000 daniel-mar 1715
                                        }
1716
                                }
1717
                        }
1718
                }
1719
                return $notifications;
1720
        }
1721
 
693 daniel-mar 1722
}