]> git.mxchange.org Git - friendica.git/blob - include/Scrape.php
Simplepie is removed since we don't use it anymore
[friendica.git] / include / Scrape.php
1 <?php
2
3 require_once('library/HTML5/Parser.php');
4 require_once('include/crypto.php');
5 require_once('include/feed.php');
6
7 if(! function_exists('scrape_dfrn')) {
8 function scrape_dfrn($url, $dont_probe = false) {
9
10         $a = get_app();
11
12         $ret = array();
13
14         logger('scrape_dfrn: url=' . $url);
15
16         $s = fetch_url($url);
17
18         if(! $s)
19                 return $ret;
20
21         if (!$dont_probe) {
22                 $probe = probe_url($url);
23
24                 if (isset($probe["addr"]))
25                         $ret["addr"] = $probe["addr"];
26         }
27
28         $headers = $a->get_curl_headers();
29         logger('scrape_dfrn: headers=' . $headers, LOGGER_DEBUG);
30
31
32         $lines = explode("\n",$headers);
33         if(count($lines)) {
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'))))
37                                 return ret;
38                 }
39         }
40
41         try {
42                 $dom = HTML5_Parser::parse($s);
43         } catch (DOMException $e) {
44                 logger('scrape_dfrn: parse error: ' . $e);
45         }
46
47         if(! $dom)
48                 return $ret;
49
50         $items = $dom->getElementsByTagName('link');
51
52         // get DFRN link elements
53
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');
60                 }
61                 if($x === 'lrdd') {
62                         $decoded = urldecode($item->getAttribute('href'));
63                         if(preg_match('/acct:([^@]*)@/',$decoded,$matches))
64                                 $ret['nick'] = $matches[1];
65                 }
66         }
67
68         // Pull out hCard profile elements
69
70         $largest_photo = 0;
71
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;
79                                 }
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);
87                                         }
88                                 }
89                                 if(attribute_contains($x->getAttribute('class'),'key')) {
90                                         $ret['key'] = $x->textContent;
91                                 }
92                         }
93                 }
94         }
95
96         return $ret;
97 }}
98
99
100
101
102
103
104 if(! function_exists('validate_dfrn')) {
105 function validate_dfrn($a) {
106         $errors = 0;
107         if(! x($a,'key'))
108                 $errors ++;
109         if(! x($a,'dfrn-request'))
110                 $errors ++;
111         if(! x($a,'dfrn-confirm'))
112                 $errors ++;
113         if(! x($a,'dfrn-notify'))
114                 $errors ++;
115         if(! x($a,'dfrn-poll'))
116                 $errors ++;
117         return $errors;
118 }}
119
120 if(! function_exists('scrape_meta')) {
121 function scrape_meta($url) {
122
123         $a = get_app();
124
125         $ret = array();
126
127         logger('scrape_meta: url=' . $url);
128
129         $s = fetch_url($url);
130
131         if(! $s)
132                 return $ret;
133
134         $headers = $a->get_curl_headers();
135         logger('scrape_meta: headers=' . $headers, LOGGER_DEBUG);
136
137         $lines = explode("\n",$headers);
138         if(count($lines)) {
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'))))
142                                 return ret;
143                 }
144         }
145
146         try {
147                 $dom = HTML5_Parser::parse($s);
148         } catch (DOMException $e) {
149                 logger('scrape_meta: parse error: ' . $e);
150         }
151
152         if(! $dom)
153                 return $ret;
154
155         $items = $dom->getElementsByTagName('meta');
156
157         // get DFRN link elements
158
159         foreach($items as $item) {
160                 $x = $item->getAttribute('name');
161                 if(substr($x,0,5) == "dfrn-")
162                         $ret[$x] = $item->getAttribute('content');
163         }
164
165         return $ret;
166 }}
167
168
169 if(! function_exists('scrape_vcard')) {
170 function scrape_vcard($url) {
171
172         $a = get_app();
173
174         $ret = array();
175
176         logger('scrape_vcard: url=' . $url);
177
178         $s = fetch_url($url);
179
180         if(! $s)
181                 return $ret;
182
183         $headers = $a->get_curl_headers();
184         $lines = explode("\n",$headers);
185         if(count($lines)) {
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'))))
189                                 return ret;
190                 }
191         }
192
193         try {
194                 $dom = HTML5_Parser::parse($s);
195         } catch (DOMException $e) {
196                 logger('scrape_vcard: parse error: ' . $e);
197         }
198
199         if(! $dom)
200                 return $ret;
201
202         // Pull out hCard profile elements
203
204         $largest_photo = 0;
205
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;
219                                         }
220                                 }
221                                 if((attribute_contains($x->getAttribute('class'),'nickname'))
222                                         || (attribute_contains($x->getAttribute('class'),'uid'))) {
223                                         $ret['nick'] = $x->textContent;
224                                 }
225                         }
226                 }
227         }
228
229         return $ret;
230 }}
231
232
233 if(! function_exists('scrape_feed')) {
234 function scrape_feed($url) {
235
236         $a = get_app();
237
238         $ret = array();
239         $cookiejar = tempnam(get_temppath(), 'cookiejar-scrape-feed-');
240         $s = fetch_url($url, false, $redirects, 0, Null, $cookiejar);
241         unlink($cookiejar);
242
243         $headers = $a->get_curl_headers();
244         $code = $a->get_curl_code();
245
246         logger('scrape_feed: returns: ' . $code . ' headers=' . $headers, LOGGER_DEBUG);
247
248         if(! $s) {
249                 logger('scrape_feed: no data returned for ' . $url);
250                 return $ret;
251         }
252
253
254         $lines = explode("\n",$headers);
255         if(count($lines)) {
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;
260                                         return $ret;
261                                 }
262                                 if(stristr($line,'application/rss+xml') || stristr($s,'<rss')) {
263                                         $ret['feed_rss'] = $url;
264                                         return $ret;
265                                 }
266                         }
267                 }
268                 // perhaps an RSS version 1 feed with a generic or incorrect content-type?
269                 if(stristr($s,'</item>')) {
270                         $ret['feed_rss'] = $url;
271                         return $ret;
272                 }
273         }
274
275         $basename = implode('/', array_slice(explode('/',$url),0,3)) . '/';
276
277         $doc = new DOMDocument();
278         @$doc->loadHTML($s);
279         $xpath = new DomXPath($doc);
280
281         $base = $xpath->query("//base");
282         foreach ($base as $node) {
283                 $attr = array();
284
285                 if ($node->attributes->length)
286                         foreach ($node->attributes as $attribute)
287                                 $attr[$attribute->name] = $attribute->value;
288
289                 if ($attr["href"] != "")
290                         $basename = $attr["href"] ;
291         }
292
293         $list = $xpath->query("//link");
294         foreach ($list as $node) {
295                 $attr = array();
296
297                 if ($node->attributes->length)
298                         foreach ($node->attributes as $attribute)
299                                 $attr[$attribute->name] = $attribute->value;
300
301                 if (($attr["rel"] == "alternate") AND ($attr["type"] == "application/atom+xml"))
302                         $ret["feed_atom"] = $attr["href"];
303
304                 if (($attr["rel"] == "alternate") AND ($attr["type"] == "application/rss+xml"))
305                         $ret["feed_rss"] = $attr["href"];
306         }
307
308         // Drupal and perhaps others only provide relative URLs. Turn them into absolute.
309
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'];
314
315         return $ret;
316 }}
317
318
319 /**
320  *
321  * Probe a network address to discover what kind of protocols we need to communicate with it.
322  *
323  * Warning: this function is a bit touchy and there are some subtle dependencies within the logic flow.
324  * Edit with care.
325  *
326  */
327
328 /**
329  *
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
333  * of network.
334  *
335  */
336
337
338 define ( 'PROBE_NORMAL',   0);
339 define ( 'PROBE_DIASPORA', 1);
340
341 function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
342         require_once('include/email.php');
343
344         $result = array();
345
346         if(! $url)
347                 return $result;
348
349         $result = Cache::get("probe_url:".$mode.":".$url);
350         if (!is_null($result)) {
351                 $result = unserialize($result);
352                 return $result;
353         }
354
355         $network = null;
356         $diaspora = false;
357         $diaspora_base = '';
358         $diaspora_guid = '';
359         $diaspora_key = '';
360         $has_lrdd = false;
361         $email_conversant = false;
362         $connectornetworks = false;
363         $appnet = false;
364
365         if (strpos($url,'twitter.com')) {
366                 $connectornetworks = true;
367                 $network = NETWORK_TWITTER;
368         }
369
370         $lastfm  = ((strpos($url,'last.fm/user') !== false) ? true : false);
371
372         $at_addr = ((strpos($url,'@') !== false) ? true : false);
373
374         if((!$appnet) && (!$lastfm) && !$connectornetworks) {
375
376                 if(strpos($url,'mailto:') !== false && $at_addr) {
377                         $url = str_replace('mailto:','',$url);
378                         $links = array();
379                 }
380                 else
381                         $links = lrdd($url);
382
383                 if(count($links)) {
384                         $has_lrdd = true;
385
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']);
404                                         $diaspora = true;
405                                 }
406                                 if($link['@attributes']['rel'] === 'http://joindiaspora.com/guid') {
407                                         $diaspora_guid = unamp($link['@attributes']['href']);
408                                         $diaspora = true;
409                                 }
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);
414                                         else
415                                                 $pubkey = $diaspora_key;
416                                         $diaspora = true;
417                                 }
418                                 if(($link['@attributes']['rel'] === 'http://ostatus.org/schema/1.0/subscribe') AND ($mode == PROBE_NORMAL)) {
419                                         $diaspora = false;
420                                 }
421                         }
422
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.
429
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']);
436                                                 }
437                                                 else
438                                                         $profile = unamp($link['@attributes']['href']);
439                                         }
440                                 }
441                         }
442
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)))
445                                 $alias = $url;
446                 }
447                 elseif($mode == PROBE_NORMAL) {
448
449                         // Check email
450
451                         $orig_url = $url;
452                         if((strpos($orig_url,'@')) && validate_email($orig_url)) {
453                                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
454                                         intval(local_user())
455                                 );
456                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
457                                         intval(local_user())
458                                 );
459                                 if(count($x) && count($r)) {
460                                         $mailbox = construct_mailbox_name($r[0]);
461                                         $password = '';
462                                         openssl_private_decrypt(hex2bin($r[0]['pass']),$password,$x[0]['prvkey']);
463                                         $mbox = email_connect($mailbox,$r[0]['user'],$password);
464                                         if(! $mbox)
465                                                 logger('probe_url: email_connect failed.');
466                                         unset($password);
467                                 }
468                                 if($mbox) {
469                                         $msgs = email_poll($mbox,$orig_url);
470                                         logger('probe_url: searching ' . $orig_url . ', ' . count($msgs) . ' messages found.', LOGGER_DEBUG);
471                                         if(count($msgs)) {
472                                                 $addr = $orig_url;
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();
481                                                 $priority = 0;
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,'');
487                                                 if(isset($adr)) {
488                                                         foreach($adr as $feadr) {
489                                                                 if((strcasecmp($feadr->mailbox,$name) == 0)
490                                                                         &&(strcasecmp($feadr->host,$phost) == 0)
491                                                                         && (strlen($feadr->personal))) {
492
493                                                                         $personal = imap_mime_header_decode($feadr->personal);
494                                                                         $vcard['fn'] = "";
495                                                                         foreach($personal as $perspart)
496                                                                                 if ($perspart->charset != "default")
497                                                                                         $vcard['fn'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
498                                                                                 else
499                                                                                         $vcard['fn'] .= $perspart->text;
500
501                                                                         $vcard['fn'] = notags($vcard['fn']);
502                                                                 }
503                                                         }
504                                                 }
505                                         }
506                                         imap_close($mbox);
507                                 }
508                         }
509                 }
510         }
511
512         if($mode == PROBE_NORMAL) {
513
514                 if(strlen($zot)) {
515                         $s = fetch_url($zot);
516                         if($s) {
517                                 $j = json_decode($s);
518                                 if($j) {
519                                         $network = NETWORK_ZOT;
520                                         $vcard   = array(
521                                                 'fn'    => $j->fullname,
522                                                 'nick'  => $j->nickname,
523                                                 'photo' => $j->photo
524                                         );
525                                         $profile  = $j->url;
526                                         $notify   = $j->post;
527                                         $pubkey   = $j->pubkey;
528                                         $poll     = 'N/A';
529                                 }
530                         }
531                 }
532
533
534                 if(strlen($dfrn)) {
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'];
542
543                                 $vcard = array();
544                                 $vcard['fn'] = $ret['fn'];
545                                 $vcard['nick'] = $ret['nick'];
546                                 $vcard['photo'] = $ret['photo'];
547                         }
548                 }
549         }
550
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);
559                         else
560                                 $pubkey = $hcard_key;
561                 }
562         }
563         if($diaspora && $diaspora_base && $diaspora_guid) {
564                 $diaspora_notify = $diaspora_base.'receive/users/'.$diaspora_guid;
565
566                 if($mode == PROBE_DIASPORA || ! $notify || ($notify == $diaspora_notify)) {
567                         $notify = $diaspora_notify;
568                         $batch  = $diaspora_base . 'receive/public' ;
569                 }
570                 if(strpos($url,'@'))
571                         $addr = str_replace('acct:', '', $url);
572         }
573
574         if($network !== NETWORK_ZOT && $network !== NETWORK_DFRN && $network !== NETWORK_MAIL) {
575                 if($diaspora)
576                         $network = NETWORK_DIASPORA;
577                 elseif($has_lrdd AND ($notify))
578                         $network  = NETWORK_OSTATUS;
579
580                 if(strpos($url,'@'))
581                         $addr = str_replace('acct:', '', $url);
582
583                 $priority = 0;
584
585                 if($hcard && ! $vcard) {
586                         $vcard = scrape_vcard($hcard);
587
588                         // Google doesn't use absolute url in profile photos
589
590                         if((x($vcard,'photo')) && substr($vcard['photo'],0,1) == '/') {
591                                 $h = @parse_url($hcard);
592                                 if($h)
593                                         $vcard['photo'] = $h['scheme'] . '://' . $h['host'] . $vcard['photo'];
594                         }
595
596                         logger('probe_url: scrape_vcard: ' . print_r($vcard,true), LOGGER_DATA);
597                 }
598
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];
604                 }
605
606                 if($lastfm) {
607                         $profile = $url;
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;
612                 }
613
614                 if(! x($vcard,'fn'))
615                         if(x($vcard,'nick'))
616                                 $vcard['fn'] = $vcard['nick'];
617
618                 $check_feed = false;
619
620                 if(stristr($url,'tumblr.com') && (! stristr($url,'/rss'))) {
621                         $poll = $url . '/rss';
622                         $check_feed = true;
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
624                 }
625
626                 if($appnet || ! $poll)
627                         $check_feed = true;
628                 if((! isset($vcard)) || (! x($vcard,'fn')) || (! $profile))
629                         $check_feed = true;
630                 if(($at_addr) && (! count($links)))
631                         $check_feed = false;
632
633                 if ($connectornetworks)
634                         $check_feed = false;
635
636                 if($check_feed) {
637
638                         $feedret = scrape_feed(($poll) ? $poll : $url);
639
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']));
643                                 if(! x($vcard))
644                                         $vcard = array();
645                         }
646
647                         if(x($feedret,'photo') && (! x($vcard,'photo')))
648                                 $vcard['photo'] = $feedret['photo'];
649
650                         $cookiejar = tempnam(get_temppath(), 'cookiejar-scrape-feed-');
651                         $xml = fetch_url($poll, false, $redirects, 0, Null, $cookiejar);
652                         unlink($cookiejar);
653
654                         logger('probe_url: fetch feed: ' . $poll . ' returns: ' . $xml, LOGGER_DATA);
655
656                         if ($xml == "") {
657                                 logger("scrape_feed: XML is empty for feed ".$poll);
658                                 $network = NETWORK_PHANTOM;
659                         } else {
660                                 $data = feed_import($xml,$dummy1,$dummy2, $dummy3, true);
661
662                                 if (!is_array($data)) {
663                                         logger("scrape_feed: This doesn't seem to be a feed: ".$poll);
664                                         $network = NETWORK_PHANTOM;
665                                 } else {
666                                         if (($vcard["photo"] == "") AND ($data["header"]["author-avatar"] != ""))
667                                                 $vcard["photo"] = $data["header"]["author-avatar"];
668
669                                         if (($vcard["fn"] == "") AND ($data["header"]["author-name"] != ""))
670                                                 $vcard["fn"] = $data["header"]["author-name"];
671
672                                         if (($vcard["nick"] == "") AND ($data["header"]["author-nick"] != ""))
673                                                 $vcard["nick"] = $data["header"]["author-nick"];
674
675                                         if(!$profile AND ($data["header"]["author-link"] != "") AND !in_array($network, array("", NETWORK_FEED)))
676                                                 $profile = $data["header"]["author-link"];
677                                 }
678                         }
679
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);
684                                 if ($noscrapejson) {
685
686                                         $network = NETWORK_DFRN;
687
688                                         $poco = str_replace("/profile/", "/poco/", $url);
689
690                                         $noscrapedata = json_decode($noscrapejson, true);
691
692                                         if (isset($noscrapedata["addr"]))
693                                                 $addr = $noscrapedata["addr"];
694
695                                         if (isset($noscrapedata["fn"]))
696                                                 $vcard["fn"] = $noscrapedata["fn"];
697
698                                         if (isset($noscrapedata["key"]))
699                                                 $pubkey = $noscrapedata["key"];
700
701                                         if (isset($noscrapedata["photo"]))
702                                                 $vcard["photo"] = $noscrapedata["photo"];
703
704                                         if (isset($noscrapedata["dfrn-request"]))
705                                                 $request = $noscrapedata["dfrn-request"];
706
707                                         if (isset($noscrapedata["dfrn-confirm"]))
708                                                 $confirm = $noscrapedata["dfrn-confirm"];
709
710                                         if (isset($noscrapedata["dfrn-notify"]))
711                                                 $notify = $noscrapedata["dfrn-notify"];
712
713                                         if (isset($noscrapedata["dfrn-poll"]))
714                                                 $poll = $noscrapedata["dfrn-poll"];
715
716                                 }
717                         }
718
719                         if(! $network)
720                                 $network = NETWORK_FEED;
721
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'],' ')));
726                         }
727                         if(! $priority)
728                                 $priority = 2;
729                 }
730         }
731
732         if(! x($vcard,'photo')) {
733                 $a = get_app();
734                 $vcard['photo'] = App::get_baseurl() . '/images/person-175.jpg' ;
735         }
736
737         if(! $profile)
738                 $profile = $url;
739
740         // No human could be associated with this link, use the URL as the contact name
741
742         if(($network === NETWORK_FEED) && ($poll) && (! x($vcard,'fn')))
743                 $vcard['fn'] = $url;
744
745         if (($notify != "") AND ($poll != "")) {
746                 $baseurl = matching(normalise_link($notify), normalise_link($poll));
747
748                 $baseurl2 = matching($baseurl, normalise_link($profile));
749                 if ($baseurl2 != "")
750                         $baseurl = $baseurl2;
751         }
752
753         if (($baseurl == "") AND ($notify != ""))
754                 $baseurl = matching(normalise_link($profile), normalise_link($notify));
755
756         if (($baseurl == "") AND ($poll != ""))
757                 $baseurl = matching(normalise_link($profile), normalise_link($poll));
758
759         $baseurl = rtrim($baseurl, "/");
760
761         if(strpos($url,'@') AND ($addr == "") AND ($network == NETWORK_DFRN))
762                 $addr = str_replace('acct:', '', $url);
763
764         $vcard['fn'] = notags($vcard['fn']);
765         $vcard['nick'] = str_replace(' ','',notags($vcard['nick']));
766
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;
783
784         logger('probe_url: ' . print_r($result,true), LOGGER_DEBUG);
785
786         if ($level == 1) {
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'] != "")
793                                 $result = $result2;
794                 }
795
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))
801                                 $result = $result2;
802                 }
803         }
804
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);
808
809         return $result;
810 }
811
812 function matching($part1, $part2) {
813         $len = min(strlen($part1), strlen($part2));
814
815         $match = "";
816         $matching = true;
817         $i = 0;
818         while (($i <= $len) AND $matching) {
819                 if (substr($part1, $i, 1) == substr($part2, $i, 1))
820                         $match .= substr($part1, $i, 1);
821                 else
822                         $matching = false;
823
824                 $i++;
825         }
826         return($match);
827 }