Subversion Repositories oidplus

Rev

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