Subversion Repositories oidplus

Rev

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