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 // There are many servers out there that don't have valid certificates
38 // We have to disable the checks :-(
39 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
40 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
42 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
43 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
46 if(intval($timeout)) {
47 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
50 $curl_time = intval(get_config('system','curl_timeout'));
51 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
53 // by default we will allow self-signed certs
54 // but you can override this
56 $check_cert = get_config('system','verifyssl');
57 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
59 $prx = get_config('system','proxy');
61 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
62 @curl_setopt($ch, CURLOPT_PROXY, $prx);
63 $prxusr = @get_config('system','proxyuser');
65 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
68 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
72 // don't let curl abort the entire application
73 // if it throws any errors.
78 $curl_info = @curl_getinfo($ch);
80 $http_code = $curl_info['http_code'];
81 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
84 // Pull out multiple headers, e.g. proxy and continuation headers
85 // allow for HTTP/2.x without fixing code
87 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
88 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
90 $base = substr($base,strlen($chunk));
93 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
94 $new_location_info = @parse_url($curl_info["redirect_url"]);
95 $old_location_info = @parse_url($curl_info["url"]);
97 $newurl = $curl_info["redirect_url"];
99 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
100 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
103 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
104 $newurl = trim(array_pop($matches));
106 if(strpos($newurl,'/') === 0)
107 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
108 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
110 return fetch_url($newurl,$binary,$redirects,$timeout,$accept_content,$cookiejar);
114 $a->set_curl_code($http_code);
115 $a->set_curl_content_type($curl_info['content_type']);
117 $body = substr($s,strlen($header));
118 $a->set_curl_headers($header);
120 $a->save_timestamp($stamp1, "network");
125 // post request to $url. $params is an array of post variables.
127 if(! function_exists('post_url')) {
128 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
129 $stamp1 = microtime(true);
132 $ch = curl_init($url);
133 if(($redirects > 8) || (! $ch))
136 logger("post_url: start ".$url, LOGGER_DATA);
138 curl_setopt($ch, CURLOPT_HEADER, true);
139 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
140 curl_setopt($ch, CURLOPT_POST,1);
141 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
142 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
144 if(intval($timeout)) {
145 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
148 $curl_time = intval(get_config('system','curl_timeout'));
149 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
152 if(defined('LIGHTTPD')) {
153 if(!is_array($headers)) {
154 $headers = array('Expect:');
156 if(!in_array('Expect:', $headers)) {
157 array_push($headers, 'Expect:');
162 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
164 $check_cert = get_config('system','verifyssl');
165 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
166 $prx = get_config('system','proxy');
168 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
169 curl_setopt($ch, CURLOPT_PROXY, $prx);
170 $prxusr = get_config('system','proxyuser');
172 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
175 $a->set_curl_code(0);
177 // don't let curl abort the entire application
178 // if it throws any errors.
180 $s = @curl_exec($ch);
183 $curl_info = curl_getinfo($ch);
184 $http_code = $curl_info['http_code'];
186 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
190 // Pull out multiple headers, e.g. proxy and continuation headers
191 // allow for HTTP/2.x without fixing code
193 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
194 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
196 $base = substr($base,strlen($chunk));
199 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
201 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
202 $newurl = trim(array_pop($matches));
203 if(strpos($newurl,'/') === 0)
204 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
205 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
207 logger("post_url: redirect ".$url." to ".$newurl);
208 return post_url($newurl,$params, $headers, $redirects, $timeout);
209 //return fetch_url($newurl,false,$redirects,$timeout);
212 $a->set_curl_code($http_code);
213 $body = substr($s,strlen($header));
215 $a->set_curl_headers($header);
219 $a->save_timestamp($stamp1, "network");
221 logger("post_url: end ".$url, LOGGER_DATA);
226 // Generic XML return
227 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
228 // of $st and an optional text <message> of $message and terminates the current process.
230 if(! function_exists('xml_status')) {
231 function xml_status($st, $message = '') {
233 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
236 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
238 header( "Content-type: text/xml" );
239 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
240 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
245 if(! function_exists('http_status_exit')) {
246 function http_status_exit($val) {
251 if($val >= 200 && $val < 300)
254 logger('http_status_exit ' . $val);
255 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
261 // convert an XML document to a normalised, case-corrected array
264 if(! function_exists('convert_xml_element_to_array')) {
265 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
267 // If we're getting too deep, bail out
268 if ($recursion_depth > 512) {
272 if (!is_string($xml_element) &&
273 !is_array($xml_element) &&
274 (get_class($xml_element) == 'SimpleXMLElement')) {
275 $xml_element_copy = $xml_element;
276 $xml_element = get_object_vars($xml_element);
279 if (is_array($xml_element)) {
280 $result_array = array();
281 if (count($xml_element) <= 0) {
282 return (trim(strval($xml_element_copy)));
285 foreach($xml_element as $key=>$value) {
288 $result_array[strtolower($key)] =
289 convert_xml_element_to_array($value, $recursion_depth);
292 if ($recursion_depth == 0) {
293 $temp_array = $result_array;
294 $result_array = array(
295 strtolower($xml_element_copy->getName()) => $temp_array,
299 return ($result_array);
302 return (trim(strval($xml_element)));
306 // Given an email style address, perform webfinger lookup and
307 // return the resulting DFRN profile URL, or if no DFRN profile URL
308 // is located, returns an OStatus subscription template (prefixed
309 // with the string 'stat:' to identify it as on OStatus template).
310 // If this isn't an email style address just return $s.
311 // Return an empty string if email-style addresses but webfinger fails,
312 // or if the resultant personal XRD doesn't contain a supported
313 // subscription/friend-request attribute.
315 // amended 7/9/2011 to return an hcard which could save potentially loading
316 // a lengthy content page to scrape dfrn attributes
318 if(! function_exists('webfinger_dfrn')) {
319 function webfinger_dfrn($s,&$hcard) {
320 if(! strstr($s,'@')) {
325 $links = webfinger($s);
326 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
328 foreach($links as $link) {
329 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
330 $profile_link = $link['@attributes']['href'];
331 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
332 $profile_link = 'stat:' . $link['@attributes']['template'];
333 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
334 $hcard = $link['@attributes']['href'];
337 return $profile_link;
340 // Given an email style address, perform webfinger lookup and
341 // return the array of link attributes from the personal XRD file.
342 // On error/failure return an empty array.
345 if(! function_exists('webfinger')) {
346 function webfinger($s, $debug = false) {
349 $host = substr($s,strpos($s,'@') + 1);
352 $tpl = fetch_lrdd_template($host);
353 logger('webfinger: lrdd template: ' . $tpl);
355 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
356 logger('webfinger: pxrd: ' . $pxrd);
357 $links = fetch_xrd_links($pxrd);
358 if(! count($links)) {
359 // try with double slashes
360 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
361 logger('webfinger: pxrd: ' . $pxrd);
362 $links = fetch_xrd_links($pxrd);
370 if(! function_exists('lrdd')) {
371 function lrdd($uri, $debug = false) {
375 // default priority is host priority, host-meta first
379 // All we have is an email address. Resource-priority is irrelevant
380 // because our URI isn't directly resolvable.
382 if(strstr($uri,'@')) {
383 return(webfinger($uri));
386 // get the host meta file
388 $host = @parse_url($uri);
391 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
392 $url .= $host['host'] . '/.well-known/host-meta' ;
397 logger('lrdd: constructed url: ' . $url);
399 $xml = fetch_url($url);
401 $headers = $a->get_curl_headers();
406 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
408 if(! stristr($xml,'<xrd'))
411 $h = parse_xml_string($xml);
415 $arr = convert_xml_element_to_array($h);
417 if(isset($arr['xrd']['property'])) {
418 $property = $arr['crd']['property'];
419 if(! isset($property[0]))
420 $properties = array($property);
422 $properties = $property;
423 foreach($properties as $prop)
424 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
425 $priority = 'resource';
428 // save the links in case we need them
432 if(isset($arr['xrd']['link'])) {
433 $link = $arr['xrd']['link'];
434 if(! isset($link[0]))
435 $links = array($link);
440 // do we have a template or href?
443 foreach($links as $link) {
444 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
445 if(x($link['@attributes'],'template'))
446 $tpl = $link['@attributes']['template'];
447 elseif(x($link['@attributes'],'href'))
448 $href = $link['@attributes']['href'];
453 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
456 if($priority === 'host') {
458 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
462 logger('lrdd: (host priority) pxrd: ' . $pxrd);
463 $links = fetch_xrd_links($pxrd);
467 $lines = explode("\n",$headers);
469 foreach($lines as $line) {
470 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
471 return(fetch_xrd_links($matches[1]));
479 // priority 'resource'
482 $html = fetch_url($uri);
483 $headers = $a->get_curl_headers();
484 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
486 // don't try and parse raw xml as html
487 if(! strstr($html,'<?xml')) {
488 require_once('library/HTML5/Parser.php');
491 $dom = HTML5_Parser::parse($html);
492 } catch (DOMException $e) {
493 logger('lrdd: parse error: ' . $e);
496 if(isset($dom) && $dom) {
497 $items = $dom->getElementsByTagName('link');
498 foreach($items as $item) {
499 $x = $item->getAttribute('rel');
501 $pagelink = $item->getAttribute('href');
509 return(fetch_xrd_links($pagelink));
511 // next look in HTTP headers
513 $lines = explode("\n",$headers);
515 foreach($lines as $line) {
516 // TODO alter the following regex to support multiple relations (space separated)
517 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
518 $pagelink = $matches[1];
521 // don't try and run feeds through the html5 parser
522 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
524 if(stristr($html,'<rss') || stristr($html,'<feed'))
530 return(fetch_xrd_links($pagelink));
532 // If we haven't found any links, return the host xrd links (which we have already fetched)
543 // Given a host name, locate the LRDD template from that
544 // host. Returns the LRDD template or an empty string on
547 if(! function_exists('fetch_lrdd_template')) {
548 function fetch_lrdd_template($host) {
551 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
552 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
553 $links = fetch_xrd_links($url1);
554 logger('fetch_lrdd_template from: ' . $url1);
555 logger('template (https): ' . print_r($links,true));
556 if(! count($links)) {
557 logger('fetch_lrdd_template from: ' . $url2);
558 $links = fetch_xrd_links($url2);
559 logger('template (http): ' . print_r($links,true));
562 foreach($links as $link)
563 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
564 $tpl = $link['@attributes']['template'];
566 if(! strpos($tpl,'{uri}'))
571 // Given a URL, retrieve the page as an XRD document.
572 // Return an array of links.
573 // on error/failure return empty array.
575 if(! function_exists('fetch_xrd_links')) {
576 function fetch_xrd_links($url) {
578 $xrd_timeout = intval(get_config('system','xrd_timeout'));
580 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
582 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
584 if ((! $xml) || (! stristr($xml,'<xrd')))
587 // fix diaspora's bad xml
588 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
590 $h = parse_xml_string($xml);
594 $arr = convert_xml_element_to_array($h);
598 if(isset($arr['xrd']['link'])) {
599 $link = $arr['xrd']['link'];
600 if(! isset($link[0]))
601 $links = array($link);
605 if(isset($arr['xrd']['alias'])) {
606 $alias = $arr['xrd']['alias'];
607 if(! isset($alias[0]))
608 $aliases = array($alias);
611 if(is_array($aliases) && count($aliases)) {
612 foreach($aliases as $alias) {
613 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
618 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
625 // Take a URL from the wild, prepend http:// if necessary
626 // and check DNS to see if it's real (or check if is a valid IP address)
627 // return true if it's OK, false if something is wrong with it
629 if(! function_exists('validate_url')) {
630 function validate_url(&$url) {
632 if(get_config('system','disable_url_validation'))
634 // no naked subdomains (allow localhost for tests)
635 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
637 if(substr($url,0,4) != 'http')
638 $url = 'http://' . $url;
639 $h = @parse_url($url);
641 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
647 // checks that email is an actual resolvable internet address
649 if(! function_exists('validate_email')) {
650 function validate_email($addr) {
652 if(get_config('system','disable_email_validation'))
655 if(! strpos($addr,'@'))
657 $h = substr($addr,strpos($addr,'@') + 1);
659 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
665 // Check $url against our list of allowed sites,
666 // wildcards allowed. If allowed_sites is unset return true;
667 // If url is allowed, return true.
668 // otherwise, return false
670 if(! function_exists('allowed_url')) {
671 function allowed_url($url) {
673 $h = @parse_url($url);
679 $str_allowed = get_config('system','allowed_sites');
685 $host = strtolower($h['host']);
687 // always allow our own site
689 if($host == strtolower($_SERVER['SERVER_NAME']))
692 $fnmatch = function_exists('fnmatch');
693 $allowed = explode(',',$str_allowed);
695 if(count($allowed)) {
696 foreach($allowed as $a) {
697 $pat = strtolower(trim($a));
698 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
707 // check if email address is allowed to register here.
708 // Compare against our list (wildcards allowed).
709 // Returns false if not allowed, true if allowed or if
710 // allowed list is not configured.
712 if(! function_exists('allowed_email')) {
713 function allowed_email($email) {
716 $domain = strtolower(substr($email,strpos($email,'@') + 1));
720 $str_allowed = get_config('system','allowed_email');
726 $fnmatch = function_exists('fnmatch');
727 $allowed = explode(',',$str_allowed);
729 if(count($allowed)) {
730 foreach($allowed as $a) {
731 $pat = strtolower(trim($a));
732 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
742 if(! function_exists('avatar_img')) {
743 function avatar_img($email) {
747 $avatar['size'] = 175;
748 $avatar['email'] = $email;
750 $avatar['success'] = false;
752 call_hooks('avatar_lookup', $avatar);
754 if(! $avatar['success'])
755 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
757 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
758 return $avatar['url'];
762 if(! function_exists('parse_xml_string')) {
763 function parse_xml_string($s,$strict = true) {
765 if(! strstr($s,'<?xml'))
767 $s2 = substr($s,strpos($s,'<?xml'));
771 libxml_use_internal_errors(true);
773 $x = @simplexml_load_string($s2);
775 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
776 foreach(libxml_get_errors() as $err)
777 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
778 libxml_clear_errors();
783 function add_fcontact($arr,$update = false) {
786 $r = q("UPDATE `fcontact` SET
799 WHERE `url` = '%s' AND `network` = '%s'",
801 dbesc($arr['photo']),
802 dbesc($arr['request']),
805 dbesc($arr['batch']),
806 dbesc($arr['notify']),
808 dbesc($arr['confirm']),
809 dbesc($arr['alias']),
810 dbesc($arr['pubkey']),
811 dbesc(datetime_convert()),
813 dbesc($arr['network'])
817 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
818 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
819 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
822 dbesc($arr['photo']),
823 dbesc($arr['request']),
826 dbesc($arr['batch']),
827 dbesc($arr['notify']),
829 dbesc($arr['confirm']),
830 dbesc($arr['network']),
831 dbesc($arr['alias']),
832 dbesc($arr['pubkey']),
833 dbesc(datetime_convert())
841 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
843 // Suppress "view full size"
844 if (intval(get_config('system','no_view_full_size')))
845 $include_link = false;
849 // Picture addresses can contain special characters
850 $s = htmlspecialchars_decode($srctext);
853 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
855 require_once('include/Photo.php');
856 foreach($matches as $mtch) {
857 logger('scale_external_image: ' . $mtch[1]);
859 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
860 if(stristr($mtch[1],$hostname))
863 // $scale_replace, if passed, is an array of two elements. The
864 // first is the name of the full-size image. The second is the
865 // name of a remote, scaled-down version of the full size image.
866 // This allows Friendica to display the smaller remote image if
867 // one exists, while still linking to the full-size image
869 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
872 $i = @fetch_url($scaled);
876 $cachefile = get_cachefile(hash("md5", $scaled));
877 if ($cachefile != '') {
878 $stamp1 = microtime(true);
879 file_put_contents($cachefile, $i);
880 $a->save_timestamp($stamp1, "file");
883 // guess mimetype from headers or filename
884 $type = guess_image_type($mtch[1],true);
887 $ph = new Photo($i, $type);
888 if($ph->is_valid()) {
889 $orig_width = $ph->getWidth();
890 $orig_height = $ph->getHeight();
892 if($orig_width > 640 || $orig_height > 640) {
894 $ph->scaleImage(640);
895 $new_width = $ph->getWidth();
896 $new_height = $ph->getHeight();
897 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
898 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
899 . "\n" . (($include_link)
900 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
902 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
909 // replace the special char encoding
910 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
915 function fix_contact_ssl_policy(&$contact,$new_policy) {
917 $ssl_changed = false;
918 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
920 $contact['url'] = str_replace('https:','http:',$contact['url']);
921 $contact['request'] = str_replace('https:','http:',$contact['request']);
922 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
923 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
924 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
925 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
928 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
930 $contact['url'] = str_replace('http:','https:',$contact['url']);
931 $contact['request'] = str_replace('http:','https:',$contact['request']);
932 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
933 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
934 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
935 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
939 q("update contact set
946 where id = %d limit 1",
947 dbesc($contact['url']),
948 dbesc($contact['request']),
949 dbesc($contact['notify']),
950 dbesc($contact['poll']),
951 dbesc($contact['confirm']),
952 dbesc($contact['poco']),
953 intval($contact['id'])
961 * xml2array() will convert the given XML text to an array in the XML structure.
962 * Link: http://www.bin-co.com/php/scripts/xml2array/
963 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
964 * Arguments : $contents - The XML text
965 * $namespaces - true or false include namespace information in the returned array as array elements.
966 * $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.
967 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
968 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
969 * Examples: $array = xml2array(file_get_contents('feed.xml'));
970 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
973 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
974 if(!$contents) return array();
976 if(!function_exists('xml_parser_create')) {
977 logger('xml2array: parser function missing');
982 libxml_use_internal_errors(true);
983 libxml_clear_errors();
986 $parser = @xml_parser_create_ns("UTF-8",':');
988 $parser = @xml_parser_create();
991 logger('xml2array: xml_parser_create: no resource');
995 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
996 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
997 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
998 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
999 @xml_parse_into_struct($parser, trim($contents), $xml_values);
1000 @xml_parser_free($parser);
1003 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
1004 foreach(libxml_get_errors() as $err)
1005 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
1006 libxml_clear_errors();
1011 $xml_array = array();
1013 $opened_tags = array();
1016 $current = &$xml_array; // Reference
1018 // Go through the tags.
1019 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1020 foreach($xml_values as $data) {
1021 unset($attributes,$value); // Remove existing values, or there will be trouble
1023 // This command will extract these variables into the foreach scope
1024 // tag(string), type(string), level(int), attributes(array).
1025 extract($data); // We could use the array by itself, but this cooler.
1028 $attributes_data = array();
1031 if($priority == 'tag') $result = $value;
1032 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1035 //Set the attributes too.
1036 if(isset($attributes) and $get_attributes) {
1037 foreach($attributes as $attr => $val) {
1038 if($priority == 'tag') $attributes_data[$attr] = $val;
1039 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1043 // See tag status and do the needed.
1044 if($namespaces && strpos($tag,':')) {
1045 $namespc = substr($tag,0,strrpos($tag,':'));
1046 $tag = strtolower(substr($tag,strlen($namespc)+1));
1047 $result['@namespace'] = $namespc;
1049 $tag = strtolower($tag);
1051 if($type == "open") { // The starting of the tag '<tag>'
1052 $parent[$level-1] = &$current;
1053 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1054 $current[$tag] = $result;
1055 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1056 $repeated_tag_index[$tag.'_'.$level] = 1;
1058 $current = &$current[$tag];
1060 } else { // There was another element with the same tag name
1062 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1063 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1064 $repeated_tag_index[$tag.'_'.$level]++;
1065 } else { // This section will make the value an array if multiple tags with the same name appear together
1066 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1067 $repeated_tag_index[$tag.'_'.$level] = 2;
1069 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1070 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1071 unset($current[$tag.'_attr']);
1075 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1076 $current = &$current[$tag][$last_item_index];
1079 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1080 //See if the key is already taken.
1081 if(!isset($current[$tag])) { //New Key
1082 $current[$tag] = $result;
1083 $repeated_tag_index[$tag.'_'.$level] = 1;
1084 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1086 } else { // If taken, put all things inside a list(array)
1087 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1089 // ...push the new element into that array.
1090 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1092 if($priority == 'tag' and $get_attributes and $attributes_data) {
1093 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1095 $repeated_tag_index[$tag.'_'.$level]++;
1097 } else { // If it is not an array...
1098 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1099 $repeated_tag_index[$tag.'_'.$level] = 1;
1100 if($priority == 'tag' and $get_attributes) {
1101 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1103 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1104 unset($current[$tag.'_attr']);
1107 if($attributes_data) {
1108 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1111 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1115 } elseif($type == 'close') { // End of tag '</tag>'
1116 $current = &$parent[$level-1];
1123 function original_url($url, $depth=1, $fetchbody = false) {
1127 // Remove Analytics Data from Google and other tracking platforms
1128 $urldata = parse_url($url);
1129 if (is_string($urldata["query"])) {
1130 $query = $urldata["query"];
1131 parse_str($query, $querydata);
1133 if (is_array($querydata))
1134 foreach ($querydata AS $param=>$value)
1135 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1136 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1137 "fb_action_ids", "fb_action_types", "fb_ref",
1139 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1141 $pair = $param."=".urlencode($value);
1142 $url = str_replace($pair, "", $url);
1144 // Second try: if the url isn't encoded completely
1145 $pair = $param."=".str_replace(" ", "+", $value);
1146 $url = str_replace($pair, "", $url);
1148 // Third try: Maybey the url isn't encoded at all
1149 $pair = $param."=".$value;
1150 $url = str_replace($pair, "", $url);
1152 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1155 if (substr($url, -1, 1) == "?")
1156 $url = substr($url, 0, -1);
1162 $url = trim($url, "'");
1164 $siteinfo = array();
1166 curl_setopt($ch, CURLOPT_URL, $url);
1167 curl_setopt($ch, CURLOPT_HEADER, 1);
1168 curl_setopt($ch, CURLOPT_NOBODY, 1);
1169 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1170 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1171 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1173 $header = curl_exec($ch);
1174 $curl_info = @curl_getinfo($ch);
1175 $http_code = $curl_info['http_code'];
1178 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1179 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1180 if ($curl_info['redirect_url'] != "")
1181 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1183 return(original_url($curl_info['location'], ++$depth, $fetchbody));
1186 // Check for redirects in the meta elements of the body if there are no redirects in the header.
1188 return(original_url($url, ++$depth, true));
1190 // if the file is too large then exit
1191 if ($curl_info["download_content_length"] > 1000000)
1194 // if it isn't a HTML file then exit
1195 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
1199 curl_setopt($ch, CURLOPT_URL, $url);
1200 curl_setopt($ch, CURLOPT_HEADER, 0);
1201 curl_setopt($ch, CURLOPT_NOBODY, 0);
1202 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1203 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1204 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1206 $body = curl_exec($ch);
1209 if (trim($body) == "")
1212 // Check for redirect in meta elements
1213 $doc = new DOMDocument();
1214 @$doc->loadHTML($body);
1216 $xpath = new DomXPath($doc);
1218 $list = $xpath->query("//meta[@content]");
1219 foreach ($list as $node) {
1221 if ($node->attributes->length)
1222 foreach ($node->attributes as $attribute)
1223 $attr[$attribute->name] = $attribute->value;
1225 if (@$attr["http-equiv"] == 'refresh') {
1226 $path = $attr["content"];
1227 $pathinfo = explode(";", $path);
1229 foreach ($pathinfo AS $value)
1230 if (substr(strtolower($value), 0, 4) == "url=")
1231 return(original_url(substr($value, 4), ++$depth));
1238 if (!function_exists('short_link')) {
1239 function short_link($url) {
1240 require_once('library/slinky.php');
1241 $slinky = new Slinky($url);
1242 $yourls_url = get_config('yourls','url1');
1244 $yourls_username = get_config('yourls','username1');
1245 $yourls_password = get_config('yourls', 'password1');
1246 $yourls_ssl = get_config('yourls', 'ssl1');
1247 $yourls = new Slinky_YourLS();
1248 $yourls->set('username', $yourls_username);
1249 $yourls->set('password', $yourls_password);
1250 $yourls->set('ssl', $yourls_ssl);
1251 $yourls->set('yourls-url', $yourls_url);
1252 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1254 // setup a cascade of shortening services
1255 // try to get a short link from these services
1256 // in the order ur1.ca, trim, id.gd, tinyurl
1257 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1259 return $slinky->short();