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 $a->save_timestamp($stamp1, "network");
112 // post request to $url. $params is an array of post variables.
114 if(! function_exists('post_url')) {
115 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
117 $stamp1 = microtime(true);
120 $ch = curl_init($url);
121 if(($redirects > 8) || (! $ch))
124 curl_setopt($ch, CURLOPT_HEADER, true);
125 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
126 curl_setopt($ch, CURLOPT_POST,1);
127 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
128 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
130 if(intval($timeout)) {
131 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
134 $curl_time = intval(get_config('system','curl_timeout'));
135 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
138 if(defined('LIGHTTPD')) {
139 if(!is_array($headers)) {
140 $headers = array('Expect:');
142 if(!in_array('Expect:', $headers)) {
143 array_push($headers, 'Expect:');
148 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
150 $check_cert = get_config('system','verifyssl');
151 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
152 $prx = get_config('system','proxy');
154 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
155 curl_setopt($ch, CURLOPT_PROXY, $prx);
156 $prxusr = get_config('system','proxyuser');
158 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
161 $a->set_curl_code(0);
163 // don't let curl abort the entire application
164 // if it throws any errors.
166 $s = @curl_exec($ch);
169 $curl_info = curl_getinfo($ch);
170 $http_code = $curl_info['http_code'];
174 // Pull out multiple headers, e.g. proxy and continuation headers
175 // allow for HTTP/2.x without fixing code
177 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
178 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
180 $base = substr($base,strlen($chunk));
183 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
185 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
186 $newurl = trim(array_pop($matches));
187 if(strpos($newurl,'/') === 0)
188 $newurl = $url . $newurl;
189 $url_parsed = @parse_url($newurl);
190 if (isset($url_parsed)) {
192 return fetch_url($newurl,false,$redirects,$timeout);
195 $a->set_curl_code($http_code);
196 $body = substr($s,strlen($header));
198 $a->set_curl_headers($header);
202 $a->save_timestamp($stamp1, "network");
207 // Generic XML return
208 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
209 // of $st and an optional text <message> of $message and terminates the current process.
211 if(! function_exists('xml_status')) {
212 function xml_status($st, $message = '') {
214 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
217 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
219 header( "Content-type: text/xml" );
220 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
221 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
226 if(! function_exists('http_status_exit')) {
227 function http_status_exit($val) {
232 if($val >= 200 && $val < 300)
235 logger('http_status_exit ' . $val);
236 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
242 // convert an XML document to a normalised, case-corrected array
245 if(! function_exists('convert_xml_element_to_array')) {
246 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
248 // If we're getting too deep, bail out
249 if ($recursion_depth > 512) {
253 if (!is_string($xml_element) &&
254 !is_array($xml_element) &&
255 (get_class($xml_element) == 'SimpleXMLElement')) {
256 $xml_element_copy = $xml_element;
257 $xml_element = get_object_vars($xml_element);
260 if (is_array($xml_element)) {
261 $result_array = array();
262 if (count($xml_element) <= 0) {
263 return (trim(strval($xml_element_copy)));
266 foreach($xml_element as $key=>$value) {
269 $result_array[strtolower($key)] =
270 convert_xml_element_to_array($value, $recursion_depth);
273 if ($recursion_depth == 0) {
274 $temp_array = $result_array;
275 $result_array = array(
276 strtolower($xml_element_copy->getName()) => $temp_array,
280 return ($result_array);
283 return (trim(strval($xml_element)));
287 // Given an email style address, perform webfinger lookup and
288 // return the resulting DFRN profile URL, or if no DFRN profile URL
289 // is located, returns an OStatus subscription template (prefixed
290 // with the string 'stat:' to identify it as on OStatus template).
291 // If this isn't an email style address just return $s.
292 // Return an empty string if email-style addresses but webfinger fails,
293 // or if the resultant personal XRD doesn't contain a supported
294 // subscription/friend-request attribute.
296 // amended 7/9/2011 to return an hcard which could save potentially loading
297 // a lengthy content page to scrape dfrn attributes
299 if(! function_exists('webfinger_dfrn')) {
300 function webfinger_dfrn($s,&$hcard) {
301 if(! strstr($s,'@')) {
306 $links = webfinger($s);
307 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
309 foreach($links as $link) {
310 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
311 $profile_link = $link['@attributes']['href'];
312 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
313 $profile_link = 'stat:' . $link['@attributes']['template'];
314 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
315 $hcard = $link['@attributes']['href'];
318 return $profile_link;
321 // Given an email style address, perform webfinger lookup and
322 // return the array of link attributes from the personal XRD file.
323 // On error/failure return an empty array.
326 if(! function_exists('webfinger')) {
327 function webfinger($s, $debug = false) {
330 $host = substr($s,strpos($s,'@') + 1);
333 $tpl = fetch_lrdd_template($host);
334 logger('webfinger: lrdd template: ' . $tpl);
336 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
337 logger('webfinger: pxrd: ' . $pxrd);
338 $links = fetch_xrd_links($pxrd);
339 if(! count($links)) {
340 // try with double slashes
341 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
342 logger('webfinger: pxrd: ' . $pxrd);
343 $links = fetch_xrd_links($pxrd);
351 if(! function_exists('lrdd')) {
352 function lrdd($uri, $debug = false) {
356 // default priority is host priority, host-meta first
360 // All we have is an email address. Resource-priority is irrelevant
361 // because our URI isn't directly resolvable.
363 if(strstr($uri,'@')) {
364 return(webfinger($uri));
367 // get the host meta file
369 $host = @parse_url($uri);
372 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
373 $url .= $host['host'] . '/.well-known/host-meta' ;
378 logger('lrdd: constructed url: ' . $url);
380 $xml = fetch_url($url);
382 $headers = $a->get_curl_headers();
387 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
389 if(! stristr($xml,'<xrd'))
392 $h = parse_xml_string($xml);
396 $arr = convert_xml_element_to_array($h);
398 if(isset($arr['xrd']['property'])) {
399 $property = $arr['crd']['property'];
400 if(! isset($property[0]))
401 $properties = array($property);
403 $properties = $property;
404 foreach($properties as $prop)
405 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
406 $priority = 'resource';
409 // save the links in case we need them
413 if(isset($arr['xrd']['link'])) {
414 $link = $arr['xrd']['link'];
415 if(! isset($link[0]))
416 $links = array($link);
421 // do we have a template or href?
424 foreach($links as $link) {
425 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
426 if(x($link['@attributes'],'template'))
427 $tpl = $link['@attributes']['template'];
428 elseif(x($link['@attributes'],'href'))
429 $href = $link['@attributes']['href'];
434 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
437 if($priority === 'host') {
439 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
443 logger('lrdd: (host priority) pxrd: ' . $pxrd);
444 $links = fetch_xrd_links($pxrd);
448 $lines = explode("\n",$headers);
450 foreach($lines as $line) {
451 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
452 return(fetch_xrd_links($matches[1]));
460 // priority 'resource'
463 $html = fetch_url($uri);
464 $headers = $a->get_curl_headers();
465 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
467 // don't try and parse raw xml as html
468 if(! strstr($html,'<?xml')) {
469 require_once('library/HTML5/Parser.php');
472 $dom = HTML5_Parser::parse($html);
473 } catch (DOMException $e) {
474 logger('lrdd: parse error: ' . $e);
477 if(isset($dom) && $dom) {
478 $items = $dom->getElementsByTagName('link');
479 foreach($items as $item) {
480 $x = $item->getAttribute('rel');
482 $pagelink = $item->getAttribute('href');
490 return(fetch_xrd_links($pagelink));
492 // next look in HTTP headers
494 $lines = explode("\n",$headers);
496 foreach($lines as $line) {
497 // TODO alter the following regex to support multiple relations (space separated)
498 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
499 $pagelink = $matches[1];
502 // don't try and run feeds through the html5 parser
503 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
505 if(stristr($html,'<rss') || stristr($html,'<feed'))
511 return(fetch_xrd_links($pagelink));
513 // If we haven't found any links, return the host xrd links (which we have already fetched)
524 // Given a host name, locate the LRDD template from that
525 // host. Returns the LRDD template or an empty string on
528 if(! function_exists('fetch_lrdd_template')) {
529 function fetch_lrdd_template($host) {
532 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
533 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
534 $links = fetch_xrd_links($url1);
535 logger('fetch_lrdd_template from: ' . $url1);
536 logger('template (https): ' . print_r($links,true));
537 if(! count($links)) {
538 logger('fetch_lrdd_template from: ' . $url2);
539 $links = fetch_xrd_links($url2);
540 logger('template (http): ' . print_r($links,true));
543 foreach($links as $link)
544 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
545 $tpl = $link['@attributes']['template'];
547 if(! strpos($tpl,'{uri}'))
552 // Given a URL, retrieve the page as an XRD document.
553 // Return an array of links.
554 // on error/failure return empty array.
556 if(! function_exists('fetch_xrd_links')) {
557 function fetch_xrd_links($url) {
559 $xrd_timeout = intval(get_config('system','xrd_timeout'));
561 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
563 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
565 if ((! $xml) || (! stristr($xml,'<xrd')))
568 // fix diaspora's bad xml
569 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
571 $h = parse_xml_string($xml);
575 $arr = convert_xml_element_to_array($h);
579 if(isset($arr['xrd']['link'])) {
580 $link = $arr['xrd']['link'];
581 if(! isset($link[0]))
582 $links = array($link);
586 if(isset($arr['xrd']['alias'])) {
587 $alias = $arr['xrd']['alias'];
588 if(! isset($alias[0]))
589 $aliases = array($alias);
592 if(is_array($aliases) && count($aliases)) {
593 foreach($aliases as $alias) {
594 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
599 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
606 // Take a URL from the wild, prepend http:// if necessary
607 // and check DNS to see if it's real (or check if is a valid IP address)
608 // return true if it's OK, false if something is wrong with it
610 if(! function_exists('validate_url')) {
611 function validate_url(&$url) {
613 // no naked subdomains (allow localhost for tests)
614 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
616 if(substr($url,0,4) != 'http')
617 $url = 'http://' . $url;
618 $h = @parse_url($url);
620 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
626 // checks that email is an actual resolvable internet address
628 if(! function_exists('validate_email')) {
629 function validate_email($addr) {
631 if(get_config('system','disable_email_validation'))
634 if(! strpos($addr,'@'))
636 $h = substr($addr,strpos($addr,'@') + 1);
638 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
644 // Check $url against our list of allowed sites,
645 // wildcards allowed. If allowed_sites is unset return true;
646 // If url is allowed, return true.
647 // otherwise, return false
649 if(! function_exists('allowed_url')) {
650 function allowed_url($url) {
652 $h = @parse_url($url);
658 $str_allowed = get_config('system','allowed_sites');
664 $host = strtolower($h['host']);
666 // always allow our own site
668 if($host == strtolower($_SERVER['SERVER_NAME']))
671 $fnmatch = function_exists('fnmatch');
672 $allowed = explode(',',$str_allowed);
674 if(count($allowed)) {
675 foreach($allowed as $a) {
676 $pat = strtolower(trim($a));
677 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
686 // check if email address is allowed to register here.
687 // Compare against our list (wildcards allowed).
688 // Returns false if not allowed, true if allowed or if
689 // allowed list is not configured.
691 if(! function_exists('allowed_email')) {
692 function allowed_email($email) {
695 $domain = strtolower(substr($email,strpos($email,'@') + 1));
699 $str_allowed = get_config('system','allowed_email');
705 $fnmatch = function_exists('fnmatch');
706 $allowed = explode(',',$str_allowed);
708 if(count($allowed)) {
709 foreach($allowed as $a) {
710 $pat = strtolower(trim($a));
711 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
721 if(! function_exists('avatar_img')) {
722 function avatar_img($email) {
726 $avatar['size'] = 175;
727 $avatar['email'] = $email;
729 $avatar['success'] = false;
731 call_hooks('avatar_lookup', $avatar);
733 if(! $avatar['success'])
734 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
736 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
737 return $avatar['url'];
741 if(! function_exists('parse_xml_string')) {
742 function parse_xml_string($s,$strict = true) {
744 if(! strstr($s,'<?xml'))
746 $s2 = substr($s,strpos($s,'<?xml'));
750 libxml_use_internal_errors(true);
752 $x = @simplexml_load_string($s2);
754 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
755 foreach(libxml_get_errors() as $err)
756 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
757 libxml_clear_errors();
762 function add_fcontact($arr,$update = false) {
765 $r = q("UPDATE `fcontact` SET
778 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
780 dbesc($arr['photo']),
781 dbesc($arr['request']),
784 dbesc($arr['batch']),
785 dbesc($arr['notify']),
787 dbesc($arr['confirm']),
788 dbesc($arr['alias']),
789 dbesc($arr['pubkey']),
790 dbesc(datetime_convert()),
792 dbesc($arr['network'])
796 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
797 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
798 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
801 dbesc($arr['photo']),
802 dbesc($arr['request']),
805 dbesc($arr['batch']),
806 dbesc($arr['notify']),
808 dbesc($arr['confirm']),
809 dbesc($arr['network']),
810 dbesc($arr['alias']),
811 dbesc($arr['pubkey']),
812 dbesc(datetime_convert())
820 function scale_external_images($s, $include_link = true, $scale_replace = false) {
824 // Picture addresses can contain special characters
825 $s = htmlspecialchars_decode($s);
828 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
830 require_once('include/Photo.php');
831 foreach($matches as $mtch) {
832 logger('scale_external_image: ' . $mtch[1]);
834 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
835 if(stristr($mtch[1],$hostname))
838 // $scale_replace, if passed, is an array of two elements. The
839 // first is the name of the full-size image. The second is the
840 // name of a remote, scaled-down version of the full size image.
841 // This allows Friendica to display the smaller remote image if
842 // one exists, while still linking to the full-size image
844 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
847 $i = fetch_url($scaled);
849 $cachefile = get_cachefile(hash("md5", $scaled));
850 if ($cachefile != '') {
851 $stamp1 = microtime(true);
852 file_put_contents($cachefile, $i);
853 $a->save_timestamp($stamp1, "file");
856 // guess mimetype from headers or filename
857 $type = guess_image_type($mtch[1],true);
860 $ph = new Photo($i, $type);
861 if($ph->is_valid()) {
862 $orig_width = $ph->getWidth();
863 $orig_height = $ph->getHeight();
865 if($orig_width > 640 || $orig_height > 640) {
867 $ph->scaleImage(640);
868 $new_width = $ph->getWidth();
869 $new_height = $ph->getHeight();
870 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
871 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
872 . "\n" . (($include_link)
873 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
875 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
882 // replace the special char encoding
883 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
888 function fix_contact_ssl_policy(&$contact,$new_policy) {
890 $ssl_changed = false;
891 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
893 $contact['url'] = str_replace('https:','http:',$contact['url']);
894 $contact['request'] = str_replace('https:','http:',$contact['request']);
895 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
896 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
897 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
898 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
901 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
903 $contact['url'] = str_replace('http:','https:',$contact['url']);
904 $contact['request'] = str_replace('http:','https:',$contact['request']);
905 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
906 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
907 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
908 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
912 q("update contact set
919 where id = %d limit 1",
920 dbesc($contact['url']),
921 dbesc($contact['request']),
922 dbesc($contact['notify']),
923 dbesc($contact['poll']),
924 dbesc($contact['confirm']),
925 dbesc($contact['poco']),
926 intval($contact['id'])
934 * xml2array() will convert the given XML text to an array in the XML structure.
935 * Link: http://www.bin-co.com/php/scripts/xml2array/
936 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
937 * Arguments : $contents - The XML text
938 * $namespaces - true or false include namespace information in the returned array as array elements.
939 * $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.
940 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
941 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
942 * Examples: $array = xml2array(file_get_contents('feed.xml'));
943 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
946 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
947 if(!$contents) return array();
949 if(!function_exists('xml_parser_create')) {
950 logger('xml2array: parser function missing');
955 libxml_use_internal_errors(true);
956 libxml_clear_errors();
959 $parser = @xml_parser_create_ns("UTF-8",':');
961 $parser = @xml_parser_create();
964 logger('xml2array: xml_parser_create: no resource');
968 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
969 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
970 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
971 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
972 @xml_parse_into_struct($parser, trim($contents), $xml_values);
973 @xml_parser_free($parser);
976 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
977 foreach(libxml_get_errors() as $err)
978 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
979 libxml_clear_errors();
984 $xml_array = array();
986 $opened_tags = array();
989 $current = &$xml_array; // Reference
991 // Go through the tags.
992 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
993 foreach($xml_values as $data) {
994 unset($attributes,$value); // Remove existing values, or there will be trouble
996 // This command will extract these variables into the foreach scope
997 // tag(string), type(string), level(int), attributes(array).
998 extract($data); // We could use the array by itself, but this cooler.
1001 $attributes_data = array();
1004 if($priority == 'tag') $result = $value;
1005 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1008 //Set the attributes too.
1009 if(isset($attributes) and $get_attributes) {
1010 foreach($attributes as $attr => $val) {
1011 if($priority == 'tag') $attributes_data[$attr] = $val;
1012 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1016 // See tag status and do the needed.
1017 if($namespaces && strpos($tag,':')) {
1018 $namespc = substr($tag,0,strrpos($tag,':'));
1019 $tag = strtolower(substr($tag,strlen($namespc)+1));
1020 $result['@namespace'] = $namespc;
1022 $tag = strtolower($tag);
1024 if($type == "open") { // The starting of the tag '<tag>'
1025 $parent[$level-1] = &$current;
1026 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1027 $current[$tag] = $result;
1028 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1029 $repeated_tag_index[$tag.'_'.$level] = 1;
1031 $current = &$current[$tag];
1033 } else { // There was another element with the same tag name
1035 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1036 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1037 $repeated_tag_index[$tag.'_'.$level]++;
1038 } else { // This section will make the value an array if multiple tags with the same name appear together
1039 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1040 $repeated_tag_index[$tag.'_'.$level] = 2;
1042 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1043 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1044 unset($current[$tag.'_attr']);
1048 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1049 $current = &$current[$tag][$last_item_index];
1052 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1053 //See if the key is already taken.
1054 if(!isset($current[$tag])) { //New Key
1055 $current[$tag] = $result;
1056 $repeated_tag_index[$tag.'_'.$level] = 1;
1057 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1059 } else { // If taken, put all things inside a list(array)
1060 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1062 // ...push the new element into that array.
1063 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1065 if($priority == 'tag' and $get_attributes and $attributes_data) {
1066 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1068 $repeated_tag_index[$tag.'_'.$level]++;
1070 } else { // If it is not an array...
1071 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1072 $repeated_tag_index[$tag.'_'.$level] = 1;
1073 if($priority == 'tag' and $get_attributes) {
1074 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1076 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1077 unset($current[$tag.'_attr']);
1080 if($attributes_data) {
1081 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1084 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1088 } elseif($type == 'close') { // End of tag '</tag>'
1089 $current = &$parent[$level-1];