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