-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminibots.class.php
2109 lines (1703 loc) · 65.6 KB
/
minibots.class.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
/* ------------------------------------------------------------------------- */
/* minibots.class.php Ver.4.2b */
/* ------------------------------------------------------------------------- */
/* Mini Bots class is a small php class that helps you to create bots, */
/* it uses some free web seriveces online to retrive usefull data. */
/* ------------------------------------------------------------------------- */
Class Minibots
{
//
// used to read only the first part of files
// with limited cURL calls
private $file_size = 0;
private $max_file_size = 5000;
private $file_downloaded = "";
//
// yes = always use file_get_contents, no = always use cURL, https = only file_get_contents for https calls
public $use_file_get_contents = "no" ;
//
// If you call $minibot->findType(...) this variable will be populated with data that describe
// common filetypes. Used in $minibot->getUrlInfo(...) method
private $fileInfoJson = false;
public function __construct () {
}
// ------------------------------------------------------------------------------------
// HELPER FUNCTIONS
// ------------------------------------------------------------------------------------
//
// get the IP address of the connected user
public function getIP() {
$ip="";
if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR");
else if(getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR");
else $ip = "";
return $ip;
}
//
// this function return the html attribute of a given tag
// (use for scraping data)
public function attr($s,$attrname) {
preg_match_all('#\s*('.$attrname.')\s*=\s*["]([^"]*)["]\s*#i', $s, $x);
if (count($x)>=3 && isset($x[2][0])) return isset($x[2][0]) ? $x[2][0] : "";
preg_match_all('#\s*('.$attrname.')\s*=\s*[\']([^\']*)[\']\s*#i', $s, $x);
if (count($x)>=3 && isset($x[2][0])) return isset($x[2][0]) ? $x[2][0] : "";
preg_match_all('#\s*('.$attrname.')\s*=\s*([^ ]*)\s*#i', $s, $x);
if (count($x)>=3 && isset($x[2][0])) return isset($x[2][0]) ? $x[2][0] : "";
return "";
}
//
// return the part of the string $s between strings $a and $b
public function betweenTags($s,$a,$b) {
$s1 = str_replace($a,"",stristr($s,$a));
if($s1) {
$s2 = str_replace(stristr($s1,$b), "", $s1);
}
return $s2;
}
/*function betweenTags($s,$a,$b) {
$s1 = str_replace($a,"",stristr($s,$a));
return $s1 ? str_replace(stristr($s1,$b), "", $s1) : $s1;
}*/
//
// return the array of matches when searching for a
// tag serie while scraping html
// $return can be "ALL" | "INNER" | "OUTER"
public function getTags($tagname,$text,$return="ALL") {
if($tagname=="img" || $tagname=="br" || $tagname=="input") {
// autoclose
preg_match_all('#<'.$tagname.'[^>]*?>#Uis', $text, $s);
} else {
preg_match_all('#<'.$tagname.'[^>]*?>(.*)</'.$tagname.'>#Uis', $text, $s);
}
if($return=="ALL") return $s;
if($return=="INNER") return $s[1];
if($return=="OUTER") return $s[0];
return $s;
}
//
// this function makes a relative url an absolute merging
// properly the url and the link.
public function makeabsolute($url,$link) {
$p = parse_url($url);
if (strpos( $link,"//")===0 ) return trim($link);
if (strpos( $link,"http://")===0 ) return trim($link);
if (strpos( $link,"https://")===0 ) return trim($link);
if($p['scheme']."://".$p['host']==$url && $link[0]!="/" && $link!=$url) return trim($p['scheme']."://".$p['host']."/".$link);
if (strpos( $link, "/")===0) return trim($p['scheme']."://".$p['host'].$link);
return trim(str_replace(substr(strrchr($url, "/"), 1),"",$url).$link);
}
//
// Retrieves a page with some parameters in POST.
// The parameters should be passed like this:
// $vars = array("name"=>value, "name2"=>value2);
public function getPagePost($url,$vars) {
if (!function_exists("curl_init")) die("getPagePost needs CURL module, please install CURL on your php.");
$s = "";
foreach($vars as $k=>$v) $s.= ($s?"&":"") . $k."=".rawurlencode($v);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $s);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_results = curl_exec ($curl);
curl_close ($curl);
return $curl_results;
}
// Not used yet
function getPageWP($url, $max_file_size=0) {
$response = wp_remote_get( $url );
$body = wp_remote_retrieve_body( $response );
$header = wp_remote_retrieve_headers( $response );
return array($body , $header);
}
//
// this method gets a page, use this to build your crawler, it calls cURL
// but on some servers file_get_contents works better, so it uses
// the main parameter "use_file_get_contents" to switch from cURL to file_get_contents.
// This method doesn't handle POST data.
public function getPage($url, $max_file_size=0) {
// turn it true for debug
$DEBUG = false;
$https = preg_match("/^https/i",$url);
if($this->use_file_get_contents=="yes") return file_get_contents($url);
if($https && $this->use_file_get_contents=="https") {
return file_get_contents($url);
}
//
// build curl call
if (!function_exists("curl_init")) die("getPage needs CURL module, please install CURL on your php.");
$ch = curl_init();
//
// VERBOSE DEBUG
if($DEBUG) {
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verboseCurl = fopen('./tmp/verbose.txt', 'w+'); // for debug purpose
curl_setopt($ch, CURLOPT_STDERR, $verboseCurl);
}
//
// PORT NUMBER
preg_match("/:([0-9]+)/i", $url, $matches);
if(isset($matches[1]) && $matches[1] > 1) {
$port = $matches[1];
curl_setopt($ch, CURLOPT_PORT, $port);
}
//
// URL
curl_setopt($ch, CURLOPT_URL, $url);
//
// FAIL ON ERROR
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
//
// FOLLOW REDIRECTS
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//
// HTTPS
if($https) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt($ch, CURLOPT_CERTINFO, true);
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");
}
//
// ASK FOR ENCODED CONTENT
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate,sdch');
//
// PUT THE RESULT IN A VAR
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
//
// GET ALSO HEADERS
curl_setopt($ch, CURLOPT_HEADER, 1);
//
// TIMEOUT AFTER 15 secs
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
//
// USER AGENT (IS IT OLD?)
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
//
// HTTP HEADERS
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
'accept-language:en-US,en;q=0.8'
));
//
// COOKIES
curl_setopt($ch , CURLOPT_COOKIEJAR, './tmp/cookies.txt');
curl_setopt($ch , CURLOPT_COOKIEFILE, './tmp/cookies.txt');
//
// TRUNCATE CALLS IF PAGE TOO BIG
if($max_file_size>0) {
// if you want to reduce download size, set the byte size limit
$this->max_file_size = $max_file_size;
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'on_curl_header'));
curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'on_curl_write'));
}
//
// GET URL!
$web_page = curl_exec($ch);
// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($web_page, 0, $header_size);
$body = substr($web_page, $header_size);
if(strlen($web_page) <= 1 && $max_file_size>0) {
$web_page = $this->file_downloaded;
}
if(curl_error($ch)) return array( curl_error($ch), $header);
if($DEBUG) {
// devug verbose
rewind($verboseCurl);
$verboseLog = stream_get_contents($verboseCurl);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
}
return array($body,$header);
}
//
// this method returns all the links inside a given url
// skip bad urls (javascript, mailto...), make all urls absolute
// flags to skip some links to particular extensions (pdf,zip,jpg...)
// and to follow external urls.
public function findLinks($url, $web_page, $FOLLOW_EXTERNAL=false, $SKIP_EXTENSIONS="") {
$stop_host = "";
$exts = array();
if($FOLLOW_EXTERNAL==false) {
$temp = parse_url($url);
if(!$temp['host']) {
("Can't determine host, plaese check starting url: ".$url);
} else {
$stop_host = $temp['host'];
}
}
if($SKIP_EXTENSIONS){
$exts = explode(",",$SKIP_EXTENSIONS);
if(empty($exts)) $SKIP_EXTENSION="";
}
//search links
preg_match_all('#<a([^>]*)?>(.*)</a>#Uis', $web_page, $a_array);
$outAr = array();
if(isset($a_array[1])) {
foreach($a_array[1] as $link) {
$href = $this->attr($link,"href");
if($href!=""
&& !preg_match("/^javascript:/",$href)
&& !preg_match("/^#/",$href)
&& !preg_match("/^mailto:/",$href)
) {
$temp = $this->makeabsolute($url,str_replace(" ","%20",$href));
if($FOLLOW_EXTERNAL==false && $stop_host) {
$temp2 = parse_url($temp);
if($temp2['host']!=$stop_host) $temp="";
}
if($SKIP_EXTENSIONS){
foreach($exts as $e){
if(preg_match("/(\.".$e.")$/",$temp)) { $temp=""; break;}
}
}
if($temp) $outAr[] = $temp;
}
}
}
return array_unique($outAr);
}
//
// this method returns all the emails contained
// in the page.
public function findEmails($page) {
preg_match_all(
'/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\b/i',
$page,
$matches
);
$outAr = array();
foreach(array_unique($matches[0]) as $email) {
//echo "<code>".$email."</code><br/>";
$outAr[] = $email;
}
return $outAr;
}
//
// remove all html and tags from a url and get only the text
// TO DO: could be improved to use only useful tags (headings and paragraphs)
public function justText($text) {
$text = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $text);
$text = preg_replace('#<style(.*?)>(.*?)</style>#is', '', $text);
$text = preg_replace("/[\n\r\t]/"," ",strip_tags($text));
$text = preg_replace("/( +)/"," ",strip_tags($text));
return trim($text);
}
//
// private function to handle file size check and prevent downloading too much
private function on_curl_header($ch, $header) {
$trimmed = rtrim($header);
if (preg_match('/^Content-Length: (\d+)$/i', $trimmed, $matches)) {
$file_size = (float)$matches[1];
if ($file_size > $this->max_file_size) {
// stop if bigger
return -1;
}
}
return strlen($header);
}
//
// like the previous one, private function to handle file size check and prevent downloading too much
private function on_curl_write($ch, $data) {
$bytes = strlen($data);
$this->file_size += $bytes;
$this->file_downloaded .= $data;
if ($this->file_size > $this->max_file_size) {
// stop if bigger
return -1;
}
return $bytes;
}
//
// function to get remote file size
// TO DO: Does it work with https?
public function getRemoteFileSize($url) {
if (substr($url,0,4)=='http') {
$h = @get_headers($url, 1);
if($h) {
$x = array_change_key_case($h,CASE_LOWER);
} else return false;
if ( strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { $x = $x['content-length'][1]; }
else { $x = $x['content-length']; }
}
else { $x = @filesize($url); }
return $x;
}
//
// function to get the http response code for a url
// TO DO: Does it work with https?
public function getHttpResponseCode($url) {
if (!function_exists("curl_init")) die("getHttpResponseCode needs CURL module, please install CURL on your php.");
// 404 not found, 403 forbidden...
$ch = @curl_init($url);
@curl_setopt($ch, CURLOPT_HEADER, TRUE);
@curl_setopt($ch, CURLOPT_NOBODY, TRUE);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$status = array();
preg_match('/HTTP\/.* ([0-9]+) .*/', @curl_exec($ch) , $status);
return isset($status[1]) ? $status[1] : null;
}
//
// walk recursively throught an object and extract matching values
// by property name or by key. Useful to extract data from
// ldjson data in pages. Used in $minibot->getUrlInfo(...) method.
public function walk_recursive($obj, $key) {
$found = array();
if ( is_object($obj) ) {
foreach ($obj as $property => $value)
if($property === $key) $found[] = $value;
elseif (is_array($value) || is_object($value))
$found = array_merge( $found, $this->walk_recursive($value, $key) );
} elseif ( is_array($obj) ) {
foreach ($obj as $keyar => $value)
if($keyar === $key) $found[] = $value;
elseif (is_array($value) || is_object($value)) $found = array_merge( $found, $this->walk_recursive($value, $key) );
}
return $found;
}
//
// sometimes downloaded pages have javascript object that are
// automatically convertible to json objects (for single quotes)
// so this functions make some replaces. Used with Amazon pages
// in $minibot->getUrlInfo(...) method.
public function fixDecodeJson( $code ) {
$code = preg_replace("/[ \t\n\r]+/", " ", $code);
$code = preg_replace("/{( *)?'/","{\"",$code);
$code = preg_replace("/'( *)?}/","\"}",$code);
$code = preg_replace("/:( *)?'/",":\"",$code);
$code = preg_replace("/'( *)?:/","\":",$code);
$code = preg_replace("/,( *)?'/",",\"",$code);
$code = preg_replace("/'( *)?,/","\",",$code);
return $code;
}
//
// return info on a file extension, lib here (downloaded locally)
// https://gist.github.com/giuliopons/0913e0bcd1ed5a9c7e0ef012248d15e3
public function findType($ext) {
if(!$this->fileInfoJson) {
$this->fileInfoJson = json_decode(file_get_contents(dirname(__FILE__) . "/fileinfo.json"));
}
foreach($this->fileInfoJson as $t => $a) {
if($t == $ext || $t==strtoupper($ext)) {
return $a->descriptions[0];
}
}
return "";
}
//
// extract the ldjson object or the oembed object from a webpage.
// this object can be used to search data with walk_recursive method.
public function getLdJsonStringOembed($webpage) {
$o = array();
preg_match_all("/<script( *)?type( *)?=( *)?\"application\/ld\+json\"([^>]*)>(.*)<\/script>/imsU", $webpage, $matches);
if(isset($matches[5]) && !empty($matches[5])) {
foreach( $matches[5] as $obj) {
$o[] = json_decode($obj);
}
}
preg_match_all("/<link rel=\"alternate\" type=\"application\/json\+oembed\" href=\"(.*)\">/imsU",$webpage,$matches);
if(isset($matches[1]) && !empty($matches[1])) {
$ar = $this->getPage($matches[1][0]);
if($ar[0]) $o[] = json_decode($ar[0]);
}
return !empty($o) ? $o : null;
}
// ------------------------------------------------------------------------------------
// BOTS
// ------------------------------------------------------------------------------------
//
// Copy a remote url to your local server
public function copyFile($url,$filename){
// copy remote file to server
$file = fopen ($url, "rb");
if (!$file) return false; else {
$fc = fopen($filename, "wb");
while (!feof ($file)) {
$line = fread ($file, 1028);
fwrite($fc,$line);
}
fclose($fc);
return true;
}
}
//
// Google spell suggest.
// Usage example:
// $obj = New Minibots();
// $word = $obj->doSpelling("wikipezia");
// --> wikipedia
public function doSpelling($q) {
// grab google page with search
$web_page = file_get_contents( "https://www.google.it/search?q=" . urlencode($q) );
// put anchors tag in an array
preg_match_all('#<a([^>]*)?>(.*)</a>#Us', $web_page, $a_array);
for($j=0;$j<count($a_array[0]);$j++) {
// find link with spell suggestion and return it
if(stristr($a_array[0][$j],"spell=1")) return strip_tags($a_array[0][$j]);
//if(stristr($a_array[0][$j],"class=\"spell\"")) return strip_tags($a_array[0][$j]);
}
return $q; //if no results returns the q value
}
//
// Make a tiny url with tinyurl.com free service.
// Usage example:
// $obj = New Minibots();
// $short_url = $obj->doShortURL("http://www.this.is.a.long.url/words-words-words");
// --> http://tinyurl.com/aiIAa (fake values)
public function doShortURL($longUrl) {
$short_url= file_get_contents('http://tinyurl.com/api-create.php?url=' . $longUrl);
return $short_url;
}
//
// Convert back from a tiny url to a long url, work also with urls of other services
// like goo.gl, bit.ly and others. This method works to handle all redirects, not only
// the ones from shorten url services.
// Usage example:
// $obj = New Minibots();
// $long_url = $obj->doShortURLDecode("http://tinyurl.com/aiIAa");
// --> http://www.this.is.a.long.url/words-words-words (fake values)
public function doShortURLDecode($url) {
if (!function_exists("curl_init")) die("doShortURLDecode needs CURL module, please install CURL on your php.");
$ch = @curl_init($url);
@curl_setopt($ch, CURLOPT_HEADER, TRUE);
@curl_setopt($ch, CURLOPT_NOBODY, TRUE);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$out = @curl_exec($ch);
preg_match('/Location: (.*)\n/i', $out, $a);
if (!isset($a[1])) return $url;
return trim($a[1]);
}
//
// Check if an mp3 URL is an mp3.
// Usage example:
// $obj = New Minibots();
// $check = $obj->checkMp3("http://www.artintent.it/Kalimba.mp3");
// --> true
public function checkMp3($url) {
if (!function_exists("curl_init")) die("checkMp3 needs CURL module, please install CURL on your php.");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$results = explode("\n", trim(curl_exec($ch)));
$mime = "";
foreach($results as $line) {
if (strtok(strtolower($line), ':') == 'content-type') {
$parts = explode(":", $line);
$mime = trim($parts[1]);
}
}
return $mime=="audio/mpeg";
}
//
// Check if a URL exists, like file_exists, but for remote urls.
// Usage example:
// $obj = new Minibots();
// $check = $obj->url_exists("http://en.wikipedia.org/wiki/Barack_Obama");
// --> true
public function url_exists($url) {
return ($this->getHttpResponseCode($url) == 200);
}
//
// Check if an email is correct, this function try to validate email address by connecting to the SMTP server.
// It returns true when email is ok or returns an array(msg, error code) when fails.
// The second parameter, $from_address should be an email with permission to send mail from your domain.
// Usage example:
// $obj = new Minibots();
// $check = $obj->doSMTPValidation("[email protected]","[email protected]");
// --> true
public function doSMTPValidation($email, $from_address="", $debug=false) {
if (!function_exists('checkdnsrr')) die("This function requires checkdnsrr function, check your Php version.");
$output = "";
// --------------------------------
// Check email syntax with regular expression, for both destination and sender
// --------------------------------
if (!$from_address) $from_address = $_SERVER["SERVER_ADMIN"];
if (!preg_match('/^([a-zA-Z0-9\._\+-]+)\@((\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,7}|[0-9]{1,3})(\]?))$/', $from_address)) {
$error = "From email is wrong.";
} elseif (preg_match('/^([a-zA-Z0-9\._\+-]+)\@((\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,7}|[0-9]{1,3})(\]?))$/', $email, $matches)) {
$domain = $matches[2];
// --------------------------------
// get DNS MX records
// --------------------------------
if(getmxrr($domain, $mxhosts, $mxweight)) {
for($i=0;$i<count($mxhosts);$i++){
$mxs[$mxhosts[$i]] = $mxweight[$i];
}
asort($mxs);
$mailers = array_keys($mxs);
} elseif(checkdnsrr($domain, 'A')) {
$mailers[0] = gethostbyname($domain);
} else {
$mailers=array();
}
$total = count($mailers);
if($total > 0) {
// --------------------------------
// Check if mail servers accept email
// --------------------------------
for($n=0; $n < $total; $n++) {
if($debug) { $output .= "Checking server $mailers[$n]...\n";}
$connect_timeout = 2;
$errno = 0;
$errstr = 0;
//$from_address = str_replace("@","",strstr($from_address, '@'));
// --------------------------------
// Open socket
// --------------------------------
if($sock = @fsockopen($mailers[$n], 25, $errno , $errstr, $connect_timeout)) {
$response = fgets($sock);
if($debug) {$output .= "Opening up socket to $mailers[$n]... Success!\n";}
stream_set_timeout($sock, 5);
$meta = stream_get_meta_data($sock);
if($debug) { $output .= "$mailers[$n] replied: $response\n";}
// --------------------------------
// Errors or time out
// --------------------------------
if(!$meta['timed_out'] && !preg_match('/^2\d\d[ -]/', $response)) {
$code = trim(substr(trim($response),0,3));
if ($code=="421") {
// 421 #4.4.5 Too many connections to this host.
$error = $response;
break;
} else {
if($response=="" || $code=="") {
// There was an error, but not clear
$code = "0";
}
$error = "Error: $mailers[$n] said: $response\n";
break;
}
break;
}
// talk to smtp server with its language
// try to ask for recipient but don't send email
$cmds = array(
"HELO $from_address",
"MAIL FROM: <{$from_address}>",
"RCPT TO: <$email>",
"QUIT",
);
foreach($cmds as $cmd) {
$before = microtime(true);
fputs($sock, "$cmd\r\n");
$response = fgets($sock, 4096);
$t = round(1000 * (microtime(true)-$before));
if($debug) {$output .= $cmd."\n". "($t ms) ". $response;}
if(!$meta['timed_out'] && preg_match('/^5\d\d[ -]/', $response)) {
$code = trim(substr(trim($response),0,3));
if ($code<>"552") {
$error = "Unverified address: $mailers[$n] said: $response";
break 2;
} else {
$error = $response;
break 2;
}
// --------------------------------
// Errors 554 and 552 are over quota, so the email is ok, but the full.
// 554 Recipient address rejected: mailbox overquota
// 552 RCPT TO: Mailbox disk quota exceeded
// --------------------------------
}
}
fclose($sock);
if($debug) { $output .= "Succesful communication with $mailers[$n], no hard errors, assuming OK\n";}
break;
} elseif($n == $total-1) {
$error = "None of the mailservers listed for $domain could be contacted";
$code = "0";
}
}
} elseif($total <= 0) {
$error = "No usable DNS records found for domain '$domain'";
}
} else {
$error = 'Email is wrong.';
}
if($debug) {
print nl2br(htmlentities($output));
}
if(!isset($code)) $code="n.a.";
if(isset($error)) return array($error,$code); else return true;
}
//
// Fetch info for a specified URL, maximages and minkbimg are usefull to get useful images,
// so if there is a small icon this image will be skipped, to find an image bigger.
// Usage example:
// $obj = new Minibots();
// $infos = $obj->getUrlInfo("http://piccsy.com/2013/10/cute-dog");
// --> array( ... )
public function getUrlInfo($url,$maximages=5,$minkbimg=10) {
//
// DEFAULTS
$data['favicon']="";
$data['images']=array();
$data["domain"] = "";
$data['title']= "";
$data["lastmodified"] = "";
$data['description']= "";
//
// ANCHOR
if(preg_match("/^#/",$url)) { $data["err"] = "Local anchor url"; return $data; }
//
// IS A MAILTO URL
if(preg_match("#^mailto:#",$url)) {
$emails = $this->findEmails($url);
$e = array_pop($emails);
$data['title']= isset($e) ? $e : "Mailto command";
$data['description']= isset($e) ? "Send an email to this address" : "Send email";
return $data;
}
//
// EMPTY
if($url=="") { $data["err"] = "Empty url"; return $data; }
//
// JAVASCRIPT
if(preg_match("/^javascript\:/",$url)) { $data["err"] = "Javascript code"; return $data; }
//
// PARSE URL OBJECT
$parsed_url = parse_url($url);
$data["domain"] = isset($parsed_url["host"]) ? $parsed_url["host"] : "";
$data["favicon"] = $parsed_url["scheme"]."://".$parsed_url["host"]."/favicon.ico"; //guess
//
// IS AN IMAGE FILE
if(preg_match("/(\.(jpe?g|gif|png|webp))$/i",$url,$matches)) {
// defaults
$data['description']= "This is an image file";
$data['title']=basename($url);
$data['images']=array($url);
$data['favicon'] = $parsed_url["scheme"]."://".$parsed_url["host"]."/favicon.ico"; //guess
return $data;
}
//
// IS A PDF FILE
if(preg_match("/(\.pdf)$/i",$url)) {
$data['description']="This is a PDF file.";
$data['title']=basename($url);
$data['images']=array();
return $data;
}
//
// IS A FACEBOOK URL
if(preg_match("#^https?://www\.facebook\.com#",$url)) {
$data['favicon']="https://www.facebook.com/favicon.ico";
$data['title']= preg_replace("#^/#","",$parsed_url['path']);
if(substr_count($parsed_url['path'],"/")==1 && $parsed_url['path']!="/sharer.php") {
$data['description']="This url should be a Facebook url page";
} elseif($parsed_url['path']=="/sharer.php"){
$data['title'] = "Share";
$data['description'] = "Share this content on Facebook";
}else {
$data['description']="This is a Facebook url";
}
return $data;
}
//
// IS A TWITTER URL
if(preg_match("#^https?://(www\.)?twitter\.com#",$url)) {
$data['favicon']="https://twitter.com/favicon.ico";
$data['title']= preg_replace("#^/#","",$parsed_url['path']);
if(substr_count($parsed_url['path'],"/")==1) {
$data['description']="This url should be a Twitter url page";
} elseif($parsed_url['path']=="/intent/tweet"){
$data['title'] = "Share";
$data['description'] = "Share this content on Twitter";
}else {
$data['description']="This is a Twitter url";
}
return $data;
}
//
// IS A LINKEDIN URL
if(preg_match("#^https?://(www\.)?linkedin\.com#",$url) && !preg_match("#^https?://(www\.)?linkedin\.com/feed/update#",$url)) {
$data['favicon']="https://www.linkedin.com/favicon.ico";
if(substr_count($parsed_url['path'],"/")==3 && preg_match("#^/in/([^/]*))/?$#",$parsed_url['path'],$m)) {
$data['description']="This is a Linkedin url page";
$data['title'] = $m[1];
} elseif($parsed_url['path']=="/shareArticle"){
$data['title'] = "Share";
$data['description'] = "Share this content on Linkedin";
}else {
$data['title'] = "Linkedin content";
$data['description']="This is a Linkedin url";
}
return $data;
}
//
// IS INSTAGRAM URL
if(preg_match("#^https?://(www\.)?instagram\.com#",$url)) {
// TRY SPECIFIC BOT
$metas = $this->getInstagramUrl($url);
if(isset($metas["og:description"])) {
$data['title']= $metas["twitter:title"];
$data['description']= $metas["og:description"];
} else {
$data['title']="Instagram URL";
$data['description']="Sorry can't fetch content";
}
return $data;
}
//
// LOCAL URL
if(!preg_match("/^https?:\/\//",$url)) { $data["err"] = "Url must begin with http"; return $data; }
//
// FETCH URL
$web_page_ar = $this->getPage($url, $maximages == 0 ? 5000 : 0);
// IF META REFRESH WITH HTML GET NEW URL
$metas = $this->getMetaTags($web_page_ar[0],["http-equiv"]);
if(isset($metas["refresh"])) {
$metas["refresh"] = preg_replace("/^([0-9]*)\;URL=/i","",$metas["refresh"]);
if($metas["refresh"]!="") {
$url = $metas["refresh"];
$web_page_ar = $this->getPage($url, $maximages == 0 ? 5000 : 0);
$parsed_url = parse_url($url);
$data["domain"] = isset($parsed_url["host"]) ? $parsed_url["host"] : "";
}
}
// IF THE FETCHED URL WAS A REDIRECT (CURL FOLLOWS REDIRECT)
// UPDATE URL INFO
preg_match("#\nlocation: (.*)\n#Uis",$web_page_ar[1],$newurl);
if(isset($newurl[1]) && $newurl[1]!="") {
$url = $newurl[1];
$parsed_url = parse_url($url);
$data["domain"] = isset($parsed_url["host"]) ? $parsed_url["host"] : "";
}
// ADDITIONAL DATA
$ldJsonOembed = $this->getLdJsonStringOembed( $web_page_ar[0] );
//
// SEARCH TITLE
$title_array = $this->getTags("title", $web_page_ar[0], "INNER");
/*preg_match_all('#<title([^>]*)?>(.*)</title>#Uis', $web_page_ar[0], $title_array);*/
$data['title'] = isset($title_array[0]) ? $title_array[0] : "";
//
// SEARCH DESCRIPTION AND TITLE
// 1 LDJSON / OEMBED
$arDescription = $this->walk_recursive( $ldJsonOembed, "description" );
if(is_array($arDescription) && isset($arDescription[0])) $data['description'] = $arDescription[0]; // o array_pop ?
else $data['description']="";
// 2 META
if($data['description']=="") {
$metas = $this->getMetaTags($web_page_ar[0]);
if(isset($metas["description"])) $data["description"] = $metas["description"];
if(isset($metas["og:description"])) $data["description"] = $metas["og:description"];
if(isset($metas["og:title"])) $data["title"] = $metas["og:title"];
}
// 3 FIRST <P>
if($data['description']=="") {
preg_match_all('#<p([^>]*)>(.*)</p>#Uis', $web_page_ar[0], $p_array);
$text = "";
for($i=0;$i<count($p_array[0]);$i++) if(strlen($text)<200) $text.=$this->justText($p_array[0][$i])." ";
$data['description']=$text;
}
// 4 TEXT
if($data['description']=="") {
$text = "";
$text =$this->justText( $web_page_ar[0]);
$data['description']=substr($text,0,200);
}
//
// SEARCH FAVICON
preg_match_all('#<link([^>]*)(.*)>#Uis', $web_page_ar[0], $link_array);
for($i=0;$i<count($link_array[0]);$i++) {
$rel = strtolower($this->attr($link_array[0][$i],"rel"));
if (stristr($rel,"icon") )
$data['favicon'] = $this->makeabsolute($url,$this->attr($link_array[0][$i],"href"));
}
//
// SEARCH PRICE (WOOCOMMERCE / SHOPIFY)
$arPrice = $this->walk_recursive( $ldJsonOembed, "price" );
if(is_array($arPrice)) {
$data['price'] = array_pop($arPrice);
$ar = $this->walk_recursive( $ldJsonOembed, "priceCurrency" );
$currency = array_pop( $ar );// (WOOCOMMERCE)
$ar = $this->walk_recursive( $ldJsonOembed, "currency_code" );
$currency = $currency !="" ? $currency : array_pop( $ar );// (SHOPIFY)
if($currency == "USD") $currency = "$";
if($currency == "EUR") $currency = "€";
if( $data['price'] > 1) $data['price'] = number_format($data['price'],0);
$data['price'] .= $currency;
$data['price'] = trim($data['price']);
}