]> git.mxchange.org Git - friendica.git/blob - include/network.php
Merge remote branch 'upstream/master'
[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) {
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) {
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         $h = parse_xml_string($xml);
368         if(! $h)
369                 return array();
370
371         $arr = convert_xml_element_to_array($h);
372
373         if(isset($arr['xrd']['property'])) {
374                 $property = $arr['crd']['property'];
375                 if(! isset($property[0]))
376                         $properties = array($property);
377                 else
378                         $properties = $property;
379                 foreach($properties as $prop)
380                         if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
381                                 $priority = 'resource';
382         } 
383
384         // save the links in case we need them
385
386         $links = array();
387
388         if(isset($arr['xrd']['link'])) {
389                 $link = $arr['xrd']['link'];
390                 if(! isset($link[0]))
391                         $links = array($link);
392                 else
393                         $links = $link;
394         }
395
396         // do we have a template or href?
397
398         if(count($links)) {
399                 foreach($links as $link) {
400                         if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
401                                 if(x($link['@attributes'],'template'))
402                                         $tpl = $link['@attributes']['template'];
403                                 elseif(x($link['@attributes'],'href'))
404                                         $href = $link['@attributes']['href'];
405                         }
406                 }               
407         }
408
409         if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
410                 $tpl = '';
411
412         if($priority === 'host') {
413                 if(strlen($tpl)) 
414                         $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
415                 elseif(isset($href))
416                         $pxrd = $href;
417                 if(isset($pxrd)) {
418                         logger('lrdd: (host priority) pxrd: ' . $pxrd);
419                         $links = fetch_xrd_links($pxrd);
420                         return $links;
421                 }
422
423                 $lines = explode("\n",$headers);
424                 if(count($lines)) {
425                         foreach($lines as $line) {                              
426                                 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
427                                         return(fetch_xrd_links($matches[1]));
428                                         break;
429                                 }
430                         }
431                 }
432         }
433
434
435         // priority 'resource'
436
437
438         $html = fetch_url($uri);
439         $headers = $a->get_curl_headers();
440         logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
441
442         // don't try and parse raw xml as html
443         if(! strstr($html,'<?xml')) {
444                 require_once('library/HTML5/Parser.php');
445
446                 try {
447                         $dom = HTML5_Parser::parse($html);
448                 } catch (DOMException $e) {
449                         logger('lrdd: parse error: ' . $e);
450                 }
451
452                 if($dom) {
453                         $items = $dom->getElementsByTagName('link');
454                         foreach($items as $item) {
455                                 $x = $item->getAttribute('rel');
456                                 if($x == "lrdd") {
457                                         $pagelink = $item->getAttribute('href');
458                                         break;
459                                 }
460                         }
461                 }
462         }
463
464         if(isset($pagelink))
465                 return(fetch_xrd_links($pagelink));
466
467         // next look in HTTP headers
468
469         $lines = explode("\n",$headers);
470         if(count($lines)) {
471                 foreach($lines as $line) {                              
472                         // TODO alter the following regex to support multiple relations (space separated)
473                         if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
474                                 $pagelink = $matches[1];
475                                 break;
476                         }
477                         // don't try and run feeds through the html5 parser
478                         if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
479                                 return array();
480                         if(stristr($html,'<rss') || stristr($html,'<feed'))
481                                 return array();
482                 }
483         }
484
485         if(isset($pagelink))
486                 return(fetch_xrd_links($pagelink));
487
488         // If we haven't found any links, return the host xrd links (which we have already fetched)
489
490         if(isset($links))
491                 return $links;
492
493         return array();
494
495 }}
496
497
498
499 // Given a host name, locate the LRDD template from that
500 // host. Returns the LRDD template or an empty string on
501 // error/failure.
502
503 if(! function_exists('fetch_lrdd_template')) {
504 function fetch_lrdd_template($host) {
505         $tpl = '';
506
507         $url1 = 'https://' . $host . '/.well-known/host-meta' ;
508         $url2 = 'http://' . $host . '/.well-known/host-meta' ;
509         $links = fetch_xrd_links($url1);
510         logger('fetch_lrdd_template from: ' . $url1);
511         logger('template (https): ' . print_r($links,true));
512         if(! count($links)) {
513                 logger('fetch_lrdd_template from: ' . $url2);
514                 $links = fetch_xrd_links($url2);
515                 logger('template (http): ' . print_r($links,true));
516         }
517         if(count($links)) {
518                 foreach($links as $link)
519                         if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
520                                 $tpl = $link['@attributes']['template'];
521         }
522         if(! strpos($tpl,'{uri}'))
523                 $tpl = '';
524         return $tpl;
525 }}
526
527 // Given a URL, retrieve the page as an XRD document.
528 // Return an array of links.
529 // on error/failure return empty array.
530
531 if(! function_exists('fetch_xrd_links')) {
532 function fetch_xrd_links($url) {
533
534         $xrd_timeout = intval(get_config('system','xrd_timeout'));
535         $redirects = 0;
536         $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
537
538         logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
539
540         if ((! $xml) || (! stristr($xml,'<xrd')))
541                 return array();
542
543         // fix diaspora's bad xml
544         $xml = str_replace(array('href=&quot;','&quot;/>'),array('href="','"/>'),$xml);
545
546         $h = parse_xml_string($xml);
547         if(! $h)
548                 return array();
549
550         $arr = convert_xml_element_to_array($h);
551
552         $links = array();
553
554         if(isset($arr['xrd']['link'])) {
555                 $link = $arr['xrd']['link'];
556                 if(! isset($link[0]))
557                         $links = array($link);
558                 else
559                         $links = $link;
560         }
561         if(isset($arr['xrd']['alias'])) {
562                 $alias = $arr['xrd']['alias'];
563                 if(! isset($alias[0]))
564                         $aliases = array($alias);
565                 else
566                         $aliases = $alias;
567                 if(is_array($aliases) && count($aliases)) {
568                         foreach($aliases as $alias) {
569                                 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
570                         }
571                 }
572         }
573
574         logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
575
576         return $links;
577
578 }}
579
580
581 // Take a URL from the wild, prepend http:// if necessary
582 // and check DNS to see if it's real
583 // return true if it's OK, false if something is wrong with it
584
585 if(! function_exists('validate_url')) {
586 function validate_url(&$url) {
587         // no naked subdomains
588         if(strpos($url,'.') === false)
589                 return false;
590         if(substr($url,0,4) != 'http')
591                 $url = 'http://' . $url;
592         $h = @parse_url($url);
593
594         if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR))) {
595                 return true;
596         }
597         return false;
598 }}
599
600 // checks that email is an actual resolvable internet address
601
602 if(! function_exists('validate_email')) {
603 function validate_email($addr) {
604
605         if(! strpos($addr,'@'))
606                 return false;
607         $h = substr($addr,strpos($addr,'@') + 1);
608
609         if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX))) {
610                 return true;
611         }
612         return false;
613 }}
614
615 // Check $url against our list of allowed sites,
616 // wildcards allowed. If allowed_sites is unset return true;
617 // If url is allowed, return true.
618 // otherwise, return false
619
620 if(! function_exists('allowed_url')) {
621 function allowed_url($url) {
622
623         $h = @parse_url($url);
624
625         if(! $h) {
626                 return false;
627         }
628
629         $str_allowed = get_config('system','allowed_sites');
630         if(! $str_allowed)
631                 return true;
632
633         $found = false;
634
635         $host = strtolower($h['host']);
636
637         // always allow our own site
638
639         if($host == strtolower($_SERVER['SERVER_NAME']))
640                 return true;
641
642         $fnmatch = function_exists('fnmatch');
643         $allowed = explode(',',$str_allowed);
644
645         if(count($allowed)) {
646                 foreach($allowed as $a) {
647                         $pat = strtolower(trim($a));
648                         if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
649                                 $found = true; 
650                                 break;
651                         }
652                 }
653         }
654         return $found;
655 }}
656
657 // check if email address is allowed to register here.
658 // Compare against our list (wildcards allowed).
659 // Returns false if not allowed, true if allowed or if
660 // allowed list is not configured.
661
662 if(! function_exists('allowed_email')) {
663 function allowed_email($email) {
664
665
666         $domain = strtolower(substr($email,strpos($email,'@') + 1));
667         if(! $domain)
668                 return false;
669
670         $str_allowed = get_config('system','allowed_email');
671         if(! $str_allowed)
672                 return true;
673
674         $found = false;
675
676         $fnmatch = function_exists('fnmatch');
677         $allowed = explode(',',$str_allowed);
678
679         if(count($allowed)) {
680                 foreach($allowed as $a) {
681                         $pat = strtolower(trim($a));
682                         if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
683                                 $found = true; 
684                                 break;
685                         }
686                 }
687         }
688         return $found;
689 }}
690
691
692 if(! function_exists('gravatar_img')) {
693 function gravatar_img($email) {
694         $size = 175;
695         $opt = 'identicon';   // psuedo-random geometric pattern if not found
696         $rating = 'pg';
697         $hash = md5(trim(strtolower($email)));
698         
699         $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg' 
700                 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
701
702         logger('gravatar: ' . $email . ' ' . $url);
703         return $url;
704 }}
705
706
707 if(! function_exists('parse_xml_string')) {
708 function parse_xml_string($s,$strict = true) {
709         if($strict) {
710                 if(! strstr($s,'<?xml'))
711                         return false;
712                 $s2 = substr($s,strpos($s,'<?xml'));
713         }
714         else
715                 $s2 = $s;
716         libxml_use_internal_errors(true);
717
718         $x = @simplexml_load_string($s2);
719         if(! $x) {
720                 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
721                 foreach(libxml_get_errors() as $err)
722                         logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
723                 libxml_clear_errors();
724         }
725         return $x;
726 }}
727
728 function add_fcontact($arr,$update = false) {
729
730         if($update) {
731                 $r = q("UPDATE `fcontact` SET
732                         `name` = '%s',
733                         `photo` = '%s',
734                         `request` = '%s',
735                         `nick` = '%s',
736                         `addr` = '%s',
737                         `batch` = '%s',
738                         `notify` = '%s',
739                         `poll` = '%s',
740                         `confirm` = '%s',
741                         `alias` = '%s',
742                         `pubkey` = '%s',
743                         `updated` = '%s'
744                         WHERE `url` = '%s' AND `network` = '%s' LIMIT 1", 
745                         dbesc($arr['name']),
746                         dbesc($arr['photo']),
747                         dbesc($arr['request']),
748                         dbesc($arr['nick']),
749                         dbesc($arr['addr']),
750                         dbesc($arr['batch']),
751                         dbesc($arr['notify']),
752                         dbesc($arr['poll']),
753                         dbesc($arr['confirm']),
754                         dbesc($arr['alias']),
755                         dbesc($arr['pubkey']),
756                         dbesc(datetime_convert()),
757                         dbesc($arr['url']),
758                         dbesc($arr['network'])
759                 );
760         }
761         else {
762                 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
763                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
764                         values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
765                         dbesc($arr['url']),
766                         dbesc($arr['name']),
767                         dbesc($arr['photo']),
768                         dbesc($arr['request']),
769                         dbesc($arr['nick']),
770                         dbesc($arr['addr']),
771                         dbesc($arr['batch']),
772                         dbesc($arr['notify']),
773                         dbesc($arr['poll']),
774                         dbesc($arr['confirm']),
775                         dbesc($arr['network']),
776                         dbesc($arr['alias']),
777                         dbesc($arr['pubkey']),
778                         dbesc(datetime_convert())
779                 );
780         }
781
782         return $r;
783 }
784
785
786 function scale_external_images($s,$include_link = true) {
787
788         $a = get_app();
789
790         $matches = null;
791         $c = preg_match_all('/\[img\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
792         if($c) {
793                 require_once('include/Photo.php');
794                 foreach($matches as $mtch) {
795                         logger('scale_external_image: ' . $mtch[1]);
796                         $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
797                         if(stristr($mtch[1],$hostname))
798                                 continue;
799                         $i = fetch_url($mtch[1]);
800                         if($i) {
801                                 $ph = new Photo($i);
802                                 if($ph->is_valid()) {
803                                         $orig_width = $ph->getWidth();
804                                         $orig_height = $ph->getHeight();
805
806                                         if($orig_width > 640 || $orig_height > 640) {
807
808                                                 $ph->scaleImage(640);
809                                                 $new_width = $ph->getWidth();
810                                                 $new_height = $ph->getHeight();
811                                                 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
812                                                 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $mtch[1] . '[/img]'
813                                                         . "\n" . (($include_link) 
814                                                                 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
815                                                                 : ''),$s);
816                                                 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
817                                         }
818                                 }
819                         }
820                 }
821         }
822         return $s;
823 }