Subversion Repositories oidplus

Rev

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