Subversion Repositories oidplus

Rev

Rev 1043 | Rev 1132 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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