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