4 // curl wrapper. If binary flag is true, return binary
7 // Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
8 // to preserve cookies from one request to the next.
9 if(! function_exists('fetch_url')) {
10 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
16 array('timeout'=>$timeout,
17 'accept_content'=>$accept_content,
18 'cookiejar'=>$cookiejar
24 if(!function_exists('z_fetch_url')){
26 * @brief fetches an URL.
30 * @param boolean $binary default false
31 * TRUE if asked to return binary results (file download)
32 * @param int $redirects default 0
33 * internal use, recursion counter
34 * @param array $opts (optional parameters) assoziative array with:
35 * * \b accept_content => supply Accept: header with 'accept_content' as the value
36 * * \b timeout => int seconds, default system config value or 60 seconds
37 * * \b http_auth => username:password
38 * * \b novalidate => do not validate SSL certs, default is to validate using our CA list
39 * * \b nobody => only return the header
40 * * \b cookiejar => path to cookie jar file
42 * @return array an assoziative array with:
43 * * \e int \b return_code => HTTP return code or 0 if timeout or failure
44 * * \e boolean \b success => boolean true (if HTTP 2xx result) or false
45 * * \e string \b header => HTTP headers
46 * * \e string \b body => fetched content
48 function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
50 $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
53 $stamp1 = microtime(true);
57 $ch = @curl_init($url);
58 if(($redirects > 8) || (! $ch))
61 @curl_setopt($ch, CURLOPT_HEADER, true);
63 if(x($opts,"cookiejar")) {
64 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
65 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
68 // These settings aren't needed. We're following the location already.
69 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
70 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
72 if (x($opts,'accept_content')){
73 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
74 "Accept: " . $opts['accept_content']
78 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
79 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
83 if(x($opts,'headers')){
84 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
86 if(x($opts,'nobody')){
87 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
89 if(x($opts,'timeout')){
90 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
92 $curl_time = intval(get_config('system','curl_timeout'));
93 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
95 // by default we will allow self-signed certs
96 // but you can override this
98 $check_cert = get_config('system','verifyssl');
99 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
100 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
102 $prx = get_config('system','proxy');
104 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
105 @curl_setopt($ch, CURLOPT_PROXY, $prx);
106 $prxusr = @get_config('system','proxyuser');
108 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
111 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
113 $a->set_curl_code(0);
115 // don't let curl abort the entire application
116 // if it throws any errors.
118 $s = @curl_exec($ch);
119 if (curl_errno($ch) !== CURLE_OK) {
120 logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
124 $curl_info = @curl_getinfo($ch);
126 $http_code = $curl_info['http_code'];
127 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
130 // Pull out multiple headers, e.g. proxy and continuation headers
131 // allow for HTTP/2.x without fixing code
133 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
134 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
136 $base = substr($base,strlen($chunk));
139 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
140 $new_location_info = @parse_url($curl_info["redirect_url"]);
141 $old_location_info = @parse_url($curl_info["url"]);
143 $newurl = $curl_info["redirect_url"];
145 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
146 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
149 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
150 $newurl = trim(array_pop($matches));
152 if(strpos($newurl,'/') === 0)
153 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
154 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
157 return z_fetch_url($newurl,$binary, $redirects, $opts);
162 $a->set_curl_code($http_code);
163 $a->set_curl_content_type($curl_info['content_type']);
165 $body = substr($s,strlen($header));
166 $a->set_curl_headers($header);
170 $rc = intval($http_code);
171 $ret['return_code'] = $rc;
172 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
173 if(! $ret['success']) {
174 $ret['error'] = curl_error($ch);
175 $ret['debug'] = $curl_info;
176 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
177 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
179 $ret['body'] = substr($s,strlen($header));
180 $ret['header'] = $header;
181 if(x($opts,'debug')) {
182 $ret['debug'] = $curl_info;
186 $a->save_timestamp($stamp1, "network");
192 // post request to $url. $params is an array of post variables.
194 if(! function_exists('post_url')) {
195 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
196 $stamp1 = microtime(true);
199 $ch = curl_init($url);
200 if(($redirects > 8) || (! $ch))
203 logger("post_url: start ".$url, LOGGER_DATA);
205 curl_setopt($ch, CURLOPT_HEADER, true);
206 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
207 curl_setopt($ch, CURLOPT_POST,1);
208 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
209 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
211 if(intval($timeout)) {
212 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
215 $curl_time = intval(get_config('system','curl_timeout'));
216 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
219 if(defined('LIGHTTPD')) {
220 if(!is_array($headers)) {
221 $headers = array('Expect:');
223 if(!in_array('Expect:', $headers)) {
224 array_push($headers, 'Expect:');
229 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
231 $check_cert = get_config('system','verifyssl');
232 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
233 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
234 $prx = get_config('system','proxy');
236 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
237 curl_setopt($ch, CURLOPT_PROXY, $prx);
238 $prxusr = get_config('system','proxyuser');
240 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
243 $a->set_curl_code(0);
245 // don't let curl abort the entire application
246 // if it throws any errors.
248 $s = @curl_exec($ch);
251 $curl_info = curl_getinfo($ch);
252 $http_code = $curl_info['http_code'];
254 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
258 // Pull out multiple headers, e.g. proxy and continuation headers
259 // allow for HTTP/2.x without fixing code
261 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
262 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
264 $base = substr($base,strlen($chunk));
267 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
269 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
270 $newurl = trim(array_pop($matches));
271 if(strpos($newurl,'/') === 0)
272 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
273 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
275 logger("post_url: redirect ".$url." to ".$newurl);
276 return post_url($newurl,$params, $headers, $redirects, $timeout);
277 //return fetch_url($newurl,false,$redirects,$timeout);
280 $a->set_curl_code($http_code);
281 $body = substr($s,strlen($header));
283 $a->set_curl_headers($header);
287 $a->save_timestamp($stamp1, "network");
289 logger("post_url: end ".$url, LOGGER_DATA);
294 // Generic XML return
295 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
296 // of $st and an optional text <message> of $message and terminates the current process.
298 if(! function_exists('xml_status')) {
299 function xml_status($st, $message = '') {
301 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
304 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
306 header( "Content-type: text/xml" );
307 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
308 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
313 if(! function_exists('http_status_exit')) {
314 function http_status_exit($val, $description = array()) {
318 if (!isset($description["title"]))
319 $description["title"] = $err." ".$val;
321 if($val >= 200 && $val < 300)
324 logger('http_status_exit ' . $val);
325 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
327 if (isset($description["title"])) {
328 $tpl = get_markup_template('http_status.tpl');
329 echo replace_macros($tpl, array('$title' => $description["title"],
330 '$description' => $description["description"]));
338 // convert an XML document to a normalised, case-corrected array
341 if(! function_exists('convert_xml_element_to_array')) {
342 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
344 // If we're getting too deep, bail out
345 if ($recursion_depth > 512) {
349 if (!is_string($xml_element) &&
350 !is_array($xml_element) &&
351 (get_class($xml_element) == 'SimpleXMLElement')) {
352 $xml_element_copy = $xml_element;
353 $xml_element = get_object_vars($xml_element);
356 if (is_array($xml_element)) {
357 $result_array = array();
358 if (count($xml_element) <= 0) {
359 return (trim(strval($xml_element_copy)));
362 foreach($xml_element as $key=>$value) {
365 $result_array[strtolower($key)] =
366 convert_xml_element_to_array($value, $recursion_depth);
369 if ($recursion_depth == 0) {
370 $temp_array = $result_array;
371 $result_array = array(
372 strtolower($xml_element_copy->getName()) => $temp_array,
376 return ($result_array);
379 return (trim(strval($xml_element)));
383 // Given an email style address, perform webfinger lookup and
384 // return the resulting DFRN profile URL, or if no DFRN profile URL
385 // is located, returns an OStatus subscription template (prefixed
386 // with the string 'stat:' to identify it as on OStatus template).
387 // If this isn't an email style address just return $s.
388 // Return an empty string if email-style addresses but webfinger fails,
389 // or if the resultant personal XRD doesn't contain a supported
390 // subscription/friend-request attribute.
392 // amended 7/9/2011 to return an hcard which could save potentially loading
393 // a lengthy content page to scrape dfrn attributes
395 if(! function_exists('webfinger_dfrn')) {
396 function webfinger_dfrn($s,&$hcard) {
397 if(! strstr($s,'@')) {
402 $links = webfinger($s);
403 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
405 foreach($links as $link) {
406 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
407 $profile_link = $link['@attributes']['href'];
408 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
409 $profile_link = 'stat:' . $link['@attributes']['template'];
410 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
411 $hcard = $link['@attributes']['href'];
414 return $profile_link;
417 // Given an email style address, perform webfinger lookup and
418 // return the array of link attributes from the personal XRD file.
419 // On error/failure return an empty array.
422 if(! function_exists('webfinger')) {
423 function webfinger($s, $debug = false) {
426 $host = substr($s,strpos($s,'@') + 1);
429 $tpl = fetch_lrdd_template($host);
430 logger('webfinger: lrdd template: ' . $tpl);
432 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
433 logger('webfinger: pxrd: ' . $pxrd);
434 $links = fetch_xrd_links($pxrd);
435 if(! count($links)) {
436 // try with double slashes
437 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
438 logger('webfinger: pxrd: ' . $pxrd);
439 $links = fetch_xrd_links($pxrd);
447 if(! function_exists('lrdd')) {
448 function lrdd($uri, $debug = false) {
452 // default priority is host priority, host-meta first
456 // All we have is an email address. Resource-priority is irrelevant
457 // because our URI isn't directly resolvable.
459 if(strstr($uri,'@')) {
460 return(webfinger($uri));
463 // get the host meta file
465 $host = @parse_url($uri);
468 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
469 $url .= $host['host'] . '/.well-known/host-meta' ;
474 logger('lrdd: constructed url: ' . $url);
476 $xml = fetch_url($url);
478 $headers = $a->get_curl_headers();
483 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
485 if(! stristr($xml,'<xrd'))
488 $h = parse_xml_string($xml);
492 $arr = convert_xml_element_to_array($h);
494 if(isset($arr['xrd']['property'])) {
495 $property = $arr['crd']['property'];
496 if(! isset($property[0]))
497 $properties = array($property);
499 $properties = $property;
500 foreach($properties as $prop)
501 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
502 $priority = 'resource';
505 // save the links in case we need them
509 if(isset($arr['xrd']['link'])) {
510 $link = $arr['xrd']['link'];
511 if(! isset($link[0]))
512 $links = array($link);
517 // do we have a template or href?
520 foreach($links as $link) {
521 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
522 if(x($link['@attributes'],'template'))
523 $tpl = $link['@attributes']['template'];
524 elseif(x($link['@attributes'],'href'))
525 $href = $link['@attributes']['href'];
530 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
533 if($priority === 'host') {
535 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
539 logger('lrdd: (host priority) pxrd: ' . $pxrd);
540 $links = fetch_xrd_links($pxrd);
544 $lines = explode("\n",$headers);
546 foreach($lines as $line) {
547 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
548 return(fetch_xrd_links($matches[1]));
556 // priority 'resource'
559 $html = fetch_url($uri);
560 $headers = $a->get_curl_headers();
561 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
563 // don't try and parse raw xml as html
564 if(! strstr($html,'<?xml')) {
565 require_once('library/HTML5/Parser.php');
568 $dom = HTML5_Parser::parse($html);
569 } catch (DOMException $e) {
570 logger('lrdd: parse error: ' . $e);
573 if(isset($dom) && $dom) {
574 $items = $dom->getElementsByTagName('link');
575 foreach($items as $item) {
576 $x = $item->getAttribute('rel');
578 $pagelink = $item->getAttribute('href');
586 return(fetch_xrd_links($pagelink));
588 // next look in HTTP headers
590 $lines = explode("\n",$headers);
592 foreach($lines as $line) {
593 /// @TODO Alter the following regex to support multiple relations (space separated)
594 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
595 $pagelink = $matches[1];
598 // don't try and run feeds through the html5 parser
599 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
601 if(stristr($html,'<rss') || stristr($html,'<feed'))
607 return(fetch_xrd_links($pagelink));
609 // If we haven't found any links, return the host xrd links (which we have already fetched)
620 // Given a host name, locate the LRDD template from that
621 // host. Returns the LRDD template or an empty string on
624 if(! function_exists('fetch_lrdd_template')) {
625 function fetch_lrdd_template($host) {
628 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
629 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
630 $links = fetch_xrd_links($url1);
631 logger('fetch_lrdd_template from: ' . $url1);
632 logger('template (https): ' . print_r($links,true));
633 if(! count($links)) {
634 logger('fetch_lrdd_template from: ' . $url2);
635 $links = fetch_xrd_links($url2);
636 logger('template (http): ' . print_r($links,true));
639 foreach($links as $link)
640 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
641 $tpl = $link['@attributes']['template'];
643 if(! strpos($tpl,'{uri}'))
648 // Given a URL, retrieve the page as an XRD document.
649 // Return an array of links.
650 // on error/failure return empty array.
652 if(! function_exists('fetch_xrd_links')) {
653 function fetch_xrd_links($url) {
655 $xrd_timeout = intval(get_config('system','xrd_timeout'));
657 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
659 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
661 if ((! $xml) || (! stristr($xml,'<xrd')))
664 // fix diaspora's bad xml
665 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
667 $h = parse_xml_string($xml);
671 $arr = convert_xml_element_to_array($h);
675 if(isset($arr['xrd']['link'])) {
676 $link = $arr['xrd']['link'];
677 if(! isset($link[0]))
678 $links = array($link);
682 if(isset($arr['xrd']['alias'])) {
683 $alias = $arr['xrd']['alias'];
684 if(! isset($alias[0]))
685 $aliases = array($alias);
688 if(is_array($aliases) && count($aliases)) {
689 foreach($aliases as $alias) {
690 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
695 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
702 // Take a URL from the wild, prepend http:// if necessary
703 // and check DNS to see if it's real (or check if is a valid IP address)
704 // return true if it's OK, false if something is wrong with it
706 if(! function_exists('validate_url')) {
707 function validate_url(&$url) {
709 if(get_config('system','disable_url_validation'))
711 // no naked subdomains (allow localhost for tests)
712 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
714 if(substr($url,0,4) != 'http')
715 $url = 'http://' . $url;
716 $h = @parse_url($url);
718 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
724 // checks that email is an actual resolvable internet address
726 if(! function_exists('validate_email')) {
727 function validate_email($addr) {
729 if(get_config('system','disable_email_validation'))
732 if(! strpos($addr,'@'))
734 $h = substr($addr,strpos($addr,'@') + 1);
736 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
742 // Check $url against our list of allowed sites,
743 // wildcards allowed. If allowed_sites is unset return true;
744 // If url is allowed, return true.
745 // otherwise, return false
747 if(! function_exists('allowed_url')) {
748 function allowed_url($url) {
750 $h = @parse_url($url);
756 $str_allowed = get_config('system','allowed_sites');
762 $host = strtolower($h['host']);
764 // always allow our own site
766 if($host == strtolower($_SERVER['SERVER_NAME']))
769 $fnmatch = function_exists('fnmatch');
770 $allowed = explode(',',$str_allowed);
772 if(count($allowed)) {
773 foreach($allowed as $a) {
774 $pat = strtolower(trim($a));
775 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
784 // check if email address is allowed to register here.
785 // Compare against our list (wildcards allowed).
786 // Returns false if not allowed, true if allowed or if
787 // allowed list is not configured.
789 if(! function_exists('allowed_email')) {
790 function allowed_email($email) {
793 $domain = strtolower(substr($email,strpos($email,'@') + 1));
797 $str_allowed = get_config('system','allowed_email');
803 $fnmatch = function_exists('fnmatch');
804 $allowed = explode(',',$str_allowed);
806 if(count($allowed)) {
807 foreach($allowed as $a) {
808 $pat = strtolower(trim($a));
809 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
819 if(! function_exists('avatar_img')) {
820 function avatar_img($email) {
824 $avatar['size'] = 175;
825 $avatar['email'] = $email;
827 $avatar['success'] = false;
829 call_hooks('avatar_lookup', $avatar);
831 if(! $avatar['success'])
832 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
834 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
835 return $avatar['url'];
839 if(! function_exists('parse_xml_string')) {
840 function parse_xml_string($s,$strict = true) {
842 if(! strstr($s,'<?xml'))
844 $s2 = substr($s,strpos($s,'<?xml'));
848 libxml_use_internal_errors(true);
850 $x = @simplexml_load_string($s2);
852 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
853 foreach(libxml_get_errors() as $err)
854 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
855 libxml_clear_errors();
860 function add_fcontact($arr,$update = false) {
863 $r = q("UPDATE `fcontact` SET
876 WHERE `url` = '%s' AND `network` = '%s'",
878 dbesc($arr['photo']),
879 dbesc($arr['request']),
882 dbesc($arr['batch']),
883 dbesc($arr['notify']),
885 dbesc($arr['confirm']),
886 dbesc($arr['alias']),
887 dbesc($arr['pubkey']),
888 dbesc(datetime_convert()),
890 dbesc($arr['network'])
894 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
895 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
896 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
899 dbesc($arr['photo']),
900 dbesc($arr['request']),
903 dbesc($arr['batch']),
904 dbesc($arr['notify']),
906 dbesc($arr['confirm']),
907 dbesc($arr['network']),
908 dbesc($arr['alias']),
909 dbesc($arr['pubkey']),
910 dbesc(datetime_convert())
918 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
920 // Suppress "view full size"
921 if (intval(get_config('system','no_view_full_size')))
922 $include_link = false;
926 // Picture addresses can contain special characters
927 $s = htmlspecialchars_decode($srctext);
930 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
932 require_once('include/Photo.php');
933 foreach($matches as $mtch) {
934 logger('scale_external_image: ' . $mtch[1]);
936 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
937 if(stristr($mtch[1],$hostname))
940 // $scale_replace, if passed, is an array of two elements. The
941 // first is the name of the full-size image. The second is the
942 // name of a remote, scaled-down version of the full size image.
943 // This allows Friendica to display the smaller remote image if
944 // one exists, while still linking to the full-size image
946 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
949 $i = @fetch_url($scaled);
953 // guess mimetype from headers or filename
954 $type = guess_image_type($mtch[1],true);
957 $ph = new Photo($i, $type);
958 if($ph->is_valid()) {
959 $orig_width = $ph->getWidth();
960 $orig_height = $ph->getHeight();
962 if($orig_width > 640 || $orig_height > 640) {
964 $ph->scaleImage(640);
965 $new_width = $ph->getWidth();
966 $new_height = $ph->getHeight();
967 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
968 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
969 . "\n" . (($include_link)
970 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
972 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
979 // replace the special char encoding
980 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
985 function fix_contact_ssl_policy(&$contact,$new_policy) {
987 $ssl_changed = false;
988 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
990 $contact['url'] = str_replace('https:','http:',$contact['url']);
991 $contact['request'] = str_replace('https:','http:',$contact['request']);
992 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
993 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
994 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
995 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
998 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
1000 $contact['url'] = str_replace('http:','https:',$contact['url']);
1001 $contact['request'] = str_replace('http:','https:',$contact['request']);
1002 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
1003 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
1004 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
1005 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
1009 q("update contact set
1016 where id = %d limit 1",
1017 dbesc($contact['url']),
1018 dbesc($contact['request']),
1019 dbesc($contact['notify']),
1020 dbesc($contact['poll']),
1021 dbesc($contact['confirm']),
1022 dbesc($contact['poco']),
1023 intval($contact['id'])
1031 * xml2array() will convert the given XML text to an array in the XML structure.
1032 * Link: http://www.bin-co.com/php/scripts/xml2array/
1033 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
1034 * Arguments : $contents - The XML text
1035 * $namespaces - true or false include namespace information in the returned array as array elements.
1036 * $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.
1037 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
1038 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
1039 * Examples: $array = xml2array(file_get_contents('feed.xml'));
1040 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
1043 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
1044 if(!$contents) return array();
1046 if(!function_exists('xml_parser_create')) {
1047 logger('xml2array: parser function missing');
1052 libxml_use_internal_errors(true);
1053 libxml_clear_errors();
1056 $parser = @xml_parser_create_ns("UTF-8",':');
1058 $parser = @xml_parser_create();
1061 logger('xml2array: xml_parser_create: no resource');
1065 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
1066 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
1067 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1068 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
1069 @xml_parse_into_struct($parser, trim($contents), $xml_values);
1070 @xml_parser_free($parser);
1073 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
1074 foreach(libxml_get_errors() as $err)
1075 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
1076 libxml_clear_errors();
1081 $xml_array = array();
1083 $opened_tags = array();
1086 $current = &$xml_array; // Reference
1088 // Go through the tags.
1089 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1090 foreach($xml_values as $data) {
1091 unset($attributes,$value); // Remove existing values, or there will be trouble
1093 // This command will extract these variables into the foreach scope
1094 // tag(string), type(string), level(int), attributes(array).
1095 extract($data); // We could use the array by itself, but this cooler.
1098 $attributes_data = array();
1101 if($priority == 'tag') $result = $value;
1102 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1105 //Set the attributes too.
1106 if(isset($attributes) and $get_attributes) {
1107 foreach($attributes as $attr => $val) {
1108 if($priority == 'tag') $attributes_data[$attr] = $val;
1109 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1113 // See tag status and do the needed.
1114 if($namespaces && strpos($tag,':')) {
1115 $namespc = substr($tag,0,strrpos($tag,':'));
1116 $tag = strtolower(substr($tag,strlen($namespc)+1));
1117 $result['@namespace'] = $namespc;
1119 $tag = strtolower($tag);
1121 if($type == "open") { // The starting of the tag '<tag>'
1122 $parent[$level-1] = &$current;
1123 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1124 $current[$tag] = $result;
1125 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1126 $repeated_tag_index[$tag.'_'.$level] = 1;
1128 $current = &$current[$tag];
1130 } else { // There was another element with the same tag name
1132 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1133 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1134 $repeated_tag_index[$tag.'_'.$level]++;
1135 } else { // This section will make the value an array if multiple tags with the same name appear together
1136 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1137 $repeated_tag_index[$tag.'_'.$level] = 2;
1139 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1140 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1141 unset($current[$tag.'_attr']);
1145 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1146 $current = &$current[$tag][$last_item_index];
1149 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1150 //See if the key is already taken.
1151 if(!isset($current[$tag])) { //New Key
1152 $current[$tag] = $result;
1153 $repeated_tag_index[$tag.'_'.$level] = 1;
1154 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1156 } else { // If taken, put all things inside a list(array)
1157 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1159 // ...push the new element into that array.
1160 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1162 if($priority == 'tag' and $get_attributes and $attributes_data) {
1163 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1165 $repeated_tag_index[$tag.'_'.$level]++;
1167 } else { // If it is not an array...
1168 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1169 $repeated_tag_index[$tag.'_'.$level] = 1;
1170 if($priority == 'tag' and $get_attributes) {
1171 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1173 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1174 unset($current[$tag.'_attr']);
1177 if($attributes_data) {
1178 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1181 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1185 } elseif($type == 'close') { // End of tag '</tag>'
1186 $current = &$parent[$level-1];
1193 function original_url($url, $depth=1, $fetchbody = false) {
1197 // Remove Analytics Data from Google and other tracking platforms
1198 $urldata = parse_url($url);
1199 if (is_string($urldata["query"])) {
1200 $query = $urldata["query"];
1201 parse_str($query, $querydata);
1203 if (is_array($querydata))
1204 foreach ($querydata AS $param=>$value)
1205 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1206 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1207 "fb_action_ids", "fb_action_types", "fb_ref",
1209 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1211 $pair = $param."=".urlencode($value);
1212 $url = str_replace($pair, "", $url);
1214 // Second try: if the url isn't encoded completely
1215 $pair = $param."=".str_replace(" ", "+", $value);
1216 $url = str_replace($pair, "", $url);
1218 // Third try: Maybey the url isn't encoded at all
1219 $pair = $param."=".$value;
1220 $url = str_replace($pair, "", $url);
1222 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1225 if (substr($url, -1, 1) == "?")
1226 $url = substr($url, 0, -1);
1232 $url = trim($url, "'");
1234 $stamp1 = microtime(true);
1236 $siteinfo = array();
1238 curl_setopt($ch, CURLOPT_URL, $url);
1239 curl_setopt($ch, CURLOPT_HEADER, 1);
1240 curl_setopt($ch, CURLOPT_NOBODY, 1);
1241 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1242 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1243 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1245 $header = curl_exec($ch);
1246 $curl_info = @curl_getinfo($ch);
1247 $http_code = $curl_info['http_code'];
1250 $a->save_timestamp($stamp1, "network");
1252 if ($http_code == 0)
1255 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1256 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1257 if ($curl_info['redirect_url'] != "")
1258 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1260 return(original_url($curl_info['location'], ++$depth, $fetchbody));
1263 // Check for redirects in the meta elements of the body if there are no redirects in the header.
1265 return(original_url($url, ++$depth, true));
1267 // if the file is too large then exit
1268 if ($curl_info["download_content_length"] > 1000000)
1271 // if it isn't a HTML file then exit
1272 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
1275 $stamp1 = microtime(true);
1278 curl_setopt($ch, CURLOPT_URL, $url);
1279 curl_setopt($ch, CURLOPT_HEADER, 0);
1280 curl_setopt($ch, CURLOPT_NOBODY, 0);
1281 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1282 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1283 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1285 $body = curl_exec($ch);
1288 $a->save_timestamp($stamp1, "network");
1290 if (trim($body) == "")
1293 // Check for redirect in meta elements
1294 $doc = new DOMDocument();
1295 @$doc->loadHTML($body);
1297 $xpath = new DomXPath($doc);
1299 $list = $xpath->query("//meta[@content]");
1300 foreach ($list as $node) {
1302 if ($node->attributes->length)
1303 foreach ($node->attributes as $attribute)
1304 $attr[$attribute->name] = $attribute->value;
1306 if (@$attr["http-equiv"] == 'refresh') {
1307 $path = $attr["content"];
1308 $pathinfo = explode(";", $path);
1310 foreach ($pathinfo AS $value)
1311 if (substr(strtolower($value), 0, 4) == "url=")
1312 return(original_url(substr($value, 4), ++$depth));
1319 if (!function_exists('short_link')) {
1320 function short_link($url) {
1321 require_once('library/slinky.php');
1322 $slinky = new Slinky($url);
1323 $yourls_url = get_config('yourls','url1');
1325 $yourls_username = get_config('yourls','username1');
1326 $yourls_password = get_config('yourls', 'password1');
1327 $yourls_ssl = get_config('yourls', 'ssl1');
1328 $yourls = new Slinky_YourLS();
1329 $yourls->set('username', $yourls_username);
1330 $yourls->set('password', $yourls_password);
1331 $yourls->set('ssl', $yourls_ssl);
1332 $yourls->set('yourls-url', $yourls_url);
1333 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1335 // setup a cascade of shortening services
1336 // try to get a short link from these services
1337 // in the order ur1.ca, trim, id.gd, tinyurl
1338 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1340 return $slinky->short();