Subversion Repositories oidplus

Rev

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