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