3 require_once('library/HTML5/Parser.php');
4 require_once('include/crypto.php');
6 if(! function_exists('scrape_dfrn')) {
7 function scrape_dfrn($url) {
13 logger('scrape_dfrn: url=' . $url);
20 $headers = $a->get_curl_headers();
21 logger('scrape_dfrn: headers=' . $headers, LOGGER_DEBUG);
24 $lines = explode("\n",$headers);
26 foreach($lines as $line) {
27 // don't try and run feeds through the html5 parser
28 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
34 $dom = HTML5_Parser::parse($s);
35 } catch (DOMException $e) {
36 logger('scrape_dfrn: parse error: ' . $e);
42 $items = $dom->getElementsByTagName('link');
44 // get DFRN link elements
46 foreach($items as $item) {
47 $x = $item->getAttribute('rel');
48 if(($x === 'alternate') && ($item->getAttribute('type') === 'application/atom+xml'))
49 $ret['feed_atom'] = $item->getAttribute('href');
50 if(substr($x,0,5) == "dfrn-") {
51 $ret[$x] = $item->getAttribute('href');
54 $decoded = urldecode($item->getAttribute('href'));
55 if(preg_match('/acct:([^@]*)@/',$decoded,$matches))
56 $ret['nick'] = $matches[1];
60 // Pull out hCard profile elements
64 $items = $dom->getElementsByTagName('*');
65 foreach($items as $item) {
66 if(attribute_contains($item->getAttribute('class'), 'vcard')) {
67 $level2 = $item->getElementsByTagName('*');
68 foreach($level2 as $x) {
69 if(attribute_contains($x->getAttribute('class'),'fn')) {
70 $ret['fn'] = $x->textContent;
72 if((attribute_contains($x->getAttribute('class'),'photo'))
73 || (attribute_contains($x->getAttribute('class'),'avatar'))) {
74 $size = intval($x->getAttribute('width'));
75 // dfrn prefers 175, so if we find this, we set largest_size so it can't be topped.
76 if(($size > $largest_photo) || ($size == 175) || (! $largest_photo)) {
77 $ret['photo'] = $x->getAttribute('src');
78 $largest_photo = (($size == 175) ? 9999 : $size);
81 if(attribute_contains($x->getAttribute('class'),'key')) {
82 $ret['key'] = $x->textContent;
96 if(! function_exists('validate_dfrn')) {
97 function validate_dfrn($a) {
101 if(! x($a,'dfrn-request'))
103 if(! x($a,'dfrn-confirm'))
105 if(! x($a,'dfrn-notify'))
107 if(! x($a,'dfrn-poll'))
112 if(! function_exists('scrape_meta')) {
113 function scrape_meta($url) {
119 logger('scrape_meta: url=' . $url);
121 $s = fetch_url($url);
126 $headers = $a->get_curl_headers();
127 logger('scrape_meta: headers=' . $headers, LOGGER_DEBUG);
129 $lines = explode("\n",$headers);
131 foreach($lines as $line) {
132 // don't try and run feeds through the html5 parser
133 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
139 $dom = HTML5_Parser::parse($s);
140 } catch (DOMException $e) {
141 logger('scrape_meta: parse error: ' . $e);
147 $items = $dom->getElementsByTagName('meta');
149 // get DFRN link elements
151 foreach($items as $item) {
152 $x = $item->getAttribute('name');
153 if(substr($x,0,5) == "dfrn-")
154 $ret[$x] = $item->getAttribute('content');
161 if(! function_exists('scrape_vcard')) {
162 function scrape_vcard($url) {
168 logger('scrape_vcard: url=' . $url);
170 $s = fetch_url($url);
175 $headers = $a->get_curl_headers();
176 $lines = explode("\n",$headers);
178 foreach($lines as $line) {
179 // don't try and run feeds through the html5 parser
180 if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
186 $dom = HTML5_Parser::parse($s);
187 } catch (DOMException $e) {
188 logger('scrape_vcard: parse error: ' . $e);
194 // Pull out hCard profile elements
198 $items = $dom->getElementsByTagName('*');
199 foreach($items as $item) {
200 if(attribute_contains($item->getAttribute('class'), 'vcard')) {
201 $level2 = $item->getElementsByTagName('*');
202 foreach($level2 as $x) {
203 if(attribute_contains($x->getAttribute('class'),'fn'))
204 $ret['fn'] = $x->textContent;
205 if((attribute_contains($x->getAttribute('class'),'photo'))
206 || (attribute_contains($x->getAttribute('class'),'avatar'))) {
207 $size = intval($x->getAttribute('width'));
208 if(($size > $largest_photo) || (! $largest_photo)) {
209 $ret['photo'] = $x->getAttribute('src');
210 $largest_photo = $size;
213 if((attribute_contains($x->getAttribute('class'),'nickname'))
214 || (attribute_contains($x->getAttribute('class'),'uid'))) {
215 $ret['nick'] = $x->textContent;
225 if(! function_exists('scrape_feed')) {
226 function scrape_feed($url) {
231 $s = fetch_url($url);
233 $headers = $a->get_curl_headers();
234 $code = $a->get_curl_code();
236 logger('scrape_feed: returns: ' . $code . ' headers=' . $headers, LOGGER_DEBUG);
239 logger('scrape_feed: no data returned for ' . $url);
244 $lines = explode("\n",$headers);
246 foreach($lines as $line) {
247 if(stristr($line,'content-type:')) {
248 if(stristr($line,'application/atom+xml') || stristr($s,'<feed')) {
249 $ret['feed_atom'] = $url;
252 if(stristr($line,'application/rss+xml') || stristr($s,'<rss')) {
253 $ret['feed_rss'] = $url;
258 // perhaps an RSS version 1 feed with a generic or incorrect content-type?
259 if(stristr($s,'</item>')) {
260 $ret['feed_rss'] = $url;
266 $dom = HTML5_Parser::parse($s);
267 } catch (DOMException $e) {
268 logger('scrape_feed: parse error: ' . $e);
272 logger('scrape_feed: failed to parse.');
277 $head = $dom->getElementsByTagName('base');
279 foreach($head as $head0) {
280 $basename = $head0->getAttribute('href');
285 $basename = implode('/', array_slice(explode('/',$url),0,3)) . '/';
287 $items = $dom->getElementsByTagName('link');
289 // get Atom/RSS link elements, take the first one of either.
292 foreach($items as $item) {
293 $x = $item->getAttribute('rel');
294 if(($x === 'alternate') && ($item->getAttribute('type') === 'application/atom+xml')) {
295 if(! x($ret,'feed_atom'))
296 $ret['feed_atom'] = $item->getAttribute('href');
298 if(($x === 'alternate') && ($item->getAttribute('type') === 'application/rss+xml')) {
299 if(! x($ret,'feed_rss'))
300 $ret['feed_rss'] = $item->getAttribute('href');
305 // Drupal and perhaps others only provide relative URL's. Turn them into absolute.
307 if(x($ret,'feed_atom') && (! strstr($ret['feed_atom'],'://')))
308 $ret['feed_atom'] = $basename . $ret['feed_atom'];
309 if(x($ret,'feed_rss') && (! strstr($ret['feed_rss'],'://')))
310 $ret['feed_rss'] = $basename . $ret['feed_rss'];
318 * Probe a network address to discover what kind of protocols we need to communicate with it.
320 * Warning: this function is a bit touchy and there are some subtle dependencies within the logic flow.
327 * PROBE_DIASPORA has a bias towards returning Diaspora information
328 * while PROBE_NORMAL has a bias towards dfrn/zot - in the case where
329 * an address (such as a Friendica address) supports more than one type
335 define ( 'PROBE_NORMAL', 0);
336 define ( 'PROBE_DIASPORA', 1);
338 function probe_url($url, $mode = PROBE_NORMAL) {
339 require_once('include/email.php');
346 $result = Cache::get("probe_url:".$mode.":".$url);
347 if (!is_null($result)) {
348 $result = unserialize($result);
358 $email_conversant = false;
359 $connectornetworks = false;
362 if (strpos($url,'twitter.com')) {
363 $connectornetworks = true;
364 $network = NETWORK_TWITTER;
367 if (strpos($url,'www.facebook.com')) {
368 $connectornetworks = true;
369 $network = NETWORK_FACEBOOK;
372 if (strpos($url,'alpha.app.net')) {
374 $network = NETWORK_APPNET;
378 // Twitter is deactivated since twitter closed its old API
379 //$twitter = ((strpos($url,'twitter.com') !== false) ? true : false);
380 $lastfm = ((strpos($url,'last.fm/user') !== false) ? true : false);
382 $at_addr = ((strpos($url,'@') !== false) ? true : false);
384 if((!$appnet) && (!$lastfm) && !$connectornetworks) {
386 if(strpos($url,'mailto:') !== false && $at_addr) {
387 $url = str_replace('mailto:','',$url);
396 logger('probe_url: found lrdd links: ' . print_r($links,true), LOGGER_DATA);
397 foreach($links as $link) {
398 if($link['@attributes']['rel'] === NAMESPACE_ZOT)
399 $zot = unamp($link['@attributes']['href']);
400 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
401 $dfrn = unamp($link['@attributes']['href']);
402 if($link['@attributes']['rel'] === 'salmon')
403 $notify = unamp($link['@attributes']['href']);
404 if($link['@attributes']['rel'] === NAMESPACE_FEED)
405 $poll = unamp($link['@attributes']['href']);
406 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
407 $hcard = unamp($link['@attributes']['href']);
408 if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
409 $profile = unamp($link['@attributes']['href']);
410 if($link['@attributes']['rel'] === 'http://portablecontacts.net/spec/1.0')
411 $poco = unamp($link['@attributes']['href']);
412 if($link['@attributes']['rel'] === 'http://joindiaspora.com/seed_location') {
413 $diaspora_base = unamp($link['@attributes']['href']);
416 if($link['@attributes']['rel'] === 'http://joindiaspora.com/guid') {
417 $diaspora_guid = unamp($link['@attributes']['href']);
420 if($link['@attributes']['rel'] === 'diaspora-public-key') {
421 $diaspora_key = base64_decode(unamp($link['@attributes']['href']));
422 if(strstr($diaspora_key,'RSA '))
423 $pubkey = rsatopem($diaspora_key);
425 $pubkey = $diaspora_key;
428 if($link['@attributes']['rel'] === 'http://ostatus.org/schema/1.0/subscribe') {
433 // Status.Net can have more than one profile URL. We need to match the profile URL
434 // to a contact on incoming messages to prevent spam, and we won't know which one
435 // to match. So in case of two, one of them is stored as an alias. Only store URL's
436 // and not webfinger user@host aliases. If they've got more than two non-email style
437 // aliases, let's hope we're lucky and get one that matches the feed author-uri because
438 // otherwise we're screwed.
440 foreach($links as $link) {
441 if($link['@attributes']['rel'] === 'alias') {
442 if(strpos($link['@attributes']['href'],'@') === false) {
443 if(isset($profile)) {
444 if($link['@attributes']['href'] !== $profile)
445 $alias = unamp($link['@attributes']['href']);
448 $profile = unamp($link['@attributes']['href']);
453 // If the profile is different from the url then the url is abviously an alias
454 if (($alias == "") AND ($profile != "") AND !$at_addr AND (normalise_link($profile) != normalise_link($url)))
457 elseif($mode == PROBE_NORMAL) {
462 if((strpos($orig_url,'@')) && validate_email($orig_url)) {
463 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
466 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
469 if(count($x) && count($r)) {
470 $mailbox = construct_mailbox_name($r[0]);
472 openssl_private_decrypt(hex2bin($r[0]['pass']),$password,$x[0]['prvkey']);
473 $mbox = email_connect($mailbox,$r[0]['user'],$password);
475 logger('probe_url: email_connect failed.');
479 $msgs = email_poll($mbox,$orig_url);
480 logger('probe_url: searching ' . $orig_url . ', ' . count($msgs) . ' messages found.', LOGGER_DEBUG);
483 $network = NETWORK_MAIL;
484 $name = substr($url,0,strpos($url,'@'));
485 $phost = substr($url,strpos($url,'@')+1);
486 $profile = 'http://' . $phost;
487 // fix nick character range
488 $vcard = array('fn' => $name, 'nick' => $name, 'photo' => avatar_img($url));
489 $notify = 'smtp ' . random_string();
490 $poll = 'email ' . random_string();
492 $x = email_msg_meta($mbox,$msgs[0]);
493 if(stristr($x[0]->from,$orig_url))
494 $adr = imap_rfc822_parse_adrlist($x[0]->from,'');
495 elseif(stristr($x[0]->to,$orig_url))
496 $adr = imap_rfc822_parse_adrlist($x[0]->to,'');
498 foreach($adr as $feadr) {
499 if((strcasecmp($feadr->mailbox,$name) == 0)
500 &&(strcasecmp($feadr->host,$phost) == 0)
501 && (strlen($feadr->personal))) {
503 $personal = imap_mime_header_decode($feadr->personal);
505 foreach($personal as $perspart)
506 if ($perspart->charset != "default")
507 $vcard['fn'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
509 $vcard['fn'] .= $perspart->text;
511 $vcard['fn'] = notags($vcard['fn']);
522 if($mode == PROBE_NORMAL) {
524 $s = fetch_url($zot);
526 $j = json_decode($s);
528 $network = NETWORK_ZOT;
530 'fn' => $j->fullname,
531 'nick' => $j->nickname,
536 $pubkey = $j->pubkey;
543 $ret = scrape_dfrn(($hcard) ? $hcard : $dfrn);
544 if(is_array($ret) && x($ret,'dfrn-request')) {
545 $network = NETWORK_DFRN;
546 $request = $ret['dfrn-request'];
547 $confirm = $ret['dfrn-confirm'];
548 $notify = $ret['dfrn-notify'];
549 $poll = $ret['dfrn-poll'];
552 $vcard['fn'] = $ret['fn'];
553 $vcard['nick'] = $ret['nick'];
554 $vcard['photo'] = $ret['photo'];
559 if($diaspora && $diaspora_base && $diaspora_guid) {
560 if($mode == PROBE_DIASPORA || ! $notify) {
561 $notify = $diaspora_base . 'receive/users/' . $diaspora_guid;
562 $batch = $diaspora_base . 'receive/public' ;
565 $addr = str_replace('acct:', '', $url);
568 if($network !== NETWORK_ZOT && $network !== NETWORK_DFRN && $network !== NETWORK_MAIL) {
570 $network = NETWORK_DIASPORA;
572 $network = NETWORK_OSTATUS;
575 $addr = str_replace('acct:', '', $url);
579 if($hcard && ! $vcard) {
580 $vcard = scrape_vcard($hcard);
582 // Google doesn't use absolute url in profile photos
584 if((x($vcard,'photo')) && substr($vcard['photo'],0,1) == '/') {
585 $h = @parse_url($hcard);
587 $vcard['photo'] = $h['scheme'] . '://' . $h['host'] . $vcard['photo'];
590 logger('probe_url: scrape_vcard: ' . print_r($vcard,true), LOGGER_DATA);
593 if($diaspora && $addr) {
594 // Diaspora returns the name as the nick. As the nick will never be updated,
595 // let's use the Diaspora nickname (the first part of the handle) as the nick instead
596 $addr_parts = explode('@', $addr);
597 $vcard['nick'] = $addr_parts[0];
601 logger('twitter: setup');
602 $tid = basename($url);
603 $tapi = 'https://api.twitter.com/1/statuses/user_timeline.rss';
605 $poll = $tapi . '?user_id=' . $tid;
607 $poll = $tapi . '?screen_name=' . $tid;
608 $profile = 'http://twitter.com/#!/' . $tid;
609 //$vcard['photo'] = 'https://api.twitter.com/1/users/profile_image/' . $tid;
610 $vcard['photo'] = 'https://api.twitter.com/1/users/profile_image?screen_name=' . $tid . '&size=bigger';
611 $vcard['nick'] = $tid;
617 $poll = str_replace(array('www.','last.fm/'),array('','ws.audioscrobbler.com/1.0/'),$url) . '/recenttracks.rss';
618 $vcard['nick'] = basename($url);
619 $vcard['fn'] = $vcard['nick'] . t(' on Last.fm');
620 $network = NETWORK_FEED;
625 $vcard['fn'] = $vcard['nick'];
629 if(stristr($url,'tumblr.com') && (! stristr($url,'/rss'))) {
630 $poll = $url . '/rss';
632 // 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
635 if($appnet || ! $poll)
637 if((! isset($vcard)) || (! x($vcard,'fn')) || (! $profile))
639 if(($at_addr) && (! count($links)))
642 if ($connectornetworks)
647 $feedret = scrape_feed(($poll) ? $poll : $url);
648 logger('probe_url: scrape_feed ' . (($poll)? $poll : $url) . ' returns: ' . print_r($feedret,true), LOGGER_DATA);
649 if(count($feedret) && ($feedret['feed_atom'] || $feedret['feed_rss'])) {
650 $poll = ((x($feedret,'feed_atom')) ? unamp($feedret['feed_atom']) : unamp($feedret['feed_rss']));
655 if(x($feedret,'photo') && (! x($vcard,'photo')))
656 $vcard['photo'] = $feedret['photo'];
657 require_once('library/simplepie/simplepie.inc');
658 $feed = new SimplePie();
659 $xml = fetch_url($poll);
661 logger('probe_url: fetch feed: ' . $poll . ' returns: ' . $xml, LOGGER_DATA);
664 logger('probe_url: scrape_feed: headers: ' . $a->get_curl_headers(), LOGGER_DATA);
666 // Don't try and parse an empty string
667 $feed->set_raw_data(($xml) ? $xml : '<?xml version="1.0" encoding="utf-8" ?><xml></xml>');
671 logger('probe_url: scrape_feed: Error parsing XML: ' . $feed->error());
674 if(! x($vcard,'photo'))
675 $vcard['photo'] = $feed->get_image_url();
676 $author = $feed->get_author();
679 $vcard['fn'] = unxmlify(trim($author->get_name()));
681 $vcard['fn'] = trim(unxmlify($author->get_email()));
682 if(strpos($vcard['fn'],'@') !== false)
683 $vcard['fn'] = substr($vcard['fn'],0,strpos($vcard['fn'],'@'));
684 $email = unxmlify($author->get_email());
685 if(! $profile && $author->get_link())
686 $profile = trim(unxmlify($author->get_link()));
687 if(! $vcard['photo']) {
688 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
690 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
691 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
692 $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
697 $item = $feed->get_item(0);
699 $author = $item->get_author();
701 $vcard['fn'] = trim(unxmlify($author->get_name()));
703 $vcard['fn'] = trim(unxmlify($author->get_email()));
704 if(strpos($vcard['fn'],'@') !== false)
705 $vcard['fn'] = substr($vcard['fn'],0,strpos($vcard['fn'],'@'));
706 $email = unxmlify($author->get_email());
707 if(! $profile && $author->get_link())
708 $profile = trim(unxmlify($author->get_link()));
710 if(! $vcard['photo']) {
711 $rawmedia = $item->get_item_tags('http://search.yahoo.com/mrss/','thumbnail');
712 if($rawmedia && $rawmedia[0]['attribs']['']['url'])
713 $vcard['photo'] = unxmlify($rawmedia[0]['attribs']['']['url']);
715 if(! $vcard['photo']) {
716 $rawtags = $item->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
718 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
719 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
720 $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
726 if((! $vcard['photo']) && strlen($email))
727 $vcard['photo'] = avatar_img($email);
728 if($poll === $profile)
729 $lnk = $feed->get_permalink();
730 if(isset($lnk) && strlen($lnk))
734 $network = NETWORK_FEED;
735 // If it is a feed, don't take the author name as feed name
738 if(! (x($vcard,'fn')))
739 $vcard['fn'] = notags($feed->get_title());
740 if(! (x($vcard,'fn')))
741 $vcard['fn'] = notags($feed->get_description());
743 if(strpos($vcard['fn'],'Twitter / ') !== false) {
744 $vcard['fn'] = substr($vcard['fn'],strpos($vcard['fn'],'/')+1);
745 $vcard['fn'] = trim($vcard['fn']);
747 if(! x($vcard,'nick')) {
748 $vcard['nick'] = strtolower(notags(unxmlify($vcard['fn'])));
749 if(strpos($vcard['nick'],' '))
750 $vcard['nick'] = trim(substr($vcard['nick'],0,strpos($vcard['nick'],' ')));
757 if(! x($vcard,'photo')) {
759 $vcard['photo'] = $a->get_baseurl() . '/images/person-175.jpg' ;
765 // No human could be associated with this link, use the URL as the contact name
767 if(($network === NETWORK_FEED) && ($poll) && (! x($vcard,'fn')))
770 if (($notify != "") AND ($poll != "")) {
771 $baseurl = matching($notify, $poll);
773 $baseurl2 = matching($baseurl, $profile);
775 $baseurl = $baseurl2;
778 if (($baseurl == "") AND ($notify != ""))
779 $baseurl = matching($profile, $notify);
781 if (($baseurl == "") AND ($poll != ""))
782 $baseurl = matching($profile, $poll);
784 $baseurl = rtrim($baseurl, "/");
786 $vcard['fn'] = notags($vcard['fn']);
787 $vcard['nick'] = str_replace(' ','',notags($vcard['nick']));
789 $result['name'] = $vcard['fn'];
790 $result['nick'] = $vcard['nick'];
791 $result['url'] = $profile;
792 $result['addr'] = $addr;
793 $result['batch'] = $batch;
794 $result['notify'] = $notify;
795 $result['poll'] = $poll;
796 $result['request'] = $request;
797 $result['confirm'] = $confirm;
798 $result['poco'] = $poco;
799 $result['photo'] = $vcard['photo'];
800 $result['priority'] = $priority;
801 $result['network'] = $network;
802 $result['alias'] = $alias;
803 $result['pubkey'] = $pubkey;
804 $result['baseurl'] = $baseurl;
806 logger('probe_url: ' . print_r($result,true), LOGGER_DEBUG);
808 // Trying if it maybe a diaspora account
809 if (($result['network'] == NETWORK_FEED) OR ($result['addr'] == "")) {
810 require_once('include/bbcode.php');
811 $address = GetProfileUsername($url, "", true);
812 $result2 = probe_url($address, $mode);
813 if ($result2['network'] != "")
817 Cache::set("probe_url:".$mode.":".$url,serialize($result));
822 function matching($part1, $part2) {
823 $len = min(strlen($part1), strlen($part2));
828 while (($i <= $len) AND $matching) {
829 if (substr($part1, $i, 1) == substr($part2, $i, 1))
830 $match .= substr($part1, $i, 1);