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