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));
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, $a->get_useragent());
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) {
627 if(get_config('system','disable_url_validation'))
629 // no naked subdomains (allow localhost for tests)
630 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
632 if(substr($url,0,4) != 'http')
633 $url = 'http://' . $url;
634 $h = @parse_url($url);
636 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
642 // checks that email is an actual resolvable internet address
644 if(! function_exists('validate_email')) {
645 function validate_email($addr) {
647 if(get_config('system','disable_email_validation'))
650 if(! strpos($addr,'@'))
652 $h = substr($addr,strpos($addr,'@') + 1);
654 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
660 // Check $url against our list of allowed sites,
661 // wildcards allowed. If allowed_sites is unset return true;
662 // If url is allowed, return true.
663 // otherwise, return false
665 if(! function_exists('allowed_url')) {
666 function allowed_url($url) {
668 $h = @parse_url($url);
674 $str_allowed = get_config('system','allowed_sites');
680 $host = strtolower($h['host']);
682 // always allow our own site
684 if($host == strtolower($_SERVER['SERVER_NAME']))
687 $fnmatch = function_exists('fnmatch');
688 $allowed = explode(',',$str_allowed);
690 if(count($allowed)) {
691 foreach($allowed as $a) {
692 $pat = strtolower(trim($a));
693 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
702 // check if email address is allowed to register here.
703 // Compare against our list (wildcards allowed).
704 // Returns false if not allowed, true if allowed or if
705 // allowed list is not configured.
707 if(! function_exists('allowed_email')) {
708 function allowed_email($email) {
711 $domain = strtolower(substr($email,strpos($email,'@') + 1));
715 $str_allowed = get_config('system','allowed_email');
721 $fnmatch = function_exists('fnmatch');
722 $allowed = explode(',',$str_allowed);
724 if(count($allowed)) {
725 foreach($allowed as $a) {
726 $pat = strtolower(trim($a));
727 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
737 if(! function_exists('avatar_img')) {
738 function avatar_img($email) {
742 $avatar['size'] = 175;
743 $avatar['email'] = $email;
745 $avatar['success'] = false;
747 call_hooks('avatar_lookup', $avatar);
749 if(! $avatar['success'])
750 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
752 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
753 return $avatar['url'];
757 if(! function_exists('parse_xml_string')) {
758 function parse_xml_string($s,$strict = true) {
760 if(! strstr($s,'<?xml'))
762 $s2 = substr($s,strpos($s,'<?xml'));
766 libxml_use_internal_errors(true);
768 $x = @simplexml_load_string($s2);
770 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
771 foreach(libxml_get_errors() as $err)
772 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
773 libxml_clear_errors();
778 function add_fcontact($arr,$update = false) {
781 $r = q("UPDATE `fcontact` SET
794 WHERE `url` = '%s' AND `network` = '%s'",
796 dbesc($arr['photo']),
797 dbesc($arr['request']),
800 dbesc($arr['batch']),
801 dbesc($arr['notify']),
803 dbesc($arr['confirm']),
804 dbesc($arr['alias']),
805 dbesc($arr['pubkey']),
806 dbesc(datetime_convert()),
808 dbesc($arr['network'])
812 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
813 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
814 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
817 dbesc($arr['photo']),
818 dbesc($arr['request']),
821 dbesc($arr['batch']),
822 dbesc($arr['notify']),
824 dbesc($arr['confirm']),
825 dbesc($arr['network']),
826 dbesc($arr['alias']),
827 dbesc($arr['pubkey']),
828 dbesc(datetime_convert())
836 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
838 // Suppress "view full size"
839 if (intval(get_config('system','no_view_full_size')))
840 $include_link = false;
844 // Picture addresses can contain special characters
845 $s = htmlspecialchars_decode($srctext);
848 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
850 require_once('include/Photo.php');
851 foreach($matches as $mtch) {
852 logger('scale_external_image: ' . $mtch[1]);
854 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
855 if(stristr($mtch[1],$hostname))
858 // $scale_replace, if passed, is an array of two elements. The
859 // first is the name of the full-size image. The second is the
860 // name of a remote, scaled-down version of the full size image.
861 // This allows Friendica to display the smaller remote image if
862 // one exists, while still linking to the full-size image
864 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
867 $i = @fetch_url($scaled);
871 $cachefile = get_cachefile(hash("md5", $scaled));
872 if ($cachefile != '') {
873 $stamp1 = microtime(true);
874 file_put_contents($cachefile, $i);
875 $a->save_timestamp($stamp1, "file");
878 // guess mimetype from headers or filename
879 $type = guess_image_type($mtch[1],true);
882 $ph = new Photo($i, $type);
883 if($ph->is_valid()) {
884 $orig_width = $ph->getWidth();
885 $orig_height = $ph->getHeight();
887 if($orig_width > 640 || $orig_height > 640) {
889 $ph->scaleImage(640);
890 $new_width = $ph->getWidth();
891 $new_height = $ph->getHeight();
892 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
893 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
894 . "\n" . (($include_link)
895 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
897 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
904 // replace the special char encoding
905 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
910 function fix_contact_ssl_policy(&$contact,$new_policy) {
912 $ssl_changed = false;
913 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
915 $contact['url'] = str_replace('https:','http:',$contact['url']);
916 $contact['request'] = str_replace('https:','http:',$contact['request']);
917 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
918 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
919 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
920 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
923 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
925 $contact['url'] = str_replace('http:','https:',$contact['url']);
926 $contact['request'] = str_replace('http:','https:',$contact['request']);
927 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
928 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
929 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
930 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
934 q("update contact set
941 where id = %d limit 1",
942 dbesc($contact['url']),
943 dbesc($contact['request']),
944 dbesc($contact['notify']),
945 dbesc($contact['poll']),
946 dbesc($contact['confirm']),
947 dbesc($contact['poco']),
948 intval($contact['id'])
956 * xml2array() will convert the given XML text to an array in the XML structure.
957 * Link: http://www.bin-co.com/php/scripts/xml2array/
958 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
959 * Arguments : $contents - The XML text
960 * $namespaces - true or false include namespace information in the returned array as array elements.
961 * $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.
962 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
963 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
964 * Examples: $array = xml2array(file_get_contents('feed.xml'));
965 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
968 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
969 if(!$contents) return array();
971 if(!function_exists('xml_parser_create')) {
972 logger('xml2array: parser function missing');
977 libxml_use_internal_errors(true);
978 libxml_clear_errors();
981 $parser = @xml_parser_create_ns("UTF-8",':');
983 $parser = @xml_parser_create();
986 logger('xml2array: xml_parser_create: no resource');
990 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
991 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
992 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
993 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
994 @xml_parse_into_struct($parser, trim($contents), $xml_values);
995 @xml_parser_free($parser);
998 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
999 foreach(libxml_get_errors() as $err)
1000 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
1001 libxml_clear_errors();
1006 $xml_array = array();
1008 $opened_tags = array();
1011 $current = &$xml_array; // Reference
1013 // Go through the tags.
1014 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1015 foreach($xml_values as $data) {
1016 unset($attributes,$value); // Remove existing values, or there will be trouble
1018 // This command will extract these variables into the foreach scope
1019 // tag(string), type(string), level(int), attributes(array).
1020 extract($data); // We could use the array by itself, but this cooler.
1023 $attributes_data = array();
1026 if($priority == 'tag') $result = $value;
1027 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1030 //Set the attributes too.
1031 if(isset($attributes) and $get_attributes) {
1032 foreach($attributes as $attr => $val) {
1033 if($priority == 'tag') $attributes_data[$attr] = $val;
1034 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1038 // See tag status and do the needed.
1039 if($namespaces && strpos($tag,':')) {
1040 $namespc = substr($tag,0,strrpos($tag,':'));
1041 $tag = strtolower(substr($tag,strlen($namespc)+1));
1042 $result['@namespace'] = $namespc;
1044 $tag = strtolower($tag);
1046 if($type == "open") { // The starting of the tag '<tag>'
1047 $parent[$level-1] = &$current;
1048 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1049 $current[$tag] = $result;
1050 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1051 $repeated_tag_index[$tag.'_'.$level] = 1;
1053 $current = &$current[$tag];
1055 } else { // There was another element with the same tag name
1057 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1058 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1059 $repeated_tag_index[$tag.'_'.$level]++;
1060 } else { // This section will make the value an array if multiple tags with the same name appear together
1061 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1062 $repeated_tag_index[$tag.'_'.$level] = 2;
1064 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1065 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1066 unset($current[$tag.'_attr']);
1070 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1071 $current = &$current[$tag][$last_item_index];
1074 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1075 //See if the key is already taken.
1076 if(!isset($current[$tag])) { //New Key
1077 $current[$tag] = $result;
1078 $repeated_tag_index[$tag.'_'.$level] = 1;
1079 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1081 } else { // If taken, put all things inside a list(array)
1082 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1084 // ...push the new element into that array.
1085 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1087 if($priority == 'tag' and $get_attributes and $attributes_data) {
1088 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1090 $repeated_tag_index[$tag.'_'.$level]++;
1092 } else { // If it is not an array...
1093 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1094 $repeated_tag_index[$tag.'_'.$level] = 1;
1095 if($priority == 'tag' and $get_attributes) {
1096 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1098 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1099 unset($current[$tag.'_attr']);
1102 if($attributes_data) {
1103 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1106 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1110 } elseif($type == 'close') { // End of tag '</tag>'
1111 $current = &$parent[$level-1];
1118 function original_url($url, $depth=1, $fetchbody = false) {
1122 // Remove Analytics Data from Google and other tracking platforms
1123 $urldata = parse_url($url);
1124 if (is_string($urldata["query"])) {
1125 $query = $urldata["query"];
1126 parse_str($query, $querydata);
1128 if (is_array($querydata))
1129 foreach ($querydata AS $param=>$value)
1130 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1131 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1132 "fb_action_ids", "fb_action_types", "fb_ref",
1134 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1136 $pair = $param."=".urlencode($value);
1137 $url = str_replace($pair, "", $url);
1139 // Second try: if the url isn't encoded completely
1140 $pair = $param."=".str_replace(" ", "+", $value);
1141 $url = str_replace($pair, "", $url);
1143 // Third try: Maybey the url isn't encoded at all
1144 $pair = $param."=".$value;
1145 $url = str_replace($pair, "", $url);
1147 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1150 if (substr($url, -1, 1) == "?")
1151 $url = substr($url, 0, -1);
1157 $url = trim($url, "'");
1159 $siteinfo = array();
1161 curl_setopt($ch, CURLOPT_URL, $url);
1162 curl_setopt($ch, CURLOPT_HEADER, 1);
1163 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, $a->get_useragent());
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 // Check for redirects in the meta elements of the body if there are no redirects in the header.
1183 return(original_url($url, ++$depth, true));
1185 // if the file is too large then exit
1186 if ($curl_info["download_content_length"] > 1000000)
1189 // if it isn't a HTML file then exit
1190 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
1194 curl_setopt($ch, CURLOPT_URL, $url);
1195 curl_setopt($ch, CURLOPT_HEADER, 0);
1196 curl_setopt($ch, CURLOPT_NOBODY, 0);
1197 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1198 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1199 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
1201 $body = curl_exec($ch);
1204 if (trim($body) == "")
1207 // Check for redirect in meta elements
1208 $doc = new DOMDocument();
1209 @$doc->loadHTML($body);
1211 $xpath = new DomXPath($doc);
1213 $list = $xpath->query("//meta[@content]");
1214 foreach ($list as $node) {
1216 if ($node->attributes->length)
1217 foreach ($node->attributes as $attribute)
1218 $attr[$attribute->name] = $attribute->value;
1220 if (@$attr["http-equiv"] == 'refresh') {
1221 $path = $attr["content"];
1222 $pathinfo = explode(";", $path);
1224 foreach ($pathinfo AS $value)
1225 if (substr(strtolower($value), 0, 4) == "url=")
1226 return(original_url(substr($value, 4), ++$depth));
1233 if (!function_exists('short_link')) {
1234 function short_link($url) {
1235 require_once('library/slinky.php');
1236 $slinky = new Slinky($url);
1237 $yourls_url = get_config('yourls','url1');
1239 $yourls_username = get_config('yourls','username1');
1240 $yourls_password = get_config('yourls', 'password1');
1241 $yourls_ssl = get_config('yourls', 'ssl1');
1242 $yourls = new Slinky_YourLS();
1243 $yourls->set('username', $yourls_username);
1244 $yourls->set('password', $yourls_password);
1245 $yourls->set('ssl', $yourls_ssl);
1246 $yourls->set('yourls-url', $yourls_url);
1247 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1249 // setup a cascade of shortening services
1250 // try to get a short link from these services
1251 // in the order ur1.ca, trim, id.gd, tinyurl
1252 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1254 return $slinky->short();