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