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