-
Notifications
You must be signed in to change notification settings - Fork 16
/
ConnectorOrsr.php
2267 lines (1977 loc) · 88 KB
/
ConnectorOrsr.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Parser pre vypis z obchodneho registra SR
* Lookup service for Slovak commercial register (www.orsr.sk)
*
* Version 1.1.2 (released 21.10.2024)
* (c) 2015 - 2024 [email protected]
*
* ------------------------------------------------------------------
* Disclaimer / Prehlásenie:
* Kód poskytnutý je bez záruky a môže kedykoľvek prestať fungovať.
* Jeho funkčnosť je striktne naviazaná na generovanú štruktúru HTML elementov.
* Autor nie je povinný udržiavať kód aktuálny a funkčný, ani neposkytuje ku nemu žiadnu podporu.
* Kód bol sprístupnený na základe početných žiadostí vývojárov finančno-ekonomických aplikácií
* a neschopnosti štátnych inštitúcií poskytnúť kvalitné a zjednotené údaje o podnikateľských subjektoch.
* Autor nezodpovedá za nesprávne použitie kódu.
* ------------------------------------------------------------------
* Poznámka / Note:
* Obchodný register SR obsahuje len časť subjektov v podnikateľskom prostredí (cca 480 tis.).
* Neobsahuje údaje napr. o živnostníkoch alebo neziskových organizáciách.
* Tieto sa nachádzajú v ďalších verejne prístupných databázach (živnostenský register,
* register účtovných závierok, register právnických osôb). Pokiaľ hľadáte profesionálne
* riešenie s prístupom ku všetkých 1.7 mil. subjektom pozrite projekt https://bizdata.sk.
* ------------------------------------------------------------------
* Github repo:
* https://github.com/lubosdz/parser-orsr
* ------------------------------------------------------------------
*
* Usage examples:
*
* // init object
* $orsr = new \lubosdz\parserOrsr\ConnectorOrsr();
*
* // turn on debug mode (means save output to a local file to reduce requests)
* $orsr->debug = true;
* $orsr->dirCache = "/app/writable/cache/";
* $orsr->setOutputFormat('xml'); xml|json|empty string
*
* // make requests
* $orsr->getDetailById(1366, 9); // a.s. - Agrostav
* $orsr->getDetailById(19691, 2); // a.s. - Kerametal
* $orsr->getDetailById(11095, 2); // s.r.o. - Elet
* $orsr->getDetailById(11075, 5); // Firma / SZCO
* $orsr->getDetailById(5721, 6); // v.o.s.
* $orsr->getDetailById(11370, 6); // druzstvo
* $orsr->getDetailById(60321, 8); // statny podnik
*
* $orsr->getDetailByICO('31577890');
* $orsr->getDetailByICO('123');
*
* $data = $orsr->findByPriezviskoMeno('novák', 'peter');
* $data = $orsr->findByObchodneMeno('Matador');
* $data = $orsr->findByICO('31411801');
*
* $data = $orsr->getDetailByICO('31411801'); // [MATADOR Automotive Vráble, a.s.] => vypis.asp?ID=1319&SID=9&P=0
* echo "<pre>".print_r($data, 1)."</pre>";
*
* $data = $orsr->getDetailById(1319, 9); // statny podnik
* echo "<pre>".print_r($data, 1)."</pre>";
*/
namespace lubosdz\parserOrsr;
/**
* DOM XML parser class for Slovak Business Register (Business Directory of Slovak Republic)
*/
class ConnectorOrsr
{
const API_VERSION = '1.1.2';
/** @var string Endpoint URL */
const URL_BASE = 'https://www.orsr.sk';
/** @var float Fixed exchange rate SKK/EUR since 2009 */
const EXCH_RATE_SKK_EUR = 30.126;
/** @var string Regex date pattern which accepts "1.2.2024" or "1. 2. 2024" or "01.02.2024" */
const REGEX_DATE = '(\d{1,2}\. ?\d{1,2}\. ?\d{4})';
const
// person types
TYP_OSOBY_PRAVNICKA = 'pravnicka',
TYP_OSOBY_FYZICKA = 'fyzicka';
const
// court type - since 01/06/2023
TYP_SUDU_OKRESNY = 'OS', // default court "Okresny sud", valid also before 01/06/2023
TYP_SUDU_MESTSKY = 'MS'; // court in major cities (Bratislava, Kosice) marked as "Mestský súd", since 01/06/2023
#################################################
## Configurable public props
#################################################
/** @var bool Stores some data into local files to avoid multiple requests during development */
public $debug = false;
/** @var string Path to cache directory in debug mode (add trailing slash) */
public $dirCache = './';
/** @var bool If false, make php tidy extension optional. Definitely NOT recommended, but for some hostings the only way to go. */
public $useTidy = true;
/** @var bool If false, return empty results on error (looks like no matches found and user won't see error message) */
public $showXmlErrors = true;
/** @var int The number of seconds to cut off request if server not responding, default 60 as per [default_socket_timeout] */
public $urlTimeoutSecs = 5;
/** @var int The number of milliseconds between two consecutive requests to ORSR to prevent rate limit ban */
public $msecDelayFetchUrl = 500;
/** @var int After how many requests to ORSR should apply delay to prevent rate limit ban */
public $delayAfterRequestCount = 3;
#################################################
/** @var integer Execution start time */
protected $ts_start;
/** @var null|string Output format JSON|XML|RAW */
protected $format = '';
/** @var array Extracted data */
protected $data = [];
/** @var string e.g. "ID=54190&SID=7&P=0" URL to source page, where data have been downloaded from, napr. zaznam firmy v ORSR */
protected $srcUrl;
/** @var bool Semaphore to avoid double output, e.g. if matched 1 item (DIC, ICO) we instantly return detail */
protected $outputSent = false;
/**
* Constructor - verify required extensions are loaded
*/
public function __construct()
{
$required = ['mbstring', 'iconv', 'dom', 'json'];
if ($this->useTidy) {
array_push($required, 'tidy');
}
foreach ($required as $extension) {
if (!extension_loaded($extension)) {
throw new \Exception('Missing required PHP extension [' . $extension . '].');
}
}
$this->delayAfterRequestCount = max(0, intval($this->delayAfterRequestCount));
$this->urlTimeoutSecs = intval($this->urlTimeoutSecs);
if ($this->urlTimeoutSecs < 0 || $this->urlTimeoutSecs > 60) {
$this->urlTimeoutSecs = 5; // default 5 secs
}
$this->ts_start = microtime(true);
}
/**
* Separate method to control timeout when fetching from remote server
* @param string $url URL to be fetched from
*/
protected function loadUrl($url)
{
if ($this->delayAfterRequestCount > 0) {
static $cntRequests = 0;
if ($cntRequests && 0 == ($cntRequests % $this->delayAfterRequestCount)) {
// ORSR.sk may reject too frequent requests according to rate limits
$this->msleep();
}
++$cntRequests;
}
$ctx = stream_context_create([
"http" => [
"timeout" => $this->urlTimeoutSecs,
],
/*
// optionally uncomment in development ie. if self-signed certificate
// https://www.php.net/manual/en/context.ssl.php
"ssl" => [
"verify_peer" => false,
"verify_peer_name" => false,
"allow_self_signed" => true,
]
*/
]);
return file_get_contents($url, false, $ctx);
}
/**
* Delay execution in msec
* @param int $msec e.g. 500 = 0.5 sec
*/
protected function msleep($msec = 0)
{
if (!$msec) {
$msec = $this->msecDelayFetchUrl;
}
$msec = max(0, intval($msec));
if ($msec >= 1000) {
$secs = min(5, intval($msec / 1000));
if ($secs > 0) {
sleep($secs);
}
} elseif ($msec > 0) {
$nanosec = $msec * 1000;
usleep($nanosec); // values over 1 mil. may not be supported on some systems
}
}
/**
* Return source URL link from which last data have been fetched
*/
public function getSrcUrl()
{
return $this->srcUrl;
}
/**
* Clear previosuly extracted data & semaphore that output has been already sent
* Use e.g. to re-send request with the same instance
*/
public function resetOutput()
{
$this->outputSent = false;
$this->data = [];
$this->srcUrl = null;
}
/**
* Set output format
* @param string $format e.g. json|xml or empty string (default, raw output)
* @return ConnectorOrsr
*/
public function setOutputFormat($format)
{
$format = trim(strtolower($format));
if (in_array($format, ['json', 'xml', ''])) {
$this->format = $format;
} else {
throw new \Exception('Output format [' . $format . '] not supported.');
}
return $this;
}
/**
* Return only data required for formulars
* @param array $data Data from requested service, which possibly will not contain ALL available attributes
* @param array $force List of required attributes. Additional queries will be executed, if required attribute is empty
*/
public function normalizeData(array $data, array $force = [])
{
// flatten array if needed
if (!empty($data['obchodne_meno'][0])) {
$data['obchodne_meno'] = $data['obchodne_meno'][0];
}
if (!empty($data['adresa'][0])) {
$data['adresa'] = $data['adresa'][0];
}
// normalize attributes
$out = [
'ico' => empty($data['ico']) ? '' : $data['ico'], // e.g. 32631413
'obchodne_meno' => empty($data['obchodne_meno']) ? '' : $data['obchodne_meno'],
'street' => '',
'number' => '',
'city' => '',
'zip' => '', // e.g. 90101
'typ_osoby' => empty($data['typ_osoby']) ? '' : $data['typ_osoby'], // fyzicka - pravnicka
'hlavicka' => empty($data['hlavicka']) ? '' : $data['hlavicka'], // Fyzicka osoba zapisana v OU Nitra vlozka 1234/B.
'hlavicka_kratka' => empty($data['hlavicka_kratka']) ? '' : $data['hlavicka_kratka'], // OU Nitra, vlozka 1234/B
'dic' => empty($data['dic']) ? '' : $data['dic'], // e.g. 1020218914
'nace_kod' => empty($data['nace_kod']) ? '' : $data['nace_kod'], // e.g. 41209
'nace_text' => empty($data['nace_text']) ? '' : $data['nace_text'], // e.g. Počítačové služby a poradenstvo
];
if (!empty($data['adresa']['street'])) {
$out['street'] = $data['adresa']['street'];
} elseif (!empty($data['street'])) {
$out['street'] = $data['street'];
}
if (!empty($data['adresa']['number'])) {
$out['number'] = $data['adresa']['number'];
} elseif (!empty($data['number'])) {
$out['number'] = $data['number'];
}
if (!empty($data['adresa']['city'])) {
$out['city'] = $data['adresa']['city'];
} elseif (!empty($data['city'])) {
$out['city'] = $data['city'];
}
if (!empty($data['adresa']['zip'])) {
$out['zip'] = $data['adresa']['zip'];
} elseif (!empty($data['zip'])) {
$out['zip'] = $data['zip'];
}
if ($force) {
// load missing required attributes
foreach ($force as $attribute) {
if (!empty($out[$attribute])) {
continue; // already set
}
switch ($attribute) {
case 'hlavicka':
case 'hlavicka_kratka':
if ($data['typ_osoby'] == 'pravnicka') {
$orsr = new ConnectorOrsr();
$extra = $orsr->getDetailByICO($data['ico']);
if (empty($extra['prislusny_sud'])) {
$link = current($extra);
$extra = $orsr->getDetailByPartialLink($link);
}
if (!empty($extra['hlavicka'])) {
if (!empty($extra['hlavicka'])) {
$out['hlavicka'] = $extra['hlavicka'];
}
if (!empty($extra['hlavicka_kratka'])) {
$out['hlavicka_kratka'] = $extra['hlavicka_kratka'];
}
}
} else {
// parser ZRSR.SK not implemented yet (the implementation requires live token obtained from a previous request - can YOU extract it? :-)
}
break;
default:
}
}
}
return $out;
}
/**
* Return output with extra meta data
*/
public function getOutput()
{
if ($this->outputSent) {
// prevent from duplicate output
return;
}
if (!$this->data) {
// nothing to return
return;
}
if (!is_array($this->data)) {
throw new \Exception('Invalid output data.');
}
if (empty($this->data['meta'])) {
// meta data not included
$this->data = [
'meta' => [
'api_version' => self::API_VERSION,
'sign' => strtoupper(md5(serialize($this->data))),
'server' => $_SERVER['SERVER_NAME'],
'time' => date('d.m.Y H:i:s'),
'sec' => number_format(microtime(true) - $this->ts_start, 3),
'mb' => number_format(memory_get_usage() / 1024 / 1024, 3),
]
] + $this->data;
}
if($this->srcUrl && empty($this->data['srcUrl'])){
$this->data['srcUrl'] = $this->srcUrl;
}
$this->outputSent = true;
if ($this->debug) {
switch (strtolower($this->format)) {
case 'json':
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($this->data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
break;
case 'xml':
header("Content-Type: text/xml; charset=UTF-8");
echo _Array2XML::get($this->data);
break;
case 'raw':
return $this->data;
default:
// direct output
if (!headers_sent()) {
header("Content-Type: text/html; charset=UTF-8");
echo '<pre>' . print_r($this->data, true) . '</pre>';
} else {
fwrite(STDOUT, PHP_EOL . print_r($this->data, true) . PHP_EOL);
}
}
} else {
return $this->data;
}
}
/**
* Fetch company page from ORSR and return parsed data
* @param int $id Company database identifier, e.g. 19456
* @param int $sid ID 0 - 8, prislusny sud/judikatura (jurisdiction district ID)
* @param int $plny 0|1 Typ vypisu, default 0 = aktualny, 1 - uplny (vratane historickych zrusenych zaznamov)
* @param bool $onlyHtml If true return only fetched HTML, dont parse into attributes
*/
public function getDetailById($id, $sid, $plny = 0, $onlyHtml = false)
{
$id = intval($id);
if ($id < 1) {
throw new \Exception('Invalid company ID.');
}
$this->srcUrl = "vypis.asp?ID={$id}&SID={$sid}&P={$plny}"; // without repetitive "https://www.orsr.sk/"
$hash = $id . '-' . $sid . '-' . $plny;
$path = $this->dirCache . 'orsr-detail-' .$hash. '-raw.html';
if ($this->debug && is_file($path) && filesize($path)) {
$html = file_get_contents($path);
} else {
// ID + SID = jedinecny identifikator subjektu
// SID (ID sudu dla kraja) = 1 .. 8 different companies :-(
// P = 1 - uplny, otherwise 0 = aktualny
$url = self::URL_BASE . "/{$this->srcUrl}";
$html = $this->loadUrl($url);
if ($html && $this->debug) {
file_put_contents($path, $html);
}
}
if (!$html) {
throw new \Exception('Failed loading data.');
}
if ($onlyHtml) {
return $html;
}
$this->data = self::extractDetail($html);
return $this->getOutput();
}
/**
* Fetch company page from ORSR and return parsed data
* @param string $link Partial link to fetch, e.g. vypis.asp?ID=54190&SID=7&P=0
* @param bool $onlyHtml If true return only fetched HTML, dont parse into attributes
*/
public function getDetailByPartialLink($link, $onlyHtml = false)
{
$data = [];
if (false !== strpos($link, 'vypis.asp?')) {
// ID + SID = jedinecny identifikator subjektu
// SID (ID sudu dla kraja) = 1 .. 8 different companies :-(
// P = 1 - uplny, 0 - aktualny
list(, $link) = explode('asp?', $link);
parse_str($link, $params);
if (isset($params['ID'], $params['SID'], $params['P'])) {
$data = $this->getDetailById($params['ID'], $params['SID'], $params['P'], $onlyHtml);
if($data && is_array($data) && $this->srcUrl){
$data['srcUrl'] = $this->srcUrl;
}
}
}
return $data;
}
/**
* Return subject details
* @param string $meno
*/
public function findByObchodneMeno($meno)
{
$meno = trim($meno);
$meno = iconv('utf-8', 'windows-1250', $meno);
$meno = urlencode($meno);
$path = $this->dirCache . 'orsr-search-obmeno-' . $meno . '.html';
if ($this->debug && is_file($path) && filesize($path)) {
$html = file_get_contents($path);
} else {
// http://www.orsr.sk/hladaj_subjekt.asp?OBMENO=sumia&PF=0&R=on
// R=on ... only aktualne zaznamy, otherwise hladaj aj v historickych zaznamoch
// PF=0 .. pravna forma (0 = any)
$url = self::URL_BASE . "/hladaj_subjekt.asp?OBMENO={$meno}&PF=0&R=on";
$html = $this->loadUrl($url);
if ($html && $this->debug) {
file_put_contents($path, $html);
}
}
return $this->handleFindResponse($html);
}
/**
* Lookup by subject ICO
*
* @param string $ico
* @return array List of matching subjects e.g. suitable for autocomplete/typeahead fields
*/
public function findByICO($ico)
{
$ico = preg_replace('/[^\d]/', '', $ico);
if (strlen($ico) != 8) {
return [];
}
$path = $this->dirCache . 'orsr-search-ico-' . $ico . '.html';
if ($this->debug && is_file($path) && filesize($path)) {
$html = file_get_contents($path);
}
// http://www.orsr.sk/hladaj_ico.asp?ICO=123&SID=0
// SID=0 .. sud ID (0 = any)
if (empty($html)) {
$url = self::URL_BASE . "/hladaj_ico.asp?ICO={$ico}&SID=0";
$html = $this->loadUrl($url);
if ($html && $this->debug) {
file_put_contents($path, $html);
}
}
// lookup by ICO always returns max. 1 record
return $this->handleFindResponse($html);
}
/**
* Looup by subject ICO & return instantly company/subject details
* @param string $ico Company ID (8 digits code)
* @param bool $onlyHtml If true return only fetched HTML, dont parse into attributes
* @return array Company / subject details
*/
public function getDetailByICO($ico, $onlyHtml = false)
{
$ico = preg_replace('/[^\d]/', '', $ico);
if (strlen($ico) != 8) {
return [];
}
$path = $this->dirCache . 'orsr-search-ico-' . $ico . '.html';
if ($this->debug && is_file($path) && filesize($path)) {
$html = file_get_contents($path);
}
// http://www.orsr.sk/hladaj_ico.asp?ICO=123&SID=0
// SID=0 .. sud ID (0 = any)
if (empty($html)) {
$url = self::URL_BASE . "/hladaj_ico.asp?ICO={$ico}&SID=0";
$html = $this->loadUrl($url);
if ($html && $this->debug) {
file_put_contents($path, $html);
}
}
// lookup by ICO always finds max. 1 record
$links = $this->handleFindResponse($html);
if ($links && is_array($links)) {
while ($link = array_shift($links)) {
$html = $this->getDetailByPartialLink($link, true);
// preverime, ci existuje viac liniek pre rovnake ICO,
// platna je linka, kde vypis neobsahuje "spis postupeny z dovodu miestnej neprislusnosti"
// note: we use single-byte stripos() to avoid unnecessary codepage conversion win-1250 -> utf-8
if (!$links || false === stripos($html, 'vodu miestnej nepr')) {
// jedina linka alebo platny spis
break;
}
// short delay before next request
$this->msleep();
}
if ($onlyHtml) {
// special cases - e.g. prefetch for later parsing
return $html;
}
// extract structured data
$this->data = self::extractDetail($html);
}
return $this->data;
}
/**
* Search by surname and/or name
* @param string $priezvisko
* @param string $meno
*/
public function findByPriezviskoMeno($priezvisko, $meno = '')
{
$priezvisko = trim($priezvisko);
$priezvisko = iconv('utf-8', 'windows-1250', $priezvisko);
$priezvisko = urlencode($priezvisko);
$meno = trim($meno);
$meno = iconv('utf-8', 'windows-1250', $meno);
$meno = urlencode($meno);
$path = $this->dirCache . 'orsr-search-priezvisko-meno-' . $priezvisko . '-' . $meno . '.html';
if ($this->debug && is_file($path) && filesize($path)) {
$html = file_get_contents($path);
} else {
// http://orsr.sk/hladaj_osoba.asp?PR=kov%E1%E8&MENO=&SID=0&T=f0&R=on
// PR=priezvisko
// MENO=meno
// R=on ... only aktualne zaznamy, otherwise hladaj aj v historickych zaznamoch
// PF=0 .. pravna forma (0 = any)
// SID=0 .. sud ID (0 = any)
$url = self::URL_BASE . "/hladaj_osoba.asp?PR={$priezvisko}&MENO={$meno}&SID=0&T=f0&R=on";
$html = $this->loadUrl($url);
if ($html && $this->debug) {
file_put_contents($path, $html);
}
}
return $this->handleFindResponse($html, 'formaterMenoPriezvisko');
}
/**
* Handle response from ORSR with search results
* @param string $html Returned HTML page from ORSR
* @param string $formatter Custom output decorator
*/
public function handleFindResponse($html, $formatter = '')
{
$html = iconv('windows-1250', 'utf-8', $html);
$html = str_replace('windows-1250', 'utf-8', $html);
// load XHTML into DOM document
$xml = new \DOMDocument('1.0', 'utf-8');
// ensure valid XHTML markup
if ($this->useTidy) {
$tidy = new \tidy();
$html = $tidy->repairString($html, array(
'output-xhtml' => true,
//'show-body-only' => true, // we MUST have HEAD with charset!!!
), 'utf8');
} else {
libxml_use_internal_errors(true);
$xml->preserveWhiteSpace = false;
}
if (!$xml->loadHTML($html)) {
// whoops, parsing error
$errors = libxml_get_errors();
libxml_clear_errors();
if (!$this->showXmlErrors) {
return [];
}
if (!$errors && !empty($php_errormsg)) {
$errors = $php_errormsg;
}
throw new \Exception('XML Error - failed loading XHTML page into DOM XML parser - corrupted XML structure. Please consider enabling tidy extension.' . ($errors ? "\n Found errors:\n" . print_r($errors, 1) : ''));
}
$xpath = new \DOMXpath($xml);
$rows = $xpath->query("/html/body/table[3]/tr/td[2]"); // all tables /html/body/table
// loop through elements, parse & normalize data
$out = [];
if ($rows->length) {
foreach ($rows as $row) {
if ($formatter && method_exists($this, $formatter)) {
$out += self::{$formatter}($row, $xpath);
} else {
// drop double quotes, nazov firmy moze obsahovat uvodzovky, alebo EOLs (multiline)
$label = trim(str_replace(['"', "\r\n"], ['', ' '], $row->nodeValue));
$links = $xpath->query(".//../td[3]/div/a", $row);
if ($links->length) {
// vrati vzdy 2x linku - prva je na Aktualny vypis (P=0), druha Uplny vypis (P=1) - parsujeme len aktualny
$linkAktualny = $links->item(0)->getAttribute('href'); // e.g. "vypis.asp?ID=208887&SID=3&P=0"
// fix - dont overwrite existing label (ie. same company name with different ICO)
if (!empty($out[$label])) {
$label .= " (" . count($out) . ")";
}
$out[$label] = $linkAktualny;
}
}
}
}
return $out;
}
/**
* Partial XML node formatter
* @param mixed $row
* @param mixed $xpath
*/
protected static function formaterMenoPriezvisko($row, $xpath)
{
$label1 = $row->nodeValue;
$label2 = $xpath->query(".//../td[3]", $row);
$label2 = $label2->item(0)->nodeValue;
$label = self::trimMulti("{$label1} ({$label2})");
$links = $xpath->query(".//../td[4]/div/a", $row);
$linkAktualny = $links->item(0)->getAttribute('href'); // e.g. "vypis.asp?ID=208887&SID=3&P=0"
return [$label => $linkAktualny];
}
/**
* Extract tags
* @param string $html
*/
protected function extractDetail($html)
{
// returned data
$this->data = [];
// extracted tags
$tags = [
'Výpis z Obchodného registra' => 'extract_prislusnySud',
'Oddiel' => 'extract_oddiel',
'Obchodné meno' => 'extract_obchodneMeno',
'Sídlo' => 'extract_sidlo',
'Bydlisko' => 'extract_bydlisko',
'Miesto podnikania' => 'extract_miesto_podnikania',
'IČO' => 'extract_ico',
'Deň zápisu' => 'extract_denZapisu',
'Deň výmazu' => 'extract_denVymazu',
'Dôvod výmazu' => 'extract_dovodVymazu',
'Spoločnosť zrušená od' => 'extract_spolocnostZrusenaOd',
'Právny dôvod zrušenia' => 'extract_pravnyDovodZrusenia',
'Právna forma' => 'extract_pravnaForma',
'Predmet činnosti' => 'extract_predmetCinnost',
'Spoločníci' => 'extract_spolocnici',
'Výška vkladu' => 'extract_vyskaVkladu',
'Štatutárny orgán' => 'extract_statutarnyOrgan',
'Likvidátor' => 'extract_likvidátori',
'Likvidácia' => 'extract_likvidácia',
'Vyhlásenie konkurzu' => 'extract_vyhlasenieKonkurzu',
'Správca konkurznej podstaty' => 'extract_spravcaKonkurznejPodstaty',
'Zastupovanie' => 'extract_zastupovanie',
'Vedúci' => 'extract_vedúci_org_zlozky',
'Konanie' => 'extract_konanie',
'Základné imanie' => 'extract_zakladneImanie',
'členský vklad' => 'extract_zakladnyClenskyVklad',
'Akcie' => 'extract_akcie',
'Dozorná rada' => 'extract_dozornaRada',
'Kontrolná komisia' => 'extract_kontrolnaKomisia',
'Ďalšie právne skutočnosti' => 'extract_dalsieSkutocnosti',
'Zlúčenie, splynutie' => 'extract_zlucenieSplynutie',
'Právny nástupca' => 'extract_pravnyNastupca',
'Dátum aktualizácie' => 'extract_datumAktualizacie',
'Dátum výpisu' => 'extract_datumVypisu',
];
// convert keys to lowercase
$keys = array_map(function ($val) {
return mb_convert_case($val, MB_CASE_LOWER, 'utf-8');
}, array_keys($tags));
$tags = array_combine($keys, $tags);
// convert encoding
// fix: added //TRANSLIT//IGNORE - some foreign companies may contain invalid UTF-8 chars
$html = iconv('windows-1250', 'utf-8//TRANSLIT//IGNORE', $html);
$html = str_replace('windows-1250', 'utf-8', $html);
$xml = new \DOMDocument('1.0', 'utf-8');
// ensure valid XHTML markup
if ($this->useTidy) {
$tidy = new \tidy();
$html = $tidy->repairString($html, array(
'output-xhtml' => true,
//'show-body-only' => true, // we MUST have HEAD with charset!!!
), 'utf8');
} else {
libxml_use_internal_errors(true);
$xml->preserveWhiteSpace = false;
}
// convert entity to a simple whitespace & replace multiple whitespaces to a single whitespace
$html = strtr($html, [' ' => ' ']);
$html = self::trimMulti($html);
// load XHTML into DOM document
if (!$xml->loadHTML($html)) {
// whoops, parsing error
$errors = libxml_get_errors();
libxml_clear_errors();
if (!$this->showXmlErrors) {
$this->data = [];
return [];
}
if (!$errors && !empty($php_errormsg)) {
$errors = $php_errormsg;
}
throw new \Exception('XML Error - failed loading XHTML page into DOM XML parser - corrupted XML structure. Please consider enabling tidy extension.' . ($errors ? "\n Found errors:\n" . print_r($errors, 1) : ''));
}
$xpath = new \DOMXpath($xml);
$elements = $xpath->query("/html/body/*"); // all tables /html/body/table
// loop through elements, parse & normalize data
if ($elements->length) {
foreach ($elements as $cntElements => $element) {
/** @var \DOMElement */
$element;
// skip first X tables
if ($cntElements < 1) {
continue;
}
/** @var \DOMNodeList */
$nodes = $element->childNodes;
if ($nodes->length) {
foreach ($nodes as $node) {
$firstCol = $xpath->query(".//td[1]", $node); // relative XPATH with ./
if ($firstCol->length) {
$firstCol = $firstCol->item(0)->nodeValue;
if ($firstCol) {
$firstCol = self::trimMulti($firstCol);
foreach ($tags as $tag => $callback) {
if (false !== mb_stripos($firstCol, $tag, 0, 'utf-8')) {
$secondCol = $xpath->query(".//td[2]", $node);
if ($secondCol->length) {
$secondCol = $secondCol->item(0);
}
//$tmp = orsr::{$callback}($firstCol, $secondCol, $xpath);
$tmp = $this->{$callback}($firstCol, $secondCol, $xpath);
if ($tmp) {
// some sections may return mepty data (e.g. extract_akcie is not aplicable for s.r.o.)
$this->data = array_merge($this->data, $tmp);
}
break; // dont loop any more tags
}
}
}
}
}
}
}
}
// add source ORSR link
if ($this->srcUrl) {
$this->data['srcUrl'] = $this->srcUrl;
}
// add meta data
$this->data = [
'meta' => [
'api_version' => self::API_VERSION,
'sign' => strtoupper(md5(serialize($this->data))),
'server' => empty($_SERVER['SERVER_NAME']) ? '' : $_SERVER['SERVER_NAME'],
'time' => date('d.m.Y H:i:s'),
'sec' => number_format(microtime(true) - $this->ts_start, 3),
'mb' => number_format(memory_get_usage() / 1024 / 1024, 3),
]
] + $this->data;
return $this->data;
}
################################################################
### process extracted tags
################################################################
protected function extract_prislusnySud($tag, $node, $xpath)
{
// e.g. Výpis z Obchodného registra Okresného súdu Trnava (default)
// since 01/06/2023 also possible e.g. Výpis z Obchodného registra Mestského súdu Bratislava III
$out = [
'typ_sudu' => self::TYP_SUDU_OKRESNY,
'prislusny_sud' => ''
];
// extract district e.g. Bratislava
if (false !== mb_stripos($tag, ' súdu ', 0, 'utf-8')) {
list(, $out['prislusny_sud']) = explode(' súdu ', $tag);
}
// detect court type - Mestsky or Okresny, we prefer avoiding multibyte comparison and shortest possible non-conflicting string
if (false !== stripos($tag, ' Mestsk')) {
$out['typ_sudu'] = self::TYP_SUDU_MESTSKY;
}
$out = array_map('trim', $out);
return $out;
}
protected function extract_oddiel($tag, $node, $xpath)
{
// e.g. Oddiel: Sro ... Vložka číslo: 8429/S
$out = [
'oddiel' => '',
'vlozka' => '',
'typ_osoby' => '',
'hlavicka' => '',
'hlavicka_kratka' => '',
];
if (false !== strpos($tag, ':')) {
list(, $out['oddiel']) = explode(':', $tag);
}
$val = trim($node->nodeValue);
if (false !== strpos($val, ':')) {
list(, $out['vlozka']) = explode(':', $val);
}
$out = array_map('trim', $out);
// oddiely - typy subjektov:
// sa = akciova spolocnost
// sro = spol. s ruc. obm.
// sr = komanditna spol.
// alebo v.o.s.
// Pšn = štátny podnik
// alebo obecny podnik
// Po = europska spolocnost
// alebo europske druzstvo
// alebo organizačná zložka podniku
// alebo organizačná zložka zahranicnej osoby
// Firm = SZCO
// Dr = druzstvo
$typ = strtolower(self::stripAccents($out['oddiel']));
$sud_short = (self::TYP_SUDU_MESTSKY == $this->data['typ_sudu']) ? "MS" : "OS";
$sud_long = (self::TYP_SUDU_MESTSKY == $this->data['typ_sudu']) ? "Mestského súdu" : "Okresného súdu";
if (preg_match('/(firm)/iu', $typ)) {
$out['typ_osoby'] = self::TYP_OSOBY_FYZICKA;
$out['hlavicka'] = 'Fyzická osoba zapísaná v obchodnom registri ' . $sud_long . ' ' . $this->data['prislusny_sud'] . ', oddiel ' . $out['oddiel'] . ', vložka ' . $out['vlozka'] . '.';
$out['hlavicka_kratka'] = $sud_short . ' ' . $this->data['prislusny_sud'] . ', oddiel ' . $out['oddiel'] . ', vložka ' . $out['vlozka'];
} else {
$out['typ_osoby'] = self::TYP_OSOBY_PRAVNICKA;
if (preg_match('/(dr)/iu', $typ)) {
$out['hlavicka'] = 'Družstvo zapísané v obchodnom registri ' . $sud_long . ' ' . $this->data['prislusny_sud'] . ', oddiel ' . $out['oddiel'] . ', vložka ' . $out['vlozka'] . '.';
$out['hlavicka_kratka'] = $sud_short . ' ' . $this->data['prislusny_sud'] . ', oddiel ' . $out['oddiel'] . ', vložka ' . $out['vlozka'];
} elseif (preg_match('/(psn)/iu', $typ)) {
$out['hlavicka'] = 'Podnik zapísaný v obchodnom registri ' . $sud_long . ' ' . $this->data['prislusny_sud'] . ', oddiel ' . $out['oddiel'] . ', vložka ' . $out['vlozka'] . '.';
$out['hlavicka_kratka'] = $sud_short . ' ' . $this->data['prislusny_sud'] . ', oddiel ' . $out['oddiel'] . ', vložka ' . $out['vlozka'];
} else {
$out['hlavicka'] = 'Spoločnosť zapísaná v obchodnom registri ' . $sud_long . ' ' . $this->data['prislusny_sud'] . ', oddiel ' . $out['oddiel'] . ', vložka ' . $out['vlozka'] . '.';
$out['hlavicka_kratka'] = $sud_short . ' ' . $this->data['prislusny_sud'] . ', oddiel ' . $out['oddiel'] . ', vložka ' . $out['vlozka'];
}
}
return $out;
}
protected function extract_obchodneMeno($tag, $node, $xpath)
{
$out = self::getFirstTableFirstCell($node, $xpath);
// e.g. if invalid company name with surrounding double quotes ["Harvex, s.r.o."]
$map = ['"' => ''];
$likvidacia = 0; // change since 1.0.7 - we return 0 rather than 'nie'
$outValid = '';
if (!is_array($out)) {
$out = [$out];
}
// meno moze byt array, napr. podnik v likvidacii ma 2 zapisy, druhy s priponou "v likvidacii"
// vratit chceme prvy zaznam, ktory moze mat priponu "v likvidacii", nepotrebujeme duplikovane zaznamy s rovnakym menom
// zaznamy su chronologicky usporiadane - prvy zaznam by mal byt aktualny, pridavok "v likvidacii" je standardna zmena obchodneho mena
foreach ($out as $id => $meno) {
$meno = str_replace(array_keys($map), $map, $meno);
$meno = trim($meno);
if (false !== mb_stripos($meno, 'v likvidácii', 0, 'utf-8') || false !== mb_stripos($meno, 'v konkurze', 0, 'utf-8')) {
$likvidacia = 1; // change since 1.0.7 - we return 1 instead of "ano"
$outValid = $meno;
}
$out[$id] = $meno;
}
if (!$outValid && $out) {
$outValid = $out[0];
}
// change date e.g. 31.12.2020, usable e.g. when company name changed
$since = self::getEventDate($node, $xpath);
return [
'obchodne_meno' => $outValid,
'obchodne_meno_since' => $since,