Subversion Repositories oidplus

Rev

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

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