Subversion Repositories oidplus

Rev

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