]> git.mxchange.org Git - friendica.git/blob - include/network.php
e4d01c00fb46ea1a2cc3064a7da72ff809c3a746
[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
105         $body = substr($s,strlen($header));
106         $a->set_curl_headers($header);
107         @curl_close($ch);
108
109         $a->save_timestamp($stamp1, "network");
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         if (filter_var($newurl, FILTER_VALIDATE_URL)) {
192             $redirects++;
193             return fetch_url($newurl,false,$redirects,$timeout);
194         }
195     }
196         $a->set_curl_code($http_code);
197         $body = substr($s,strlen($header));
198
199         $a->set_curl_headers($header);
200
201         curl_close($ch);
202
203         $a->save_timestamp($stamp1, "network");
204
205         return($body);
206 }}
207
208 // Generic XML return
209 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable 
210 // of $st and an optional text <message> of $message and terminates the current process. 
211
212 if(! function_exists('xml_status')) {
213 function xml_status($st, $message = '') {
214
215         $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
216
217         if($st)
218                 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
219
220         header( "Content-type: text/xml" );
221         echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
222         echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
223         killme();
224 }}
225
226
227 if(! function_exists('http_status_exit')) {
228 function http_status_exit($val) {
229
230     $err = '';
231         if($val >= 400)
232                 $err = 'Error';
233         if($val >= 200 && $val < 300)
234                 $err = 'OK';
235
236         logger('http_status_exit ' . $val);     
237         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
238         killme();
239
240 }}
241
242
243 // convert an XML document to a normalised, case-corrected array
244 // used by webfinger
245
246 if(! function_exists('convert_xml_element_to_array')) {
247 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
248
249         // If we're getting too deep, bail out
250         if ($recursion_depth > 512) {
251                 return(null);
252         }
253
254         if (!is_string($xml_element) &&
255         !is_array($xml_element) &&
256         (get_class($xml_element) == 'SimpleXMLElement')) {
257                 $xml_element_copy = $xml_element;
258                 $xml_element = get_object_vars($xml_element);
259         }
260
261         if (is_array($xml_element)) {
262                 $result_array = array();
263                 if (count($xml_element) <= 0) {
264                         return (trim(strval($xml_element_copy)));
265                 }
266
267                 foreach($xml_element as $key=>$value) {
268
269                         $recursion_depth++;
270                         $result_array[strtolower($key)] =
271                 convert_xml_element_to_array($value, $recursion_depth);
272                         $recursion_depth--;
273                 }
274                 if ($recursion_depth == 0) {
275                         $temp_array = $result_array;
276                         $result_array = array(
277                                 strtolower($xml_element_copy->getName()) => $temp_array,
278                         );
279                 }
280
281                 return ($result_array);
282
283         } else {
284                 return (trim(strval($xml_element)));
285         }
286 }}
287
288 // Given an email style address, perform webfinger lookup and 
289 // return the resulting DFRN profile URL, or if no DFRN profile URL
290 // is located, returns an OStatus subscription template (prefixed 
291 // with the string 'stat:' to identify it as on OStatus template).
292 // If this isn't an email style address just return $s.
293 // Return an empty string if email-style addresses but webfinger fails,
294 // or if the resultant personal XRD doesn't contain a supported 
295 // subscription/friend-request attribute.
296
297 // amended 7/9/2011 to return an hcard which could save potentially loading 
298 // a lengthy content page to scrape dfrn attributes
299
300 if(! function_exists('webfinger_dfrn')) {
301 function webfinger_dfrn($s,&$hcard) {
302         if(! strstr($s,'@')) {
303                 return $s;
304         }
305         $profile_link = '';
306
307         $links = webfinger($s);
308         logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
309         if(count($links)) {
310                 foreach($links as $link) {
311                         if($link['@attributes']['rel'] === NAMESPACE_DFRN)
312                                 $profile_link = $link['@attributes']['href'];
313                         if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
314                                 $profile_link = 'stat:' . $link['@attributes']['template'];
315                         if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
316                                 $hcard = $link['@attributes']['href'];
317                 }
318         }
319         return $profile_link;
320 }}
321
322 // Given an email style address, perform webfinger lookup and 
323 // return the array of link attributes from the personal XRD file.
324 // On error/failure return an empty array.
325
326
327 if(! function_exists('webfinger')) {
328 function webfinger($s, $debug = false) {
329         $host = '';
330         if(strstr($s,'@')) {
331                 $host = substr($s,strpos($s,'@') + 1);
332         }
333         if(strlen($host)) {
334                 $tpl = fetch_lrdd_template($host);
335                 logger('webfinger: lrdd template: ' . $tpl);
336                 if(strlen($tpl)) {
337                         $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
338                         logger('webfinger: pxrd: ' . $pxrd);
339                         $links = fetch_xrd_links($pxrd);
340                         if(! count($links)) {
341                                 // try with double slashes
342                                 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
343                                 logger('webfinger: pxrd: ' . $pxrd);
344                                 $links = fetch_xrd_links($pxrd);
345                         }
346                         return $links;
347                 }
348         }
349         return array();
350 }}
351
352 if(! function_exists('lrdd')) {
353 function lrdd($uri, $debug = false) {
354
355         $a = get_app();
356
357         // default priority is host priority, host-meta first
358
359         $priority = 'host';
360
361         // All we have is an email address. Resource-priority is irrelevant
362         // because our URI isn't directly resolvable.
363
364         if(strstr($uri,'@')) {  
365                 return(webfinger($uri));
366         }
367
368         // get the host meta file
369
370         $host = @parse_url($uri);
371
372         if($host) {
373                 $url  = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
374                 $url .= $host['host'] . '/.well-known/host-meta' ;
375         }
376         else
377                 return array();
378
379         logger('lrdd: constructed url: ' . $url);
380
381         $xml = fetch_url($url);
382
383         $headers = $a->get_curl_headers();
384
385         if (! $xml)
386                 return array();
387
388         logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
389
390         if(! stristr($xml,'<xrd'))
391                 return array();
392
393         $h = parse_xml_string($xml);
394         if(! $h)
395                 return array();
396
397         $arr = convert_xml_element_to_array($h);
398
399         if(isset($arr['xrd']['property'])) {
400                 $property = $arr['crd']['property'];
401                 if(! isset($property[0]))
402                         $properties = array($property);
403                 else
404                         $properties = $property;
405                 foreach($properties as $prop)
406                         if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
407                                 $priority = 'resource';
408         } 
409
410         // save the links in case we need them
411
412         $links = array();
413
414         if(isset($arr['xrd']['link'])) {
415                 $link = $arr['xrd']['link'];
416                 if(! isset($link[0]))
417                         $links = array($link);
418                 else
419                         $links = $link;
420         }
421
422         // do we have a template or href?
423
424         if(count($links)) {
425                 foreach($links as $link) {
426                         if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
427                                 if(x($link['@attributes'],'template'))
428                                         $tpl = $link['@attributes']['template'];
429                                 elseif(x($link['@attributes'],'href'))
430                                         $href = $link['@attributes']['href'];
431                         }
432                 }
433         }
434
435         if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
436                 $tpl = '';
437
438         if($priority === 'host') {
439                 if(strlen($tpl)) 
440                         $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
441                 elseif(isset($href))
442                         $pxrd = $href;
443                 if(isset($pxrd)) {
444                         logger('lrdd: (host priority) pxrd: ' . $pxrd);
445                         $links = fetch_xrd_links($pxrd);
446                         return $links;
447                 }
448
449                 $lines = explode("\n",$headers);
450                 if(count($lines)) {
451                         foreach($lines as $line) {
452                                 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
453                                         return(fetch_xrd_links($matches[1]));
454                                         break;
455                                 }
456                         }
457                 }
458         }
459
460
461         // priority 'resource'
462
463
464         $html = fetch_url($uri);
465         $headers = $a->get_curl_headers();
466         logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
467
468         // don't try and parse raw xml as html
469         if(! strstr($html,'<?xml')) {
470                 require_once('library/HTML5/Parser.php');
471
472                 try {
473                         $dom = HTML5_Parser::parse($html);
474                 } catch (DOMException $e) {
475                         logger('lrdd: parse error: ' . $e);
476                 }
477
478                 if(isset($dom) && $dom) {
479                         $items = $dom->getElementsByTagName('link');
480                         foreach($items as $item) {
481                                 $x = $item->getAttribute('rel');
482                                 if($x == "lrdd") {
483                                         $pagelink = $item->getAttribute('href');
484                                         break;
485                                 }
486                         }
487                 }
488         }
489
490         if(isset($pagelink))
491                 return(fetch_xrd_links($pagelink));
492
493         // next look in HTTP headers
494
495         $lines = explode("\n",$headers);
496         if(count($lines)) {
497                 foreach($lines as $line) {
498                         // TODO alter the following regex to support multiple relations (space separated)
499                         if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
500                                 $pagelink = $matches[1];
501                                 break;
502                         }
503                         // don't try and run feeds through the html5 parser
504                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
505                                 return array();
506                         if(stristr($html,'<rss') || stristr($html,'<feed'))
507                                 return array();
508                 }
509         }
510
511         if(isset($pagelink))
512                 return(fetch_xrd_links($pagelink));
513
514         // If we haven't found any links, return the host xrd links (which we have already fetched)
515
516         if(isset($links))
517                 return $links;
518
519         return array();
520
521 }}
522
523
524
525 // Given a host name, locate the LRDD template from that
526 // host. Returns the LRDD template or an empty string on
527 // error/failure.
528
529 if(! function_exists('fetch_lrdd_template')) {
530 function fetch_lrdd_template($host) {
531         $tpl = '';
532
533         $url1 = 'https://' . $host . '/.well-known/host-meta' ;
534         $url2 = 'http://' . $host . '/.well-known/host-meta' ;
535         $links = fetch_xrd_links($url1);
536         logger('fetch_lrdd_template from: ' . $url1);
537         logger('template (https): ' . print_r($links,true));
538         if(! count($links)) {
539                 logger('fetch_lrdd_template from: ' . $url2);
540                 $links = fetch_xrd_links($url2);
541                 logger('template (http): ' . print_r($links,true));
542         }
543         if(count($links)) {
544                 foreach($links as $link)
545                         if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
546                                 $tpl = $link['@attributes']['template'];
547         }
548         if(! strpos($tpl,'{uri}'))
549                 $tpl = '';
550         return $tpl;
551 }}
552
553 // Given a URL, retrieve the page as an XRD document.
554 // Return an array of links.
555 // on error/failure return empty array.
556
557 if(! function_exists('fetch_xrd_links')) {
558 function fetch_xrd_links($url) {
559
560         $xrd_timeout = intval(get_config('system','xrd_timeout'));
561         $redirects = 0;
562         $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
563
564         logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
565
566         if ((! $xml) || (! stristr($xml,'<xrd')))
567                 return array();
568
569         // fix diaspora's bad xml
570         $xml = str_replace(array('href=&quot;','&quot;/>'),array('href="','"/>'),$xml);
571
572         $h = parse_xml_string($xml);
573         if(! $h)
574                 return array();
575
576         $arr = convert_xml_element_to_array($h);
577
578         $links = array();
579
580         if(isset($arr['xrd']['link'])) {
581                 $link = $arr['xrd']['link'];
582                 if(! isset($link[0]))
583                         $links = array($link);
584                 else
585                         $links = $link;
586         }
587         if(isset($arr['xrd']['alias'])) {
588                 $alias = $arr['xrd']['alias'];
589                 if(! isset($alias[0]))
590                         $aliases = array($alias);
591                 else
592                         $aliases = $alias;
593                 if(is_array($aliases) && count($aliases)) {
594                         foreach($aliases as $alias) {
595                                 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
596                         }
597                 }
598         }
599
600         logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
601
602         return $links;
603
604 }}
605
606
607 // Take a URL from the wild, prepend http:// if necessary
608 // and check DNS to see if it's real (or check if is a valid IP address)
609 // return true if it's OK, false if something is wrong with it
610
611 if(! function_exists('validate_url')) {
612 function validate_url(&$url) {
613
614         // no naked subdomains (allow localhost for tests)
615         if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
616                 return false;
617         if(substr($url,0,4) != 'http')
618                 $url = 'http://' . $url;
619         $h = @parse_url($url);
620
621         if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
622                 return true;
623         }
624         return false;
625 }}
626
627 // checks that email is an actual resolvable internet address
628
629 if(! function_exists('validate_email')) {
630 function validate_email($addr) {
631
632         if(get_config('system','disable_email_validation'))
633                 return true;
634
635         if(! strpos($addr,'@'))
636                 return false;
637         $h = substr($addr,strpos($addr,'@') + 1);
638
639         if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
640                 return true;
641         }
642         return false;
643 }}
644
645 // Check $url against our list of allowed sites,
646 // wildcards allowed. If allowed_sites is unset return true;
647 // If url is allowed, return true.
648 // otherwise, return false
649
650 if(! function_exists('allowed_url')) {
651 function allowed_url($url) {
652
653         $h = @parse_url($url);
654
655         if(! $h) {
656                 return false;
657         }
658
659         $str_allowed = get_config('system','allowed_sites');
660         if(! $str_allowed)
661                 return true;
662
663         $found = false;
664
665         $host = strtolower($h['host']);
666
667         // always allow our own site
668
669         if($host == strtolower($_SERVER['SERVER_NAME']))
670                 return true;
671
672         $fnmatch = function_exists('fnmatch');
673         $allowed = explode(',',$str_allowed);
674
675         if(count($allowed)) {
676                 foreach($allowed as $a) {
677                         $pat = strtolower(trim($a));
678                         if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
679                                 $found = true; 
680                                 break;
681                         }
682                 }
683         }
684         return $found;
685 }}
686
687 // check if email address is allowed to register here.
688 // Compare against our list (wildcards allowed).
689 // Returns false if not allowed, true if allowed or if
690 // allowed list is not configured.
691
692 if(! function_exists('allowed_email')) {
693 function allowed_email($email) {
694
695
696         $domain = strtolower(substr($email,strpos($email,'@') + 1));
697         if(! $domain)
698                 return false;
699
700         $str_allowed = get_config('system','allowed_email');
701         if(! $str_allowed)
702                 return true;
703
704         $found = false;
705
706         $fnmatch = function_exists('fnmatch');
707         $allowed = explode(',',$str_allowed);
708
709         if(count($allowed)) {
710                 foreach($allowed as $a) {
711                         $pat = strtolower(trim($a));
712                         if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
713                                 $found = true; 
714                                 break;
715                         }
716                 }
717         }
718         return $found;
719 }}
720
721
722 if(! function_exists('avatar_img')) {
723 function avatar_img($email) {
724
725         $a = get_app();
726
727         $avatar['size'] = 175;
728         $avatar['email'] = $email;
729         $avatar['url'] = '';
730         $avatar['success'] = false;
731
732         call_hooks('avatar_lookup', $avatar);
733
734         if(! $avatar['success'])
735                 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
736
737         logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
738         return $avatar['url'];
739 }}
740
741
742 if(! function_exists('parse_xml_string')) {
743 function parse_xml_string($s,$strict = true) {
744         if($strict) {
745                 if(! strstr($s,'<?xml'))
746                         return false;
747                 $s2 = substr($s,strpos($s,'<?xml'));
748         }
749         else
750                 $s2 = $s;
751         libxml_use_internal_errors(true);
752
753         $x = @simplexml_load_string($s2);
754         if(! $x) {
755                 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
756                 foreach(libxml_get_errors() as $err)
757                         logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
758                 libxml_clear_errors();
759         }
760         return $x;
761 }}
762
763 function add_fcontact($arr,$update = false) {
764
765         if($update) {
766                 $r = q("UPDATE `fcontact` SET
767                         `name` = '%s',
768                         `photo` = '%s',
769                         `request` = '%s',
770                         `nick` = '%s',
771                         `addr` = '%s',
772                         `batch` = '%s',
773                         `notify` = '%s',
774                         `poll` = '%s',
775                         `confirm` = '%s',
776                         `alias` = '%s',
777                         `pubkey` = '%s',
778                         `updated` = '%s'
779                         WHERE `url` = '%s' AND `network` = '%s' LIMIT 1", 
780                         dbesc($arr['name']),
781                         dbesc($arr['photo']),
782                         dbesc($arr['request']),
783                         dbesc($arr['nick']),
784                         dbesc($arr['addr']),
785                         dbesc($arr['batch']),
786                         dbesc($arr['notify']),
787                         dbesc($arr['poll']),
788                         dbesc($arr['confirm']),
789                         dbesc($arr['alias']),
790                         dbesc($arr['pubkey']),
791                         dbesc(datetime_convert()),
792                         dbesc($arr['url']),
793                         dbesc($arr['network'])
794                 );
795         }
796         else {
797                 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
798                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
799                         values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
800                         dbesc($arr['url']),
801                         dbesc($arr['name']),
802                         dbesc($arr['photo']),
803                         dbesc($arr['request']),
804                         dbesc($arr['nick']),
805                         dbesc($arr['addr']),
806                         dbesc($arr['batch']),
807                         dbesc($arr['notify']),
808                         dbesc($arr['poll']),
809                         dbesc($arr['confirm']),
810                         dbesc($arr['network']),
811                         dbesc($arr['alias']),
812                         dbesc($arr['pubkey']),
813                         dbesc(datetime_convert())
814                 );
815         }
816
817         return $r;
818 }
819
820
821 function scale_external_images($s, $include_link = true, $scale_replace = false) {
822
823         $a = get_app();
824
825         // Picture addresses can contain special characters
826         $s = htmlspecialchars_decode($s);
827
828         $matches = null;
829         $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
830         if($c) {
831                 require_once('include/Photo.php');
832                 foreach($matches as $mtch) {
833                         logger('scale_external_image: ' . $mtch[1]);
834
835                         $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
836                         if(stristr($mtch[1],$hostname))
837                                 continue;
838
839                         // $scale_replace, if passed, is an array of two elements. The
840                         // first is the name of the full-size image. The second is the
841                         // name of a remote, scaled-down version of the full size image.
842                         // This allows Friendica to display the smaller remote image if
843                         // one exists, while still linking to the full-size image
844                         if($scale_replace)
845                                 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
846                         else
847                                 $scaled = $mtch[1];
848                         $i = fetch_url($scaled);
849
850                         $cachefile = get_cachefile(hash("md5", $scaled));
851                         if ($cachefile != '') {
852                                 $stamp1 = microtime(true);
853                                 file_put_contents($cachefile, $i);
854                                 $a->save_timestamp($stamp1, "file");
855                         }
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 }