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