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 redirect_url => in case of redirect, content was finally retrieved from this URL
46 * * \e string \b header => HTTP headers
47 * * \e string \b body => fetched content
49 function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
51 $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
54 $stamp1 = microtime(true);
58 $ch = @curl_init($url);
59 if(($redirects > 8) || (! $ch))
62 @curl_setopt($ch, CURLOPT_HEADER, true);
64 if(x($opts,"cookiejar")) {
65 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
66 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
69 // These settings aren't needed. We're following the location already.
70 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
71 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
73 if (x($opts,'accept_content')){
74 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
75 "Accept: " . $opts['accept_content']
79 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
80 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
84 if(x($opts,'headers')){
85 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
87 if(x($opts,'nobody')){
88 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
90 if(x($opts,'timeout')){
91 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
93 $curl_time = intval(get_config('system','curl_timeout'));
94 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
96 // by default we will allow self-signed certs
97 // but you can override this
99 $check_cert = get_config('system','verifyssl');
100 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
101 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
103 $prx = get_config('system','proxy');
105 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
106 @curl_setopt($ch, CURLOPT_PROXY, $prx);
107 $prxusr = @get_config('system','proxyuser');
109 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
112 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
114 $a->set_curl_code(0);
116 // don't let curl abort the entire application
117 // if it throws any errors.
119 $s = @curl_exec($ch);
120 if (curl_errno($ch) !== CURLE_OK) {
121 logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
125 $curl_info = @curl_getinfo($ch);
127 $http_code = $curl_info['http_code'];
128 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
131 // Pull out multiple headers, e.g. proxy and continuation headers
132 // allow for HTTP/2.x without fixing code
134 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
135 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
137 $base = substr($base,strlen($chunk));
140 $a->set_curl_code($http_code);
141 $a->set_curl_content_type($curl_info['content_type']);
142 $a->set_curl_headers($header);
144 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
145 $new_location_info = @parse_url($curl_info["redirect_url"]);
146 $old_location_info = @parse_url($curl_info["url"]);
148 $newurl = $curl_info["redirect_url"];
150 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
151 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
154 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
155 $newurl = trim(array_pop($matches));
157 if(strpos($newurl,'/') === 0)
158 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
159 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
162 return z_fetch_url($newurl,$binary, $redirects, $opts);
167 $a->set_curl_code($http_code);
168 $a->set_curl_content_type($curl_info['content_type']);
170 $body = substr($s,strlen($header));
174 $rc = intval($http_code);
175 $ret['return_code'] = $rc;
176 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
177 $ret['redirect_url'] = $url;
178 if(! $ret['success']) {
179 $ret['error'] = curl_error($ch);
180 $ret['debug'] = $curl_info;
181 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
182 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
184 $ret['body'] = substr($s,strlen($header));
185 $ret['header'] = $header;
186 if(x($opts,'debug')) {
187 $ret['debug'] = $curl_info;
191 $a->save_timestamp($stamp1, "network");
197 // post request to $url. $params is an array of post variables.
199 if(! function_exists('post_url')) {
200 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
201 $stamp1 = microtime(true);
204 $ch = curl_init($url);
205 if(($redirects > 8) || (! $ch))
208 logger("post_url: start ".$url, LOGGER_DATA);
210 curl_setopt($ch, CURLOPT_HEADER, true);
211 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
212 curl_setopt($ch, CURLOPT_POST,1);
213 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
214 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
216 if(intval($timeout)) {
217 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
220 $curl_time = intval(get_config('system','curl_timeout'));
221 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
224 if(defined('LIGHTTPD')) {
225 if(!is_array($headers)) {
226 $headers = array('Expect:');
228 if(!in_array('Expect:', $headers)) {
229 array_push($headers, 'Expect:');
234 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
236 $check_cert = get_config('system','verifyssl');
237 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
238 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
239 $prx = get_config('system','proxy');
241 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
242 curl_setopt($ch, CURLOPT_PROXY, $prx);
243 $prxusr = get_config('system','proxyuser');
245 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
248 $a->set_curl_code(0);
250 // don't let curl abort the entire application
251 // if it throws any errors.
253 $s = @curl_exec($ch);
256 $curl_info = curl_getinfo($ch);
257 $http_code = $curl_info['http_code'];
259 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
263 // Pull out multiple headers, e.g. proxy and continuation headers
264 // allow for HTTP/2.x without fixing code
266 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
267 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
269 $base = substr($base,strlen($chunk));
272 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
274 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
275 $newurl = trim(array_pop($matches));
276 if(strpos($newurl,'/') === 0)
277 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
278 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
280 logger("post_url: redirect ".$url." to ".$newurl);
281 return post_url($newurl,$params, $headers, $redirects, $timeout);
282 //return fetch_url($newurl,false,$redirects,$timeout);
285 $a->set_curl_code($http_code);
286 $body = substr($s,strlen($header));
288 $a->set_curl_headers($header);
292 $a->save_timestamp($stamp1, "network");
294 logger("post_url: end ".$url, LOGGER_DATA);
299 // Generic XML return
300 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
301 // of $st and an optional text <message> of $message and terminates the current process.
303 if(! function_exists('xml_status')) {
304 function xml_status($st, $message = '') {
306 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
309 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
311 header( "Content-type: text/xml" );
312 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
313 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
318 if(! function_exists('http_status_exit')) {
319 function http_status_exit($val, $description = array()) {
323 if (!isset($description["title"]))
324 $description["title"] = $err." ".$val;
326 if($val >= 200 && $val < 300)
329 logger('http_status_exit ' . $val);
330 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
332 if (isset($description["title"])) {
333 $tpl = get_markup_template('http_status.tpl');
334 echo replace_macros($tpl, array('$title' => $description["title"],
335 '$description' => $description["description"]));
343 // convert an XML document to a normalised, case-corrected array
346 if(! function_exists('convert_xml_element_to_array')) {
347 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
349 // If we're getting too deep, bail out
350 if ($recursion_depth > 512) {
354 if (!is_string($xml_element) &&
355 !is_array($xml_element) &&
356 (get_class($xml_element) == 'SimpleXMLElement')) {
357 $xml_element_copy = $xml_element;
358 $xml_element = get_object_vars($xml_element);
361 if (is_array($xml_element)) {
362 $result_array = array();
363 if (count($xml_element) <= 0) {
364 return (trim(strval($xml_element_copy)));
367 foreach($xml_element as $key=>$value) {
370 $result_array[strtolower($key)] =
371 convert_xml_element_to_array($value, $recursion_depth);
374 if ($recursion_depth == 0) {
375 $temp_array = $result_array;
376 $result_array = array(
377 strtolower($xml_element_copy->getName()) => $temp_array,
381 return ($result_array);
384 return (trim(strval($xml_element)));
388 // Given an email style address, perform webfinger lookup and
389 // return the resulting DFRN profile URL, or if no DFRN profile URL
390 // is located, returns an OStatus subscription template (prefixed
391 // with the string 'stat:' to identify it as on OStatus template).
392 // If this isn't an email style address just return $s.
393 // Return an empty string if email-style addresses but webfinger fails,
394 // or if the resultant personal XRD doesn't contain a supported
395 // subscription/friend-request attribute.
397 // amended 7/9/2011 to return an hcard which could save potentially loading
398 // a lengthy content page to scrape dfrn attributes
400 if(! function_exists('webfinger_dfrn')) {
401 function webfinger_dfrn($s,&$hcard) {
402 if(! strstr($s,'@')) {
407 $links = webfinger($s);
408 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
410 foreach($links as $link) {
411 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
412 $profile_link = $link['@attributes']['href'];
413 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
414 $profile_link = 'stat:' . $link['@attributes']['template'];
415 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
416 $hcard = $link['@attributes']['href'];
419 return $profile_link;
422 // Given an email style address, perform webfinger lookup and
423 // return the array of link attributes from the personal XRD file.
424 // On error/failure return an empty array.
427 if(! function_exists('webfinger')) {
428 function webfinger($s, $debug = false) {
431 $host = substr($s,strpos($s,'@') + 1);
434 $tpl = fetch_lrdd_template($host);
435 logger('webfinger: lrdd template: ' . $tpl);
437 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
438 logger('webfinger: pxrd: ' . $pxrd);
439 $links = fetch_xrd_links($pxrd);
440 if(! count($links)) {
441 // try with double slashes
442 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
443 logger('webfinger: pxrd: ' . $pxrd);
444 $links = fetch_xrd_links($pxrd);
452 if(! function_exists('lrdd')) {
453 function lrdd($uri, $debug = false) {
457 // default priority is host priority, host-meta first
461 // All we have is an email address. Resource-priority is irrelevant
462 // because our URI isn't directly resolvable.
464 if(strstr($uri,'@')) {
465 return(webfinger($uri));
468 // get the host meta file
470 $host = @parse_url($uri);
473 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
474 $url .= $host['host'] . '/.well-known/host-meta' ;
479 logger('lrdd: constructed url: ' . $url);
481 $xml = fetch_url($url);
483 $headers = $a->get_curl_headers();
488 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
490 if(! stristr($xml,'<xrd'))
493 $h = parse_xml_string($xml);
497 $arr = convert_xml_element_to_array($h);
499 if(isset($arr['xrd']['property'])) {
500 $property = $arr['crd']['property'];
501 if(! isset($property[0]))
502 $properties = array($property);
504 $properties = $property;
505 foreach($properties as $prop)
506 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
507 $priority = 'resource';
510 // save the links in case we need them
514 if(isset($arr['xrd']['link'])) {
515 $link = $arr['xrd']['link'];
516 if(! isset($link[0]))
517 $links = array($link);
522 // do we have a template or href?
525 foreach($links as $link) {
526 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
527 if(x($link['@attributes'],'template'))
528 $tpl = $link['@attributes']['template'];
529 elseif(x($link['@attributes'],'href'))
530 $href = $link['@attributes']['href'];
535 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
538 if($priority === 'host') {
540 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
544 logger('lrdd: (host priority) pxrd: ' . $pxrd);
545 $links = fetch_xrd_links($pxrd);
549 $lines = explode("\n",$headers);
551 foreach($lines as $line) {
552 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
553 return(fetch_xrd_links($matches[1]));
561 // priority 'resource'
564 $html = fetch_url($uri);
565 $headers = $a->get_curl_headers();
566 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
568 // don't try and parse raw xml as html
569 if(! strstr($html,'<?xml')) {
570 require_once('library/HTML5/Parser.php');
573 $dom = HTML5_Parser::parse($html);
574 } catch (DOMException $e) {
575 logger('lrdd: parse error: ' . $e);
578 if(isset($dom) && $dom) {
579 $items = $dom->getElementsByTagName('link');
580 foreach($items as $item) {
581 $x = $item->getAttribute('rel');
583 $pagelink = $item->getAttribute('href');
591 return(fetch_xrd_links($pagelink));
593 // next look in HTTP headers
595 $lines = explode("\n",$headers);
597 foreach($lines as $line) {
598 /// @TODO Alter the following regex to support multiple relations (space separated)
599 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
600 $pagelink = $matches[1];
603 // don't try and run feeds through the html5 parser
604 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
606 if(stristr($html,'<rss') || stristr($html,'<feed'))
612 return(fetch_xrd_links($pagelink));
614 // If we haven't found any links, return the host xrd links (which we have already fetched)
625 // Given a host name, locate the LRDD template from that
626 // host. Returns the LRDD template or an empty string on
629 if(! function_exists('fetch_lrdd_template')) {
630 function fetch_lrdd_template($host) {
633 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
634 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
635 $links = fetch_xrd_links($url1);
636 logger('fetch_lrdd_template from: ' . $url1);
637 logger('template (https): ' . print_r($links,true));
638 if(! count($links)) {
639 logger('fetch_lrdd_template from: ' . $url2);
640 $links = fetch_xrd_links($url2);
641 logger('template (http): ' . print_r($links,true));
644 foreach($links as $link)
645 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
646 $tpl = $link['@attributes']['template'];
648 if(! strpos($tpl,'{uri}'))
653 // Given a URL, retrieve the page as an XRD document.
654 // Return an array of links.
655 // on error/failure return empty array.
657 if(! function_exists('fetch_xrd_links')) {
658 function fetch_xrd_links($url) {
660 $xrd_timeout = intval(get_config('system','xrd_timeout'));
662 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
664 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
666 if ((! $xml) || (! stristr($xml,'<xrd')))
669 // fix diaspora's bad xml
670 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
672 $h = parse_xml_string($xml);
676 $arr = convert_xml_element_to_array($h);
680 if(isset($arr['xrd']['link'])) {
681 $link = $arr['xrd']['link'];
682 if(! isset($link[0]))
683 $links = array($link);
687 if(isset($arr['xrd']['alias'])) {
688 $alias = $arr['xrd']['alias'];
689 if(! isset($alias[0]))
690 $aliases = array($alias);
693 if(is_array($aliases) && count($aliases)) {
694 foreach($aliases as $alias) {
695 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
700 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
707 // Take a URL from the wild, prepend http:// if necessary
708 // and check DNS to see if it's real (or check if is a valid IP address)
709 // return true if it's OK, false if something is wrong with it
711 if(! function_exists('validate_url')) {
712 function validate_url(&$url) {
714 if(get_config('system','disable_url_validation'))
716 // no naked subdomains (allow localhost for tests)
717 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
719 if(substr($url,0,4) != 'http')
720 $url = 'http://' . $url;
721 $h = @parse_url($url);
723 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
729 // checks that email is an actual resolvable internet address
731 if(! function_exists('validate_email')) {
732 function validate_email($addr) {
734 if(get_config('system','disable_email_validation'))
737 if(! strpos($addr,'@'))
739 $h = substr($addr,strpos($addr,'@') + 1);
741 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
747 // Check $url against our list of allowed sites,
748 // wildcards allowed. If allowed_sites is unset return true;
749 // If url is allowed, return true.
750 // otherwise, return false
752 if(! function_exists('allowed_url')) {
753 function allowed_url($url) {
755 $h = @parse_url($url);
761 $str_allowed = get_config('system','allowed_sites');
767 $host = strtolower($h['host']);
769 // always allow our own site
771 if($host == strtolower($_SERVER['SERVER_NAME']))
774 $fnmatch = function_exists('fnmatch');
775 $allowed = explode(',',$str_allowed);
777 if(count($allowed)) {
778 foreach($allowed as $a) {
779 $pat = strtolower(trim($a));
780 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
789 // check if email address is allowed to register here.
790 // Compare against our list (wildcards allowed).
791 // Returns false if not allowed, true if allowed or if
792 // allowed list is not configured.
794 if(! function_exists('allowed_email')) {
795 function allowed_email($email) {
798 $domain = strtolower(substr($email,strpos($email,'@') + 1));
802 $str_allowed = get_config('system','allowed_email');
808 $fnmatch = function_exists('fnmatch');
809 $allowed = explode(',',$str_allowed);
811 if(count($allowed)) {
812 foreach($allowed as $a) {
813 $pat = strtolower(trim($a));
814 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
824 if(! function_exists('avatar_img')) {
825 function avatar_img($email) {
829 $avatar['size'] = 175;
830 $avatar['email'] = $email;
832 $avatar['success'] = false;
834 call_hooks('avatar_lookup', $avatar);
836 if(! $avatar['success'])
837 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
839 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
840 return $avatar['url'];
844 if(! function_exists('parse_xml_string')) {
845 function parse_xml_string($s,$strict = true) {
847 if(! strstr($s,'<?xml'))
849 $s2 = substr($s,strpos($s,'<?xml'));
853 libxml_use_internal_errors(true);
855 $x = @simplexml_load_string($s2);
857 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
858 foreach(libxml_get_errors() as $err)
859 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
860 libxml_clear_errors();
865 function add_fcontact($arr,$update = false) {
868 $r = q("UPDATE `fcontact` SET
881 WHERE `url` = '%s' AND `network` = '%s'",
883 dbesc($arr['photo']),
884 dbesc($arr['request']),
887 dbesc($arr['batch']),
888 dbesc($arr['notify']),
890 dbesc($arr['confirm']),
891 dbesc($arr['alias']),
892 dbesc($arr['pubkey']),
893 dbesc(datetime_convert()),
895 dbesc($arr['network'])
899 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
900 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
901 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
904 dbesc($arr['photo']),
905 dbesc($arr['request']),
908 dbesc($arr['batch']),
909 dbesc($arr['notify']),
911 dbesc($arr['confirm']),
912 dbesc($arr['network']),
913 dbesc($arr['alias']),
914 dbesc($arr['pubkey']),
915 dbesc(datetime_convert())
923 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
925 // Suppress "view full size"
926 if (intval(get_config('system','no_view_full_size')))
927 $include_link = false;
931 // Picture addresses can contain special characters
932 $s = htmlspecialchars_decode($srctext);
935 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
937 require_once('include/Photo.php');
938 foreach($matches as $mtch) {
939 logger('scale_external_image: ' . $mtch[1]);
941 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
942 if(stristr($mtch[1],$hostname))
945 // $scale_replace, if passed, is an array of two elements. The
946 // first is the name of the full-size image. The second is the
947 // name of a remote, scaled-down version of the full size image.
948 // This allows Friendica to display the smaller remote image if
949 // one exists, while still linking to the full-size image
951 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
954 $i = @fetch_url($scaled);
958 // guess mimetype from headers or filename
959 $type = guess_image_type($mtch[1],true);
962 $ph = new Photo($i, $type);
963 if($ph->is_valid()) {
964 $orig_width = $ph->getWidth();
965 $orig_height = $ph->getHeight();
967 if($orig_width > 640 || $orig_height > 640) {
969 $ph->scaleImage(640);
970 $new_width = $ph->getWidth();
971 $new_height = $ph->getHeight();
972 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
973 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
974 . "\n" . (($include_link)
975 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
977 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
984 // replace the special char encoding
985 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
990 function fix_contact_ssl_policy(&$contact,$new_policy) {
992 $ssl_changed = false;
993 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
995 $contact['url'] = str_replace('https:','http:',$contact['url']);
996 $contact['request'] = str_replace('https:','http:',$contact['request']);
997 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
998 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
999 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
1000 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
1003 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
1004 $ssl_changed = true;
1005 $contact['url'] = str_replace('http:','https:',$contact['url']);
1006 $contact['request'] = str_replace('http:','https:',$contact['request']);
1007 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
1008 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
1009 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
1010 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
1014 q("update contact set
1021 where id = %d limit 1",
1022 dbesc($contact['url']),
1023 dbesc($contact['request']),
1024 dbesc($contact['notify']),
1025 dbesc($contact['poll']),
1026 dbesc($contact['confirm']),
1027 dbesc($contact['poco']),
1028 intval($contact['id'])
1036 * xml2array() will convert the given XML text to an array in the XML structure.
1037 * Link: http://www.bin-co.com/php/scripts/xml2array/
1038 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
1039 * Arguments : $contents - The XML text
1040 * $namespaces - true or false include namespace information in the returned array as array elements.
1041 * $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.
1042 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
1043 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
1044 * Examples: $array = xml2array(file_get_contents('feed.xml'));
1045 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
1048 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
1049 if(!$contents) return array();
1051 if(!function_exists('xml_parser_create')) {
1052 logger('xml2array: parser function missing');
1057 libxml_use_internal_errors(true);
1058 libxml_clear_errors();
1061 $parser = @xml_parser_create_ns("UTF-8",':');
1063 $parser = @xml_parser_create();
1066 logger('xml2array: xml_parser_create: no resource');
1070 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
1071 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
1072 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1073 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
1074 @xml_parse_into_struct($parser, trim($contents), $xml_values);
1075 @xml_parser_free($parser);
1078 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
1079 foreach(libxml_get_errors() as $err)
1080 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
1081 libxml_clear_errors();
1086 $xml_array = array();
1088 $opened_tags = array();
1091 $current = &$xml_array; // Reference
1093 // Go through the tags.
1094 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1095 foreach($xml_values as $data) {
1096 unset($attributes,$value); // Remove existing values, or there will be trouble
1098 // This command will extract these variables into the foreach scope
1099 // tag(string), type(string), level(int), attributes(array).
1100 extract($data); // We could use the array by itself, but this cooler.
1103 $attributes_data = array();
1106 if($priority == 'tag') $result = $value;
1107 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1110 //Set the attributes too.
1111 if(isset($attributes) and $get_attributes) {
1112 foreach($attributes as $attr => $val) {
1113 if($priority == 'tag') $attributes_data[$attr] = $val;
1114 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1118 // See tag status and do the needed.
1119 if($namespaces && strpos($tag,':')) {
1120 $namespc = substr($tag,0,strrpos($tag,':'));
1121 $tag = strtolower(substr($tag,strlen($namespc)+1));
1122 $result['@namespace'] = $namespc;
1124 $tag = strtolower($tag);
1126 if($type == "open") { // The starting of the tag '<tag>'
1127 $parent[$level-1] = &$current;
1128 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1129 $current[$tag] = $result;
1130 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1131 $repeated_tag_index[$tag.'_'.$level] = 1;
1133 $current = &$current[$tag];
1135 } else { // There was another element with the same tag name
1137 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1138 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1139 $repeated_tag_index[$tag.'_'.$level]++;
1140 } else { // This section will make the value an array if multiple tags with the same name appear together
1141 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1142 $repeated_tag_index[$tag.'_'.$level] = 2;
1144 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1145 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1146 unset($current[$tag.'_attr']);
1150 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1151 $current = &$current[$tag][$last_item_index];
1154 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1155 //See if the key is already taken.
1156 if(!isset($current[$tag])) { //New Key
1157 $current[$tag] = $result;
1158 $repeated_tag_index[$tag.'_'.$level] = 1;
1159 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1161 } else { // If taken, put all things inside a list(array)
1162 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1164 // ...push the new element into that array.
1165 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1167 if($priority == 'tag' and $get_attributes and $attributes_data) {
1168 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1170 $repeated_tag_index[$tag.'_'.$level]++;
1172 } else { // If it is not an array...
1173 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1174 $repeated_tag_index[$tag.'_'.$level] = 1;
1175 if($priority == 'tag' and $get_attributes) {
1176 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1178 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1179 unset($current[$tag.'_attr']);
1182 if($attributes_data) {
1183 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1186 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1190 } elseif($type == 'close') { // End of tag '</tag>'
1191 $current = &$parent[$level-1];
1198 function original_url($url, $depth=1, $fetchbody = false) {
1202 // Remove Analytics Data from Google and other tracking platforms
1203 $urldata = parse_url($url);
1204 if (is_string($urldata["query"])) {
1205 $query = $urldata["query"];
1206 parse_str($query, $querydata);
1208 if (is_array($querydata))
1209 foreach ($querydata AS $param=>$value)
1210 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1211 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1212 "fb_action_ids", "fb_action_types", "fb_ref",
1214 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1216 $pair = $param."=".urlencode($value);
1217 $url = str_replace($pair, "", $url);
1219 // Second try: if the url isn't encoded completely
1220 $pair = $param."=".str_replace(" ", "+", $value);
1221 $url = str_replace($pair, "", $url);
1223 // Third try: Maybey the url isn't encoded at all
1224 $pair = $param."=".$value;
1225 $url = str_replace($pair, "", $url);
1227 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1230 if (substr($url, -1, 1) == "?")
1231 $url = substr($url, 0, -1);
1237 $url = trim($url, "'");
1239 $stamp1 = microtime(true);
1241 $siteinfo = array();
1243 curl_setopt($ch, CURLOPT_URL, $url);
1244 curl_setopt($ch, CURLOPT_HEADER, 1);
1245 curl_setopt($ch, CURLOPT_NOBODY, 1);
1246 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1247 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1248 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1250 $header = curl_exec($ch);
1251 $curl_info = @curl_getinfo($ch);
1252 $http_code = $curl_info['http_code'];
1255 $a->save_timestamp($stamp1, "network");
1257 if ($http_code == 0)
1260 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1261 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1262 if ($curl_info['redirect_url'] != "")
1263 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1265 return(original_url($curl_info['location'], ++$depth, $fetchbody));
1268 // Check for redirects in the meta elements of the body if there are no redirects in the header.
1270 return(original_url($url, ++$depth, true));
1272 // if the file is too large then exit
1273 if ($curl_info["download_content_length"] > 1000000)
1276 // if it isn't a HTML file then exit
1277 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
1280 $stamp1 = microtime(true);
1283 curl_setopt($ch, CURLOPT_URL, $url);
1284 curl_setopt($ch, CURLOPT_HEADER, 0);
1285 curl_setopt($ch, CURLOPT_NOBODY, 0);
1286 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1287 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1288 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1290 $body = curl_exec($ch);
1293 $a->save_timestamp($stamp1, "network");
1295 if (trim($body) == "")
1298 // Check for redirect in meta elements
1299 $doc = new DOMDocument();
1300 @$doc->loadHTML($body);
1302 $xpath = new DomXPath($doc);
1304 $list = $xpath->query("//meta[@content]");
1305 foreach ($list as $node) {
1307 if ($node->attributes->length)
1308 foreach ($node->attributes as $attribute)
1309 $attr[$attribute->name] = $attribute->value;
1311 if (@$attr["http-equiv"] == 'refresh') {
1312 $path = $attr["content"];
1313 $pathinfo = explode(";", $path);
1315 foreach ($pathinfo AS $value)
1316 if (substr(strtolower($value), 0, 4) == "url=")
1317 return(original_url(substr($value, 4), ++$depth));
1324 if (!function_exists('short_link')) {
1325 function short_link($url) {
1326 require_once('library/slinky.php');
1327 $slinky = new Slinky($url);
1328 $yourls_url = get_config('yourls','url1');
1330 $yourls_username = get_config('yourls','username1');
1331 $yourls_password = get_config('yourls', 'password1');
1332 $yourls_ssl = get_config('yourls', 'ssl1');
1333 $yourls = new Slinky_YourLS();
1334 $yourls->set('username', $yourls_username);
1335 $yourls->set('password', $yourls_password);
1336 $yourls->set('ssl', $yourls_ssl);
1337 $yourls->set('yourls-url', $yourls_url);
1338 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1340 // setup a cascade of shortening services
1341 // try to get a short link from these services
1342 // in the order ur1.ca, trim, id.gd, tinyurl
1343 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1345 return $slinky->short();