Subversion Repositories oidplus

Rev

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