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