Subversion Repositories oidplus

Rev

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