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