Subversion Repositories oidplus

Rev

Rev 1454 | Blame | Compare with Previous | Last modification | View Log | RSS feed

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