]> git.mxchange.org Git - friendica.git/blob - include/network.php
fix validate_email
[friendica.git] / include / network.php
1 <?php
2
3
4 // curl wrapper. If binary flag is true, return binary
5 // results.
6
7 // Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
8 // to preserve cookies from one request to the next.
9 if(! function_exists('fetch_url')) {
10 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
11
12         $stamp1 = microtime(true);
13
14         $a = get_app();
15
16         $ch = @curl_init($url);
17         if(($redirects > 8) || (! $ch))
18                 return false;
19
20         @curl_setopt($ch, CURLOPT_HEADER, true);
21
22         if($cookiejar) {
23                 curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiejar);
24                 curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiejar);
25         }
26
27 //  These settings aren't needed. We're following the location already.
28 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
29 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
30
31         if (!is_null($accept_content)){
32                 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
33                         "Accept: " . $accept_content
34                 ));
35         }
36
37         @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
38         @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
39
40
41         if(intval($timeout)) {
42                 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
43         }
44         else {
45                 $curl_time = intval(get_config('system','curl_timeout'));
46                 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
47         }
48         // by default we will allow self-signed certs
49         // but you can override this
50
51         $check_cert = get_config('system','verifyssl');
52         @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
53
54         $prx = get_config('system','proxy');
55         if(strlen($prx)) {
56                 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
57                 @curl_setopt($ch, CURLOPT_PROXY, $prx);
58                 $prxusr = @get_config('system','proxyuser');
59                 if(strlen($prxusr))
60                         @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
61         }
62         if($binary)
63                 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
64
65         $a->set_curl_code(0);
66
67         // don't let curl abort the entire application
68         // if it throws any errors.
69
70         $s = @curl_exec($ch);
71
72         $base = $s;
73         $curl_info = @curl_getinfo($ch);
74         $http_code = $curl_info['http_code'];
75         logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
76         $header = '';
77
78         // Pull out multiple headers, e.g. proxy and continuation headers
79         // allow for HTTP/2.x without fixing code
80
81         while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
82                 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
83                 $header .= $chunk;
84                 $base = substr($base,strlen($chunk));
85         }
86
87         if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
88                 $new_location_info = @parse_url($curl_info["redirect_url"]);
89                 $old_location_info = @parse_url($curl_info["url"]);
90
91                 $newurl = $curl_info["redirect_url"];
92
93                 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
94                         $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
95
96                 $matches = array();
97                 if (preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches)) {
98                         $newurl = trim(array_pop($matches));
99                 }
100                 if(strpos($newurl,'/') === 0)
101                         $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
102                 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
103                         $redirects++;
104                         return fetch_url($newurl,$binary,$redirects,$timeout,$accept_content,$cookiejar);
105                 }
106         }
107
108         $a->set_curl_code($http_code);
109         $a->set_curl_content_type($curl_info['content_type']);
110
111         $body = substr($s,strlen($header));
112         $a->set_curl_headers($header);
113         @curl_close($ch);
114
115         $a->save_timestamp($stamp1, "network");
116
117         return($body);
118 }}
119
120 // post request to $url. $params is an array of post variables.
121
122 if(! function_exists('post_url')) {
123 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
124         $stamp1 = microtime(true);
125
126         $a = get_app();
127         $ch = curl_init($url);
128         if(($redirects > 8) || (! $ch))
129                 return false;
130
131         logger("post_url: start ".$url, LOGGER_DATA);
132
133         curl_setopt($ch, CURLOPT_HEADER, true);
134         curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
135         curl_setopt($ch, CURLOPT_POST,1);
136         curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
137         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
138
139         if(intval($timeout)) {
140                 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
141         }
142         else {
143                 $curl_time = intval(get_config('system','curl_timeout'));
144                 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
145         }
146
147         if(defined('LIGHTTPD')) {
148                 if(!is_array($headers)) {
149                         $headers = array('Expect:');
150                 } else {
151                         if(!in_array('Expect:', $headers)) {
152                                 array_push($headers, 'Expect:');
153                         }
154                 }
155         }
156         if($headers)
157                 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
158
159         $check_cert = get_config('system','verifyssl');
160         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
161         $prx = get_config('system','proxy');
162         if(strlen($prx)) {
163                 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
164                 curl_setopt($ch, CURLOPT_PROXY, $prx);
165                 $prxusr = get_config('system','proxyuser');
166                 if(strlen($prxusr))
167                         curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
168         }
169
170         $a->set_curl_code(0);
171
172         // don't let curl abort the entire application
173         // if it throws any errors.
174
175         $s = @curl_exec($ch);
176
177         $base = $s;
178         $curl_info = curl_getinfo($ch);
179         $http_code = $curl_info['http_code'];
180
181         logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
182
183         $header = '';
184
185         // Pull out multiple headers, e.g. proxy and continuation headers
186         // allow for HTTP/2.x without fixing code
187
188         while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
189                 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
190                 $header .= $chunk;
191                 $base = substr($base,strlen($chunk));
192         }
193
194         if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
195                 $matches = array();
196                 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
197                 $newurl = trim(array_pop($matches));
198                 if(strpos($newurl,'/') === 0)
199                         $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
200                 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
201                         $redirects++;
202                         logger("post_url: redirect ".$url." to ".$newurl);
203                         return post_url($newurl,$params, $headers, $redirects, $timeout);
204                         //return fetch_url($newurl,false,$redirects,$timeout);
205                 }
206         }
207         $a->set_curl_code($http_code);
208         $body = substr($s,strlen($header));
209
210         $a->set_curl_headers($header);
211
212         curl_close($ch);
213
214         $a->save_timestamp($stamp1, "network");
215
216         logger("post_url: end ".$url, LOGGER_DATA);
217
218         return($body);
219 }}
220
221 // Generic XML return
222 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
223 // of $st and an optional text <message> of $message and terminates the current process.
224
225 if(! function_exists('xml_status')) {
226 function xml_status($st, $message = '') {
227
228         $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
229
230         if($st)
231                 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
232
233         header( "Content-type: text/xml" );
234         echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
235         echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
236         killme();
237 }}
238
239
240 if(! function_exists('http_status_exit')) {
241 function http_status_exit($val) {
242
243     $err = '';
244         if($val >= 400)
245                 $err = 'Error';
246         if($val >= 200 && $val < 300)
247                 $err = 'OK';
248
249         logger('http_status_exit ' . $val);
250         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
251         killme();
252
253 }}
254
255
256 // convert an XML document to a normalised, case-corrected array
257 // used by webfinger
258
259 if(! function_exists('convert_xml_element_to_array')) {
260 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
261
262         // If we're getting too deep, bail out
263         if ($recursion_depth > 512) {
264                 return(null);
265         }
266
267         if (!is_string($xml_element) &&
268         !is_array($xml_element) &&
269         (get_class($xml_element) == 'SimpleXMLElement')) {
270                 $xml_element_copy = $xml_element;
271                 $xml_element = get_object_vars($xml_element);
272         }
273
274         if (is_array($xml_element)) {
275                 $result_array = array();
276                 if (count($xml_element) <= 0) {
277                         return (trim(strval($xml_element_copy)));
278                 }
279
280                 foreach($xml_element as $key=>$value) {
281
282                         $recursion_depth++;
283                         $result_array[strtolower($key)] =
284                 convert_xml_element_to_array($value, $recursion_depth);
285                         $recursion_depth--;
286                 }
287                 if ($recursion_depth == 0) {
288                         $temp_array = $result_array;
289                         $result_array = array(
290                                 strtolower($xml_element_copy->getName()) => $temp_array,
291                         );
292                 }
293
294                 return ($result_array);
295
296         } else {
297                 return (trim(strval($xml_element)));
298         }
299 }}
300
301 // Given an email style address, perform webfinger lookup and
302 // return the resulting DFRN profile URL, or if no DFRN profile URL
303 // is located, returns an OStatus subscription template (prefixed
304 // with the string 'stat:' to identify it as on OStatus template).
305 // If this isn't an email style address just return $s.
306 // Return an empty string if email-style addresses but webfinger fails,
307 // or if the resultant personal XRD doesn't contain a supported
308 // subscription/friend-request attribute.
309
310 // amended 7/9/2011 to return an hcard which could save potentially loading
311 // a lengthy content page to scrape dfrn attributes
312
313 if(! function_exists('webfinger_dfrn')) {
314 function webfinger_dfrn($s,&$hcard) {
315         if(! strstr($s,'@')) {
316                 return $s;
317         }
318         $profile_link = '';
319
320         $links = webfinger($s);
321         logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
322         if(count($links)) {
323                 foreach($links as $link) {
324                         if($link['@attributes']['rel'] === NAMESPACE_DFRN)
325                                 $profile_link = $link['@attributes']['href'];
326                         if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
327                                 $profile_link = 'stat:' . $link['@attributes']['template'];
328                         if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
329                                 $hcard = $link['@attributes']['href'];
330                 }
331         }
332         return $profile_link;
333 }}
334
335 // Given an email style address, perform webfinger lookup and
336 // return the array of link attributes from the personal XRD file.
337 // On error/failure return an empty array.
338
339
340 if(! function_exists('webfinger')) {
341 function webfinger($s, $debug = false) {
342         $host = '';
343         if(strstr($s,'@')) {
344                 $host = substr($s,strpos($s,'@') + 1);
345         }
346         if(strlen($host)) {
347                 $tpl = fetch_lrdd_template($host);
348                 logger('webfinger: lrdd template: ' . $tpl);
349                 if(strlen($tpl)) {
350                         $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
351                         logger('webfinger: pxrd: ' . $pxrd);
352                         $links = fetch_xrd_links($pxrd);
353                         if(! count($links)) {
354                                 // try with double slashes
355                                 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
356                                 logger('webfinger: pxrd: ' . $pxrd);
357                                 $links = fetch_xrd_links($pxrd);
358                         }
359                         return $links;
360                 }
361         }
362         return array();
363 }}
364
365 if(! function_exists('lrdd')) {
366 function lrdd($uri, $debug = false) {
367
368         $a = get_app();
369
370         // default priority is host priority, host-meta first
371
372         $priority = 'host';
373
374         // All we have is an email address. Resource-priority is irrelevant
375         // because our URI isn't directly resolvable.
376
377         if(strstr($uri,'@')) {
378                 return(webfinger($uri));
379         }
380
381         // get the host meta file
382
383         $host = @parse_url($uri);
384
385         if($host) {
386                 $url  = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
387                 $url .= $host['host'] . '/.well-known/host-meta' ;
388         }
389         else
390                 return array();
391
392         logger('lrdd: constructed url: ' . $url);
393
394         $xml = fetch_url($url);
395
396         $headers = $a->get_curl_headers();
397
398         if (! $xml)
399                 return array();
400
401         logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
402
403         if(! stristr($xml,'<xrd'))
404                 return array();
405
406         $h = parse_xml_string($xml);
407         if(! $h)
408                 return array();
409
410         $arr = convert_xml_element_to_array($h);
411
412         if(isset($arr['xrd']['property'])) {
413                 $property = $arr['crd']['property'];
414                 if(! isset($property[0]))
415                         $properties = array($property);
416                 else
417                         $properties = $property;
418                 foreach($properties as $prop)
419                         if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
420                                 $priority = 'resource';
421         }
422
423         // save the links in case we need them
424
425         $links = array();
426
427         if(isset($arr['xrd']['link'])) {
428                 $link = $arr['xrd']['link'];
429                 if(! isset($link[0]))
430                         $links = array($link);
431                 else
432                         $links = $link;
433         }
434
435         // do we have a template or href?
436
437         if(count($links)) {
438                 foreach($links as $link) {
439                         if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
440                                 if(x($link['@attributes'],'template'))
441                                         $tpl = $link['@attributes']['template'];
442                                 elseif(x($link['@attributes'],'href'))
443                                         $href = $link['@attributes']['href'];
444                         }
445                 }
446         }
447
448         if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
449                 $tpl = '';
450
451         if($priority === 'host') {
452                 if(strlen($tpl))
453                         $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
454                 elseif(isset($href))
455                         $pxrd = $href;
456                 if(isset($pxrd)) {
457                         logger('lrdd: (host priority) pxrd: ' . $pxrd);
458                         $links = fetch_xrd_links($pxrd);
459                         return $links;
460                 }
461
462                 $lines = explode("\n",$headers);
463                 if(count($lines)) {
464                         foreach($lines as $line) {
465                                 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
466                                         return(fetch_xrd_links($matches[1]));
467                                         break;
468                                 }
469                         }
470                 }
471         }
472
473
474         // priority 'resource'
475
476
477         $html = fetch_url($uri);
478         $headers = $a->get_curl_headers();
479         logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
480
481         // don't try and parse raw xml as html
482         if(! strstr($html,'<?xml')) {
483                 require_once('library/HTML5/Parser.php');
484
485                 try {
486                         $dom = HTML5_Parser::parse($html);
487                 } catch (DOMException $e) {
488                         logger('lrdd: parse error: ' . $e);
489                 }
490
491                 if(isset($dom) && $dom) {
492                         $items = $dom->getElementsByTagName('link');
493                         foreach($items as $item) {
494                                 $x = $item->getAttribute('rel');
495                                 if($x == "lrdd") {
496                                         $pagelink = $item->getAttribute('href');
497                                         break;
498                                 }
499                         }
500                 }
501         }
502
503         if(isset($pagelink))
504                 return(fetch_xrd_links($pagelink));
505
506         // next look in HTTP headers
507
508         $lines = explode("\n",$headers);
509         if(count($lines)) {
510                 foreach($lines as $line) {
511                         // TODO alter the following regex to support multiple relations (space separated)
512                         if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
513                                 $pagelink = $matches[1];
514                                 break;
515                         }
516                         // don't try and run feeds through the html5 parser
517                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
518                                 return array();
519                         if(stristr($html,'<rss') || stristr($html,'<feed'))
520                                 return array();
521                 }
522         }
523
524         if(isset($pagelink))
525                 return(fetch_xrd_links($pagelink));
526
527         // If we haven't found any links, return the host xrd links (which we have already fetched)
528
529         if(isset($links))
530                 return $links;
531
532         return array();
533
534 }}
535
536
537
538 // Given a host name, locate the LRDD template from that
539 // host. Returns the LRDD template or an empty string on
540 // error/failure.
541
542 if(! function_exists('fetch_lrdd_template')) {
543 function fetch_lrdd_template($host) {
544         $tpl = '';
545
546         $url1 = 'https://' . $host . '/.well-known/host-meta' ;
547         $url2 = 'http://' . $host . '/.well-known/host-meta' ;
548         $links = fetch_xrd_links($url1);
549         logger('fetch_lrdd_template from: ' . $url1);
550         logger('template (https): ' . print_r($links,true));
551         if(! count($links)) {
552                 logger('fetch_lrdd_template from: ' . $url2);
553                 $links = fetch_xrd_links($url2);
554                 logger('template (http): ' . print_r($links,true));
555         }
556         if(count($links)) {
557                 foreach($links as $link)
558                         if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
559                                 $tpl = $link['@attributes']['template'];
560         }
561         if(! strpos($tpl,'{uri}'))
562                 $tpl = '';
563         return $tpl;
564 }}
565
566 // Given a URL, retrieve the page as an XRD document.
567 // Return an array of links.
568 // on error/failure return empty array.
569
570 if(! function_exists('fetch_xrd_links')) {
571 function fetch_xrd_links($url) {
572
573         $xrd_timeout = intval(get_config('system','xrd_timeout'));
574         $redirects = 0;
575         $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
576
577         logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
578
579         if ((! $xml) || (! stristr($xml,'<xrd')))
580                 return array();
581
582         // fix diaspora's bad xml
583         $xml = str_replace(array('href=&quot;','&quot;/>'),array('href="','"/>'),$xml);
584
585         $h = parse_xml_string($xml);
586         if(! $h)
587                 return array();
588
589         $arr = convert_xml_element_to_array($h);
590
591         $links = array();
592
593         if(isset($arr['xrd']['link'])) {
594                 $link = $arr['xrd']['link'];
595                 if(! isset($link[0]))
596                         $links = array($link);
597                 else
598                         $links = $link;
599         }
600         if(isset($arr['xrd']['alias'])) {
601                 $alias = $arr['xrd']['alias'];
602                 if(! isset($alias[0]))
603                         $aliases = array($alias);
604                 else
605                         $aliases = $alias;
606                 if(is_array($aliases) && count($aliases)) {
607                         foreach($aliases as $alias) {
608                                 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
609                         }
610                 }
611         }
612
613         logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
614
615         return $links;
616
617 }}
618
619
620 // Take a URL from the wild, prepend http:// if necessary
621 // and check DNS to see if it's real (or check if is a valid IP address)
622 // return true if it's OK, false if something is wrong with it
623
624 if(! function_exists('validate_url')) {
625 function validate_url(&$url) {
626
627         if(get_config('system','disable_url_validation'))
628                 return true;
629         // no naked subdomains (allow localhost for tests)
630         if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
631                 return false;
632         if(substr($url,0,4) != 'http')
633                 $url = 'http://' . $url;
634         $h = @parse_url($url);
635
636         if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
637                 return true;
638         }
639         return false;
640 }}
641
642 // checks that email is an actual resolvable internet address
643
644 if(! function_exists('validate_email')) {
645 function validate_email($addr) {
646
647         if(get_config('system','disable_email_validation'))
648                 return true;
649
650         if(! strpos($addr,'@'))
651                 return false;
652         $h = substr($addr,strpos($addr,'@') + 1);
653
654         if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
655                 return true;
656         }
657         return false;
658 }}
659
660 // Check $url against our list of allowed sites,
661 // wildcards allowed. If allowed_sites is unset return true;
662 // If url is allowed, return true.
663 // otherwise, return false
664
665 if(! function_exists('allowed_url')) {
666 function allowed_url($url) {
667
668         $h = @parse_url($url);
669
670         if(! $h) {
671                 return false;
672         }
673
674         $str_allowed = get_config('system','allowed_sites');
675         if(! $str_allowed)
676                 return true;
677
678         $found = false;
679
680         $host = strtolower($h['host']);
681
682         // always allow our own site
683
684         if($host == strtolower($_SERVER['SERVER_NAME']))
685                 return true;
686
687         $fnmatch = function_exists('fnmatch');
688         $allowed = explode(',',$str_allowed);
689
690         if(count($allowed)) {
691                 foreach($allowed as $a) {
692                         $pat = strtolower(trim($a));
693                         if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
694                                 $found = true;
695                                 break;
696                         }
697                 }
698         }
699         return $found;
700 }}
701
702 // check if email address is allowed to register here.
703 // Compare against our list (wildcards allowed).
704 // Returns false if not allowed, true if allowed or if
705 // allowed list is not configured.
706
707 if(! function_exists('allowed_email')) {
708 function allowed_email($email) {
709
710
711         $domain = strtolower(substr($email,strpos($email,'@') + 1));
712         if(! $domain)
713                 return false;
714
715         $str_allowed = get_config('system','allowed_email');
716         if(! $str_allowed)
717                 return true;
718
719         $found = false;
720
721         $fnmatch = function_exists('fnmatch');
722         $allowed = explode(',',$str_allowed);
723
724         if(count($allowed)) {
725                 foreach($allowed as $a) {
726                         $pat = strtolower(trim($a));
727                         if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
728                                 $found = true;
729                                 break;
730                         }
731                 }
732         }
733         return $found;
734 }}
735
736
737 if(! function_exists('avatar_img')) {
738 function avatar_img($email) {
739
740         $a = get_app();
741
742         $avatar['size'] = 175;
743         $avatar['email'] = $email;
744         $avatar['url'] = '';
745         $avatar['success'] = false;
746
747         call_hooks('avatar_lookup', $avatar);
748
749         if(! $avatar['success'])
750                 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
751
752         logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
753         return $avatar['url'];
754 }}
755
756
757 if(! function_exists('parse_xml_string')) {
758 function parse_xml_string($s,$strict = true) {
759         if($strict) {
760                 if(! strstr($s,'<?xml'))
761                         return false;
762                 $s2 = substr($s,strpos($s,'<?xml'));
763         }
764         else
765                 $s2 = $s;
766         libxml_use_internal_errors(true);
767
768         $x = @simplexml_load_string($s2);
769         if(! $x) {
770                 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
771                 foreach(libxml_get_errors() as $err)
772                         logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
773                 libxml_clear_errors();
774         }
775         return $x;
776 }}
777
778 function add_fcontact($arr,$update = false) {
779
780         if($update) {
781                 $r = q("UPDATE `fcontact` SET
782                         `name` = '%s',
783                         `photo` = '%s',
784                         `request` = '%s',
785                         `nick` = '%s',
786                         `addr` = '%s',
787                         `batch` = '%s',
788                         `notify` = '%s',
789                         `poll` = '%s',
790                         `confirm` = '%s',
791                         `alias` = '%s',
792                         `pubkey` = '%s',
793                         `updated` = '%s'
794                         WHERE `url` = '%s' AND `network` = '%s'",
795                         dbesc($arr['name']),
796                         dbesc($arr['photo']),
797                         dbesc($arr['request']),
798                         dbesc($arr['nick']),
799                         dbesc($arr['addr']),
800                         dbesc($arr['batch']),
801                         dbesc($arr['notify']),
802                         dbesc($arr['poll']),
803                         dbesc($arr['confirm']),
804                         dbesc($arr['alias']),
805                         dbesc($arr['pubkey']),
806                         dbesc(datetime_convert()),
807                         dbesc($arr['url']),
808                         dbesc($arr['network'])
809                 );
810         }
811         else {
812                 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
813                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
814                         values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
815                         dbesc($arr['url']),
816                         dbesc($arr['name']),
817                         dbesc($arr['photo']),
818                         dbesc($arr['request']),
819                         dbesc($arr['nick']),
820                         dbesc($arr['addr']),
821                         dbesc($arr['batch']),
822                         dbesc($arr['notify']),
823                         dbesc($arr['poll']),
824                         dbesc($arr['confirm']),
825                         dbesc($arr['network']),
826                         dbesc($arr['alias']),
827                         dbesc($arr['pubkey']),
828                         dbesc(datetime_convert())
829                 );
830         }
831
832         return $r;
833 }
834
835
836 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
837
838         // Suppress "view full size"
839         if (intval(get_config('system','no_view_full_size')))
840                 $include_link = false;
841
842         $a = get_app();
843
844         // Picture addresses can contain special characters
845         $s = htmlspecialchars_decode($srctext);
846
847         $matches = null;
848         $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
849         if($c) {
850                 require_once('include/Photo.php');
851                 foreach($matches as $mtch) {
852                         logger('scale_external_image: ' . $mtch[1]);
853
854                         $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
855                         if(stristr($mtch[1],$hostname))
856                                 continue;
857
858                         // $scale_replace, if passed, is an array of two elements. The
859                         // first is the name of the full-size image. The second is the
860                         // name of a remote, scaled-down version of the full size image.
861                         // This allows Friendica to display the smaller remote image if
862                         // one exists, while still linking to the full-size image
863                         if($scale_replace)
864                                 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
865                         else
866                                 $scaled = $mtch[1];
867                         $i = @fetch_url($scaled);
868                         if(! $i)
869                                 return $srctext;
870
871                         $cachefile = get_cachefile(hash("md5", $scaled));
872                         if ($cachefile != '') {
873                                 $stamp1 = microtime(true);
874                                 file_put_contents($cachefile, $i);
875                                 $a->save_timestamp($stamp1, "file");
876                         }
877
878                         // guess mimetype from headers or filename
879                         $type = guess_image_type($mtch[1],true);
880
881                         if($i) {
882                                 $ph = new Photo($i, $type);
883                                 if($ph->is_valid()) {
884                                         $orig_width = $ph->getWidth();
885                                         $orig_height = $ph->getHeight();
886
887                                         if($orig_width > 640 || $orig_height > 640) {
888
889                                                 $ph->scaleImage(640);
890                                                 $new_width = $ph->getWidth();
891                                                 $new_height = $ph->getHeight();
892                                                 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
893                                                 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
894                                                         . "\n" . (($include_link)
895                                                                 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
896                                                                 : ''),$s);
897                                                 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
898                                         }
899                                 }
900                         }
901                 }
902         }
903
904         // replace the special char encoding
905         $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
906         return $s;
907 }
908
909
910 function fix_contact_ssl_policy(&$contact,$new_policy) {
911
912         $ssl_changed = false;
913         if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
914                 $ssl_changed = true;
915                 $contact['url']     =   str_replace('https:','http:',$contact['url']);
916                 $contact['request'] =   str_replace('https:','http:',$contact['request']);
917                 $contact['notify']  =   str_replace('https:','http:',$contact['notify']);
918                 $contact['poll']    =   str_replace('https:','http:',$contact['poll']);
919                 $contact['confirm'] =   str_replace('https:','http:',$contact['confirm']);
920                 $contact['poco']    =   str_replace('https:','http:',$contact['poco']);
921         }
922
923         if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
924                 $ssl_changed = true;
925                 $contact['url']     =   str_replace('http:','https:',$contact['url']);
926                 $contact['request'] =   str_replace('http:','https:',$contact['request']);
927                 $contact['notify']  =   str_replace('http:','https:',$contact['notify']);
928                 $contact['poll']    =   str_replace('http:','https:',$contact['poll']);
929                 $contact['confirm'] =   str_replace('http:','https:',$contact['confirm']);
930                 $contact['poco']    =   str_replace('http:','https:',$contact['poco']);
931         }
932
933         if($ssl_changed) {
934                 q("update contact set
935                         url = '%s',
936                         request = '%s',
937                         notify = '%s',
938                         poll = '%s',
939                         confirm = '%s',
940                         poco = '%s'
941                         where id = %d limit 1",
942                         dbesc($contact['url']),
943                         dbesc($contact['request']),
944                         dbesc($contact['notify']),
945                         dbesc($contact['poll']),
946                         dbesc($contact['confirm']),
947                         dbesc($contact['poco']),
948                         intval($contact['id'])
949                 );
950         }
951 }
952
953
954
955 /**
956  * xml2array() will convert the given XML text to an array in the XML structure.
957  * Link: http://www.bin-co.com/php/scripts/xml2array/
958  * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
959  * Arguments : $contents - The XML text
960  *                $namespaces - true or false include namespace information in the returned array as array elements.
961  *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
962  *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
963  * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
964  * Examples: $array =  xml2array(file_get_contents('feed.xml'));
965  *              $array =  xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
966  */
967
968 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
969     if(!$contents) return array();
970
971     if(!function_exists('xml_parser_create')) {
972         logger('xml2array: parser function missing');
973         return array();
974     }
975
976
977         libxml_use_internal_errors(true);
978         libxml_clear_errors();
979
980         if($namespaces)
981             $parser = @xml_parser_create_ns("UTF-8",':');
982         else
983             $parser = @xml_parser_create();
984
985         if(! $parser) {
986                 logger('xml2array: xml_parser_create: no resource');
987                 return array();
988         }
989
990     xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
991         // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
992     xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
993     xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
994     @xml_parse_into_struct($parser, trim($contents), $xml_values);
995     @xml_parser_free($parser);
996
997     if(! $xml_values) {
998                 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
999                 foreach(libxml_get_errors() as $err)
1000                         logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
1001                 libxml_clear_errors();
1002                 return;
1003         }
1004
1005     //Initializations
1006     $xml_array = array();
1007     $parents = array();
1008     $opened_tags = array();
1009     $arr = array();
1010
1011     $current = &$xml_array; // Reference
1012
1013     // Go through the tags.
1014     $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1015     foreach($xml_values as $data) {
1016         unset($attributes,$value); // Remove existing values, or there will be trouble
1017
1018         // This command will extract these variables into the foreach scope
1019         // tag(string), type(string), level(int), attributes(array).
1020         extract($data); // We could use the array by itself, but this cooler.
1021
1022         $result = array();
1023         $attributes_data = array();
1024
1025         if(isset($value)) {
1026             if($priority == 'tag') $result = $value;
1027             else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1028         }
1029
1030         //Set the attributes too.
1031         if(isset($attributes) and $get_attributes) {
1032             foreach($attributes as $attr => $val) {
1033                 if($priority == 'tag') $attributes_data[$attr] = $val;
1034                 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1035             }
1036         }
1037
1038         // See tag status and do the needed.
1039                 if($namespaces && strpos($tag,':')) {
1040                         $namespc = substr($tag,0,strrpos($tag,':'));
1041                         $tag = strtolower(substr($tag,strlen($namespc)+1));
1042                         $result['@namespace'] = $namespc;
1043                 }
1044                 $tag = strtolower($tag);
1045
1046                 if($type == "open") {   // The starting of the tag '<tag>'
1047             $parent[$level-1] = &$current;
1048             if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1049                 $current[$tag] = $result;
1050                 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1051                 $repeated_tag_index[$tag.'_'.$level] = 1;
1052
1053                 $current = &$current[$tag];
1054
1055             } else { // There was another element with the same tag name
1056
1057                 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1058                     $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1059                     $repeated_tag_index[$tag.'_'.$level]++;
1060                 } else { // This section will make the value an array if multiple tags with the same name appear together
1061                     $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1062                     $repeated_tag_index[$tag.'_'.$level] = 2;
1063
1064                     if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1065                         $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1066                         unset($current[$tag.'_attr']);
1067                     }
1068
1069                 }
1070                 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1071                 $current = &$current[$tag][$last_item_index];
1072             }
1073
1074         } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1075             //See if the key is already taken.
1076             if(!isset($current[$tag])) { //New Key
1077                 $current[$tag] = $result;
1078                 $repeated_tag_index[$tag.'_'.$level] = 1;
1079                 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1080
1081             } else { // If taken, put all things inside a list(array)
1082                 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1083
1084                     // ...push the new element into that array.
1085                     $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1086
1087                     if($priority == 'tag' and $get_attributes and $attributes_data) {
1088                         $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1089                     }
1090                     $repeated_tag_index[$tag.'_'.$level]++;
1091
1092                 } else { // If it is not an array...
1093                     $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1094                     $repeated_tag_index[$tag.'_'.$level] = 1;
1095                     if($priority == 'tag' and $get_attributes) {
1096                         if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1097
1098                             $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1099                             unset($current[$tag.'_attr']);
1100                         }
1101
1102                         if($attributes_data) {
1103                             $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1104                         }
1105                     }
1106                     $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1107                 }
1108             }
1109
1110         } elseif($type == 'close') { // End of tag '</tag>'
1111             $current = &$parent[$level-1];
1112         }
1113     }
1114
1115     return($xml_array);
1116 }
1117
1118 function original_url($url, $depth=1, $fetchbody = false) {
1119
1120         $a = get_app();
1121
1122         // Remove Analytics Data from Google and other tracking platforms
1123         $urldata = parse_url($url);
1124         if (is_string($urldata["query"])) {
1125                 $query = $urldata["query"];
1126                 parse_str($query, $querydata);
1127
1128                 if (is_array($querydata))
1129                         foreach ($querydata AS $param=>$value)
1130                                 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1131                                                         "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1132                                                         "fb_action_ids", "fb_action_types", "fb_ref",
1133                                                         "awesm", "wtrid",
1134                                                         "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1135
1136                                         $pair = $param."=".urlencode($value);
1137                                         $url = str_replace($pair, "", $url);
1138
1139                                         // Second try: if the url isn't encoded completely
1140                                         $pair = $param."=".str_replace(" ", "+", $value);
1141                                         $url = str_replace($pair, "", $url);
1142
1143                                         // Third try: Maybey the url isn't encoded at all
1144                                         $pair = $param."=".$value;
1145                                         $url = str_replace($pair, "", $url);
1146
1147                                         $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1148                                 }
1149
1150                 if (substr($url, -1, 1) == "?")
1151                         $url = substr($url, 0, -1);
1152         }
1153
1154         if ($depth > 10)
1155                 return($url);
1156
1157         $url = trim($url, "'");
1158
1159         $siteinfo = array();
1160         $ch = curl_init();
1161         curl_setopt($ch, CURLOPT_URL, $url);
1162         curl_setopt($ch, CURLOPT_HEADER, 1);
1163         curl_setopt($ch, CURLOPT_NOBODY, 1);
1164         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1165         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1166         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1167
1168         $header = curl_exec($ch);
1169         $curl_info = @curl_getinfo($ch);
1170         $http_code = $curl_info['http_code'];
1171         curl_close($ch);
1172
1173         if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1174                 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1175                 if ($curl_info['redirect_url'] != "")
1176                         return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1177                 else
1178                         return(original_url($curl_info['location'], ++$depth, $fetchbody));
1179         }
1180
1181         // Check for redirects in the meta elements of the body if there are no redirects in the header.
1182         if (!$fetchbody)
1183                 return(original_url($url, ++$depth, true));
1184
1185         // if the file is too large then exit
1186         if ($curl_info["download_content_length"] > 1000000)
1187                 return($url);
1188
1189         // if it isn't a HTML file then exit
1190         if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
1191                 return($url);
1192
1193         $ch = curl_init();
1194         curl_setopt($ch, CURLOPT_URL, $url);
1195         curl_setopt($ch, CURLOPT_HEADER, 0);
1196         curl_setopt($ch, CURLOPT_NOBODY, 0);
1197         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1198         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1199         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1200
1201         $body = curl_exec($ch);
1202         curl_close($ch);
1203
1204         if (trim($body) == "")
1205                 return($url);
1206
1207         // Check for redirect in meta elements
1208         $doc = new DOMDocument();
1209         @$doc->loadHTML($body);
1210
1211         $xpath = new DomXPath($doc);
1212
1213         $list = $xpath->query("//meta[@content]");
1214         foreach ($list as $node) {
1215                 $attr = array();
1216                 if ($node->attributes->length)
1217                         foreach ($node->attributes as $attribute)
1218                                 $attr[$attribute->name] = $attribute->value;
1219
1220                 if (@$attr["http-equiv"] == 'refresh') {
1221                         $path = $attr["content"];
1222                         $pathinfo = explode(";", $path);
1223                         $content = "";
1224                         foreach ($pathinfo AS $value)
1225                                 if (substr(strtolower($value), 0, 4) == "url=")
1226                                         return(original_url(substr($value, 4), ++$depth));
1227                 }
1228         }
1229
1230         return($url);
1231 }
1232
1233 if (!function_exists('short_link')) {
1234 function short_link($url) {
1235         require_once('library/slinky.php');
1236         $slinky = new Slinky($url);
1237         $yourls_url = get_config('yourls','url1');
1238         if ($yourls_url) {
1239                 $yourls_username = get_config('yourls','username1');
1240                 $yourls_password = get_config('yourls', 'password1');
1241                 $yourls_ssl = get_config('yourls', 'ssl1');
1242                 $yourls = new Slinky_YourLS();
1243                 $yourls->set('username', $yourls_username);
1244                 $yourls->set('password', $yourls_password);
1245                 $yourls->set('ssl', $yourls_ssl);
1246                 $yourls->set('yourls-url', $yourls_url);
1247                 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1248         } else {
1249                 // setup a cascade of shortening services
1250                 // try to get a short link from these services
1251                 // in the order ur1.ca, trim, id.gd, tinyurl
1252                 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1253         }
1254         return $slinky->short();
1255 }};