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, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
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));
54 $prx = get_config('system','proxy');
56 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
57 @curl_setopt($ch, CURLOPT_PROXY, $prx);
58 $prxusr = @get_config('system','proxyuser');
60 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
63 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
67 // don't let curl abort the entire application
68 // if it throws any errors.
73 $curl_info = @curl_getinfo($ch);
74 $http_code = $curl_info['http_code'];
75 logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
78 // Pull out multiple headers, e.g. proxy and continuation headers
79 // allow for HTTP/2.x without fixing code
81 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
82 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
84 $base = substr($base,strlen($chunk));
87 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
88 $new_location_info = @parse_url($curl_info["redirect_url"]);
89 $old_location_info = @parse_url($curl_info["url"]);
91 $newurl = $curl_info["redirect_url"];
93 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
94 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
97 if (preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches)) {
98 $newurl = trim(array_pop($matches));
100 if(strpos($newurl,'/') === 0)
101 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
102 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
104 return fetch_url($newurl,$binary,$redirects,$timeout,$accept_content,$cookiejar);
108 $a->set_curl_code($http_code);
109 $a->set_curl_content_type($curl_info['content_type']);
111 $body = substr($s,strlen($header));
112 $a->set_curl_headers($header);
115 $a->save_timestamp($stamp1, "network");
120 // post request to $url. $params is an array of post variables.
122 if(! function_exists('post_url')) {
123 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
124 $stamp1 = microtime(true);
127 $ch = curl_init($url);
128 if(($redirects > 8) || (! $ch))
131 logger("post_url: start ".$url, LOGGER_DATA);
133 curl_setopt($ch, CURLOPT_HEADER, true);
134 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
135 curl_setopt($ch, CURLOPT_POST,1);
136 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
137 curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
139 if(intval($timeout)) {
140 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
143 $curl_time = intval(get_config('system','curl_timeout'));
144 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
147 if(defined('LIGHTTPD')) {
148 if(!is_array($headers)) {
149 $headers = array('Expect:');
151 if(!in_array('Expect:', $headers)) {
152 array_push($headers, 'Expect:');
157 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
159 $check_cert = get_config('system','verifyssl');
160 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
161 $prx = get_config('system','proxy');
163 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
164 curl_setopt($ch, CURLOPT_PROXY, $prx);
165 $prxusr = get_config('system','proxyuser');
167 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
170 $a->set_curl_code(0);
172 // don't let curl abort the entire application
173 // if it throws any errors.
175 $s = @curl_exec($ch);
178 $curl_info = curl_getinfo($ch);
179 $http_code = $curl_info['http_code'];
181 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
185 // Pull out multiple headers, e.g. proxy and continuation headers
186 // allow for HTTP/2.x without fixing code
188 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
189 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
191 $base = substr($base,strlen($chunk));
194 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
196 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
197 $newurl = trim(array_pop($matches));
198 if(strpos($newurl,'/') === 0)
199 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
200 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
202 logger("post_url: redirect ".$url." to ".$newurl);
203 return post_url($newurl,$params, $headers, $redirects, $timeout);
204 //return fetch_url($newurl,false,$redirects,$timeout);
207 $a->set_curl_code($http_code);
208 $body = substr($s,strlen($header));
210 $a->set_curl_headers($header);
214 $a->save_timestamp($stamp1, "network");
216 logger("post_url: end ".$url, LOGGER_DATA);
221 // Generic XML return
222 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
223 // of $st and an optional text <message> of $message and terminates the current process.
225 if(! function_exists('xml_status')) {
226 function xml_status($st, $message = '') {
228 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
231 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
233 header( "Content-type: text/xml" );
234 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
235 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
240 if(! function_exists('http_status_exit')) {
241 function http_status_exit($val) {
246 if($val >= 200 && $val < 300)
249 logger('http_status_exit ' . $val);
250 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
256 // convert an XML document to a normalised, case-corrected array
259 if(! function_exists('convert_xml_element_to_array')) {
260 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
262 // If we're getting too deep, bail out
263 if ($recursion_depth > 512) {
267 if (!is_string($xml_element) &&
268 !is_array($xml_element) &&
269 (get_class($xml_element) == 'SimpleXMLElement')) {
270 $xml_element_copy = $xml_element;
271 $xml_element = get_object_vars($xml_element);
274 if (is_array($xml_element)) {
275 $result_array = array();
276 if (count($xml_element) <= 0) {
277 return (trim(strval($xml_element_copy)));
280 foreach($xml_element as $key=>$value) {
283 $result_array[strtolower($key)] =
284 convert_xml_element_to_array($value, $recursion_depth);
287 if ($recursion_depth == 0) {
288 $temp_array = $result_array;
289 $result_array = array(
290 strtolower($xml_element_copy->getName()) => $temp_array,
294 return ($result_array);
297 return (trim(strval($xml_element)));
301 // Given an email style address, perform webfinger lookup and
302 // return the resulting DFRN profile URL, or if no DFRN profile URL
303 // is located, returns an OStatus subscription template (prefixed
304 // with the string 'stat:' to identify it as on OStatus template).
305 // If this isn't an email style address just return $s.
306 // Return an empty string if email-style addresses but webfinger fails,
307 // or if the resultant personal XRD doesn't contain a supported
308 // subscription/friend-request attribute.
310 // amended 7/9/2011 to return an hcard which could save potentially loading
311 // a lengthy content page to scrape dfrn attributes
313 if(! function_exists('webfinger_dfrn')) {
314 function webfinger_dfrn($s,&$hcard) {
315 if(! strstr($s,'@')) {
320 $links = webfinger($s);
321 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
323 foreach($links as $link) {
324 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
325 $profile_link = $link['@attributes']['href'];
326 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
327 $profile_link = 'stat:' . $link['@attributes']['template'];
328 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
329 $hcard = $link['@attributes']['href'];
332 return $profile_link;
335 // Given an email style address, perform webfinger lookup and
336 // return the array of link attributes from the personal XRD file.
337 // On error/failure return an empty array.
340 if(! function_exists('webfinger')) {
341 function webfinger($s, $debug = false) {
344 $host = substr($s,strpos($s,'@') + 1);
347 $tpl = fetch_lrdd_template($host);
348 logger('webfinger: lrdd template: ' . $tpl);
350 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
351 logger('webfinger: pxrd: ' . $pxrd);
352 $links = fetch_xrd_links($pxrd);
353 if(! count($links)) {
354 // try with double slashes
355 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
356 logger('webfinger: pxrd: ' . $pxrd);
357 $links = fetch_xrd_links($pxrd);
365 if(! function_exists('lrdd')) {
366 function lrdd($uri, $debug = false) {
370 // default priority is host priority, host-meta first
374 // All we have is an email address. Resource-priority is irrelevant
375 // because our URI isn't directly resolvable.
377 if(strstr($uri,'@')) {
378 return(webfinger($uri));
381 // get the host meta file
383 $host = @parse_url($uri);
386 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
387 $url .= $host['host'] . '/.well-known/host-meta' ;
392 logger('lrdd: constructed url: ' . $url);
394 $xml = fetch_url($url);
396 $headers = $a->get_curl_headers();
401 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
403 if(! stristr($xml,'<xrd'))
406 $h = parse_xml_string($xml);
410 $arr = convert_xml_element_to_array($h);
412 if(isset($arr['xrd']['property'])) {
413 $property = $arr['crd']['property'];
414 if(! isset($property[0]))
415 $properties = array($property);
417 $properties = $property;
418 foreach($properties as $prop)
419 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
420 $priority = 'resource';
423 // save the links in case we need them
427 if(isset($arr['xrd']['link'])) {
428 $link = $arr['xrd']['link'];
429 if(! isset($link[0]))
430 $links = array($link);
435 // do we have a template or href?
438 foreach($links as $link) {
439 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
440 if(x($link['@attributes'],'template'))
441 $tpl = $link['@attributes']['template'];
442 elseif(x($link['@attributes'],'href'))
443 $href = $link['@attributes']['href'];
448 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
451 if($priority === 'host') {
453 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
457 logger('lrdd: (host priority) pxrd: ' . $pxrd);
458 $links = fetch_xrd_links($pxrd);
462 $lines = explode("\n",$headers);
464 foreach($lines as $line) {
465 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
466 return(fetch_xrd_links($matches[1]));
474 // priority 'resource'
477 $html = fetch_url($uri);
478 $headers = $a->get_curl_headers();
479 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
481 // don't try and parse raw xml as html
482 if(! strstr($html,'<?xml')) {
483 require_once('library/HTML5/Parser.php');
486 $dom = HTML5_Parser::parse($html);
487 } catch (DOMException $e) {
488 logger('lrdd: parse error: ' . $e);
491 if(isset($dom) && $dom) {
492 $items = $dom->getElementsByTagName('link');
493 foreach($items as $item) {
494 $x = $item->getAttribute('rel');
496 $pagelink = $item->getAttribute('href');
504 return(fetch_xrd_links($pagelink));
506 // next look in HTTP headers
508 $lines = explode("\n",$headers);
510 foreach($lines as $line) {
511 // TODO alter the following regex to support multiple relations (space separated)
512 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
513 $pagelink = $matches[1];
516 // don't try and run feeds through the html5 parser
517 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
519 if(stristr($html,'<rss') || stristr($html,'<feed'))
525 return(fetch_xrd_links($pagelink));
527 // If we haven't found any links, return the host xrd links (which we have already fetched)
538 // Given a host name, locate the LRDD template from that
539 // host. Returns the LRDD template or an empty string on
542 if(! function_exists('fetch_lrdd_template')) {
543 function fetch_lrdd_template($host) {
546 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
547 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
548 $links = fetch_xrd_links($url1);
549 logger('fetch_lrdd_template from: ' . $url1);
550 logger('template (https): ' . print_r($links,true));
551 if(! count($links)) {
552 logger('fetch_lrdd_template from: ' . $url2);
553 $links = fetch_xrd_links($url2);
554 logger('template (http): ' . print_r($links,true));
557 foreach($links as $link)
558 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
559 $tpl = $link['@attributes']['template'];
561 if(! strpos($tpl,'{uri}'))
566 // Given a URL, retrieve the page as an XRD document.
567 // Return an array of links.
568 // on error/failure return empty array.
570 if(! function_exists('fetch_xrd_links')) {
571 function fetch_xrd_links($url) {
573 $xrd_timeout = intval(get_config('system','xrd_timeout'));
575 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
577 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
579 if ((! $xml) || (! stristr($xml,'<xrd')))
582 // fix diaspora's bad xml
583 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
585 $h = parse_xml_string($xml);
589 $arr = convert_xml_element_to_array($h);
593 if(isset($arr['xrd']['link'])) {
594 $link = $arr['xrd']['link'];
595 if(! isset($link[0]))
596 $links = array($link);
600 if(isset($arr['xrd']['alias'])) {
601 $alias = $arr['xrd']['alias'];
602 if(! isset($alias[0]))
603 $aliases = array($alias);
606 if(is_array($aliases) && count($aliases)) {
607 foreach($aliases as $alias) {
608 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
613 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
620 // Take a URL from the wild, prepend http:// if necessary
621 // and check DNS to see if it's real (or check if is a valid IP address)
622 // return true if it's OK, false if something is wrong with it
624 if(! function_exists('validate_url')) {
625 function validate_url(&$url) {
626 // no naked subdomains (allow localhost for tests)
627 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
629 if(substr($url,0,4) != 'http')
630 $url = 'http://' . $url;
631 $h = @parse_url($url);
633 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
639 // checks that email is an actual resolvable internet address
641 if(! function_exists('validate_email')) {
642 function validate_email($addr) {
644 if(get_config('system','disable_email_validation'))
647 if(! strpos($addr,'@'))
649 $h = substr($addr,strpos($addr,'@') + 1);
651 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
657 // Check $url against our list of allowed sites,
658 // wildcards allowed. If allowed_sites is unset return true;
659 // If url is allowed, return true.
660 // otherwise, return false
662 if(! function_exists('allowed_url')) {
663 function allowed_url($url) {
665 $h = @parse_url($url);
671 $str_allowed = get_config('system','allowed_sites');
677 $host = strtolower($h['host']);
679 // always allow our own site
681 if($host == strtolower($_SERVER['SERVER_NAME']))
684 $fnmatch = function_exists('fnmatch');
685 $allowed = explode(',',$str_allowed);
687 if(count($allowed)) {
688 foreach($allowed as $a) {
689 $pat = strtolower(trim($a));
690 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
699 // check if email address is allowed to register here.
700 // Compare against our list (wildcards allowed).
701 // Returns false if not allowed, true if allowed or if
702 // allowed list is not configured.
704 if(! function_exists('allowed_email')) {
705 function allowed_email($email) {
708 $domain = strtolower(substr($email,strpos($email,'@') + 1));
712 $str_allowed = get_config('system','allowed_email');
718 $fnmatch = function_exists('fnmatch');
719 $allowed = explode(',',$str_allowed);
721 if(count($allowed)) {
722 foreach($allowed as $a) {
723 $pat = strtolower(trim($a));
724 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
734 if(! function_exists('avatar_img')) {
735 function avatar_img($email) {
739 $avatar['size'] = 175;
740 $avatar['email'] = $email;
742 $avatar['success'] = false;
744 call_hooks('avatar_lookup', $avatar);
746 if(! $avatar['success'])
747 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
749 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
750 return $avatar['url'];
754 if(! function_exists('parse_xml_string')) {
755 function parse_xml_string($s,$strict = true) {
757 if(! strstr($s,'<?xml'))
759 $s2 = substr($s,strpos($s,'<?xml'));
763 libxml_use_internal_errors(true);
765 $x = @simplexml_load_string($s2);
767 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
768 foreach(libxml_get_errors() as $err)
769 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
770 libxml_clear_errors();
775 function add_fcontact($arr,$update = false) {
778 $r = q("UPDATE `fcontact` SET
791 WHERE `url` = '%s' AND `network` = '%s'",
793 dbesc($arr['photo']),
794 dbesc($arr['request']),
797 dbesc($arr['batch']),
798 dbesc($arr['notify']),
800 dbesc($arr['confirm']),
801 dbesc($arr['alias']),
802 dbesc($arr['pubkey']),
803 dbesc(datetime_convert()),
805 dbesc($arr['network'])
809 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
810 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
811 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
814 dbesc($arr['photo']),
815 dbesc($arr['request']),
818 dbesc($arr['batch']),
819 dbesc($arr['notify']),
821 dbesc($arr['confirm']),
822 dbesc($arr['network']),
823 dbesc($arr['alias']),
824 dbesc($arr['pubkey']),
825 dbesc(datetime_convert())
833 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
835 // Suppress "view full size"
836 if (intval(get_config('system','no_view_full_size')))
837 $include_link = false;
841 // Picture addresses can contain special characters
842 $s = htmlspecialchars_decode($srctext);
845 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
847 require_once('include/Photo.php');
848 foreach($matches as $mtch) {
849 logger('scale_external_image: ' . $mtch[1]);
851 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
852 if(stristr($mtch[1],$hostname))
855 // $scale_replace, if passed, is an array of two elements. The
856 // first is the name of the full-size image. The second is the
857 // name of a remote, scaled-down version of the full size image.
858 // This allows Friendica to display the smaller remote image if
859 // one exists, while still linking to the full-size image
861 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
864 $i = @fetch_url($scaled);
868 $cachefile = get_cachefile(hash("md5", $scaled));
869 if ($cachefile != '') {
870 $stamp1 = microtime(true);
871 file_put_contents($cachefile, $i);
872 $a->save_timestamp($stamp1, "file");
875 // guess mimetype from headers or filename
876 $type = guess_image_type($mtch[1],true);
879 $ph = new Photo($i, $type);
880 if($ph->is_valid()) {
881 $orig_width = $ph->getWidth();
882 $orig_height = $ph->getHeight();
884 if($orig_width > 640 || $orig_height > 640) {
886 $ph->scaleImage(640);
887 $new_width = $ph->getWidth();
888 $new_height = $ph->getHeight();
889 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
890 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
891 . "\n" . (($include_link)
892 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
894 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
901 // replace the special char encoding
902 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
907 function fix_contact_ssl_policy(&$contact,$new_policy) {
909 $ssl_changed = false;
910 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
912 $contact['url'] = str_replace('https:','http:',$contact['url']);
913 $contact['request'] = str_replace('https:','http:',$contact['request']);
914 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
915 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
916 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
917 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
920 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
922 $contact['url'] = str_replace('http:','https:',$contact['url']);
923 $contact['request'] = str_replace('http:','https:',$contact['request']);
924 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
925 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
926 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
927 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
931 q("update contact set
938 where id = %d limit 1",
939 dbesc($contact['url']),
940 dbesc($contact['request']),
941 dbesc($contact['notify']),
942 dbesc($contact['poll']),
943 dbesc($contact['confirm']),
944 dbesc($contact['poco']),
945 intval($contact['id'])
953 * xml2array() will convert the given XML text to an array in the XML structure.
954 * Link: http://www.bin-co.com/php/scripts/xml2array/
955 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
956 * Arguments : $contents - The XML text
957 * $namespaces - true or false include namespace information in the returned array as array elements.
958 * $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.
959 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
960 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
961 * Examples: $array = xml2array(file_get_contents('feed.xml'));
962 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
965 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
966 if(!$contents) return array();
968 if(!function_exists('xml_parser_create')) {
969 logger('xml2array: parser function missing');
974 libxml_use_internal_errors(true);
975 libxml_clear_errors();
978 $parser = @xml_parser_create_ns("UTF-8",':');
980 $parser = @xml_parser_create();
983 logger('xml2array: xml_parser_create: no resource');
987 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
988 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
989 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
990 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
991 @xml_parse_into_struct($parser, trim($contents), $xml_values);
992 @xml_parser_free($parser);
995 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
996 foreach(libxml_get_errors() as $err)
997 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
998 libxml_clear_errors();
1003 $xml_array = array();
1005 $opened_tags = array();
1008 $current = &$xml_array; // Reference
1010 // Go through the tags.
1011 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1012 foreach($xml_values as $data) {
1013 unset($attributes,$value); // Remove existing values, or there will be trouble
1015 // This command will extract these variables into the foreach scope
1016 // tag(string), type(string), level(int), attributes(array).
1017 extract($data); // We could use the array by itself, but this cooler.
1020 $attributes_data = array();
1023 if($priority == 'tag') $result = $value;
1024 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1027 //Set the attributes too.
1028 if(isset($attributes) and $get_attributes) {
1029 foreach($attributes as $attr => $val) {
1030 if($priority == 'tag') $attributes_data[$attr] = $val;
1031 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1035 // See tag status and do the needed.
1036 if($namespaces && strpos($tag,':')) {
1037 $namespc = substr($tag,0,strrpos($tag,':'));
1038 $tag = strtolower(substr($tag,strlen($namespc)+1));
1039 $result['@namespace'] = $namespc;
1041 $tag = strtolower($tag);
1043 if($type == "open") { // The starting of the tag '<tag>'
1044 $parent[$level-1] = &$current;
1045 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1046 $current[$tag] = $result;
1047 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1048 $repeated_tag_index[$tag.'_'.$level] = 1;
1050 $current = &$current[$tag];
1052 } else { // There was another element with the same tag name
1054 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1055 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1056 $repeated_tag_index[$tag.'_'.$level]++;
1057 } else { // This section will make the value an array if multiple tags with the same name appear together
1058 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1059 $repeated_tag_index[$tag.'_'.$level] = 2;
1061 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1062 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1063 unset($current[$tag.'_attr']);
1067 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1068 $current = &$current[$tag][$last_item_index];
1071 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1072 //See if the key is already taken.
1073 if(!isset($current[$tag])) { //New Key
1074 $current[$tag] = $result;
1075 $repeated_tag_index[$tag.'_'.$level] = 1;
1076 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1078 } else { // If taken, put all things inside a list(array)
1079 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1081 // ...push the new element into that array.
1082 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1084 if($priority == 'tag' and $get_attributes and $attributes_data) {
1085 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1087 $repeated_tag_index[$tag.'_'.$level]++;
1089 } else { // If it is not an array...
1090 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1091 $repeated_tag_index[$tag.'_'.$level] = 1;
1092 if($priority == 'tag' and $get_attributes) {
1093 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1095 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1096 unset($current[$tag.'_attr']);
1099 if($attributes_data) {
1100 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1103 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1107 } elseif($type == 'close') { // End of tag '</tag>'
1108 $current = &$parent[$level-1];
1115 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 $siteinfo = array();
1156 curl_setopt($ch, CURLOPT_URL, $url);
1157 curl_setopt($ch, CURLOPT_HEADER, 1);
1160 curl_setopt($ch, CURLOPT_NOBODY, 0);
1162 curl_setopt($ch, CURLOPT_NOBODY, 1);
1164 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1165 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1166 curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
1168 $header = curl_exec($ch);
1169 $curl_info = @curl_getinfo($ch);
1170 $http_code = $curl_info['http_code'];
1173 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1174 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1175 if ($curl_info['redirect_url'] != "")
1176 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1178 return(original_url($curl_info['location'], ++$depth, $fetchbody));
1181 $pos = strpos($header, "\r\n\r\n");
1184 $body = trim(substr($header, $pos));
1188 if (trim($body) == "")
1189 return(original_url($url, ++$depth, true));
1191 $doc = new DOMDocument();
1192 @$doc->loadHTML($body);
1194 $xpath = new DomXPath($doc);
1196 $list = $xpath->query("//meta[@content]");
1197 foreach ($list as $node) {
1199 if ($node->attributes->length)
1200 foreach ($node->attributes as $attribute)
1201 $attr[$attribute->name] = $attribute->value;
1203 if (@$attr["http-equiv"] == 'refresh') {
1204 $path = $attr["content"];
1205 $pathinfo = explode(";", $path);
1207 foreach ($pathinfo AS $value)
1208 if (substr(strtolower($value), 0, 4) == "url=")
1209 return(original_url(substr($value, 4), ++$depth));
1216 if (!function_exists('short_link')) {
1217 function short_link($url) {
1218 require_once('library/slinky.php');
1219 $slinky = new Slinky($url);
1220 $yourls_url = get_config('yourls','url1');
1222 $yourls_username = get_config('yourls','username1');
1223 $yourls_password = get_config('yourls', 'password1');
1224 $yourls_ssl = get_config('yourls', 'ssl1');
1225 $yourls = new Slinky_YourLS();
1226 $yourls->set('username', $yourls_username);
1227 $yourls->set('password', $yourls_password);
1228 $yourls->set('ssl', $yourls_ssl);
1229 $yourls->set('yourls-url', $yourls_url);
1230 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1232 // setup a cascade of shortening services
1233 // try to get a short link from these services
1234 // in the order ur1.ca, trim, id.gd, tinyurl
1235 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1237 return $slinky->short();