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