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