]> git.mxchange.org Git - friendica.git/blob - include/Scrape.php
Merge event-attendance into develop
[friendica.git] / include / Scrape.php
1 <?php
2
3 require_once('library/HTML5/Parser.php');
4 require_once('include/crypto.php');
5
6 if(! function_exists('scrape_dfrn')) {
7 function scrape_dfrn($url) {
8
9         $a = get_app();
10
11         $ret = array();
12
13         logger('scrape_dfrn: url=' . $url);
14
15         $s = fetch_url($url);
16
17         if(! $s)
18                 return $ret;
19
20         $headers = $a->get_curl_headers();
21         logger('scrape_dfrn: headers=' . $headers, LOGGER_DEBUG);
22
23
24         $lines = explode("\n",$headers);
25         if(count($lines)) {
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'))))
29                                 return ret;
30                 }
31         }
32
33         try {
34                 $dom = HTML5_Parser::parse($s);
35         } catch (DOMException $e) {
36                 logger('scrape_dfrn: parse error: ' . $e);
37         }
38
39         if(! $dom)
40                 return $ret;
41
42         $items = $dom->getElementsByTagName('link');
43
44         // get DFRN link elements
45
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');
52                 }
53                 if($x === 'lrdd') {
54                         $decoded = urldecode($item->getAttribute('href'));
55                         if(preg_match('/acct:([^@]*)@/',$decoded,$matches))
56                                 $ret['nick'] = $matches[1];
57                 }
58         }
59
60         // Pull out hCard profile elements
61
62         $largest_photo = 0;
63
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;
71                                 }
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);
79                                         }
80                                 }
81                                 if(attribute_contains($x->getAttribute('class'),'key')) {
82                                         $ret['key'] = $x->textContent;
83                                 }
84                         }
85                 }
86         }
87
88         return $ret;
89 }}
90
91
92
93
94
95
96 if(! function_exists('validate_dfrn')) {
97 function validate_dfrn($a) {
98         $errors = 0;
99         if(! x($a,'key'))
100                 $errors ++;
101         if(! x($a,'dfrn-request'))
102                 $errors ++;
103         if(! x($a,'dfrn-confirm'))
104                 $errors ++;
105         if(! x($a,'dfrn-notify'))
106                 $errors ++;
107         if(! x($a,'dfrn-poll'))
108                 $errors ++;
109         return $errors;
110 }}
111
112 if(! function_exists('scrape_meta')) {
113 function scrape_meta($url) {
114
115         $a = get_app();
116
117         $ret = array();
118
119         logger('scrape_meta: url=' . $url);
120
121         $s = fetch_url($url);
122
123         if(! $s)
124                 return $ret;
125
126         $headers = $a->get_curl_headers();
127         logger('scrape_meta: headers=' . $headers, LOGGER_DEBUG);
128
129         $lines = explode("\n",$headers);
130         if(count($lines)) {
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'))))
134                                 return ret;
135                 }
136         }
137
138         try {
139                 $dom = HTML5_Parser::parse($s);
140         } catch (DOMException $e) {
141                 logger('scrape_meta: parse error: ' . $e);
142         }
143
144         if(! $dom)
145                 return $ret;
146
147         $items = $dom->getElementsByTagName('meta');
148
149         // get DFRN link elements
150
151         foreach($items as $item) {
152                 $x = $item->getAttribute('name');
153                 if(substr($x,0,5) == "dfrn-")
154                         $ret[$x] = $item->getAttribute('content');
155         }
156
157         return $ret;
158 }}
159
160
161 if(! function_exists('scrape_vcard')) {
162 function scrape_vcard($url) {
163
164         $a = get_app();
165
166         $ret = array();
167
168         logger('scrape_vcard: url=' . $url);
169
170         $s = fetch_url($url);
171
172         if(! $s)
173                 return $ret;
174
175         $headers = $a->get_curl_headers();
176         $lines = explode("\n",$headers);
177         if(count($lines)) {
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'))))
181                                 return ret;
182                 }
183         }
184
185         try {
186                 $dom = HTML5_Parser::parse($s);
187         } catch (DOMException $e) {
188                 logger('scrape_vcard: parse error: ' . $e);
189         }
190
191         if(! $dom)
192                 return $ret;
193
194         // Pull out hCard profile elements
195
196         $largest_photo = 0;
197
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;
211                                         }
212                                 }
213                                 if((attribute_contains($x->getAttribute('class'),'nickname'))
214                                         || (attribute_contains($x->getAttribute('class'),'uid'))) {
215                                         $ret['nick'] = $x->textContent;
216                                 }
217                         }
218                 }
219         }
220
221         return $ret;
222 }}
223
224
225 if(! function_exists('scrape_feed')) {
226 function scrape_feed($url) {
227
228         $a = get_app();
229
230         $ret = array();
231         $s = fetch_url($url);
232
233         $headers = $a->get_curl_headers();
234         $code = $a->get_curl_code();
235
236         logger('scrape_feed: returns: ' . $code . ' headers=' . $headers, LOGGER_DEBUG);
237
238         if(! $s) {
239                 logger('scrape_feed: no data returned for ' . $url);
240                 return $ret;
241         }
242
243
244         $lines = explode("\n",$headers);
245         if(count($lines)) {
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;
250                                         return $ret;
251                                 }
252                                 if(stristr($line,'application/rss+xml') || stristr($s,'<rss')) {
253                                         $ret['feed_rss'] = $url;
254                                         return $ret;
255                                 }
256                         }
257                 }
258                 // perhaps an RSS version 1 feed with a generic or incorrect content-type?
259                 if(stristr($s,'</item>')) {
260                         $ret['feed_rss'] = $url;
261                         return $ret;
262                 }
263         }
264
265         $basename = implode('/', array_slice(explode('/',$url),0,3)) . '/';
266
267         $doc = new DOMDocument();
268         @$doc->loadHTML($s);
269         $xpath = new DomXPath($doc);
270
271         $base = $xpath->query("//base");
272         foreach ($base as $node) {
273                 $attr = array();
274
275                 if ($node->attributes->length)
276                         foreach ($node->attributes as $attribute)
277                                 $attr[$attribute->name] = $attribute->value;
278
279                 if ($attr["href"] != "")
280                         $basename = $attr["href"] ;
281         }
282
283         $list = $xpath->query("//link");
284         foreach ($list as $node) {
285                 $attr = array();
286
287                 if ($node->attributes->length)
288                         foreach ($node->attributes as $attribute)
289                                 $attr[$attribute->name] = $attribute->value;
290
291                 if (($attr["rel"] == "alternate") AND ($attr["type"] == "application/atom+xml"))
292                         $ret["feed_atom"] = $attr["href"];
293
294                 if (($attr["rel"] == "alternate") AND ($attr["type"] == "application/rss+xml"))
295                         $ret["feed_rss"] = $attr["href"];
296         }
297
298         // Drupal and perhaps others only provide relative URLs. Turn them into absolute.
299
300         if(x($ret,'feed_atom') && (! strstr($ret['feed_atom'],'://')))
301                 $ret['feed_atom'] = $basename . $ret['feed_atom'];
302         if(x($ret,'feed_rss') && (! strstr($ret['feed_rss'],'://')))
303                 $ret['feed_rss'] = $basename . $ret['feed_rss'];
304
305         return $ret;
306 }}
307
308
309 /**
310  *
311  * Probe a network address to discover what kind of protocols we need to communicate with it.
312  *
313  * Warning: this function is a bit touchy and there are some subtle dependencies within the logic flow.
314  * Edit with care.
315  *
316  */
317
318 /**
319  *
320  * PROBE_DIASPORA has a bias towards returning Diaspora information
321  * while PROBE_NORMAL has a bias towards dfrn/zot - in the case where
322  * an address (such as a Friendica address) supports more than one type
323  * of network. 
324  *
325  */
326
327
328 define ( 'PROBE_NORMAL',   0);
329 define ( 'PROBE_DIASPORA', 1);
330
331 function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
332         require_once('include/email.php');
333
334         $result = array();
335
336         if(! $url)
337                 return $result;
338
339         $result = Cache::get("probe_url:".$mode.":".$url);
340         if (!is_null($result)) {
341                 $result = unserialize($result);
342                 return $result;
343         }
344
345         $network = null;
346         $diaspora = false;
347         $diaspora_base = '';
348         $diaspora_guid = '';
349         $diaspora_key = '';
350         $has_lrdd = false;
351         $email_conversant = false;
352         $connectornetworks = false;
353         $appnet = false;
354
355         if (strpos($url,'twitter.com')) {
356                 $connectornetworks = true;
357                 $network = NETWORK_TWITTER;
358         }
359
360         // Twitter is deactivated since twitter closed its old API
361         //$twitter = ((strpos($url,'twitter.com') !== false) ? true : false);
362         $lastfm  = ((strpos($url,'last.fm/user') !== false) ? true : false);
363
364         $at_addr = ((strpos($url,'@') !== false) ? true : false);
365
366         if((!$appnet) && (!$lastfm) && !$connectornetworks) {
367
368                 if(strpos($url,'mailto:') !== false && $at_addr) {
369                         $url = str_replace('mailto:','',$url);
370                         $links = array();
371                 }
372                 else
373                         $links = lrdd($url);
374
375                 if(count($links)) {
376                         $has_lrdd = true;
377
378                         logger('probe_url: found lrdd links: ' . print_r($links,true), LOGGER_DATA);
379                         foreach($links as $link) {
380                                 if($link['@attributes']['rel'] === NAMESPACE_ZOT)
381                                         $zot = unamp($link['@attributes']['href']);
382                                 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
383                                         $dfrn = unamp($link['@attributes']['href']);
384                                 if($link['@attributes']['rel'] === 'salmon')
385                                         $notify = unamp($link['@attributes']['href']);
386                                 if($link['@attributes']['rel'] === NAMESPACE_FEED)
387                                         $poll = unamp($link['@attributes']['href']);
388                                 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
389                                         $hcard = unamp($link['@attributes']['href']);
390                                 if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
391                                         $profile = unamp($link['@attributes']['href']);
392                                 if($link['@attributes']['rel'] === 'http://portablecontacts.net/spec/1.0')
393                                         $poco = unamp($link['@attributes']['href']);
394                                 if($link['@attributes']['rel'] === 'http://joindiaspora.com/seed_location') {
395                                         $diaspora_base = unamp($link['@attributes']['href']);
396                                         $diaspora = true;
397                                 }
398                                 if($link['@attributes']['rel'] === 'http://joindiaspora.com/guid') {
399                                         $diaspora_guid = unamp($link['@attributes']['href']);
400                                         $diaspora = true;
401                                 }
402                                 if($link['@attributes']['rel'] === 'diaspora-public-key') {
403                                         $diaspora_key = base64_decode(unamp($link['@attributes']['href']));
404                                         if(strstr($diaspora_key,'RSA '))
405                                                 $pubkey = rsatopem($diaspora_key);
406                                         else
407                                                 $pubkey = $diaspora_key;
408                                         $diaspora = true;
409                                 }
410                                 if($link['@attributes']['rel'] === 'http://ostatus.org/schema/1.0/subscribe') {
411                                         $diaspora = false;
412                                 }
413                         }
414
415                         // Status.Net can have more than one profile URL. We need to match the profile URL
416                         // to a contact on incoming messages to prevent spam, and we won't know which one
417                         // to match. So in case of two, one of them is stored as an alias. Only store URL's
418                         // and not webfinger user@host aliases. If they've got more than two non-email style
419                         // aliases, let's hope we're lucky and get one that matches the feed author-uri because
420                         // otherwise we're screwed.
421
422                         foreach($links as $link) {
423                                 if($link['@attributes']['rel'] === 'alias') {
424                                         if(strpos($link['@attributes']['href'],'@') === false) {
425                                                 if(isset($profile)) {
426                                                         if($link['@attributes']['href'] !== $profile)
427                                                                 $alias = unamp($link['@attributes']['href']);
428                                                 }
429                                                 else
430                                                         $profile = unamp($link['@attributes']['href']);
431                                         }
432                                 }
433                         }
434
435                         // If the profile is different from the url then the url is abviously an alias
436                         if (($alias == "") AND ($profile != "") AND !$at_addr AND (normalise_link($profile) != normalise_link($url)))
437                                 $alias = $url;
438                 }
439                 elseif($mode == PROBE_NORMAL) {
440
441                         // Check email
442
443                         $orig_url = $url;
444                         if((strpos($orig_url,'@')) && validate_email($orig_url)) {
445                                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
446                                         intval(local_user())
447                                 );
448                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
449                                         intval(local_user())
450                                 );
451                                 if(count($x) && count($r)) {
452                                         $mailbox = construct_mailbox_name($r[0]);
453                                         $password = '';
454                                         openssl_private_decrypt(hex2bin($r[0]['pass']),$password,$x[0]['prvkey']);
455                                         $mbox = email_connect($mailbox,$r[0]['user'],$password);
456                                         if(! $mbox)
457                                                 logger('probe_url: email_connect failed.');
458                                         unset($password);
459                                 }
460                                 if($mbox) {
461                                         $msgs = email_poll($mbox,$orig_url);
462                                         logger('probe_url: searching ' . $orig_url . ', ' . count($msgs) . ' messages found.', LOGGER_DEBUG);
463                                         if(count($msgs)) {
464                                                 $addr = $orig_url;
465                                                 $network = NETWORK_MAIL;
466                                                 $name = substr($url,0,strpos($url,'@'));
467                                                 $phost = substr($url,strpos($url,'@')+1);
468                                                 $profile = 'http://' . $phost;
469                                                 // fix nick character range
470                                                 $vcard = array('fn' => $name, 'nick' => $name, 'photo' => avatar_img($url));
471                                                 $notify = 'smtp ' . random_string();
472                                                 $poll = 'email ' . random_string();
473                                                 $priority = 0;
474                                                 $x = email_msg_meta($mbox,$msgs[0]);
475                                                 if(stristr($x[0]->from,$orig_url))
476                                                         $adr = imap_rfc822_parse_adrlist($x[0]->from,'');
477                                                 elseif(stristr($x[0]->to,$orig_url))
478                                                         $adr = imap_rfc822_parse_adrlist($x[0]->to,'');
479                                                 if(isset($adr)) {
480                                                         foreach($adr as $feadr) {
481                                                                 if((strcasecmp($feadr->mailbox,$name) == 0)
482                                                                         &&(strcasecmp($feadr->host,$phost) == 0)
483                                                                         && (strlen($feadr->personal))) {
484
485                                                                         $personal = imap_mime_header_decode($feadr->personal);
486                                                                         $vcard['fn'] = "";
487                                                                         foreach($personal as $perspart)
488                                                                                 if ($perspart->charset != "default")
489                                                                                         $vcard['fn'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
490                                                                                 else
491                                                                                         $vcard['fn'] .= $perspart->text;
492
493                                                                         $vcard['fn'] = notags($vcard['fn']);
494                                                                 }
495                                                         }
496                                                 }
497                                         }
498                                         imap_close($mbox);
499                                 }
500                         }
501                 }
502         }
503
504         if($mode == PROBE_NORMAL) {
505
506                 if(strlen($zot)) {
507                         $s = fetch_url($zot);
508                         if($s) {
509                                 $j = json_decode($s);
510                                 if($j) {
511                                         $network = NETWORK_ZOT;
512                                         $vcard   = array(
513                                                 'fn'    => $j->fullname,
514                                                 'nick'  => $j->nickname,
515                                                 'photo' => $j->photo
516                                         );
517                                         $profile  = $j->url;
518                                         $notify   = $j->post;
519                                         $pubkey   = $j->pubkey;
520                                         $poll     = 'N/A';
521                                 }
522                         }
523                 }
524
525
526                 if(strlen($dfrn)) {
527                         $ret = scrape_dfrn(($hcard) ? $hcard : $dfrn);
528                         if(is_array($ret) && x($ret,'dfrn-request')) {
529                                 $network = NETWORK_DFRN;
530                                 $request = $ret['dfrn-request'];
531                                 $confirm = $ret['dfrn-confirm'];
532                                 $notify  = $ret['dfrn-notify'];
533                                 $poll    = $ret['dfrn-poll'];
534
535                                 $vcard = array();
536                                 $vcard['fn'] = $ret['fn'];
537                                 $vcard['nick'] = $ret['nick'];
538                                 $vcard['photo'] = $ret['photo'];
539                         }
540                 }
541         }
542
543         if($diaspora && $diaspora_base && $diaspora_guid) {
544                 if($mode == PROBE_DIASPORA || ! $notify) {
545                         $notify = $diaspora_base . 'receive/users/' . $diaspora_guid;
546                         $batch  = $diaspora_base . 'receive/public' ;
547                 }
548                 if(strpos($url,'@'))
549                         $addr = str_replace('acct:', '', $url);
550         }
551
552         if($network !== NETWORK_ZOT && $network !== NETWORK_DFRN && $network !== NETWORK_MAIL) {
553                 if($diaspora)
554                         $network = NETWORK_DIASPORA;
555                 elseif($has_lrdd)
556                         $network  = NETWORK_OSTATUS;
557
558                 if(strpos($url,'@'))
559                         $addr = str_replace('acct:', '', $url);
560
561                 $priority = 0;
562
563                 if($hcard && ! $vcard) {
564                         $vcard = scrape_vcard($hcard);
565
566                         // Google doesn't use absolute url in profile photos
567
568                         if((x($vcard,'photo')) && substr($vcard['photo'],0,1) == '/') {
569                                 $h = @parse_url($hcard);
570                                 if($h)
571                                         $vcard['photo'] = $h['scheme'] . '://' . $h['host'] . $vcard['photo'];
572                         }
573
574                         logger('probe_url: scrape_vcard: ' . print_r($vcard,true), LOGGER_DATA);
575                 }
576
577                 if($diaspora && $addr) {
578                         // Diaspora returns the name as the nick. As the nick will never be updated,
579                         // let's use the Diaspora nickname (the first part of the handle) as the nick instead
580                         $addr_parts = explode('@', $addr);
581                         $vcard['nick'] = $addr_parts[0];
582                 }
583
584                 /* if($twitter) {
585                         logger('twitter: setup');
586                         $tid = basename($url);
587                         $tapi = 'https://api.twitter.com/1/statuses/user_timeline.rss';
588                         if(intval($tid))
589                                 $poll = $tapi . '?user_id=' . $tid;
590                         else
591                                 $poll = $tapi . '?screen_name=' . $tid;
592                         $profile = 'http://twitter.com/#!/' . $tid;
593                         //$vcard['photo'] = 'https://api.twitter.com/1/users/profile_image/' . $tid;
594                         $vcard['photo'] = 'https://api.twitter.com/1/users/profile_image?screen_name=' . $tid . '&size=bigger';
595                         $vcard['nick'] = $tid;
596                         $vcard['fn'] = $tid;
597                 } */
598
599                 if($lastfm) {
600                         $profile = $url;
601                         $poll = str_replace(array('www.','last.fm/'),array('','ws.audioscrobbler.com/1.0/'),$url) . '/recenttracks.rss';
602                         $vcard['nick'] = basename($url);
603                         $vcard['fn'] = $vcard['nick'] . t(' on Last.fm');
604                         $network = NETWORK_FEED;
605                 }
606
607                 if(! x($vcard,'fn'))
608                         if(x($vcard,'nick'))
609                                 $vcard['fn'] = $vcard['nick'];
610
611                 $check_feed = false;
612
613                 if(stristr($url,'tumblr.com') && (! stristr($url,'/rss'))) {
614                         $poll = $url . '/rss';
615                         $check_feed = true;
616                         // 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
617                 }
618
619                 if($appnet || ! $poll)
620                         $check_feed = true;
621                 if((! isset($vcard)) || (! x($vcard,'fn')) || (! $profile))
622                         $check_feed = true;
623                 if(($at_addr) && (! count($links)))
624                         $check_feed = false;
625
626                 if ($connectornetworks)
627                         $check_feed = false;
628
629                 if($check_feed) {
630
631                         $feedret = scrape_feed(($poll) ? $poll : $url);
632
633                         logger('probe_url: scrape_feed ' . (($poll)? $poll : $url) . ' returns: ' . print_r($feedret,true), LOGGER_DATA);
634                         if(count($feedret) && ($feedret['feed_atom'] || $feedret['feed_rss'])) {
635                                 $poll = ((x($feedret,'feed_atom')) ? unamp($feedret['feed_atom']) : unamp($feedret['feed_rss']));
636                                 if(! x($vcard))
637                                         $vcard = array();
638                         }
639
640                         if(x($feedret,'photo') && (! x($vcard,'photo')))
641                                 $vcard['photo'] = $feedret['photo'];
642                         require_once('library/simplepie/simplepie.inc');
643                         $feed = new SimplePie();
644                         $xml = fetch_url($poll);
645
646                         logger('probe_url: fetch feed: ' . $poll . ' returns: ' . $xml, LOGGER_DATA);
647                         $a = get_app();
648
649                         logger('probe_url: scrape_feed: headers: ' . $a->get_curl_headers(), LOGGER_DATA);
650
651                         // Don't try and parse an empty string
652                         $feed->set_raw_data(($xml) ? $xml : '<?xml version="1.0" encoding="utf-8" ?><xml></xml>');
653
654                         $feed->init();
655                         if($feed->error())
656                                 logger('probe_url: scrape_feed: Error parsing XML: ' . $feed->error());
657
658
659                         if(! x($vcard,'photo'))
660                                 $vcard['photo'] = $feed->get_image_url();
661                         $author = $feed->get_author();
662
663                         if($author) {
664                                 $vcard['fn'] = unxmlify(trim($author->get_name()));
665                                 if(! $vcard['fn'])
666                                         $vcard['fn'] = trim(unxmlify($author->get_email()));
667                                 if(strpos($vcard['fn'],'@') !== false)
668                                         $vcard['fn'] = substr($vcard['fn'],0,strpos($vcard['fn'],'@'));
669
670                                 $email = unxmlify($author->get_email());
671                                 if(! $profile && $author->get_link())
672                                         $profile = trim(unxmlify($author->get_link()));
673                                 if(! $vcard['photo']) {
674                                         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
675                                         if($rawtags) {
676                                                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
677                                                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
678                                                         $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
679                                         }
680                                 }
681                                 // Fetch fullname via poco:displayName
682                                 $pocotags = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
683                                 if ($pocotags) {
684                                         $elems = $pocotags[0]['child']['http://portablecontacts.net/spec/1.0'];
685                                         if (isset($elems["displayName"]))
686                                                 $vcard['fn'] = $elems["displayName"][0]["data"];
687                                         if (isset($elems["preferredUsername"]))
688                                                 $vcard['nick'] = $elems["preferredUsername"][0]["data"];
689                                 }
690                         }
691                         else {
692                                 $item = $feed->get_item(0);
693                                 if($item) {
694                                         $author = $item->get_author();
695                                         if($author) {
696                                                 $vcard['fn'] = trim(unxmlify($author->get_name()));
697                                                 if(! $vcard['fn'])
698                                                         $vcard['fn'] = trim(unxmlify($author->get_email()));
699                                                 if(strpos($vcard['fn'],'@') !== false)
700                                                         $vcard['fn'] = substr($vcard['fn'],0,strpos($vcard['fn'],'@'));
701                                                 $email = unxmlify($author->get_email());
702                                                 if(! $profile && $author->get_link())
703                                                         $profile = trim(unxmlify($author->get_link()));
704                                         }
705                                         if(! $vcard['photo']) {
706                                                 $rawmedia = $item->get_item_tags('http://search.yahoo.com/mrss/','thumbnail');
707                                                 if($rawmedia && $rawmedia[0]['attribs']['']['url'])
708                                                         $vcard['photo'] = unxmlify($rawmedia[0]['attribs']['']['url']);
709                                         }
710                                         if(! $vcard['photo']) {
711                                                 $rawtags = $item->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
712                                                 if($rawtags) {
713                                                         $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
714                                                         if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
715                                                                 $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
716                                                 }
717                                         }
718                                 }
719                         }
720
721                         if((! $vcard['photo']) && strlen($email))
722                                 $vcard['photo'] = avatar_img($email);
723                         if($poll === $profile)
724                                 $lnk = $feed->get_permalink();
725                         if(isset($lnk) && strlen($lnk))
726                                 $profile = $lnk;
727
728                         if(! $network) {
729                                 $network = NETWORK_FEED;
730                                 // If it is a feed, don't take the author name as feed name
731                                 unset($vcard['fn']);
732                         }
733                         if(! (x($vcard,'fn')))
734                                 $vcard['fn'] = notags($feed->get_title());
735                         if(! (x($vcard,'fn')))
736                                 $vcard['fn'] = notags($feed->get_description());
737
738                         if(strpos($vcard['fn'],'Twitter / ') !== false) {
739                                 $vcard['fn'] = substr($vcard['fn'],strpos($vcard['fn'],'/')+1);
740                                 $vcard['fn'] = trim($vcard['fn']);
741                         }
742                         if(! x($vcard,'nick')) {
743                                 $vcard['nick'] = strtolower(notags(unxmlify($vcard['fn'])));
744                                 if(strpos($vcard['nick'],' '))
745                                         $vcard['nick'] = trim(substr($vcard['nick'],0,strpos($vcard['nick'],' ')));
746                         }
747                         if(! $priority)
748                                 $priority = 2;
749                 }
750         }
751
752         if(! x($vcard,'photo')) {
753                 $a = get_app();
754                 $vcard['photo'] = $a->get_baseurl() . '/images/person-175.jpg' ;
755         }
756
757         if(! $profile)
758                 $profile = $url;
759
760         // No human could be associated with this link, use the URL as the contact name
761
762         if(($network === NETWORK_FEED) && ($poll) && (! x($vcard,'fn')))
763                 $vcard['fn'] = $url;
764
765         if (($notify != "") AND ($poll != "")) {
766                 $baseurl = matching(normalise_link($notify), normalise_link($poll));
767
768                 $baseurl2 = matching($baseurl, normalise_link($profile));
769                 if ($baseurl2 != "")
770                         $baseurl = $baseurl2;
771         }
772
773         if (($baseurl == "") AND ($notify != ""))
774                 $baseurl = matching(normalise_link($profile), normalise_link($notify));
775
776         if (($baseurl == "") AND ($poll != ""))
777                 $baseurl = matching(normalise_link($profile), normalise_link($poll));
778
779         $baseurl = rtrim($baseurl, "/");
780
781         $vcard['fn'] = notags($vcard['fn']);
782         $vcard['nick'] = str_replace(' ','',notags($vcard['nick']));
783
784         $result['name'] = $vcard['fn'];
785         $result['nick'] = $vcard['nick'];
786         $result['url'] = $profile;
787         $result['addr'] = $addr;
788         $result['batch'] = $batch;
789         $result['notify'] = $notify;
790         $result['poll'] = $poll;
791         $result['request'] = $request;
792         $result['confirm'] = $confirm;
793         $result['poco'] = $poco;
794         $result['photo'] = $vcard['photo'];
795         $result['priority'] = $priority;
796         $result['network'] = $network;
797         $result['alias'] = $alias;
798         $result['pubkey'] = $pubkey;
799         $result['baseurl'] = $baseurl;
800
801         logger('probe_url: ' . print_r($result,true), LOGGER_DEBUG);
802
803         if ($level == 1) {
804                 // Trying if it maybe a diaspora account
805                 if (($result['network'] == NETWORK_FEED) OR ($result['addr'] == "")) {
806                         require_once('include/bbcode.php');
807                         $address = GetProfileUsername($url, "", true);
808                         $result2 = probe_url($address, $mode, ++$level);
809                         if ($result2['network'] != "")
810                                 $result = $result2;
811                 }
812
813                 // Maybe it's some non standard GNU Social installation (Single user, subfolder or no uri rewrite)
814                 if (($result['network'] == NETWORK_FEED) AND ($result['baseurl'] != "") AND ($result['nick'] != "")) {
815                         $addr = $result['nick'].'@'.str_replace("http://", "", $result['baseurl']);
816                         $result2 = probe_url($addr, $mode, ++$level);
817                         if (($result2['network'] != "") AND ($result2['network'] != NETWORK_FEED))
818                                 $result = $result2;
819                 }
820         }
821
822         // Only store into the cache if the value seems to be valid
823         if ($result['network'] != NETWORK_FEED)
824                 Cache::set("probe_url:".$mode.":".$url,serialize($result), CACHE_DAY);
825
826         return $result;
827 }
828
829 function matching($part1, $part2) {
830         $len = min(strlen($part1), strlen($part2));
831
832         $match = "";
833         $matching = true;
834         $i = 0;
835         while (($i <= $len) AND $matching) {
836                 if (substr($part1, $i, 1) == substr($part2, $i, 1))
837                         $match .= substr($part1, $i, 1);
838                 else
839                         $matching = false;
840
841                 $i++;
842         }
843         return($match);
844 }