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