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, "Friendica");
39 @curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Friendica)");
42 if(intval($timeout)) {
43 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
46 $curl_time = intval(get_config('system','curl_timeout'));
47 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
49 // by default we will allow self-signed certs
50 // but you can override this
52 $check_cert = get_config('system','verifyssl');
53 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
55 $prx = get_config('system','proxy');
57 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
58 @curl_setopt($ch, CURLOPT_PROXY, $prx);
59 $prxusr = @get_config('system','proxyuser');
61 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
64 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
68 // don't let curl abort the entire application
69 // if it throws any errors.
74 $curl_info = @curl_getinfo($ch);
75 $http_code = $curl_info['http_code'];
76 // logger('fetch_url:' . $http_code . ' data: ' . $s);
79 // Pull out multiple headers, e.g. proxy and continuation headers
80 // allow for HTTP/2.x without fixing code
82 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
83 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
85 $base = substr($base,strlen($chunk));
88 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
89 $new_location_info = @parse_url($curl_info["redirect_url"]);
90 $old_location_info = @parse_url($curl_info["url"]);
92 $newurl = $curl_info["redirect_url"];
94 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
95 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
98 if (preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches)) {
99 $newurl = trim(array_pop($matches));
101 if(strpos($newurl,'/') === 0)
102 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
103 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
105 return fetch_url($newurl,$binary,$redirects,$timeout,$accept_content,$cookiejar);
109 $a->set_curl_code($http_code);
110 $a->set_curl_content_type($curl_info['content_type']);
112 $body = substr($s,strlen($header));
113 $a->set_curl_headers($header);
116 $a->save_timestamp($stamp1, "network");
121 // post request to $url. $params is an array of post variables.
123 if(! function_exists('post_url')) {
124 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
125 $stamp1 = microtime(true);
128 $ch = curl_init($url);
129 if(($redirects > 8) || (! $ch))
132 logger("post_url: start ".$url, LOGGER_DATA);
134 curl_setopt($ch, CURLOPT_HEADER, true);
135 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
136 curl_setopt($ch, CURLOPT_POST,1);
137 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
138 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
140 if(intval($timeout)) {
141 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
144 $curl_time = intval(get_config('system','curl_timeout'));
145 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
148 if(defined('LIGHTTPD')) {
149 if(!is_array($headers)) {
150 $headers = array('Expect:');
152 if(!in_array('Expect:', $headers)) {
153 array_push($headers, 'Expect:');
158 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
160 $check_cert = get_config('system','verifyssl');
161 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
162 $prx = get_config('system','proxy');
164 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
165 curl_setopt($ch, CURLOPT_PROXY, $prx);
166 $prxusr = get_config('system','proxyuser');
168 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
171 $a->set_curl_code(0);
173 // don't let curl abort the entire application
174 // if it throws any errors.
176 $s = @curl_exec($ch);
179 $curl_info = curl_getinfo($ch);
180 $http_code = $curl_info['http_code'];
182 logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
186 // Pull out multiple headers, e.g. proxy and continuation headers
187 // allow for HTTP/2.x without fixing code
189 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
190 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
192 $base = substr($base,strlen($chunk));
195 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
197 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
198 $newurl = trim(array_pop($matches));
199 if(strpos($newurl,'/') === 0)
200 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
201 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
203 logger("post_url: redirect ".$url." to ".$newurl);
204 return post_url($newurl,$params, $headers, $redirects, $timeout);
205 //return fetch_url($newurl,false,$redirects,$timeout);
208 $a->set_curl_code($http_code);
209 $body = substr($s,strlen($header));
211 $a->set_curl_headers($header);
215 $a->save_timestamp($stamp1, "network");
217 logger("post_url: end ".$url, LOGGER_DATA);
222 // Generic XML return
223 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
224 // of $st and an optional text <message> of $message and terminates the current process.
226 if(! function_exists('xml_status')) {
227 function xml_status($st, $message = '') {
229 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
232 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
234 header( "Content-type: text/xml" );
235 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
236 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
241 if(! function_exists('http_status_exit')) {
242 function http_status_exit($val) {
247 if($val >= 200 && $val < 300)
250 logger('http_status_exit ' . $val);
251 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
257 // convert an XML document to a normalised, case-corrected array
260 if(! function_exists('convert_xml_element_to_array')) {
261 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
263 // If we're getting too deep, bail out
264 if ($recursion_depth > 512) {
268 if (!is_string($xml_element) &&
269 !is_array($xml_element) &&
270 (get_class($xml_element) == 'SimpleXMLElement')) {
271 $xml_element_copy = $xml_element;
272 $xml_element = get_object_vars($xml_element);
275 if (is_array($xml_element)) {
276 $result_array = array();
277 if (count($xml_element) <= 0) {
278 return (trim(strval($xml_element_copy)));
281 foreach($xml_element as $key=>$value) {
284 $result_array[strtolower($key)] =
285 convert_xml_element_to_array($value, $recursion_depth);
288 if ($recursion_depth == 0) {
289 $temp_array = $result_array;
290 $result_array = array(
291 strtolower($xml_element_copy->getName()) => $temp_array,
295 return ($result_array);
298 return (trim(strval($xml_element)));
302 // Given an email style address, perform webfinger lookup and
303 // return the resulting DFRN profile URL, or if no DFRN profile URL
304 // is located, returns an OStatus subscription template (prefixed
305 // with the string 'stat:' to identify it as on OStatus template).
306 // If this isn't an email style address just return $s.
307 // Return an empty string if email-style addresses but webfinger fails,
308 // or if the resultant personal XRD doesn't contain a supported
309 // subscription/friend-request attribute.
311 // amended 7/9/2011 to return an hcard which could save potentially loading
312 // a lengthy content page to scrape dfrn attributes
314 if(! function_exists('webfinger_dfrn')) {
315 function webfinger_dfrn($s,&$hcard) {
316 if(! strstr($s,'@')) {
321 $links = webfinger($s);
322 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
324 foreach($links as $link) {
325 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
326 $profile_link = $link['@attributes']['href'];
327 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
328 $profile_link = 'stat:' . $link['@attributes']['template'];
329 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
330 $hcard = $link['@attributes']['href'];
333 return $profile_link;
336 // Given an email style address, perform webfinger lookup and
337 // return the array of link attributes from the personal XRD file.
338 // On error/failure return an empty array.
341 if(! function_exists('webfinger')) {
342 function webfinger($s, $debug = false) {
345 $host = substr($s,strpos($s,'@') + 1);
348 $tpl = fetch_lrdd_template($host);
349 logger('webfinger: lrdd template: ' . $tpl);
351 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
352 logger('webfinger: pxrd: ' . $pxrd);
353 $links = fetch_xrd_links($pxrd);
354 if(! count($links)) {
355 // try with double slashes
356 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
357 logger('webfinger: pxrd: ' . $pxrd);
358 $links = fetch_xrd_links($pxrd);
366 if(! function_exists('lrdd')) {
367 function lrdd($uri, $debug = false) {
371 // default priority is host priority, host-meta first
375 // All we have is an email address. Resource-priority is irrelevant
376 // because our URI isn't directly resolvable.
378 if(strstr($uri,'@')) {
379 return(webfinger($uri));
382 // get the host meta file
384 $host = @parse_url($uri);
387 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
388 $url .= $host['host'] . '/.well-known/host-meta' ;
393 logger('lrdd: constructed url: ' . $url);
395 $xml = fetch_url($url);
397 $headers = $a->get_curl_headers();
402 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
404 if(! stristr($xml,'<xrd'))
407 $h = parse_xml_string($xml);
411 $arr = convert_xml_element_to_array($h);
413 if(isset($arr['xrd']['property'])) {
414 $property = $arr['crd']['property'];
415 if(! isset($property[0]))
416 $properties = array($property);
418 $properties = $property;
419 foreach($properties as $prop)
420 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
421 $priority = 'resource';
424 // save the links in case we need them
428 if(isset($arr['xrd']['link'])) {
429 $link = $arr['xrd']['link'];
430 if(! isset($link[0]))
431 $links = array($link);
436 // do we have a template or href?
439 foreach($links as $link) {
440 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
441 if(x($link['@attributes'],'template'))
442 $tpl = $link['@attributes']['template'];
443 elseif(x($link['@attributes'],'href'))
444 $href = $link['@attributes']['href'];
449 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
452 if($priority === 'host') {
454 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
458 logger('lrdd: (host priority) pxrd: ' . $pxrd);
459 $links = fetch_xrd_links($pxrd);
463 $lines = explode("\n",$headers);
465 foreach($lines as $line) {
466 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
467 return(fetch_xrd_links($matches[1]));
475 // priority 'resource'
478 $html = fetch_url($uri);
479 $headers = $a->get_curl_headers();
480 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
482 // don't try and parse raw xml as html
483 if(! strstr($html,'<?xml')) {
484 require_once('library/HTML5/Parser.php');
487 $dom = HTML5_Parser::parse($html);
488 } catch (DOMException $e) {
489 logger('lrdd: parse error: ' . $e);
492 if(isset($dom) && $dom) {
493 $items = $dom->getElementsByTagName('link');
494 foreach($items as $item) {
495 $x = $item->getAttribute('rel');
497 $pagelink = $item->getAttribute('href');
505 return(fetch_xrd_links($pagelink));
507 // next look in HTTP headers
509 $lines = explode("\n",$headers);
511 foreach($lines as $line) {
512 // TODO alter the following regex to support multiple relations (space separated)
513 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
514 $pagelink = $matches[1];
517 // don't try and run feeds through the html5 parser
518 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
520 if(stristr($html,'<rss') || stristr($html,'<feed'))
526 return(fetch_xrd_links($pagelink));
528 // If we haven't found any links, return the host xrd links (which we have already fetched)
539 // Given a host name, locate the LRDD template from that
540 // host. Returns the LRDD template or an empty string on
543 if(! function_exists('fetch_lrdd_template')) {
544 function fetch_lrdd_template($host) {
547 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
548 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
549 $links = fetch_xrd_links($url1);
550 logger('fetch_lrdd_template from: ' . $url1);
551 logger('template (https): ' . print_r($links,true));
552 if(! count($links)) {
553 logger('fetch_lrdd_template from: ' . $url2);
554 $links = fetch_xrd_links($url2);
555 logger('template (http): ' . print_r($links,true));
558 foreach($links as $link)
559 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
560 $tpl = $link['@attributes']['template'];
562 if(! strpos($tpl,'{uri}'))
567 // Given a URL, retrieve the page as an XRD document.
568 // Return an array of links.
569 // on error/failure return empty array.
571 if(! function_exists('fetch_xrd_links')) {
572 function fetch_xrd_links($url) {
574 $xrd_timeout = intval(get_config('system','xrd_timeout'));
576 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
578 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
580 if ((! $xml) || (! stristr($xml,'<xrd')))
583 // fix diaspora's bad xml
584 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
586 $h = parse_xml_string($xml);
590 $arr = convert_xml_element_to_array($h);
594 if(isset($arr['xrd']['link'])) {
595 $link = $arr['xrd']['link'];
596 if(! isset($link[0]))
597 $links = array($link);
601 if(isset($arr['xrd']['alias'])) {
602 $alias = $arr['xrd']['alias'];
603 if(! isset($alias[0]))
604 $aliases = array($alias);
607 if(is_array($aliases) && count($aliases)) {
608 foreach($aliases as $alias) {
609 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
614 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
621 // Take a URL from the wild, prepend http:// if necessary
622 // and check DNS to see if it's real (or check if is a valid IP address)
623 // return true if it's OK, false if something is wrong with it
625 if(! function_exists('validate_url')) {
626 function validate_url(&$url) {
627 // no naked subdomains (allow localhost for tests)
628 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
630 if(substr($url,0,4) != 'http')
631 $url = 'http://' . $url;
632 $h = @parse_url($url);
634 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
640 // checks that email is an actual resolvable internet address
642 if(! function_exists('validate_email')) {
643 function validate_email($addr) {
645 if(get_config('system','disable_email_validation'))
648 if(! strpos($addr,'@'))
650 $h = substr($addr,strpos($addr,'@') + 1);
652 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
658 // Check $url against our list of allowed sites,
659 // wildcards allowed. If allowed_sites is unset return true;
660 // If url is allowed, return true.
661 // otherwise, return false
663 if(! function_exists('allowed_url')) {
664 function allowed_url($url) {
666 $h = @parse_url($url);
672 $str_allowed = get_config('system','allowed_sites');
678 $host = strtolower($h['host']);
680 // always allow our own site
682 if($host == strtolower($_SERVER['SERVER_NAME']))
685 $fnmatch = function_exists('fnmatch');
686 $allowed = explode(',',$str_allowed);
688 if(count($allowed)) {
689 foreach($allowed as $a) {
690 $pat = strtolower(trim($a));
691 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
700 // check if email address is allowed to register here.
701 // Compare against our list (wildcards allowed).
702 // Returns false if not allowed, true if allowed or if
703 // allowed list is not configured.
705 if(! function_exists('allowed_email')) {
706 function allowed_email($email) {
709 $domain = strtolower(substr($email,strpos($email,'@') + 1));
713 $str_allowed = get_config('system','allowed_email');
719 $fnmatch = function_exists('fnmatch');
720 $allowed = explode(',',$str_allowed);
722 if(count($allowed)) {
723 foreach($allowed as $a) {
724 $pat = strtolower(trim($a));
725 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
735 if(! function_exists('avatar_img')) {
736 function avatar_img($email) {
740 $avatar['size'] = 175;
741 $avatar['email'] = $email;
743 $avatar['success'] = false;
745 call_hooks('avatar_lookup', $avatar);
747 if(! $avatar['success'])
748 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
750 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
751 return $avatar['url'];
755 if(! function_exists('parse_xml_string')) {
756 function parse_xml_string($s,$strict = true) {
758 if(! strstr($s,'<?xml'))
760 $s2 = substr($s,strpos($s,'<?xml'));
764 libxml_use_internal_errors(true);
766 $x = @simplexml_load_string($s2);
768 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
769 foreach(libxml_get_errors() as $err)
770 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
771 libxml_clear_errors();
776 function add_fcontact($arr,$update = false) {
779 $r = q("UPDATE `fcontact` SET
792 WHERE `url` = '%s' AND `network` = '%s'",
794 dbesc($arr['photo']),
795 dbesc($arr['request']),
798 dbesc($arr['batch']),
799 dbesc($arr['notify']),
801 dbesc($arr['confirm']),
802 dbesc($arr['alias']),
803 dbesc($arr['pubkey']),
804 dbesc(datetime_convert()),
806 dbesc($arr['network'])
810 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
811 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
812 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
815 dbesc($arr['photo']),
816 dbesc($arr['request']),
819 dbesc($arr['batch']),
820 dbesc($arr['notify']),
822 dbesc($arr['confirm']),
823 dbesc($arr['network']),
824 dbesc($arr['alias']),
825 dbesc($arr['pubkey']),
826 dbesc(datetime_convert())
834 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
836 // Suppress "view full size"
837 if (intval(get_config('system','no_view_full_size')))
838 $include_link = false;
842 // Picture addresses can contain special characters
843 $s = htmlspecialchars_decode($srctext);
846 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
848 require_once('include/Photo.php');
849 foreach($matches as $mtch) {
850 logger('scale_external_image: ' . $mtch[1]);
852 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
853 if(stristr($mtch[1],$hostname))
856 // $scale_replace, if passed, is an array of two elements. The
857 // first is the name of the full-size image. The second is the
858 // name of a remote, scaled-down version of the full size image.
859 // This allows Friendica to display the smaller remote image if
860 // one exists, while still linking to the full-size image
862 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
865 $i = @fetch_url($scaled);
869 $cachefile = get_cachefile(hash("md5", $scaled));
870 if ($cachefile != '') {
871 $stamp1 = microtime(true);
872 file_put_contents($cachefile, $i);
873 $a->save_timestamp($stamp1, "file");
876 // guess mimetype from headers or filename
877 $type = guess_image_type($mtch[1],true);
880 $ph = new Photo($i, $type);
881 if($ph->is_valid()) {
882 $orig_width = $ph->getWidth();
883 $orig_height = $ph->getHeight();
885 if($orig_width > 640 || $orig_height > 640) {
887 $ph->scaleImage(640);
888 $new_width = $ph->getWidth();
889 $new_height = $ph->getHeight();
890 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
891 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
892 . "\n" . (($include_link)
893 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
895 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
902 // replace the special char encoding
903 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
908 function fix_contact_ssl_policy(&$contact,$new_policy) {
910 $ssl_changed = false;
911 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
913 $contact['url'] = str_replace('https:','http:',$contact['url']);
914 $contact['request'] = str_replace('https:','http:',$contact['request']);
915 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
916 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
917 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
918 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
921 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
923 $contact['url'] = str_replace('http:','https:',$contact['url']);
924 $contact['request'] = str_replace('http:','https:',$contact['request']);
925 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
926 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
927 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
928 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
932 q("update contact set
939 where id = %d limit 1",
940 dbesc($contact['url']),
941 dbesc($contact['request']),
942 dbesc($contact['notify']),
943 dbesc($contact['poll']),
944 dbesc($contact['confirm']),
945 dbesc($contact['poco']),
946 intval($contact['id'])
954 * xml2array() will convert the given XML text to an array in the XML structure.
955 * Link: http://www.bin-co.com/php/scripts/xml2array/
956 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
957 * Arguments : $contents - The XML text
958 * $namespaces - true or false include namespace information in the returned array as array elements.
959 * $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.
960 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
961 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
962 * Examples: $array = xml2array(file_get_contents('feed.xml'));
963 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
966 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
967 if(!$contents) return array();
969 if(!function_exists('xml_parser_create')) {
970 logger('xml2array: parser function missing');
975 libxml_use_internal_errors(true);
976 libxml_clear_errors();
979 $parser = @xml_parser_create_ns("UTF-8",':');
981 $parser = @xml_parser_create();
984 logger('xml2array: xml_parser_create: no resource');
988 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
989 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
990 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
991 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
992 @xml_parse_into_struct($parser, trim($contents), $xml_values);
993 @xml_parser_free($parser);
996 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
997 foreach(libxml_get_errors() as $err)
998 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
999 libxml_clear_errors();
1004 $xml_array = array();
1006 $opened_tags = array();
1009 $current = &$xml_array; // Reference
1011 // Go through the tags.
1012 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1013 foreach($xml_values as $data) {
1014 unset($attributes,$value); // Remove existing values, or there will be trouble
1016 // This command will extract these variables into the foreach scope
1017 // tag(string), type(string), level(int), attributes(array).
1018 extract($data); // We could use the array by itself, but this cooler.
1021 $attributes_data = array();
1024 if($priority == 'tag') $result = $value;
1025 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1028 //Set the attributes too.
1029 if(isset($attributes) and $get_attributes) {
1030 foreach($attributes as $attr => $val) {
1031 if($priority == 'tag') $attributes_data[$attr] = $val;
1032 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1036 // See tag status and do the needed.
1037 if($namespaces && strpos($tag,':')) {
1038 $namespc = substr($tag,0,strrpos($tag,':'));
1039 $tag = strtolower(substr($tag,strlen($namespc)+1));
1040 $result['@namespace'] = $namespc;
1042 $tag = strtolower($tag);
1044 if($type == "open") { // The starting of the tag '<tag>'
1045 $parent[$level-1] = &$current;
1046 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1047 $current[$tag] = $result;
1048 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1049 $repeated_tag_index[$tag.'_'.$level] = 1;
1051 $current = &$current[$tag];
1053 } else { // There was another element with the same tag name
1055 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1056 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1057 $repeated_tag_index[$tag.'_'.$level]++;
1058 } else { // This section will make the value an array if multiple tags with the same name appear together
1059 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1060 $repeated_tag_index[$tag.'_'.$level] = 2;
1062 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1063 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1064 unset($current[$tag.'_attr']);
1068 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1069 $current = &$current[$tag][$last_item_index];
1072 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1073 //See if the key is already taken.
1074 if(!isset($current[$tag])) { //New Key
1075 $current[$tag] = $result;
1076 $repeated_tag_index[$tag.'_'.$level] = 1;
1077 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1079 } else { // If taken, put all things inside a list(array)
1080 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1082 // ...push the new element into that array.
1083 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1085 if($priority == 'tag' and $get_attributes and $attributes_data) {
1086 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1088 $repeated_tag_index[$tag.'_'.$level]++;
1090 } else { // If it is not an array...
1091 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1092 $repeated_tag_index[$tag.'_'.$level] = 1;
1093 if($priority == 'tag' and $get_attributes) {
1094 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1096 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1097 unset($current[$tag.'_attr']);
1100 if($attributes_data) {
1101 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1104 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1108 } elseif($type == 'close') { // End of tag '</tag>'
1109 $current = &$parent[$level-1];
1116 function original_url($url, $depth=1, $fetchbody = false) {
1118 // Remove Analytics Data from Google and other tracking platforms
1119 $urldata = parse_url($url);
1120 if (is_string($urldata["query"])) {
1121 $query = $urldata["query"];
1122 parse_str($query, $querydata);
1124 if (is_array($querydata))
1125 foreach ($querydata AS $param=>$value)
1126 if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
1127 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
1128 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
1129 $pair = $param."=".$value;
1130 $url = str_replace($pair, "", $url);
1131 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
1134 if (substr($url, -1, 1) == "?")
1135 $url = substr($url, 0, -1);
1141 $url = trim($url, "'");
1143 $siteinfo = array();
1145 curl_setopt($ch, CURLOPT_URL, $url);
1146 curl_setopt($ch, CURLOPT_HEADER, 1);
1149 curl_setopt($ch, CURLOPT_NOBODY, 0);
1151 curl_setopt($ch, CURLOPT_NOBODY, 1);
1153 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
1154 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1155 curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0');
1157 $header = curl_exec($ch);
1158 $curl_info = @curl_getinfo($ch);
1159 $http_code = $curl_info['http_code'];
1162 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
1163 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
1164 if ($curl_info['redirect_url'] != "")
1165 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
1167 return(original_url($curl_info['location'], ++$depth, $fetchbody));
1170 $pos = strpos($header, "\r\n\r\n");
1173 $body = trim(substr($header, $pos));
1177 if (trim($body) == "")
1178 return(original_url($url, ++$depth, true));
1180 $doc = new DOMDocument();
1181 @$doc->loadHTML($body);
1183 $xpath = new DomXPath($doc);
1185 $list = $xpath->query("//meta[@content]");
1186 foreach ($list as $node) {
1188 if ($node->attributes->length)
1189 foreach ($node->attributes as $attribute)
1190 $attr[$attribute->name] = $attribute->value;
1192 if (@$attr["http-equiv"] == 'refresh') {
1193 $path = $attr["content"];
1194 $pathinfo = explode(";", $path);
1196 foreach ($pathinfo AS $value)
1197 if (substr(strtolower($value), 0, 4) == "url=")
1198 return(original_url(substr($value, 4), ++$depth));
1205 if (!function_exists('short_link')) {
1206 function short_link($url) {
1207 require_once('library/slinky.php');
1208 $slinky = new Slinky($url);
1209 $yourls_url = get_config('yourls','url1');
1211 $yourls_username = get_config('yourls','username1');
1212 $yourls_password = get_config('yourls', 'password1');
1213 $yourls_ssl = get_config('yourls', 'ssl1');
1214 $yourls = new Slinky_YourLS();
1215 $yourls->set('username', $yourls_username);
1216 $yourls->set('password', $yourls_password);
1217 $yourls->set('ssl', $yourls_ssl);
1218 $yourls->set('yourls-url', $yourls_url);
1219 $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1221 // setup a cascade of shortening services
1222 // try to get a short link from these services
1223 // in the order ur1.ca, trim, id.gd, tinyurl
1224 $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
1226 return $slinky->short();