Subversion Repositories oidplus

Rev

Rev 1288 | Rev 1291 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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