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