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) {
126 $stamp1 = microtime(true);
129 $ch = curl_init($url);
130 if(($redirects > 8) || (! $ch))
133 curl_setopt($ch, CURLOPT_HEADER, true);
134 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
135 curl_setopt($ch, CURLOPT_POST,1);
136 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
137 curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
139 if(intval($timeout)) {
140 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
143 $curl_time = intval(get_config('system','curl_timeout'));
144 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
147 if(defined('LIGHTTPD')) {
148 if(!is_array($headers)) {
149 $headers = array('Expect:');
151 if(!in_array('Expect:', $headers)) {
152 array_push($headers, 'Expect:');
157 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
159 $check_cert = get_config('system','verifyssl');
160 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
161 $prx = get_config('system','proxy');
163 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
164 curl_setopt($ch, CURLOPT_PROXY, $prx);
165 $prxusr = get_config('system','proxyuser');
167 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
170 $a->set_curl_code(0);
172 // don't let curl abort the entire application
173 // if it throws any errors.
175 $s = @curl_exec($ch);
178 $curl_info = curl_getinfo($ch);
179 $http_code = $curl_info['http_code'];
183 // Pull out multiple headers, e.g. proxy and continuation headers
184 // allow for HTTP/2.x without fixing code
186 while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
187 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
189 $base = substr($base,strlen($chunk));
192 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
194 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
195 $newurl = trim(array_pop($matches));
196 if(strpos($newurl,'/') === 0)
197 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
198 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
200 return fetch_url($newurl,false,$redirects,$timeout);
203 $a->set_curl_code($http_code);
204 $body = substr($s,strlen($header));
206 $a->set_curl_headers($header);
210 $a->save_timestamp($stamp1, "network");
215 // Generic XML return
216 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
217 // of $st and an optional text <message> of $message and terminates the current process.
219 if(! function_exists('xml_status')) {
220 function xml_status($st, $message = '') {
222 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
225 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
227 header( "Content-type: text/xml" );
228 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
229 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
234 if(! function_exists('http_status_exit')) {
235 function http_status_exit($val) {
240 if($val >= 200 && $val < 300)
243 logger('http_status_exit ' . $val);
244 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
250 // convert an XML document to a normalised, case-corrected array
253 if(! function_exists('convert_xml_element_to_array')) {
254 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
256 // If we're getting too deep, bail out
257 if ($recursion_depth > 512) {
261 if (!is_string($xml_element) &&
262 !is_array($xml_element) &&
263 (get_class($xml_element) == 'SimpleXMLElement')) {
264 $xml_element_copy = $xml_element;
265 $xml_element = get_object_vars($xml_element);
268 if (is_array($xml_element)) {
269 $result_array = array();
270 if (count($xml_element) <= 0) {
271 return (trim(strval($xml_element_copy)));
274 foreach($xml_element as $key=>$value) {
277 $result_array[strtolower($key)] =
278 convert_xml_element_to_array($value, $recursion_depth);
281 if ($recursion_depth == 0) {
282 $temp_array = $result_array;
283 $result_array = array(
284 strtolower($xml_element_copy->getName()) => $temp_array,
288 return ($result_array);
291 return (trim(strval($xml_element)));
295 // Given an email style address, perform webfinger lookup and
296 // return the resulting DFRN profile URL, or if no DFRN profile URL
297 // is located, returns an OStatus subscription template (prefixed
298 // with the string 'stat:' to identify it as on OStatus template).
299 // If this isn't an email style address just return $s.
300 // Return an empty string if email-style addresses but webfinger fails,
301 // or if the resultant personal XRD doesn't contain a supported
302 // subscription/friend-request attribute.
304 // amended 7/9/2011 to return an hcard which could save potentially loading
305 // a lengthy content page to scrape dfrn attributes
307 if(! function_exists('webfinger_dfrn')) {
308 function webfinger_dfrn($s,&$hcard) {
309 if(! strstr($s,'@')) {
314 $links = webfinger($s);
315 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
317 foreach($links as $link) {
318 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
319 $profile_link = $link['@attributes']['href'];
320 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
321 $profile_link = 'stat:' . $link['@attributes']['template'];
322 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
323 $hcard = $link['@attributes']['href'];
326 return $profile_link;
329 // Given an email style address, perform webfinger lookup and
330 // return the array of link attributes from the personal XRD file.
331 // On error/failure return an empty array.
334 if(! function_exists('webfinger')) {
335 function webfinger($s, $debug = false) {
338 $host = substr($s,strpos($s,'@') + 1);
341 $tpl = fetch_lrdd_template($host);
342 logger('webfinger: lrdd template: ' . $tpl);
344 $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
345 logger('webfinger: pxrd: ' . $pxrd);
346 $links = fetch_xrd_links($pxrd);
347 if(! count($links)) {
348 // try with double slashes
349 $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
350 logger('webfinger: pxrd: ' . $pxrd);
351 $links = fetch_xrd_links($pxrd);
359 if(! function_exists('lrdd')) {
360 function lrdd($uri, $debug = false) {
364 // default priority is host priority, host-meta first
368 // All we have is an email address. Resource-priority is irrelevant
369 // because our URI isn't directly resolvable.
371 if(strstr($uri,'@')) {
372 return(webfinger($uri));
375 // get the host meta file
377 $host = @parse_url($uri);
380 $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
381 $url .= $host['host'] . '/.well-known/host-meta' ;
386 logger('lrdd: constructed url: ' . $url);
388 $xml = fetch_url($url);
390 $headers = $a->get_curl_headers();
395 logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
397 if(! stristr($xml,'<xrd'))
400 $h = parse_xml_string($xml);
404 $arr = convert_xml_element_to_array($h);
406 if(isset($arr['xrd']['property'])) {
407 $property = $arr['crd']['property'];
408 if(! isset($property[0]))
409 $properties = array($property);
411 $properties = $property;
412 foreach($properties as $prop)
413 if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
414 $priority = 'resource';
417 // save the links in case we need them
421 if(isset($arr['xrd']['link'])) {
422 $link = $arr['xrd']['link'];
423 if(! isset($link[0]))
424 $links = array($link);
429 // do we have a template or href?
432 foreach($links as $link) {
433 if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
434 if(x($link['@attributes'],'template'))
435 $tpl = $link['@attributes']['template'];
436 elseif(x($link['@attributes'],'href'))
437 $href = $link['@attributes']['href'];
442 if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
445 if($priority === 'host') {
447 $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
451 logger('lrdd: (host priority) pxrd: ' . $pxrd);
452 $links = fetch_xrd_links($pxrd);
456 $lines = explode("\n",$headers);
458 foreach($lines as $line) {
459 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
460 return(fetch_xrd_links($matches[1]));
468 // priority 'resource'
471 $html = fetch_url($uri);
472 $headers = $a->get_curl_headers();
473 logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
475 // don't try and parse raw xml as html
476 if(! strstr($html,'<?xml')) {
477 require_once('library/HTML5/Parser.php');
480 $dom = HTML5_Parser::parse($html);
481 } catch (DOMException $e) {
482 logger('lrdd: parse error: ' . $e);
485 if(isset($dom) && $dom) {
486 $items = $dom->getElementsByTagName('link');
487 foreach($items as $item) {
488 $x = $item->getAttribute('rel');
490 $pagelink = $item->getAttribute('href');
498 return(fetch_xrd_links($pagelink));
500 // next look in HTTP headers
502 $lines = explode("\n",$headers);
504 foreach($lines as $line) {
505 // TODO alter the following regex to support multiple relations (space separated)
506 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
507 $pagelink = $matches[1];
510 // don't try and run feeds through the html5 parser
511 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
513 if(stristr($html,'<rss') || stristr($html,'<feed'))
519 return(fetch_xrd_links($pagelink));
521 // If we haven't found any links, return the host xrd links (which we have already fetched)
532 // Given a host name, locate the LRDD template from that
533 // host. Returns the LRDD template or an empty string on
536 if(! function_exists('fetch_lrdd_template')) {
537 function fetch_lrdd_template($host) {
540 $url1 = 'https://' . $host . '/.well-known/host-meta' ;
541 $url2 = 'http://' . $host . '/.well-known/host-meta' ;
542 $links = fetch_xrd_links($url1);
543 logger('fetch_lrdd_template from: ' . $url1);
544 logger('template (https): ' . print_r($links,true));
545 if(! count($links)) {
546 logger('fetch_lrdd_template from: ' . $url2);
547 $links = fetch_xrd_links($url2);
548 logger('template (http): ' . print_r($links,true));
551 foreach($links as $link)
552 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
553 $tpl = $link['@attributes']['template'];
555 if(! strpos($tpl,'{uri}'))
560 // Given a URL, retrieve the page as an XRD document.
561 // Return an array of links.
562 // on error/failure return empty array.
564 if(! function_exists('fetch_xrd_links')) {
565 function fetch_xrd_links($url) {
567 $xrd_timeout = intval(get_config('system','xrd_timeout'));
569 $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
571 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
573 if ((! $xml) || (! stristr($xml,'<xrd')))
576 // fix diaspora's bad xml
577 $xml = str_replace(array('href="','"/>'),array('href="','"/>'),$xml);
579 $h = parse_xml_string($xml);
583 $arr = convert_xml_element_to_array($h);
587 if(isset($arr['xrd']['link'])) {
588 $link = $arr['xrd']['link'];
589 if(! isset($link[0]))
590 $links = array($link);
594 if(isset($arr['xrd']['alias'])) {
595 $alias = $arr['xrd']['alias'];
596 if(! isset($alias[0]))
597 $aliases = array($alias);
600 if(is_array($aliases) && count($aliases)) {
601 foreach($aliases as $alias) {
602 $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
607 logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
614 // Take a URL from the wild, prepend http:// if necessary
615 // and check DNS to see if it's real (or check if is a valid IP address)
616 // return true if it's OK, false if something is wrong with it
618 if(! function_exists('validate_url')) {
619 function validate_url(&$url) {
621 // no naked subdomains (allow localhost for tests)
622 if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
624 if(substr($url,0,4) != 'http')
625 $url = 'http://' . $url;
626 $h = @parse_url($url);
628 if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
634 // checks that email is an actual resolvable internet address
636 if(! function_exists('validate_email')) {
637 function validate_email($addr) {
639 if(get_config('system','disable_email_validation'))
642 if(! strpos($addr,'@'))
644 $h = substr($addr,strpos($addr,'@') + 1);
646 if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
652 // Check $url against our list of allowed sites,
653 // wildcards allowed. If allowed_sites is unset return true;
654 // If url is allowed, return true.
655 // otherwise, return false
657 if(! function_exists('allowed_url')) {
658 function allowed_url($url) {
660 $h = @parse_url($url);
666 $str_allowed = get_config('system','allowed_sites');
672 $host = strtolower($h['host']);
674 // always allow our own site
676 if($host == strtolower($_SERVER['SERVER_NAME']))
679 $fnmatch = function_exists('fnmatch');
680 $allowed = explode(',',$str_allowed);
682 if(count($allowed)) {
683 foreach($allowed as $a) {
684 $pat = strtolower(trim($a));
685 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
694 // check if email address is allowed to register here.
695 // Compare against our list (wildcards allowed).
696 // Returns false if not allowed, true if allowed or if
697 // allowed list is not configured.
699 if(! function_exists('allowed_email')) {
700 function allowed_email($email) {
703 $domain = strtolower(substr($email,strpos($email,'@') + 1));
707 $str_allowed = get_config('system','allowed_email');
713 $fnmatch = function_exists('fnmatch');
714 $allowed = explode(',',$str_allowed);
716 if(count($allowed)) {
717 foreach($allowed as $a) {
718 $pat = strtolower(trim($a));
719 if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
729 if(! function_exists('avatar_img')) {
730 function avatar_img($email) {
734 $avatar['size'] = 175;
735 $avatar['email'] = $email;
737 $avatar['success'] = false;
739 call_hooks('avatar_lookup', $avatar);
741 if(! $avatar['success'])
742 $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
744 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
745 return $avatar['url'];
749 if(! function_exists('parse_xml_string')) {
750 function parse_xml_string($s,$strict = true) {
752 if(! strstr($s,'<?xml'))
754 $s2 = substr($s,strpos($s,'<?xml'));
758 libxml_use_internal_errors(true);
760 $x = @simplexml_load_string($s2);
762 logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
763 foreach(libxml_get_errors() as $err)
764 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
765 libxml_clear_errors();
770 function add_fcontact($arr,$update = false) {
773 $r = q("UPDATE `fcontact` SET
786 WHERE `url` = '%s' AND `network` = '%s'",
788 dbesc($arr['photo']),
789 dbesc($arr['request']),
792 dbesc($arr['batch']),
793 dbesc($arr['notify']),
795 dbesc($arr['confirm']),
796 dbesc($arr['alias']),
797 dbesc($arr['pubkey']),
798 dbesc(datetime_convert()),
800 dbesc($arr['network'])
804 $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
805 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
806 values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
809 dbesc($arr['photo']),
810 dbesc($arr['request']),
813 dbesc($arr['batch']),
814 dbesc($arr['notify']),
816 dbesc($arr['confirm']),
817 dbesc($arr['network']),
818 dbesc($arr['alias']),
819 dbesc($arr['pubkey']),
820 dbesc(datetime_convert())
828 function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
832 // Picture addresses can contain special characters
833 $s = htmlspecialchars_decode($srctext);
836 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
838 require_once('include/Photo.php');
839 foreach($matches as $mtch) {
840 logger('scale_external_image: ' . $mtch[1]);
842 $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
843 if(stristr($mtch[1],$hostname))
846 // $scale_replace, if passed, is an array of two elements. The
847 // first is the name of the full-size image. The second is the
848 // name of a remote, scaled-down version of the full size image.
849 // This allows Friendica to display the smaller remote image if
850 // one exists, while still linking to the full-size image
852 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
855 $i = @fetch_url($scaled);
859 $cachefile = get_cachefile(hash("md5", $scaled));
860 if ($cachefile != '') {
861 $stamp1 = microtime(true);
862 file_put_contents($cachefile, $i);
863 $a->save_timestamp($stamp1, "file");
866 // guess mimetype from headers or filename
867 $type = guess_image_type($mtch[1],true);
870 $ph = new Photo($i, $type);
871 if($ph->is_valid()) {
872 $orig_width = $ph->getWidth();
873 $orig_height = $ph->getHeight();
875 if($orig_width > 640 || $orig_height > 640) {
877 $ph->scaleImage(640);
878 $new_width = $ph->getWidth();
879 $new_height = $ph->getHeight();
880 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
881 $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
882 . "\n" . (($include_link)
883 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
885 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
892 // replace the special char encoding
893 $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
898 function fix_contact_ssl_policy(&$contact,$new_policy) {
900 $ssl_changed = false;
901 if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
903 $contact['url'] = str_replace('https:','http:',$contact['url']);
904 $contact['request'] = str_replace('https:','http:',$contact['request']);
905 $contact['notify'] = str_replace('https:','http:',$contact['notify']);
906 $contact['poll'] = str_replace('https:','http:',$contact['poll']);
907 $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
908 $contact['poco'] = str_replace('https:','http:',$contact['poco']);
911 if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
913 $contact['url'] = str_replace('http:','https:',$contact['url']);
914 $contact['request'] = str_replace('http:','https:',$contact['request']);
915 $contact['notify'] = str_replace('http:','https:',$contact['notify']);
916 $contact['poll'] = str_replace('http:','https:',$contact['poll']);
917 $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
918 $contact['poco'] = str_replace('http:','https:',$contact['poco']);
922 q("update contact set
929 where id = %d limit 1",
930 dbesc($contact['url']),
931 dbesc($contact['request']),
932 dbesc($contact['notify']),
933 dbesc($contact['poll']),
934 dbesc($contact['confirm']),
935 dbesc($contact['poco']),
936 intval($contact['id'])
944 * xml2array() will convert the given XML text to an array in the XML structure.
945 * Link: http://www.bin-co.com/php/scripts/xml2array/
946 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
947 * Arguments : $contents - The XML text
948 * $namespaces - true or false include namespace information in the returned array as array elements.
949 * $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.
950 * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
951 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
952 * Examples: $array = xml2array(file_get_contents('feed.xml'));
953 * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
956 function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
957 if(!$contents) return array();
959 if(!function_exists('xml_parser_create')) {
960 logger('xml2array: parser function missing');
965 libxml_use_internal_errors(true);
966 libxml_clear_errors();
969 $parser = @xml_parser_create_ns("UTF-8",':');
971 $parser = @xml_parser_create();
974 logger('xml2array: xml_parser_create: no resource');
978 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
979 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
980 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
981 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
982 @xml_parse_into_struct($parser, trim($contents), $xml_values);
983 @xml_parser_free($parser);
986 logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
987 foreach(libxml_get_errors() as $err)
988 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
989 libxml_clear_errors();
994 $xml_array = array();
996 $opened_tags = array();
999 $current = &$xml_array; // Reference
1001 // Go through the tags.
1002 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
1003 foreach($xml_values as $data) {
1004 unset($attributes,$value); // Remove existing values, or there will be trouble
1006 // This command will extract these variables into the foreach scope
1007 // tag(string), type(string), level(int), attributes(array).
1008 extract($data); // We could use the array by itself, but this cooler.
1011 $attributes_data = array();
1014 if($priority == 'tag') $result = $value;
1015 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
1018 //Set the attributes too.
1019 if(isset($attributes) and $get_attributes) {
1020 foreach($attributes as $attr => $val) {
1021 if($priority == 'tag') $attributes_data[$attr] = $val;
1022 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
1026 // See tag status and do the needed.
1027 if($namespaces && strpos($tag,':')) {
1028 $namespc = substr($tag,0,strrpos($tag,':'));
1029 $tag = strtolower(substr($tag,strlen($namespc)+1));
1030 $result['@namespace'] = $namespc;
1032 $tag = strtolower($tag);
1034 if($type == "open") { // The starting of the tag '<tag>'
1035 $parent[$level-1] = &$current;
1036 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
1037 $current[$tag] = $result;
1038 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
1039 $repeated_tag_index[$tag.'_'.$level] = 1;
1041 $current = &$current[$tag];
1043 } else { // There was another element with the same tag name
1045 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
1046 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1047 $repeated_tag_index[$tag.'_'.$level]++;
1048 } else { // This section will make the value an array if multiple tags with the same name appear together
1049 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
1050 $repeated_tag_index[$tag.'_'.$level] = 2;
1052 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1053 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1054 unset($current[$tag.'_attr']);
1058 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
1059 $current = &$current[$tag][$last_item_index];
1062 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
1063 //See if the key is already taken.
1064 if(!isset($current[$tag])) { //New Key
1065 $current[$tag] = $result;
1066 $repeated_tag_index[$tag.'_'.$level] = 1;
1067 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
1069 } else { // If taken, put all things inside a list(array)
1070 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
1072 // ...push the new element into that array.
1073 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
1075 if($priority == 'tag' and $get_attributes and $attributes_data) {
1076 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1078 $repeated_tag_index[$tag.'_'.$level]++;
1080 } else { // If it is not an array...
1081 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
1082 $repeated_tag_index[$tag.'_'.$level] = 1;
1083 if($priority == 'tag' and $get_attributes) {
1084 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
1086 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
1087 unset($current[$tag.'_attr']);
1090 if($attributes_data) {
1091 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
1094 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
1098 } elseif($type == 'close') { // End of tag '</tag>'
1099 $current = &$parent[$level-1];