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