Subversion Repositories oidplus

Rev

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