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