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