]> git.mxchange.org Git - friendica.git/blob - include/Scrape.php
3fead0c415d085ffcd0927922138f395691a0b5b
[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         $original_url = $url;
369         $network = null;
370         $diaspora = false;
371         $diaspora_base = '';
372         $diaspora_guid = '';
373         $diaspora_key = '';
374         $has_lrdd = false;
375         $email_conversant = false;
376         $connectornetworks = false;
377         $appnet = false;
378
379         if (strpos($url,'twitter.com')) {
380                 $connectornetworks = true;
381                 $network = NETWORK_TWITTER;
382         }
383
384         $lastfm  = ((strpos($url,'last.fm/user') !== false) ? true : false);
385
386         $at_addr = ((strpos($url,'@') !== false) ? true : false);
387
388         if((!$appnet) && (!$lastfm) && !$connectornetworks) {
389
390                 if(strpos($url,'mailto:') !== false && $at_addr) {
391                         $url = str_replace('mailto:','',$url);
392                         $links = array();
393                 }
394                 else
395                         $links = lrdd($url);
396
397                 if ((count($links) == 0) AND strstr($url, "/index.php")) {
398                         $url = str_replace("/index.php", "", $url);
399                         $links = lrdd($url);
400                 }
401
402                 if (count($links)) {
403                         $has_lrdd = true;
404
405                         logger('probe_url: found lrdd links: ' . print_r($links,true), LOGGER_DATA);
406                         foreach($links as $link) {
407                                 if($link['@attributes']['rel'] === NAMESPACE_ZOT)
408                                         $zot = unamp($link['@attributes']['href']);
409                                 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
410                                         $dfrn = unamp($link['@attributes']['href']);
411                                 if($link['@attributes']['rel'] === 'salmon')
412                                         $notify = unamp($link['@attributes']['href']);
413                                 if($link['@attributes']['rel'] === NAMESPACE_FEED)
414                                         $poll = unamp($link['@attributes']['href']);
415                                 if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
416                                         $hcard = unamp($link['@attributes']['href']);
417                                 if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
418                                         $profile = unamp($link['@attributes']['href']);
419                                 if($link['@attributes']['rel'] === 'http://portablecontacts.net/spec/1.0')
420                                         $poco = unamp($link['@attributes']['href']);
421                                 if($link['@attributes']['rel'] === 'http://joindiaspora.com/seed_location') {
422                                         $diaspora_base = unamp($link['@attributes']['href']);
423                                         $diaspora = true;
424                                 }
425                                 if($link['@attributes']['rel'] === 'http://joindiaspora.com/guid') {
426                                         $diaspora_guid = unamp($link['@attributes']['href']);
427                                         $diaspora = true;
428                                 }
429                                 if($link['@attributes']['rel'] === 'diaspora-public-key') {
430                                         $diaspora_key = base64_decode(unamp($link['@attributes']['href']));
431                                         if(strstr($diaspora_key,'RSA '))
432                                                 $pubkey = rsatopem($diaspora_key);
433                                         else
434                                                 $pubkey = $diaspora_key;
435                                         $diaspora = true;
436                                 }
437                                 if(($link['@attributes']['rel'] === 'http://ostatus.org/schema/1.0/subscribe') AND ($mode == PROBE_NORMAL)) {
438                                         $diaspora = false;
439                                 }
440                         }
441
442                         // Status.Net can have more than one profile URL. We need to match the profile URL
443                         // to a contact on incoming messages to prevent spam, and we won't know which one
444                         // to match. So in case of two, one of them is stored as an alias. Only store URL's
445                         // and not webfinger user@host aliases. If they've got more than two non-email style
446                         // aliases, let's hope we're lucky and get one that matches the feed author-uri because
447                         // otherwise we're screwed.
448
449                         $backup_alias = "";
450
451                         foreach($links as $link) {
452                                 if($link['@attributes']['rel'] === 'alias') {
453                                         if(strpos($link['@attributes']['href'],'@') === false) {
454                                                 if(isset($profile)) {
455                                                         $alias_url = $link['@attributes']['href'];
456
457                                                         if(($alias_url !== $profile) AND ($backup_alias == "") AND
458                                                                 ($alias_url !== str_replace("/index.php", "", $profile)))
459                                                                 $backup_alias = $alias_url;
460
461                                                         if(($alias_url !== $profile) AND !strstr($alias_url, "index.php") AND
462                                                                 ($alias_url !== str_replace("/index.php", "", $profile)))
463                                                                 $alias = $alias_url;
464                                                 }
465                                                 else
466                                                         $profile = unamp($link['@attributes']['href']);
467                                         }
468                                 }
469                         }
470
471                         if ($alias == "")
472                                 $alias = $backup_alias;
473
474                         // If the profile is different from the url then the url is abviously an alias
475                         if (($alias == "") AND ($profile != "") AND !$at_addr AND (normalise_link($profile) != normalise_link($url)))
476                                 $alias = $url;
477                 }
478                 elseif($mode == PROBE_NORMAL) {
479
480                         // Check email
481
482                         $orig_url = $url;
483                         if((strpos($orig_url,'@')) && validate_email($orig_url)) {
484                                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1",
485                                         intval(local_user())
486                                 );
487                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
488                                         intval(local_user())
489                                 );
490                                 if(count($x) && count($r)) {
491                                         $mailbox = construct_mailbox_name($r[0]);
492                                         $password = '';
493                                         openssl_private_decrypt(hex2bin($r[0]['pass']),$password,$x[0]['prvkey']);
494                                         $mbox = email_connect($mailbox,$r[0]['user'],$password);
495                                         if(! $mbox)
496                                                 logger('probe_url: email_connect failed.');
497                                         unset($password);
498                                 }
499                                 if($mbox) {
500                                         $msgs = email_poll($mbox,$orig_url);
501                                         logger('probe_url: searching ' . $orig_url . ', ' . count($msgs) . ' messages found.', LOGGER_DEBUG);
502                                         if(count($msgs)) {
503                                                 $addr = $orig_url;
504                                                 $network = NETWORK_MAIL;
505                                                 $name = substr($url,0,strpos($url,'@'));
506                                                 $phost = substr($url,strpos($url,'@')+1);
507                                                 $profile = 'http://' . $phost;
508                                                 // fix nick character range
509                                                 $vcard = array('fn' => $name, 'nick' => $name, 'photo' => avatar_img($url));
510                                                 $notify = 'smtp ' . random_string();
511                                                 $poll = 'email ' . random_string();
512                                                 $priority = 0;
513                                                 $x = email_msg_meta($mbox,$msgs[0]);
514                                                 if(stristr($x[0]->from,$orig_url))
515                                                         $adr = imap_rfc822_parse_adrlist($x[0]->from,'');
516                                                 elseif(stristr($x[0]->to,$orig_url))
517                                                         $adr = imap_rfc822_parse_adrlist($x[0]->to,'');
518                                                 if(isset($adr)) {
519                                                         foreach($adr as $feadr) {
520                                                                 if((strcasecmp($feadr->mailbox,$name) == 0)
521                                                                         &&(strcasecmp($feadr->host,$phost) == 0)
522                                                                         && (strlen($feadr->personal))) {
523
524                                                                         $personal = imap_mime_header_decode($feadr->personal);
525                                                                         $vcard['fn'] = "";
526                                                                         foreach($personal as $perspart)
527                                                                                 if ($perspart->charset != "default")
528                                                                                         $vcard['fn'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
529                                                                                 else
530                                                                                         $vcard['fn'] .= $perspart->text;
531
532                                                                         $vcard['fn'] = notags($vcard['fn']);
533                                                                 }
534                                                         }
535                                                 }
536                                         }
537                                         imap_close($mbox);
538                                 }
539                         }
540                 }
541         }
542
543         if($mode == PROBE_NORMAL) {
544
545                 if(strlen($zot)) {
546                         $s = fetch_url($zot);
547                         if($s) {
548                                 $j = json_decode($s);
549                                 if($j) {
550                                         $network = NETWORK_ZOT;
551                                         $vcard   = array(
552                                                 'fn'    => $j->fullname,
553                                                 'nick'  => $j->nickname,
554                                                 'photo' => $j->photo
555                                         );
556                                         $profile  = $j->url;
557                                         $notify   = $j->post;
558                                         $pubkey   = $j->pubkey;
559                                         $poll     = 'N/A';
560                                 }
561                         }
562                 }
563
564
565                 if(strlen($dfrn)) {
566                         $ret = scrape_dfrn(($hcard) ? $hcard : $dfrn, true);
567                         if(is_array($ret) && x($ret,'dfrn-request')) {
568                                 $network = NETWORK_DFRN;
569                                 $request = $ret['dfrn-request'];
570                                 $confirm = $ret['dfrn-confirm'];
571                                 $notify  = $ret['dfrn-notify'];
572                                 $poll    = $ret['dfrn-poll'];
573
574                                 $vcard = array();
575                                 $vcard['fn'] = $ret['fn'];
576                                 $vcard['nick'] = $ret['nick'];
577                                 $vcard['photo'] = $ret['photo'];
578                         }
579                 }
580         }
581
582         // Scrape the public key from the hcard.
583         // Diaspora will remove it from the webfinger somewhere in the future.
584         if (($hcard != "") AND ($pubkey == "")) {
585                 $ret = scrape_dfrn(($hcard) ? $hcard : $dfrn, true);
586                 if (isset($ret["key"])) {
587                         $hcard_key = $ret["key"];
588                         if(strstr($hcard_key,'RSA '))
589                                 $pubkey = rsatopem($hcard_key);
590                         else
591                                 $pubkey = $hcard_key;
592                 }
593         }
594         if($diaspora && $diaspora_base && $diaspora_guid) {
595                 $diaspora_notify = $diaspora_base.'receive/users/'.$diaspora_guid;
596
597                 if($mode == PROBE_DIASPORA || ! $notify || ($notify == $diaspora_notify)) {
598                         $notify = $diaspora_notify;
599                         $batch  = $diaspora_base . 'receive/public' ;
600                 }
601                 if(strpos($url,'@'))
602                         $addr = str_replace('acct:', '', $url);
603         }
604
605         if($network !== NETWORK_ZOT && $network !== NETWORK_DFRN && $network !== NETWORK_MAIL) {
606                 if($diaspora)
607                         $network = NETWORK_DIASPORA;
608                 elseif($has_lrdd AND ($notify))
609                         $network  = NETWORK_OSTATUS;
610
611                 if(strpos($url,'@'))
612                         $addr = str_replace('acct:', '', $url);
613
614                 $priority = 0;
615
616                 if($hcard && ! $vcard) {
617                         $vcard = scrape_vcard($hcard);
618
619                         // Google doesn't use absolute url in profile photos
620
621                         if((x($vcard,'photo')) && substr($vcard['photo'],0,1) == '/') {
622                                 $h = @parse_url($hcard);
623                                 if($h)
624                                         $vcard['photo'] = $h['scheme'] . '://' . $h['host'] . $vcard['photo'];
625                         }
626
627                         logger('probe_url: scrape_vcard: ' . print_r($vcard,true), LOGGER_DATA);
628                 }
629
630                 if($diaspora && $addr) {
631                         // Diaspora returns the name as the nick. As the nick will never be updated,
632                         // let's use the Diaspora nickname (the first part of the handle) as the nick instead
633                         $addr_parts = explode('@', $addr);
634                         $vcard['nick'] = $addr_parts[0];
635                 }
636
637                 if($lastfm) {
638                         $profile = $url;
639                         $poll = str_replace(array('www.','last.fm/'),array('','ws.audioscrobbler.com/1.0/'),$url) . '/recenttracks.rss';
640                         $vcard['nick'] = basename($url);
641                         $vcard['fn'] = $vcard['nick'] . t(' on Last.fm');
642                         $network = NETWORK_FEED;
643                 }
644
645                 if(! x($vcard,'fn'))
646                         if(x($vcard,'nick'))
647                                 $vcard['fn'] = $vcard['nick'];
648
649                 $check_feed = false;
650
651                 if(stristr($url,'tumblr.com') && (! stristr($url,'/rss'))) {
652                         $poll = $url . '/rss';
653                         $check_feed = true;
654                         // 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
655                 }
656
657                 if($appnet || ! $poll)
658                         $check_feed = true;
659                 if((! isset($vcard)) || (! x($vcard,'fn')) || (! $profile))
660                         $check_feed = true;
661                 if(($at_addr) && (! count($links)))
662                         $check_feed = false;
663
664                 if ($connectornetworks)
665                         $check_feed = false;
666
667                 if($check_feed) {
668
669                         $feedret = scrape_feed(($poll) ? $poll : $url);
670
671                         logger('probe_url: scrape_feed ' . (($poll)? $poll : $url) . ' returns: ' . print_r($feedret,true), LOGGER_DATA);
672                         if(count($feedret) && ($feedret['feed_atom'] || $feedret['feed_rss'])) {
673                                 $poll = ((x($feedret,'feed_atom')) ? unamp($feedret['feed_atom']) : unamp($feedret['feed_rss']));
674                                 if(! x($vcard))
675                                         $vcard = array();
676                         }
677
678                         if(x($feedret,'photo') && (! x($vcard,'photo')))
679                                 $vcard['photo'] = $feedret['photo'];
680
681                         $cookiejar = tempnam(get_temppath(), 'cookiejar-scrape-feed-');
682                         $xml = fetch_url($poll, false, $redirects, 0, Null, $cookiejar);
683                         unlink($cookiejar);
684
685                         logger('probe_url: fetch feed: ' . $poll . ' returns: ' . $xml, LOGGER_DATA);
686
687                         if ($xml == "") {
688                                 logger("scrape_feed: XML is empty for feed ".$poll);
689                                 $network = NETWORK_PHANTOM;
690                         } else {
691                                 $data = feed_import($xml,$dummy1,$dummy2, $dummy3, true);
692
693                                 if (!is_array($data)) {
694                                         logger("scrape_feed: This doesn't seem to be a feed: ".$poll);
695                                         $network = NETWORK_PHANTOM;
696                                 } else {
697                                         if (($vcard["photo"] == "") AND ($data["header"]["author-avatar"] != ""))
698                                                 $vcard["photo"] = $data["header"]["author-avatar"];
699
700                                         if (($vcard["fn"] == "") AND ($data["header"]["author-name"] != ""))
701                                                 $vcard["fn"] = $data["header"]["author-name"];
702
703                                         if (($vcard["nick"] == "") AND ($data["header"]["author-nick"] != ""))
704                                                 $vcard["nick"] = $data["header"]["author-nick"];
705
706                                         if(!$profile AND ($data["header"]["author-link"] != "") AND !in_array($network, array("", NETWORK_FEED)))
707                                                 $profile = $data["header"]["author-link"];
708                                 }
709                         }
710
711                         // Workaround for misconfigured Friendica servers
712                         if (($network == "") AND (strstr($url, "/profile/"))) {
713                                 $noscrape = str_replace("/profile/", "/noscrape/", $url);
714                                 $noscrapejson = fetch_url($noscrape);
715                                 if ($noscrapejson) {
716
717                                         $network = NETWORK_DFRN;
718
719                                         $poco = str_replace("/profile/", "/poco/", $url);
720
721                                         $noscrapedata = json_decode($noscrapejson, true);
722
723                                         if (isset($noscrapedata["addr"]))
724                                                 $addr = $noscrapedata["addr"];
725
726                                         if (isset($noscrapedata["fn"]))
727                                                 $vcard["fn"] = $noscrapedata["fn"];
728
729                                         if (isset($noscrapedata["key"]))
730                                                 $pubkey = $noscrapedata["key"];
731
732                                         if (isset($noscrapedata["photo"]))
733                                                 $vcard["photo"] = $noscrapedata["photo"];
734
735                                         if (isset($noscrapedata["dfrn-request"]))
736                                                 $request = $noscrapedata["dfrn-request"];
737
738                                         if (isset($noscrapedata["dfrn-confirm"]))
739                                                 $confirm = $noscrapedata["dfrn-confirm"];
740
741                                         if (isset($noscrapedata["dfrn-notify"]))
742                                                 $notify = $noscrapedata["dfrn-notify"];
743
744                                         if (isset($noscrapedata["dfrn-poll"]))
745                                                 $poll = $noscrapedata["dfrn-poll"];
746
747                                 }
748                         }
749
750                         if(! $network)
751                                 $network = NETWORK_FEED;
752
753                         if(! x($vcard,'nick')) {
754                                 $vcard['nick'] = strtolower(notags(unxmlify($vcard['fn'])));
755                                 if(strpos($vcard['nick'],' '))
756                                         $vcard['nick'] = trim(substr($vcard['nick'],0,strpos($vcard['nick'],' ')));
757                         }
758                         if(! $priority)
759                                 $priority = 2;
760                 }
761         }
762
763         if(! x($vcard,'photo')) {
764                 $a = get_app();
765                 $vcard['photo'] = App::get_baseurl() . '/images/person-175.jpg' ;
766         }
767
768         if(! $profile)
769                 $profile = $url;
770
771         // No human could be associated with this link, use the URL as the contact name
772
773         if(($network === NETWORK_FEED) && ($poll) && (! x($vcard,'fn')))
774                 $vcard['fn'] = $url;
775
776         if (($notify != "") AND ($poll != "")) {
777                 $baseurl = matching_url(normalise_link($notify), normalise_link($poll));
778
779                 $baseurl2 = matching_url($baseurl, normalise_link($profile));
780                 if ($baseurl2 != "")
781                         $baseurl = $baseurl2;
782         }
783
784         if (($baseurl == "") AND ($notify != ""))
785                 $baseurl = matching_url(normalise_link($profile), normalise_link($notify));
786
787         if (($baseurl == "") AND ($poll != ""))
788                 $baseurl = matching_url(normalise_link($profile), normalise_link($poll));
789
790         if (substr($baseurl, -10) == "/index.php")
791                 $baseurl = str_replace("/index.php", "", $baseurl);
792
793         $baseurl = rtrim($baseurl, "/");
794
795         if(strpos($url,'@') AND ($addr == "") AND ($network == NETWORK_DFRN))
796                 $addr = str_replace('acct:', '', $url);
797
798         $vcard['fn'] = notags($vcard['fn']);
799         $vcard['nick'] = str_replace(' ','',notags($vcard['nick']));
800
801         $result['name'] = $vcard['fn'];
802         $result['nick'] = $vcard['nick'];
803         $result['url'] = $profile;
804         $result['addr'] = $addr;
805         $result['batch'] = $batch;
806         $result['notify'] = $notify;
807         $result['poll'] = $poll;
808         $result['request'] = $request;
809         $result['confirm'] = $confirm;
810         $result['poco'] = $poco;
811         $result['photo'] = $vcard['photo'];
812         $result['priority'] = $priority;
813         $result['network'] = $network;
814         $result['alias'] = $alias;
815         $result['pubkey'] = $pubkey;
816         $result['baseurl'] = $baseurl;
817
818         logger('probe_url: ' . print_r($result,true), LOGGER_DEBUG);
819
820         if ($level == 1) {
821                 // Trying if it maybe a diaspora account
822                 if (($result['network'] == NETWORK_FEED) OR ($result['addr'] == "")) {
823                         require_once('include/bbcode.php');
824                         $address = GetProfileUsername($url, "", true);
825                         $result2 = probe_url($address, $mode, ++$level);
826                         if ($result2['network'] != "")
827                                 $result = $result2;
828                 }
829
830                 // Maybe it's some non standard GNU Social installation (Single user, subfolder or no uri rewrite)
831                 if (($result['network'] == NETWORK_FEED) AND ($result['baseurl'] != "") AND ($result['nick'] != "")) {
832                         $addr = $result['nick'].'@'.str_replace("http://", "", $result['baseurl']);
833                         $result2 = probe_url($addr, $mode, ++$level);
834                         if (($result2['network'] != "") AND ($result2['network'] != NETWORK_FEED))
835                                 $result = $result2;
836                 }
837         }
838
839         // Only store into the cache if the value seems to be valid
840         if ($result['network'] != NETWORK_PHANTOM) {
841                 Cache::set("probe_url:".$mode.":".$original_url,serialize($result), CACHE_DAY);
842
843                 /// @todo temporary fix - we need a real contact update function that updates only changing fields
844                 /// The biggest problem is the avatar picture that could have a reduced image size.
845                 /// It should only be updated if the existing picture isn't existing anymore.
846                 if (($result['network'] != NETWORK_FEED) AND $result["addr"] AND $result["name"] AND $result["nick"])
847                         q("UPDATE `contact` SET `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
848                                 `name-date` = '%s', `uri-date` = '%s' WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
849                                 dbesc($result["addr"]),
850                                 dbesc($result["alias"]),
851                                 dbesc($result["name"]),
852                                 dbesc($result["nick"]),
853                                 dbesc(datetime_convert()),
854                                 dbesc(datetime_convert()),
855                                 dbesc(normalise_link($result['url']))
856                 );
857         }
858
859         return $result;
860 }
861
862 /**
863  * @brief Find the matching part between two url
864  *
865  * @param string $url1
866  * @param string $url2
867  * @return string The matching part
868  */
869 function matching_url($url1, $url2) {
870
871         if (($url1 == "") OR ($url2 == ""))
872                 return "";
873
874         $url1 = normalise_link($url1);
875         $url2 = normalise_link($url2);
876
877         $parts1 = parse_url($url1);
878         $parts2 = parse_url($url2);
879
880         if (!isset($parts1["host"]) OR !isset($parts2["host"]))
881                 return "";
882
883         if ($parts1["scheme"] != $parts2["scheme"])
884                 return "";
885
886         if ($parts1["host"] != $parts2["host"])
887                 return "";
888
889         if ($parts1["port"] != $parts2["port"])
890                 return "";
891
892         $match = $parts1["scheme"]."://".$parts1["host"];
893
894         if ($parts1["port"])
895                 $match .= ":".$parts1["port"];
896
897         $pathparts1 = explode("/", $parts1["path"]);
898         $pathparts2 = explode("/", $parts2["path"]);
899
900         $i = 0;
901         $path = "";
902         do {
903                 $path1 = $pathparts1[$i];
904                 $path2 = $pathparts2[$i];
905
906                 if ($path1 == $path2)
907                         $path .= $path1."/";
908
909         } while (($path1 == $path2) AND ($i++ <= count($pathparts1)));
910
911         $match .= $path;
912
913         return normalise_link($match);
914 }