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);
21 // These settings aren't needed. We're following the location already.
22 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
23 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
25 if (!is_null($accept_content)){
26 curl_setopt($ch,CURLOPT_HTTPHEADER, array (
27 "Accept: " . $accept_content
31 @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
32 //@curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
33 @curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Friendica)");
36 if(intval($timeout)) {
37 @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
40 $curl_time = intval(get_config('system','curl_timeout'));
41 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
43 // by default we will allow self-signed certs
44 // but you can override this
46 $check_cert = get_config('system','verifyssl');
47 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
49 $prx = get_config('system','proxy');
51 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
52 @curl_setopt($ch, CURLOPT_PROXY, $prx);
53 $prxusr = @get_config('system','proxyuser');
55 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
58 @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
62 // don't let curl abort the entire application
63 // if it throws any errors.
68 $curl_info = @curl_getinfo($ch);
69 $http_code = $curl_info['http_code'];
70 // logger('fetch_url:' . $http_code . ' data: ' . $s);
73 // Pull out multiple headers, e.g. proxy and continuation headers
74 // allow for HTTP/2.x without fixing code
76 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
77 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
79 $base = substr($base,strlen($chunk));
82 if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
83 $new_location_info = @parse_url($curl_info["redirect_url"]);
84 $old_location_info = @parse_url($curl_info["url"]);
86 $newurl = $curl_info["redirect_url"];
88 if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
89 $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
92 if (preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches)) {
93 $newurl = trim(array_pop($matches));
95 if(strpos($newurl,'/') === 0)
96 $newurl = $url . $newurl;
97 $url_parsed = @parse_url($newurl);
98 if (isset($url_parsed)) {
100 return fetch_url($newurl,$binary,$redirects,$timeout);
104 $a->set_curl_code($http_code);
106 $body = substr($s,strlen($header));
107 $a->set_curl_headers($header);
110 $a->save_timestamp($stamp1, "network");
115 // post request to $url. $params is an array of post variables.
117 if(! function_exists('post_url')) {
118 function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
120 $stamp1 = microtime(true);
123 $ch = curl_init($url);
124 if(($redirects > 8) || (! $ch))
127 curl_setopt($ch, CURLOPT_HEADER, true);
128 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
129 curl_setopt($ch, CURLOPT_POST,1);
130 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
131 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
133 if(intval($timeout)) {
134 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
137 $curl_time = intval(get_config('system','curl_timeout'));
138 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
141 if(defined('LIGHTTPD')) {
142 if(!is_array($headers)) {
143 $headers = array('Expect:');
145 if(!in_array('Expect:', $headers)) {
146 array_push($headers, 'Expect:');
151 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
153 $check_cert = get_config('system','verifyssl');
154 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
155 $prx = get_config('system','proxy');
157 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
158 curl_setopt($ch, CURLOPT_PROXY, $prx);
159 $prxusr = get_config('system','proxyuser');
161 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
164 $a->set_curl_code(0);
166 // don't let curl abort the entire application
167 // if it throws any errors.
169 $s = @curl_exec($ch);
172 $curl_info = curl_getinfo($ch);
173 $http_code = $curl_info['http_code'];
177 // Pull out multiple headers, e.g. proxy and continuation headers
178 // allow for HTTP/2.x without fixing code
180 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
181 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
183 $base = substr($base,strlen($chunk));
186 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
188 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
189 $newurl = trim(array_pop($matches));
190 if(strpos($newurl,'/') === 0)
191 $newurl = $url . $newurl;
192 $url_parsed = @parse_url($newurl);
193 if (isset($url_parsed)) {
195 return fetch_url($newurl,false,$redirects,$timeout);
198 $a->set_curl_code($http_code);
199 $body = substr($s,strlen($header));
201 $a->set_curl_headers($header);
205 $a->save_timestamp($stamp1, "network");
210 // Generic XML return
211 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
212 // of $st and an optional text <message> of $message and terminates the current process.
214 if(! function_exists('xml_status')) {
215 function xml_status($st, $message = '') {
217 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
220 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
222 header( "Content-type: text/xml" );
223 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
224 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
229 if(! function_exists('http_status_exit')) {
230 function http_status_exit($val) {
235 if($val >= 200 && $val < 300)
238 logger('http_status_exit ' . $val);
239 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
245 // convert an XML document to a normalised, case-corrected array
248 if(! function_exists('convert_xml_element_to_array')) {
249 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
251 // If we're getting too deep, bail out
252 if ($recursion_depth > 512) {
256 if (!is_string($xml_element) &&
257 !is_array($xml_element) &&
258 (get_class($xml_element) == 'SimpleXMLElement')) {
259 $xml_element_copy = $xml_element;
260 $xml_element = get_object_vars($xml_element);
263 if (is_array($xml_element)) {
264 $result_array = array();
265 if (count($xml_element) <= 0) {
266 return (trim(strval($xml_element_copy)));
269 foreach($xml_element as $key=>$value) {
272 $result_array[strtolower($key)] =
273 convert_xml_element_to_array($value, $recursion_depth);
276 if ($recursion_depth == 0) {
277 $temp_array = $result_array;
278 $result_array = array(
279 strtolower($xml_element_copy->getName()) => $temp_array,
283 return ($result_array);
286 return (trim(strval($xml_element)));
290 // Given an email style address, perform webfinger lookup and
291 // return the resulting DFRN profile URL, or if no DFRN profile URL
292 // is located, returns an OStatus subscription template (prefixed
293 // with the string 'stat:' to identify it as on OStatus template).
294 // If this isn't an email style address just return $s.
295 // Return an empty string if email-style addresses but webfinger fails,
296 // or if the resultant personal XRD doesn't contain a supported
297 // subscription/friend-request attribute.
299 // amended 7/9/2011 to return an hcard which could save potentially loading
300 // a lengthy content page to scrape dfrn attributes
302 if(! function_exists('webfinger_dfrn')) {
303 function webfinger_dfrn($s,&$hcard) {
304 if(! strstr($s,'@')) {
309 $links = webfinger($s);
310 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
312 foreach($links as $link) {
313 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
314 $profile_link = $link['@attributes']['href'];
315 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
316 $profile_link = 'stat:' . $link['@attributes']['template'];
317 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
318 $hcard = $link['@attributes']['href'];
321 return $profile_link;
324 // Given an email style address, perform webfinger lookup and
325 // return the array of link attributes from the personal XRD file.
326 // On error/failure return an empty array.
329 if(! function_exists('webfinger')) {
330 function webfinger($s, $debug = false) {
333 $host = substr($s,strpos($s,'@') + 1);
336 $tpl = fetch_lrdd_template($host);
337 logger('webfinger: lrdd template: ' . $tpl);
339 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
340 logger('webfinger: pxrd: ' . $pxrd);
341 $links = fetch_xrd_links($pxrd);
342 if(! count($links)) {
343 // try with double slashes
344 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
345 logger('webfinger: pxrd: ' . $pxrd);
346 $links = fetch_xrd_links($pxrd);
354 if(! function_exists('lrdd')) {
355 function lrdd($uri, $debug = false) {
359 // default priority is host priority, host-meta first
363 // All we have is an email address. Resource-priority is irrelevant
364 // because our URI isn't directly resolvable.
366 if(strstr($uri,'@')) {
367 return(webfinger($uri));
370 // get the host meta file
372 $host = @parse_url($uri);
375 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
376 $url .= $host['host'] . '/.well-known/host-meta' ;
381 logger('lrdd: constructed url: ' . $url);
383 $xml = fetch_url($url);
385 $headers = $a->get_curl_headers();
390 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
392 if(! stristr($xml,'<xrd'))
395 $h = parse_xml_string($xml);
399 $arr = convert_xml_element_to_array($h);
401 if(isset($arr['xrd']['property'])) {
402 $property = $arr['crd']['property'];
403 if(! isset($property[0]))
404 $properties = array($property);
406 $properties = $property;
407 foreach($properties as $prop)
408 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
409 $priority = 'resource';
412 // save the links in case we need them
416 if(isset($arr['xrd']['link'])) {
417 $link = $arr['xrd']['link'];
418 if(! isset($link[0]))
419 $links = array($link);
424 // do we have a template or href?
427 foreach($links as $link) {
428 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
429 if(x($link['@attributes'],'template'))
430 $tpl = $link['@attributes']['template'];
431 elseif(x($link['@attributes'],'href'))
432 $href = $link['@attributes']['href'];
437 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
440 if($priority === 'host') {
442 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
446 logger('lrdd: (host priority) pxrd: ' . $pxrd);
447 $links = fetch_xrd_links($pxrd);
451 $lines = explode("\n",$headers);
453 foreach($lines as $line) {
454 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
455 return(fetch_xrd_links($matches[1]));
463 // priority 'resource'
466 $html = fetch_url($uri);
467 $headers = $a->get_curl_headers();
468 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
470 // don't try and parse raw xml as html
471 if(! strstr($html,'<?xml')) {
472 require_once('library/HTML5/Parser.php');
475 $dom = HTML5_Parser::parse($html);
476 } catch (DOMException $e) {
477 logger('lrdd: parse error: ' . $e);
480 if(isset($dom) && $dom) {
481 $items = $dom->getElementsByTagName('link');
482 foreach($items as $item) {
483 $x = $item->getAttribute('rel');
485 $pagelink = $item->getAttribute('href');
493 return(fetch_xrd_links($pagelink));
495 // next look in HTTP headers
497 $lines = explode("\n",$headers);
499 foreach($lines as $line) {
500 // TODO alter the following regex to support multiple relations (space separated)
501 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
502 $pagelink = $matches[1];
505 // don't try and run feeds through the html5 parser
506 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
508 if(stristr($html,'<rss') || stristr($html,'<feed'))
514 return(fetch_xrd_links($pagelink));
516 // If we haven't found any links, return the host xrd links (which we have already fetched)
527 // Given a host name, locate the LRDD template from that
528 // host. Returns the LRDD template or an empty string on
531 if(! function_exists('fetch_lrdd_template')) {
532 function fetch_lrdd_template($host) {
535 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
536 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
537 $links = fetch_xrd_links($url1);
538 logger('fetch_lrdd_template from: ' . $url1);
539 logger('template (https): ' . print_r($links,true));
540 if(! count($links)) {
541 logger('fetch_lrdd_template from: ' . $url2);
542 $links = fetch_xrd_links($url2);
543 logger('template (http): ' . print_r($links,true));
546 foreach($links as $link)
547 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
548 $tpl = $link['@attributes']['template'];
550 if(! strpos($tpl,'{uri}'))
555 // Given a URL, retrieve the page as an XRD document.
556 // Return an array of links.
557 // on error/failure return empty array.
559 if(! function_exists('fetch_xrd_links')) {
560 function fetch_xrd_links($url) {
562 $xrd_timeout = intval(get_config('system','xrd_timeout'));
564 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20));
566 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
568 if ((! $xml) || (! stristr($xml,'<xrd')))
571 // fix diaspora's bad xml
572 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
574 $h = parse_xml_string($xml);
578 $arr = convert_xml_element_to_array($h);
582 if(isset($arr['xrd']['link'])) {
583 $link = $arr['xrd']['link'];
584 if(! isset($link[0]))
585 $links = array($link);
589 if(isset($arr['xrd']['alias'])) {
590 $alias = $arr['xrd']['alias'];
591 if(! isset($alias[0]))
592 $aliases = array($alias);
595 if(is_array($aliases) && count($aliases)) {
596 foreach($aliases as $alias) {
597 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
602 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
609 // Take a URL from the wild, prepend http:// if necessary
610 // and check DNS to see if it's real (or check if is a valid IP address)
611 // return true if it's OK, false if something is wrong with it
613 if(! function_exists('validate_url')) {
614 function validate_url(&$url) {
616 // no naked subdomains (allow localhost for tests)
617 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
619 if(substr($url,0,4) != 'http')
620 $url = 'http://' . $url;
621 $h = @parse_url($url);
623 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
629 // checks that email is an actual resolvable internet address
631 if(! function_exists('validate_email')) {
632 function validate_email($addr) {
634 if(get_config('system','disable_email_validation'))
637 if(! strpos($addr,'@'))
639 $h = substr($addr,strpos($addr,'@') + 1);
641 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
647 // Check $url against our list of allowed sites,
648 // wildcards allowed. If allowed_sites is unset return true;
649 // If url is allowed, return true.
650 // otherwise, return false
652 if(! function_exists('allowed_url')) {
653 function allowed_url($url) {
655 $h = @parse_url($url);
661 $str_allowed = get_config('system','allowed_sites');
667 $host = strtolower($h['host']);
669 // always allow our own site
671 if($host == strtolower($_SERVER['SERVER_NAME']))
674 $fnmatch = function_exists('fnmatch');
675 $allowed = explode(',',$str_allowed);
677 if(count($allowed)) {
678 foreach($allowed as $a) {
679 $pat = strtolower(trim($a));
680 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
689 // check if email address is allowed to register here.
690 // Compare against our list (wildcards allowed).
691 // Returns false if not allowed, true if allowed or if
692 // allowed list is not configured.
694 if(! function_exists('allowed_email')) {
695 function allowed_email($email) {
698 $domain = strtolower(substr($email,strpos($email,'@') + 1));
702 $str_allowed = get_config('system','allowed_email');
708 $fnmatch = function_exists('fnmatch');
709 $allowed = explode(',',$str_allowed);
711 if(count($allowed)) {
712 foreach($allowed as $a) {
713 $pat = strtolower(trim($a));
714 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
724 if(! function_exists('avatar_img')) {
725 function avatar_img($email) {
729 $avatar['size'] = 175;
730 $avatar['email'] = $email;
732 $avatar['success'] = false;
734 call_hooks('avatar_lookup', $avatar);
736 if(! $avatar['success'])
737 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
739 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
740 return $avatar['url'];
744 if(! function_exists('parse_xml_string')) {
745 function parse_xml_string($s,$strict = true) {
747 if(! strstr($s,'<?xml'))
749 $s2 = substr($s,strpos($s,'<?xml'));
753 libxml_use_internal_errors(true);
755 $x = @simplexml_load_string($s2);
757 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
758 foreach(libxml_get_errors() as $err)
759 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
760 libxml_clear_errors();
765 function add_fcontact($arr,$update = false) {
768 $r = q("UPDATE `fcontact` SET
781 WHERE `url` = '%s' AND `network` = '%s' LIMIT 1",
783 dbesc($arr['photo']),
784 dbesc($arr['request']),
787 dbesc($arr['batch']),
788 dbesc($arr['notify']),
790 dbesc($arr['confirm']),
791 dbesc($arr['alias']),
792 dbesc($arr['pubkey']),
793 dbesc(datetime_convert()),
795 dbesc($arr['network'])
799 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
800 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
801 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
804 dbesc($arr['photo']),
805 dbesc($arr['request']),
808 dbesc($arr['batch']),
809 dbesc($arr['notify']),
811 dbesc($arr['confirm']),
812 dbesc($arr['network']),
813 dbesc($arr['alias']),
814 dbesc($arr['pubkey']),
815 dbesc(datetime_convert())
823 function scale_external_images($s, $include_link = true, $scale_replace = false) {
827 // Picture addresses can contain special characters
828 $s = htmlspecialchars_decode($s);
831 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
833 require_once('include/Photo.php');
834 foreach($matches as $mtch) {
835 logger('scale_external_image: ' . $mtch[1]);
837 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
838 if(stristr($mtch[1],$hostname))
841 // $scale_replace, if passed, is an array of two elements. The
842 // first is the name of the full-size image. The second is the
843 // name of a remote, scaled-down version of the full size image.
844 // This allows Friendica to display the smaller remote image if
845 // one exists, while still linking to the full-size image
847 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
850 $i = fetch_url($scaled);
852 $cachefile = get_cachefile(hash("md5", $scaled));
853 if ($cachefile != '') {
854 $stamp1 = microtime(true);
855 file_put_contents($cachefile, $i);
856 $a->save_timestamp($stamp1, "file");
859 // guess mimetype from headers or filename
860 $type = guess_image_type($mtch[1],true);
863 $ph = new Photo($i, $type);
864 if($ph->is_valid()) {
865 $orig_width = $ph->getWidth();
866 $orig_height = $ph->getHeight();
868 if($orig_width > 640 || $orig_height > 640) {
870 $ph->scaleImage(640);
871 $new_width = $ph->getWidth();
872 $new_height = $ph->getHeight();
873 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
874 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
875 . "\n" . (($include_link)
876 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
878 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
885 // replace the special char encoding
886 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
891 function fix_contact_ssl_policy(&$contact,$new_policy) {
893 $ssl_changed = false;
894 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
896 $contact['url'] = str_replace('https:','http:',$contact['url']);
897 $contact['request'] = str_replace('https:','http:',$contact['request']);
898 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
899 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
900 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
901 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
904 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
906 $contact['url'] = str_replace('http:','https:',$contact['url']);
907 $contact['request'] = str_replace('http:','https:',$contact['request']);
908 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
909 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
910 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
911 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
915 q("update contact set
922 where id = %d limit 1",
923 dbesc($contact['url']),
924 dbesc($contact['request']),
925 dbesc($contact['notify']),
926 dbesc($contact['poll']),
927 dbesc($contact['confirm']),
928 dbesc($contact['poco']),
929 intval($contact['id'])
937 * xml2array() will convert the given XML text to an array in the XML structure.
938 * Link: http://www.bin-co.com/php/scripts/xml2array/
939 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
940 * Arguments : $contents - The XML text
941 * $namespaces - true or false include namespace information in the returned array as array elements.
942 * $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.
943 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
944 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
945 * Examples: $array = xml2array(file_get_contents('feed.xml'));
946 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
949 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
950 if(!$contents) return array();
952 if(!function_exists('xml_parser_create')) {
953 logger('xml2array: parser function missing');
958 libxml_use_internal_errors(true);
959 libxml_clear_errors();
962 $parser = @xml_parser_create_ns("UTF-8",':');
964 $parser = @xml_parser_create();
967 logger('xml2array: xml_parser_create: no resource');
971 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
972 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
973 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
974 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
975 @xml_parse_into_struct($parser, trim($contents), $xml_values);
976 @xml_parser_free($parser);
979 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
980 foreach(libxml_get_errors() as $err)
981 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
982 libxml_clear_errors();
987 $xml_array = array();
989 $opened_tags = array();
992 $current = &$xml_array; // Reference
994 // Go through the tags.
995 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
996 foreach($xml_values as $data) {
997 unset($attributes,$value); // Remove existing values, or there will be trouble
999 // This command will extract these variables into the foreach scope
1000 // tag(string), type(string), level(int), attributes(array).
1001 extract($data); // We could use the array by itself, but this cooler.
1004 $attributes_data = array();
1007 if($priority == 'tag') $result = $value;
1008 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1011 //Set the attributes too.
1012 if(isset($attributes) and $get_attributes) {
1013 foreach($attributes as $attr => $val) {
1014 if($priority == 'tag') $attributes_data[$attr] = $val;
1015 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1019 // See tag status and do the needed.
1020 if($namespaces && strpos($tag,':')) {
1021 $namespc = substr($tag,0,strrpos($tag,':'));
1022 $tag = strtolower(substr($tag,strlen($namespc)+1));
1023 $result['@namespace'] = $namespc;
1025 $tag = strtolower($tag);
1027 if($type == "open") { // The starting of the tag '<tag>'
1028 $parent[$level-1] = &$current;
1029 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1030 $current[$tag] = $result;
1031 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1032 $repeated_tag_index[$tag.'_'.$level] = 1;
1034 $current = &$current[$tag];
1036 } else { // There was another element with the same tag name
1038 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1039 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1040 $repeated_tag_index[$tag.'_'.$level]++;
1041 } else { // This section will make the value an array if multiple tags with the same name appear together
1042 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1043 $repeated_tag_index[$tag.'_'.$level] = 2;
1045 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1046 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1047 unset($current[$tag.'_attr']);
1051 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1052 $current = &$current[$tag][$last_item_index];
1055 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1056 //See if the key is already taken.
1057 if(!isset($current[$tag])) { //New Key
1058 $current[$tag] = $result;
1059 $repeated_tag_index[$tag.'_'.$level] = 1;
1060 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1062 } else { // If taken, put all things inside a list(array)
1063 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1065 // ...push the new element into that array.
1066 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1068 if($priority == 'tag' and $get_attributes and $attributes_data) {
1069 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1071 $repeated_tag_index[$tag.'_'.$level]++;
1073 } else { // If it is not an array...
1074 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1075 $repeated_tag_index[$tag.'_'.$level] = 1;
1076 if($priority == 'tag' and $get_attributes) {
1077 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1079 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1080 unset($current[$tag.'_attr']);
1083 if($attributes_data) {
1084 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1087 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1091 } elseif($type == 'close') { // End of tag '</tag>'
1092 $current = &$parent[$level-1];