]> git.mxchange.org Git - friendica.git/blob - include/Probe.php
4dcbc7841156546c2688e74cc6eb4f1aedef7048
[friendica.git] / include / Probe.php
1 <?php
2 /**
3  * @brief This class contain functions for probing URL
4  *
5  */
6
7 use \Friendica\Core\Config;
8 use \Friendica\Core\PConfig;
9
10 require_once("include/feed.php");
11 require_once('include/email.php');
12 require_once('include/network.php');
13
14 class Probe {
15
16         private function rearrange_data($data) {
17                 $fields = array("name", "nick", "guid", "url", "addr", "alias",
18                                 "photo", "community", "keywords", "location", "about",
19                                 "batch", "notify", "poll", "request", "confirm", "poco",
20                                 "priority", "network", "pubkey", "baseurl");
21
22                 $newdata = array();
23                 foreach ($fields AS $field)
24                         if (isset($data[$field]))
25                                 $newdata[$field] = $data[$field];
26                         else
27                                 $newdata[$field] = "";
28
29                 // We don't use the "priority" field anymore and replace it with a dummy.
30                 $newdata["priority"] = 0;
31
32                 return $newdata;
33         }
34
35         /**
36          * @brief Probes for XRD data
37          *
38          * @return array
39          *      'lrdd' => Link to LRDD endpoint
40          *      'lrdd-xml' => Link to LRDD endpoint in XML format
41          *      'lrdd-json' => Link to LRDD endpoint in JSON format
42          */
43         private function xrd($host) {
44
45                 $ssl_url = "https://".$host."/.well-known/host-meta";
46                 $url = "http://".$host."/.well-known/host-meta";
47
48                 $xrd_timeout = Config::get('system','xrd_timeout', 20);
49                 $redirects = 0;
50
51                 $xml = fetch_url($ssl_url, false, $redirects, $xrd_timeout, "application/xrd+xml");
52                 $xrd = parse_xml_string($xml, false);
53
54                 if (!is_object($xrd)) {
55                         $xml = fetch_url($url, false, $redirects, $xrd_timeout, "application/xrd+xml");
56                         $xrd = parse_xml_string($xml, false);
57                 }
58                 if (!is_object($xrd))
59                         return false;
60
61                 $links = xml::element_to_array($xrd);
62                 if (!isset($links["xrd"]["link"]))
63                         return false;
64
65                 $xrd_data = array();
66                 foreach ($links["xrd"]["link"] AS $value => $link) {
67                         if (isset($link["@attributes"]))
68                                 $attributes = $link["@attributes"];
69                         elseif ($value == "@attributes")
70                                 $attributes = $link;
71                         else
72                                 continue;
73
74                         if (($attributes["rel"] == "lrdd") AND
75                                 ($attributes["type"] == "application/xrd+xml"))
76                                 $xrd_data["lrdd-xml"] = $attributes["template"];
77                         elseif (($attributes["rel"] == "lrdd") AND
78                                 ($attributes["type"] == "application/json"))
79                                 $xrd_data["lrdd-json"] = $attributes["template"];
80                         elseif ($attributes["rel"] == "lrdd")
81                                 $xrd_data["lrdd"] = $attributes["template"];
82                 }
83                 return $xrd_data;
84         }
85
86         public static function uri($uri, $network = "", $uid = 0, $cache = true) {
87
88                 if ($cache) {
89                         $result = Cache::get("probe_url:".$network.":".$uri);
90                         if (!is_null($result)) {
91                                 $result = unserialize($result);
92                                 return $result;
93                         }
94                 }
95
96                 if ($uid == 0)
97                         $uid = local_user();
98
99                 $data = self::detect($uri, $network, $uid);
100
101                 if (!isset($data["url"]))
102                         $data["url"] = $uri;
103
104                 if ($data["photo"] != "")
105                         $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
106                 else
107                         $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
108
109                 if (!isset($data["name"]))
110                         $data["name"] = $data["url"];
111
112                 if (!isset($data["nick"]))
113                         $data["nick"] = strtolower($data["name"]);
114
115                 if (!isset($data["network"]))
116                         $data["network"] = NETWORK_PHANTOM;
117
118                 $data = self::rearrange_data($data);
119
120                 // Only store into the cache if the value seems to be valid
121                 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
122                         Cache::set("probe_url:".$network.":".$uri,serialize($data), CACHE_DAY);
123
124                         /// @todo temporary fix - we need a real contact update function that updates only changing fields
125                         /// The biggest problem is the avatar picture that could have a reduced image size.
126                         /// It should only be updated if the existing picture isn't existing anymore.
127                         if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
128                                 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
129                                 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
130                                                 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
131                                         WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
132                                         dbesc($data["name"]),
133                                         dbesc($data["nick"]),
134                                         dbesc($data["url"]),
135                                         dbesc($data["addr"]),
136                                         dbesc($data["notify"]),
137                                         dbesc($data["poll"]),
138                                         dbesc($data["alias"]),
139                                         dbesc(datetime_convert()),
140                                         dbesc(normalise_link($data['url']))
141                         );
142                 }
143                 return $data;
144         }
145
146         private function detect($uri, $network, $uid) {
147                 if (strstr($uri, '@')) {
148                         // If the URI starts with "mailto:" then jum directly to the mail detection
149                         if (strpos($url,'mailto:') !== false) {
150                                 $uri = str_replace('mailto:', '', $url);
151                                 return self::mail($uri, $uid);
152                         }
153
154                         if ($network == NETWORK_MAIL)
155                                 return self::mail($uri, $uid);
156
157                         // Remove "acct:" from the URI
158                         $uri = str_replace('acct:', '', $uri);
159
160                         $host = substr($uri,strpos($uri, '@') + 1);
161                         $nick = substr($uri,0, strpos($uri, '@'));
162
163                         $lrdd = self::xrd($host);
164                         if (!$lrdd)
165                                 return self::mail($uri, $uid);
166
167                         $addr = $uri;
168                 } else {
169                         $parts = parse_url($uri);
170                         if (!isset($parts["scheme"]) OR
171                                 !isset($parts["host"]) OR
172                                 !isset($parts["path"]))
173                                 return false;
174
175                         // todo: Ports?
176                         $host = $parts["host"];
177                         $lrdd = self::xrd($host);
178
179                         $path_parts = explode("/", trim($parts["path"], "/"));
180
181                         while (!$lrdd AND (sizeof($path_parts) > 1)) {
182                                 $host .= "/".array_shift($path_parts);
183                                 $lrdd = self::xrd($host);
184                         }
185                         if (!$lrdd)
186                                 return self::feed($uri);
187
188                         $nick = array_pop($path_parts);
189                         $addr = $nick."@".$host;
190                 }
191
192                 $webfinger = false;
193
194                 /// @todo Do we need the prefix "acct:" or "acct://"?
195
196                 foreach ($lrdd AS $key => $link) {
197                         if ($webfinger)
198                                 continue;
199
200                         if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
201                                 continue;
202
203                         $path = str_replace('{uri}', urlencode($addr), $link);
204
205                         $webfinger = self::webfinger($path);
206                 }
207                 if (!$webfinger)
208                         return self::feed($uri);
209
210                 $result = false;
211
212                 logger("Probing ".$uri, LOGGER_DEBUG);
213
214                 if (in_array($network, array("", NETWORK_DFRN)))
215                         $result = self::dfrn($webfinger);
216                 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
217                         $result = self::diaspora($webfinger);
218                 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
219                         $result = self::ostatus($webfinger);
220                 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
221                         $result = self::pumpio($webfinger);
222                 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
223                         $result = self::feed($uri);
224                 else {
225                         // We overwrite the detected nick with our try if the previois routines hadn't detected it.
226                         // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
227                         if (!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " ")))
228                                 $result["nick"] = $nick;
229
230                         if (!isset($result["addr"]) OR ($result["addr"] == ""))
231                                 $result["addr"] = $addr;
232                 }
233
234                 logger($uri." is ".$result["network"], LOGGER_DEBUG);
235
236                 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
237                         $pos = strpos($result["url"], $host);
238                         if ($pos)
239                                 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
240                 }
241
242                 return $result;
243         }
244
245         private function webfinger($url) {
246
247                 $xrd_timeout = Config::get('system','xrd_timeout', 20);
248                 $redirects = 0;
249
250                 $data = fetch_url($url, false, $redirects, $xrd_timeout, "application/xrd+xml");
251                 $xrd = parse_xml_string($data, false);
252
253                 if (!is_object($xrd)) {
254                         // If it is not XML, maybe it is JSON
255                         $webfinger = json_decode($data, true);
256
257                         if (!isset($webfinger["links"]))
258                                 return false;
259
260                         return $webfinger;
261                 }
262
263                 $xrd_arr = xml::element_to_array($xrd);
264                 if (!isset($xrd_arr["xrd"]["link"]))
265                         return false;
266
267                 $webfinger = array();
268
269                 if (isset($xrd_arr["xrd"]["subject"]))
270                         $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
271
272                 if (isset($xrd_arr["xrd"]["alias"]))
273                         $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
274
275                 $webfinger["links"] = array();
276
277                 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
278                         if (isset($data["@attributes"]))
279                                 $attributes = $data["@attributes"];
280                         elseif ($value == "@attributes")
281                                 $attributes = $data;
282                         else
283                                 continue;
284
285                         $webfinger["links"][] = $attributes;
286                 }
287                 return $webfinger;
288         }
289
290         private function poll_noscrape($noscrape, $data) {
291                 $content = fetch_url($noscrape);
292                 if (!$content)
293                         return false;
294
295                 $json = json_decode($content, true);
296                 if (!is_array($json))
297                         return false;
298
299                 if (isset($json["fn"]))
300                         $data["name"] = $json["fn"];
301
302                 if (isset($json["addr"]))
303                         $data["addr"] = $json["addr"];
304
305                 if (isset($json["nick"]))
306                         $data["nick"] = $json["nick"];
307
308                 if (isset($json["comm"]))
309                         $data["community"] = $json["comm"];
310
311                 if (isset($json["tags"])) {
312                         $keywords = implode(" ", $json["tags"]);
313                         if ($keywords != "")
314                                 $data["keywords"] = $keywords;
315                 }
316
317                 $location = formatted_location($json);
318                 if ($location)
319                         $data["location"] = $location;
320
321                 if (isset($json["about"]))
322                         $data["about"] = $json["about"];
323
324                 if (isset($json["key"]))
325                         $data["pubkey"] = $json["key"];
326
327                 if (isset($json["photo"]))
328                         $data["photo"] = $json["photo"];
329
330                 if (isset($json["dfrn-request"]))
331                         $data["request"] = $json["dfrn-request"];
332
333                 if (isset($json["dfrn-confirm"]))
334                         $data["confirm"] = $json["dfrn-confirm"];
335
336                 if (isset($json["dfrn-notify"]))
337                         $data["notify"] = $json["dfrn-notify"];
338
339                 if (isset($json["dfrn-poll"]))
340                         $data["poll"] = $json["dfrn-poll"];
341
342                 return $data;
343         }
344
345         public static function valid_dfrn($data) {
346                 $errors = 0;
347                 if(!isset($data['key']))
348                         $errors ++;
349                 if(!isset($data['dfrn-request']))
350                         $errors ++;
351                 if(!isset($data['dfrn-confirm']))
352                         $errors ++;
353                 if(!isset($data['dfrn-notify']))
354                         $errors ++;
355                 if(!isset($data['dfrn-poll']))
356                         $errors ++;
357                 return $errors;
358         }
359
360         public static function profile($profile) {
361
362                 $data = array();
363
364                 // Fetch data via noscrape - this is faster
365                 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
366                 $data = self::poll_noscrape($noscrape, $data);
367
368                 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
369                         !isset($data["request"]) OR !isset($data["poll"]) OR
370                         !isset($data["poco"]) OR !isset($data["name"]) OR
371                         !isset($data["photo"]))
372                         $data = self::poll_hcard($profile, $data, true);
373
374                 $prof_data = array();
375                 $prof_data["addr"] = $data["addr"];
376                 $prof_data["nick"] = $data["nick"];
377                 $prof_data["dfrn-request"] = $data["request"];
378                 $prof_data["dfrn-confirm"] = $data["confirm"];
379                 $prof_data["dfrn-notify"] = $data["notify"];
380                 $prof_data["dfrn-poll"] = $data["poll"];
381                 $prof_data["dfrn-poco"] = $data["poco"];
382                 $prof_data["photo"] = $data["photo"];
383                 $prof_data["fn"] = $data["name"];
384                 $prof_data["key"] = $data["pubkey"];
385
386                 return $prof_data;
387         }
388
389         private function dfrn($webfinger) {
390
391                 $hcard = "";
392                 $data = array();
393                 foreach ($webfinger["links"] AS $link) {
394                         if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
395                                 $data["network"] = NETWORK_DFRN;
396                         elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
397                                 $data["poll"] = $link["href"];
398                         elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
399                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
400                                 $data["url"] = $link["href"];
401                         elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
402                                 $hcard = $link["href"];
403                         elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
404                                 $data["poco"] = $link["href"];
405                         elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
406                                 $data["photo"] = $link["href"];
407
408                         elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
409                                 $data["baseurl"] = trim($link["href"], '/');
410                         elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
411                                 $data["guid"] = $link["href"];
412                         elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
413                                 $data["pubkey"] = base64_decode($link["href"]);
414
415                                 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
416                                 if (strstr($data["pubkey"], 'RSA '))
417                                         $data["pubkey"] = rsatopem($data["pubkey"]);
418                         }
419                 }
420
421                 if (!isset($data["network"]) OR ($hcard == ""))
422                         return false;
423
424                 // Fetch data via noscrape - this is faster
425                 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
426                 $data = self::poll_noscrape($noscrape, $data);
427
428                 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
429                         isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
430                         return $data;
431
432                 $data = self::poll_hcard($hcard, $data, true);
433
434                 return $data;
435         }
436
437         private function poll_hcard($hcard, $data, $dfrn = false) {
438
439                 $doc = new DOMDocument();
440                 if (!@$doc->loadHTMLFile($hcard))
441                         return false;
442
443                 $xpath = new DomXPath($doc);
444
445                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
446                 if (!is_object($vcards))
447                         return false;
448
449                 if ($vcards->length == 0)
450                         return false;
451
452                 $vcard = $vcards->item(0);
453
454                 // We have to discard the guid from the hcard in favour of the guid from lrdd
455                 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
456                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
457                 if (($search->length > 0) AND ($data["guid"] == ""))
458                         $data["guid"] = $search->item(0)->nodeValue;
459
460                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
461                 if ($search->length > 0)
462                         $data["nick"] = $search->item(0)->nodeValue;
463
464                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
465                 if ($search->length > 0)
466                         $data["name"] = $search->item(0)->nodeValue;
467
468                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
469                 if ($search->length > 0)
470                         $data["searchable"] = $search->item(0)->nodeValue;
471
472                 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
473                 if ($search->length > 0) {
474                         $data["pubkey"] = $search->item(0)->nodeValue;
475                         if (strstr($data["pubkey"], 'RSA '))
476                                 $data["pubkey"] = rsatopem($data["pubkey"]);
477                 }
478
479                 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
480                 if ($search->length > 0)
481                         $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
482
483                 $avatar = array();
484                 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
485                 foreach ($photos AS $photo) {
486                         $attr = array();
487                         foreach ($photo->attributes as $attribute)
488                                 $attr[$attribute->name] = trim($attribute->value);
489
490                         if (isset($attr["src"]) AND isset($attr["width"]))
491                                 $avatar[$attr["width"]] = $attr["src"];
492                 }
493
494                 if (sizeof($avatar)) {
495                         ksort($avatar);
496                         $data["photo"] = array_pop($avatar);
497                 }
498
499                 if ($dfrn) {
500                         // Poll DFRN specific data
501                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
502                         if ($search->length > 0) {
503                                 foreach ($search AS $link) {
504                                         //$data["request"] = $search->item(0)->nodeValue;
505                                         $attr = array();
506                                         foreach ($link->attributes as $attribute)
507                                                 $attr[$attribute->name] = trim($attribute->value);
508
509                                         $data[substr($attr["rel"], 5)] = $attr["href"];
510                                 }
511                         }
512
513                         // Older Friendica versions had used the "uid" field differently than newer versions
514                         if ($data["nick"] == $data["guid"])
515                                 unset($data["guid"]);
516                 }
517
518
519                 return $data;
520         }
521
522         private function diaspora($webfinger) {
523
524                 $hcard = "";
525                 $data = array();
526                 foreach ($webfinger["links"] AS $link) {
527                         if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
528                                 $hcard = $link["href"];
529                         elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
530                                 $data["baseurl"] = trim($link["href"], '/');
531                         elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
532                                 $data["guid"] = $link["href"];
533                         elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
534                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
535                                 $data["url"] = $link["href"];
536                         elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
537                                 $data["poll"] = $link["href"];
538                         elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
539                                 $data["poco"] = $link["href"];
540                         elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
541                                 $data["notify"] = $link["href"];
542                         elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
543                                 $data["pubkey"] = base64_decode($link["href"]);
544
545                                 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
546                                 if (strstr($data["pubkey"], 'RSA '))
547                                         $data["pubkey"] = rsatopem($data["pubkey"]);
548                         }
549                 }
550
551                 if (!isset($data["url"]) OR ($hcard == ""))
552                         return false;
553
554                 if (is_array($webfinger["aliases"]))
555                         foreach ($webfinger["aliases"] AS $alias)
556                                 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
557                                         $data["alias"] = $alias;
558
559                 // Fetch further information from the hcard
560                 $data = self::poll_hcard($hcard, $data);
561
562                 if (!$data)
563                         return false;
564
565                 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
566                         isset($data["pubkey"]) AND ($hcard != "")) {
567                         $data["network"] = NETWORK_DIASPORA;
568
569                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
570                         $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
571                         $data["batch"] = $data["baseurl"]."/receive/public";
572                 } else
573                         return false;
574
575                 return $data;
576         }
577
578         private function ostatus($webfinger) {
579
580                 $pubkey = "";
581                 $data = array();
582                 foreach ($webfinger["links"] AS $link) {
583                         if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
584                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
585                                 $data["url"] = $link["href"];
586                         elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
587                                 $data["notify"] = $link["href"];
588                         elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
589                                 $data["poll"] = $link["href"];
590                         elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
591                                 $pubkey = $link["href"];
592
593                                 if (substr($pubkey, 0, 5) === 'data:') {
594                                         if (strstr($pubkey, ','))
595                                                 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
596                                         else
597                                                 $pubkey = substr($pubkey, 5);
598                                 } else
599                                         $pubkey = fetch_url($pubkey);
600
601                                 $key = explode(".", $pubkey);
602
603                                 if (sizeof($key) >= 3) {
604                                         $m = base64url_decode($key[1]);
605                                         $e = base64url_decode($key[2]);
606                                         $data["pubkey"] = metopem($m,$e);
607                                 }
608
609                         }
610                 }
611
612                 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
613                         isset($data["poll"]) AND isset($data["url"])) {
614                         $data["network"] = NETWORK_OSTATUS;
615                 } else
616                         return false;
617
618                 // Fetch all additional data from the feed
619                 $feed = fetch_url($data["poll"]);
620                 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
621                 if (!$feed_data)
622                         return false;
623
624                 if ($feed_data["header"]["author-name"] != "")
625                         $data["name"] = $feed_data["header"]["author-name"];
626
627                 if ($feed_data["header"]["author-nick"] != "")
628                         $data["nick"] = $feed_data["header"]["author-nick"];
629
630                 if ($feed_data["header"]["author-avatar"] != "")
631                         $data["photo"] = $feed_data["header"]["author-avatar"];
632
633                 if ($feed_data["header"]["author-id"] != "")
634                         $data["alias"] = $feed_data["header"]["author-id"];
635
636                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
637                 // So we take the value that we just fetched, although the other one worked as well
638                 if ($feed_data["header"]["author-link"] != "")
639                         $data["url"] = $feed_data["header"]["author-link"];
640
641                 /// @todo Fetch location and "about" from the feed as well
642                 return $data;
643         }
644
645         private function pumpio_profile_data($profile) {
646
647                 $doc = new DOMDocument();
648                 if (!@$doc->loadHTMLFile($profile))
649                         return false;
650
651                 $xpath = new DomXPath($doc);
652
653                 $data = array();
654
655                 // This is ugly - but pump.io doesn't seem to know a better way for it
656                 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
657                 $pos = strpos($data["name"], chr(10));
658                 if ($pos)
659                         $data["name"] = trim(substr($data["name"], 0, $pos));
660
661                 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
662                 if ($avatar)
663                         foreach ($avatar->attributes as $attribute)
664                                 if ($attribute->name == "src")
665                                         $data["photo"] = trim($attribute->value);
666
667                 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
668                 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
669
670                 return $data;
671         }
672
673         private function pumpio($webfinger) {
674                 $data = array();
675                 foreach ($webfinger["links"] AS $link) {
676                         if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
677                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
678                                 $data["url"] = $link["href"];
679                         elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
680                                 $data["activity-inbox"] = $link["href"];
681                         elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
682                                 $data["activity-outbox"] = $link["href"];
683                         elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
684                                 $data["dialback"] = $link["href"];
685                 }
686                 if (isset($data["activity-inbox"]) AND isset($data["activity-outbox"]) AND
687                         isset($data["dialback"]) AND isset($data["url"])) {
688
689                         // by now we use these fields only for the network type detection
690                         // So we unset all data that isn't used at the moment
691                         unset($data["activity-inbox"]);
692                         unset($data["activity-outbox"]);
693                         unset($data["dialback"]);
694
695                         $data["network"] = NETWORK_PUMPIO;
696                 } else
697                         return false;
698
699                 $profile_data = self::pumpio_profile_data($data["url"]);
700
701                 if (!$profile_data)
702                         return false;
703
704                 $data = array_merge($data, $profile_data);
705
706                 return $data;
707         }
708
709         private function get_feed_link($url) {
710                 $doc = new DOMDocument();
711
712                 if (!@$doc->loadHTMLFile($url))
713                         return false;
714
715                 $xpath = new DomXPath($doc);
716
717                 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
718                 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
719                 if (!is_object($feeds))
720                         return false;
721
722                 if ($feeds->length == 0)
723                         return false;
724
725                 $feed_url = "";
726
727                 foreach ($feeds AS $feed) {
728                         $attr = array();
729                         foreach ($feed->attributes as $attribute)
730                         $attr[$attribute->name] = trim($attribute->value);
731
732                         if ($feed_url == "")
733                                 $feed_url = $attr["href"];
734                 }
735
736                 return $feed_url;
737         }
738
739         private function feed($url, $probe = true) {
740                 $feed = fetch_url($url);
741                 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
742
743                 if (!$feed_data) {
744                         if (!$probe)
745                                 return false;
746
747                         $feed_url = self::get_feed_link($url);
748
749                         if (!$feed_url)
750                                 return false;
751
752                         return self::feed($feed_url, false);
753                 }
754
755                 if ($feed_data["header"]["author-name"] != "")
756                         $data["name"] = $feed_data["header"]["author-name"];
757
758                 if ($feed_data["header"]["author-nick"] != "")
759                         $data["nick"] = $feed_data["header"]["author-nick"];
760
761                 if ($feed_data["header"]["author-avatar"] != "")
762                         $data["photo"] = $feed_data["header"]["author-avatar"];
763
764                 if ($feed_data["header"]["author-id"] != "")
765                         $data["alias"] = $feed_data["header"]["author-id"];
766
767                 $data["url"] = $url;
768                 $data["poll"] = $url;
769
770                 if ($feed_data["header"]["author-link"] != "")
771                         $data["baseurl"] = $feed_data["header"]["author-link"];
772                 else
773                         $data["baseurl"] = $data["url"];
774
775                 $data["network"] = NETWORK_FEED;
776
777                 return $data;
778         }
779
780         private function mail($uri, $uid) {
781
782                 if (!validate_email($uri))
783                         return false;
784
785                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
786
787                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
788
789                 if(count($x) && count($r)) {
790                         $mailbox = construct_mailbox_name($r[0]);
791                         $password = '';
792                         openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
793                         $mbox = email_connect($mailbox,$r[0]['user'], $password);
794                         if(!mbox)
795                                 return false;
796                 }
797
798                 $msgs = email_poll($mbox, $uri);
799                 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
800
801                 if (!count($msgs))
802                         return false;
803
804                 $data = array();
805
806                 $data["addr"] = $uri;
807                 $data["network"] = NETWORK_MAIL;
808                 $data["name"] = substr($uri, 0, strpos($uri,'@'));
809                 $data["nick"] = $data["name"];
810                 $data["photo"] = avatar_img($uri);
811
812                 $phost = substr($uri, strpos($uri,'@') + 1);
813                 $data["url"] = 'http://'.$phost."/".$data["nick"];
814                 $data["notify"] = 'smtp '.random_string();
815                 $data["poll"] = 'email '.random_string();
816
817                 $x = email_msg_meta($mbox, $msgs[0]);
818                 if(stristr($x[0]->from, $uri))
819                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
820                 elseif(stristr($x[0]->to, $uri))
821                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
822                 if(isset($adr)) {
823                         foreach($adr as $feadr) {
824                                 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
825                                         &&(strcasecmp($feadr->host, $phost) == 0)
826                                         && (strlen($feadr->personal))) {
827
828                                         $personal = imap_mime_header_decode($feadr->personal);
829                                         $data["name"] = "";
830                                         foreach($personal as $perspart)
831                                                 if ($perspart->charset != "default")
832                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
833                                                 else
834                                                         $data["name"] .= $perspart->text;
835
836                                         $data["name"] = notags($data["name"]);
837                                 }
838                         }
839                 }
840                 imap_close($mbox);
841
842                 return $data;
843         }
844 }
845 ?>