4 // curl wrapper. If binary flag is true, return binary
7 if(! function_exists('fetch_url')) {
8 function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null) {
10 $stamp1 = microtime(true);
14 $ch = @curl_init($url);
15 if(($redirects > 8) || (! $ch))
18 @curl_setopt($ch, CURLOPT_HEADER, true);
20 @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
21 @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
23 if (!is_null($accept_content)){
24 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
25 "Accept: " . $accept_content
29 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
30 //@curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
31 @curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Friendica)");
34 if(intval($timeout)) {
35 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
38 $curl_time = intval(get_config('system','curl_timeout'));
39 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
41 // by default we will allow self-signed certs
42 // but you can override this
44 $check_cert = get_config('system','verifyssl');
45 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
47 $prx = get_config('system','proxy');
49 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
50 @curl_setopt($ch, CURLOPT_PROXY, $prx);
51 $prxusr = @get_config('system','proxyuser');
53 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
56 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
60 // don't let curl abort the entire application
61 // if it throws any errors.
66 $curl_info = @curl_getinfo($ch);
67 $http_code = $curl_info['http_code'];
68 // logger('fetch_url:' . $http_code . ' data: ' . $s);
71 // Pull out multiple headers, e.g. proxy and continuation headers
72 // allow for HTTP/2.x without fixing code
74 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
75 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
77 $base = substr($base,strlen($chunk));
80 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
81 $new_location_info = @parse_url($curl_info["redirect_url"]);
82 $old_location_info = @parse_url($curl_info["url"]);
84 $newurl = $curl_info["redirect_url"];
86 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
87 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
90 //preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
91 //$newurl = trim(array_pop($matches));
92 if(strpos($newurl,'/') === 0)
93 $newurl = $url . $newurl;
94 $url_parsed = @parse_url($newurl);
95 if (isset($url_parsed)) {
97 return fetch_url($newurl,$binary,$redirects,$timeout);
101 $a->set_curl_code($http_code);
103 $body = substr($s,strlen($header));
104 $a->set_curl_headers($header);
107 $stamp2 = microtime(true);
108 $duration = (float)($stamp2-$stamp1);
109 $a->performance["network"] += (float)$duration;
114 // post request to $url. $params is an array of post variables.
116 if(! function_exists('post_url')) {
117 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
119 $stamp1 = microtime(true);
122 $ch = curl_init($url);
123 if(($redirects > 8) || (! $ch))
126 curl_setopt($ch, CURLOPT_HEADER, true);
127 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
128 curl_setopt($ch, CURLOPT_POST,1);
129 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
130 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
132 if(intval($timeout)) {
133 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
136 $curl_time = intval(get_config('system','curl_timeout'));
137 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
140 if(defined('LIGHTTPD')) {
141 if(!is_array($headers)) {
142 $headers = array('Expect:');
144 if(!in_array('Expect:', $headers)) {
145 array_push($headers, 'Expect:');
150 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
152 $check_cert = get_config('system','verifyssl');
153 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
154 $prx = get_config('system','proxy');
156 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
157 curl_setopt($ch, CURLOPT_PROXY, $prx);
158 $prxusr = get_config('system','proxyuser');
160 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
163 $a->set_curl_code(0);
165 // don't let curl abort the entire application
166 // if it throws any errors.
168 $s = @curl_exec($ch);
171 $curl_info = curl_getinfo($ch);
172 $http_code = $curl_info['http_code'];
176 // Pull out multiple headers, e.g. proxy and continuation headers
177 // allow for HTTP/2.x without fixing code
179 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
180 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
182 $base = substr($base,strlen($chunk));
185 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
187 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
188 $newurl = trim(array_pop($matches));
189 if(strpos($newurl,'/') === 0)
190 $newurl = $url . $newurl;
191 $url_parsed = @parse_url($newurl);
192 if (isset($url_parsed)) {
194 return fetch_url($newurl,false,$redirects,$timeout);
197 $a->set_curl_code($http_code);
198 $body = substr($s,strlen($header));
200 $a->set_curl_headers($header);
204 $stamp2 = microtime(true);
205 $duration = (float)($stamp2-$stamp1);
206 $a->performance["network"] += (float)$duration;
211 // Generic XML return
212 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
213 // of $st and an optional text <message> of $message and terminates the current process.
215 if(! function_exists('xml_status')) {
216 function xml_status($st, $message = '') {
218 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
221 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
223 header( "Content-type: text/xml" );
224 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
225 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
230 if(! function_exists('http_status_exit')) {
231 function http_status_exit($val) {
236 if($val >= 200 && $val < 300)
239 logger('http_status_exit ' . $val);
240 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
246 // convert an XML document to a normalised, case-corrected array
249 if(! function_exists('convert_xml_element_to_array')) {
250 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
252 // If we're getting too deep, bail out
253 if ($recursion_depth > 512) {
257 if (!is_string($xml_element) &&
258 !is_array($xml_element) &&
259 (get_class($xml_element) == 'SimpleXMLElement')) {
260 $xml_element_copy = $xml_element;
261 $xml_element = get_object_vars($xml_element);
264 if (is_array($xml_element)) {
265 $result_array = array();
266 if (count($xml_element) <= 0) {
267 return (trim(strval($xml_element_copy)));
270 foreach($xml_element as $key=>$value) {
273 $result_array[strtolower($key)] =
274 convert_xml_element_to_array($value, $recursion_depth);
277 if ($recursion_depth == 0) {
278 $temp_array = $result_array;
279 $result_array = array(
280 strtolower($xml_element_copy->getName()) => $temp_array,
284 return ($result_array);
287 return (trim(strval($xml_element)));
291 // Given an email style address, perform webfinger lookup and
292 // return the resulting DFRN profile URL, or if no DFRN profile URL
293 // is located, returns an OStatus subscription template (prefixed
294 // with the string 'stat:' to identify it as on OStatus template).
295 // If this isn't an email style address just return $s.
296 // Return an empty string if email-style addresses but webfinger fails,
297 // or if the resultant personal XRD doesn't contain a supported
298 // subscription/friend-request attribute.
300 // amended 7/9/2011 to return an hcard which could save potentially loading
301 // a lengthy content page to scrape dfrn attributes
303 if(! function_exists('webfinger_dfrn')) {
304 function webfinger_dfrn($s,&$hcard) {
305 if(! strstr($s,'@')) {
310 $links = webfinger($s);
311 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
313 foreach($links as $link) {
314 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
315 $profile_link = $link['@attributes']['href'];
316 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
317 $profile_link = 'stat:' . $link['@attributes']['template'];
318 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
319 $hcard = $link['@attributes']['href'];
322 return $profile_link;
325 // Given an email style address, perform webfinger lookup and
326 // return the array of link attributes from the personal XRD file.
327 // On error/failure return an empty array.
330 if(! function_exists('webfinger')) {
331 function webfinger($s, $debug = false) {
334 $host = substr($s,strpos($s,'@') + 1);
337 $tpl = fetch_lrdd_template($host);
338 logger('webfinger: lrdd template: ' . $tpl);
340 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
341 logger('webfinger: pxrd: ' . $pxrd);
342 $links = fetch_xrd_links($pxrd);
343 if(! count($links)) {
344 // try with double slashes
345 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
346 logger('webfinger: pxrd: ' . $pxrd);
347 $links = fetch_xrd_links($pxrd);
355 if(! function_exists('lrdd')) {
356 function lrdd($uri, $debug = false) {
360 // default priority is host priority, host-meta first
364 // All we have is an email address. Resource-priority is irrelevant
365 // because our URI isn't directly resolvable.
367 if(strstr($uri,'@')) {
368 return(webfinger($uri));
371 // get the host meta file
373 $host = @parse_url($uri);
376 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
377 $url .= $host['host'] . '/.well-known/host-meta' ;
382 logger('lrdd: constructed url: ' . $url);
384 $xml = fetch_url($url);
386 $headers = $a->get_curl_headers();
391 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
393 if(! stristr($xml,'<xrd'))
396 $h = parse_xml_string($xml);
400 $arr = convert_xml_element_to_array($h);
402 if(isset($arr['xrd']['property'])) {
403 $property = $arr['crd']['property'];
404 if(! isset($property[0]))
405 $properties = array($property);
407 $properties = $property;
408 foreach($properties as $prop)
409 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
410 $priority = 'resource';
413 // save the links in case we need them
417 if(isset($arr['xrd']['link'])) {
418 $link = $arr['xrd']['link'];
419 if(! isset($link[0]))
420 $links = array($link);
425 // do we have a template or href?
428 foreach($links as $link) {
429 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
430 if(x($link['@attributes'],'template'))
431 $tpl = $link['@attributes']['template'];
432 elseif(x($link['@attributes'],'href'))
433 $href = $link['@attributes']['href'];
438 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
441 if($priority === 'host') {
443 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
447 logger('lrdd: (host priority) pxrd: ' . $pxrd);
448 $links = fetch_xrd_links($pxrd);
452 $lines = explode("\n",$headers);
454 foreach($lines as $line) {
455 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
456 return(fetch_xrd_links($matches[1]));
464 // priority 'resource'
467 $html = fetch_url($uri);
468 $headers = $a->get_curl_headers();
469 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
471 // don't try and parse raw xml as html
472 if(! strstr($html,'<?xml')) {
473 require_once('library/HTML5/Parser.php');
476 $dom = HTML5_Parser::parse($html);
477 } catch (DOMException $e) {
478 logger('lrdd: parse error: ' . $e);
481 if(isset($dom) && $dom) {
482 $items = $dom->getElementsByTagName('link');
483 foreach($items as $item) {
484 $x = $item->getAttribute('rel');
486 $pagelink = $item->getAttribute('href');
494 return(fetch_xrd_links($pagelink));
496 // next look in HTTP headers
498 $lines = explode("\n",$headers);
500 foreach($lines as $line) {
501 // TODO alter the following regex to support multiple relations (space separated)
502 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
503 $pagelink = $matches[1];
506 // don't try and run feeds through the html5 parser
507 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
509 if(stristr($html,'<rss') || stristr($html,'<feed'))
515 return(fetch_xrd_links($pagelink));
517 // If we haven't found any links, return the host xrd links (which we have already fetched)
528 // Given a host name, locate the LRDD template from that
529 // host. Returns the LRDD template or an empty string on
532 if(! function_exists('fetch_lrdd_template')) {
533 function fetch_lrdd_template($host) {
536 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
537 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
538 $links = fetch_xrd_links($url1);
539 logger('fetch_lrdd_template from: ' . $url1);
540 logger('template (https): ' . print_r($links,true));
541 if(! count($links)) {
542 logger('fetch_lrdd_template from: ' . $url2);
543 $links = fetch_xrd_links($url2);
544 logger('template (http): ' . print_r($links,true));
547 foreach($links as $link)
548 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
549 $tpl = $link['@attributes']['template'];
551 if(! strpos($tpl,'{uri}'))
556 // Given a URL, retrieve the page as an XRD document.
557 // Return an array of links.
558 // on error/failure return empty array.
560 if(! function_exists('fetch_xrd_links')) {
561 function fetch_xrd_links($url) {
563 $xrd_timeout = intval(get_config('system','xrd_timeout'));
565 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
567 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
569 if ((! $xml) || (! stristr($xml,'<xrd')))
572 // fix diaspora's bad xml
573 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
575 $h = parse_xml_string($xml);
579 $arr = convert_xml_element_to_array($h);
583 if(isset($arr['xrd']['link'])) {
584 $link = $arr['xrd']['link'];
585 if(! isset($link[0]))
586 $links = array($link);
590 if(isset($arr['xrd']['alias'])) {
591 $alias = $arr['xrd']['alias'];
592 if(! isset($alias[0]))
593 $aliases = array($alias);
596 if(is_array($aliases) && count($aliases)) {
597 foreach($aliases as $alias) {
598 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
603 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
610 // Take a URL from the wild, prepend http:// if necessary
611 // and check DNS to see if it's real (or check if is a valid IP address)
612 // return true if it's OK, false if something is wrong with it
614 if(! function_exists('validate_url')) {
615 function validate_url(&$url) {
617 // no naked subdomains (allow localhost for tests)
618 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
620 if(substr($url,0,4) != 'http')
621 $url = 'http://' . $url;
622 $h = @parse_url($url);
624 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
630 // checks that email is an actual resolvable internet address
632 if(! function_exists('validate_email')) {
633 function validate_email($addr) {
635 if(get_config('system','disable_email_validation'))
638 if(! strpos($addr,'@'))
640 $h = substr($addr,strpos($addr,'@') + 1);
642 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
648 // Check $url against our list of allowed sites,
649 // wildcards allowed. If allowed_sites is unset return true;
650 // If url is allowed, return true.
651 // otherwise, return false
653 if(! function_exists('allowed_url')) {
654 function allowed_url($url) {
656 $h = @parse_url($url);
662 $str_allowed = get_config('system','allowed_sites');
668 $host = strtolower($h['host']);
670 // always allow our own site
672 if($host == strtolower($_SERVER['SERVER_NAME']))
675 $fnmatch = function_exists('fnmatch');
676 $allowed = explode(',',$str_allowed);
678 if(count($allowed)) {
679 foreach($allowed as $a) {
680 $pat = strtolower(trim($a));
681 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
690 // check if email address is allowed to register here.
691 // Compare against our list (wildcards allowed).
692 // Returns false if not allowed, true if allowed or if
693 // allowed list is not configured.
695 if(! function_exists('allowed_email')) {
696 function allowed_email($email) {
699 $domain = strtolower(substr($email,strpos($email,'@') + 1));
703 $str_allowed = get_config('system','allowed_email');
709 $fnmatch = function_exists('fnmatch');
710 $allowed = explode(',',$str_allowed);
712 if(count($allowed)) {
713 foreach($allowed as $a) {
714 $pat = strtolower(trim($a));
715 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
725 if(! function_exists('avatar_img')) {
726 function avatar_img($email) {
730 $avatar['size'] = 175;
731 $avatar['email'] = $email;
733 $avatar['success'] = false;
735 call_hooks('avatar_lookup', $avatar);
737 if(! $avatar['success'])
738 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
740 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
741 return $avatar['url'];
745 if(! function_exists('parse_xml_string')) {
746 function parse_xml_string($s,$strict = true) {
748 if(! strstr($s,'<?xml'))
750 $s2 = substr($s,strpos($s,'<?xml'));
754 libxml_use_internal_errors(true);
756 $x = @simplexml_load_string($s2);
758 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
759 foreach(libxml_get_errors() as $err)
760 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
761 libxml_clear_errors();
766 function add_fcontact($arr,$update = false) {
769 $r = q("UPDATE `fcontact` SET
782 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
784 dbesc($arr['photo']),
785 dbesc($arr['request']),
788 dbesc($arr['batch']),
789 dbesc($arr['notify']),
791 dbesc($arr['confirm']),
792 dbesc($arr['alias']),
793 dbesc($arr['pubkey']),
794 dbesc(datetime_convert()),
796 dbesc($arr['network'])
800 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
801 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
802 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
805 dbesc($arr['photo']),
806 dbesc($arr['request']),
809 dbesc($arr['batch']),
810 dbesc($arr['notify']),
812 dbesc($arr['confirm']),
813 dbesc($arr['network']),
814 dbesc($arr['alias']),
815 dbesc($arr['pubkey']),
816 dbesc(datetime_convert())
824 function scale_external_images($s, $include_link = true, $scale_replace = false) {
828 // Picture addresses can contain special characters
829 $s = htmlspecialchars_decode($s);
832 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
834 require_once('include/Photo.php');
835 foreach($matches as $mtch) {
836 logger('scale_external_image: ' . $mtch[1]);
838 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
839 if(stristr($mtch[1],$hostname))
842 // $scale_replace, if passed, is an array of two elements. The
843 // first is the name of the full-size image. The second is the
844 // name of a remote, scaled-down version of the full size image.
845 // This allows Friendica to display the smaller remote image if
846 // one exists, while still linking to the full-size image
848 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
851 $i = fetch_url($scaled);
853 $cachefile = get_cachefile(hash("md5", $scaled));
854 if ($cachefile != '')
855 file_put_contents($cachefile, $i);
857 // guess mimetype from headers or filename
858 $type = guess_image_type($mtch[1],true);
861 $ph = new Photo($i, $type);
862 if($ph->is_valid()) {
863 $orig_width = $ph->getWidth();
864 $orig_height = $ph->getHeight();
866 if($orig_width > 640 || $orig_height > 640) {
868 $ph->scaleImage(640);
869 $new_width = $ph->getWidth();
870 $new_height = $ph->getHeight();
871 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
872 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
873 . "\n" . (($include_link)
874 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
876 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
883 // replace the special char encoding
884 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
889 function fix_contact_ssl_policy(&$contact,$new_policy) {
891 $ssl_changed = false;
892 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
894 $contact['url'] = str_replace('https:','http:',$contact['url']);
895 $contact['request'] = str_replace('https:','http:',$contact['request']);
896 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
897 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
898 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
899 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
902 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
904 $contact['url'] = str_replace('http:','https:',$contact['url']);
905 $contact['request'] = str_replace('http:','https:',$contact['request']);
906 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
907 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
908 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
909 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
913 q("update contact set
920 where id = %d limit 1",
921 dbesc($contact['url']),
922 dbesc($contact['request']),
923 dbesc($contact['notify']),
924 dbesc($contact['poll']),
925 dbesc($contact['confirm']),
926 dbesc($contact['poco']),
927 intval($contact['id'])
935 * xml2array() will convert the given XML text to an array in the XML structure.
936 * Link: http://www.bin-co.com/php/scripts/xml2array/
937 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
938 * Arguments : $contents - The XML text
939 * $namespaces - true or false include namespace information in the returned array as array elements.
940 * $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.
941 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
942 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
943 * Examples: $array = xml2array(file_get_contents('feed.xml'));
944 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
947 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
948 if(!$contents) return array();
950 if(!function_exists('xml_parser_create')) {
951 logger('xml2array: parser function missing');
956 libxml_use_internal_errors(true);
957 libxml_clear_errors();
960 $parser = @xml_parser_create_ns("UTF-8",':');
962 $parser = @xml_parser_create();
965 logger('xml2array: xml_parser_create: no resource');
969 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
970 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
971 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
972 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
973 @xml_parse_into_struct($parser, trim($contents), $xml_values);
974 @xml_parser_free($parser);
977 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
978 foreach(libxml_get_errors() as $err)
979 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
980 libxml_clear_errors();
985 $xml_array = array();
987 $opened_tags = array();
990 $current = &$xml_array; // Reference
992 // Go through the tags.
993 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
994 foreach($xml_values as $data) {
995 unset($attributes,$value); // Remove existing values, or there will be trouble
997 // This command will extract these variables into the foreach scope
998 // tag(string), type(string), level(int), attributes(array).
999 extract($data); // We could use the array by itself, but this cooler.
1002 $attributes_data = array();
1005 if($priority == 'tag') $result = $value;
1006 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1009 //Set the attributes too.
1010 if(isset($attributes) and $get_attributes) {
1011 foreach($attributes as $attr => $val) {
1012 if($priority == 'tag') $attributes_data[$attr] = $val;
1013 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1017 // See tag status and do the needed.
1018 if($namespaces && strpos($tag,':')) {
1019 $namespc = substr($tag,0,strrpos($tag,':'));
1020 $tag = strtolower(substr($tag,strlen($namespc)+1));
1021 $result['@namespace'] = $namespc;
1023 $tag = strtolower($tag);
1025 if($type == "open") { // The starting of the tag '<tag>'
1026 $parent[$level-1] = &$current;
1027 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1028 $current[$tag] = $result;
1029 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1030 $repeated_tag_index[$tag.'_'.$level] = 1;
1032 $current = &$current[$tag];
1034 } else { // There was another element with the same tag name
1036 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1037 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1038 $repeated_tag_index[$tag.'_'.$level]++;
1039 } else { // This section will make the value an array if multiple tags with the same name appear together
1040 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1041 $repeated_tag_index[$tag.'_'.$level] = 2;
1043 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1044 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1045 unset($current[$tag.'_attr']);
1049 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1050 $current = &$current[$tag][$last_item_index];
1053 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1054 //See if the key is already taken.
1055 if(!isset($current[$tag])) { //New Key
1056 $current[$tag] = $result;
1057 $repeated_tag_index[$tag.'_'.$level] = 1;
1058 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1060 } else { // If taken, put all things inside a list(array)
1061 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1063 // ...push the new element into that array.
1064 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1066 if($priority == 'tag' and $get_attributes and $attributes_data) {
1067 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1069 $repeated_tag_index[$tag.'_'.$level]++;
1071 } else { // If it is not an array...
1072 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1073 $repeated_tag_index[$tag.'_'.$level] = 1;
1074 if($priority == 'tag' and $get_attributes) {
1075 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1077 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1078 unset($current[$tag.'_attr']);
1081 if($attributes_data) {
1082 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1085 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1089 } elseif($type == 'close') { // End of tag '</tag>'
1090 $current = &$parent[$level-1];