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