]> git.mxchange.org Git - friendica.git/blob - include/network.php
8c678a443a6b9840b122a123b6435af8be2312cb
[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,$binary,$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         if($val >= 400)
210                 $err = 'Error';
211         if($val >= 200 && $val < 300)
212                 $err = 'OK';
213
214         logger('http_status_exit ' . $val);     
215         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
216         killme();
217
218 }}
219
220
221 // convert an XML document to a normalised, case-corrected array
222 // used by webfinger
223
224 if(! function_exists('convert_xml_element_to_array')) {
225 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
226
227         // If we're getting too deep, bail out
228         if ($recursion_depth > 512) {
229                 return(null);
230         }
231
232         if (!is_string($xml_element) &&
233         !is_array($xml_element) &&
234         (get_class($xml_element) == 'SimpleXMLElement')) {
235                 $xml_element_copy = $xml_element;
236                 $xml_element = get_object_vars($xml_element);
237         }
238
239         if (is_array($xml_element)) {
240                 $result_array = array();
241                 if (count($xml_element) <= 0) {
242                         return (trim(strval($xml_element_copy)));
243                 }
244
245                 foreach($xml_element as $key=>$value) {
246
247                         $recursion_depth++;
248                         $result_array[strtolower($key)] =
249                 convert_xml_element_to_array($value, $recursion_depth);
250                         $recursion_depth--;
251                 }
252                 if ($recursion_depth == 0) {
253                         $temp_array = $result_array;
254                         $result_array = array(
255                                 strtolower($xml_element_copy->getName()) => $temp_array,
256                         );
257                 }
258
259                 return ($result_array);
260
261         } else {
262                 return (trim(strval($xml_element)));
263         }
264 }}
265
266 // Given an email style address, perform webfinger lookup and 
267 // return the resulting DFRN profile URL, or if no DFRN profile URL
268 // is located, returns an OStatus subscription template (prefixed 
269 // with the string 'stat:' to identify it as on OStatus template).
270 // If this isn't an email style address just return $s.
271 // Return an empty string if email-style addresses but webfinger fails,
272 // or if the resultant personal XRD doesn't contain a supported 
273 // subscription/friend-request attribute.
274
275 // amended 7/9/2011 to return an hcard which could save potentially loading 
276 // a lengthy content page to scrape dfrn attributes
277
278 if(! function_exists('webfinger_dfrn')) {
279 function webfinger_dfrn($s,&$hcard) {
280         if(! strstr($s,'@')) {
281                 return $s;
282         }
283         $profile_link = '';
284
285         $links = webfinger($s);
286         logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
287         if(count($links)) {
288                 foreach($links as $link) {
289                         if($link['@attributes']['rel'] === NAMESPACE_DFRN)
290                                 $profile_link = $link['@attributes']['href'];
291                         if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
292                                 $profile_link = 'stat:' . $link['@attributes']['template'];     
293                         if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
294                                 $hcard = $link['@attributes']['href'];                          
295                 }
296         }
297         return $profile_link;
298 }}
299
300 // Given an email style address, perform webfinger lookup and 
301 // return the array of link attributes from the personal XRD file.
302 // On error/failure return an empty array.
303
304
305 if(! function_exists('webfinger')) {
306 function webfinger($s, $debug = false) {
307         $host = '';
308         if(strstr($s,'@')) {
309                 $host = substr($s,strpos($s,'@') + 1);
310         }
311         if(strlen($host)) {
312                 $tpl = fetch_lrdd_template($host);
313                 logger('webfinger: lrdd template: ' . $tpl);
314                 if(strlen($tpl)) {
315                         $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
316                         logger('webfinger: pxrd: ' . $pxrd);
317                         $links = fetch_xrd_links($pxrd);
318                         if(! count($links)) {
319                                 // try with double slashes
320                                 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
321                                 logger('webfinger: pxrd: ' . $pxrd);
322                                 $links = fetch_xrd_links($pxrd);
323                         }
324                         return $links;
325                 }
326         }
327         return array();
328 }}
329
330 if(! function_exists('lrdd')) {
331 function lrdd($uri, $debug = false) {
332
333         $a = get_app();
334
335         // default priority is host priority, host-meta first
336
337         $priority = 'host';
338
339         // All we have is an email address. Resource-priority is irrelevant
340         // because our URI isn't directly resolvable.
341
342         if(strstr($uri,'@')) {  
343                 return(webfinger($uri));
344         }
345
346         // get the host meta file
347
348         $host = @parse_url($uri);
349
350         if($host) {
351                 $url  = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
352                 $url .= $host['host'] . '/.well-known/host-meta' ;
353         }
354         else
355                 return array();
356
357         logger('lrdd: constructed url: ' . $url);
358
359         $xml = fetch_url($url);
360         $headers = $a->get_curl_headers();
361
362         if (! $xml)
363                 return array();
364
365         logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
366
367         if(! stristr($xml,'<xrd'))
368                 return array();
369
370         $h = parse_xml_string($xml);
371         if(! $h)
372                 return array();
373
374         $arr = convert_xml_element_to_array($h);
375
376         if(isset($arr['xrd']['property'])) {
377                 $property = $arr['crd']['property'];
378                 if(! isset($property[0]))
379                         $properties = array($property);
380                 else
381                         $properties = $property;
382                 foreach($properties as $prop)
383                         if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
384                                 $priority = 'resource';
385         } 
386
387         // save the links in case we need them
388
389         $links = array();
390
391         if(isset($arr['xrd']['link'])) {
392                 $link = $arr['xrd']['link'];
393                 if(! isset($link[0]))
394                         $links = array($link);
395                 else
396                         $links = $link;
397         }
398
399         // do we have a template or href?
400
401         if(count($links)) {
402                 foreach($links as $link) {
403                         if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
404                                 if(x($link['@attributes'],'template'))
405                                         $tpl = $link['@attributes']['template'];
406                                 elseif(x($link['@attributes'],'href'))
407                                         $href = $link['@attributes']['href'];
408                         }
409                 }               
410         }
411
412         if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
413                 $tpl = '';
414
415         if($priority === 'host') {
416                 if(strlen($tpl)) 
417                         $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
418                 elseif(isset($href))
419                         $pxrd = $href;
420                 if(isset($pxrd)) {
421                         logger('lrdd: (host priority) pxrd: ' . $pxrd);
422                         $links = fetch_xrd_links($pxrd);
423                         return $links;
424                 }
425
426                 $lines = explode("\n",$headers);
427                 if(count($lines)) {
428                         foreach($lines as $line) {                              
429                                 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
430                                         return(fetch_xrd_links($matches[1]));
431                                         break;
432                                 }
433                         }
434                 }
435         }
436
437
438         // priority 'resource'
439
440
441         $html = fetch_url($uri);
442         $headers = $a->get_curl_headers();
443         logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
444
445         // don't try and parse raw xml as html
446         if(! strstr($html,'<?xml')) {
447                 require_once('library/HTML5/Parser.php');
448
449                 try {
450                         $dom = HTML5_Parser::parse($html);
451                 } catch (DOMException $e) {
452                         logger('lrdd: parse error: ' . $e);
453                 }
454
455                 if($dom) {
456                         $items = $dom->getElementsByTagName('link');
457                         foreach($items as $item) {
458                                 $x = $item->getAttribute('rel');
459                                 if($x == "lrdd") {
460                                         $pagelink = $item->getAttribute('href');
461                                         break;
462                                 }
463                         }
464                 }
465         }
466
467         if(isset($pagelink))
468                 return(fetch_xrd_links($pagelink));
469
470         // next look in HTTP headers
471
472         $lines = explode("\n",$headers);
473         if(count($lines)) {
474                 foreach($lines as $line) {                              
475                         // TODO alter the following regex to support multiple relations (space separated)
476                         if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
477                                 $pagelink = $matches[1];
478                                 break;
479                         }
480                         // don't try and run feeds through the html5 parser
481                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
482                                 return array();
483                         if(stristr($html,'<rss') || stristr($html,'<feed'))
484                                 return array();
485                 }
486         }
487
488         if(isset($pagelink))
489                 return(fetch_xrd_links($pagelink));
490
491         // If we haven't found any links, return the host xrd links (which we have already fetched)
492
493         if(isset($links))
494                 return $links;
495
496         return array();
497
498 }}
499
500
501
502 // Given a host name, locate the LRDD template from that
503 // host. Returns the LRDD template or an empty string on
504 // error/failure.
505
506 if(! function_exists('fetch_lrdd_template')) {
507 function fetch_lrdd_template($host) {
508         $tpl = '';
509
510         $url1 = 'https://' . $host . '/.well-known/host-meta' ;
511         $url2 = 'http://' . $host . '/.well-known/host-meta' ;
512         $links = fetch_xrd_links($url1);
513         logger('fetch_lrdd_template from: ' . $url1);
514         logger('template (https): ' . print_r($links,true));
515         if(! count($links)) {
516                 logger('fetch_lrdd_template from: ' . $url2);
517                 $links = fetch_xrd_links($url2);
518                 logger('template (http): ' . print_r($links,true));
519         }
520         if(count($links)) {
521                 foreach($links as $link)
522                         if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
523                                 $tpl = $link['@attributes']['template'];
524         }
525         if(! strpos($tpl,'{uri}'))
526                 $tpl = '';
527         return $tpl;
528 }}
529
530 // Given a URL, retrieve the page as an XRD document.
531 // Return an array of links.
532 // on error/failure return empty array.
533
534 if(! function_exists('fetch_xrd_links')) {
535 function fetch_xrd_links($url) {
536
537         $xrd_timeout = intval(get_config('system','xrd_timeout'));
538         $redirects = 0;
539         $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
540
541         logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
542
543         if ((! $xml) || (! stristr($xml,'<xrd')))
544                 return array();
545
546         // fix diaspora's bad xml
547         $xml = str_replace(array('href=&quot;','&quot;/>'),array('href="','"/>'),$xml);
548
549         $h = parse_xml_string($xml);
550         if(! $h)
551                 return array();
552
553         $arr = convert_xml_element_to_array($h);
554
555         $links = array();
556
557         if(isset($arr['xrd']['link'])) {
558                 $link = $arr['xrd']['link'];
559                 if(! isset($link[0]))
560                         $links = array($link);
561                 else
562                         $links = $link;
563         }
564         if(isset($arr['xrd']['alias'])) {
565                 $alias = $arr['xrd']['alias'];
566                 if(! isset($alias[0]))
567                         $aliases = array($alias);
568                 else
569                         $aliases = $alias;
570                 if(is_array($aliases) && count($aliases)) {
571                         foreach($aliases as $alias) {
572                                 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
573                         }
574                 }
575         }
576
577         logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
578
579         return $links;
580
581 }}
582
583
584 // Take a URL from the wild, prepend http:// if necessary
585 // and check DNS to see if it's real
586 // return true if it's OK, false if something is wrong with it
587
588 if(! function_exists('validate_url')) {
589 function validate_url(&$url) {
590         
591         // no naked subdomains (allow localhost for tests)
592         if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
593                 return false;
594         if(substr($url,0,4) != 'http')
595                 $url = 'http://' . $url;
596         $h = @parse_url($url);
597         
598         if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
599                 return true;
600         }
601         return false;
602 }}
603
604 // checks that email is an actual resolvable internet address
605
606 if(! function_exists('validate_email')) {
607 function validate_email($addr) {
608
609         if(! strpos($addr,'@'))
610                 return false;
611         $h = substr($addr,strpos($addr,'@') + 1);
612
613         if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
614                 return true;
615         }
616         return false;
617 }}
618
619 // Check $url against our list of allowed sites,
620 // wildcards allowed. If allowed_sites is unset return true;
621 // If url is allowed, return true.
622 // otherwise, return false
623
624 if(! function_exists('allowed_url')) {
625 function allowed_url($url) {
626
627         $h = @parse_url($url);
628
629         if(! $h) {
630                 return false;
631         }
632
633         $str_allowed = get_config('system','allowed_sites');
634         if(! $str_allowed)
635                 return true;
636
637         $found = false;
638
639         $host = strtolower($h['host']);
640
641         // always allow our own site
642
643         if($host == strtolower($_SERVER['SERVER_NAME']))
644                 return true;
645
646         $fnmatch = function_exists('fnmatch');
647         $allowed = explode(',',$str_allowed);
648
649         if(count($allowed)) {
650                 foreach($allowed as $a) {
651                         $pat = strtolower(trim($a));
652                         if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
653                                 $found = true; 
654                                 break;
655                         }
656                 }
657         }
658         return $found;
659 }}
660
661 // check if email address is allowed to register here.
662 // Compare against our list (wildcards allowed).
663 // Returns false if not allowed, true if allowed or if
664 // allowed list is not configured.
665
666 if(! function_exists('allowed_email')) {
667 function allowed_email($email) {
668
669
670         $domain = strtolower(substr($email,strpos($email,'@') + 1));
671         if(! $domain)
672                 return false;
673
674         $str_allowed = get_config('system','allowed_email');
675         if(! $str_allowed)
676                 return true;
677
678         $found = false;
679
680         $fnmatch = function_exists('fnmatch');
681         $allowed = explode(',',$str_allowed);
682
683         if(count($allowed)) {
684                 foreach($allowed as $a) {
685                         $pat = strtolower(trim($a));
686                         if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
687                                 $found = true; 
688                                 break;
689                         }
690                 }
691         }
692         return $found;
693 }}
694
695
696 if(! function_exists('avatar_img')) {
697 function avatar_img($email) {
698
699         $a = get_app();
700
701         $avatar['size'] = 175;
702         $avatar['email'] = $email;
703         $avatar['url'] = '';
704         $avatar['success'] = false;
705
706         call_hooks('avatar_lookup', $avatar);
707
708         if(! $avatar['success'])
709                 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
710
711         logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
712         return $avatar['url'];
713 }}
714
715
716 if(! function_exists('parse_xml_string')) {
717 function parse_xml_string($s,$strict = true) {
718         if($strict) {
719                 if(! strstr($s,'<?xml'))
720                         return false;
721                 $s2 = substr($s,strpos($s,'<?xml'));
722         }
723         else
724                 $s2 = $s;
725         libxml_use_internal_errors(true);
726
727         $x = @simplexml_load_string($s2);
728         if(! $x) {
729                 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
730                 foreach(libxml_get_errors() as $err)
731                         logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
732                 libxml_clear_errors();
733         }
734         return $x;
735 }}
736
737 function add_fcontact($arr,$update = false) {
738
739         if($update) {
740                 $r = q("UPDATE `fcontact` SET
741                         `name` = '%s',
742                         `photo` = '%s',
743                         `request` = '%s',
744                         `nick` = '%s',
745                         `addr` = '%s',
746                         `batch` = '%s',
747                         `notify` = '%s',
748                         `poll` = '%s',
749                         `confirm` = '%s',
750                         `alias` = '%s',
751                         `pubkey` = '%s',
752                         `updated` = '%s'
753                         WHERE `url` = '%s' AND `network` = '%s' LIMIT 1", 
754                         dbesc($arr['name']),
755                         dbesc($arr['photo']),
756                         dbesc($arr['request']),
757                         dbesc($arr['nick']),
758                         dbesc($arr['addr']),
759                         dbesc($arr['batch']),
760                         dbesc($arr['notify']),
761                         dbesc($arr['poll']),
762                         dbesc($arr['confirm']),
763                         dbesc($arr['alias']),
764                         dbesc($arr['pubkey']),
765                         dbesc(datetime_convert()),
766                         dbesc($arr['url']),
767                         dbesc($arr['network'])
768                 );
769         }
770         else {
771                 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
772                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
773                         values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
774                         dbesc($arr['url']),
775                         dbesc($arr['name']),
776                         dbesc($arr['photo']),
777                         dbesc($arr['request']),
778                         dbesc($arr['nick']),
779                         dbesc($arr['addr']),
780                         dbesc($arr['batch']),
781                         dbesc($arr['notify']),
782                         dbesc($arr['poll']),
783                         dbesc($arr['confirm']),
784                         dbesc($arr['network']),
785                         dbesc($arr['alias']),
786                         dbesc($arr['pubkey']),
787                         dbesc(datetime_convert())
788                 );
789         }
790
791         return $r;
792 }
793
794
795 function scale_external_images($s,$include_link = true) {
796
797         $a = get_app();
798
799         $matches = null;
800         $c = preg_match_all('/\[img\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
801         if($c) {
802                 require_once('include/Photo.php');
803                 foreach($matches as $mtch) {
804                         logger('scale_external_image: ' . $mtch[1]);
805                         $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
806                         if(stristr($mtch[1],$hostname))
807                                 continue;
808                         $i = fetch_url($mtch[1]);
809                         if($i) {
810                                 $ph = new Photo($i);
811                                 if($ph->is_valid()) {
812                                         $orig_width = $ph->getWidth();
813                                         $orig_height = $ph->getHeight();
814
815                                         if($orig_width > 640 || $orig_height > 640) {
816
817                                                 $ph->scaleImage(640);
818                                                 $new_width = $ph->getWidth();
819                                                 $new_height = $ph->getHeight();
820                                                 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
821                                                 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $mtch[1] . '[/img]'
822                                                         . "\n" . (($include_link) 
823                                                                 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
824                                                                 : ''),$s);
825                                                 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
826                                         }
827                                 }
828                         }
829                 }
830         }
831         return $s;
832 }
833
834
835 function fix_contact_ssl_policy(&$contact,$new_policy) {
836
837         $ssl_changed = false;
838         if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
839                 $ssl_changed = true;
840                 $contact['url']     =   str_replace('https:','http:',$contact['url']);
841                 $contact['request'] =   str_replace('https:','http:',$contact['request']);
842                 $contact['notify']  =   str_replace('https:','http:',$contact['notify']);
843                 $contact['poll']    =   str_replace('https:','http:',$contact['poll']);
844                 $contact['confirm'] =   str_replace('https:','http:',$contact['confirm']);
845                 $contact['poco']    =   str_replace('https:','http:',$contact['poco']);
846         }
847
848         if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
849                 $ssl_changed = true;
850                 $contact['url']     =   str_replace('http:','https:',$contact['url']);
851                 $contact['request'] =   str_replace('http:','https:',$contact['request']);
852                 $contact['notify']  =   str_replace('http:','https:',$contact['notify']);
853                 $contact['poll']    =   str_replace('http:','https:',$contact['poll']);
854                 $contact['confirm'] =   str_replace('http:','https:',$contact['confirm']);
855                 $contact['poco']    =   str_replace('http:','https:',$contact['poco']);
856         }
857
858         if($ssl_changed) {
859                 q("update contact set 
860                         url = '%s', 
861                         request = '%s',
862                         notify = '%s',
863                         poll = '%s',
864                         confirm = '%s',
865                         poco = '%s'
866                         where id = %d limit 1",
867                         dbesc($contact['url']),
868                         dbesc($contact['request']),
869                         dbesc($contact['notify']),
870                         dbesc($contact['poll']),
871                         dbesc($contact['confirm']),
872                         dbesc($contact['poco']),
873                         intval($contact['id'])
874                 );
875         }
876 }
877