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