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