]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
c515e066a2888ddb1b124ea6567e0b622a188e7d
[friendica.git] / src / Network / Probe.php
1 <?php
2 /**
3  * @file src/Network/Probe.php
4  */
5 namespace Friendica\Network;
6
7 /**
8  * @file src/Network/Probe.php
9  * @brief Functions for probing URL
10  */
11
12 use DOMDocument;
13 use Friendica\Core\Cache;
14 use Friendica\Core\Config;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Profile;
19 use Friendica\Protocol\Email;
20 use Friendica\Protocol\Feed;
21 use Friendica\Util\Crypto;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Network;
24 use Friendica\Util\XML;
25 use DomXPath;
26
27 require_once 'include/dba.php';
28
29 /**
30  * @brief This class contain functions for probing URL
31  *
32  */
33 class Probe
34 {
35         private static $baseurl;
36
37         /**
38          * @brief Rearrange the array so that it always has the same order
39          *
40          * @param array $data Unordered data
41          *
42          * @return array Ordered data
43          */
44         private static function rearrangeData($data)
45         {
46                 $fields = ["name", "nick", "guid", "url", "addr", "alias",
47                                 "photo", "community", "keywords", "location", "about",
48                                 "batch", "notify", "poll", "request", "confirm", "poco",
49                                 "priority", "network", "pubkey", "baseurl"];
50
51                 $newdata = [];
52                 foreach ($fields as $field) {
53                         if (isset($data[$field])) {
54                                 $newdata[$field] = $data[$field];
55                         } else {
56                                 $newdata[$field] = "";
57                         }
58                 }
59
60                 // We don't use the "priority" field anymore and replace it with a dummy.
61                 $newdata["priority"] = 0;
62
63                 return $newdata;
64         }
65
66         /**
67          * @brief Check if the hostname belongs to the own server
68          *
69          * @param string $host The hostname that is to be checked
70          *
71          * @return bool Does the testes hostname belongs to the own server?
72          */
73         private static function ownHost($host)
74         {
75                 $own_host = get_app()->get_hostname();
76
77                 $parts = parse_url($host);
78
79                 if (!isset($parts['scheme'])) {
80                         $parts = parse_url('http://'.$host);
81                 }
82
83                 if (!isset($parts['host'])) {
84                         return false;
85                 }
86                 return $parts['host'] == $own_host;
87         }
88
89         /**
90          * @brief Probes for webfinger path via "host-meta"
91          *
92          * We have to check if the servers in the future still will offer this.
93          * It seems as if it was dropped from the standard.
94          *
95          * @param string $host The host part of an url
96          *
97          * @return array with template and type of the webfinger template for JSON or XML
98          */
99         private static function hostMeta($host)
100         {
101                 // Reset the static variable
102                 self::$baseurl = '';
103
104                 $ssl_url = "https://".$host."/.well-known/host-meta";
105                 $url = "http://".$host."/.well-known/host-meta";
106
107                 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
108                 $redirects = 0;
109
110                 logger("Probing for ".$host, LOGGER_DEBUG);
111                 $xrd = null;
112
113                 $ret = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
114                 if ($ret['success']) {
115                         $xml = $ret['body'];
116                         $xrd = XML::parseString($xml, false);
117                         $host_url = 'https://'.$host;
118                 }
119
120                 if (!is_object($xrd)) {
121                         $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
122                         if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
123                                 logger("Probing timeout for ".$url, LOGGER_DEBUG);
124                                 return false;
125                         }
126                         $xml = $ret['body'];
127                         $xrd = XML::parseString($xml, false);
128                         $host_url = 'http://'.$host;
129                 }
130                 if (!is_object($xrd)) {
131                         logger("No xrd object found for ".$host, LOGGER_DEBUG);
132                         return [];
133                 }
134
135                 $links = XML::elementToArray($xrd);
136                 if (!isset($links["xrd"]["link"])) {
137                         logger("No xrd data found for ".$host, LOGGER_DEBUG);
138                         return [];
139                 }
140
141                 $lrdd = [];
142                 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
143                 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
144                 // compared to the XML webfinger. So this is commented out by now.
145                 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
146
147                 foreach ($links["xrd"]["link"] as $value => $link) {
148                         if (!empty($link["@attributes"])) {
149                                 $attributes = $link["@attributes"];
150                         } elseif ($value == "@attributes") {
151                                 $attributes = $link;
152                         } else {
153                                 continue;
154                         }
155
156                         if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
157                                 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
158
159                                 $lrdd[$type] = $attributes["template"];
160                         }
161                 }
162
163                 self::$baseurl = "http://".$host;
164
165                 logger("Probing successful for ".$host, LOGGER_DEBUG);
166
167                 return $lrdd;
168         }
169
170         /**
171          * @brief Perform Webfinger lookup and return DFRN data
172          *
173          * Given an email style address, perform webfinger lookup and
174          * return the resulting DFRN profile URL, or if no DFRN profile URL
175          * is located, returns an OStatus subscription template (prefixed
176          * with the string 'stat:' to identify it as on OStatus template).
177          * If this isn't an email style address just return $webbie.
178          * Return an empty string if email-style addresses but webfinger fails,
179          * or if the resultant personal XRD doesn't contain a supported
180          * subscription/friend-request attribute.
181          *
182          * amended 7/9/2011 to return an hcard which could save potentially loading
183          * a lengthy content page to scrape dfrn attributes
184          *
185          * @param string $webbie    Address that should be probed
186          * @param string $hcard_url Link to the hcard - is returned by reference
187          *
188          * @return string profile link
189          */
190         public static function webfingerDfrn($webbie, &$hcard_url)
191         {
192                 $profile_link = '';
193
194                 $links = self::lrdd($webbie);
195                 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
196                 if (count($links)) {
197                         foreach ($links as $link) {
198                                 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
199                                         $profile_link = $link['@attributes']['href'];
200                                 }
201                                 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
202                                         $profile_link = 'stat:'.$link['@attributes']['template'];
203                                 }
204                                 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
205                                         $hcard_url = $link['@attributes']['href'];
206                                 }
207                         }
208                 }
209                 return $profile_link;
210         }
211
212         /**
213          * @brief Check an URI for LRDD data
214          *
215          * this is a replacement for the "lrdd" function.
216          * It isn't used in this class and has some redundancies in the code.
217          * When time comes we can check the existing calls for "lrdd" if we can rework them.
218          *
219          * @param string $uri Address that should be probed
220          *
221          * @return array uri data
222          */
223         public static function lrdd($uri)
224         {
225                 $lrdd = self::hostMeta($uri);
226                 $webfinger = null;
227
228                 if (is_bool($lrdd)) {
229                         return [];
230                 }
231
232                 if (!$lrdd) {
233                         $parts = @parse_url($uri);
234                         if (!$parts) {
235                                 return [];
236                         }
237
238                         $host = $parts["host"];
239                         if (!empty($parts["port"])) {
240                                 $host .= ':'.$parts["port"];
241                         }
242
243                         $path_parts = explode("/", trim($parts["path"], "/"));
244
245                         $nick = array_pop($path_parts);
246
247                         do {
248                                 $lrdd = self::hostMeta($host);
249                                 $host .= "/".array_shift($path_parts);
250                         } while (!$lrdd && (sizeof($path_parts) > 0));
251                 }
252
253                 if (!$lrdd) {
254                         logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
255                         return [];
256                 }
257
258                 foreach ($lrdd as $type => $template) {
259                         if ($webfinger) {
260                                 continue;
261                         }
262
263                         $path = str_replace('{uri}', urlencode($uri), $template);
264                         $webfinger = self::webfinger($path, $type);
265
266                         if (!$webfinger && (strstr($uri, "@"))) {
267                                 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
268                                 $webfinger = self::webfinger($path, $type);
269                         }
270
271                         // Special treatment for Mastodon
272                         // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
273                         // But the webfinger for this format fails.
274                         if (!$webfinger && !empty($nick)) {
275                                 // Mastodon uses a "@" as prefix for usernames in their url format
276                                 $nick = ltrim($nick, '@');
277
278                                 $addr = $nick."@".$host;
279
280                                 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
281                                 $webfinger = self::webfinger($path, $type);
282                         }
283                 }
284
285                 if (!is_array($webfinger["links"])) {
286                         logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
287                         return false;
288                 }
289
290                 $data = [];
291
292                 foreach ($webfinger["links"] as $link) {
293                         $data[] = ["@attributes" => $link];
294                 }
295
296                 if (is_array($webfinger["aliases"])) {
297                         foreach ($webfinger["aliases"] as $alias) {
298                                 $data[] = ["@attributes" =>
299                                                         ["rel" => "alias",
300                                                                 "href" => $alias]];
301                         }
302                 }
303
304                 return $data;
305         }
306
307         /**
308          * @brief Fetch information (protocol endpoints and user information) about a given uri
309          *
310          * @param string  $uri     Address that should be probed
311          * @param string  $network Test for this specific network
312          * @param integer $uid     User ID for the probe (only used for mails)
313          * @param boolean $cache   Use cached values?
314          *
315          * @return array uri data
316          */
317         public static function uri($uri, $network = "", $uid = -1, $cache = true)
318         {
319                 if ($cache) {
320                         $result = Cache::get("Probe::uri:".$network.":".$uri);
321                         if (!is_null($result)) {
322                                 return $result;
323                         }
324                 }
325
326                 if ($uid == -1) {
327                         $uid = local_user();
328                 }
329
330                 $data = self::detect($uri, $network, $uid);
331
332                 if (!isset($data["url"])) {
333                         $data["url"] = $uri;
334                 }
335
336                 if (x($data, "photo")) {
337                         $data["baseurl"] = Network::getUrlMatch(normalise_link(defaults($data, "baseurl", "")), normalise_link($data["photo"]));
338                 } else {
339                         $data["photo"] = System::baseUrl().'/images/person-175.jpg';
340                 }
341
342                 if (empty($data["name"])) {
343                         if (!empty($data["nick"])) {
344                                 $data["name"] = $data["nick"];
345                         }
346
347                         if (!x($data, "name")) {
348                                 $data["name"] = $data["url"];
349                         }
350                 }
351
352                 if (empty($data["nick"])) {
353                         $data["nick"] = strtolower($data["name"]);
354
355                         if (strpos($data['nick'], ' ')) {
356                                 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
357                         }
358                 }
359
360                 if (!empty(self::$baseurl)) {
361                         $data["baseurl"] = self::$baseurl;
362                 }
363
364                 if (empty($data["network"])) {
365                         $data["network"] = NETWORK_PHANTOM;
366                 }
367
368                 $data = self::rearrangeData($data);
369
370                 // Only store into the cache if the value seems to be valid
371                 if (!in_array($data['network'], [NETWORK_PHANTOM, NETWORK_MAIL])) {
372                         Cache::set("Probe::uri:".$network.":".$uri, $data, CACHE_DAY);
373
374                         /// @todo temporary fix - we need a real contact update function that updates only changing fields
375                         /// The biggest problem is the avatar picture that could have a reduced image size.
376                         /// It should only be updated if the existing picture isn't existing anymore.
377                         /// We only update the contact when it is no probing for a specific network.
378                         if (($data['network'] != NETWORK_FEED)
379                                 && ($network == "")
380                                 && $data["name"]
381                                 && $data["nick"]
382                                 && $data["url"]
383                                 && $data["addr"]
384                                 && $data["poll"]
385                         ) {
386                                 $fields = ['name' => $data['name'],
387                                                 'nick' => $data['nick'],
388                                                 'url' => $data['url'],
389                                                 'addr' => $data['addr'],
390                                                 'photo' => $data['photo'],
391                                                 'keywords' => $data['keywords'],
392                                                 'location' => $data['location'],
393                                                 'about' => $data['about'],
394                                                 'notify' => $data['notify'],
395                                                 'network' => $data['network'],
396                                                 'server_url' => $data['baseurl']];
397
398                                 // This doesn't cover the case when a community isn't a community anymore
399                                 if (!empty($data['community']) && $data['community']) {
400                                         $fields['community'] = $data['community'];
401                                         $fields['contact-type'] = Contact::ACCOUNT_TYPE_COMMUNITY;
402                                 }
403
404                                 $fieldnames = [];
405
406                                 foreach ($fields as $key => $val) {
407                                         if (empty($val)) {
408                                                 unset($fields[$key]);
409                                         } else {
410                                                 $fieldnames[] = $key;
411                                         }
412                                 }
413
414                                 $fields['updated'] = DateTimeFormat::utcNow();
415
416                                 $condition = ['nurl' => normalise_link($data["url"])];
417
418                                 $old_fields = DBA::selectFirst('gcontact', $fieldnames, $condition);
419
420                                 // When the gcontact doesn't exist, the value "true" will trigger an insert.
421                                 // In difference to the public contacts we want to have every contact
422                                 // in the world in our global contacts.
423                                 if (!$old_fields) {
424                                         $old_fields = true;
425
426                                         // These values have to be set only on insert
427                                         $fields['photo'] = $data['photo'];
428                                         $fields['created'] = DateTimeFormat::utcNow();
429                                 }
430
431                                 DBA::update('gcontact', $fields, $condition, $old_fields);
432
433                                 $fields = ['name' => $data['name'],
434                                                 'nick' => $data['nick'],
435                                                 'url' => $data['url'],
436                                                 'addr' => $data['addr'],
437                                                 'alias' => $data['alias'],
438                                                 'keywords' => $data['keywords'],
439                                                 'location' => $data['location'],
440                                                 'about' => $data['about'],
441                                                 'batch' => $data['batch'],
442                                                 'notify' => $data['notify'],
443                                                 'poll' => $data['poll'],
444                                                 'request' => $data['request'],
445                                                 'confirm' => $data['confirm'],
446                                                 'poco' => $data['poco'],
447                                                 'network' => $data['network'],
448                                                 'pubkey' => $data['pubkey'],
449                                                 'priority' => $data['priority'],
450                                                 'writable' => true,
451                                                 'rel' => Contact::SHARING];
452
453                                 $fieldnames = [];
454
455                                 foreach ($fields as $key => $val) {
456                                         if (empty($val)) {
457                                                 unset($fields[$key]);
458                                         } else {
459                                                 $fieldnames[] = $key;
460                                         }
461                                 }
462
463                                 $condition = ['nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0];
464
465                                 // "$old_fields" will return a "false" when the contact doesn't exist.
466                                 // This won't trigger an insert. This is intended, since we only need
467                                 // public contacts for everyone we store items from.
468                                 // We don't need to store every contact on the planet.
469                                 $old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
470
471                                 $fields['name-date'] = DateTimeFormat::utcNow();
472                                 $fields['uri-date'] = DateTimeFormat::utcNow();
473                                 $fields['success_update'] = DateTimeFormat::utcNow();
474
475                                 DBA::update('contact', $fields, $condition, $old_fields);
476                         }
477                 }
478
479                 return $data;
480         }
481
482         /**
483          * @brief Switch the scheme of an url between http and https
484          *
485          * @param string $url URL
486          *
487          * @return string switched URL
488          */
489         private static function switchScheme($url)
490         {
491                 $parts = parse_url($url);
492
493                 if (!isset($parts['scheme'])) {
494                         return $url;
495                 }
496
497                 if ($parts['scheme'] == 'http') {
498                         $url = str_replace('http://', 'https://', $url);
499                 } elseif ($parts['scheme'] == 'https') {
500                         $url = str_replace('https://', 'http://', $url);
501                 }
502
503                 return $url;
504         }
505
506         /**
507          * @brief Checks if a profile url should be OStatus but only provides partial information
508          *
509          * @param array  $webfinger Webfinger data
510          * @param string $lrdd      Path template for webfinger request
511          * @param string $type      type
512          *
513          * @return array fixed webfinger data
514          */
515         private static function fixOStatus($webfinger, $lrdd, $type)
516         {
517                 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
518                         return $webfinger;
519                 }
520
521                 $is_ostatus = false;
522                 $has_key = false;
523
524                 foreach ($webfinger['links'] as $link) {
525                         if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
526                                 $is_ostatus = true;
527                         }
528                         if ($link['rel'] == 'magic-public-key') {
529                                 $has_key = true;
530                         }
531                 }
532
533                 if (!$is_ostatus || $has_key) {
534                         return $webfinger;
535                 }
536
537                 $url = self::switchScheme($webfinger['subject']);
538                 $path = str_replace('{uri}', urlencode($url), $lrdd);
539                 $webfinger2 = self::webfinger($path, $type);
540
541                 // Is the new webfinger detectable as OStatus?
542                 if (self::ostatus($webfinger2, true)) {
543                         $webfinger = $webfinger2;
544                 }
545
546                 return $webfinger;
547         }
548
549         /**
550          * @brief Fetch information (protocol endpoints and user information) about a given uri
551          *
552          * This function is only called by the "uri" function that adds caching and rearranging of data.
553          *
554          * @param string  $uri     Address that should be probed
555          * @param string  $network Test for this specific network
556          * @param integer $uid     User ID for the probe (only used for mails)
557          *
558          * @return array uri data
559          */
560         private static function detect($uri, $network, $uid)
561         {
562                 $parts = parse_url($uri);
563
564                 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
565                         $host = $parts["host"];
566                         if (!empty($parts["port"])) {
567                                 $host .= ':'.$parts["port"];
568                         }
569
570                         if ($host == 'twitter.com') {
571                                 return ["network" => NETWORK_TWITTER];
572                         }
573                         $lrdd = self::hostMeta($host);
574
575                         if (is_bool($lrdd)) {
576                                 return [];
577                         }
578
579                         $path_parts = explode("/", trim($parts["path"], "/"));
580
581                         while (!$lrdd && (sizeof($path_parts) > 1)) {
582                                 $host .= "/".array_shift($path_parts);
583                                 $lrdd = self::hostMeta($host);
584                         }
585                         if (!$lrdd) {
586                                 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
587                                 return self::feed($uri);
588                         }
589                         $nick = array_pop($path_parts);
590
591                         // Mastodon uses a "@" as prefix for usernames in their url format
592                         $nick = ltrim($nick, '@');
593
594                         $addr = $nick."@".$host;
595                 } elseif (strstr($uri, '@')) {
596                         // If the URI starts with "mailto:" then jump directly to the mail detection
597                         if (strpos($uri, 'mailto:') !== false) {
598                                 $uri = str_replace('mailto:', '', $uri);
599                                 return self::mail($uri, $uid);
600                         }
601
602                         if ($network == NETWORK_MAIL) {
603                                 return self::mail($uri, $uid);
604                         }
605                         // Remove "acct:" from the URI
606                         $uri = str_replace('acct:', '', $uri);
607
608                         $host = substr($uri, strpos($uri, '@') + 1);
609                         $nick = substr($uri, 0, strpos($uri, '@'));
610
611                         if (strpos($uri, '@twitter.com')) {
612                                 return ["network" => NETWORK_TWITTER];
613                         }
614                         $lrdd = self::hostMeta($host);
615
616                         if (is_bool($lrdd)) {
617                                 return [];
618                         }
619
620                         if (!$lrdd) {
621                                 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
622                                 return self::mail($uri, $uid);
623                         }
624                         $addr = $uri;
625                 } else {
626                         logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
627                         return false;
628                 }
629
630                 $webfinger = false;
631
632                 /// @todo Do we need the prefix "acct:" or "acct://"?
633
634                 foreach ($lrdd as $type => $template) {
635                         if ($webfinger) {
636                                 continue;
637                         }
638
639                         // At first try it with the given uri
640                         $path = str_replace('{uri}', urlencode($uri), $template);
641                         $webfinger = self::webfinger($path, $type);
642
643                         // Fix possible problems with GNU Social probing to wrong scheme
644                         $webfinger = self::fixOStatus($webfinger, $template, $type);
645
646                         // We cannot be sure that the detected address was correct, so we don't use the values
647                         if ($webfinger && ($uri != $addr)) {
648                                 $nick = "";
649                                 $addr = "";
650                         }
651
652                         // Try webfinger with the address (user@domain.tld)
653                         if (!$webfinger) {
654                                 $path = str_replace('{uri}', urlencode($addr), $template);
655                                 $webfinger = self::webfinger($path, $type);
656                         }
657
658                         // Mastodon needs to have it with "acct:"
659                         if (!$webfinger) {
660                                 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
661                                 $webfinger = self::webfinger($path, $type);
662                         }
663                 }
664
665                 if (!$webfinger) {
666                         return self::feed($uri);
667                 }
668
669                 $result = false;
670
671                 logger("Probing ".$uri, LOGGER_DEBUG);
672
673                 if (in_array($network, ["", NETWORK_DFRN])) {
674                         $result = self::dfrn($webfinger);
675                 }
676                 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
677                         $result = self::diaspora($webfinger);
678                 }
679                 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
680                         $result = self::ostatus($webfinger);
681                 }
682                 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
683                         $result = self::pumpio($webfinger, $addr);
684                 }
685                 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
686                         $result = self::feed($uri);
687                 } else {
688                         // We overwrite the detected nick with our try if the previois routines hadn't detected it.
689                         // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
690                         if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
691                                 $result["nick"] = $nick;
692                         }
693
694                         if (empty($result["addr"]) && ($addr != "")) {
695                                 $result["addr"] = $addr;
696                         }
697                 }
698
699                 if (empty($result["network"])) {
700                         $result["network"] = NETWORK_PHANTOM;
701                 }
702
703                 if (empty($result["url"])) {
704                         $result["url"] = $uri;
705                 }
706
707                 logger($uri." is ".$result["network"], LOGGER_DEBUG);
708
709                 if (empty($result["baseurl"])) {
710                         $pos = strpos($result["url"], $host);
711                         if ($pos) {
712                                 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
713                         }
714                 }
715                 return $result;
716         }
717
718         /**
719          * @brief Perform a webfinger request.
720          *
721          * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
722          *
723          * @param string $url  Address that should be probed
724          * @param string $type type
725          *
726          * @return array webfinger data
727          */
728         private static function webfinger($url, $type)
729         {
730                 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
731                 $redirects = 0;
732
733                 $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
734                 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
735                         return false;
736                 }
737                 $data = $ret['body'];
738
739                 $webfinger = json_decode($data, true);
740                 if (is_array($webfinger)) {
741                         if (!isset($webfinger["links"])) {
742                                 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
743                                 return false;
744                         }
745                         return $webfinger;
746                 }
747
748                 // If it is not JSON, maybe it is XML
749                 $xrd = XML::parseString($data, false);
750                 if (!is_object($xrd)) {
751                         logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
752                         return false;
753                 }
754
755                 $xrd_arr = XML::elementToArray($xrd);
756                 if (!isset($xrd_arr["xrd"]["link"])) {
757                         logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
758                         return false;
759                 }
760
761                 $webfinger = [];
762
763                 if (!empty($xrd_arr["xrd"]["subject"])) {
764                         $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
765                 }
766
767                 if (!empty($xrd_arr["xrd"]["alias"])) {
768                         $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
769                 }
770
771                 $webfinger["links"] = [];
772
773                 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
774                         if (!empty($data["@attributes"])) {
775                                 $attributes = $data["@attributes"];
776                         } elseif ($value == "@attributes") {
777                                 $attributes = $data;
778                         } else {
779                                 continue;
780                         }
781
782                         $webfinger["links"][] = $attributes;
783                 }
784                 return $webfinger;
785         }
786
787         /**
788          * @brief Poll the Friendica specific noscrape page.
789          *
790          * "noscrape" is a faster alternative to fetch the data from the hcard.
791          * This functionality was originally created for the directory.
792          *
793          * @param string $noscrape_url Link to the noscrape page
794          * @param array  $data         The already fetched data
795          *
796          * @return array noscrape data
797          */
798         private static function pollNoscrape($noscrape_url, $data)
799         {
800                 $ret = Network::curl($noscrape_url);
801                 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
802                         return false;
803                 }
804                 $content = $ret['body'];
805                 if (!$content) {
806                         logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
807                         return false;
808                 }
809
810                 $json = json_decode($content, true);
811                 if (!is_array($json)) {
812                         logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
813                         return false;
814                 }
815
816                 if (!empty($json["fn"])) {
817                         $data["name"] = $json["fn"];
818                 }
819
820                 if (!empty($json["addr"])) {
821                         $data["addr"] = $json["addr"];
822                 }
823
824                 if (!empty($json["nick"])) {
825                         $data["nick"] = $json["nick"];
826                 }
827
828                 if (!empty($json["guid"])) {
829                         $data["guid"] = $json["guid"];
830                 }
831
832                 if (!empty($json["comm"])) {
833                         $data["community"] = $json["comm"];
834                 }
835
836                 if (!empty($json["tags"])) {
837                         $keywords = implode(" ", $json["tags"]);
838                         if ($keywords != "") {
839                                 $data["keywords"] = $keywords;
840                         }
841                 }
842
843                 $location = Profile::formatLocation($json);
844                 if ($location) {
845                         $data["location"] = $location;
846                 }
847
848                 if (!empty($json["about"])) {
849                         $data["about"] = $json["about"];
850                 }
851
852                 if (!empty($json["key"])) {
853                         $data["pubkey"] = $json["key"];
854                 }
855
856                 if (!empty($json["photo"])) {
857                         $data["photo"] = $json["photo"];
858                 }
859
860                 if (!empty($json["dfrn-request"])) {
861                         $data["request"] = $json["dfrn-request"];
862                 }
863
864                 if (!empty($json["dfrn-confirm"])) {
865                         $data["confirm"] = $json["dfrn-confirm"];
866                 }
867
868                 if (!empty($json["dfrn-notify"])) {
869                         $data["notify"] = $json["dfrn-notify"];
870                 }
871
872                 if (!empty($json["dfrn-poll"])) {
873                         $data["poll"] = $json["dfrn-poll"];
874                 }
875
876                 return $data;
877         }
878
879         /**
880          * @brief Check for valid DFRN data
881          *
882          * @param array $data DFRN data
883          *
884          * @return int Number of errors
885          */
886         public static function validDfrn($data)
887         {
888                 $errors = 0;
889                 if (!isset($data['key'])) {
890                         $errors ++;
891                 }
892                 if (!isset($data['dfrn-request'])) {
893                         $errors ++;
894                 }
895                 if (!isset($data['dfrn-confirm'])) {
896                         $errors ++;
897                 }
898                 if (!isset($data['dfrn-notify'])) {
899                         $errors ++;
900                 }
901                 if (!isset($data['dfrn-poll'])) {
902                         $errors ++;
903                 }
904                 return $errors;
905         }
906
907         /**
908          * @brief Fetch data from a DFRN profile page and via "noscrape"
909          *
910          * @param string $profile_link Link to the profile page
911          *
912          * @return array profile data
913          */
914         public static function profile($profile_link)
915         {
916                 $data = [];
917
918                 logger("Check profile ".$profile_link, LOGGER_DEBUG);
919
920                 // Fetch data via noscrape - this is faster
921                 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
922                 $data = self::pollNoscrape($noscrape_url, $data);
923
924                 if (!isset($data["notify"])
925                         || !isset($data["confirm"])
926                         || !isset($data["request"])
927                         || !isset($data["poll"])
928                         || !isset($data["poco"])
929                         || !isset($data["name"])
930                         || !isset($data["photo"])
931                 ) {
932                         $data = self::pollHcard($profile_link, $data, true);
933                 }
934
935                 $prof_data = [];
936                 $prof_data["addr"]         = $data["addr"];
937                 $prof_data["nick"]         = $data["nick"];
938                 $prof_data["dfrn-request"] = $data["request"];
939                 $prof_data["dfrn-confirm"] = $data["confirm"];
940                 $prof_data["dfrn-notify"]  = $data["notify"];
941                 $prof_data["dfrn-poll"]    = $data["poll"];
942                 $prof_data["dfrn-poco"]    = $data["poco"];
943                 $prof_data["photo"]        = $data["photo"];
944                 $prof_data["fn"]           = $data["name"];
945                 $prof_data["key"]          = $data["pubkey"];
946
947                 // This logging is for temporarily debugging reasons
948                 if (!isset($data["poco"])) {
949                         logger('POCO not defined for ' . $profile_link . ' - ' . System::callstack(), LOGGER_DEBUG);
950                 }
951
952                 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
953
954                 return $prof_data;
955         }
956
957         /**
958          * @brief Check for DFRN contact
959          *
960          * @param array $webfinger Webfinger data
961          *
962          * @return array DFRN data
963          */
964         private static function dfrn($webfinger)
965         {
966                 $hcard_url = "";
967                 $data = [];
968                 foreach ($webfinger["links"] as $link) {
969                         if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
970                                 $data["network"] = NETWORK_DFRN;
971                         } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
972                                 $data["poll"] = $link["href"];
973                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
974                                 $data["url"] = $link["href"];
975                         } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
976                                 $hcard_url = $link["href"];
977                         } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
978                                 $data["poco"] = $link["href"];
979                         } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
980                                 $data["photo"] = $link["href"];
981                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
982                                 $data["baseurl"] = trim($link["href"], '/');
983                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
984                                 $data["guid"] = $link["href"];
985                         } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
986                                 $data["pubkey"] = base64_decode($link["href"]);
987
988                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
989                                 if (strstr($data["pubkey"], 'RSA ')) {
990                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
991                                 }
992                         }
993                 }
994
995                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
996                         foreach ($webfinger["aliases"] as $alias) {
997                                 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
998                                         $data["alias"] = $alias;
999                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1000                                         $data["addr"] = substr($alias, 5);
1001                                 }
1002                         }
1003                 }
1004
1005                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1006                         $data["addr"] = substr($webfinger["subject"], 5);
1007                 }
1008
1009                 if (!isset($data["network"]) || ($hcard_url == "")) {
1010                         return false;
1011                 }
1012
1013                 // Fetch data via noscrape - this is faster
1014                 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1015                 $data = self::pollNoscrape($noscrape_url, $data);
1016
1017                 if (isset($data["notify"])
1018                         && isset($data["confirm"])
1019                         && isset($data["request"])
1020                         && isset($data["poll"])
1021                         && isset($data["name"])
1022                         && isset($data["photo"])
1023                 ) {
1024                         return $data;
1025                 }
1026
1027                 $data = self::pollHcard($hcard_url, $data, true);
1028
1029                 return $data;
1030         }
1031
1032         /**
1033          * @brief Poll the hcard page (Diaspora and Friendica specific)
1034          *
1035          * @param string  $hcard_url Link to the hcard page
1036          * @param array   $data      The already fetched data
1037          * @param boolean $dfrn      Poll DFRN specific data
1038          *
1039          * @return array hcard data
1040          */
1041         private static function pollHcard($hcard_url, $data, $dfrn = false)
1042         {
1043                 $ret = Network::curl($hcard_url);
1044                 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1045                         return false;
1046                 }
1047                 $content = $ret['body'];
1048                 if (!$content) {
1049                         return false;
1050                 }
1051
1052                 $doc = new DOMDocument();
1053                 if (!@$doc->loadHTML($content)) {
1054                         return false;
1055                 }
1056
1057                 $xpath = new DomXPath($doc);
1058
1059                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1060                 if (!is_object($vcards)) {
1061                         return false;
1062                 }
1063
1064                 if (!isset($data["baseurl"])) {
1065                         $data["baseurl"] = "";
1066                 }
1067
1068                 if ($vcards->length > 0) {
1069                         $vcard = $vcards->item(0);
1070
1071                         // We have to discard the guid from the hcard in favour of the guid from lrdd
1072                         // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1073                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1074                         if (($search->length > 0) && empty($data["guid"])) {
1075                                 $data["guid"] = $search->item(0)->nodeValue;
1076                         }
1077
1078                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1079                         if ($search->length > 0) {
1080                                 $data["nick"] = $search->item(0)->nodeValue;
1081                         }
1082
1083                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1084                         if ($search->length > 0) {
1085                                 $data["name"] = $search->item(0)->nodeValue;
1086                         }
1087
1088                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1089                         if ($search->length > 0) {
1090                                 $data["searchable"] = $search->item(0)->nodeValue;
1091                         }
1092
1093                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1094                         if ($search->length > 0) {
1095                                 $data["pubkey"] = $search->item(0)->nodeValue;
1096                                 if (strstr($data["pubkey"], 'RSA ')) {
1097                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1098                                 }
1099                         }
1100
1101                         $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1102                         if ($search->length > 0) {
1103                                 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1104                         }
1105                 }
1106
1107                 $avatar = [];
1108                 if (!empty($vcard)) {
1109                         $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1110                         foreach ($photos as $photo) {
1111                                 $attr = [];
1112                                 foreach ($photo->attributes as $attribute) {
1113                                         $attr[$attribute->name] = trim($attribute->value);
1114                                 }
1115
1116                                 if (isset($attr["src"]) && isset($attr["width"])) {
1117                                         $avatar[$attr["width"]] = $attr["src"];
1118                                 }
1119
1120                                 // We don't have a width. So we just take everything that we got.
1121                                 // This is a Hubzilla workaround which doesn't send a width.
1122                                 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1123                                         $avatar[] = $attr["src"];
1124                                 }
1125                         }
1126                 }
1127
1128                 if (sizeof($avatar)) {
1129                         ksort($avatar);
1130                         $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1131                 }
1132
1133                 if ($dfrn) {
1134                         // Poll DFRN specific data
1135                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1136                         if ($search->length > 0) {
1137                                 foreach ($search as $link) {
1138                                         //$data["request"] = $search->item(0)->nodeValue;
1139                                         $attr = [];
1140                                         foreach ($link->attributes as $attribute) {
1141                                                 $attr[$attribute->name] = trim($attribute->value);
1142                                         }
1143
1144                                         $data[substr($attr["rel"], 5)] = $attr["href"];
1145                                 }
1146                         }
1147
1148                         // Older Friendica versions had used the "uid" field differently than newer versions
1149                         if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1150                                 unset($data["guid"]);
1151                         }
1152                 }
1153
1154
1155                 return $data;
1156         }
1157
1158         /**
1159          * @brief Check for Diaspora contact
1160          *
1161          * @param array $webfinger Webfinger data
1162          *
1163          * @return array Diaspora data
1164          */
1165         private static function diaspora($webfinger)
1166         {
1167                 $hcard_url = "";
1168                 $data = [];
1169                 foreach ($webfinger["links"] as $link) {
1170                         if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1171                                 $hcard_url = $link["href"];
1172                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1173                                 $data["baseurl"] = trim($link["href"], '/');
1174                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1175                                 $data["guid"] = $link["href"];
1176                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1177                                 $data["url"] = $link["href"];
1178                         } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1179                                 $data["poll"] = $link["href"];
1180                         } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1181                                 $data["poco"] = $link["href"];
1182                         } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1183                                 $data["notify"] = $link["href"];
1184                         } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1185                                 $data["pubkey"] = base64_decode($link["href"]);
1186
1187                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1188                                 if (strstr($data["pubkey"], 'RSA ')) {
1189                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1190                                 }
1191                         }
1192                 }
1193
1194                 if (!isset($data["url"]) || ($hcard_url == "")) {
1195                         return false;
1196                 }
1197
1198                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1199                         foreach ($webfinger["aliases"] as $alias) {
1200                                 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1201                                         $data["alias"] = $alias;
1202                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1203                                         $data["addr"] = substr($alias, 5);
1204                                 }
1205                         }
1206                 }
1207
1208                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1209                         $data["addr"] = substr($webfinger["subject"], 5);
1210                 }
1211
1212                 // Fetch further information from the hcard
1213                 $data = self::pollHcard($hcard_url, $data);
1214
1215                 if (!$data) {
1216                         return false;
1217                 }
1218
1219                 if (isset($data["url"])
1220                         && isset($data["guid"])
1221                         && isset($data["baseurl"])
1222                         && isset($data["pubkey"])
1223                         && ($hcard_url != "")
1224                 ) {
1225                         $data["network"] = NETWORK_DIASPORA;
1226
1227                         // The Diaspora handle must always be lowercase
1228                         if (!empty($data["addr"])) {
1229                                 $data["addr"] = strtolower($data["addr"]);
1230                         }
1231
1232                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1233                         $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1234                         $data["batch"]  = $data["baseurl"] . "/receive/public";
1235                 } else {
1236                         return false;
1237                 }
1238
1239                 return $data;
1240         }
1241
1242         /**
1243          * @brief Check for OStatus contact
1244          *
1245          * @param array $webfinger Webfinger data
1246          * @param bool  $short     Short detection mode
1247          *
1248          * @return array|bool OStatus data or "false" on error or "true" on short mode
1249          */
1250         private static function ostatus($webfinger, $short = false)
1251         {
1252                 $data = [];
1253
1254                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1255                         foreach ($webfinger["aliases"] as $alias) {
1256                                 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1257                                         $data["addr"] = str_replace('acct:', '', $alias);
1258                                 }
1259                         }
1260                 }
1261
1262                 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1263                         && !strstr(normalise_link($webfinger["subject"]), "http://")
1264                 ) {
1265                         $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1266                 }
1267
1268                 $pubkey = "";
1269                 if (is_array($webfinger["links"])) {
1270                         foreach ($webfinger["links"] as $link) {
1271                                 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1272                                         && ($link["type"] == "text/html")
1273                                         && ($link["href"] != "")
1274                                 ) {
1275                                         $data["url"] = $link["href"];
1276                                 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1277                                         $data["notify"] = $link["href"];
1278                                 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1279                                         $data["poll"] = $link["href"];
1280                                 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1281                                         $pubkey = $link["href"];
1282
1283                                         if (substr($pubkey, 0, 5) === 'data:') {
1284                                                 if (strstr($pubkey, ',')) {
1285                                                         $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1286                                                 } else {
1287                                                         $pubkey = substr($pubkey, 5);
1288                                                 }
1289                                         } elseif (normalise_link($pubkey) == 'http://') {
1290                                                 $ret = Network::curl($pubkey);
1291                                                 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1292                                                         return false;
1293                                                 }
1294                                                 $pubkey = $ret['body'];
1295                                         }
1296
1297                                         $key = explode(".", $pubkey);
1298
1299                                         if (sizeof($key) >= 3) {
1300                                                 $m = base64url_decode($key[1]);
1301                                                 $e = base64url_decode($key[2]);
1302                                                 $data["pubkey"] = Crypto::meToPem($m, $e);
1303                                         }
1304                                 }
1305                         }
1306                 }
1307
1308                 if (isset($data["notify"]) && isset($data["pubkey"])
1309                         && isset($data["poll"])
1310                         && isset($data["url"])
1311                 ) {
1312                         $data["network"] = NETWORK_OSTATUS;
1313                 } else {
1314                         return false;
1315                 }
1316
1317                 if ($short) {
1318                         return true;
1319                 }
1320
1321                 // Fetch all additional data from the feed
1322                 $ret = Network::curl($data["poll"]);
1323                 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1324                         return false;
1325                 }
1326                 $feed = $ret['body'];
1327                 $dummy1 = null;
1328                 $dummy2 = null;
1329                 $dummy2 = null;
1330                 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1331                 if (!$feed_data) {
1332                         return false;
1333                 }
1334
1335                 if (!empty($feed_data["header"]["author-name"])) {
1336                         $data["name"] = $feed_data["header"]["author-name"];
1337                 }
1338                 if (!empty($feed_data["header"]["author-nick"])) {
1339                         $data["nick"] = $feed_data["header"]["author-nick"];
1340                 }
1341                 if (!empty($feed_data["header"]["author-avatar"])) {
1342                         $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1343                 }
1344                 if (!empty($feed_data["header"]["author-id"])) {
1345                         $data["alias"] = $feed_data["header"]["author-id"];
1346                 }
1347                 if (!empty($feed_data["header"]["author-location"])) {
1348                         $data["location"] = $feed_data["header"]["author-location"];
1349                 }
1350                 if (!empty($feed_data["header"]["author-about"])) {
1351                         $data["about"] = $feed_data["header"]["author-about"];
1352                 }
1353                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1354                 // So we take the value that we just fetched, although the other one worked as well
1355                 if (!empty($feed_data["header"]["author-link"])) {
1356                         $data["url"] = $feed_data["header"]["author-link"];
1357                 }
1358
1359                 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1360                         $data['url'] = $data["alias"];
1361                         $data["alias"] = '';
1362                 }
1363
1364                 /// @todo Fetch location and "about" from the feed as well
1365                 return $data;
1366         }
1367
1368         /**
1369          * @brief Fetch data from a pump.io profile page
1370          *
1371          * @param string $profile_link Link to the profile page
1372          *
1373          * @return array profile data
1374          */
1375         private static function pumpioProfileData($profile_link)
1376         {
1377                 $doc = new DOMDocument();
1378                 if (!@$doc->loadHTMLFile($profile_link)) {
1379                         return false;
1380                 }
1381
1382                 $xpath = new DomXPath($doc);
1383
1384                 $data = [];
1385
1386                 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1387
1388                 if ($data["name"] == '') {
1389                         // This is ugly - but pump.io doesn't seem to know a better way for it
1390                         $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1391                         $pos = strpos($data["name"], chr(10));
1392                         if ($pos) {
1393                                 $data["name"] = trim(substr($data["name"], 0, $pos));
1394                         }
1395                 }
1396
1397                 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1398
1399                 if ($data["location"] == '') {
1400                         $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1401                 }
1402
1403                 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1404
1405                 if ($data["about"] == '') {
1406                         $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1407                 }
1408
1409                 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1410                 if (!$avatar) {
1411                         $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1412                 }
1413                 if ($avatar) {
1414                         foreach ($avatar->attributes as $attribute) {
1415                                 if ($attribute->name == "src") {
1416                                         $data["photo"] = trim($attribute->value);
1417                                 }
1418                         }
1419                 }
1420
1421                 return $data;
1422         }
1423
1424         /**
1425          * @brief Check for pump.io contact
1426          *
1427          * @param array $webfinger Webfinger data
1428          *
1429          * @return array pump.io data
1430          */
1431         private static function pumpio($webfinger, $addr)
1432         {
1433                 $data = [];
1434                 foreach ($webfinger["links"] as $link) {
1435                         if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1436                                 && ($link["type"] == "text/html")
1437                                 && ($link["href"] != "")
1438                         ) {
1439                                 $data["url"] = $link["href"];
1440                         } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1441                                 $data["notify"] = $link["href"];
1442                         } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1443                                 $data["poll"] = $link["href"];
1444                         } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1445                                 $data["dialback"] = $link["href"];
1446                         }
1447                 }
1448                 if (isset($data["poll"]) && isset($data["notify"])
1449                         && isset($data["dialback"])
1450                         && isset($data["url"])
1451                 ) {
1452                         // by now we use these fields only for the network type detection
1453                         // So we unset all data that isn't used at the moment
1454                         unset($data["dialback"]);
1455
1456                         $data["network"] = NETWORK_PUMPIO;
1457                 } else {
1458                         return false;
1459                 }
1460
1461                 $profile_data = self::pumpioProfileData($data["url"]);
1462
1463                 if (!$profile_data) {
1464                         return false;
1465                 }
1466
1467                 $data = array_merge($data, $profile_data);
1468
1469                 if (($addr != '') && ($data['name'] != '')) {
1470                         $name = trim(str_replace($addr, '', $data['name']));
1471                         if ($name != '') {
1472                                 $data['name'] = $name;
1473                         }
1474                 }
1475
1476                 return $data;
1477         }
1478
1479         /**
1480          * @brief Check page for feed link
1481          *
1482          * @param string $url Page link
1483          *
1484          * @return string feed link
1485          */
1486         private static function getFeedLink($url)
1487         {
1488                 $doc = new DOMDocument();
1489
1490                 if (!@$doc->loadHTMLFile($url)) {
1491                         return false;
1492                 }
1493
1494                 $xpath = new DomXPath($doc);
1495
1496                 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1497                 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1498                 if (!is_object($feeds)) {
1499                         return false;
1500                 }
1501
1502                 if ($feeds->length == 0) {
1503                         return false;
1504                 }
1505
1506                 $feed_url = "";
1507
1508                 foreach ($feeds as $feed) {
1509                         $attr = [];
1510                         foreach ($feed->attributes as $attribute) {
1511                                 $attr[$attribute->name] = trim($attribute->value);
1512                         }
1513
1514                         if ($feed_url == "") {
1515                                 $feed_url = $attr["href"];
1516                         }
1517                 }
1518
1519                 return $feed_url;
1520         }
1521
1522         /**
1523          * @brief Check for feed contact
1524          *
1525          * @param string  $url   Profile link
1526          * @param boolean $probe Do a probe if the page contains a feed link
1527          *
1528          * @return array feed data
1529          */
1530         private static function feed($url, $probe = true)
1531         {
1532                 $ret = Network::curl($url);
1533                 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1534                         return false;
1535                 }
1536                 $feed = $ret['body'];
1537                 $dummy1 = $dummy2 = $dummy3 = null;
1538                 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1539
1540                 if (!$feed_data) {
1541                         if (!$probe) {
1542                                 return false;
1543                         }
1544
1545                         $feed_url = self::getFeedLink($url);
1546
1547                         if (!$feed_url) {
1548                                 return false;
1549                         }
1550
1551                         return self::feed($feed_url, false);
1552                 }
1553
1554                 if (!empty($feed_data["header"]["author-name"])) {
1555                         $data["name"] = $feed_data["header"]["author-name"];
1556                 }
1557
1558                 if (!empty($feed_data["header"]["author-nick"])) {
1559                         $data["nick"] = $feed_data["header"]["author-nick"];
1560                 }
1561
1562                 if (!empty($feed_data["header"]["author-avatar"])) {
1563                         $data["photo"] = $feed_data["header"]["author-avatar"];
1564                 }
1565
1566                 if (!empty($feed_data["header"]["author-id"])) {
1567                         $data["alias"] = $feed_data["header"]["author-id"];
1568                 }
1569
1570                 $data["url"] = $url;
1571                 $data["poll"] = $url;
1572
1573                 if (!empty($feed_data["header"]["author-link"])) {
1574                         $data["baseurl"] = $feed_data["header"]["author-link"];
1575                 } else {
1576                         $data["baseurl"] = $data["url"];
1577                 }
1578
1579                 $data["network"] = NETWORK_FEED;
1580
1581                 return $data;
1582         }
1583
1584         /**
1585          * @brief Check for mail contact
1586          *
1587          * @param string  $uri Profile link
1588          * @param integer $uid User ID
1589          *
1590          * @return array mail data
1591          */
1592         private static function mail($uri, $uid)
1593         {
1594                 if (!Network::isEmailDomainValid($uri)) {
1595                         return false;
1596                 }
1597
1598                 if ($uid == 0) {
1599                         return false;
1600                 }
1601
1602                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1603
1604                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1605
1606                 if (!DBA::isResult($x) || !DBA::isResult($r)) {
1607                         return false;
1608                 }
1609
1610                 $mailbox = Email::constructMailboxName($r[0]);
1611                 $password = '';
1612                 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1613                 $mbox = Email::connect($mailbox, $r[0]['user'], $password);
1614                 if (!$mbox) {
1615                         return false;
1616                 }
1617
1618                 $msgs = Email::poll($mbox, $uri);
1619                 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1620
1621                 if (!count($msgs)) {
1622                         return false;
1623                 }
1624
1625                 $phost = substr($uri, strpos($uri, '@') + 1);
1626
1627                 $data = [];
1628                 $data["addr"]    = $uri;
1629                 $data["network"] = NETWORK_MAIL;
1630                 $data["name"]    = substr($uri, 0, strpos($uri, '@'));
1631                 $data["nick"]    = $data["name"];
1632                 $data["photo"]   = Network::lookupAvatarByEmail($uri);
1633                 $data["url"]     = 'mailto:'.$uri;
1634                 $data["notify"]  = 'smtp '.random_string();
1635                 $data["poll"]    = 'email '.random_string();
1636
1637                 $x = Email::messageMeta($mbox, $msgs[0]);
1638                 if (stristr($x[0]->from, $uri)) {
1639                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1640                 } elseif (stristr($x[0]->to, $uri)) {
1641                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1642                 }
1643                 if (isset($adr)) {
1644                         foreach ($adr as $feadr) {
1645                                 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1646                                         &&(strcasecmp($feadr->host, $phost) == 0)
1647                                         && (strlen($feadr->personal))
1648                                 ) {
1649                                         $personal = imap_mime_header_decode($feadr->personal);
1650                                         $data["name"] = "";
1651                                         foreach ($personal as $perspart) {
1652                                                 if ($perspart->charset != "default") {
1653                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1654                                                 } else {
1655                                                         $data["name"] .= $perspart->text;
1656                                                 }
1657                                         }
1658
1659                                         $data["name"] = notags($data["name"]);
1660                                 }
1661                         }
1662                 }
1663                 if (!empty($mbox)) {
1664                         imap_close($mbox);
1665                 }
1666
1667                 return $data;
1668         }
1669
1670         /**
1671          * @brief Mix two paths together to possibly fix missing parts
1672          *
1673          * @param string $avatar Path to the avatar
1674          * @param string $base   Another path that is hopefully complete
1675          *
1676          * @return string fixed avatar path
1677          */
1678         public static function fixAvatar($avatar, $base)
1679         {
1680                 $base_parts = parse_url($base);
1681
1682                 // Remove all parts that could create a problem
1683                 unset($base_parts['path']);
1684                 unset($base_parts['query']);
1685                 unset($base_parts['fragment']);
1686
1687                 $avatar_parts = parse_url($avatar);
1688
1689                 // Now we mix them
1690                 $parts = array_merge($base_parts, $avatar_parts);
1691
1692                 // And put them together again
1693                 $scheme   = isset($parts['scheme'])   ? $parts['scheme'] . '://' : '';
1694                 $host     = isset($parts['host'])     ? $parts['host']           : '';
1695                 $port     = isset($parts['port'])     ? ':' . $parts['port']     : '';
1696                 $path     = isset($parts['path'])     ? $parts['path']           : '';
1697                 $query    = isset($parts['query'])    ? '?' . $parts['query']    : '';
1698                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1699
1700                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1701
1702                 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);
1703
1704                 return $fixed;
1705         }
1706 }