Subversion Repositories oidplus

Rev

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

Rev Author Line No. Line
139 daniel-mar 1
<?php
2
 
3
/**
4
 * OID-Info.com API by Daniel Marschall, ViaThinkSoft
5
 * License terms: Apache 2.0
181 daniel-mar 6
 * Revision: 2019-08-26
139 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';
161 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';
139 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
 
182 daniel-mar 513
                // Request by O.D. 26 August 2019
514
                $elements['description'] = trim($elements['description']);
515
                if (preg_match('@^[a-z]@', $elements['description'], $m)) {
516
                        if (($ending_dot_policy != self::OIDINFO_CORRECT_DESC_ENFORCE_ENDING_DOT) && (strpos($elements['description'], ' ') === false)) { // <-- added by DM
517
                                $elements['description'] = '"' . $elements['description'] . '"';
518
                        }
519
                }
520
                // End request by O.D. 26. August 2019
521
 
139 daniel-mar 522
                if ($params['auto_extract_name'] || $params['auto_extract_url']) {
523
                        if (!empty($elements['information'])) $elements['information'] .= '<br /><br />';
524
                        if ($params['auto_extract_name'] || $params['auto_extract_url']) {
525
                                $elements['information'] .= 'Automatically extracted from <a href="'.$params['auto_extract_url'].'">'.$params['auto_extract_name'].'</a>.';
526
                        } else if ($params['auto_extract_name']) {
527
                                $elements['information'] .= 'Automatically extracted from '.$params['auto_extract_name'];
528
                        } else if ($params['auto_extract_url']) {
529
                                $hr_url = $params['auto_extract_url'];
530
                                // $hr_url = preg_replace('@^https{0,1}://@ismU', '', $hr_url);
531
                                $hr_url = preg_replace('@^http://@ismU', '', $hr_url);
532
                                $elements['information'] .= 'Automatically extracted from <a href="'.$params['auto_extract_url'].'">'.$hr_url.'</a>.';
533
                        }
534
                }
535
 
536
                // Validate ASN.1 ID
537
                if (isset($elements['synonymous-identifier'])) {
538
                        if (!is_array($elements['synonymous-identifier'])) {
539
                                $elements['synonymous-identifier'] = array($elements['synonymous-identifier']);
540
                        }
541
                        foreach ($elements['synonymous-identifier'] as &$synid) {
542
                                if ($synid == '') {
543
                                        $synid = null;
544
                                        continue;
545
                                }
546
 
547
                                $behavior = $params['soft_correct_behavior'];
548
 
549
                                if ($behavior == self::SOFT_CORRECT_BEHAVIOR_NONE) {
550
                                        if (!oid_id_is_valid($synid)) $synid = null;
551
                                } else if ($behavior == self::SOFT_CORRECT_BEHAVIOR_LOWERCASE_BEGINNING) {
552
                                        $synid[0] = strtolower($synid[0]);
553
                                        if (!oid_id_is_valid($synid)) $synid = null;
554
                                } else if ($behavior == self::SOFT_CORRECT_BEHAVIOR_ALL_POSSIBLE) {
555
                                        $synid = oid_soft_correct_id($synid);
556
                                        // if (!oid_id_is_valid($synid)) $synid = null;
557
                                } else {
558
                                        throw new OIDInfoException("Unexpected soft-correction behavior for ASN.1 IDs");
559
                                }
560
                        }
561
                }
562
 
563
                // ATTENTION: the XML-generator will always add <dotted-oid> , but what will happen if additionally an
564
                // asn1-path (<value>) is given? (the resulting OIDs might be inconsistent/mismatch)
565
                if (isset($elements['value']) && (!asn1_path_valid($elements['value']))) {
566
                        unset($elements['value']);
567
                }
568
 
569
                // Validate IRI (currently not supported by oid-info.com, but the tag name is reserved)
570
                if (isset($elements['iri'])) {
571
                        if (!is_array($elements['iri'])) {
572
                                $elements['iri'] = array($elements['iri']);
573
                        }
574
                        foreach ($elements['iri'] as &$iri) {
575
                                // Numeric-only nicht erlauben. Das wäre ja nur in einem IRI-Pfad gültig, aber nicht als einzelner Identifier
576
                                if (!iri_arc_valid($iri, false)) $iri = null;
577
                        }
578
                }
579
 
580
                if (isset($elements['first-registrant']['phone']))
581
                $elements['first-registrant']['phone']   = $this->softCorrectPhone($elements['first-registrant']['phone'], $params);
582
 
583
                if (isset($elements['current-registrant']['phone']))
584
                $elements['current-registrant']['phone'] = $this->softCorrectPhone($elements['current-registrant']['phone'], $params);
585
 
586
                if (isset($elements['first-registrant']['fax']))
587
                $elements['first-registrant']['fax']     = $this->softCorrectPhone($elements['first-registrant']['fax'], $params);
588
 
589
                if (isset($elements['current-registrant']['fax']))
590
                $elements['current-registrant']['fax']   = $this->softCorrectPhone($elements['current-registrant']['fax'], $params);
591
 
592
                if (isset($elements['first-registrant']['email']))
593
                $elements['first-registrant']['email']   = $this->softCorrectEMail($elements['first-registrant']['email'], $params);
594
 
595
                if (isset($elements['current-registrant']['email']))
596
                $elements['current-registrant']['email'] = $this->softCorrectEMail($elements['current-registrant']['email'], $params);
597
 
598
                // TODO: if name is empty, but address has 1 line, take it as firstname (but remove hyperlink)
599
 
600
                $out_loc = '';
601
                foreach ($elements as $name => $val) {
602
                        if (($name == 'first-registrant') || ($name == 'current-registrant')) {
603
                                $out_loc2 = '';
604
                                foreach ($val as $name2 => $val2) {
605
                                        if (is_null($val2)) continue;
606
                                        if (empty($val2)) continue;
607
 
608
                                        if (!is_array($val2)) $val2 = array($val2);
609
 
610
                                        foreach ($val2 as $val3) {
611
                                                // if (is_null($val3)) continue;
612
                                                if (empty($val3)) continue;
613
 
614
                                                if ($name2 == 'address') {
615
                                                        // $val3 = htmlentities_numeric($val3);
616
                                                        $val3 = $this->correctDesc($val3, $params, self::OIDINFO_CORRECT_DESC_DISALLOW_ENDING_DOT, true);
617
                                                } else {
618
                                                        // $val3 = htmlentities_numeric($val3);
619
                                                        $val3 = $this->correctDesc($val3, $params, self::OIDINFO_CORRECT_DESC_DISALLOW_ENDING_DOT, false);
620
                                                }
621
                                                $out_loc2 .= "\t\t\t<$name2>".$val3."</$name2>\n";
622
                                        }
623
                                }
624
 
625
                                if (!empty($out_loc2)) {
626
                                        $out_loc .= "\t\t<$name>\n";
627
                                        $out_loc .= $out_loc2;
628
                                        $out_loc .= "\t\t</$name>\n";
629
                                }
630
                        } else {
631
                                // if (is_null($val)) continue;
632
                                if (empty($val) && ($name != 'description')) continue; // description is mandatory, according to http://oid-info.com/oid.xsd
633
 
634
                                if (!is_array($val)) $val = array($val);
635
 
636
                                foreach ($val as $val2) {
637
                                        // if (is_null($val2)) continue;
638
                                        if (empty($val2) && ($name != 'description')) continue; // description is mandatory, according to http://oid-info.com/oid.xsd
639
 
640
                                        if (($name != 'description') && ($name != 'information')) { // don't correctDesc description/information, because we already did it above.
641
                                                // $val2 = htmlentities_numeric($val2);
642
                                                $val2 = $this->correctDesc($val2, $params, self::OIDINFO_CORRECT_DESC_OPTIONAL_ENDING_DOT, false);
643
                                        }
644
                                        $out_loc .= "\t\t<$name>".$val2."</$name>\n";
645
                                }
646
                        }
647
                }
648
 
649
                if (!empty($out)) {
650
                        $out = "\t<oid>\n"."\t\t".trim($out)."\n";
651
                } else {
652
                        $out = "\t<oid>\n";
653
                }
654
                $out .= "\t\t<dot-notation>$oid</dot-notation>\n";
655
                $out .= $out_loc;
656
                $out .= "\t</oid>\n";
657
 
658
                return $out;
659
        }
660
 
661
        # --- PART 4: Offline check if OIDs are illegal
662
 
663
        protected $illegality_rules = array();
664
 
665
        public function clearIllegalityRules() {
666
                $this->illegality_rules = array();
667
        }
668
 
669
        public function loadIllegalityRuleFile($file) {
670
                if (!file_exists($file)) {
671
                        throw new OIDInfoException("Error: File '$file' does not exist");
672
                }
673
 
674
                $lines = file($file);
675
 
676
                if ($lines === false) {
677
                        throw new OIDInfoException("Error: Could not load '$file'");
678
                }
679
 
680
                $signature = trim(array_shift($lines));
681
                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]')) {
682
                        throw new OIDInfoException("'$file' does not seem to a valid illegality rule file (file format OID does not match. Signature $signature unexpected)");
683
                }
684
 
685
                foreach ($lines as $line) {
686
                        // Remove comments
687
                        $ary  = explode('--', $line);
688
                        $rule = trim($ary[0]);
689
 
690
                        if ($rule !== '') $this->addIllegalityRule($rule);
691
                }
692
        }
693
 
694
        public function addIllegalityRule($rule) {
695
                $test = $rule;
696
                $test = preg_replace('@\\.\\(!\\d+\\)@ismU', '.0', $test); // added in ver 2
697
                $test = preg_replace('@\\.\\(\\d+\\+\\)@ismU', '.0', $test);
698
                $test = preg_replace('@\\.\\(\\d+\\-\\)@ismU', '.0', $test);
699
                $test = preg_replace('@\\.\\(\\d+\\-\\d+\\)@ismU', '.0', $test);
700
                $test = preg_replace('@\\.\\*@ismU', '.0', $test);
701
 
702
                if (!oid_valid_dotnotation($test, false, false, 1)) {
703
                        throw new OIDInfoException("Illegal illegality rule '$rule'.");
704
                }
705
 
706
                $this->illegality_rules[] = $rule;
707
        }
708
 
709
        public function illegalOID($oid, &$illegal_root='') {
710
                $bak = $oid;
711
                $oid = self::trySanitizeOID($oid);
712
                if ($oid === false) {
713
                        $illegal_root = $bak;
714
                        return true; // is illegal
715
                }
716
 
717
                $rules = $this->illegality_rules;
718
 
719
                foreach ($rules as $rule) {
720
                        $rule = str_replace(array('(', ')'), '', $rule);
721
 
722
                        $oarr = explode('.', $oid);
723
                        $rarr = explode('.', $rule);
724
 
725
                        if (count($oarr) < count($rarr)) continue;
726
 
727
                        $rulefit = true;
728
 
729
                        $illrootary = array();
730
 
731
                        $vararcs = 0;
732
                        $varsfit = 0;
733
                        for ($i=0; $i<count($rarr); $i++) {
734
                                $oelem = $oarr[$i];
735
                                $relem = $rarr[$i];
736
 
737
                                $illrootary[] = $oelem;
738
 
739
                                if ($relem == '*') $relem = '0+';
740
 
741
                                $startchar = substr($relem, 0, 1);
742
                                $endchar = substr($relem, -1, 1);
743
                                if ($startchar == '!') { // added in ver 2
744
                                        $vararcs++;
745
                                        $relem = substr($relem, 1, strlen($relem)-1); // cut away first char
746
                                        if ($oelem != $relem) $varsfit++;
747
                                } else if ($endchar == '+') {
748
                                        $vararcs++;
749
                                        $relem = substr($relem, 0, strlen($relem)-1); // cut away last char
750
                                        if ($oelem >= $relem) $varsfit++;
751
                                } else if ($endchar == '-') {
752
                                        $vararcs++;
753
                                        $relem = substr($relem, 0, strlen($relem)-1); // cut away last char
754
                                        if ($oelem <= $relem) $varsfit++;
755
                                } else if (strpos($relem, '-') !== false) {
756
                                        $vararcs++;
757
                                        $limarr = explode('-', $relem);
758
                                        $limmin = $limarr[0];
759
                                        $limmax = $limarr[1];
760
                                        if (($oelem >= $limmin) && ($oelem <= $limmax)) $varsfit++;
761
                                } else {
762
                                        if ($relem != $oelem) {
763
                                                $rulefit = false;
764
                                                break;
765
                                        }
766
                                }
767
                        }
768
 
769
                        if ($rulefit && ($vararcs == $varsfit)) {
770
                                $illegal_root = implode('.', $illrootary);
771
                                return true; // is illegal
772
                        }
773
                }
774
 
775
                $illegal_root = '';
776
                return false; // not illegal
777
        }
778
 
779
        # --- PART 5: Misc functions
780
 
781
        function __construct() {
782
                if (file_exists(self::DEFAULT_ILLEGALITY_RULE_FILE)) {
783
                        $this->loadIllegalityRuleFile(self::DEFAULT_ILLEGALITY_RULE_FILE);
784
                }
785
        }
786
 
787
        public static function getPublicURL($oid) {
788
                return "http://oid-info.com/get/$oid";
789
        }
790
 
791
        public function oidExisting($oid, $onlineCheck=true, $useSimplePingProvider=true) {
792
                $bak_oid = $oid;
793
                $oid = self::trySanitizeOID($oid);
794
                if ($oid === false) {
795
                        throw new OIDInfoException("'$bak_oid' is not a valid OID");
796
                }
797
 
798
                $canuseSimplePingProvider = $useSimplePingProvider && $this->simplePingProviderAvailable();
799
                if ($canuseSimplePingProvider) {
800
                        if ($this->simplePingProviderCheckOID($oid)) return true;
801
                }
802
                if ($onlineCheck) {
803
                        return $this->checkOnlineExists($oid);
804
                }
805
                if ((!$canuseSimplePingProvider) && (!$onlineCheck)) {
806
                        throw new OIDInfoException("No simple or verbose checking method chosen/available");
807
                }
808
                return false;
809
        }
810
 
811
        public function oidMayCreate($oid, $onlineCheck=true, $useSimplePingProvider=true, $illegalityCheck=true) {
812
                $bak_oid = $oid;
813
                $oid = self::trySanitizeOID($oid);
814
                if ($oid === false) {
815
                        throw new OIDInfoException("'$bak_oid' is not a valid OID");
816
                }
817
 
818
                if ($illegalityCheck && $this->illegalOID($oid)) return false;
819
 
820
                $canuseSimplePingProvider = $useSimplePingProvider && $this->simplePingProviderAvailable();
821
                if ($canuseSimplePingProvider) {
822
                        if ($this->simplePingProviderCheckOID($oid)) return false;
823
                }
824
                if ($onlineCheck) {
825
                        return $this->checkOnlineMayCreate($oid);
826
                }
827
                if ((!$canuseSimplePingProvider) && (!$onlineCheck)) {
828
                        throw new OIDInfoException("No simple or verbose checking method chosen/available");
829
                }
830
                return true;
831
        }
832
 
833
        # --- PART 6: Simple Ping Providers
834
        # TODO: Question ... can't these provider concepts (SPP and VPP) not somehow be combined?
835
 
836
        protected $simplePingProviders = array();
837
 
838
        public function addSimplePingProvider($addr) {
839
                if (!isset($this->simplePingProviders[$addr])) {
840
                        if (strtolower(substr($addr, -4, 4)) == '.csv') {
841
                                $this->simplePingProviders[$addr] = new CSVSimplePingProvider($addr);
842
                        } else {
843
                                $this->simplePingProviders[$addr] = new OIDSimplePingProvider($addr);
844
                                // $this->simplePingProviders[$addr]->connect();
845
                        }
846
                }
847
                return $this->simplePingProviders[$addr];
848
        }
849
 
850
        public function removeSimplePingProvider($addr) {
851
                $this->simplePingProviders[$addr]->disconnect();
852
                unset($this->simplePingProviders[$addr]);
853
        }
854
 
855
        public function removeAllSimplePingProviders() {
856
                foreach ($this->simplePingProviders as $addr => $obj) {
857
                        $this->removeSimplePingProvider($addr);
858
                }
859
        }
860
 
861
        public function listSimplePingProviders() {
862
                $out = array();
863
                foreach ($this->simplePingProviders as $addr => $obj) {
864
                        $out[] = $addr;
865
                }
866
                return $out;
867
        }
868
 
869
        public function simplePingProviderCheckOID($oid) {
870
                if (!$this->simplePingProviderAvailable()) {
871
                        throw new OIDInfoException("No simple ping providers available.");
872
                }
873
 
874
                $one_null = false;
875
                foreach ($this->simplePingProviders as $addr => $obj) {
876
                        $res = $obj->queryOID($oid);
877
                        if ($res) return true;
878
                        if ($res !== false) $one_null = true;
879
                }
880
 
881
                return $one_null ? null : false;
882
        }
883
 
884
        public function simplePingProviderAvailable() {
885
                return count($this->simplePingProviders) >= 1;
886
        }
887
 
888
}
889
 
890
interface IOIDSimplePingProvider {
891
        public function queryOID($oid);
892
        public function disconnect();
893
        public function connect();
894
}
895
 
896
class CSVSimplePingProvider implements IOIDSimplePingProvider {
897
        protected $csvfile = '';
898
        protected $lines = array();
899
        protected $filemtime = 0;
900
 
901
        public function queryOID($oid) {
902
                $this->reloadCSV();
903
                return in_array($oid, $this->lines);
904
        }
905
 
906
        public function disconnect() {
907
                // Nothing
908
        }
909
 
910
        public function connect() {
911
                // Nothing
912
        }
913
 
914
        // 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.
915
        protected function reloadCSV() {
916
                if (!file_exists($this->csvfile)) {
917
                        throw new OIDInfoException("File '".$this->csvfile."' does not exist");
918
                }
919
                $filemtime = filemtime($this->csvfile);
920
                if ($filemtime != $this->filemtime) {
921
                        $this->lines = file($csvfile);
922
                        $this->filemtime = $filemtime;
923
                }
924
        }
925
 
926
        function __construct($csvfile) {
927
                $this->csvfile = $csvfile;
928
                $this->reloadCSV();
929
        }
930
}
931
 
932
 
933
class OIDSimplePingProvider implements IOIDSimplePingProvider {
934
        protected $addr = '';
935
        protected $connected = false;
936
        protected $socket = null;
937
 
938
        const SPP_MAX_CONNECTION_ATTEMPTS = 3; // TODO: Auslagern in OIDInfoAPI Klasse...?
939
 
940
        const DEFAULT_PORT = 49500;
941
 
942
        protected function spp_reader_init() {
943
                $this->spp_reader_uninit();
944
 
945
                $ary = explode(':', $this->addr);
946
                $host = $ary[0];
947
                $service_port = isset($ary[1]) ? $ary[1] : self::DEFAULT_PORT;
948
                $address = @gethostbyname($host);
949
                if ($address === false) {
950
                        echo "gethostbyname() failed.\n"; // TODO: exceptions? (Auch alle "echos" darunter)
951
                        return false;
952
                }
953
                $this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
954
                if ($this->socket === false) {
955
                        echo "socket_create() failed: " . socket_strerror(socket_last_error()) . "\n";
956
                        return false;
957
                }
958
                $result = @socket_connect($this->socket, $address, $service_port);
959
                if ($result === false) {
960
                        echo "socket_connect() failed: " . socket_strerror(socket_last_error($this->socket)) . "\n";
961
                        return false;
962
                }
963
 
964
                $this->connected = true;
965
        }
966
 
967
        protected function spp_reader_avail($oid, $failcount=0) {
968
                $in = "${oid}\n\0"; // PHP's socket_send() does not send a trailing \n . There needs to be something after the \n ... :(
969
 
970
                if ($failcount >= self::SPP_MAX_CONNECTION_ATTEMPTS) {
971
                        echo "Query $oid: CONNECTION FAILED!\n";
972
                        return null;
973
                }
974
 
975
                if (!$this->connected) {
976
                        $this->spp_reader_init();
977
                }
978
 
979
                $s = @socket_send($this->socket, $in, strlen($in), 0);
980
                if ($s != strlen($in)) {
981
                        // echo "Query $oid: Sending failed\n";
982
                        $this->spp_reader_init();
983
                        if (!$this->socket) return null;
984
                        return $this->spp_reader_avail($oid, $failcount+1);
985
                }
986
 
987
                $out = @socket_read($this->socket, 2048);
988
                if (trim($out) == '1') {
989
                        return true;
990
                } else if (trim($out) == '0') {
991
                        return false;
992
                } else {
993
                        // echo "Query $oid: Receiving failed\n";
994
                        $this->spp_reader_init();
995
                        if (!$this->socket) return null;
996
                        return $this->spp_reader_avail($oid, $failcount+1);
997
                }
998
        }
999
 
1000
        protected function spp_reader_uninit() {
1001
                if (!$this->connected) return;
1002
                @socket_close($this->socket);
1003
                $this->connected = false;
1004
        }
1005
 
1006
        public function queryOID($oid) {
1007
                if (trim($oid) === 'bye') return null;
1008
                return $this->spp_reader_avail($oid);
1009
        }
1010
 
1011
        public function disconnect() {
1012
                return $this->spp_reader_uninit();
1013
        }
1014
 
1015
        public function connect() {
1016
                return $this->spp_reader_init();
1017
        }
1018
 
1019
        function __construct($addr='localhost:49500') {
1020
                $this->addr = $addr;
1021
        }
1022
 
1023
}