Subversion Repositories oidinfo_api

Rev

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

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