Subversion Repositories oidplus

Rev

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