3 require_once('library/HTML5/Parser.php');
4 require_once('include/crypto.php');
5 require_once('include/feed.php');
7 if(! function_exists('scrape_dfrn')) {
8 function scrape_dfrn($url, $dont_probe = false) {
14 logger('scrape_dfrn: url=' . $url);
22 $probe = probe_url($url);
24 if (isset($probe["addr"]))
25 $ret["addr"] = $probe["addr"];
28 $headers = $a->get_curl_headers();
29 logger('scrape_dfrn: headers=' . $headers, LOGGER_DEBUG);
32 $lines = explode("\n",$headers);
34 foreach($lines as $line) {
35 // don't try and run feeds through the html5 parser
36 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
42 $dom = HTML5_Parser::parse($s);
43 } catch (DOMException $e) {
44 logger('scrape_dfrn: parse error: ' . $e);
50 $items = $dom->getElementsByTagName('link');
52 // get DFRN link elements
54 foreach($items as $item) {
55 $x = $item->getAttribute('rel');
56 if(($x === 'alternate') && ($item->getAttribute('type') === 'application/atom+xml'))
57 $ret['feed_atom'] = $item->getAttribute('href');
58 if(substr($x,0,5) == "dfrn-") {
59 $ret[$x] = $item->getAttribute('href');
62 $decoded = urldecode($item->getAttribute('href'));
63 if(preg_match('/acct:([^@]*)@/',$decoded,$matches))
64 $ret['nick'] = $matches[1];
68 // Pull out hCard profile elements
72 $items = $dom->getElementsByTagName('*');
73 foreach($items as $item) {
74 if(attribute_contains($item->getAttribute('class'), 'vcard')) {
75 $level2 = $item->getElementsByTagName('*');
76 foreach($level2 as $x) {
77 if(attribute_contains($x->getAttribute('class'),'fn')) {
78 $ret['fn'] = $x->textContent;
80 if((attribute_contains($x->getAttribute('class'),'photo'))
81 || (attribute_contains($x->getAttribute('class'),'avatar'))) {
82 $size = intval($x->getAttribute('width'));
83 // dfrn prefers 175, so if we find this, we set largest_size so it can't be topped.
84 if(($size > $largest_photo) || ($size == 175) || (! $largest_photo)) {
85 $ret['photo'] = $x->getAttribute('src');
86 $largest_photo = (($size == 175) ? 9999 : $size);
89 if(attribute_contains($x->getAttribute('class'),'key')) {
90 $ret['key'] = $x->textContent;
104 if(! function_exists('validate_dfrn')) {
105 function validate_dfrn($a) {
109 if(! x($a,'dfrn-request'))
111 if(! x($a,'dfrn-confirm'))
113 if(! x($a,'dfrn-notify'))
115 if(! x($a,'dfrn-poll'))
120 if(! function_exists('scrape_meta')) {
121 function scrape_meta($url) {
127 logger('scrape_meta: url=' . $url);
129 $s = fetch_url($url);
134 $headers = $a->get_curl_headers();
135 logger('scrape_meta: headers=' . $headers, LOGGER_DEBUG);
137 $lines = explode("\n",$headers);
139 foreach($lines as $line) {
140 // don't try and run feeds through the html5 parser
141 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
147 $dom = HTML5_Parser::parse($s);
148 } catch (DOMException $e) {
149 logger('scrape_meta: parse error: ' . $e);
155 $items = $dom->getElementsByTagName('meta');
157 // get DFRN link elements
159 foreach($items as $item) {
160 $x = $item->getAttribute('name');
161 if(substr($x,0,5) == "dfrn-")
162 $ret[$x] = $item->getAttribute('content');
169 if(! function_exists('scrape_vcard')) {
170 function scrape_vcard($url) {
176 logger('scrape_vcard: url=' . $url);
178 $s = fetch_url($url);
183 $headers = $a->get_curl_headers();
184 $lines = explode("\n",$headers);
186 foreach($lines as $line) {
187 // don't try and run feeds through the html5 parser
188 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
194 $dom = HTML5_Parser::parse($s);
195 } catch (DOMException $e) {
196 logger('scrape_vcard: parse error: ' . $e);
202 // Pull out hCard profile elements
206 $items = $dom->getElementsByTagName('*');
207 foreach($items as $item) {
208 if(attribute_contains($item->getAttribute('class'), 'vcard')) {
209 $level2 = $item->getElementsByTagName('*');
210 foreach($level2 as $x) {
211 if(attribute_contains($x->getAttribute('class'),'fn'))
212 $ret['fn'] = $x->textContent;
213 if((attribute_contains($x->getAttribute('class'),'photo'))
214 || (attribute_contains($x->getAttribute('class'),'avatar'))) {
215 $size = intval($x->getAttribute('width'));
216 if(($size > $largest_photo) || (! $largest_photo)) {
217 $ret['photo'] = $x->getAttribute('src');
218 $largest_photo = $size;
221 if((attribute_contains($x->getAttribute('class'),'nickname'))
222 || (attribute_contains($x->getAttribute('class'),'uid'))) {
223 $ret['nick'] = $x->textContent;
233 if(! function_exists('scrape_feed')) {
234 function scrape_feed($url) {
239 $cookiejar = tempnam(get_temppath(), 'cookiejar-scrape-feed-');
240 $s = fetch_url($url, false, $redirects, 0, Null, $cookiejar);
243 $headers = $a->get_curl_headers();
244 $code = $a->get_curl_code();
246 logger('scrape_feed: returns: ' . $code . ' headers=' . $headers, LOGGER_DEBUG);
249 logger('scrape_feed: no data returned for ' . $url);
254 $lines = explode("\n",$headers);
256 foreach($lines as $line) {
257 if(stristr($line,'content-type:')) {
258 if(stristr($line,'application/atom+xml') || stristr($s,'<feed')) {
259 $ret['feed_atom'] = $url;
262 if(stristr($line,'application/rss+xml') || stristr($s,'<rss')) {
263 $ret['feed_rss'] = $url;
268 // perhaps an RSS version 1 feed with a generic or incorrect content-type?
269 if(stristr($s,'</item>')) {
270 $ret['feed_rss'] = $url;
275 $basename = implode('/', array_slice(explode('/',$url),0,3)) . '/';
277 $doc = new DOMDocument();
279 $xpath = new DomXPath($doc);
281 $base = $xpath->query("//base");
282 foreach ($base as $node) {
285 if ($node->attributes->length)
286 foreach ($node->attributes as $attribute)
287 $attr[$attribute->name] = $attribute->value;
289 if ($attr["href"] != "")
290 $basename = $attr["href"] ;
293 $list = $xpath->query("//link");
294 foreach ($list as $node) {
297 if ($node->attributes->length)
298 foreach ($node->attributes as $attribute)
299 $attr[$attribute->name] = $attribute->value;
301 if (($attr["rel"] == "alternate") AND ($attr["type"] == "application/atom+xml"))
302 $ret["feed_atom"] = $attr["href"];
304 if (($attr["rel"] == "alternate") AND ($attr["type"] == "application/rss+xml"))
305 $ret["feed_rss"] = $attr["href"];
308 // Drupal and perhaps others only provide relative URLs. Turn them into absolute.
310 if(x($ret,'feed_atom') && (! strstr($ret['feed_atom'],'://')))
311 $ret['feed_atom'] = $basename . $ret['feed_atom'];
312 if(x($ret,'feed_rss') && (! strstr($ret['feed_rss'],'://')))
313 $ret['feed_rss'] = $basename . $ret['feed_rss'];
321 * Probe a network address to discover what kind of protocols we need to communicate with it.
323 * Warning: this function is a bit touchy and there are some subtle dependencies within the logic flow.
330 * PROBE_DIASPORA has a bias towards returning Diaspora information
331 * while PROBE_NORMAL has a bias towards dfrn/zot - in the case where
332 * an address (such as a Friendica address) supports more than one type
338 define ( 'PROBE_NORMAL', 0);
339 define ( 'PROBE_DIASPORA', 1);
341 function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
342 require_once('include/email.php');
349 $result = Cache::get("probe_url:".$mode.":".$url);
350 if (!is_null($result)) {
351 $result = unserialize($result);
361 $email_conversant = false;
362 $connectornetworks = false;
365 if (strpos($url,'twitter.com')) {
366 $connectornetworks = true;
367 $network = NETWORK_TWITTER;
370 $lastfm = ((strpos($url,'last.fm/user') !== false) ? true : false);
372 $at_addr = ((strpos($url,'@') !== false) ? true : false);
374 if((!$appnet) && (!$lastfm) && !$connectornetworks) {
376 if(strpos($url,'mailto:') !== false && $at_addr) {
377 $url = str_replace('mailto:','',$url);
386 logger('probe_url: found lrdd links: ' . print_r($links,true), LOGGER_DATA);
387 foreach($links as $link) {
388 if($link['@attributes']['rel'] === NAMESPACE_ZOT)
389 $zot = unamp($link['@attributes']['href']);
390 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
391 $dfrn = unamp($link['@attributes']['href']);
392 if($link['@attributes']['rel'] === 'salmon')
393 $notify = unamp($link['@attributes']['href']);
394 if($link['@attributes']['rel'] === NAMESPACE_FEED)
395 $poll = unamp($link['@attributes']['href']);
396 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
397 $hcard = unamp($link['@attributes']['href']);
398 if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
399 $profile = unamp($link['@attributes']['href']);
400 if($link['@attributes']['rel'] === 'http://portablecontacts.net/spec/1.0')
401 $poco = unamp($link['@attributes']['href']);
402 if($link['@attributes']['rel'] === 'http://joindiaspora.com/seed_location') {
403 $diaspora_base = unamp($link['@attributes']['href']);
406 if($link['@attributes']['rel'] === 'http://joindiaspora.com/guid') {
407 $diaspora_guid = unamp($link['@attributes']['href']);
410 if($link['@attributes']['rel'] === 'diaspora-public-key') {
411 $diaspora_key = base64_decode(unamp($link['@attributes']['href']));
412 if(strstr($diaspora_key,'RSA '))
413 $pubkey = rsatopem($diaspora_key);
415 $pubkey = $diaspora_key;
418 if(($link['@attributes']['rel'] === 'http://ostatus.org/schema/1.0/subscribe') AND ($mode == PROBE_NORMAL)) {
423 // Status.Net can have more than one profile URL. We need to match the profile URL
424 // to a contact on incoming messages to prevent spam, and we won't know which one
425 // to match. So in case of two, one of them is stored as an alias. Only store URL's
426 // and not webfinger user@host aliases. If they've got more than two non-email style
427 // aliases, let's hope we're lucky and get one that matches the feed author-uri because
428 // otherwise we're screwed.
430 foreach($links as $link) {
431 if($link['@attributes']['rel'] === 'alias') {
432 if(strpos($link['@attributes']['href'],'@') === false) {
433 if(isset($profile)) {
434 if($link['@attributes']['href'] !== $profile)
435 $alias = unamp($link['@attributes']['href']);
438 $profile = unamp($link['@attributes']['href']);
443 // If the profile is different from the url then the url is abviously an alias
444 if (($alias == "") AND ($profile != "") AND !$at_addr AND (normalise_link($profile) != normalise_link($url)))
447 elseif($mode == PROBE_NORMAL) {
452 if((strpos($orig_url,'@')) && validate_email($orig_url)) {
453 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
456 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
459 if(count($x) && count($r)) {
460 $mailbox = construct_mailbox_name($r[0]);
462 openssl_private_decrypt(hex2bin($r[0]['pass']),$password,$x[0]['prvkey']);
463 $mbox = email_connect($mailbox,$r[0]['user'],$password);
465 logger('probe_url: email_connect failed.');
469 $msgs = email_poll($mbox,$orig_url);
470 logger('probe_url: searching ' . $orig_url . ', ' . count($msgs) . ' messages found.', LOGGER_DEBUG);
473 $network = NETWORK_MAIL;
474 $name = substr($url,0,strpos($url,'@'));
475 $phost = substr($url,strpos($url,'@')+1);
476 $profile = 'http://' . $phost;
477 // fix nick character range
478 $vcard = array('fn' => $name, 'nick' => $name, 'photo' => avatar_img($url));
479 $notify = 'smtp ' . random_string();
480 $poll = 'email ' . random_string();
482 $x = email_msg_meta($mbox,$msgs[0]);
483 if(stristr($x[0]->from,$orig_url))
484 $adr = imap_rfc822_parse_adrlist($x[0]->from,'');
485 elseif(stristr($x[0]->to,$orig_url))
486 $adr = imap_rfc822_parse_adrlist($x[0]->to,'');
488 foreach($adr as $feadr) {
489 if((strcasecmp($feadr->mailbox,$name) == 0)
490 &&(strcasecmp($feadr->host,$phost) == 0)
491 && (strlen($feadr->personal))) {
493 $personal = imap_mime_header_decode($feadr->personal);
495 foreach($personal as $perspart)
496 if ($perspart->charset != "default")
497 $vcard['fn'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
499 $vcard['fn'] .= $perspart->text;
501 $vcard['fn'] = notags($vcard['fn']);
512 if($mode == PROBE_NORMAL) {
515 $s = fetch_url($zot);
517 $j = json_decode($s);
519 $network = NETWORK_ZOT;
521 'fn' => $j->fullname,
522 'nick' => $j->nickname,
527 $pubkey = $j->pubkey;
535 $ret = scrape_dfrn(($hcard) ? $hcard : $dfrn, true);
536 if(is_array($ret) && x($ret,'dfrn-request')) {
537 $network = NETWORK_DFRN;
538 $request = $ret['dfrn-request'];
539 $confirm = $ret['dfrn-confirm'];
540 $notify = $ret['dfrn-notify'];
541 $poll = $ret['dfrn-poll'];
544 $vcard['fn'] = $ret['fn'];
545 $vcard['nick'] = $ret['nick'];
546 $vcard['photo'] = $ret['photo'];
551 // Scrape the public key from the hcard.
552 // Diaspora will remove it from the webfinger somewhere in the future.
553 if (($hcard != "") AND ($pubkey == "")) {
554 $ret = scrape_dfrn(($hcard) ? $hcard : $dfrn, true);
555 if (isset($ret["key"])) {
556 $hcard_key = $ret["key"];
557 if(strstr($hcard_key,'RSA '))
558 $pubkey = rsatopem($hcard_key);
560 $pubkey = $hcard_key;
563 if($diaspora && $diaspora_base && $diaspora_guid) {
564 $diaspora_notify = $diaspora_base.'receive/users/'.$diaspora_guid;
566 if($mode == PROBE_DIASPORA || ! $notify || ($notify == $diaspora_notify)) {
567 $notify = $diaspora_notify;
568 $batch = $diaspora_base . 'receive/public' ;
571 $addr = str_replace('acct:', '', $url);
574 if($network !== NETWORK_ZOT && $network !== NETWORK_DFRN && $network !== NETWORK_MAIL) {
576 $network = NETWORK_DIASPORA;
577 elseif($has_lrdd AND ($notify))
578 $network = NETWORK_OSTATUS;
581 $addr = str_replace('acct:', '', $url);
585 if($hcard && ! $vcard) {
586 $vcard = scrape_vcard($hcard);
588 // Google doesn't use absolute url in profile photos
590 if((x($vcard,'photo')) && substr($vcard['photo'],0,1) == '/') {
591 $h = @parse_url($hcard);
593 $vcard['photo'] = $h['scheme'] . '://' . $h['host'] . $vcard['photo'];
596 logger('probe_url: scrape_vcard: ' . print_r($vcard,true), LOGGER_DATA);
599 if($diaspora && $addr) {
600 // Diaspora returns the name as the nick. As the nick will never be updated,
601 // let's use the Diaspora nickname (the first part of the handle) as the nick instead
602 $addr_parts = explode('@', $addr);
603 $vcard['nick'] = $addr_parts[0];
608 $poll = str_replace(array('www.','last.fm/'),array('','ws.audioscrobbler.com/1.0/'),$url) . '/recenttracks.rss';
609 $vcard['nick'] = basename($url);
610 $vcard['fn'] = $vcard['nick'] . t(' on Last.fm');
611 $network = NETWORK_FEED;
616 $vcard['fn'] = $vcard['nick'];
620 if(stristr($url,'tumblr.com') && (! stristr($url,'/rss'))) {
621 $poll = $url . '/rss';
623 // Will leave it to others to figure out how to grab the avatar, which is on the $url page in the open graph meta links
626 if($appnet || ! $poll)
628 if((! isset($vcard)) || (! x($vcard,'fn')) || (! $profile))
630 if(($at_addr) && (! count($links)))
633 if ($connectornetworks)
638 $feedret = scrape_feed(($poll) ? $poll : $url);
640 logger('probe_url: scrape_feed ' . (($poll)? $poll : $url) . ' returns: ' . print_r($feedret,true), LOGGER_DATA);
641 if(count($feedret) && ($feedret['feed_atom'] || $feedret['feed_rss'])) {
642 $poll = ((x($feedret,'feed_atom')) ? unamp($feedret['feed_atom']) : unamp($feedret['feed_rss']));
647 if(x($feedret,'photo') && (! x($vcard,'photo')))
648 $vcard['photo'] = $feedret['photo'];
650 $cookiejar = tempnam(get_temppath(), 'cookiejar-scrape-feed-');
651 $xml = fetch_url($poll, false, $redirects, 0, Null, $cookiejar);
654 logger('probe_url: fetch feed: ' . $poll . ' returns: ' . $xml, LOGGER_DATA);
657 logger("scrape_feed: XML is empty for feed ".$poll);
658 $network = NETWORK_PHANTOM;
660 $data = feed_import($xml,$dummy1,$dummy2, $dummy3, true);
662 if (!is_array($data)) {
663 logger("scrape_feed: This doesn't seem to be a feed: ".$poll);
664 $network = NETWORK_PHANTOM;
666 if (($vcard["photo"] == "") AND ($data["header"]["author-avatar"] != ""))
667 $vcard["photo"] = $data["header"]["author-avatar"];
669 if (($vcard["fn"] == "") AND ($data["header"]["author-name"] != ""))
670 $vcard["fn"] = $data["header"]["author-name"];
672 if (($vcard["nick"] == "") AND ($data["header"]["author-nick"] != ""))
673 $vcard["nick"] = $data["header"]["author-nick"];
675 if(!$profile AND ($data["header"]["author-link"] != "") AND !in_array($network, array("", NETWORK_FEED)))
676 $profile = $data["header"]["author-link"];
680 // Workaround for misconfigured Friendica servers
681 if (($network == "") AND (strstr($url, "/profile/"))) {
682 $noscrape = str_replace("/profile/", "/noscrape/", $url);
683 $noscrapejson = fetch_url($noscrape);
686 $network = NETWORK_DFRN;
688 $poco = str_replace("/profile/", "/poco/", $url);
690 $noscrapedata = json_decode($noscrapejson, true);
692 if (isset($noscrapedata["addr"]))
693 $addr = $noscrapedata["addr"];
695 if (isset($noscrapedata["fn"]))
696 $vcard["fn"] = $noscrapedata["fn"];
698 if (isset($noscrapedata["key"]))
699 $pubkey = $noscrapedata["key"];
701 if (isset($noscrapedata["photo"]))
702 $vcard["photo"] = $noscrapedata["photo"];
704 if (isset($noscrapedata["dfrn-request"]))
705 $request = $noscrapedata["dfrn-request"];
707 if (isset($noscrapedata["dfrn-confirm"]))
708 $confirm = $noscrapedata["dfrn-confirm"];
710 if (isset($noscrapedata["dfrn-notify"]))
711 $notify = $noscrapedata["dfrn-notify"];
713 if (isset($noscrapedata["dfrn-poll"]))
714 $poll = $noscrapedata["dfrn-poll"];
720 $network = NETWORK_FEED;
722 if(! x($vcard,'nick')) {
723 $vcard['nick'] = strtolower(notags(unxmlify($vcard['fn'])));
724 if(strpos($vcard['nick'],' '))
725 $vcard['nick'] = trim(substr($vcard['nick'],0,strpos($vcard['nick'],' ')));
732 if(! x($vcard,'photo')) {
734 $vcard['photo'] = App::get_baseurl() . '/images/person-175.jpg' ;
740 // No human could be associated with this link, use the URL as the contact name
742 if(($network === NETWORK_FEED) && ($poll) && (! x($vcard,'fn')))
745 if (($notify != "") AND ($poll != "")) {
746 $baseurl = matching(normalise_link($notify), normalise_link($poll));
748 $baseurl2 = matching($baseurl, normalise_link($profile));
750 $baseurl = $baseurl2;
753 if (($baseurl == "") AND ($notify != ""))
754 $baseurl = matching(normalise_link($profile), normalise_link($notify));
756 if (($baseurl == "") AND ($poll != ""))
757 $baseurl = matching(normalise_link($profile), normalise_link($poll));
759 $baseurl = rtrim($baseurl, "/");
761 if(strpos($url,'@') AND ($addr == "") AND ($network == NETWORK_DFRN))
762 $addr = str_replace('acct:', '', $url);
764 $vcard['fn'] = notags($vcard['fn']);
765 $vcard['nick'] = str_replace(' ','',notags($vcard['nick']));
767 $result['name'] = $vcard['fn'];
768 $result['nick'] = $vcard['nick'];
769 $result['url'] = $profile;
770 $result['addr'] = $addr;
771 $result['batch'] = $batch;
772 $result['notify'] = $notify;
773 $result['poll'] = $poll;
774 $result['request'] = $request;
775 $result['confirm'] = $confirm;
776 $result['poco'] = $poco;
777 $result['photo'] = $vcard['photo'];
778 $result['priority'] = $priority;
779 $result['network'] = $network;
780 $result['alias'] = $alias;
781 $result['pubkey'] = $pubkey;
782 $result['baseurl'] = $baseurl;
784 logger('probe_url: ' . print_r($result,true), LOGGER_DEBUG);
787 // Trying if it maybe a diaspora account
788 if (($result['network'] == NETWORK_FEED) OR ($result['addr'] == "")) {
789 require_once('include/bbcode.php');
790 $address = GetProfileUsername($url, "", true);
791 $result2 = probe_url($address, $mode, ++$level);
792 if ($result2['network'] != "")
796 // Maybe it's some non standard GNU Social installation (Single user, subfolder or no uri rewrite)
797 if (($result['network'] == NETWORK_FEED) AND ($result['baseurl'] != "") AND ($result['nick'] != "")) {
798 $addr = $result['nick'].'@'.str_replace("http://", "", $result['baseurl']);
799 $result2 = probe_url($addr, $mode, ++$level);
800 if (($result2['network'] != "") AND ($result2['network'] != NETWORK_FEED))
805 // Only store into the cache if the value seems to be valid
806 if ($result['network'] != NETWORK_PHANTOM)
807 Cache::set("probe_url:".$mode.":".$url,serialize($result), CACHE_DAY);
812 function matching($part1, $part2) {
813 $len = min(strlen($part1), strlen($part2));
818 while (($i <= $len) AND $matching) {
819 if (substr($part1, $i, 1) == substr($part2, $i, 1))
820 $match .= substr($part1, $i, 1);