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