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(intval($timeout)) {
90 @curl_setopt($ch, CURLOPT_TIMEOUT, $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);
122 $curl_info = @curl_getinfo($ch);
124 $http_code = $curl_info['http_code'];
125 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
128 // Pull out multiple headers, e.g. proxy and continuation headers
129 // allow for HTTP/2.x without fixing code
131 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
132 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
134 $base = substr($base,strlen($chunk));
137 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
138 $new_location_info = @parse_url($curl_info["redirect_url"]);
139 $old_location_info = @parse_url($curl_info["url"]);
141 $newurl = $curl_info["redirect_url"];
143 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
144 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
147 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
148 $newurl = trim(array_pop($matches));
150 if(strpos($newurl,'/') === 0)
151 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
152 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
155 return z_fetch_url($newurl,$binary, $redirects, $opts);
160 $a->set_curl_code($http_code);
161 $a->set_curl_content_type($curl_info['content_type']);
163 $body = substr($s,strlen($header));
164 $a->set_curl_headers($header);
168 $rc = intval($http_code);
169 $ret['return_code'] = $rc;
170 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
171 if(! $ret['success']) {
172 $ret['error'] = curl_error($ch);
173 $ret['debug'] = $curl_info;
174 logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
175 logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
177 $ret['body'] = substr($s,strlen($header));
178 $ret['header'] = $header;
179 if(x($opts,'debug')) {
180 $ret['debug'] = $curl_info;
184 $a->save_timestamp($stamp1, "network");
190 // post request to $url. $params is an array of post variables.
192 if(! function_exists('post_url')) {
193 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
194 $stamp1 = microtime(true);
197 $ch = curl_init($url);
198 if(($redirects > 8) || (! $ch))
201 logger("post_url: start ".$url, LOGGER_DATA);
203 curl_setopt($ch, CURLOPT_HEADER, true);
204 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
205 curl_setopt($ch, CURLOPT_POST,1);
206 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
207 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
209 if(intval($timeout)) {
210 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
213 $curl_time = intval(get_config('system','curl_timeout'));
214 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
217 if(defined('LIGHTTPD')) {
218 if(!is_array($headers)) {
219 $headers = array('Expect:');
221 if(!in_array('Expect:', $headers)) {
222 array_push($headers, 'Expect:');
227 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
229 $check_cert = get_config('system','verifyssl');
230 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
231 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
232 $prx = get_config('system','proxy');
234 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
235 curl_setopt($ch, CURLOPT_PROXY, $prx);
236 $prxusr = get_config('system','proxyuser');
238 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
241 $a->set_curl_code(0);
243 // don't let curl abort the entire application
244 // if it throws any errors.
246 $s = @curl_exec($ch);
249 $curl_info = curl_getinfo($ch);
250 $http_code = $curl_info['http_code'];
252 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
256 // Pull out multiple headers, e.g. proxy and continuation headers
257 // allow for HTTP/2.x without fixing code
259 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
260 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
262 $base = substr($base,strlen($chunk));
265 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
267 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
268 $newurl = trim(array_pop($matches));
269 if(strpos($newurl,'/') === 0)
270 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
271 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
273 logger("post_url: redirect ".$url." to ".$newurl);
274 return post_url($newurl,$params, $headers, $redirects, $timeout);
275 //return fetch_url($newurl,false,$redirects,$timeout);
278 $a->set_curl_code($http_code);
279 $body = substr($s,strlen($header));
281 $a->set_curl_headers($header);
285 $a->save_timestamp($stamp1, "network");
287 logger("post_url: end ".$url, LOGGER_DATA);
292 // Generic XML return
293 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
294 // of $st and an optional text <message> of $message and terminates the current process.
296 if(! function_exists('xml_status')) {
297 function xml_status($st, $message = '') {
299 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
302 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
304 header( "Content-type: text/xml" );
305 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
306 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
311 if(! function_exists('http_status_exit')) {
312 function http_status_exit($val, $description = array()) {
316 if (!isset($description["title"]))
317 $description["title"] = $err." ".$val;
319 if($val >= 200 && $val < 300)
322 logger('http_status_exit ' . $val);
323 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
325 if (isset($description["title"])) {
326 $tpl = get_markup_template('http_status.tpl');
327 echo replace_macros($tpl, array('$title' => $description["title"],
328 '$description' => $description["description"]));
336 // convert an XML document to a normalised, case-corrected array
339 if(! function_exists('convert_xml_element_to_array')) {
340 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
342 // If we're getting too deep, bail out
343 if ($recursion_depth > 512) {
347 if (!is_string($xml_element) &&
348 !is_array($xml_element) &&
349 (get_class($xml_element) == 'SimpleXMLElement')) {
350 $xml_element_copy = $xml_element;
351 $xml_element = get_object_vars($xml_element);
354 if (is_array($xml_element)) {
355 $result_array = array();
356 if (count($xml_element) <= 0) {
357 return (trim(strval($xml_element_copy)));
360 foreach($xml_element as $key=>$value) {
363 $result_array[strtolower($key)] =
364 convert_xml_element_to_array($value, $recursion_depth);
367 if ($recursion_depth == 0) {
368 $temp_array = $result_array;
369 $result_array = array(
370 strtolower($xml_element_copy->getName()) => $temp_array,
374 return ($result_array);
377 return (trim(strval($xml_element)));
381 // Given an email style address, perform webfinger lookup and
382 // return the resulting DFRN profile URL, or if no DFRN profile URL
383 // is located, returns an OStatus subscription template (prefixed
384 // with the string 'stat:' to identify it as on OStatus template).
385 // If this isn't an email style address just return $s.
386 // Return an empty string if email-style addresses but webfinger fails,
387 // or if the resultant personal XRD doesn't contain a supported
388 // subscription/friend-request attribute.
390 // amended 7/9/2011 to return an hcard which could save potentially loading
391 // a lengthy content page to scrape dfrn attributes
393 if(! function_exists('webfinger_dfrn')) {
394 function webfinger_dfrn($s,&$hcard) {
395 if(! strstr($s,'@')) {
400 $links = webfinger($s);
401 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
403 foreach($links as $link) {
404 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
405 $profile_link = $link['@attributes']['href'];
406 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
407 $profile_link = 'stat:' . $link['@attributes']['template'];
408 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
409 $hcard = $link['@attributes']['href'];
412 return $profile_link;
415 // Given an email style address, perform webfinger lookup and
416 // return the array of link attributes from the personal XRD file.
417 // On error/failure return an empty array.
420 if(! function_exists('webfinger')) {
421 function webfinger($s, $debug = false) {
424 $host = substr($s,strpos($s,'@') + 1);
427 $tpl = fetch_lrdd_template($host);
428 logger('webfinger: lrdd template: ' . $tpl);
430 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
431 logger('webfinger: pxrd: ' . $pxrd);
432 $links = fetch_xrd_links($pxrd);
433 if(! count($links)) {
434 // try with double slashes
435 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
436 logger('webfinger: pxrd: ' . $pxrd);
437 $links = fetch_xrd_links($pxrd);
445 if(! function_exists('lrdd')) {
446 function lrdd($uri, $debug = false) {
450 // default priority is host priority, host-meta first
454 // All we have is an email address. Resource-priority is irrelevant
455 // because our URI isn't directly resolvable.
457 if(strstr($uri,'@')) {
458 return(webfinger($uri));
461 // get the host meta file
463 $host = @parse_url($uri);
466 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
467 $url .= $host['host'] . '/.well-known/host-meta' ;
472 logger('lrdd: constructed url: ' . $url);
474 $xml = fetch_url($url);
476 $headers = $a->get_curl_headers();
481 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
483 if(! stristr($xml,'<xrd'))
486 $h = parse_xml_string($xml);
490 $arr = convert_xml_element_to_array($h);
492 if(isset($arr['xrd']['property'])) {
493 $property = $arr['crd']['property'];
494 if(! isset($property[0]))
495 $properties = array($property);
497 $properties = $property;
498 foreach($properties as $prop)
499 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
500 $priority = 'resource';
503 // save the links in case we need them
507 if(isset($arr['xrd']['link'])) {
508 $link = $arr['xrd']['link'];
509 if(! isset($link[0]))
510 $links = array($link);
515 // do we have a template or href?
518 foreach($links as $link) {
519 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
520 if(x($link['@attributes'],'template'))
521 $tpl = $link['@attributes']['template'];
522 elseif(x($link['@attributes'],'href'))
523 $href = $link['@attributes']['href'];
528 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
531 if($priority === 'host') {
533 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
537 logger('lrdd: (host priority) pxrd: ' . $pxrd);
538 $links = fetch_xrd_links($pxrd);
542 $lines = explode("\n",$headers);
544 foreach($lines as $line) {
545 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
546 return(fetch_xrd_links($matches[1]));
554 // priority 'resource'
557 $html = fetch_url($uri);
558 $headers = $a->get_curl_headers();
559 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
561 // don't try and parse raw xml as html
562 if(! strstr($html,'<?xml')) {
563 require_once('library/HTML5/Parser.php');
566 $dom = HTML5_Parser::parse($html);
567 } catch (DOMException $e) {
568 logger('lrdd: parse error: ' . $e);
571 if(isset($dom) && $dom) {
572 $items = $dom->getElementsByTagName('link');
573 foreach($items as $item) {
574 $x = $item->getAttribute('rel');
576 $pagelink = $item->getAttribute('href');
584 return(fetch_xrd_links($pagelink));
586 // next look in HTTP headers
588 $lines = explode("\n",$headers);
590 foreach($lines as $line) {
591 // TODO alter the following regex to support multiple relations (space separated)
592 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
593 $pagelink = $matches[1];
596 // don't try and run feeds through the html5 parser
597 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
599 if(stristr($html,'<rss') || stristr($html,'<feed'))
605 return(fetch_xrd_links($pagelink));
607 // If we haven't found any links, return the host xrd links (which we have already fetched)
618 // Given a host name, locate the LRDD template from that
619 // host. Returns the LRDD template or an empty string on
622 if(! function_exists('fetch_lrdd_template')) {
623 function fetch_lrdd_template($host) {
626 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
627 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
628 $links = fetch_xrd_links($url1);
629 logger('fetch_lrdd_template from: ' . $url1);
630 logger('template (https): ' . print_r($links,true));
631 if(! count($links)) {
632 logger('fetch_lrdd_template from: ' . $url2);
633 $links = fetch_xrd_links($url2);
634 logger('template (http): ' . print_r($links,true));
637 foreach($links as $link)
638 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
639 $tpl = $link['@attributes']['template'];
641 if(! strpos($tpl,'{uri}'))
646 // Given a URL, retrieve the page as an XRD document.
647 // Return an array of links.
648 // on error/failure return empty array.
650 if(! function_exists('fetch_xrd_links')) {
651 function fetch_xrd_links($url) {
653 $xrd_timeout = intval(get_config('system','xrd_timeout'));
655 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
657 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
659 if ((! $xml) || (! stristr($xml,'<xrd')))
662 // fix diaspora's bad xml
663 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
665 $h = parse_xml_string($xml);
669 $arr = convert_xml_element_to_array($h);
673 if(isset($arr['xrd']['link'])) {
674 $link = $arr['xrd']['link'];
675 if(! isset($link[0]))
676 $links = array($link);
680 if(isset($arr['xrd']['alias'])) {
681 $alias = $arr['xrd']['alias'];
682 if(! isset($alias[0]))
683 $aliases = array($alias);
686 if(is_array($aliases) && count($aliases)) {
687 foreach($aliases as $alias) {
688 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
693 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
700 // Take a URL from the wild, prepend http:// if necessary
701 // and check DNS to see if it's real (or check if is a valid IP address)
702 // return true if it's OK, false if something is wrong with it
704 if(! function_exists('validate_url')) {
705 function validate_url(&$url) {
707 if(get_config('system','disable_url_validation'))
709 // no naked subdomains (allow localhost for tests)
710 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
712 if(substr($url,0,4) != 'http')
713 $url = 'http://' . $url;
714 $h = @parse_url($url);
716 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
722 // checks that email is an actual resolvable internet address
724 if(! function_exists('validate_email')) {
725 function validate_email($addr) {
727 if(get_config('system','disable_email_validation'))
730 if(! strpos($addr,'@'))
732 $h = substr($addr,strpos($addr,'@') + 1);
734 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
740 // Check $url against our list of allowed sites,
741 // wildcards allowed. If allowed_sites is unset return true;
742 // If url is allowed, return true.
743 // otherwise, return false
745 if(! function_exists('allowed_url')) {
746 function allowed_url($url) {
748 $h = @parse_url($url);
754 $str_allowed = get_config('system','allowed_sites');
760 $host = strtolower($h['host']);
762 // always allow our own site
764 if($host == strtolower($_SERVER['SERVER_NAME']))
767 $fnmatch = function_exists('fnmatch');
768 $allowed = explode(',',$str_allowed);
770 if(count($allowed)) {
771 foreach($allowed as $a) {
772 $pat = strtolower(trim($a));
773 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
782 // check if email address is allowed to register here.
783 // Compare against our list (wildcards allowed).
784 // Returns false if not allowed, true if allowed or if
785 // allowed list is not configured.
787 if(! function_exists('allowed_email')) {
788 function allowed_email($email) {
791 $domain = strtolower(substr($email,strpos($email,'@') + 1));
795 $str_allowed = get_config('system','allowed_email');
801 $fnmatch = function_exists('fnmatch');
802 $allowed = explode(',',$str_allowed);
804 if(count($allowed)) {
805 foreach($allowed as $a) {
806 $pat = strtolower(trim($a));
807 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
817 if(! function_exists('avatar_img')) {
818 function avatar_img($email) {
822 $avatar['size'] = 175;
823 $avatar['email'] = $email;
825 $avatar['success'] = false;
827 call_hooks('avatar_lookup', $avatar);
829 if(! $avatar['success'])
830 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
832 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
833 return $avatar['url'];
837 if(! function_exists('parse_xml_string')) {
838 function parse_xml_string($s,$strict = true) {
840 if(! strstr($s,'<?xml'))
842 $s2 = substr($s,strpos($s,'<?xml'));
846 libxml_use_internal_errors(true);
848 $x = @simplexml_load_string($s2);
850 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
851 foreach(libxml_get_errors() as $err)
852 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
853 libxml_clear_errors();
858 function add_fcontact($arr,$update = false) {
861 $r = q("UPDATE `fcontact` SET
874 WHERE `url` = '%s' AND `network` = '%s'",
876 dbesc($arr['photo']),
877 dbesc($arr['request']),
880 dbesc($arr['batch']),
881 dbesc($arr['notify']),
883 dbesc($arr['confirm']),
884 dbesc($arr['alias']),
885 dbesc($arr['pubkey']),
886 dbesc(datetime_convert()),
888 dbesc($arr['network'])
892 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
893 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
894 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
897 dbesc($arr['photo']),
898 dbesc($arr['request']),
901 dbesc($arr['batch']),
902 dbesc($arr['notify']),
904 dbesc($arr['confirm']),
905 dbesc($arr['network']),
906 dbesc($arr['alias']),
907 dbesc($arr['pubkey']),
908 dbesc(datetime_convert())
916 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
918 // Suppress "view full size"
919 if (intval(get_config('system','no_view_full_size')))
920 $include_link = false;
924 // Picture addresses can contain special characters
925 $s = htmlspecialchars_decode($srctext);
928 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
930 require_once('include/Photo.php');
931 foreach($matches as $mtch) {
932 logger('scale_external_image: ' . $mtch[1]);
934 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
935 if(stristr($mtch[1],$hostname))
938 // $scale_replace, if passed, is an array of two elements. The
939 // first is the name of the full-size image. The second is the
940 // name of a remote, scaled-down version of the full size image.
941 // This allows Friendica to display the smaller remote image if
942 // one exists, while still linking to the full-size image
944 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
947 $i = @fetch_url($scaled);
951 // guess mimetype from headers or filename
952 $type = guess_image_type($mtch[1],true);
955 $ph = new Photo($i, $type);
956 if($ph->is_valid()) {
957 $orig_width = $ph->getWidth();
958 $orig_height = $ph->getHeight();
960 if($orig_width > 640 || $orig_height > 640) {
962 $ph->scaleImage(640);
963 $new_width = $ph->getWidth();
964 $new_height = $ph->getHeight();
965 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
966 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
967 . "\n" . (($include_link)
968 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
970 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
977 // replace the special char encoding
978 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
983 function fix_contact_ssl_policy(&$contact,$new_policy) {
985 $ssl_changed = false;
986 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
988 $contact['url'] = str_replace('https:','http:',$contact['url']);
989 $contact['request'] = str_replace('https:','http:',$contact['request']);
990 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
991 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
992 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
993 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
996 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
998 $contact['url'] = str_replace('http:','https:',$contact['url']);
999 $contact['request'] = str_replace('http:','https:',$contact['request']);
1000 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
1001 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
1002 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
1003 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
1007 q("update contact set
1014 where id = %d limit 1",
1015 dbesc($contact['url']),
1016 dbesc($contact['request']),
1017 dbesc($contact['notify']),
1018 dbesc($contact['poll']),
1019 dbesc($contact['confirm']),
1020 dbesc($contact['poco']),
1021 intval($contact['id'])
1029 * xml2array() will convert the given XML text to an array in the XML structure.
1030 * Link: http://www.bin-co.com/php/scripts/xml2array/
1031 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
1032 * Arguments : $contents - The XML text
1033 * $namespaces - true or false include namespace information in the returned array as array elements.
1034 * $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.
1035 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
1036 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
1037 * Examples: $array = xml2array(file_get_contents('feed.xml'));
1038 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
1041 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
1042 if(!$contents) return array();
1044 if(!function_exists('xml_parser_create')) {
1045 logger('xml2array: parser function missing');
1050 libxml_use_internal_errors(true);
1051 libxml_clear_errors();
1054 $parser = @xml_parser_create_ns("UTF-8",':');
1056 $parser = @xml_parser_create();
1059 logger('xml2array: xml_parser_create: no resource');
1063 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
1064 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
1065 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1066 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
1067 @xml_parse_into_struct($parser, trim($contents), $xml_values);
1068 @xml_parser_free($parser);
1071 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
1072 foreach(libxml_get_errors() as $err)
1073 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
1074 libxml_clear_errors();
1079 $xml_array = array();
1081 $opened_tags = array();
1084 $current = &$xml_array; // Reference
1086 // Go through the tags.
1087 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1088 foreach($xml_values as $data) {
1089 unset($attributes,$value); // Remove existing values, or there will be trouble
1091 // This command will extract these variables into the foreach scope
1092 // tag(string), type(string), level(int), attributes(array).
1093 extract($data); // We could use the array by itself, but this cooler.
1096 $attributes_data = array();
1099 if($priority == 'tag') $result = $value;
1100 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1103 //Set the attributes too.
1104 if(isset($attributes) and $get_attributes) {
1105 foreach($attributes as $attr => $val) {
1106 if($priority == 'tag') $attributes_data[$attr] = $val;
1107 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1111 // See tag status and do the needed.
1112 if($namespaces && strpos($tag,':')) {
1113 $namespc = substr($tag,0,strrpos($tag,':'));
1114 $tag = strtolower(substr($tag,strlen($namespc)+1));
1115 $result['@namespace'] = $namespc;
1117 $tag = strtolower($tag);
1119 if($type == "open") { // The starting of the tag '<tag>'
1120 $parent[$level-1] = &$current;
1121 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1122 $current[$tag] = $result;
1123 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1124 $repeated_tag_index[$tag.'_'.$level] = 1;
1126 $current = &$current[$tag];
1128 } else { // There was another element with the same tag name
1130 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1131 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1132 $repeated_tag_index[$tag.'_'.$level]++;
1133 } else { // This section will make the value an array if multiple tags with the same name appear together
1134 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1135 $repeated_tag_index[$tag.'_'.$level] = 2;
1137 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1138 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1139 unset($current[$tag.'_attr']);
1143 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1144 $current = &$current[$tag][$last_item_index];
1147 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1148 //See if the key is already taken.
1149 if(!isset($current[$tag])) { //New Key
1150 $current[$tag] = $result;
1151 $repeated_tag_index[$tag.'_'.$level] = 1;
1152 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1154 } else { // If taken, put all things inside a list(array)
1155 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1157 // ...push the new element into that array.
1158 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1160 if($priority == 'tag' and $get_attributes and $attributes_data) {
1161 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1163 $repeated_tag_index[$tag.'_'.$level]++;
1165 } else { // If it is not an array...
1166 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1167 $repeated_tag_index[$tag.'_'.$level] = 1;
1168 if($priority == 'tag' and $get_attributes) {
1169 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1171 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1172 unset($current[$tag.'_attr']);
1175 if($attributes_data) {
1176 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1179 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1183 } elseif($type == 'close') { // End of tag '</tag>'
1184 $current = &$parent[$level-1];
1191 function original_url($url, $depth=1, $fetchbody = false) {
1195 // Remove Analytics Data from Google and other tracking platforms
1196 $urldata = parse_url($url);
1197 if (is_string($urldata["query"])) {
1198 $query = $urldata["query"];
1199 parse_str($query, $querydata);
1201 if (is_array($querydata))
1202 foreach ($querydata AS $param=>$value)
1203 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1204 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1205 "fb_action_ids", "fb_action_types", "fb_ref",
1207 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1209 $pair = $param."=".urlencode($value);
1210 $url = str_replace($pair, "", $url);
1212 // Second try: if the url isn't encoded completely
1213 $pair = $param."=".str_replace(" ", "+", $value);
1214 $url = str_replace($pair, "", $url);
1216 // Third try: Maybey the url isn't encoded at all
1217 $pair = $param."=".$value;
1218 $url = str_replace($pair, "", $url);
1220 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1223 if (substr($url, -1, 1) == "?")
1224 $url = substr($url, 0, -1);
1230 $url = trim($url, "'");
1232 $stamp1 = microtime(true);
1234 $siteinfo = array();
1236 curl_setopt($ch, CURLOPT_URL, $url);
1237 curl_setopt($ch, CURLOPT_HEADER, 1);
1238 curl_setopt($ch, CURLOPT_NOBODY, 1);
1239 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1240 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1241 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1243 $header = curl_exec($ch);
1244 $curl_info = @curl_getinfo($ch);
1245 $http_code = $curl_info['http_code'];
1248 $a->save_timestamp($stamp1, "network");
1250 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1251 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1252 if ($curl_info['redirect_url'] != "")
1253 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1255 return(original_url($curl_info['location'], ++$depth, $fetchbody));
1258 // Check for redirects in the meta elements of the body if there are no redirects in the header.
1260 return(original_url($url, ++$depth, true));
1262 // if the file is too large then exit
1263 if ($curl_info["download_content_length"] > 1000000)
1266 // if it isn't a HTML file then exit
1267 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
1270 $stamp1 = microtime(true);
1273 curl_setopt($ch, CURLOPT_URL, $url);
1274 curl_setopt($ch, CURLOPT_HEADER, 0);
1275 curl_setopt($ch, CURLOPT_NOBODY, 0);
1276 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1277 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1278 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1280 $body = curl_exec($ch);
1283 $a->save_timestamp($stamp1, "network");
1285 if (trim($body) == "")
1288 // Check for redirect in meta elements
1289 $doc = new DOMDocument();
1290 @$doc->loadHTML($body);
1292 $xpath = new DomXPath($doc);
1294 $list = $xpath->query("//meta[@content]");
1295 foreach ($list as $node) {
1297 if ($node->attributes->length)
1298 foreach ($node->attributes as $attribute)
1299 $attr[$attribute->name] = $attribute->value;
1301 if (@$attr["http-equiv"] == 'refresh') {
1302 $path = $attr["content"];
1303 $pathinfo = explode(";", $path);
1305 foreach ($pathinfo AS $value)
1306 if (substr(strtolower($value), 0, 4) == "url=")
1307 return(original_url(substr($value, 4), ++$depth));
1314 if (!function_exists('short_link')) {
1315 function short_link($url) {
1316 require_once('library/slinky.php');
1317 $slinky = new Slinky($url);
1318 $yourls_url = get_config('yourls','url1');
1320 $yourls_username = get_config('yourls','username1');
1321 $yourls_password = get_config('yourls', 'password1');
1322 $yourls_ssl = get_config('yourls', 'ssl1');
1323 $yourls = new Slinky_YourLS();
1324 $yourls->set('username', $yourls_username);
1325 $yourls->set('password', $yourls_password);
1326 $yourls->set('ssl', $yourls_ssl);
1327 $yourls->set('yourls-url', $yourls_url);
1328 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1330 // setup a cascade of shortening services
1331 // try to get a short link from these services
1332 // in the order ur1.ca, trim, id.gd, tinyurl
1333 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1335 return $slinky->short();