Subversion Repositories oidplus

Rev

Go to most recent revision | Blame | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /**
  4.  * OID-Info.com API by Daniel Marschall, ViaThinkSoft
  5.  * License terms: Apache 2.0
  6.  * Revision: 2019-04-01
  7.  */
  8.  
  9. error_reporting(E_ALL | E_NOTICE | E_STRICT | E_DEPRECATED);
  10.  
  11. /*
  12. if (file_exists(__DIR__ . '/oid_utils.inc.phps')) require_once __DIR__ . '/oid_utils.inc.phps';
  13. if (file_exists(__DIR__ . '/oid_utils.inc.php'))  require_once __DIR__ . '/oid_utils.inc.php';
  14. if (file_exists(__DIR__ . '/xml_utils.inc.phps')) require_once __DIR__ . '/xml_utils.inc.phps';
  15. if (file_exists(__DIR__ . '/xml_utils.inc.php'))  require_once __DIR__ . '/xml_utils.inc.php';
  16. */
  17.  
  18. require_once __DIR__ . '/../../../includes/oid_utils.inc.php';
  19. require_once __DIR__ . '/../../../includes/xml_utils.inc.php';
  20.  
  21. class OIDInfoException extends Exception {
  22. }
  23.  
  24. class OIDInfoAPI {
  25.  
  26.         # --- PART 0: Constants
  27.  
  28.         // First digit of the ping result
  29.         // "-" = error
  30.         // "0" = OID does not exist
  31.         // "1" = OID does exist, but is not approved yet
  32.         // "2" = OID does exist and is accessible
  33.         /*private*/ const PING_IDX_EXISTS = 0;
  34.  
  35.         // Second digit of the ping result
  36.         // "-" = error
  37.         // "0" = The OID may not be created
  38.         // "1" = OID is not an illegal OID, and none of its ascendant is a leaf and its parent OID is not frozen
  39.         /*private*/ const PING_IDX_MAY_CREATE = 1;
  40.  
  41.         /*private*/ const SOFT_CORRECT_BEHAVIOR_NONE = 0;
  42.         /*private*/ const SOFT_CORRECT_BEHAVIOR_LOWERCASE_BEGINNING = 1;
  43.         /*private*/ const SOFT_CORRECT_BEHAVIOR_ALL_POSSIBLE = 2;
  44.  
  45.         /*public*/ const DEFAULT_ILLEGALITY_RULE_FILE = __DIR__ . '/oid_illegality_rules';
  46.  
  47.         # --- Part 1: "Ping API" for checking if OIDs are available or allowed to create
  48.  
  49.         public $verbosePingProviders = array('https://misc.daniel-marschall.de/oid-repository/ping_oid.php?oid={OID}');
  50.  
  51.         private $pingCache = array();
  52.  
  53.         public $pingCacheMaxAge = 3600;
  54.  
  55.         public function clearPingCache() {
  56.                 $this->pingCache = array();
  57.         }
  58.  
  59.         public function checkOnlineExists($oid) {
  60.                 if (!self::strictCheckSyntax($oid)) return false;
  61.  
  62.                 $pingResult = $this->pingOID($oid);
  63.                 $ret = $pingResult[self::PING_IDX_EXISTS] >= 1;
  64.                 return $ret;
  65.         }
  66.  
  67.         public function checkOnlineAvailable($oid) {
  68.                 if (!self::strictCheckSyntax($oid)) return false;
  69.  
  70.                 $pingResult = $this->pingOID($oid);
  71.                 $ret = $pingResult[self::PING_IDX_EXISTS] == 2;
  72.                 return $ret;
  73.         }
  74.  
  75.         public function checkOnlineAllowed($oid) {
  76.                 if (!self::strictCheckSyntax($oid)) return false;
  77.  
  78.                 $pingResult = $this->pingOID($oid);
  79.                 return $pingResult[self::PING_IDX_MAY_CREATE] == 1;
  80.         }
  81.  
  82.         public function checkOnlineMayCreate($oid) {
  83.                 if (!self::strictCheckSyntax($oid)) return false;
  84.  
  85.                 $pingResult = $this->pingOID($oid);
  86.  
  87.                 // OID is either illegal, or one of their parents are leaf or frozen
  88.                 # if (!checkOnlineAllowed($oid)) return false;
  89.                 if ($pingResult[self::PING_IDX_MAY_CREATE] == 0) return false;
  90.  
  91.                 // The OID exists already, so we don't need to create it again
  92.                 # if ($this->checkOnlineExists($oid)) return false;
  93.                 if ($pingResult[self::PING_IDX_EXISTS] >= 1) return false;
  94.  
  95.                 return true;
  96.         }
  97.  
  98.         protected function pingOID($oid) {
  99.                 if (isset($this->pingCache[$oid])) {
  100.                         $cacheAge = $this->pingCache[$oid][0] - time();
  101.                         if ($cacheAge <= $this->pingCacheMaxAge) {
  102.                                 return $this->pingCache[$oid][1];
  103.                         }
  104.                 }
  105.  
  106.                 if (count($this->verbosePingProviders) == 0) {
  107.                         throw new OIDInfoException("No verbose ping provider available!");
  108.                 }
  109.  
  110.                 $res = false;
  111.                 foreach ($this->verbosePingProviders as $url) {
  112.                         $url = str_replace('{OID}', $oid, $url);
  113.                         $cn = @file_get_contents($url);
  114.                         if ($cn === false) continue;
  115.                         $loc_res = trim($cn);
  116.                         if (strpos($loc_res, '-') === false) {
  117.                                 $res = $loc_res;
  118.                                 break;
  119.                         }
  120.                 }
  121.                 if ($res === false) {
  122.                         throw new OIDInfoException("Could not ping OID $oid status!");
  123.                 }
  124.  
  125.                 // if ($this->pingCacheMaxAge >= 0) {
  126.                         $this->pingCache[$oid] = array(time(), $res);
  127.                 //}
  128.  
  129.                 return $res;
  130.         }
  131.  
  132.         # --- PART 2: Syntax checking
  133.  
  134.         public static function strictCheckSyntax($oid) {
  135.                 return oid_valid_dotnotation($oid, false, false, 1);
  136.         }
  137.  
  138.         // Returns false if $oid has wrong syntax
  139.         // Return an OID without leading dot or zeroes, if the syntax is acceptable
  140.         public static function trySanitizeOID($oid) {
  141.                 // Allow leading dots and leading zeroes, but remove then afterwards
  142.                 $ok = oid_valid_dotnotation($oid, true, true, 1);
  143.                 if ($ok === false) return false;
  144.  
  145.                 return sanitizeOID($oid, $oid[0] == '.');
  146.         }
  147.  
  148.         # --- PART 3: XML file creation
  149.  
  150.         protected static function eMailValid($email) {
  151.                 # TODO: use isemail project
  152.  
  153.                 if (empty($email)) return false;
  154.  
  155.                 if (strpos($email, '@') === false) return false;
  156.  
  157.                 $ary = explode('@', $email, 2);
  158.                 if (!isset($ary[1])) return false;
  159.                 if (strpos($ary[1], '.') === false) return false;
  160.  
  161.                 return true;
  162.         }
  163.  
  164.         public function softCorrectEMail($email, $params) {
  165.                 $email = str_replace(' ', '', $email);
  166.                 $email = str_replace('&', '@', $email);
  167.                 $email = str_replace('(at)', '@', $email);
  168.                 $email = str_replace('[at]', '@', $email);
  169.                 $email = str_replace('(dot)', '.', $email);
  170.                 $email = str_replace('[dot]', '.', $email);
  171.                 $email = trim($email);
  172.  
  173.                 if (!$params['allow_illegal_email'] && !self::eMailValid($email)) {
  174.                         return '';
  175.                 }
  176.  
  177.                 return $email;
  178.         }
  179.  
  180.         public function softCorrectPhone($phone, $params) {
  181.                 // TODO: if no "+", add "+1" , but only if address is in USA
  182.                 // TODO: or use param to fixate country if it is not known
  183.                 /*
  184.                 NOTE: with german phone numbers, this will cause trouble, even if we assume "+49"
  185.                         06223 / 1234
  186.                         shall be
  187.                         +49 6223 1234
  188.                         and not
  189.                         +49 06223 1234
  190.                 */
  191.  
  192.                 $phone = str_replace('-', ' ', $phone);
  193.                 $phone = str_replace('.', ' ', $phone);
  194.                 $phone = str_replace('/', ' ', $phone);
  195.                 $phone = str_replace('(', ' ', $phone);
  196.                 $phone = str_replace(')', ' ', $phone);
  197.  
  198.                 // HL7 registry has included this accidently
  199.                 $phone = str_replace('&quot;', '', $phone);
  200.  
  201.                 $phone = trim($phone);
  202.  
  203.                 return $phone;
  204.         }
  205.  
  206.         private static function strip_to_xhtml_light($str){
  207.                 $str = str_ireplace('<b>', '<strong>', $str);
  208.                 $str = str_ireplace('</b>', '</strong>', $str);
  209.  
  210.                 $str = preg_replace('@<\s*script.+<\s*/script.*>@isU', '', $str);
  211.                 $str = preg_replace('@<\s*style.+<\s*/style.*>@isU', '', $str);
  212.  
  213.                 $str = preg_replace_callback(
  214.                         '@<(\s*/{0,1}\d*)([^\s/>]+)(\s*[^>]*)>@i',
  215.                         function ($treffer) {
  216.                                 // see http://oid-info.com/xhtml-light.xsd
  217.                                 $whitelist = array('a', 'br', 'code', 'em', 'font', 'img', 'li', 'strong', 'sub', 'sup', 'ul');
  218.  
  219.                                 $pre = $treffer[1];
  220.                                 $tag = $treffer[2];
  221.                                 $attrib = $treffer[3];
  222.                                 if (in_array($tag, $whitelist)) {
  223.                                         return '<'.$pre.$tag.$attrib.'>';
  224.                                 } else {
  225.                                         return '';
  226.                                 }
  227.                         }, $str);
  228.  
  229.                 return $str;
  230.         }
  231.  
  232.         const OIDINFO_CORRECT_DESC_OPTIONAL_ENDING_DOT = 0;
  233.         const OIDINFO_CORRECT_DESC_ENFORCE_ENDING_DOT = 1;
  234.         const OIDINFO_CORRECT_DESC_DISALLOW_ENDING_DOT = 2;
  235.  
  236.         public function correctDesc($desc, $params, $ending_dot_policy=self::OIDINFO_CORRECT_DESC_OPTIONAL_ENDING_DOT, $enforce_xhtml_light=false) {
  237.                 $desc = trim($desc);
  238.  
  239.                 $desc = preg_replace('@<!\\[CDATA\\[(.+)\\]\\]>@ismU', '\\1', $desc);
  240.  
  241.                 if (substr_count($desc, '>') != substr_count($desc, '<')) {
  242.                         $params['allow_html'] = false;
  243.                 }
  244.  
  245.                 $desc = str_replace("\r", '', $desc);
  246.  
  247.                 if (!$params['allow_html']) {
  248.                         // htmlentities_numeric() does this for us
  249.                         /*
  250.                         $desc = str_replace('&', '&amp;', $desc);
  251.                         $desc = str_replace('<', '&lt;', $desc);
  252.                         $desc = str_replace('>', '&gt;', $desc);
  253.                         $desc = str_replace('"', '&quot;', $desc);
  254.                         $desc = str_replace("'", '&#39;', $desc); // &apos; is not HTML. It is XML
  255.                         */
  256.  
  257.                         $desc = str_replace("\n", '<br />', $desc);
  258.                 } else {
  259.                         // Some problems we had with HL7 registry
  260.                         $desc = preg_replace('@&lt;(/{0,1}(p|i|b|u|ul|li))&gt;@ismU', '<\\1>', $desc);
  261.                         # preg_match_all('@&lt;[^ :\\@]+&gt;@ismU', $desc, $m);
  262.                         # if (count($m[0]) > 0) print_r($m);
  263.  
  264.                         $desc = preg_replace('@<i>(.+)&lt;i/&gt;@ismU', '<i>\\1</i>', $desc);
  265.                         $desc = str_replace('<p><p>', '</p><p>', $desc);
  266.  
  267.                         // <p> are not supported by oid-info.com
  268.                         $desc = str_replace('<p>', '<br /><br />', $desc);
  269.                         $desc = str_replace('</p>', '', $desc);
  270.                 }
  271.  
  272.                 // Escape unicode characters as numeric &#...;
  273.                 // The XML 1.0 standard does only has a few entities, but nothing like e.g. &euro; , so we prefer numeric
  274.  
  275.                 //$desc = htmlentities_numeric($desc, $params['allow_html']);
  276.                 if (!$params['allow_html']) $desc = htmlentities($desc);
  277.                 $desc = html_named_to_numeric_entities($desc);
  278.  
  279.                 // Remove HTML tags which are not allowed
  280.                 if ($params['allow_html'] && (!$params['ignore_xhtml_light']) && $enforce_xhtml_light) {
  281.                         // oid-info.com does only allow a few HTML tags
  282.                         // see http://oid-info.com/xhtml-light.xsd
  283.                         $desc = self::strip_to_xhtml_light($desc);
  284.                 }
  285.  
  286.                 // Solve some XML problems...
  287.                 $desc = preg_replace('@<\s*br\s*>@ismU', '<br/>', $desc); // auto close <br>
  288.                 $desc = preg_replace('@(href\s*=\s*)(["\'])(.*)&([^#].*)(\2)@ismU', '\1\2\3&amp;\4\5', $desc); // fix "&" inside href-URLs to &amp;
  289.                 // TODO: what do we do if there are more XHTML errors (e.g. additional open tags) which would make the XML invalid?
  290.  
  291.                 // "Trim" <br/>
  292.                 do { $desc = preg_replace('@^\s*<\s*br\s*/{0,1}\s*>@isU', '', $desc, -1, $count); } while ($count > 0); // left trim
  293.                 do { $desc = preg_replace('@<\s*br\s*/{0,1}\s*>\s*$@isU', '', $desc, -1, $count); } while ($count > 0); // right trim
  294.  
  295.                 // Correct double-encoded stuff
  296.                 if (!isset($params['tolerant_htmlentities']) || $params['tolerant_htmlentities']) {
  297.                         do {
  298.                                 $old_desc = $desc;
  299.                                 # Full list of entities: https://www.freeformatter.com/html-entities.html
  300.                                 # Max: 8 chars ( &thetasym; )
  301.                                 # Min: 2 chars ( lt,gt,ni,or,ne,le,ge,Mu,Nu,Xi,Pi,mu,nu,xi,pi )
  302.                                 $desc = preg_replace('@(&|&amp;)(#|&#35;)(\d+);@ismU', '&#\3;', $desc);
  303.                                 $desc = preg_replace('@(&|&amp;)([a-zA-Z0-9]{2,8});@ismU', '&\2;', $desc);
  304.                         } while ($old_desc != $desc);
  305.                 }
  306.  
  307.                 // TODO: use the complete list of oid-info.com
  308.                 // TODO: Make this step optional using $params
  309.                 /*
  310.                 Array
  311.                 (
  312.                     [0] => Root OID for
  313.                     [1] => OID for
  314.                     [2] => OID identifying
  315.                     [3] => Top arc for
  316.                     [4] => Arc for
  317.                     [5] => arc root
  318.                     [6] => Node for
  319.                     [7] => Leaf node for
  320.                     [8] => This OID describes
  321.                     [9] => [tT]his oid
  322.                     [10] => This arc describes
  323.                     [11] => This identifies
  324.                     [12] => Identifies a
  325.                     [13] => [Oo]bject [Ii]dentifier
  326.                     [14] => Identifier for
  327.                     [15] => This [Ii]dentifier is for
  328.                     [16] => Identifiers used by
  329.                     [17] => identifier$
  330.                     [18] => This branch
  331.                     [19] => Branch for
  332.                     [20] => Child tree for
  333.                     [21] => Child for
  334.                     [22] => Subtree for
  335.                     [23] => Sub-OID
  336.                     [24] => Tree for
  337.                     [25] => Child object
  338.                     [26] => Parent OID
  339.                     [27] =>  root for
  340.                     [28] => Assigned for
  341.                     [29] => Used to identify
  342.                     [30] => Used in
  343.                     [31] => Used for
  344.                     [32] => For use by
  345.                     [33] => Entry for
  346.                     [34] => This is for
  347.                     [35] =>  ["]?OID["]?
  348.                     [36] => ^OID
  349.                     [37] =>  OID$
  350.                     [38] =>  oid
  351.                     [39] =>  oid$
  352.                     [40] =>  OIDs
  353.                 )
  354.                 $x = 'Root OID for ; OID for ; OID identifying ; Top arc for ; Arc for ; arc root; Node for ; Leaf node for ; This OID describes ; [tT]his oid ; This arc describes ; This identifies ; Identifies a ; [Oo]bject [Ii]dentifier; Identifier for ; This [Ii]dentifier is for ; Identifiers used by ; identifier$; This branch ; Branch for ; Child tree for ; Child for ; Subtree for ; Sub-OID; Tree for ; Child object; Parent OID;  root for ; Assigned for ; Used to identify ; Used in ; Used for ; For use by ; Entry for ; This is for ;  ["]?OID["]? ; ^OID ;  OID$;  oid ;  oid$;  OIDs';
  355.                 $ary = explode('; ', $x);
  356.                 print_r($ary);
  357.                 */
  358.                 $desc = preg_replace("@^Root OID for the @i",                   '', $desc);
  359.                 $desc = preg_replace("@^Root OID for @i",                       '', $desc);
  360.                 $desc = preg_replace("@^OID root for the @i",                   '', $desc);
  361.                 $desc = preg_replace("@^OID root for @i",                       '', $desc);
  362.                 $desc = preg_replace("@^This OID will be used for @i",          '', $desc);
  363.                 $desc = preg_replace("@^This will be a generic OID for the @i", '', $desc);
  364.                 $desc = preg_replace("@^OID for @i",                            '', $desc);
  365.                 $desc = preg_replace("@ Root OID$@i",                           '', $desc);
  366.                 $desc = preg_replace("@ OID$@i",                                '', $desc);
  367.                 $desc = preg_replace("@ OID Namespace$@i",                      '', $desc);
  368.                 $desc = preg_replace("@^OID for @i",                            '', $desc);
  369.  
  370.                 $desc = rtrim($desc);
  371.                 if ($ending_dot_policy == self::OIDINFO_CORRECT_DESC_ENFORCE_ENDING_DOT) {
  372.                         if (($desc != '') && (substr($desc, -1)) != '.') $desc .= '.';
  373.                 } else if ($ending_dot_policy == self::OIDINFO_CORRECT_DESC_DISALLOW_ENDING_DOT) {
  374.                         $desc = preg_replace('@\\.$@', '', $desc);
  375.                 }
  376.  
  377.                 return $desc;
  378.         }
  379.  
  380.         public function xmlAddHeader($firstName, $lastName, $email) {
  381.                 // TODO: encode
  382.  
  383.                 $firstName = htmlentities_numeric($firstName);
  384.                 if (empty($firstName)) {
  385.                         throw new OIDInfoException("Please supply a first name");
  386.                 }
  387.  
  388.                 $lastName  = htmlentities_numeric($lastName);
  389.                 if (empty($lastName)) {
  390.                         throw new OIDInfoException("Please supply a last name");
  391.                 }
  392.  
  393.                 $email     = htmlentities_numeric($email);
  394.                 if (empty($email)) {
  395.                         throw new OIDInfoException("Please supply an email address");
  396.                 }
  397.  
  398. //              $out  = "<!DOCTYPE oid-database>\n\n";
  399.                 $out  = '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
  400.                 $out .= '<oid-database xmlns="http://oid-info.com"'."\n";
  401.                 $out .= '              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'."\n";
  402.                 $out .= '              xsi:schemaLocation="http://oid-info.com '."\n";
  403.                 $out .= '                                  http://oid-info.com/oid.xsd">'."\n";
  404.                 $out .= "\t<submitter>\n";
  405.                 $out .= "\t\t<first-name>$firstName</first-name>\n";
  406.                 $out .= "\t\t<last-name>$lastName</last-name>\n";
  407.                 $out .= "\t\t<email>$email</email>\n";
  408.                 $out .= "\t</submitter>\n";
  409.  
  410.                 if (!self::eMailValid($email)) {
  411.                         throw new OIDInfoException("eMail address '$email' is invalid");
  412.                 }
  413.  
  414.                 return $out;
  415.         }
  416.  
  417.         public function xmlAddFooter() {
  418.                 return "</oid-database>\n";
  419.         }
  420.  
  421.         /*
  422.                 -- CODE TEMPLATE --
  423.  
  424.                 $params['allow_html'] = false; // Allow HTML in <description> and <information>
  425.                 $params['allow_illegal_email'] = true; // We should allow it, because we don't know if the user has some kind of human-readable anti-spam technique
  426.                 $params['soft_correct_behavior'] = OIDInfoAPI::SOFT_CORRECT_BEHAVIOR_NONE;
  427.                 $params['do_online_check'] = false; // Flag to disable this online check, because it generates a lot of traffic and runtime.
  428.                 $params['do_illegality_check'] = true;
  429.                 $params['do_simpleping_check'] = true;
  430.                 $params['auto_extract_name'] = '';
  431.                 $params['auto_extract_url'] = '';
  432.                 $params['always_output_comment'] = false; // Also output comment if there was an error (e.g. OID already existing)
  433.                 $params['creation_allowed_check'] = true;
  434.                 $params['tolerant_htmlentities'] = true;
  435.                 $params['ignore_xhtml_light'] = false;
  436.  
  437.                 $elements['synonymous-identifier'] = ''; // string or array
  438.                 $elements['description'] = '';
  439.                 $elements['information'] = '';
  440.  
  441.                 $elements['first-registrant']['first-name'] = '';
  442.                 $elements['first-registrant']['last-name'] = '';
  443.                 $elements['first-registrant']['address'] = '';
  444.                 $elements['first-registrant']['email'] = '';
  445.                 $elements['first-registrant']['phone'] = '';
  446.                 $elements['first-registrant']['fax'] = '';
  447.                 $elements['first-registrant']['creation-date'] = '';
  448.  
  449.                 $elements['current-registrant']['first-name'] = '';
  450.                 $elements['current-registrant']['last-name'] = '';
  451.                 $elements['current-registrant']['address'] = '';
  452.                 $elements['current-registrant']['email'] = '';
  453.                 $elements['current-registrant']['phone'] = '';
  454.                 $elements['current-registrant']['fax'] = '';
  455.                 $elements['current-registrant']['modification-date'] = '';
  456.  
  457.                 $oid = '1.2.3';
  458.  
  459.                 $comment = 'test';
  460.  
  461.                 echo $oa->createXMLEntry($oid, $elements, $params, $comment);
  462.         */
  463.         public function createXMLEntry($oid, $elements, $params, $comment='') {
  464.                 // Backward compatibility
  465.                 if (!isset($params['do_csv_check']))           $params['do_simpleping_check'] = true;
  466.  
  467.                 // Set default behavior
  468.                 if (!isset($params['allow_html']))             $params['allow_html'] = false; // Allow HTML in <description> and <information>
  469.                 if (!isset($params['allow_illegal_email']))    $params['allow_illegal_email'] = true; // We should allow it, because we don't know if the user has some kind of human-readable anti-spam technique
  470.                 if (!isset($params['soft_correct_behavior']))  $params['soft_correct_behavior'] = self::SOFT_CORRECT_BEHAVIOR_NONE;
  471.                 if (!isset($params['do_online_check']))        $params['do_online_check'] = false; // Flag to disable this online check, because it generates a lot of traffic and runtime.
  472.                 if (!isset($params['do_illegality_check']))    $params['do_illegality_check'] = true;
  473.                 if (!isset($params['do_simpleping_check']))    $params['do_simpleping_check'] = true;
  474.                 if (!isset($params['auto_extract_name']))      $params['auto_extract_name'] = '';
  475.                 if (!isset($params['auto_extract_url']))       $params['auto_extract_url'] = '';
  476.                 if (!isset($params['always_output_comment']))  $params['always_output_comment'] = false; // Also output comment if there was an error (e.g. OID already existing)
  477.                 if (!isset($params['creation_allowed_check'])) $params['creation_allowed_check'] = true;
  478.                 if (!isset($params['tolerant_htmlentities']))  $params['tolerant_htmlentities'] = true;
  479.                 if (!isset($params['ignore_xhtml_light']))     $params['ignore_xhtml_light'] = false;
  480.  
  481.                 $out = '';
  482.                 if (!empty($comment)) $out .= "\t\t<!-- $comment -->\n";
  483.  
  484.                 if ($params['always_output_comment']) {
  485.                         $err = $out;
  486.                 } else {
  487.                         $err = false;
  488.                 }
  489.  
  490.                 if (isset($elements['dotted_oid'])) {
  491.                         throw new OIDInfoException("'dotted_oid' in the \$elements array is not supported. Please use the \$oid argument.");
  492.                 }
  493.                 if (isset($elements['value'])) {
  494.                         // TODO: WHAT SHOULD WE DO WITH THAT?
  495.                         throw new OIDInfoException("'value' in the \$elements array is currently not supported.");
  496.                 }
  497.  
  498.                 $bak_oid = $oid;
  499.                 $oid = self::trySanitizeOID($oid);
  500.                 if ($oid === false) {
  501.                         $out .= "\t\t<!-- Ignored '$bak_oid', because it is not a valid OID -->\n";
  502.                         return false;
  503.                 }
  504.  
  505.                 if ($params['creation_allowed_check']) {
  506.                         if (!$this->oidMayCreate($oid, $params['do_online_check'], $params['do_simpleping_check'], $params['do_illegality_check'])) return $err;
  507.                 }
  508.  
  509.                 $elements['description'] = $this->correctDesc($elements['description'], $params, self::OIDINFO_CORRECT_DESC_DISALLOW_ENDING_DOT, true);
  510.                 $elements['information'] = $this->correctDesc($elements['information'], $params, self::OIDINFO_CORRECT_DESC_ENFORCE_ENDING_DOT, true);
  511.  
  512.                 if ($params['auto_extract_name'] || $params['auto_extract_url']) {
  513.                         if (!empty($elements['information'])) $elements['information'] .= '<br /><br />';
  514.                         if ($params['auto_extract_name'] || $params['auto_extract_url']) {
  515.                                 $elements['information'] .= 'Automatically extracted from <a href="'.$params['auto_extract_url'].'">'.$params['auto_extract_name'].'</a>.';
  516.                         } else if ($params['auto_extract_name']) {
  517.                                 $elements['information'] .= 'Automatically extracted from '.$params['auto_extract_name'];
  518.                         } else if ($params['auto_extract_url']) {
  519.                                 $hr_url = $params['auto_extract_url'];
  520.                                 // $hr_url = preg_replace('@^https{0,1}://@ismU', '', $hr_url);
  521.                                 $hr_url = preg_replace('@^http://@ismU', '', $hr_url);
  522.                                 $elements['information'] .= 'Automatically extracted from <a href="'.$params['auto_extract_url'].'">'.$hr_url.'</a>.';
  523.                         }
  524.                 }
  525.  
  526.                 // Validate ASN.1 ID
  527.                 if (isset($elements['synonymous-identifier'])) {
  528.                         if (!is_array($elements['synonymous-identifier'])) {
  529.                                 $elements['synonymous-identifier'] = array($elements['synonymous-identifier']);
  530.                         }
  531.                         foreach ($elements['synonymous-identifier'] as &$synid) {
  532.                                 if ($synid == '') {
  533.                                         $synid = null;
  534.                                         continue;
  535.                                 }
  536.  
  537.                                 $behavior = $params['soft_correct_behavior'];
  538.  
  539.                                 if ($behavior == self::SOFT_CORRECT_BEHAVIOR_NONE) {
  540.                                         if (!oid_id_is_valid($synid)) $synid = null;
  541.                                 } else if ($behavior == self::SOFT_CORRECT_BEHAVIOR_LOWERCASE_BEGINNING) {
  542.                                         $synid[0] = strtolower($synid[0]);
  543.                                         if (!oid_id_is_valid($synid)) $synid = null;
  544.                                 } else if ($behavior == self::SOFT_CORRECT_BEHAVIOR_ALL_POSSIBLE) {
  545.                                         $synid = oid_soft_correct_id($synid);
  546.                                         // if (!oid_id_is_valid($synid)) $synid = null;
  547.                                 } else {
  548.                                         throw new OIDInfoException("Unexpected soft-correction behavior for ASN.1 IDs");
  549.                                 }
  550.                         }
  551.                 }
  552.  
  553.                 // ATTENTION: the XML-generator will always add <dotted-oid> , but what will happen if additionally an
  554.                 // asn1-path (<value>) is given? (the resulting OIDs might be inconsistent/mismatch)
  555.                 if (isset($elements['value']) && (!asn1_path_valid($elements['value']))) {
  556.                         unset($elements['value']);
  557.                 }
  558.  
  559.                 // Validate IRI (currently not supported by oid-info.com, but the tag name is reserved)
  560.                 if (isset($elements['iri'])) {
  561.                         if (!is_array($elements['iri'])) {
  562.                                 $elements['iri'] = array($elements['iri']);
  563.                         }
  564.                         foreach ($elements['iri'] as &$iri) {
  565.                                 // Numeric-only nicht erlauben. Das wäre ja nur in einem IRI-Pfad gültig, aber nicht als einzelner Identifier
  566.                                 if (!iri_arc_valid($iri, false)) $iri = null;
  567.                         }
  568.                 }
  569.  
  570.                 if (isset($elements['first-registrant']['phone']))
  571.                 $elements['first-registrant']['phone']   = $this->softCorrectPhone($elements['first-registrant']['phone'], $params);
  572.  
  573.                 if (isset($elements['current-registrant']['phone']))
  574.                 $elements['current-registrant']['phone'] = $this->softCorrectPhone($elements['current-registrant']['phone'], $params);
  575.  
  576.                 if (isset($elements['first-registrant']['fax']))
  577.                 $elements['first-registrant']['fax']     = $this->softCorrectPhone($elements['first-registrant']['fax'], $params);
  578.  
  579.                 if (isset($elements['current-registrant']['fax']))
  580.                 $elements['current-registrant']['fax']   = $this->softCorrectPhone($elements['current-registrant']['fax'], $params);
  581.  
  582.                 if (isset($elements['first-registrant']['email']))
  583.                 $elements['first-registrant']['email']   = $this->softCorrectEMail($elements['first-registrant']['email'], $params);
  584.  
  585.                 if (isset($elements['current-registrant']['email']))
  586.                 $elements['current-registrant']['email'] = $this->softCorrectEMail($elements['current-registrant']['email'], $params);
  587.  
  588.                 // TODO: if name is empty, but address has 1 line, take it as firstname (but remove hyperlink)
  589.  
  590.                 $out_loc = '';
  591.                 foreach ($elements as $name => $val) {
  592.                         if (($name == 'first-registrant') || ($name == 'current-registrant')) {
  593.                                 $out_loc2 = '';
  594.                                 foreach ($val as $name2 => $val2) {
  595.                                         if (is_null($val2)) continue;
  596.                                         if (empty($val2)) continue;
  597.  
  598.                                         if (!is_array($val2)) $val2 = array($val2);
  599.  
  600.                                         foreach ($val2 as $val3) {
  601.                                                 // if (is_null($val3)) continue;
  602.                                                 if (empty($val3)) continue;
  603.  
  604.                                                 if ($name2 == 'address') {
  605.                                                         // $val3 = htmlentities_numeric($val3);
  606.                                                         $val3 = $this->correctDesc($val3, $params, self::OIDINFO_CORRECT_DESC_DISALLOW_ENDING_DOT, true);
  607.                                                 } else {
  608.                                                         // $val3 = htmlentities_numeric($val3);
  609.                                                         $val3 = $this->correctDesc($val3, $params, self::OIDINFO_CORRECT_DESC_DISALLOW_ENDING_DOT, false);
  610.                                                 }
  611.                                                 $out_loc2 .= "\t\t\t<$name2>".$val3."</$name2>\n";
  612.                                         }
  613.                                 }
  614.  
  615.                                 if (!empty($out_loc2)) {
  616.                                         $out_loc .= "\t\t<$name>\n";
  617.                                         $out_loc .= $out_loc2;
  618.                                         $out_loc .= "\t\t</$name>\n";
  619.                                 }
  620.                         } else {
  621.                                 // if (is_null($val)) continue;
  622.                                 if (empty($val) && ($name != 'description')) continue; // description is mandatory, according to http://oid-info.com/oid.xsd
  623.  
  624.                                 if (!is_array($val)) $val = array($val);
  625.  
  626.                                 foreach ($val as $val2) {
  627.                                         // if (is_null($val2)) continue;
  628.                                         if (empty($val2) && ($name != 'description')) continue; // description is mandatory, according to http://oid-info.com/oid.xsd
  629.  
  630.                                         if (($name != 'description') && ($name != 'information')) { // don't correctDesc description/information, because we already did it above.
  631.                                                 // $val2 = htmlentities_numeric($val2);
  632.                                                 $val2 = $this->correctDesc($val2, $params, self::OIDINFO_CORRECT_DESC_OPTIONAL_ENDING_DOT, false);
  633.                                         }
  634.                                         $out_loc .= "\t\t<$name>".$val2."</$name>\n";
  635.                                 }
  636.                         }
  637.                 }
  638.  
  639.                 if (!empty($out)) {
  640.                         $out = "\t<oid>\n"."\t\t".trim($out)."\n";
  641.                 } else {
  642.                         $out = "\t<oid>\n";
  643.                 }
  644.                 $out .= "\t\t<dot-notation>$oid</dot-notation>\n";
  645.                 $out .= $out_loc;
  646.                 $out .= "\t</oid>\n";
  647.  
  648.                 return $out;
  649.         }
  650.  
  651.         # --- PART 4: Offline check if OIDs are illegal
  652.  
  653.         protected $illegality_rules = array();
  654.  
  655.         public function clearIllegalityRules() {
  656.                 $this->illegality_rules = array();
  657.         }
  658.  
  659.         public function loadIllegalityRuleFile($file) {
  660.                 if (!file_exists($file)) {
  661.                         throw new OIDInfoException("Error: File '$file' does not exist");
  662.                 }
  663.  
  664.                 $lines = file($file);
  665.  
  666.                 if ($lines === false) {
  667.                         throw new OIDInfoException("Error: Could not load '$file'");
  668.                 }
  669.  
  670.                 $signature = trim(array_shift($lines));
  671.                 if (($signature != '[1.3.6.1.4.1.37476.3.1.5.1]') && ($signature != '[1.3.6.1.4.1.37476.3.1.5.2]')) {
  672.                         throw new OIDInfoException("'$file' does not seem to a valid illegality rule file (file format OID does not match. Signature $signature unexpected)");
  673.                 }
  674.  
  675.                 foreach ($lines as $line) {
  676.                         // Remove comments
  677.                         $ary  = explode('--', $line);
  678.                         $rule = trim($ary[0]);
  679.  
  680.                         if ($rule !== '') $this->addIllegalityRule($rule);
  681.                 }
  682.         }
  683.  
  684.         public function addIllegalityRule($rule) {
  685.                 $test = $rule;
  686.                 $test = preg_replace('@\\.\\(!\\d+\\)@ismU', '.0', $test); // added in ver 2
  687.                 $test = preg_replace('@\\.\\(\\d+\\+\\)@ismU', '.0', $test);
  688.                 $test = preg_replace('@\\.\\(\\d+\\-\\)@ismU', '.0', $test);
  689.                 $test = preg_replace('@\\.\\(\\d+\\-\\d+\\)@ismU', '.0', $test);
  690.                 $test = preg_replace('@\\.\\*@ismU', '.0', $test);
  691.  
  692.                 if (!oid_valid_dotnotation($test, false, false, 1)) {
  693.                         throw new OIDInfoException("Illegal illegality rule '$rule'.");
  694.                 }
  695.  
  696.                 $this->illegality_rules[] = $rule;
  697.         }
  698.  
  699.         public function illegalOID($oid, &$illegal_root='') {
  700.                 $bak = $oid;
  701.                 $oid = self::trySanitizeOID($oid);
  702.                 if ($oid === false) {
  703.                         $illegal_root = $bak;
  704.                         return true; // is illegal
  705.                 }
  706.  
  707.                 $rules = $this->illegality_rules;
  708.  
  709.                 foreach ($rules as $rule) {
  710.                         $rule = str_replace(array('(', ')'), '', $rule);
  711.  
  712.                         $oarr = explode('.', $oid);
  713.                         $rarr = explode('.', $rule);
  714.  
  715.                         if (count($oarr) < count($rarr)) continue;
  716.  
  717.                         $rulefit = true;
  718.  
  719.                         $illrootary = array();
  720.  
  721.                         $vararcs = 0;
  722.                         $varsfit = 0;
  723.                         for ($i=0; $i<count($rarr); $i++) {
  724.                                 $oelem = $oarr[$i];
  725.                                 $relem = $rarr[$i];
  726.  
  727.                                 $illrootary[] = $oelem;
  728.  
  729.                                 if ($relem == '*') $relem = '0+';
  730.  
  731.                                 $startchar = substr($relem, 0, 1);
  732.                                 $endchar = substr($relem, -1, 1);
  733.                                 if ($startchar == '!') { // added in ver 2
  734.                                         $vararcs++;
  735.                                         $relem = substr($relem, 1, strlen($relem)-1); // cut away first char
  736.                                         if ($oelem != $relem) $varsfit++;
  737.                                 } else if ($endchar == '+') {
  738.                                         $vararcs++;
  739.                                         $relem = substr($relem, 0, strlen($relem)-1); // cut away last char
  740.                                         if ($oelem >= $relem) $varsfit++;
  741.                                 } else if ($endchar == '-') {
  742.                                         $vararcs++;
  743.                                         $relem = substr($relem, 0, strlen($relem)-1); // cut away last char
  744.                                         if ($oelem <= $relem) $varsfit++;
  745.                                 } else if (strpos($relem, '-') !== false) {
  746.                                         $vararcs++;
  747.                                         $limarr = explode('-', $relem);
  748.                                         $limmin = $limarr[0];
  749.                                         $limmax = $limarr[1];
  750.                                         if (($oelem >= $limmin) && ($oelem <= $limmax)) $varsfit++;
  751.                                 } else {
  752.                                         if ($relem != $oelem) {
  753.                                                 $rulefit = false;
  754.                                                 break;
  755.                                         }
  756.                                 }
  757.                         }
  758.  
  759.                         if ($rulefit && ($vararcs == $varsfit)) {
  760.                                 $illegal_root = implode('.', $illrootary);
  761.                                 return true; // is illegal
  762.                         }
  763.                 }
  764.  
  765.                 $illegal_root = '';
  766.                 return false; // not illegal
  767.         }
  768.  
  769.         # --- PART 5: Misc functions
  770.  
  771.         function __construct() {
  772.                 if (file_exists(self::DEFAULT_ILLEGALITY_RULE_FILE)) {
  773.                         $this->loadIllegalityRuleFile(self::DEFAULT_ILLEGALITY_RULE_FILE);
  774.                 }
  775.         }
  776.  
  777.         public static function getPublicURL($oid) {
  778.                 return "http://oid-info.com/get/$oid";
  779.         }
  780.  
  781.         public function oidExisting($oid, $onlineCheck=true, $useSimplePingProvider=true) {
  782.                 $bak_oid = $oid;
  783.                 $oid = self::trySanitizeOID($oid);
  784.                 if ($oid === false) {
  785.                         throw new OIDInfoException("'$bak_oid' is not a valid OID");
  786.                 }
  787.  
  788.                 $canuseSimplePingProvider = $useSimplePingProvider && $this->simplePingProviderAvailable();
  789.                 if ($canuseSimplePingProvider) {
  790.                         if ($this->simplePingProviderCheckOID($oid)) return true;
  791.                 }
  792.                 if ($onlineCheck) {
  793.                         return $this->checkOnlineExists($oid);
  794.                 }
  795.                 if ((!$canuseSimplePingProvider) && (!$onlineCheck)) {
  796.                         throw new OIDInfoException("No simple or verbose checking method chosen/available");
  797.                 }
  798.                 return false;
  799.         }
  800.  
  801.         public function oidMayCreate($oid, $onlineCheck=true, $useSimplePingProvider=true, $illegalityCheck=true) {
  802.                 $bak_oid = $oid;
  803.                 $oid = self::trySanitizeOID($oid);
  804.                 if ($oid === false) {
  805.                         throw new OIDInfoException("'$bak_oid' is not a valid OID");
  806.                 }
  807.  
  808.                 if ($illegalityCheck && $this->illegalOID($oid)) return false;
  809.  
  810.                 $canuseSimplePingProvider = $useSimplePingProvider && $this->simplePingProviderAvailable();
  811.                 if ($canuseSimplePingProvider) {
  812.                         if ($this->simplePingProviderCheckOID($oid)) return false;
  813.                 }
  814.                 if ($onlineCheck) {
  815.                         return $this->checkOnlineMayCreate($oid);
  816.                 }
  817.                 if ((!$canuseSimplePingProvider) && (!$onlineCheck)) {
  818.                         throw new OIDInfoException("No simple or verbose checking method chosen/available");
  819.                 }
  820.                 return true;
  821.         }
  822.  
  823.         # --- PART 6: Simple Ping Providers
  824.         # TODO: Question ... can't these provider concepts (SPP and VPP) not somehow be combined?
  825.  
  826.         protected $simplePingProviders = array();
  827.  
  828.         public function addSimplePingProvider($addr) {
  829.                 if (!isset($this->simplePingProviders[$addr])) {
  830.                         if (strtolower(substr($addr, -4, 4)) == '.csv') {
  831.                                 $this->simplePingProviders[$addr] = new CSVSimplePingProvider($addr);
  832.                         } else {
  833.                                 $this->simplePingProviders[$addr] = new OIDSimplePingProvider($addr);
  834.                                 // $this->simplePingProviders[$addr]->connect();
  835.                         }
  836.                 }
  837.                 return $this->simplePingProviders[$addr];
  838.         }
  839.  
  840.         public function removeSimplePingProvider($addr) {
  841.                 $this->simplePingProviders[$addr]->disconnect();
  842.                 unset($this->simplePingProviders[$addr]);
  843.         }
  844.  
  845.         public function removeAllSimplePingProviders() {
  846.                 foreach ($this->simplePingProviders as $addr => $obj) {
  847.                         $this->removeSimplePingProvider($addr);
  848.                 }
  849.         }
  850.  
  851.         public function listSimplePingProviders() {
  852.                 $out = array();
  853.                 foreach ($this->simplePingProviders as $addr => $obj) {
  854.                         $out[] = $addr;
  855.                 }
  856.                 return $out;
  857.         }
  858.  
  859.         public function simplePingProviderCheckOID($oid) {
  860.                 if (!$this->simplePingProviderAvailable()) {
  861.                         throw new OIDInfoException("No simple ping providers available.");
  862.                 }
  863.  
  864.                 $one_null = false;
  865.                 foreach ($this->simplePingProviders as $addr => $obj) {
  866.                         $res = $obj->queryOID($oid);
  867.                         if ($res) return true;
  868.                         if ($res !== false) $one_null = true;
  869.                 }
  870.  
  871.                 return $one_null ? null : false;
  872.         }
  873.  
  874.         public function simplePingProviderAvailable() {
  875.                 return count($this->simplePingProviders) >= 1;
  876.         }
  877.  
  878. }
  879.  
  880. interface IOIDSimplePingProvider {
  881.         public function queryOID($oid);
  882.         public function disconnect();
  883.         public function connect();
  884. }
  885.  
  886. class CSVSimplePingProvider implements IOIDSimplePingProvider {
  887.         protected $csvfile = '';
  888.         protected $lines = array();
  889.         protected $filemtime = 0;
  890.  
  891.         public function queryOID($oid) {
  892.                 $this->reloadCSV();
  893.                 return in_array($oid, $this->lines);
  894.         }
  895.  
  896.         public function disconnect() {
  897.                 // Nothing
  898.         }
  899.  
  900.         public function connect() {
  901.                 // Nothing
  902.         }
  903.  
  904.         // TODO: This cannot handle big CSVs. We need to introduce the old code of "2016-09-02_old_oidinfo_api_with_csv_reader.zip" here.
  905.         protected function reloadCSV() {
  906.                 if (!file_exists($this->csvfile)) {
  907.                         throw new OIDInfoException("File '".$this->csvfile."' does not exist");
  908.                 }
  909.                 $filemtime = filemtime($this->csvfile);
  910.                 if ($filemtime != $this->filemtime) {
  911.                         $this->lines = file($csvfile);
  912.                         $this->filemtime = $filemtime;
  913.                 }
  914.         }
  915.  
  916.         function __construct($csvfile) {
  917.                 $this->csvfile = $csvfile;
  918.                 $this->reloadCSV();
  919.         }
  920. }
  921.  
  922.  
  923. class OIDSimplePingProvider implements IOIDSimplePingProvider {
  924.         protected $addr = '';
  925.         protected $connected = false;
  926.         protected $socket = null;
  927.  
  928.         const SPP_MAX_CONNECTION_ATTEMPTS = 3; // TODO: Auslagern in OIDInfoAPI Klasse...?
  929.  
  930.         const DEFAULT_PORT = 49500;
  931.  
  932.         protected function spp_reader_init() {
  933.                 $this->spp_reader_uninit();
  934.  
  935.                 $ary = explode(':', $this->addr);
  936.                 $host = $ary[0];
  937.                 $service_port = isset($ary[1]) ? $ary[1] : self::DEFAULT_PORT;
  938.                 $address = @gethostbyname($host);
  939.                 if ($address === false) {
  940.                         echo "gethostbyname() failed.\n"; // TODO: exceptions? (Auch alle "echos" darunter)
  941.                         return false;
  942.                 }
  943.                 $this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  944.                 if ($this->socket === false) {
  945.                         echo "socket_create() failed: " . socket_strerror(socket_last_error()) . "\n";
  946.                         return false;
  947.                 }
  948.                 $result = @socket_connect($this->socket, $address, $service_port);
  949.                 if ($result === false) {
  950.                         echo "socket_connect() failed: " . socket_strerror(socket_last_error($this->socket)) . "\n";
  951.                         return false;
  952.                 }
  953.  
  954.                 $this->connected = true;
  955.         }
  956.  
  957.         protected function spp_reader_avail($oid, $failcount=0) {
  958.                 $in = "${oid}\n\0"; // PHP's socket_send() does not send a trailing \n . There needs to be something after the \n ... :(
  959.  
  960.                 if ($failcount >= self::SPP_MAX_CONNECTION_ATTEMPTS) {
  961.                         echo "Query $oid: CONNECTION FAILED!\n";
  962.                         return null;
  963.                 }
  964.  
  965.                 if (!$this->connected) {
  966.                         $this->spp_reader_init();
  967.                 }
  968.  
  969.                 $s = @socket_send($this->socket, $in, strlen($in), 0);
  970.                 if ($s != strlen($in)) {
  971.                         // echo "Query $oid: Sending failed\n";
  972.                         $this->spp_reader_init();
  973.                         if (!$this->socket) return null;
  974.                         return $this->spp_reader_avail($oid, $failcount+1);
  975.                 }
  976.  
  977.                 $out = @socket_read($this->socket, 2048);
  978.                 if (trim($out) == '1') {
  979.                         return true;
  980.                 } else if (trim($out) == '0') {
  981.                         return false;
  982.                 } else {
  983.                         // echo "Query $oid: Receiving failed\n";
  984.                         $this->spp_reader_init();
  985.                         if (!$this->socket) return null;
  986.                         return $this->spp_reader_avail($oid, $failcount+1);
  987.                 }
  988.         }
  989.  
  990.         protected function spp_reader_uninit() {
  991.                 if (!$this->connected) return;
  992.                 @socket_close($this->socket);
  993.                 $this->connected = false;
  994.         }
  995.  
  996.         public function queryOID($oid) {
  997.                 if (trim($oid) === 'bye') return null;
  998.                 return $this->spp_reader_avail($oid);
  999.         }
  1000.  
  1001.         public function disconnect() {
  1002.                 return $this->spp_reader_uninit();
  1003.         }
  1004.  
  1005.         public function connect() {
  1006.                 return $this->spp_reader_init();
  1007.         }
  1008.  
  1009.         function __construct($addr='localhost:49500') {
  1010.                 $this->addr = $addr;
  1011.         }
  1012.  
  1013. }
  1014.