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