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