Subversion Repositories oidplus

Rev

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