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