]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
2b9e51e4f677d6c43973c098f4fe0c0ed6b24dbe
[friendica.git] / include / socgraph.php
1 <?php
2 /**
3  * @file include/socgraph.php
4  *
5  * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6  * @todo Fetch profile data from profile page for Redmatrix users
7  * @todo Detect if it is a forum
8  */
9
10 use Friendica\App;
11 use Friendica\Core\System;
12 use Friendica\Core\Config;
13 use Friendica\Core\Worker;
14 use Friendica\Network\Probe;
15
16 require_once 'include/datetime.php';
17 require_once 'include/probe.php';
18 require_once 'include/network.php';
19 require_once 'include/html2bbcode.php';
20 require_once 'include/Contact.php';
21 require_once 'include/Photo.php';
22
23 /**
24  * @brief Fetch POCO data
25  *
26  * @param integer $cid Contact ID
27  * @param integer $uid User ID
28  * @param integer $zcid Global Contact ID
29  * @param integer $url POCO address that should be polled
30  *
31  * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
32  * and add the entries to the gcontact (Global Contact) table, or update existing entries
33  * if anything (name or photo) has changed.
34  * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
35  *
36  * Once the global contact is stored add (if necessary) the contact linkage which associates
37  * the given uid, cid to the global contact entry. There can be many uid/cid combinations
38  * pointing to the same global contact id.
39  *
40  */
41 function poco_load($cid, $uid = 0, $zcid = 0, $url = null) {
42         // Call the function "poco_load_worker" via the worker
43         Worker::add(PRIORITY_LOW, "discover_poco", "poco_load", (int)$cid, (int)$uid, (int)$zcid, $url);
44 }
45
46 /**
47  * @brief Fetch POCO data from the worker
48  *
49  * @param integer $cid Contact ID
50  * @param integer $uid User ID
51  * @param integer $zcid Global Contact ID
52  * @param integer $url POCO address that should be polled
53  *
54  */
55 function poco_load_worker($cid, $uid, $zcid, $url) {
56         $a = get_app();
57
58         if ($cid) {
59                 if ((! $url) || (! $uid)) {
60                         $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
61                                 intval($cid)
62                         );
63                         if (dbm::is_result($r)) {
64                                 $url = $r[0]['poco'];
65                                 $uid = $r[0]['uid'];
66                         }
67                 }
68                 if (! $uid) {
69                         return;
70                 }
71         }
72
73         if (! $url) {
74                 return;
75         }
76
77         $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ;
78
79         logger('poco_load: ' . $url, LOGGER_DEBUG);
80
81         $s = fetch_url($url);
82
83         logger('poco_load: returns ' . $s, LOGGER_DATA);
84
85         logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
86
87         if (($a->get_curl_code() > 299) || (! $s)) {
88                 return;
89         }
90
91         $j = json_decode($s);
92
93         logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
94
95         if (! isset($j->entry)) {
96                 return;
97         }
98
99         $total = 0;
100         foreach ($j->entry as $entry) {
101
102                 $total ++;
103                 $profile_url = '';
104                 $profile_photo = '';
105                 $connect_url = '';
106                 $name = '';
107                 $network = '';
108                 $updated = NULL_DATE;
109                 $location = '';
110                 $about = '';
111                 $keywords = '';
112                 $gender = '';
113                 $contact_type = -1;
114                 $generation = 0;
115
116                 $name = $entry->displayName;
117
118                 if (isset($entry->urls)) {
119                         foreach ($entry->urls as $url) {
120                                 if ($url->type == 'profile') {
121                                         $profile_url = $url->value;
122                                         continue;
123                                 }
124                                 if ($url->type == 'webfinger') {
125                                         $connect_url = str_replace('acct:' , '', $url->value);
126                                         continue;
127                                 }
128                         }
129                 }
130                 if (isset($entry->photos)) {
131                         foreach ($entry->photos as $photo) {
132                                 if ($photo->type == 'profile') {
133                                         $profile_photo = $photo->value;
134                                         continue;
135                                 }
136                         }
137                 }
138
139                 if (isset($entry->updated)) {
140                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
141                 }
142
143                 if (isset($entry->network)) {
144                         $network = $entry->network;
145                 }
146
147                 if (isset($entry->currentLocation)) {
148                         $location = $entry->currentLocation;
149                 }
150
151                 if (isset($entry->aboutMe)) {
152                         $about = html2bbcode($entry->aboutMe);
153                 }
154
155                 if (isset($entry->gender)) {
156                         $gender = $entry->gender;
157                 }
158
159                 if (isset($entry->generation) && ($entry->generation > 0)) {
160                         $generation = ++$entry->generation;
161                 }
162
163                 if (isset($entry->tags)) {
164                         foreach ($entry->tags as $tag) {
165                                 $keywords = implode(", ", $tag);
166                         }
167                 }
168
169                 if (isset($entry->contactType) && ($entry->contactType >= 0)) {
170                         $contact_type = $entry->contactType;
171                 }
172
173                 $gcontact = array("url" => $profile_url,
174                                 "name" => $name,
175                                 "network" => $network,
176                                 "photo" => $profile_photo,
177                                 "about" => $about,
178                                 "location" => $location,
179                                 "gender" => $gender,
180                                 "keywords" => $keywords,
181                                 "connect" => $connect_url,
182                                 "updated" => $updated,
183                                 "contact-type" => $contact_type,
184                                 "generation" => $generation);
185
186                 try {
187                         $gcontact = sanitize_gcontact($gcontact);
188                         $gcid = update_gcontact($gcontact);
189
190                         link_gcontact($gcid, $uid, $cid, $zcid);
191                 } catch (Exception $e) {
192                         logger($e->getMessage(), LOGGER_DEBUG);
193                 }
194         }
195         logger("poco_load: loaded $total entries",LOGGER_DEBUG);
196
197         q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
198                 intval($cid),
199                 intval($uid),
200                 intval($zcid)
201         );
202
203 }
204 /**
205  * @brief Sanitize the given gcontact data
206  *
207  * @param array $gcontact array with gcontact data
208  * @throw Exception
209  *
210  * Generation:
211  *  0: No definition
212  *  1: Profiles on this server
213  *  2: Contacts of profiles on this server
214  *  3: Contacts of contacts of profiles on this server
215  *  4: ...
216  *
217  */
218 function sanitize_gcontact($gcontact) {
219
220         if ($gcontact['url'] == "") {
221                 throw new Exception('URL is empty');
222         }
223
224         $urlparts = parse_url($gcontact['url']);
225         if (!isset($urlparts["scheme"])) {
226                 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
227         }
228
229         if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
230                                                 "identi.ca", "alpha.app.net"))) {
231                 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
232         }
233
234         // Don't store the statusnet connector as network
235         // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
236         if ($gcontact['network'] == NETWORK_STATUSNET) {
237                 $gcontact['network'] = "";
238         }
239
240         // Assure that there are no parameter fragments in the profile url
241         if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
242                 $gcontact['url'] = clean_contact_url($gcontact['url']);
243         }
244
245         $alternate = poco_alternate_ostatus_url($gcontact['url']);
246
247         // The global contacts should contain the original picture, not the cached one
248         if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
249                 $gcontact['photo'] = "";
250         }
251
252         if (!isset($gcontact['network'])) {
253                 $r = q("SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
254                         dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
255                 );
256                 if (dbm::is_result($r)) {
257                         $gcontact['network'] = $r[0]["network"];
258                 }
259
260                 if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
261                         $r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
262                                 dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
263                         );
264                         if (dbm::is_result($r)) {
265                                 $gcontact['network'] = $r[0]["network"];
266                         }
267                 }
268         }
269
270         $gcontact['server_url'] = '';
271         $gcontact['network'] = '';
272
273         $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
274                 dbesc(normalise_link($gcontact['url']))
275         );
276
277         if (dbm::is_result($x)) {
278                 if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
279                         $gcontact['network'] = $x[0]["network"];
280                 }
281                 if ($gcontact['updated'] <= NULL_DATE) {
282                         $gcontact['updated'] = $x[0]["updated"];
283                 }
284                 if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
285                         $gcontact['server_url'] = $x[0]["server_url"];
286                 }
287                 if (!isset($gcontact['addr'])) {
288                         $gcontact['addr'] = $x[0]["addr"];
289                 }
290         }
291
292         if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
293                 && poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
294                 $data = Probe::uri($gcontact['url']);
295
296                 if ($data["network"] == NETWORK_PHANTOM) {
297                         throw new Exception('Probing for URL '.$gcontact['url'].' failed');
298                 }
299
300                 $orig_profile = $gcontact['url'];
301
302                 $gcontact["server_url"] = $data["baseurl"];
303
304                 $gcontact = array_merge($gcontact, $data);
305
306                 if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
307                         // Delete the old entry - if it exists
308                         $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
309                         if (dbm::is_result($r)) {
310                                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
311                                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
312                         }
313                 }
314         }
315
316         if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
317                 throw new Exception('No name and photo for URL '.$gcontact['url']);
318         }
319
320         if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
321                 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
322         }
323
324         if (!isset($gcontact['server_url'])) {
325                 // We check the server url to be sure that it is a real one
326                 $server_url = poco_detect_server($gcontact['url']);
327
328                 // We are now sure that it is a correct URL. So we use it in the future
329                 if ($server_url != "") {
330                         $gcontact['server_url'] = $server_url;
331                 }
332         }
333
334         // The server URL doesn't seem to be valid, so we don't store it.
335         if (!poco_check_server($gcontact['server_url'], $gcontact['network'])) {
336                 $gcontact['server_url'] = "";
337         }
338
339         return $gcontact;
340 }
341
342 /**
343  * @brief Link the gcontact entry with user, contact and global contact
344  *
345  * @param integer $gcid Global contact ID
346  * @param integer $cid Contact ID
347  * @param integer $uid User ID
348  * @param integer $zcid Global Contact ID
349  * *
350  */
351 function link_gcontact($gcid, $uid = 0, $cid = 0, $zcid = 0) {
352
353         if ($gcid <= 0) {
354                 return;
355         }
356
357         $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
358                 intval($cid),
359                 intval($uid),
360                 intval($gcid),
361                 intval($zcid)
362         );
363
364         if (!dbm::is_result($r)) {
365                 q("INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
366                         intval($cid),
367                         intval($uid),
368                         intval($gcid),
369                         intval($zcid),
370                         dbesc(datetime_convert())
371                 );
372         } else {
373                 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
374                         dbesc(datetime_convert()),
375                         intval($cid),
376                         intval($uid),
377                         intval($gcid),
378                         intval($zcid)
379                 );
380         }
381 }
382
383 function poco_reachable($profile, $server = "", $network = "", $force = false) {
384
385         if ($server == "") {
386                 $server = poco_detect_server($profile);
387         }
388
389         if ($server == "") {
390                 return true;
391         }
392
393         return poco_check_server($server, $network, $force);
394 }
395
396 function poco_detect_server($profile) {
397
398         // Try to detect the server path based upon some known standard paths
399         $server_url = "";
400
401         if ($server_url == "") {
402                 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
403                 if ($friendica != $profile) {
404                         $server_url = $friendica;
405                         $network = NETWORK_DFRN;
406                 }
407         }
408
409         if ($server_url == "") {
410                 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
411                 if ($diaspora != $profile) {
412                         $server_url = $diaspora;
413                         $network = NETWORK_DIASPORA;
414                 }
415         }
416
417         if ($server_url == "") {
418                 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
419                 if ($red != $profile) {
420                         $server_url = $red;
421                         $network = NETWORK_DIASPORA;
422                 }
423         }
424
425         // Mastodon
426         if ($server_url == "") {
427                 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
428                 if ($mastodon != $profile) {
429                         $server_url = $mastodon;
430                         $network = NETWORK_OSTATUS;
431                 }
432         }
433
434         // Numeric OStatus variant
435         if ($server_url == "") {
436                 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
437                 if ($ostatus != $profile) {
438                         $server_url = $ostatus;
439                         $network = NETWORK_OSTATUS;
440                 }
441         }
442
443         // Wild guess
444         if ($server_url == "") {
445                 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
446                 if ($base != $profile) {
447                         $server_url = $base;
448                         $network = NETWORK_PHANTOM;
449                 }
450         }
451
452         if ($server_url == "") {
453                 return "";
454         }
455
456         $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
457                 dbesc(normalise_link($server_url)));
458         if (dbm::is_result($r)) {
459                 return $server_url;
460         }
461
462         // Fetch the host-meta to check if this really is a server
463         $serverret = z_fetch_url($server_url."/.well-known/host-meta");
464         if (!$serverret["success"]) {
465                 return "";
466         }
467
468         return $server_url;
469 }
470
471 function poco_alternate_ostatus_url($url) {
472         return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
473 }
474
475 function poco_last_updated($profile, $force = false) {
476
477         $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
478                         dbesc(normalise_link($profile)));
479
480         if (!dbm::is_result($gcontacts)) {
481                 return false;
482         }
483
484         $contact = array("url" => $profile);
485
486         if ($gcontacts[0]["created"] <= NULL_DATE) {
487                 $contact['created'] = datetime_convert();
488         }
489
490         if ($force) {
491                 $server_url = normalise_link(poco_detect_server($profile));
492         }
493
494         if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
495                 $server_url = $gcontacts[0]["server_url"];
496         }
497
498         if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
499                 $server_url = normalise_link(poco_detect_server($profile));
500         }
501
502         if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
503                 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
504                 return false;
505         }
506
507         if ($server_url != "") {
508                 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
509                         if ($force) {
510                                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
511                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
512                         }
513
514                         logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
515                         return false;
516                 }
517                 $contact['server_url'] = $server_url;
518         }
519
520         if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
521                 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
522                         dbesc(normalise_link($server_url)));
523
524                 if ($server) {
525                         $contact['network'] = $server[0]["network"];
526                 } else {
527                         return false;
528                 }
529         }
530
531         // noscrape is really fast so we don't cache the call.
532         if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
533
534                 //  Use noscrape if possible
535                 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
536
537                 if ($server) {
538                         $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
539
540                         if ($noscraperet["success"] && ($noscraperet["body"] != "")) {
541
542                                 $noscrape = json_decode($noscraperet["body"], true);
543
544                                 if (is_array($noscrape)) {
545                                         $contact["network"] = $server[0]["network"];
546
547                                         if (isset($noscrape["fn"])) {
548                                                 $contact["name"] = $noscrape["fn"];
549                                         }
550                                         if (isset($noscrape["comm"])) {
551                                                 $contact["community"] = $noscrape["comm"];
552                                         }
553                                         if (isset($noscrape["tags"])) {
554                                                 $keywords = implode(" ", $noscrape["tags"]);
555                                                 if ($keywords != "") {
556                                                         $contact["keywords"] = $keywords;
557                                                 }
558                                         }
559
560                                         $location = formatted_location($noscrape);
561                                         if ($location) {
562                                                 $contact["location"] = $location;
563                                         }
564                                         if (isset($noscrape["dfrn-notify"])) {
565                                                 $contact["notify"] = $noscrape["dfrn-notify"];
566                                         }
567                                         // Remove all fields that are not present in the gcontact table
568                                         unset($noscrape["fn"]);
569                                         unset($noscrape["key"]);
570                                         unset($noscrape["homepage"]);
571                                         unset($noscrape["comm"]);
572                                         unset($noscrape["tags"]);
573                                         unset($noscrape["locality"]);
574                                         unset($noscrape["region"]);
575                                         unset($noscrape["country-name"]);
576                                         unset($noscrape["contacts"]);
577                                         unset($noscrape["dfrn-request"]);
578                                         unset($noscrape["dfrn-confirm"]);
579                                         unset($noscrape["dfrn-notify"]);
580                                         unset($noscrape["dfrn-poll"]);
581
582                                         // Set the date of the last contact
583                                         /// @todo By now the function "update_gcontact" doesn't work with this field
584                                         //$contact["last_contact"] = datetime_convert();
585
586                                         $contact = array_merge($contact, $noscrape);
587
588                                         update_gcontact($contact);
589
590                                         if (trim($noscrape["updated"]) != "") {
591                                                 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
592                                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
593
594                                                 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
595
596                                                 return $noscrape["updated"];
597                                         }
598                                 }
599                         }
600                 }
601         }
602
603         // If we only can poll the feed, then we only do this once a while
604         if (!$force && !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
605                 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
606
607                 update_gcontact($contact);
608                 return $gcontacts[0]["updated"];
609         }
610
611         $data = Probe::uri($profile);
612
613         // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
614         // Then check the other link and delete this one
615         if (($data["network"] == NETWORK_OSTATUS) && poco_alternate_ostatus_url($profile) &&
616                 (normalise_link($profile) == normalise_link($data["alias"])) &&
617                 (normalise_link($profile) != normalise_link($data["url"]))) {
618
619                 // Delete the old entry
620                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
621                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
622
623                 $gcontact = array_merge($gcontacts[0], $data);
624
625                 $gcontact["server_url"] = $data["baseurl"];
626
627                 try {
628                         $gcontact = sanitize_gcontact($gcontact);
629                         update_gcontact($gcontact);
630
631                         poco_last_updated($data["url"], $force);
632                 } catch (Exception $e) {
633                         logger($e->getMessage(), LOGGER_DEBUG);
634                 }
635
636                 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
637                 return false;
638         }
639
640         if (($data["poll"] == "") || (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
641                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
642                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
643
644                 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
645                 return false;
646         }
647
648         $contact = array_merge($contact, $data);
649
650         $contact["server_url"] = $data["baseurl"];
651
652         update_gcontact($contact);
653
654         $feedret = z_fetch_url($data["poll"]);
655
656         if (!$feedret["success"]) {
657                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
658                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
659
660                 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
661                 return false;
662         }
663
664         $doc = new DOMDocument();
665         @$doc->loadXML($feedret["body"]);
666
667         $xpath = new DomXPath($doc);
668         $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
669
670         $entries = $xpath->query('/atom:feed/atom:entry');
671
672         $last_updated = "";
673
674         foreach ($entries as $entry) {
675                 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
676                 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
677
678                 if ($last_updated < $published)
679                         $last_updated = $published;
680
681                 if ($last_updated < $updated)
682                         $last_updated = $updated;
683         }
684
685         // Maybe there aren't any entries. Then check if it is a valid feed
686         if ($last_updated == "") {
687                 if ($xpath->query('/atom:feed')->length > 0) {
688                         $last_updated = NULL_DATE;
689                 }
690         }
691         q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
692                 dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
693
694         if (($gcontacts[0]["generation"] == 0)) {
695                 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
696                         dbesc(normalise_link($profile)));
697         }
698
699         logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
700
701         return($last_updated);
702 }
703
704 function poco_do_update($created, $updated, $last_failure,  $last_contact) {
705         $now = strtotime(datetime_convert());
706
707         if ($updated > $last_contact) {
708                 $contact_time = strtotime($updated);
709         } else {
710                 $contact_time = strtotime($last_contact);
711         }
712
713         $failure_time = strtotime($last_failure);
714         $created_time = strtotime($created);
715
716         // If there is no "created" time then use the current time
717         if ($created_time <= 0) {
718                 $created_time = $now;
719         }
720
721         // If the last contact was less than 24 hours then don't update
722         if (($now - $contact_time) < (60 * 60 * 24)) {
723                 return false;
724         }
725
726         // If the last failure was less than 24 hours then don't update
727         if (($now - $failure_time) < (60 * 60 * 24)) {
728                 return false;
729         }
730
731         // If the last contact was less than a week ago and the last failure is older than a week then don't update
732         //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
733         //      return false;
734
735         // If the last contact time was more than a week ago and the contact was created more than a week ago, then only try once a week
736         if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
737                 return false;
738         }
739
740         // If the last contact time was more than a month ago and the contact was created more than a month ago, then only try once a month
741         if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
742                 return false;
743         }
744
745         return true;
746 }
747
748 function poco_to_boolean($val) {
749         if (($val == "true") || ($val == 1)) {
750                 return true;
751         } elseif (($val == "false") || ($val == 0)) {
752                 return false;
753         }
754
755         return $val;
756 }
757
758 /**
759  * @brief Detect server type (Hubzilla or Friendica) via the poco data
760  *
761  * @param object $data POCO data
762  * @return array Server data
763  */
764 function poco_detect_poco_data($data) {
765         $server = false;
766
767         if (!isset($data->entry)) {
768                 return false;
769         }
770
771         if (count($data->entry) == 0) {
772                 return false;
773         }
774
775         if (!isset($data->entry[0]->urls)) {
776                 return false;
777         }
778
779         if (count($data->entry[0]->urls) == 0) {
780                 return false;
781         }
782
783         foreach ($data->entry[0]->urls as $url) {
784                 if ($url->type == 'zot') {
785                         $server = array();
786                         $server["platform"] = 'Hubzilla';
787                         $server["network"] = NETWORK_DIASPORA;
788                         return $server;
789                 }
790         }
791         return false;
792 }
793
794 /**
795  * @brief Detect server type by using the nodeinfo data
796  *
797  * @param string $server_url address of the server
798  * @return array Server data
799  */
800 function poco_fetch_nodeinfo($server_url) {
801         $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
802         if (!$serverret["success"]) {
803                 return false;
804         }
805
806         $nodeinfo = json_decode($serverret['body']);
807
808         if (!is_object($nodeinfo)) {
809                 return false;
810         }
811
812         if (!is_array($nodeinfo->links)) {
813                 return false;
814         }
815
816         $nodeinfo_url = '';
817
818         foreach ($nodeinfo->links as $link) {
819                 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
820                         $nodeinfo_url = $link->href;
821                 }
822         }
823
824         if ($nodeinfo_url == '') {
825                 return false;
826         }
827
828         $serverret = z_fetch_url($nodeinfo_url);
829         if (!$serverret["success"]) {
830                 return false;
831         }
832
833         $nodeinfo = json_decode($serverret['body']);
834
835         if (!is_object($nodeinfo)) {
836                 return false;
837         }
838
839         $server = array();
840
841         $server['register_policy'] = REGISTER_CLOSED;
842
843         if (is_bool($nodeinfo->openRegistrations) && $nodeinfo->openRegistrations) {
844                 $server['register_policy'] = REGISTER_OPEN;
845         }
846
847         if (is_object($nodeinfo->software)) {
848                 if (isset($nodeinfo->software->name)) {
849                         $server['platform'] = $nodeinfo->software->name;
850                 }
851
852                 if (isset($nodeinfo->software->version)) {
853                         $server['version'] = $nodeinfo->software->version;
854                         // Version numbers on Nodeinfo are presented with additional info, e.g.:
855                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
856                         $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
857                 }
858         }
859
860         if (is_object($nodeinfo->metadata)) {
861                 if (isset($nodeinfo->metadata->nodeName)) {
862                         $server['site_name'] = $nodeinfo->metadata->nodeName;
863                 }
864         }
865
866         $diaspora = false;
867         $friendica = false;
868         $gnusocial = false;
869
870         if (is_array($nodeinfo->protocols->inbound)) {
871                 foreach ($nodeinfo->protocols->inbound as $inbound) {
872                         if ($inbound == 'diaspora') {
873                                 $diaspora = true;
874                         }
875                         if ($inbound == 'friendica') {
876                                 $friendica = true;
877                         }
878                         if ($inbound == 'gnusocial') {
879                                 $gnusocial = true;
880                         }
881                 }
882         }
883
884         if ($gnusocial) {
885                 $server['network'] = NETWORK_OSTATUS;
886         }
887         if ($diaspora) {
888                 $server['network'] = NETWORK_DIASPORA;
889         }
890         if ($friendica) {
891                 $server['network'] = NETWORK_DFRN;
892         }
893
894         if (!$server) {
895                 return false;
896         }
897
898         return $server;
899 }
900
901 /**
902  * @brief Detect server type (Hubzilla or Friendica) via the front page body
903  *
904  * @param string $body Front page of the server
905  * @return array Server data
906  */
907 function poco_detect_server_type($body) {
908         $server = false;
909
910         $doc = new DOMDocument();
911         @$doc->loadHTML($body);
912         $xpath = new DomXPath($doc);
913
914         $list = $xpath->query("//meta[@name]");
915
916         foreach ($list as $node) {
917                 $attr = array();
918                 if ($node->attributes->length) {
919                         foreach ($node->attributes as $attribute) {
920                                 $attr[$attribute->name] = $attribute->value;
921                         }
922                 }
923                 if ($attr['name'] == 'generator') {
924                         $version_part = explode(" ", $attr['content']);
925                         if (count($version_part) == 2) {
926                                 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
927                                         $server = array();
928                                         $server["platform"] = $version_part[0];
929                                         $server["version"] = $version_part[1];
930                                         $server["network"] = NETWORK_DFRN;
931                                 }
932                         }
933                 }
934         }
935
936         if (!$server) {
937                 $list = $xpath->query("//meta[@property]");
938
939                 foreach ($list as $node) {
940                         $attr = array();
941                         if ($node->attributes->length) {
942                                 foreach ($node->attributes as $attribute) {
943                                         $attr[$attribute->name] = $attribute->value;
944                                 }
945                         }
946                         if ($attr['property'] == 'generator' && in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
947                                 $server = array();
948                                 $server["platform"] = $attr['content'];
949                                 $server["version"] = "";
950                                 $server["network"] = NETWORK_DIASPORA;
951                         }
952                 }
953         }
954
955         if (!$server) {
956                 return false;
957         }
958
959         $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
960         return $server;
961 }
962
963 function poco_check_server($server_url, $network = "", $force = false) {
964
965         // Unify the server address
966         $server_url = trim($server_url, "/");
967         $server_url = str_replace("/index.php", "", $server_url);
968
969         if ($server_url == "") {
970                 return false;
971         }
972
973         $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
974         if (dbm::is_result($servers)) {
975
976                 if ($servers[0]["created"] <= NULL_DATE) {
977                         q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
978                                 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
979                 }
980                 $poco = $servers[0]["poco"];
981                 $noscrape = $servers[0]["noscrape"];
982
983                 if ($network == "") {
984                         $network = $servers[0]["network"];
985                 }
986
987                 $last_contact = $servers[0]["last_contact"];
988                 $last_failure = $servers[0]["last_failure"];
989                 $version = $servers[0]["version"];
990                 $platform = $servers[0]["platform"];
991                 $site_name = $servers[0]["site_name"];
992                 $info = $servers[0]["info"];
993                 $register_policy = $servers[0]["register_policy"];
994
995                 if (!$force && !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
996                         logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
997                         return ($last_contact >= $last_failure);
998                 }
999         } else {
1000                 $poco = "";
1001                 $noscrape = "";
1002                 $version = "";
1003                 $platform = "";
1004                 $site_name = "";
1005                 $info = "";
1006                 $register_policy = -1;
1007
1008                 $last_contact = NULL_DATE;
1009                 $last_failure = NULL_DATE;
1010         }
1011         logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
1012
1013         $failure = false;
1014         $possible_failure = false;
1015         $orig_last_failure = $last_failure;
1016         $orig_last_contact = $last_contact;
1017
1018         // Check if the page is accessible via SSL.
1019         $orig_server_url = $server_url;
1020         $server_url = str_replace("http://", "https://", $server_url);
1021
1022         // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1023         $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1024
1025         // Quit if there is a timeout.
1026         // But we want to make sure to only quit if we are mostly sure that this server url fits.
1027         if (dbm::is_result($servers) && ($orig_server_url == $server_url) &&
1028                 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1029                 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1030                 dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
1031                 return false;
1032         }
1033
1034         // Maybe the page is unencrypted only?
1035         $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1036         if (!$serverret["success"] || ($serverret["body"] == "") || (@sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1037                 $server_url = str_replace("https://", "http://", $server_url);
1038
1039                 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1040                 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1041
1042                 // Quit if there is a timeout
1043                 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1044                         logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1045                         dba::update('gserver', array('last_failure' => datetime_convert()), array('nurl' => normalise_link($server_url)));
1046                         return false;
1047                 }
1048
1049                 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1050         }
1051
1052         if (!$serverret["success"] || ($serverret["body"] == "") || (sizeof($xmlobj) == 0) || !is_object($xmlobj)) {
1053                 // Workaround for bad configured servers (known nginx problem)
1054                 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1055                         $failure = true;
1056                 }
1057                 $possible_failure = true;
1058         }
1059
1060         // If the server has no possible failure we reset the cached data
1061         if (!$possible_failure) {
1062                 $version = "";
1063                 $platform = "";
1064                 $site_name = "";
1065                 $info = "";
1066                 $register_policy = -1;
1067         }
1068
1069         // Look for poco
1070         if (!$failure) {
1071                 $serverret = z_fetch_url($server_url."/poco");
1072                 if ($serverret["success"]) {
1073                         $data = json_decode($serverret["body"]);
1074                         if (isset($data->totalResults)) {
1075                                 $poco = $server_url."/poco";
1076                                 $server = poco_detect_poco_data($data);
1077                                 if ($server) {
1078                                         $platform = $server['platform'];
1079                                         $network = $server['network'];
1080                                         $version = '';
1081                                         $site_name = '';
1082                                 }
1083                         }
1084                 }
1085         }
1086
1087         if (!$failure) {
1088                 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1089                 $serverret = z_fetch_url($server_url);
1090
1091                 if (!$serverret["success"] || ($serverret["body"] == "")) {
1092                         $failure = true;
1093                 } else {
1094                         $server = poco_detect_server_type($serverret["body"]);
1095                         if ($server) {
1096                                 $platform = $server['platform'];
1097                                 $network = $server['network'];
1098                                 $version = $server['version'];
1099                                 $site_name = $server['site_name'];
1100                         }
1101
1102                         $lines = explode("\n",$serverret["header"]);
1103                         if (count($lines)) {
1104                                 foreach($lines as $line) {
1105                                         $line = trim($line);
1106                                         if (stristr($line,'X-Diaspora-Version:')) {
1107                                                 $platform = "Diaspora";
1108                                                 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1109                                                 $version = trim(str_replace("x-diaspora-version:", "", $version));
1110                                                 $network = NETWORK_DIASPORA;
1111                                                 $versionparts = explode("-", $version);
1112                                                 $version = $versionparts[0];
1113                                         }
1114
1115                                         if (stristr($line,'Server: Mastodon')) {
1116                                                 $platform = "Mastodon";
1117                                                 $network = NETWORK_OSTATUS;
1118                                         }
1119                                 }
1120                         }
1121                 }
1122         }
1123
1124         if (!$failure && ($poco == "")) {
1125                 // Test for Statusnet
1126                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1127                 // The "not implemented" is a special treatment for really, really old Friendica versions
1128                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1129                 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1130                         ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1131                         $platform = "StatusNet";
1132                         // Remove junk that some GNU Social servers return
1133                         $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1134                         $version = trim($version, '"');
1135                         $network = NETWORK_OSTATUS;
1136                 }
1137
1138                 // Test for GNU Social
1139                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1140                 if ($serverret["success"] && ($serverret["body"] != '{"error":"not implemented"}') &&
1141                         ($serverret["body"] != '') && (strlen($serverret["body"]) < 30)) {
1142                         $platform = "GNU Social";
1143                         // Remove junk that some GNU Social servers return
1144                         $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1145                         $version = trim($version, '"');
1146                         $network = NETWORK_OSTATUS;
1147                 }
1148
1149                 // Test for Mastodon
1150                 $orig_version = $version;
1151                 $serverret = z_fetch_url($server_url."/api/v1/instance");
1152                 if ($serverret["success"] && ($serverret["body"] != '')) {
1153                         $data = json_decode($serverret["body"]);
1154                         if (isset($data->version)) {
1155                                 $platform = "Mastodon";
1156                                 $version = $data->version;
1157                                 $site_name = $data->title;
1158                                 $info = $data->description;
1159                                 $network = NETWORK_OSTATUS;
1160                         }
1161                 }
1162                 if (strstr($orig_version.$version, 'Pleroma')) {
1163                         $platform = 'Pleroma';
1164                         $version = trim(str_replace('Pleroma', '', $version));
1165                 }
1166         }
1167
1168         if (!$failure) {
1169                 // Test for Hubzilla and Red
1170                 $serverret = z_fetch_url($server_url."/siteinfo.json");
1171                 if ($serverret["success"]) {
1172                         $data = json_decode($serverret["body"]);
1173                         if (isset($data->url)) {
1174                                 $platform = $data->platform;
1175                                 $version = $data->version;
1176                                 $network = NETWORK_DIASPORA;
1177                         }
1178                         if (!empty($data->site_name)) {
1179                                 $site_name = $data->site_name;
1180                         }
1181                         switch ($data->register_policy) {
1182                                 case "REGISTER_OPEN":
1183                                         $register_policy = REGISTER_OPEN;
1184                                         break;
1185                                 case "REGISTER_APPROVE":
1186                                         $register_policy = REGISTER_APPROVE;
1187                                         break;
1188                                 case "REGISTER_CLOSED":
1189                                 default:
1190                                         $register_policy = REGISTER_CLOSED;
1191                                         break;
1192                         }
1193                 } else {
1194                         // Test for Hubzilla, Redmatrix or Friendica
1195                         $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1196                         if ($serverret["success"]) {
1197                                 $data = json_decode($serverret["body"]);
1198                                 if (isset($data->site->server)) {
1199                                         if (isset($data->site->platform)) {
1200                                                 $platform = $data->site->platform->PLATFORM_NAME;
1201                                                 $version = $data->site->platform->STD_VERSION;
1202                                                 $network = NETWORK_DIASPORA;
1203                                         }
1204                                         if (isset($data->site->BlaBlaNet)) {
1205                                                 $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1206                                                 $version = $data->site->BlaBlaNet->STD_VERSION;
1207                                                 $network = NETWORK_DIASPORA;
1208                                         }
1209                                         if (isset($data->site->hubzilla)) {
1210                                                 $platform = $data->site->hubzilla->PLATFORM_NAME;
1211                                                 $version = $data->site->hubzilla->RED_VERSION;
1212                                                 $network = NETWORK_DIASPORA;
1213                                         }
1214                                         if (isset($data->site->redmatrix)) {
1215                                                 if (isset($data->site->redmatrix->PLATFORM_NAME)) {
1216                                                         $platform = $data->site->redmatrix->PLATFORM_NAME;
1217                                                 } elseif (isset($data->site->redmatrix->RED_PLATFORM)) {
1218                                                         $platform = $data->site->redmatrix->RED_PLATFORM;
1219                                                 }
1220
1221                                                 $version = $data->site->redmatrix->RED_VERSION;
1222                                                 $network = NETWORK_DIASPORA;
1223                                         }
1224                                         if (isset($data->site->friendica)) {
1225                                                 $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1226                                                 $version = $data->site->friendica->FRIENDICA_VERSION;
1227                                                 $network = NETWORK_DFRN;
1228                                         }
1229
1230                                         $site_name = $data->site->name;
1231
1232                                         $data->site->closed = poco_to_boolean($data->site->closed);
1233                                         $data->site->private = poco_to_boolean($data->site->private);
1234                                         $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1235
1236                                         if (!$data->site->closed && !$data->site->private and $data->site->inviteonly) {
1237                                                 $register_policy = REGISTER_APPROVE;
1238                                         } elseif (!$data->site->closed && !$data->site->private) {
1239                                                 $register_policy = REGISTER_OPEN;
1240                                         } else {
1241                                                 $register_policy = REGISTER_CLOSED;
1242                                         }
1243                                 }
1244                         }
1245                 }
1246         }
1247
1248         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1249         if (!$failure) {
1250                 $serverret = z_fetch_url($server_url."/statistics.json");
1251                 if ($serverret["success"]) {
1252                         $data = json_decode($serverret["body"]);
1253                         if (isset($data->version)) {
1254                                 $version = $data->version;
1255                                 // Version numbers on statistics.json are presented with additional info, e.g.:
1256                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1257                                 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1258                         }
1259
1260                         if (!empty($data->name)) {
1261                                 $site_name = $data->name;
1262                         }
1263
1264                         if (!empty($data->network)) {
1265                                 $platform = $data->network;
1266                         }
1267
1268                         if ($platform == "Diaspora") {
1269                                 $network = NETWORK_DIASPORA;
1270                         }
1271
1272                         if ($data->registrations_open) {
1273                                 $register_policy = REGISTER_OPEN;
1274                         } else {
1275                                 $register_policy = REGISTER_CLOSED;
1276                         }
1277                 }
1278         }
1279
1280         // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1281         if (!$failure) {
1282                 $server = poco_fetch_nodeinfo($server_url);
1283                 if ($server) {
1284                         $register_policy = $server['register_policy'];
1285
1286                         if (isset($server['platform'])) {
1287                                 $platform = $server['platform'];
1288                         }
1289
1290                         if (isset($server['network'])) {
1291                                 $network = $server['network'];
1292                         }
1293
1294                         if (isset($server['version'])) {
1295                                 $version = $server['version'];
1296                         }
1297
1298                         if (isset($server['site_name'])) {
1299                                 $site_name = $server['site_name'];
1300                         }
1301                 }
1302         }
1303
1304         // Check for noscrape
1305         // Friendica servers could be detected as OStatus servers
1306         if (!$failure && in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1307                 $serverret = z_fetch_url($server_url."/friendica/json");
1308
1309                 if (!$serverret["success"]) {
1310                         $serverret = z_fetch_url($server_url."/friendika/json");
1311                 }
1312
1313                 if ($serverret["success"]) {
1314                         $data = json_decode($serverret["body"]);
1315
1316                         if (isset($data->version)) {
1317                                 $network = NETWORK_DFRN;
1318
1319                                 $noscrape = $data->no_scrape_url;
1320                                 $version = $data->version;
1321                                 $site_name = $data->site_name;
1322                                 $info = $data->info;
1323                                 $register_policy_str = $data->register_policy;
1324                                 $platform = $data->platform;
1325
1326                                 switch ($register_policy_str) {
1327                                         case "REGISTER_CLOSED":
1328                                                 $register_policy = REGISTER_CLOSED;
1329                                                 break;
1330                                         case "REGISTER_APPROVE":
1331                                                 $register_policy = REGISTER_APPROVE;
1332                                                 break;
1333                                         case "REGISTER_OPEN":
1334                                                 $register_policy = REGISTER_OPEN;
1335                                                 break;
1336                                 }
1337                         }
1338                 }
1339         }
1340
1341         if ($possible_failure && !$failure) {
1342                 $failure = true;
1343         }
1344
1345         if ($failure) {
1346                 $last_contact = $orig_last_contact;
1347                 $last_failure = datetime_convert();
1348         } else {
1349                 $last_contact = datetime_convert();
1350                 $last_failure = $orig_last_failure;
1351         }
1352
1353         if (($last_contact <= $last_failure) && !$failure) {
1354                 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1355         } elseif (($last_contact >= $last_failure) && $failure) {
1356                 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1357         }
1358
1359         // Check again if the server exists
1360         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1361
1362         $version = strip_tags($version);
1363         $site_name = strip_tags($site_name);
1364         $info = strip_tags($info);
1365         $platform = strip_tags($platform);
1366
1367         if ($servers) {
1368                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1369                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1370                         dbesc($server_url),
1371                         dbesc($version),
1372                         dbesc($site_name),
1373                         dbesc($info),
1374                         intval($register_policy),
1375                         dbesc($poco),
1376                         dbesc($noscrape),
1377                         dbesc($network),
1378                         dbesc($platform),
1379                         dbesc($last_contact),
1380                         dbesc($last_failure),
1381                         dbesc(normalise_link($server_url))
1382                 );
1383         } elseif (!$failure) {
1384                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1385                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1386                                 dbesc($server_url),
1387                                 dbesc(normalise_link($server_url)),
1388                                 dbesc($version),
1389                                 dbesc($site_name),
1390                                 dbesc($info),
1391                                 intval($register_policy),
1392                                 dbesc($poco),
1393                                 dbesc($noscrape),
1394                                 dbesc($network),
1395                                 dbesc($platform),
1396                                 dbesc(datetime_convert()),
1397                                 dbesc($last_contact),
1398                                 dbesc($last_failure),
1399                                 dbesc(datetime_convert())
1400                 );
1401         }
1402         logger("End discovery for server " . $server_url, LOGGER_DEBUG);
1403
1404         return !$failure;
1405 }
1406
1407 function count_common_friends($uid, $cid) {
1408
1409         $r = q("SELECT count(*) as `total`
1410                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1411                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1412                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1413                 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1414                 intval($cid),
1415                 intval($uid),
1416                 intval($uid),
1417                 intval($cid)
1418         );
1419
1420         // logger("count_common_friends: $uid $cid {$r[0]['total']}");
1421         if (dbm::is_result($r)) {
1422                 return $r[0]['total'];
1423         }
1424         return 0;
1425
1426 }
1427
1428
1429 function common_friends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false) {
1430
1431         if ($shuffle) {
1432                 $sql_extra = " order by rand() ";
1433         } else {
1434                 $sql_extra = " order by `gcontact`.`name` asc ";
1435         }
1436
1437         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1438                 FROM `glink`
1439                 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1440                 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1441                 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1442                         AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1443                         AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1444                         AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1445                         $sql_extra LIMIT %d, %d",
1446                 intval($cid),
1447                 intval($uid),
1448                 intval($uid),
1449                 intval($cid),
1450                 intval($start),
1451                 intval($limit)
1452         );
1453
1454         /// @TODO Check all calling-findings of this function if they properly use dbm::is_result()
1455         return $r;
1456
1457 }
1458
1459
1460 function count_common_friends_zcid($uid, $zcid) {
1461
1462         $r = q("SELECT count(*) as `total`
1463                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1464                 where `glink`.`zcid` = %d
1465                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1466                 intval($zcid),
1467                 intval($uid)
1468         );
1469
1470         if (dbm::is_result($r)) {
1471                 return $r[0]['total'];
1472         }
1473         return 0;
1474
1475 }
1476
1477 function common_friends_zcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false) {
1478
1479         if ($shuffle) {
1480                 $sql_extra = " order by rand() ";
1481         } else {
1482                 $sql_extra = " order by `gcontact`.`name` asc ";
1483         }
1484
1485         $r = q("SELECT `gcontact`.*
1486                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1487                 where `glink`.`zcid` = %d
1488                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1489                 $sql_extra limit %d, %d",
1490                 intval($zcid),
1491                 intval($uid),
1492                 intval($start),
1493                 intval($limit)
1494         );
1495
1496         /// @TODO Check all calling-findings of this function if they properly use dbm::is_result()
1497         return $r;
1498
1499 }
1500
1501
1502 function count_all_friends($uid, $cid) {
1503
1504         $r = q("SELECT count(*) as `total`
1505                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1506                 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1507                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1508                 intval($cid),
1509                 intval($uid)
1510         );
1511
1512         if (dbm::is_result($r)) {
1513                 return $r[0]['total'];
1514         }
1515         return 0;
1516
1517 }
1518
1519
1520 function all_friends($uid, $cid, $start = 0, $limit = 80) {
1521
1522         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1523                 FROM `glink`
1524                 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1525                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1526                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1527                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1528                 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1529                 intval($uid),
1530                 intval($cid),
1531                 intval($uid),
1532                 intval($start),
1533                 intval($limit)
1534         );
1535
1536         /// @TODO Check all calling-findings of this function if they properly use dbm::is_result()
1537         return $r;
1538 }
1539
1540
1541
1542 function suggestion_query($uid, $start = 0, $limit = 80) {
1543
1544         if (!$uid) {
1545                 return array();
1546         }
1547
1548         /*
1549          * Uncommented because the result of the queries are to big to store it in the cache.
1550          * We need to decide if we want to change the db column type or if we want to delete it.
1551          */
1552         //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1553         //if (!is_null($list)) {
1554         //      return $list;
1555         //}
1556
1557         $network = array(NETWORK_DFRN);
1558
1559         if (get_config('system','diaspora_enabled')) {
1560                 $network[] = NETWORK_DIASPORA;
1561         }
1562
1563         if (!get_config('system','ostatus_disabled')) {
1564                 $network[] = NETWORK_OSTATUS;
1565         }
1566
1567         $sql_network = implode("', '", $network);
1568         $sql_network = "'".$sql_network."'";
1569
1570         /// @todo This query is really slow
1571         // By now we cache the data for five minutes
1572         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1573                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1574                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1575                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1576                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1577                 AND `gcontact`.`updated` >= '%s'
1578                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1579                 AND `gcontact`.`network` IN (%s)
1580                 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1581                 intval($uid),
1582                 intval($uid),
1583                 intval($uid),
1584                 intval($uid),
1585                 dbesc(NULL_DATE),
1586                 $sql_network,
1587                 intval($start),
1588                 intval($limit)
1589         );
1590
1591         if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1592                 /*
1593                  * Uncommented because the result of the queries are to big to store it in the cache.
1594                  * We need to decide if we want to change the db column type or if we want to delete it.
1595                  */
1596                 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1597
1598                 return $r;
1599         }
1600
1601         $r2 = q("SELECT gcontact.* FROM gcontact
1602                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1603                 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1604                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1605                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1606                 AND `gcontact`.`updated` >= '%s'
1607                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1608                 AND `gcontact`.`network` IN (%s)
1609                 ORDER BY rand() LIMIT %d, %d",
1610                 intval($uid),
1611                 intval($uid),
1612                 intval($uid),
1613                 dbesc(NULL_DATE),
1614                 $sql_network,
1615                 intval($start),
1616                 intval($limit)
1617         );
1618
1619         $list = array();
1620         foreach ($r2 as $suggestion) {
1621                 $list[$suggestion["nurl"]] = $suggestion;
1622         }
1623
1624         foreach ($r as $suggestion) {
1625                 $list[$suggestion["nurl"]] = $suggestion;
1626         }
1627
1628         while (sizeof($list) > ($limit)) {
1629                 array_pop($list);
1630         }
1631
1632         /*
1633          * Uncommented because the result of the queries are to big to store it in the cache.
1634          * We need to decide if we want to change the db column type or if we want to delete it.
1635          */
1636         //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1637         return $list;
1638 }
1639
1640 function update_suggestions() {
1641
1642         $a = get_app();
1643
1644         $done = array();
1645
1646         /// @TODO Check if it is really neccessary to poll the own server
1647         poco_load(0, 0, 0, System::baseUrl() . '/poco');
1648
1649         $done[] = System::baseUrl() . '/poco';
1650
1651         if (strlen(get_config('system','directory'))) {
1652                 $x = fetch_url(get_server()."/pubsites");
1653                 if ($x) {
1654                         $j = json_decode($x);
1655                         if ($j->entries) {
1656                                 foreach ($j->entries as $entry) {
1657
1658                                         poco_check_server($entry->url);
1659
1660                                         $url = $entry->url . '/poco';
1661                                         if (! in_array($url,$done)) {
1662                                                 poco_load(0,0,0,$entry->url . '/poco');
1663                                         }
1664                                 }
1665                         }
1666                 }
1667         }
1668
1669         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1670         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1671                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1672         );
1673
1674         if (dbm::is_result($r)) {
1675                 foreach ($r as $rr) {
1676                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1677                         if (! in_array($base,$done)) {
1678                                 poco_load(0,0,0,$base);
1679                         }
1680                 }
1681         }
1682 }
1683
1684 /**
1685  * @brief Fetch server list from remote servers and adds them when they are new.
1686  *
1687  * @param string $poco URL to the POCO endpoint
1688  */
1689 function poco_fetch_serverlist($poco) {
1690         $serverret = z_fetch_url($poco."/@server");
1691         if (!$serverret["success"]) {
1692                 return;
1693         }
1694         $serverlist = json_decode($serverret['body']);
1695
1696         if (!is_array($serverlist)) {
1697                 return;
1698         }
1699
1700         foreach ($serverlist as $server) {
1701                 $server_url = str_replace("/index.php", "", $server->url);
1702
1703                 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1704                 if (!dbm::is_result($r)) {
1705                         logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1706                         Worker::add(PRIORITY_LOW, "discover_poco", "server", $server_url);
1707                 }
1708         }
1709 }
1710
1711 function poco_discover_federation() {
1712         $last = get_config('poco','last_federation_discovery');
1713
1714         if ($last) {
1715                 $next = $last + (24 * 60 * 60);
1716                 if ($next > time()) {
1717                         return;
1718                 }
1719         }
1720
1721         // Discover Friendica, Hubzilla and Diaspora servers
1722         $serverdata = fetch_url("http://the-federation.info/pods.json");
1723
1724         if ($serverdata) {
1725                 $servers = json_decode($serverdata);
1726
1727                 foreach ($servers->pods as $server) {
1728                         Worker::add(PRIORITY_LOW, "discover_poco", "server", "https://".$server->host);
1729                 }
1730         }
1731
1732         // Disvover Mastodon servers
1733         if (!Config::get('system','ostatus_disabled')) {
1734                 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1735
1736                 if ($serverdata) {
1737                         $servers = json_decode($serverdata);
1738
1739                         foreach ($servers as $server) {
1740                                 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1741                                 Worker::add(PRIORITY_LOW, "discover_poco", "server", $url);
1742                         }
1743                 }
1744         }
1745
1746         // Currently disabled, since the service isn't available anymore.
1747         // It is not removed since I hope that there will be a successor.
1748         // Discover GNU Social Servers.
1749         //if (!get_config('system','ostatus_disabled')) {
1750         //      $serverdata = "http://gstools.org/api/get_open_instances/";
1751
1752         //      $result = z_fetch_url($serverdata);
1753         //      if ($result["success"]) {
1754         //              $servers = json_decode($result["body"]);
1755
1756         //              foreach($servers->data as $server)
1757         //                      poco_check_server($server->instance_address);
1758         //      }
1759         //}
1760
1761         set_config('poco','last_federation_discovery', time());
1762 }
1763
1764 function poco_discover_single_server($id) {
1765         $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1766         if (!dbm::is_result($r)) {
1767                 return false;
1768         }
1769
1770         $server = $r[0];
1771
1772         // Discover new servers out there (Works from Friendica version 3.5.2)
1773         poco_fetch_serverlist($server["poco"]);
1774
1775         // Fetch all users from the other server
1776         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1777
1778         logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1779
1780         $retdata = z_fetch_url($url);
1781         if ($retdata["success"]) {
1782                 $data = json_decode($retdata["body"]);
1783
1784                 poco_discover_server($data, 2);
1785
1786                 if (get_config('system','poco_discovery') > 1) {
1787
1788                         $timeframe = get_config('system','poco_discovery_since');
1789                         if ($timeframe == 0) {
1790                                 $timeframe = 30;
1791                         }
1792
1793                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1794
1795                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1796                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1797
1798                         $success = false;
1799
1800                         $retdata = z_fetch_url($url);
1801                         if ($retdata["success"]) {
1802                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1803                                 $success = poco_discover_server(json_decode($retdata["body"]));
1804                         }
1805
1806                         if (!$success && (get_config('system','poco_discovery') > 2)) {
1807                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1808                                 poco_discover_server_users($data, $server);
1809                         }
1810                 }
1811
1812                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1813
1814                 return true;
1815         } else {
1816                 // If the server hadn't replied correctly, then force a sanity check
1817                 poco_check_server($server["url"], $server["network"], true);
1818
1819                 // If we couldn't reach the server, we will try it some time later
1820                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1821
1822                 return false;
1823         }
1824 }
1825
1826 function poco_discover($complete = false) {
1827
1828         // Update the server list
1829         poco_discover_federation();
1830
1831         $no_of_queries = 5;
1832
1833         $requery_days = intval(get_config("system", "poco_requery_days"));
1834
1835         if ($requery_days == 0) {
1836                 $requery_days = 7;
1837         }
1838         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1839
1840         $r = q("SELECT `id`, `url`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
1841         if (dbm::is_result($r)) {
1842                 foreach ($r as $server) {
1843
1844                         if (!poco_check_server($server["url"], $server["network"])) {
1845                                 // The server is not reachable? Okay, then we will try it later
1846                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1847                                 continue;
1848                         }
1849
1850                         logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1851                         Worker::add(PRIORITY_LOW, "discover_poco", "update_server_directory", (int)$server['id']);
1852
1853                         if (!$complete && (--$no_of_queries == 0)) {
1854                                 break;
1855                         }
1856                 }
1857         }
1858 }
1859
1860 function poco_discover_server_users($data, $server) {
1861
1862         if (!isset($data->entry)) {
1863                 return;
1864         }
1865
1866         foreach ($data->entry as $entry) {
1867                 $username = "";
1868                 if (isset($entry->urls)) {
1869                         foreach ($entry->urls as $url) {
1870                                 if ($url->type == 'profile') {
1871                                         $profile_url = $url->value;
1872                                         $urlparts = parse_url($profile_url);
1873                                         $username = end(explode("/", $urlparts["path"]));
1874                                 }
1875                         }
1876                 }
1877                 if ($username != "") {
1878                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1879
1880                         // Fetch all contacts from a given user from the other server
1881                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1882
1883                         $retdata = z_fetch_url($url);
1884                         if ($retdata["success"]) {
1885                                 poco_discover_server(json_decode($retdata["body"]), 3);
1886                         }
1887                 }
1888         }
1889 }
1890
1891 function poco_discover_server($data, $default_generation = 0) {
1892
1893         if (!isset($data->entry) || !count($data->entry)) {
1894                 return false;
1895         }
1896
1897         $success = false;
1898
1899         foreach ($data->entry as $entry) {
1900                 $profile_url = '';
1901                 $profile_photo = '';
1902                 $connect_url = '';
1903                 $name = '';
1904                 $network = '';
1905                 $updated = NULL_DATE;
1906                 $location = '';
1907                 $about = '';
1908                 $keywords = '';
1909                 $gender = '';
1910                 $contact_type = -1;
1911                 $generation = $default_generation;
1912
1913                 $name = $entry->displayName;
1914
1915                 if (isset($entry->urls)) {
1916                         foreach ($entry->urls as $url) {
1917                                 if ($url->type == 'profile') {
1918                                         $profile_url = $url->value;
1919                                         continue;
1920                                 }
1921                                 if ($url->type == 'webfinger') {
1922                                         $connect_url = str_replace('acct:' , '', $url->value);
1923                                         continue;
1924                                 }
1925                         }
1926                 }
1927
1928                 if (isset($entry->photos)) {
1929                         foreach ($entry->photos as $photo) {
1930                                 if ($photo->type == 'profile') {
1931                                         $profile_photo = $photo->value;
1932                                         continue;
1933                                 }
1934                         }
1935                 }
1936
1937                 if (isset($entry->updated)) {
1938                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1939                 }
1940
1941                 if (isset($entry->network)) {
1942                         $network = $entry->network;
1943                 }
1944
1945                 if (isset($entry->currentLocation)) {
1946                         $location = $entry->currentLocation;
1947                 }
1948
1949                 if (isset($entry->aboutMe)) {
1950                         $about = html2bbcode($entry->aboutMe);
1951                 }
1952
1953                 if (isset($entry->gender)) {
1954                         $gender = $entry->gender;
1955                 }
1956
1957                 if(isset($entry->generation) && ($entry->generation > 0)) {
1958                         $generation = ++$entry->generation;
1959                 }
1960
1961                 if(isset($entry->contactType) && ($entry->contactType >= 0)) {
1962                         $contact_type = $entry->contactType;
1963                 }
1964
1965                 if (isset($entry->tags)) {
1966                         foreach ($entry->tags as $tag) {
1967                                 $keywords = implode(", ", $tag);
1968                         }
1969                 }
1970
1971                 if ($generation > 0) {
1972                         $success = true;
1973
1974                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1975
1976                         $gcontact = array("url" => $profile_url,
1977                                         "name" => $name,
1978                                         "network" => $network,
1979                                         "photo" => $profile_photo,
1980                                         "about" => $about,
1981                                         "location" => $location,
1982                                         "gender" => $gender,
1983                                         "keywords" => $keywords,
1984                                         "connect" => $connect_url,
1985                                         "updated" => $updated,
1986                                         "contact-type" => $contact_type,
1987                                         "generation" => $generation);
1988
1989                         try {
1990                                 $gcontact = sanitize_gcontact($gcontact);
1991                                 update_gcontact($gcontact);
1992                         } catch (Exception $e) {
1993                                 logger($e->getMessage(), LOGGER_DEBUG);
1994                         }
1995
1996                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1997                 }
1998         }
1999         return $success;
2000 }
2001
2002 /**
2003  * @brief Removes unwanted parts from a contact url
2004  *
2005  * @param string $url Contact url
2006  * @return string Contact url with the wanted parts
2007  */
2008 function clean_contact_url($url) {
2009         $parts = parse_url($url);
2010
2011         if (!isset($parts["scheme"]) || !isset($parts["host"])) {
2012                 return $url;
2013         }
2014
2015         $new_url = $parts["scheme"]."://".$parts["host"];
2016
2017         if (isset($parts["port"])) {
2018                 $new_url .= ":".$parts["port"];
2019         }
2020
2021         if (isset($parts["path"])) {
2022                 $new_url .= $parts["path"];
2023         }
2024
2025         if ($new_url != $url) {
2026                 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
2027         }
2028
2029         return $new_url;
2030 }
2031
2032 /**
2033  * @brief Replace alternate OStatus user format with the primary one
2034  *
2035  * @param arr $contact contact array (called by reference)
2036  */
2037 function fix_alternate_contact_address(&$contact) {
2038         if (($contact["network"] == NETWORK_OSTATUS) && poco_alternate_ostatus_url($contact["url"])) {
2039                 $data = probe_url($contact["url"]);
2040                 if ($contact["network"] == NETWORK_OSTATUS) {
2041                         logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
2042                         $contact["url"] = $data["url"];
2043                         $contact["addr"] = $data["addr"];
2044                         $contact["alias"] = $data["alias"];
2045                         $contact["server_url"] = $data["baseurl"];
2046                 }
2047         }
2048 }
2049
2050 /**
2051  * @brief Fetch the gcontact id, add an entry if not existed
2052  *
2053  * @param arr $contact contact array
2054  * @return bool|int Returns false if not found, integer if contact was found
2055  */
2056 function get_gcontact_id($contact) {
2057
2058         $gcontact_id = 0;
2059         $doprobing = false;
2060
2061         if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
2062                 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
2063                 return false;
2064         }
2065
2066         if ($contact["network"] == NETWORK_STATUSNET) {
2067                 $contact["network"] = NETWORK_OSTATUS;
2068         }
2069
2070         // All new contacts are hidden by default
2071         if (!isset($contact["hide"])) {
2072                 $contact["hide"] = true;
2073         }
2074
2075         // Replace alternate OStatus user format with the primary one
2076         fix_alternate_contact_address($contact);
2077
2078         // Remove unwanted parts from the contact url (e.g. "?zrl=...")
2079         if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
2080                 $contact["url"] = clean_contact_url($contact["url"]);
2081         }
2082
2083         dba::lock('gcontact');
2084         $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
2085                 dbesc(normalise_link($contact["url"])));
2086
2087         if (dbm::is_result($r)) {
2088                 $gcontact_id = $r[0]["id"];
2089
2090                 // Update every 90 days
2091                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
2092                         $last_failure_str = $r[0]["last_failure"];
2093                         $last_failure = strtotime($r[0]["last_failure"]);
2094                         $last_contact_str = $r[0]["last_contact"];
2095                         $last_contact = strtotime($r[0]["last_contact"]);
2096                         $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
2097                 }
2098         } else {
2099                 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
2100                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
2101                         dbesc($contact["name"]),
2102                         dbesc($contact["nick"]),
2103                         dbesc($contact["addr"]),
2104                         dbesc($contact["network"]),
2105                         dbesc($contact["url"]),
2106                         dbesc(normalise_link($contact["url"])),
2107                         dbesc($contact["photo"]),
2108                         dbesc(datetime_convert()),
2109                         dbesc(datetime_convert()),
2110                         dbesc($contact["location"]),
2111                         dbesc($contact["about"]),
2112                         intval($contact["hide"]),
2113                         intval($contact["generation"])
2114                 );
2115
2116                 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
2117                         dbesc(normalise_link($contact["url"])));
2118
2119                 if (dbm::is_result($r)) {
2120                         $gcontact_id = $r[0]["id"];
2121
2122                         $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2123                 }
2124         }
2125         dba::unlock();
2126
2127         if ($doprobing) {
2128                 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2129                 Worker::add(PRIORITY_LOW, 'gprobe', $contact["url"]);
2130         }
2131
2132         return $gcontact_id;
2133 }
2134
2135 /**
2136  * @brief Updates the gcontact table from a given array
2137  *
2138  * @param arr $contact contact array
2139  * @return bool|int Returns false if not found, integer if contact was found
2140  */
2141 function update_gcontact($contact) {
2142
2143         // Check for invalid "contact-type" value
2144         if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
2145                 $contact['contact-type'] = 0;
2146         }
2147
2148         /// @todo update contact table as well
2149
2150         $gcontact_id = get_gcontact_id($contact);
2151
2152         if (!$gcontact_id) {
2153                 return false;
2154         }
2155
2156         $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2157                         `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2158                 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2159                 intval($gcontact_id));
2160
2161         // Get all field names
2162         $fields = array();
2163         foreach ($r[0] as $field => $data) {
2164                 $fields[$field] = $data;
2165         }
2166
2167         unset($fields["url"]);
2168         unset($fields["updated"]);
2169         unset($fields["hide"]);
2170
2171         // Bugfix: We had an error in the storing of keywords which lead to the "0"
2172         // This value is still transmitted via poco.
2173         if ($contact["keywords"] == "0") {
2174                 unset($contact["keywords"]);
2175         }
2176
2177         if ($r[0]["keywords"] == "0") {
2178                 $r[0]["keywords"] = "";
2179         }
2180
2181         // assign all unassigned fields from the database entry
2182         foreach ($fields as $field => $data) {
2183                 if (!isset($contact[$field]) || ($contact[$field] == "")) {
2184                         $contact[$field] = $r[0][$field];
2185                 }
2186         }
2187
2188         if (!isset($contact["hide"])) {
2189                 $contact["hide"] = $r[0]["hide"];
2190         }
2191
2192         $fields["hide"] = $r[0]["hide"];
2193
2194         if ($contact["network"] == NETWORK_STATUSNET) {
2195                 $contact["network"] = NETWORK_OSTATUS;
2196         }
2197
2198         // Replace alternate OStatus user format with the primary one
2199         fix_alternate_contact_address($contact);
2200
2201         if (!isset($contact["updated"])) {
2202                 $contact["updated"] = dbm::date();
2203         }
2204
2205         if ($contact["network"] == NETWORK_TWITTER) {
2206                 $contact["server_url"] = 'http://twitter.com';
2207         }
2208
2209         if ($contact["server_url"] == "") {
2210                 $data = Probe::uri($contact["url"]);
2211                 if ($data["network"] != NETWORK_PHANTOM) {
2212                         $contact["server_url"] = $data['baseurl'];
2213                 }
2214         } else {
2215                 $contact["server_url"] = normalise_link($contact["server_url"]);
2216         }
2217
2218         if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
2219                 $hostname = str_replace("http://", "", $contact["server_url"]);
2220                 $contact["addr"] = $contact["nick"]."@".$hostname;
2221         }
2222
2223         // Check if any field changed
2224         $update = false;
2225         unset($fields["generation"]);
2226
2227         if ((($contact["generation"] > 0) && ($contact["generation"] <= $r[0]["generation"])) || ($r[0]["generation"] == 0)) {
2228                 foreach ($fields as $field => $data) {
2229                         if ($contact[$field] != $r[0][$field]) {
2230                                 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2231                                 $update = true;
2232                         }
2233                 }
2234
2235                 if ($contact["generation"] < $r[0]["generation"]) {
2236                         logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2237                         $update = true;
2238                 }
2239         }
2240
2241         if ($update) {
2242                 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2243                 $condition = array('`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
2244                                 normalise_link($contact["url"]), $contact["generation"]);
2245                 $contact["updated"] = dbm::date($contact["updated"]);
2246
2247                 $updated = array('photo' => $contact['photo'], 'name' => $contact['name'],
2248                                 'nick' => $contact['nick'], 'addr' => $contact['addr'],
2249                                 'network' => $contact['network'], 'birthday' => $contact['birthday'],
2250                                 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
2251                                 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
2252                                 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
2253                                 'notify' => $contact['notify'], 'url' => $contact['url'],
2254                                 'location' => $contact['location'], 'about' => $contact['about'],
2255                                 'generation' => $contact['generation'], 'updated' => $contact['updated'],
2256                                 'server_url' => $contact['server_url'], 'connect' => $contact['connect']);
2257
2258                 dba::update('gcontact', $updated, $condition, $fields);
2259
2260                 // Now update the contact entry with the user id "0" as well.
2261                 // This is used for the shadow copies of public items.
2262                 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2263                         dbesc(normalise_link($contact["url"])));
2264
2265                 if (dbm::is_result($r)) {
2266                         logger("Update public contact ".$r[0]["id"], LOGGER_DEBUG);
2267
2268                         update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2269
2270                         $fields = array('name', 'nick', 'addr',
2271                                         'network', 'bd', 'gender',
2272                                         'keywords', 'alias', 'contact-type',
2273                                         'url', 'location', 'about');
2274                         $old_contact = dba::select('contact', $fields, array('id' => $r[0]["id"]), array('limit' => 1));
2275
2276                         // Update it with the current values
2277                         $fields = array('name' => $contact['name'], 'nick' => $contact['nick'],
2278                                         'addr' => $contact['addr'], 'network' => $contact['network'],
2279                                         'bd' => $contact['birthday'], 'gender' => $contact['gender'],
2280                                         'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
2281                                         'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
2282                                         'location' => $contact['location'], 'about' => $contact['about']);
2283
2284                         dba::update('contact', $fields, array('id' => $r[0]["id"]), $old_contact);
2285                 }
2286         }
2287
2288         return $gcontact_id;
2289 }
2290
2291 /**
2292  * @brief Updates the gcontact entry from probe
2293  *
2294  * @param str $url profile link
2295  */
2296 function update_gcontact_from_probe($url) {
2297         $data = probe_url($url);
2298
2299         if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2300                 logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
2301                 return;
2302         }
2303
2304         $data["server_url"] = $data["baseurl"];
2305
2306         update_gcontact($data);
2307 }
2308
2309 /**
2310  * @brief Update the gcontact entry for a given user id
2311  *
2312  * @param int $uid User ID
2313  */
2314 function update_gcontact_for_user($uid) {
2315         $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2316                         `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2317                         `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2318                         `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2319                         `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2320                 FROM `profile`
2321                         INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2322                         INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2323                 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2324                 intval($uid));
2325
2326         $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2327                                                 "country-name" => $r[0]["country-name"]));
2328
2329         // The "addr" field was added in 3.4.3 so it can be empty for older users
2330         if ($r[0]["addr"] != "") {
2331                 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", System::baseUrl());
2332         } else {
2333                 $addr = $r[0]["addr"];
2334         }
2335
2336         $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2337                         "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2338                         "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2339                         "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2340                         "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
2341                         "nick" => $r[0]["nickname"], "addr" => $addr,
2342                         "connect" => $addr, "server_url" => System::baseUrl(),
2343                         "generation" => 1, "network" => NETWORK_DFRN);
2344
2345         update_gcontact($gcontact);
2346 }
2347
2348 /**
2349  * @brief Fetches users of given GNU Social server
2350  *
2351  * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2352  *
2353  * @param str $server Server address
2354  */
2355 function gs_fetch_users($server) {
2356
2357         logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2358
2359         $url = $server."/main/statistics";
2360
2361         $result = z_fetch_url($url);
2362         if (!$result["success"]) {
2363                 return false;
2364         }
2365
2366         $statistics = json_decode($result["body"]);
2367
2368         if (is_object($statistics->config)) {
2369                 if ($statistics->config->instance_with_ssl) {
2370                         $server = "https://";
2371                 } else {
2372                         $server = "http://";
2373                 }
2374
2375                 $server .= $statistics->config->instance_address;
2376
2377                 $hostname = $statistics->config->instance_address;
2378         } else {
2379                 /// @TODO is_object() above means here no object, still $statistics is being used as object
2380                 if ($statistics->instance_with_ssl) {
2381                         $server = "https://";
2382                 } else {
2383                         $server = "http://";
2384                 }
2385
2386                 $server .= $statistics->instance_address;
2387
2388                 $hostname = $statistics->instance_address;
2389         }
2390
2391         if (is_object($statistics->users)) {
2392                 foreach ($statistics->users as $nick => $user) {
2393                         $profile_url = $server."/".$user->nickname;
2394
2395                         $contact = array("url" => $profile_url,
2396                                         "name" => $user->fullname,
2397                                         "addr" => $user->nickname."@".$hostname,
2398                                         "nick" => $user->nickname,
2399                                         "about" => $user->bio,
2400                                         "network" => NETWORK_OSTATUS,
2401                                         "photo" => System::baseUrl()."/images/person-175.jpg");
2402                         get_gcontact_id($contact);
2403                 }
2404         }
2405 }
2406
2407 /**
2408  * @brief Asking GNU Social server on a regular base for their user data
2409  *
2410  */
2411 function gs_discover() {
2412
2413         $requery_days = intval(get_config("system", "poco_requery_days"));
2414
2415         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2416
2417         $r = q("SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
2418                 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2419
2420         if (!dbm::is_result($r)) {
2421                 return;
2422         }
2423
2424         foreach ($r as $server) {
2425                 gs_fetch_users($server["url"]);
2426                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2427         }
2428 }
2429
2430 /**
2431  * @brief Returns a list of all known servers
2432  * @return array List of server urls
2433  */
2434 function poco_serverlist() {
2435         $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2436                 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2437                 ORDER BY `last_contact`
2438                 LIMIT 1000",
2439                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2440         if (!dbm::is_result($r)) {
2441                 return false;
2442         }
2443
2444         return $r;
2445 }