Subversion Repositories oidinfo_api

Rev

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