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