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) {
12 $stamp1 = microtime(true);
16 $ch = @curl_init($url);
17 if(($redirects > 8) || (! $ch))
20 @curl_setopt($ch, CURLOPT_HEADER, true);
23 curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiejar);
24 curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiejar);
27 // These settings aren't needed. We're following the location already.
28 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
29 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
31 if (!is_null($accept_content)){
32 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
33 "Accept: " . $accept_content
37 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
38 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
41 if(intval($timeout)) {
42 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
45 $curl_time = intval(get_config('system','curl_timeout'));
46 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
48 // by default we will allow self-signed certs
49 // but you can override this
51 $check_cert = get_config('system','verifyssl');
52 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
53 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
55 $prx = get_config('system','proxy');
57 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
58 @curl_setopt($ch, CURLOPT_PROXY, $prx);
59 $prxusr = @get_config('system','proxyuser');
61 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
64 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
68 // don't let curl abort the entire application
69 // if it throws any errors.
74 $curl_info = @curl_getinfo($ch);
76 $http_code = $curl_info['http_code'];
77 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
80 // Pull out multiple headers, e.g. proxy and continuation headers
81 // allow for HTTP/2.x without fixing code
83 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
84 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
86 $base = substr($base,strlen($chunk));
89 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
90 $new_location_info = @parse_url($curl_info["redirect_url"]);
91 $old_location_info = @parse_url($curl_info["url"]);
93 $newurl = $curl_info["redirect_url"];
95 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
96 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
99 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
100 $newurl = trim(array_pop($matches));
102 if(strpos($newurl,'/') === 0)
103 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
104 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
106 return fetch_url($newurl,$binary,$redirects,$timeout,$accept_content,$cookiejar);
110 $a->set_curl_code($http_code);
111 $a->set_curl_content_type($curl_info['content_type']);
113 $body = substr($s,strlen($header));
114 $a->set_curl_headers($header);
116 $a->save_timestamp($stamp1, "network");
121 // post request to $url. $params is an array of post variables.
123 if(! function_exists('post_url')) {
124 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
125 $stamp1 = microtime(true);
128 $ch = curl_init($url);
129 if(($redirects > 8) || (! $ch))
132 logger("post_url: start ".$url, LOGGER_DATA);
134 curl_setopt($ch, CURLOPT_HEADER, true);
135 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
136 curl_setopt($ch, CURLOPT_POST,1);
137 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
138 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
140 if(intval($timeout)) {
141 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
144 $curl_time = intval(get_config('system','curl_timeout'));
145 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
148 if(defined('LIGHTTPD')) {
149 if(!is_array($headers)) {
150 $headers = array('Expect:');
152 if(!in_array('Expect:', $headers)) {
153 array_push($headers, 'Expect:');
158 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
160 $check_cert = get_config('system','verifyssl');
161 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
162 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
163 $prx = get_config('system','proxy');
165 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
166 curl_setopt($ch, CURLOPT_PROXY, $prx);
167 $prxusr = get_config('system','proxyuser');
169 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
172 $a->set_curl_code(0);
174 // don't let curl abort the entire application
175 // if it throws any errors.
177 $s = @curl_exec($ch);
180 $curl_info = curl_getinfo($ch);
181 $http_code = $curl_info['http_code'];
183 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
187 // Pull out multiple headers, e.g. proxy and continuation headers
188 // allow for HTTP/2.x without fixing code
190 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
191 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
193 $base = substr($base,strlen($chunk));
196 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
198 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
199 $newurl = trim(array_pop($matches));
200 if(strpos($newurl,'/') === 0)
201 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
202 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
204 logger("post_url: redirect ".$url." to ".$newurl);
205 return post_url($newurl,$params, $headers, $redirects, $timeout);
206 //return fetch_url($newurl,false,$redirects,$timeout);
209 $a->set_curl_code($http_code);
210 $body = substr($s,strlen($header));
212 $a->set_curl_headers($header);
216 $a->save_timestamp($stamp1, "network");
218 logger("post_url: end ".$url, LOGGER_DATA);
223 // Generic XML return
224 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
225 // of $st and an optional text <message> of $message and terminates the current process.
227 if(! function_exists('xml_status')) {
228 function xml_status($st, $message = '') {
230 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
233 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
235 header( "Content-type: text/xml" );
236 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
237 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
242 if(! function_exists('http_status_exit')) {
243 function http_status_exit($val) {
248 if($val >= 200 && $val < 300)
251 logger('http_status_exit ' . $val);
252 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
258 // convert an XML document to a normalised, case-corrected array
261 if(! function_exists('convert_xml_element_to_array')) {
262 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
264 // If we're getting too deep, bail out
265 if ($recursion_depth > 512) {
269 if (!is_string($xml_element) &&
270 !is_array($xml_element) &&
271 (get_class($xml_element) == 'SimpleXMLElement')) {
272 $xml_element_copy = $xml_element;
273 $xml_element = get_object_vars($xml_element);
276 if (is_array($xml_element)) {
277 $result_array = array();
278 if (count($xml_element) <= 0) {
279 return (trim(strval($xml_element_copy)));
282 foreach($xml_element as $key=>$value) {
285 $result_array[strtolower($key)] =
286 convert_xml_element_to_array($value, $recursion_depth);
289 if ($recursion_depth == 0) {
290 $temp_array = $result_array;
291 $result_array = array(
292 strtolower($xml_element_copy->getName()) => $temp_array,
296 return ($result_array);
299 return (trim(strval($xml_element)));
303 // Given an email style address, perform webfinger lookup and
304 // return the resulting DFRN profile URL, or if no DFRN profile URL
305 // is located, returns an OStatus subscription template (prefixed
306 // with the string 'stat:' to identify it as on OStatus template).
307 // If this isn't an email style address just return $s.
308 // Return an empty string if email-style addresses but webfinger fails,
309 // or if the resultant personal XRD doesn't contain a supported
310 // subscription/friend-request attribute.
312 // amended 7/9/2011 to return an hcard which could save potentially loading
313 // a lengthy content page to scrape dfrn attributes
315 if(! function_exists('webfinger_dfrn')) {
316 function webfinger_dfrn($s,&$hcard) {
317 if(! strstr($s,'@')) {
322 $links = webfinger($s);
323 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
325 foreach($links as $link) {
326 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
327 $profile_link = $link['@attributes']['href'];
328 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
329 $profile_link = 'stat:' . $link['@attributes']['template'];
330 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
331 $hcard = $link['@attributes']['href'];
334 return $profile_link;
337 // Given an email style address, perform webfinger lookup and
338 // return the array of link attributes from the personal XRD file.
339 // On error/failure return an empty array.
342 if(! function_exists('webfinger')) {
343 function webfinger($s, $debug = false) {
346 $host = substr($s,strpos($s,'@') + 1);
349 $tpl = fetch_lrdd_template($host);
350 logger('webfinger: lrdd template: ' . $tpl);
352 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
353 logger('webfinger: pxrd: ' . $pxrd);
354 $links = fetch_xrd_links($pxrd);
355 if(! count($links)) {
356 // try with double slashes
357 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
358 logger('webfinger: pxrd: ' . $pxrd);
359 $links = fetch_xrd_links($pxrd);
367 if(! function_exists('lrdd')) {
368 function lrdd($uri, $debug = false) {
372 // default priority is host priority, host-meta first
376 // All we have is an email address. Resource-priority is irrelevant
377 // because our URI isn't directly resolvable.
379 if(strstr($uri,'@')) {
380 return(webfinger($uri));
383 // get the host meta file
385 $host = @parse_url($uri);
388 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
389 $url .= $host['host'] . '/.well-known/host-meta' ;
394 logger('lrdd: constructed url: ' . $url);
396 $xml = fetch_url($url);
398 $headers = $a->get_curl_headers();
403 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
405 if(! stristr($xml,'<xrd'))
408 $h = parse_xml_string($xml);
412 $arr = convert_xml_element_to_array($h);
414 if(isset($arr['xrd']['property'])) {
415 $property = $arr['crd']['property'];
416 if(! isset($property[0]))
417 $properties = array($property);
419 $properties = $property;
420 foreach($properties as $prop)
421 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
422 $priority = 'resource';
425 // save the links in case we need them
429 if(isset($arr['xrd']['link'])) {
430 $link = $arr['xrd']['link'];
431 if(! isset($link[0]))
432 $links = array($link);
437 // do we have a template or href?
440 foreach($links as $link) {
441 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
442 if(x($link['@attributes'],'template'))
443 $tpl = $link['@attributes']['template'];
444 elseif(x($link['@attributes'],'href'))
445 $href = $link['@attributes']['href'];
450 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
453 if($priority === 'host') {
455 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
459 logger('lrdd: (host priority) pxrd: ' . $pxrd);
460 $links = fetch_xrd_links($pxrd);
464 $lines = explode("\n",$headers);
466 foreach($lines as $line) {
467 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
468 return(fetch_xrd_links($matches[1]));
476 // priority 'resource'
479 $html = fetch_url($uri);
480 $headers = $a->get_curl_headers();
481 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
483 // don't try and parse raw xml as html
484 if(! strstr($html,'<?xml')) {
485 require_once('library/HTML5/Parser.php');
488 $dom = HTML5_Parser::parse($html);
489 } catch (DOMException $e) {
490 logger('lrdd: parse error: ' . $e);
493 if(isset($dom) && $dom) {
494 $items = $dom->getElementsByTagName('link');
495 foreach($items as $item) {
496 $x = $item->getAttribute('rel');
498 $pagelink = $item->getAttribute('href');
506 return(fetch_xrd_links($pagelink));
508 // next look in HTTP headers
510 $lines = explode("\n",$headers);
512 foreach($lines as $line) {
513 // TODO alter the following regex to support multiple relations (space separated)
514 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
515 $pagelink = $matches[1];
518 // don't try and run feeds through the html5 parser
519 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
521 if(stristr($html,'<rss') || stristr($html,'<feed'))
527 return(fetch_xrd_links($pagelink));
529 // If we haven't found any links, return the host xrd links (which we have already fetched)
540 // Given a host name, locate the LRDD template from that
541 // host. Returns the LRDD template or an empty string on
544 if(! function_exists('fetch_lrdd_template')) {
545 function fetch_lrdd_template($host) {
548 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
549 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
550 $links = fetch_xrd_links($url1);
551 logger('fetch_lrdd_template from: ' . $url1);
552 logger('template (https): ' . print_r($links,true));
553 if(! count($links)) {
554 logger('fetch_lrdd_template from: ' . $url2);
555 $links = fetch_xrd_links($url2);
556 logger('template (http): ' . print_r($links,true));
559 foreach($links as $link)
560 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
561 $tpl = $link['@attributes']['template'];
563 if(! strpos($tpl,'{uri}'))
568 // Given a URL, retrieve the page as an XRD document.
569 // Return an array of links.
570 // on error/failure return empty array.
572 if(! function_exists('fetch_xrd_links')) {
573 function fetch_xrd_links($url) {
575 $xrd_timeout = intval(get_config('system','xrd_timeout'));
577 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
579 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
581 if ((! $xml) || (! stristr($xml,'<xrd')))
584 // fix diaspora's bad xml
585 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
587 $h = parse_xml_string($xml);
591 $arr = convert_xml_element_to_array($h);
595 if(isset($arr['xrd']['link'])) {
596 $link = $arr['xrd']['link'];
597 if(! isset($link[0]))
598 $links = array($link);
602 if(isset($arr['xrd']['alias'])) {
603 $alias = $arr['xrd']['alias'];
604 if(! isset($alias[0]))
605 $aliases = array($alias);
608 if(is_array($aliases) && count($aliases)) {
609 foreach($aliases as $alias) {
610 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
615 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
622 // Take a URL from the wild, prepend http:// if necessary
623 // and check DNS to see if it's real (or check if is a valid IP address)
624 // return true if it's OK, false if something is wrong with it
626 if(! function_exists('validate_url')) {
627 function validate_url(&$url) {
629 if(get_config('system','disable_url_validation'))
631 // no naked subdomains (allow localhost for tests)
632 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
634 if(substr($url,0,4) != 'http')
635 $url = 'http://' . $url;
636 $h = @parse_url($url);
638 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
644 // checks that email is an actual resolvable internet address
646 if(! function_exists('validate_email')) {
647 function validate_email($addr) {
649 if(get_config('system','disable_email_validation'))
652 if(! strpos($addr,'@'))
654 $h = substr($addr,strpos($addr,'@') + 1);
656 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
662 // Check $url against our list of allowed sites,
663 // wildcards allowed. If allowed_sites is unset return true;
664 // If url is allowed, return true.
665 // otherwise, return false
667 if(! function_exists('allowed_url')) {
668 function allowed_url($url) {
670 $h = @parse_url($url);
676 $str_allowed = get_config('system','allowed_sites');
682 $host = strtolower($h['host']);
684 // always allow our own site
686 if($host == strtolower($_SERVER['SERVER_NAME']))
689 $fnmatch = function_exists('fnmatch');
690 $allowed = explode(',',$str_allowed);
692 if(count($allowed)) {
693 foreach($allowed as $a) {
694 $pat = strtolower(trim($a));
695 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
704 // check if email address is allowed to register here.
705 // Compare against our list (wildcards allowed).
706 // Returns false if not allowed, true if allowed or if
707 // allowed list is not configured.
709 if(! function_exists('allowed_email')) {
710 function allowed_email($email) {
713 $domain = strtolower(substr($email,strpos($email,'@') + 1));
717 $str_allowed = get_config('system','allowed_email');
723 $fnmatch = function_exists('fnmatch');
724 $allowed = explode(',',$str_allowed);
726 if(count($allowed)) {
727 foreach($allowed as $a) {
728 $pat = strtolower(trim($a));
729 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
739 if(! function_exists('avatar_img')) {
740 function avatar_img($email) {
744 $avatar['size'] = 175;
745 $avatar['email'] = $email;
747 $avatar['success'] = false;
749 call_hooks('avatar_lookup', $avatar);
751 if(! $avatar['success'])
752 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
754 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
755 return $avatar['url'];
759 if(! function_exists('parse_xml_string')) {
760 function parse_xml_string($s,$strict = true) {
762 if(! strstr($s,'<?xml'))
764 $s2 = substr($s,strpos($s,'<?xml'));
768 libxml_use_internal_errors(true);
770 $x = @simplexml_load_string($s2);
772 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
773 foreach(libxml_get_errors() as $err)
774 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
775 libxml_clear_errors();
780 function add_fcontact($arr,$update = false) {
783 $r = q("UPDATE `fcontact` SET
796 WHERE `url` = '%s' AND `network` = '%s'",
798 dbesc($arr['photo']),
799 dbesc($arr['request']),
802 dbesc($arr['batch']),
803 dbesc($arr['notify']),
805 dbesc($arr['confirm']),
806 dbesc($arr['alias']),
807 dbesc($arr['pubkey']),
808 dbesc(datetime_convert()),
810 dbesc($arr['network'])
814 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
815 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
816 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
819 dbesc($arr['photo']),
820 dbesc($arr['request']),
823 dbesc($arr['batch']),
824 dbesc($arr['notify']),
826 dbesc($arr['confirm']),
827 dbesc($arr['network']),
828 dbesc($arr['alias']),
829 dbesc($arr['pubkey']),
830 dbesc(datetime_convert())
838 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
840 // Suppress "view full size"
841 if (intval(get_config('system','no_view_full_size')))
842 $include_link = false;
846 // Picture addresses can contain special characters
847 $s = htmlspecialchars_decode($srctext);
850 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
852 require_once('include/Photo.php');
853 foreach($matches as $mtch) {
854 logger('scale_external_image: ' . $mtch[1]);
856 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
857 if(stristr($mtch[1],$hostname))
860 // $scale_replace, if passed, is an array of two elements. The
861 // first is the name of the full-size image. The second is the
862 // name of a remote, scaled-down version of the full size image.
863 // This allows Friendica to display the smaller remote image if
864 // one exists, while still linking to the full-size image
866 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
869 $i = @fetch_url($scaled);
873 // guess mimetype from headers or filename
874 $type = guess_image_type($mtch[1],true);
877 $ph = new Photo($i, $type);
878 if($ph->is_valid()) {
879 $orig_width = $ph->getWidth();
880 $orig_height = $ph->getHeight();
882 if($orig_width > 640 || $orig_height > 640) {
884 $ph->scaleImage(640);
885 $new_width = $ph->getWidth();
886 $new_height = $ph->getHeight();
887 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
888 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
889 . "\n" . (($include_link)
890 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
892 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
899 // replace the special char encoding
900 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
905 function fix_contact_ssl_policy(&$contact,$new_policy) {
907 $ssl_changed = false;
908 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
910 $contact['url'] = str_replace('https:','http:',$contact['url']);
911 $contact['request'] = str_replace('https:','http:',$contact['request']);
912 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
913 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
914 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
915 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
918 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
920 $contact['url'] = str_replace('http:','https:',$contact['url']);
921 $contact['request'] = str_replace('http:','https:',$contact['request']);
922 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
923 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
924 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
925 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
929 q("update contact set
936 where id = %d limit 1",
937 dbesc($contact['url']),
938 dbesc($contact['request']),
939 dbesc($contact['notify']),
940 dbesc($contact['poll']),
941 dbesc($contact['confirm']),
942 dbesc($contact['poco']),
943 intval($contact['id'])
951 * xml2array() will convert the given XML text to an array in the XML structure.
952 * Link: http://www.bin-co.com/php/scripts/xml2array/
953 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
954 * Arguments : $contents - The XML text
955 * $namespaces - true or false include namespace information in the returned array as array elements.
956 * $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.
957 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
958 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
959 * Examples: $array = xml2array(file_get_contents('feed.xml'));
960 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
963 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
964 if(!$contents) return array();
966 if(!function_exists('xml_parser_create')) {
967 logger('xml2array: parser function missing');
972 libxml_use_internal_errors(true);
973 libxml_clear_errors();
976 $parser = @xml_parser_create_ns("UTF-8",':');
978 $parser = @xml_parser_create();
981 logger('xml2array: xml_parser_create: no resource');
985 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
986 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
987 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
988 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
989 @xml_parse_into_struct($parser, trim($contents), $xml_values);
990 @xml_parser_free($parser);
993 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
994 foreach(libxml_get_errors() as $err)
995 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
996 libxml_clear_errors();
1001 $xml_array = array();
1003 $opened_tags = array();
1006 $current = &$xml_array; // Reference
1008 // Go through the tags.
1009 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1010 foreach($xml_values as $data) {
1011 unset($attributes,$value); // Remove existing values, or there will be trouble
1013 // This command will extract these variables into the foreach scope
1014 // tag(string), type(string), level(int), attributes(array).
1015 extract($data); // We could use the array by itself, but this cooler.
1018 $attributes_data = array();
1021 if($priority == 'tag') $result = $value;
1022 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1025 //Set the attributes too.
1026 if(isset($attributes) and $get_attributes) {
1027 foreach($attributes as $attr => $val) {
1028 if($priority == 'tag') $attributes_data[$attr] = $val;
1029 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1033 // See tag status and do the needed.
1034 if($namespaces && strpos($tag,':')) {
1035 $namespc = substr($tag,0,strrpos($tag,':'));
1036 $tag = strtolower(substr($tag,strlen($namespc)+1));
1037 $result['@namespace'] = $namespc;
1039 $tag = strtolower($tag);
1041 if($type == "open") { // The starting of the tag '<tag>'
1042 $parent[$level-1] = &$current;
1043 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1044 $current[$tag] = $result;
1045 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1046 $repeated_tag_index[$tag.'_'.$level] = 1;
1048 $current = &$current[$tag];
1050 } else { // There was another element with the same tag name
1052 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1053 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1054 $repeated_tag_index[$tag.'_'.$level]++;
1055 } else { // This section will make the value an array if multiple tags with the same name appear together
1056 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1057 $repeated_tag_index[$tag.'_'.$level] = 2;
1059 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1060 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1061 unset($current[$tag.'_attr']);
1065 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1066 $current = &$current[$tag][$last_item_index];
1069 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1070 //See if the key is already taken.
1071 if(!isset($current[$tag])) { //New Key
1072 $current[$tag] = $result;
1073 $repeated_tag_index[$tag.'_'.$level] = 1;
1074 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1076 } else { // If taken, put all things inside a list(array)
1077 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1079 // ...push the new element into that array.
1080 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1082 if($priority == 'tag' and $get_attributes and $attributes_data) {
1083 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1085 $repeated_tag_index[$tag.'_'.$level]++;
1087 } else { // If it is not an array...
1088 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1089 $repeated_tag_index[$tag.'_'.$level] = 1;
1090 if($priority == 'tag' and $get_attributes) {
1091 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1093 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1094 unset($current[$tag.'_attr']);
1097 if($attributes_data) {
1098 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1101 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1105 } elseif($type == 'close') { // End of tag '</tag>'
1106 $current = &$parent[$level-1];
1113 function original_url($url, $depth=1, $fetchbody = false) {
1117 // Remove Analytics Data from Google and other tracking platforms
1118 $urldata = parse_url($url);
1119 if (is_string($urldata["query"])) {
1120 $query = $urldata["query"];
1121 parse_str($query, $querydata);
1123 if (is_array($querydata))
1124 foreach ($querydata AS $param=>$value)
1125 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1126 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1127 "fb_action_ids", "fb_action_types", "fb_ref",
1129 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1131 $pair = $param."=".urlencode($value);
1132 $url = str_replace($pair, "", $url);
1134 // Second try: if the url isn't encoded completely
1135 $pair = $param."=".str_replace(" ", "+", $value);
1136 $url = str_replace($pair, "", $url);
1138 // Third try: Maybey the url isn't encoded at all
1139 $pair = $param."=".$value;
1140 $url = str_replace($pair, "", $url);
1142 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1145 if (substr($url, -1, 1) == "?")
1146 $url = substr($url, 0, -1);
1152 $url = trim($url, "'");
1154 $stamp1 = microtime(true);
1156 $siteinfo = array();
1158 curl_setopt($ch, CURLOPT_URL, $url);
1159 curl_setopt($ch, CURLOPT_HEADER, 1);
1160 curl_setopt($ch, CURLOPT_NOBODY, 1);
1161 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1162 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1163 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1165 $header = curl_exec($ch);
1166 $curl_info = @curl_getinfo($ch);
1167 $http_code = $curl_info['http_code'];
1170 $a->save_timestamp($stamp1, "network");
1172 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1173 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1174 if ($curl_info['redirect_url'] != "")
1175 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1177 return(original_url($curl_info['location'], ++$depth, $fetchbody));
1180 // Check for redirects in the meta elements of the body if there are no redirects in the header.
1182 return(original_url($url, ++$depth, true));
1184 // if the file is too large then exit
1185 if ($curl_info["download_content_length"] > 1000000)
1188 // if it isn't a HTML file then exit
1189 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
1192 $stamp1 = microtime(true);
1195 curl_setopt($ch, CURLOPT_URL, $url);
1196 curl_setopt($ch, CURLOPT_HEADER, 0);
1197 curl_setopt($ch, CURLOPT_NOBODY, 0);
1198 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1199 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1200 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1202 $body = curl_exec($ch);
1205 $a->save_timestamp($stamp1, "network");
1207 if (trim($body) == "")
1210 // Check for redirect in meta elements
1211 $doc = new DOMDocument();
1212 @$doc->loadHTML($body);
1214 $xpath = new DomXPath($doc);
1216 $list = $xpath->query("//meta[@content]");
1217 foreach ($list as $node) {
1219 if ($node->attributes->length)
1220 foreach ($node->attributes as $attribute)
1221 $attr[$attribute->name] = $attribute->value;
1223 if (@$attr["http-equiv"] == 'refresh') {
1224 $path = $attr["content"];
1225 $pathinfo = explode(";", $path);
1227 foreach ($pathinfo AS $value)
1228 if (substr(strtolower($value), 0, 4) == "url=")
1229 return(original_url(substr($value, 4), ++$depth));
1236 if (!function_exists('short_link')) {
1237 function short_link($url) {
1238 require_once('library/slinky.php');
1239 $slinky = new Slinky($url);
1240 $yourls_url = get_config('yourls','url1');
1242 $yourls_username = get_config('yourls','username1');
1243 $yourls_password = get_config('yourls', 'password1');
1244 $yourls_ssl = get_config('yourls', 'ssl1');
1245 $yourls = new Slinky_YourLS();
1246 $yourls->set('username', $yourls_username);
1247 $yourls->set('password', $yourls_password);
1248 $yourls->set('ssl', $yourls_ssl);
1249 $yourls->set('yourls-url', $yourls_url);
1250 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1252 // setup a cascade of shortening services
1253 // try to get a short link from these services
1254 // in the order ur1.ca, trim, id.gd, tinyurl
1255 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1257 return $slinky->short();