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