]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
used more App::get_baseurl() instead of get_app()->get_baseurl().
[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         if (($network == "") OR ($network == NETWORK_OSTATUS)) {
227                 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
228                         dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
229                 );
230                 if (dbm::is_result($r)) {
231                         $network = $r[0]["network"];
232                         //$profile_url = $r[0]["url"];
233                 }
234         }
235
236         $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
237                 dbesc(normalise_link($profile_url))
238         );
239
240         if (count($x)) {
241                 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
242                         $network = $x[0]["network"];
243
244                 if ($updated == "0000-00-00 00:00:00")
245                         $updated = $x[0]["updated"];
246
247                 $created = $x[0]["created"];
248                 $server_url = $x[0]["server_url"];
249                 $nick = $x[0]["nick"];
250                 $addr = $x[0]["addr"];
251                 $alias =  $x[0]["alias"];
252                 $notify =  $x[0]["notify"];
253         } else {
254                 $created = "0000-00-00 00:00:00";
255                 $server_url = "";
256
257                 $urlparts = parse_url($profile_url);
258                 $nick = end(explode("/", $urlparts["path"]));
259                 $addr = "";
260                 $alias = "";
261                 $notify = "";
262         }
263
264         if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
265                 AND poco_reachable($profile_url, $server_url, $network, false)) {
266                 $data = probe_url($profile_url);
267
268                 $orig_profile = $profile_url;
269
270                 $network = $data["network"];
271                 $name = $data["name"];
272                 $nick = $data["nick"];
273                 $addr = $data["addr"];
274                 $alias = $data["alias"];
275                 $notify = $data["notify"];
276                 $profile_url = $data["url"];
277                 $profile_photo = $data["photo"];
278                 $server_url = $data["baseurl"];
279
280                 if ($alternate AND ($network == NETWORK_OSTATUS)) {
281                         // Delete the old entry - if it exists
282                         $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
283                         if ($r) {
284                                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
285                                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
286                         }
287
288                         // possibly create a new entry
289                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
290                 }
291         }
292
293         if ($alternate AND ($network == NETWORK_OSTATUS))
294                 return $gcid;
295
296         if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
297                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
298                         dbesc($network),
299                         dbesc(normalise_link($profile_url))
300                 );
301         }
302
303         if (($name == "") OR ($profile_photo == ""))
304                 return $gcid;
305
306         if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
307                 return $gcid;
308
309         logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
310
311         poco_check_server($server_url, $network);
312
313         $gcontact = array("url" => $profile_url,
314                         "addr" => $addr,
315                         "alias" => $alias,
316                         "name" => $name,
317                         "network" => $network,
318                         "photo" => $profile_photo,
319                         "about" => $about,
320                         "location" => $location,
321                         "gender" => $gender,
322                         "keywords" => $keywords,
323                         "server_url" => $server_url,
324                         "connect" => $connect_url,
325                         "notify" => $notify,
326                         "updated" => $updated,
327                         "generation" => $generation);
328
329         $gcid = update_gcontact($gcontact);
330
331         if(!$gcid)
332                 return $gcid;
333
334         $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
335                 intval($cid),
336                 intval($uid),
337                 intval($gcid),
338                 intval($zcid)
339         );
340         if (! dbm::is_result($r)) {
341                 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
342                         intval($cid),
343                         intval($uid),
344                         intval($gcid),
345                         intval($zcid),
346                         dbesc(datetime_convert())
347                 );
348         } else {
349                 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
350                         dbesc(datetime_convert()),
351                         intval($cid),
352                         intval($uid),
353                         intval($gcid),
354                         intval($zcid)
355                 );
356         }
357
358         return $gcid;
359 }
360
361 function poco_reachable($profile, $server = "", $network = "", $force = false) {
362
363         if ($server == "")
364                 $server = poco_detect_server($profile);
365
366         if ($server == "")
367                 return true;
368
369         return poco_check_server($server, $network, $force);
370 }
371
372 function poco_detect_server($profile) {
373
374         // Try to detect the server path based upon some known standard paths
375         $server_url = "";
376
377         if ($server_url == "") {
378                 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
379                 if ($friendica != $profile) {
380                         $server_url = $friendica;
381                         $network = NETWORK_DFRN;
382                 }
383         }
384
385         if ($server_url == "") {
386                 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
387                 if ($diaspora != $profile) {
388                         $server_url = $diaspora;
389                         $network = NETWORK_DIASPORA;
390                 }
391         }
392
393         if ($server_url == "") {
394                 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
395                 if ($red != $profile) {
396                         $server_url = $red;
397                         $network = NETWORK_DIASPORA;
398                 }
399         }
400
401         // Mastodon
402         if ($server_url == "") {
403                 $red = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
404                 if ($red != $profile) {
405                         $server_url = $red;
406                         $network = NETWORK_OSTATUS;
407                 }
408         }
409
410         return $server_url;
411 }
412
413 function poco_alternate_ostatus_url($url) {
414         return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
415 }
416
417 function poco_last_updated($profile, $force = false) {
418
419         $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
420                         dbesc(normalise_link($profile)));
421
422         if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
423                 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
424                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
425
426         if ($gcontacts[0]["server_url"] != "")
427                 $server_url = $gcontacts[0]["server_url"];
428         else
429                 $server_url = poco_detect_server($profile);
430
431         if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
432                 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
433                 return false;
434         }
435
436         if ($server_url != "") {
437                 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
438
439                         if ($force)
440                                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
441                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
442
443                         logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
444                         return false;
445                 }
446
447                 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
448                         dbesc($server_url), dbesc(normalise_link($profile)));
449         }
450
451         if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
452                 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
453                         dbesc(normalise_link($server_url)));
454
455                 if ($server)
456                         q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
457                                 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
458                 else
459                         return false;
460         }
461
462         // noscrape is really fast so we don't cache the call.
463         if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
464
465                 //  Use noscrape if possible
466                 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
467
468                 if ($server) {
469                         $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
470
471                          if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
472
473                                 $noscrape = json_decode($noscraperet["body"], true);
474
475                                 if (is_array($noscrape)) {
476                                         $contact = array("url" => $profile,
477                                                         "network" => $server[0]["network"],
478                                                         "generation" => $gcontacts[0]["generation"]);
479
480                                         if (isset($noscrape["fn"]))
481                                                 $contact["name"] = $noscrape["fn"];
482
483                                         if (isset($noscrape["comm"]))
484                                                 $contact["community"] = $noscrape["comm"];
485
486                                         if (isset($noscrape["tags"])) {
487                                                 $keywords = implode(" ", $noscrape["tags"]);
488                                                 if ($keywords != "")
489                                                         $contact["keywords"] = $keywords;
490                                         }
491
492                                         $location = formatted_location($noscrape);
493                                         if ($location)
494                                                 $contact["location"] = $location;
495
496                                         if (isset($noscrape["dfrn-notify"]))
497                                                 $contact["notify"] = $noscrape["dfrn-notify"];
498
499                                         // Remove all fields that are not present in the gcontact table
500                                         unset($noscrape["fn"]);
501                                         unset($noscrape["key"]);
502                                         unset($noscrape["homepage"]);
503                                         unset($noscrape["comm"]);
504                                         unset($noscrape["tags"]);
505                                         unset($noscrape["locality"]);
506                                         unset($noscrape["region"]);
507                                         unset($noscrape["country-name"]);
508                                         unset($noscrape["contacts"]);
509                                         unset($noscrape["dfrn-request"]);
510                                         unset($noscrape["dfrn-confirm"]);
511                                         unset($noscrape["dfrn-notify"]);
512                                         unset($noscrape["dfrn-poll"]);
513
514                                         // Set the date of the last contact
515                                         /// @todo By now the function "update_gcontact" doesn't work with this field
516                                         //$contact["last_contact"] = datetime_convert();
517
518                                         $contact = array_merge($contact, $noscrape);
519
520                                         update_gcontact($contact);
521
522                                         if (trim($noscrape["updated"]) != "") {
523                                                 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
524                                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
525
526                                                 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
527
528                                                 return $noscrape["updated"];
529                                         }
530                                 }
531                         }
532                 }
533         }
534
535         // If we only can poll the feed, then we only do this once a while
536         if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"],  $gcontacts[0]["last_contact"])) {
537                 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
538                 return $gcontacts[0]["updated"];
539         }
540
541         $data = probe_url($profile);
542
543         // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
544         // Then check the other link and delete this one
545         if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
546                 (normalise_link($profile) == normalise_link($data["alias"])) AND
547                 (normalise_link($profile) != normalise_link($data["url"]))) {
548
549                 // Delete the old entry
550                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
551                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
552
553                 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
554                                 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
555
556                 poco_last_updated($data["url"], $force);
557
558                 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
559                 return false;
560         }
561
562         if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
563                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
564                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
565
566                 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
567                 return false;
568         }
569
570         $contact = array("generation" => $gcontacts[0]["generation"]);
571
572         $contact = array_merge($contact, $data);
573
574         $contact["server_url"] = $data["baseurl"];
575
576         unset($contact["batch"]);
577         unset($contact["poll"]);
578         unset($contact["request"]);
579         unset($contact["confirm"]);
580         unset($contact["poco"]);
581         unset($contact["priority"]);
582         unset($contact["pubkey"]);
583         unset($contact["baseurl"]);
584
585         update_gcontact($contact);
586
587         $feedret = z_fetch_url($data["poll"]);
588
589         if (!$feedret["success"]) {
590                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
591                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
592
593                 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
594                 return false;
595         }
596
597         $doc = new DOMDocument();
598         @$doc->loadXML($feedret["body"]);
599
600         $xpath = new DomXPath($doc);
601         $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
602
603         $entries = $xpath->query('/atom:feed/atom:entry');
604
605         $last_updated = "";
606
607         foreach ($entries AS $entry) {
608                 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
609                 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
610
611                 if ($last_updated < $published)
612                         $last_updated = $published;
613
614                 if ($last_updated < $updated)
615                         $last_updated = $updated;
616         }
617
618         // Maybe there aren't any entries. Then check if it is a valid feed
619         if ($last_updated == "")
620                 if ($xpath->query('/atom:feed')->length > 0)
621                         $last_updated = "0000-00-00 00:00:00";
622
623         q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
624                 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
625
626         if (($gcontacts[0]["generation"] == 0))
627                 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
628                         dbesc(normalise_link($profile)));
629
630         logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
631
632         return($last_updated);
633 }
634
635 function poco_do_update($created, $updated, $last_failure,  $last_contact) {
636         $now = strtotime(datetime_convert());
637
638         if ($updated > $last_contact)
639                 $contact_time = strtotime($updated);
640         else
641                 $contact_time = strtotime($last_contact);
642
643         $failure_time = strtotime($last_failure);
644         $created_time = strtotime($created);
645
646         // If there is no "created" time then use the current time
647         if ($created_time <= 0)
648                 $created_time = $now;
649
650         // If the last contact was less than 24 hours then don't update
651         if (($now - $contact_time) < (60 * 60 * 24))
652                 return false;
653
654         // If the last failure was less than 24 hours then don't update
655         if (($now - $failure_time) < (60 * 60 * 24))
656                 return false;
657
658         // If the last contact was less than a week ago and the last failure is older than a week then don't update
659         //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
660         //      return false;
661
662         // 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
663         if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
664                 return false;
665
666         // 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
667         if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
668                 return false;
669
670         return true;
671 }
672
673 function poco_to_boolean($val) {
674         if (($val == "true") OR ($val == 1))
675                 return(true);
676         if (($val == "false") OR ($val == 0))
677                 return(false);
678
679         return ($val);
680 }
681
682 function poco_check_server($server_url, $network = "", $force = false) {
683
684         // Unify the server address
685         $server_url = trim($server_url, "/");
686         $server_url = str_replace("/index.php", "", $server_url);
687
688         if ($server_url == "")
689                 return false;
690
691         $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
692         if ($servers) {
693
694                 if ($servers[0]["created"] == "0000-00-00 00:00:00")
695                         q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
696                                 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
697
698                 $poco = $servers[0]["poco"];
699                 $noscrape = $servers[0]["noscrape"];
700
701                 if ($network == "")
702                         $network = $servers[0]["network"];
703
704                 $last_contact = $servers[0]["last_contact"];
705                 $last_failure = $servers[0]["last_failure"];
706                 $version = $servers[0]["version"];
707                 $platform = $servers[0]["platform"];
708                 $site_name = $servers[0]["site_name"];
709                 $info = $servers[0]["info"];
710                 $register_policy = $servers[0]["register_policy"];
711
712                 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
713                         logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
714                         return ($last_contact >= $last_failure);
715                 }
716         } else {
717                 $poco = "";
718                 $noscrape = "";
719                 $version = "";
720                 $platform = "";
721                 $site_name = "";
722                 $info = "";
723                 $register_policy = -1;
724
725                 $last_contact = "0000-00-00 00:00:00";
726                 $last_failure = "0000-00-00 00:00:00";
727         }
728         logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
729
730         $failure = false;
731         $orig_last_failure = $last_failure;
732
733         // Check if the page is accessible via SSL.
734         $server_url = str_replace("http://", "https://", $server_url);
735         $serverret = z_fetch_url($server_url."/.well-known/host-meta");
736
737         // Maybe the page is unencrypted only?
738         $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
739         if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
740                 $server_url = str_replace("https://", "http://", $server_url);
741                 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
742
743                 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
744         }
745
746         if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
747                 // Workaround for bad configured servers (known nginx problem)
748                 if ($serverret["debug"]["http_code"] != "403") {
749                         $last_failure = datetime_convert();
750                         $failure = true;
751                 }
752         } elseif ($network == NETWORK_DIASPORA)
753                 $last_contact = datetime_convert();
754
755         if (!$failure) {
756                 // Test for Diaspora
757                 $serverret = z_fetch_url($server_url);
758
759                 if (!$serverret["success"] OR ($serverret["body"] == ""))
760                         $failure = true;
761                 else {
762                         $lines = explode("\n",$serverret["header"]);
763                         if(count($lines))
764                                 foreach($lines as $line) {
765                                         $line = trim($line);
766                                         if(stristr($line,'X-Diaspora-Version:')) {
767                                                 $platform = "Diaspora";
768                                                 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
769                                                 $version = trim(str_replace("x-diaspora-version:", "", $version));
770                                                 $network = NETWORK_DIASPORA;
771                                                 $versionparts = explode("-", $version);
772                                                 $version = $versionparts[0];
773                                         }
774
775                                         if(stristr($line,'Server: Mastodon')) {
776                                                 $platform = "Mastodon";
777                                                 $network = NETWORK_OSTATUS;
778                                                 // Mastodon doesn't reveal version numbers
779                                                 $version = "";
780                                         }
781                                 }
782                 }
783         }
784
785         if (!$failure) {
786                 // Test for Statusnet
787                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
788                 // The "not implemented" is a special treatment for really, really old Friendica versions
789                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
790                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
791                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
792                         $platform = "StatusNet";
793                         $version = trim($serverret["body"], '"');
794                         $network = NETWORK_OSTATUS;
795                 }
796
797                 // Test for GNU Social
798                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
799                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
800                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
801                         $platform = "GNU Social";
802                         $version = trim($serverret["body"], '"');
803                         $network = NETWORK_OSTATUS;
804                 }
805
806                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
807                 if ($serverret["success"]) {
808                         $data = json_decode($serverret["body"]);
809
810                         if (isset($data->site->server)) {
811                                 $last_contact = datetime_convert();
812
813                                 if (isset($data->site->hubzilla)) {
814                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
815                                         $version = $data->site->hubzilla->RED_VERSION;
816                                         $network = NETWORK_DIASPORA;
817                                 }
818                                 if (isset($data->site->redmatrix)) {
819                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
820                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
821                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
822                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
823
824                                         $version = $data->site->redmatrix->RED_VERSION;
825                                         $network = NETWORK_DIASPORA;
826                                 }
827                                 if (isset($data->site->friendica)) {
828                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
829                                         $version = $data->site->friendica->FRIENDICA_VERSION;
830                                         $network = NETWORK_DFRN;
831                                 }
832
833                                 $site_name = $data->site->name;
834
835                                 $data->site->closed = poco_to_boolean($data->site->closed);
836                                 $data->site->private = poco_to_boolean($data->site->private);
837                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
838
839                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
840                                         $register_policy = REGISTER_APPROVE;
841                                 elseif (!$data->site->closed AND !$data->site->private)
842                                         $register_policy = REGISTER_OPEN;
843                                 else
844                                         $register_policy = REGISTER_CLOSED;
845                         }
846                 }
847         }
848
849         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
850         if (!$failure) {
851                 $serverret = z_fetch_url($server_url."/statistics.json");
852                 if ($serverret["success"]) {
853                         $data = json_decode($serverret["body"]);
854                         if ($version == "")
855                                 $version = $data->version;
856
857                         $site_name = $data->name;
858
859                         if (isset($data->network) AND ($platform == ""))
860                                 $platform = $data->network;
861
862                         if ($platform == "Diaspora")
863                                 $network = NETWORK_DIASPORA;
864
865                         if ($data->registrations_open)
866                                 $register_policy = REGISTER_OPEN;
867                         else
868                                 $register_policy = REGISTER_CLOSED;
869
870                         if (isset($data->version))
871                                 $last_contact = datetime_convert();
872                 }
873         }
874
875         // Check for noscrape
876         // Friendica servers could be detected as OStatus servers
877         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
878                 $serverret = z_fetch_url($server_url."/friendica/json");
879
880                 if (!$serverret["success"])
881                         $serverret = z_fetch_url($server_url."/friendika/json");
882
883                 if ($serverret["success"]) {
884                         $data = json_decode($serverret["body"]);
885
886                         if (isset($data->version)) {
887                                 $last_contact = datetime_convert();
888                                 $network = NETWORK_DFRN;
889
890                                 $noscrape = $data->no_scrape_url;
891                                 $version = $data->version;
892                                 $site_name = $data->site_name;
893                                 $info = $data->info;
894                                 $register_policy_str = $data->register_policy;
895                                 $platform = $data->platform;
896
897                                 switch ($register_policy_str) {
898                                         case "REGISTER_CLOSED":
899                                                 $register_policy = REGISTER_CLOSED;
900                                                 break;
901                                         case "REGISTER_APPROVE":
902                                                 $register_policy = REGISTER_APPROVE;
903                                                 break;
904                                         case "REGISTER_OPEN":
905                                                 $register_policy = REGISTER_OPEN;
906                                                 break;
907                                 }
908                         }
909                 }
910         }
911
912         // Look for poco
913         if (!$failure) {
914                 $serverret = z_fetch_url($server_url."/poco");
915                 if ($serverret["success"]) {
916                         $data = json_decode($serverret["body"]);
917                         if (isset($data->totalResults)) {
918                                 $poco = $server_url."/poco";
919                                 $last_contact = datetime_convert();
920                         }
921                 }
922         }
923
924         // Check again if the server exists
925         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
926
927         $version = strip_tags($version);
928         $site_name = strip_tags($site_name);
929         $info = strip_tags($info);
930         $platform = strip_tags($platform);
931
932         if ($servers)
933                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
934                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
935                         dbesc($server_url),
936                         dbesc($version),
937                         dbesc($site_name),
938                         dbesc($info),
939                         intval($register_policy),
940                         dbesc($poco),
941                         dbesc($noscrape),
942                         dbesc($network),
943                         dbesc($platform),
944                         dbesc($last_contact),
945                         dbesc($last_failure),
946                         dbesc(normalise_link($server_url))
947                 );
948         else
949                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
950                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
951                                 dbesc($server_url),
952                                 dbesc(normalise_link($server_url)),
953                                 dbesc($version),
954                                 dbesc($site_name),
955                                 dbesc($info),
956                                 intval($register_policy),
957                                 dbesc($poco),
958                                 dbesc($noscrape),
959                                 dbesc($network),
960                                 dbesc($platform),
961                                 dbesc(datetime_convert()),
962                                 dbesc($last_contact),
963                                 dbesc($last_failure),
964                                 dbesc(datetime_convert())
965                 );
966
967         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
968
969         return !$failure;
970 }
971
972 function count_common_friends($uid,$cid) {
973
974         $r = q("SELECT count(*) as `total`
975                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
976                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
977                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
978                 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
979                 intval($cid),
980                 intval($uid),
981                 intval($uid),
982                 intval($cid)
983         );
984
985 //      logger("count_common_friends: $uid $cid {$r[0]['total']}");
986         if (dbm::is_result($r))
987                 return $r[0]['total'];
988         return 0;
989
990 }
991
992
993 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
994
995         if($shuffle)
996                 $sql_extra = " order by rand() ";
997         else
998                 $sql_extra = " order by `gcontact`.`name` asc ";
999
1000         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1001                 FROM `glink`
1002                 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1003                 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1004                 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1005                         AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1006                         AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1007                         AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1008                         $sql_extra LIMIT %d, %d",
1009                 intval($cid),
1010                 intval($uid),
1011                 intval($uid),
1012                 intval($cid),
1013                 intval($start),
1014                 intval($limit)
1015         );
1016
1017         return $r;
1018
1019 }
1020
1021
1022 function count_common_friends_zcid($uid,$zcid) {
1023
1024         $r = q("SELECT count(*) as `total`
1025                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1026                 where `glink`.`zcid` = %d
1027                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1028                 intval($zcid),
1029                 intval($uid)
1030         );
1031
1032         if (dbm::is_result($r))
1033                 return $r[0]['total'];
1034         return 0;
1035
1036 }
1037
1038 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1039
1040         if($shuffle)
1041                 $sql_extra = " order by rand() ";
1042         else
1043                 $sql_extra = " order by `gcontact`.`name` asc ";
1044
1045         $r = q("SELECT `gcontact`.*
1046                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1047                 where `glink`.`zcid` = %d
1048                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) 
1049                 $sql_extra limit %d, %d",
1050                 intval($zcid),
1051                 intval($uid),
1052                 intval($start),
1053                 intval($limit)
1054         );
1055
1056         return $r;
1057
1058 }
1059
1060
1061 function count_all_friends($uid,$cid) {
1062
1063         $r = q("SELECT count(*) as `total`
1064                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1065                 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1066                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1067                 intval($cid),
1068                 intval($uid)
1069         );
1070
1071         if (dbm::is_result($r))
1072                 return $r[0]['total'];
1073         return 0;
1074
1075 }
1076
1077
1078 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1079
1080         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1081                 FROM `glink`
1082                 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1083                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1084                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1085                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1086                 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1087                 intval($uid),
1088                 intval($cid),
1089                 intval($uid),
1090                 intval($start),
1091                 intval($limit)
1092         );
1093
1094         return $r;
1095 }
1096
1097
1098
1099 function suggestion_query($uid, $start = 0, $limit = 80) {
1100
1101         if (!$uid) {
1102                 return array();
1103         }
1104
1105 // Uncommented because the result of the queries are to big to store it in the cache.
1106 // We need to decide if we want to change the db column type or if we want to delete it.
1107 //      $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1108 //      if (!is_null($list)) {
1109 //              return $list;
1110 //      }
1111
1112         $network = array(NETWORK_DFRN);
1113
1114         if (get_config('system','diaspora_enabled'))
1115                 $network[] = NETWORK_DIASPORA;
1116
1117         if (!get_config('system','ostatus_disabled'))
1118                 $network[] = NETWORK_OSTATUS;
1119
1120         $sql_network = implode("', '", $network);
1121         $sql_network = "'".$sql_network."'";
1122
1123         /// @todo This query is really slow
1124         // By now we cache the data for five minutes
1125         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1126                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1127                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1128                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1129                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1130                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1131                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1132                 AND `gcontact`.`network` IN (%s)
1133                 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1134                 intval($uid),
1135                 intval($uid),
1136                 intval($uid),
1137                 intval($uid),
1138                 $sql_network,
1139                 intval($start),
1140                 intval($limit)
1141         );
1142
1143         if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1144 // Uncommented because the result of the queries are to big to store it in the cache.
1145 // We need to decide if we want to change the db column type or if we want to delete it.
1146 //              Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1147
1148                 return $r;
1149         }
1150
1151         $r2 = q("SELECT gcontact.* FROM gcontact
1152                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1153                 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1154                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1155                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1156                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1157                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1158                 AND `gcontact`.`network` IN (%s)
1159                 ORDER BY rand() LIMIT %d, %d",
1160                 intval($uid),
1161                 intval($uid),
1162                 intval($uid),
1163                 $sql_network,
1164                 intval($start),
1165                 intval($limit)
1166         );
1167
1168         $list = array();
1169         foreach ($r2 AS $suggestion)
1170                 $list[$suggestion["nurl"]] = $suggestion;
1171
1172         foreach ($r AS $suggestion)
1173                 $list[$suggestion["nurl"]] = $suggestion;
1174
1175         while (sizeof($list) > ($limit))
1176                 array_pop($list);
1177
1178 // Uncommented because the result of the queries are to big to store it in the cache.
1179 // We need to decide if we want to change the db column type or if we want to delete it.
1180 //      Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1181         return $list;
1182 }
1183
1184 function update_suggestions() {
1185
1186         $a = get_app();
1187
1188         $done = array();
1189
1190         /// TODO Check if it is really neccessary to poll the own server
1191         poco_load(0,0,0,App::get_baseurl() . '/poco');
1192
1193         $done[] = App::get_baseurl() . '/poco';
1194
1195         if (strlen(get_config('system','directory'))) {
1196                 $x = fetch_url(get_server()."/pubsites");
1197                 if ($x) {
1198                         $j = json_decode($x);
1199                         if ($j->entries) {
1200                                 foreach ($j->entries as $entry) {
1201
1202                                         poco_check_server($entry->url);
1203
1204                                         $url = $entry->url . '/poco';
1205                                         if (! in_array($url,$done)) {
1206                                                 poco_load(0,0,0,$entry->url . '/poco');
1207                                         }
1208                                 }
1209                         }
1210                 }
1211         }
1212
1213         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1214         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1215                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1216         );
1217
1218         if (dbm::is_result($r)) {
1219                 foreach ($r as $rr) {
1220                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1221                         if(! in_array($base,$done))
1222                                 poco_load(0,0,0,$base);
1223                 }
1224         }
1225 }
1226
1227 function poco_discover_federation() {
1228         $last = get_config('poco','last_federation_discovery');
1229
1230         if ($last) {
1231                 $next = $last + (24 * 60 * 60);
1232                 if($next > time())
1233                         return;
1234         }
1235
1236         // Discover Friendica, Hubzilla and Diaspora servers
1237         $serverdata = fetch_url("http://the-federation.info/pods.json");
1238
1239         if ($serverdata) {
1240                 $servers = json_decode($serverdata);
1241
1242                 foreach($servers->pods AS $server)
1243                         poco_check_server("https://".$server->host);
1244         }
1245
1246         // Discover GNU Social Servers
1247         if (!get_config('system','ostatus_disabled')) {
1248                 $serverdata = "http://gstools.org/api/get_open_instances/";
1249
1250                 $result = z_fetch_url($serverdata);
1251                 if ($result["success"]) {
1252                         $servers = json_decode($result["body"]);
1253
1254                         foreach($servers->data AS $server)
1255                                 poco_check_server($server->instance_address);
1256                 }
1257         }
1258
1259         set_config('poco','last_federation_discovery', time());
1260 }
1261
1262 function poco_discover($complete = false) {
1263
1264         // Update the server list
1265         poco_discover_federation();
1266
1267         $no_of_queries = 5;
1268
1269         $requery_days = intval(get_config("system", "poco_requery_days"));
1270
1271         if ($requery_days == 0)
1272                 $requery_days = 7;
1273
1274         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1275
1276         $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));
1277         if ($r)
1278                 foreach ($r AS $server) {
1279
1280                         if (!poco_check_server($server["url"], $server["network"])) {
1281                                 // The server is not reachable? Okay, then we will try it later
1282                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1283                                 continue;
1284                         }
1285
1286                         // Fetch all users from the other server
1287                         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1288
1289                         logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1290
1291                         $retdata = z_fetch_url($url);
1292                         if ($retdata["success"]) {
1293                                 $data = json_decode($retdata["body"]);
1294
1295                                 poco_discover_server($data, 2);
1296
1297                                 if (get_config('system','poco_discovery') > 1) {
1298
1299                                         $timeframe = get_config('system','poco_discovery_since');
1300                                         if ($timeframe == 0)
1301                                                 $timeframe = 30;
1302
1303                                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1304
1305                                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1306                                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1307
1308                                         $success = false;
1309
1310                                         $retdata = z_fetch_url($url);
1311                                         if ($retdata["success"]) {
1312                                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1313                                                 $success = poco_discover_server(json_decode($retdata["body"]));
1314                                         }
1315
1316                                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1317                                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1318                                                 poco_discover_server_users($data, $server);
1319                                         }
1320                                 }
1321
1322                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1323                                 if (!$complete AND (--$no_of_queries == 0))
1324                                         break;
1325                         } else {
1326                                 // If the server hadn't replied correctly, then force a sanity check
1327                                 poco_check_server($server["url"], $server["network"], true);
1328
1329                                 // If we couldn't reach the server, we will try it some time later
1330                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1331                         }
1332                 }
1333 }
1334
1335 function poco_discover_server_users($data, $server) {
1336
1337         if (!isset($data->entry))
1338                 return;
1339
1340         foreach ($data->entry AS $entry) {
1341                 $username = "";
1342                 if (isset($entry->urls)) {
1343                         foreach($entry->urls as $url)
1344                                 if ($url->type == 'profile') {
1345                                         $profile_url = $url->value;
1346                                         $urlparts = parse_url($profile_url);
1347                                         $username = end(explode("/", $urlparts["path"]));
1348                                 }
1349                 }
1350                 if ($username != "") {
1351                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1352
1353                         // Fetch all contacts from a given user from the other server
1354                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1355
1356                         $retdata = z_fetch_url($url);
1357                         if ($retdata["success"])
1358                                 poco_discover_server(json_decode($retdata["body"]), 3);
1359                 }
1360         }
1361 }
1362
1363 function poco_discover_server($data, $default_generation = 0) {
1364
1365         if (!isset($data->entry) OR !count($data->entry))
1366                 return false;
1367
1368         $success = false;
1369
1370         foreach ($data->entry AS $entry) {
1371                 $profile_url = '';
1372                 $profile_photo = '';
1373                 $connect_url = '';
1374                 $name = '';
1375                 $network = '';
1376                 $updated = '0000-00-00 00:00:00';
1377                 $location = '';
1378                 $about = '';
1379                 $keywords = '';
1380                 $gender = '';
1381                 $contact_type = -1;
1382                 $generation = $default_generation;
1383
1384                 $name = $entry->displayName;
1385
1386                 if (isset($entry->urls)) {
1387                         foreach($entry->urls as $url) {
1388                                 if ($url->type == 'profile') {
1389                                         $profile_url = $url->value;
1390                                         continue;
1391                                 }
1392                                 if ($url->type == 'webfinger') {
1393                                         $connect_url = str_replace('acct:' , '', $url->value);
1394                                         continue;
1395                                 }
1396                         }
1397                 }
1398
1399                 if (isset($entry->photos)) {
1400                         foreach ($entry->photos as $photo) {
1401                                 if ($photo->type == 'profile') {
1402                                         $profile_photo = $photo->value;
1403                                         continue;
1404                                 }
1405                         }
1406                 }
1407
1408                 if (isset($entry->updated)) {
1409                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1410                 }
1411
1412                 if(isset($entry->network)) {
1413                         $network = $entry->network;
1414                 }
1415
1416                 if(isset($entry->currentLocation)) {
1417                         $location = $entry->currentLocation;
1418                 }
1419
1420                 if(isset($entry->aboutMe)) {
1421                         $about = html2bbcode($entry->aboutMe);
1422                 }
1423
1424                 if(isset($entry->gender)) {
1425                         $gender = $entry->gender;
1426                 }
1427
1428                 if(isset($entry->generation) AND ($entry->generation > 0)) {
1429                         $generation = ++$entry->generation;
1430                 }
1431
1432                 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1433                         $contact_type = $entry->contactType;
1434                 }
1435
1436                 if(isset($entry->tags)) {
1437                         foreach ($entry->tags as $tag) {
1438                                 $keywords = implode(", ", $tag);
1439                         }
1440                 }
1441
1442                 if ($generation > 0) {
1443                         $success = true;
1444
1445                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1446                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1447
1448                         $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
1449                         update_gcontact($gcontact);
1450
1451                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1452                 }
1453         }
1454         return $success;
1455 }
1456
1457 /**
1458  * @brief Removes unwanted parts from a contact url
1459  *
1460  * @param string $url Contact url
1461  * @return string Contact url with the wanted parts
1462  */
1463 function clean_contact_url($url) {
1464         $parts = parse_url($url);
1465
1466         if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1467                 return $url;
1468
1469         $new_url = $parts["scheme"]."://".$parts["host"];
1470
1471         if (isset($parts["port"]))
1472                 $new_url .= ":".$parts["port"];
1473
1474         if (isset($parts["path"]))
1475                 $new_url .= $parts["path"];
1476
1477         if ($new_url != $url)
1478                 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1479
1480         return $new_url;
1481 }
1482
1483 /**
1484  * @brief Replace alternate OStatus user format with the primary one
1485  *
1486  * @param arr $contact contact array (called by reference)
1487  */
1488 function fix_alternate_contact_address(&$contact) {
1489         if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1490                 $data = probe_url($contact["url"]);
1491                 if ($contact["network"] == NETWORK_OSTATUS) {
1492                         logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1493                         $contact["url"] = $data["url"];
1494                         $contact["addr"] = $data["addr"];
1495                         $contact["alias"] = $data["alias"];
1496                         $contact["server_url"] = $data["baseurl"];
1497                 }
1498         }
1499 }
1500
1501 /**
1502  * @brief Fetch the gcontact id, add an entry if not existed
1503  *
1504  * @param arr $contact contact array
1505  * @return bool|int Returns false if not found, integer if contact was found
1506  */
1507 function get_gcontact_id($contact) {
1508
1509         $gcontact_id = 0;
1510         $doprobing = false;
1511
1512         if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1513                 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1514                 return false;
1515         }
1516
1517         if ($contact["network"] == NETWORK_STATUSNET)
1518                 $contact["network"] = NETWORK_OSTATUS;
1519
1520         // All new contacts are hidden by default
1521         if (!isset($contact["hide"]))
1522                 $contact["hide"] = true;
1523
1524         // Replace alternate OStatus user format with the primary one
1525         fix_alternate_contact_address($contact);
1526
1527         // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1528         if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1529                 $contact["url"] = clean_contact_url($contact["url"]);
1530
1531         $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1532                 dbesc(normalise_link($contact["url"])));
1533
1534         if ($r) {
1535                 $gcontact_id = $r[0]["id"];
1536
1537                 // Update every 90 days
1538                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
1539                         $last_failure_str = $r[0]["last_failure"];
1540                         $last_failure = strtotime($r[0]["last_failure"]);
1541                         $last_contact_str = $r[0]["last_contact"];
1542                         $last_contact = strtotime($r[0]["last_contact"]);
1543                         $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
1544                 }
1545         } else {
1546                 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
1547                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
1548                         dbesc($contact["name"]),
1549                         dbesc($contact["nick"]),
1550                         dbesc($contact["addr"]),
1551                         dbesc($contact["network"]),
1552                         dbesc($contact["url"]),
1553                         dbesc(normalise_link($contact["url"])),
1554                         dbesc($contact["photo"]),
1555                         dbesc(datetime_convert()),
1556                         dbesc(datetime_convert()),
1557                         dbesc($contact["location"]),
1558                         dbesc($contact["about"]),
1559                         intval($contact["hide"]),
1560                         intval($contact["generation"])
1561                 );
1562
1563                 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1564                         dbesc(normalise_link($contact["url"])));
1565
1566                 if ($r) {
1567                         $gcontact_id = $r[0]["id"];
1568
1569                         $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
1570                 }
1571         }
1572
1573         if ($doprobing) {
1574                 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
1575                 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
1576         }
1577
1578         if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1579          q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1580                 dbesc(normalise_link($contact["url"])),
1581                 intval($gcontact_id));
1582
1583         return $gcontact_id;
1584 }
1585
1586 /**
1587  * @brief Updates the gcontact table from a given array
1588  *
1589  * @param arr $contact contact array
1590  * @return bool|int Returns false if not found, integer if contact was found
1591  */
1592 function update_gcontact($contact) {
1593
1594         /// @todo update contact table as well
1595
1596         $gcontact_id = get_gcontact_id($contact);
1597
1598         if (!$gcontact_id)
1599                 return false;
1600
1601         $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1602                         `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1603                 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1604                 intval($gcontact_id));
1605
1606         // Get all field names
1607         $fields = array();
1608         foreach ($r[0] AS $field => $data)
1609                 $fields[$field] = $data;
1610
1611         unset($fields["url"]);
1612         unset($fields["updated"]);
1613         unset($fields["hide"]);
1614
1615         // Bugfix: We had an error in the storing of keywords which lead to the "0"
1616         // This value is still transmitted via poco.
1617         if ($contact["keywords"] == "0")
1618                 unset($contact["keywords"]);
1619
1620         if ($r[0]["keywords"] == "0")
1621                 $r[0]["keywords"] = "";
1622
1623         // assign all unassigned fields from the database entry
1624         foreach ($fields AS $field => $data)
1625                 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1626                         $contact[$field] = $r[0][$field];
1627
1628         if (!isset($contact["hide"]))
1629                 $contact["hide"] = $r[0]["hide"];
1630
1631         $fields["hide"] = $r[0]["hide"];
1632
1633         if ($contact["network"] == NETWORK_STATUSNET)
1634                 $contact["network"] = NETWORK_OSTATUS;
1635
1636         // Replace alternate OStatus user format with the primary one
1637         fix_alternate_contact_address($contact);
1638
1639         if (!isset($contact["updated"]))
1640                 $contact["updated"] = datetime_convert();
1641
1642         if ($contact["server_url"] == "") {
1643                 $server_url = $contact["url"];
1644
1645                 $server_url = matching_url($server_url, $contact["alias"]);
1646                 if ($server_url != "")
1647                         $contact["server_url"] = $server_url;
1648
1649                 $server_url = matching_url($server_url, $contact["photo"]);
1650                 if ($server_url != "")
1651                         $contact["server_url"] = $server_url;
1652
1653                 $server_url = matching_url($server_url, $contact["notify"]);
1654                 if ($server_url != "")
1655                         $contact["server_url"] = $server_url;
1656         } else
1657                 $contact["server_url"] = normalise_link($contact["server_url"]);
1658
1659         if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1660                 $hostname = str_replace("http://", "", $contact["server_url"]);
1661                 $contact["addr"] = $contact["nick"]."@".$hostname;
1662         }
1663
1664         // Check if any field changed
1665         $update = false;
1666         unset($fields["generation"]);
1667
1668         if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1669                 foreach ($fields AS $field => $data)
1670                         if ($contact[$field] != $r[0][$field]) {
1671                                 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1672                                 $update = true;
1673                         }
1674
1675                 if ($contact["generation"] < $r[0]["generation"]) {
1676                         logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1677                         $update = true;
1678                 }
1679         }
1680
1681         if ($update) {
1682                 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
1683
1684                 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1685                                         `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1686                                         `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
1687                                         `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1688                                         `server_url` = '%s', `connect` = '%s'
1689                                 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1690                         dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1691                         dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1692                         dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1693                         intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
1694                         dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
1695                         dbesc($contact["about"]), intval($contact["generation"]), dbesc($contact["updated"]),
1696                         dbesc($contact["server_url"]), dbesc($contact["connect"]),
1697                         dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1698
1699
1700                 // Now update the contact entry with the user id "0" as well.
1701                 // This is used for the shadow copies of public items.
1702                 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1703                         dbesc(normalise_link($contact["url"])));
1704
1705                 if ($r) {
1706                         logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1707
1708                         update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1709
1710                         q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1711                                                 `network` = '%s', `bd` = '%s', `gender` = '%s',
1712                                                 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
1713                                                 `url` = '%s', `location` = '%s', `about` = '%s'
1714                                         WHERE `id` = %d",
1715                                 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1716                                 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1717                                 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
1718                                 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1719                                 intval($r[0]["id"]));
1720                 }
1721         }
1722
1723         return $gcontact_id;
1724 }
1725
1726 /**
1727  * @brief Updates the gcontact entry from probe
1728  *
1729  * @param str $url profile link
1730  */
1731 function update_gcontact_from_probe($url) {
1732         $data = probe_url($url);
1733
1734         if (in_array($data["network"], array(NETWORK_PHANTOM))) {
1735                 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1736                 return;
1737         }
1738
1739         update_gcontact($data);
1740 }
1741
1742 /**
1743  * @brief Update the gcontact entry for a given user id
1744  *
1745  * @param int $uid User ID
1746  */
1747 function update_gcontact_for_user($uid) {
1748         $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1749                         `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1750                         `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1751                         `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1752                         `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1753                 FROM `profile`
1754                         INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1755                         INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1756                 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1757                 intval($uid));
1758
1759         $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
1760                                                 "country-name" => $r[0]["country-name"]));
1761
1762         // The "addr" field was added in 3.4.3 so it can be empty for older users
1763         if ($r[0]["addr"] != "")
1764                 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
1765         else
1766                 $addr = $r[0]["addr"];
1767
1768         $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
1769                         "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
1770                         "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1771                         "notify" => $r[0]["notify"], "url" => $r[0]["url"],
1772                         "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
1773                         "nick" => $r[0]["nickname"], "addr" => $addr,
1774                         "connect" => $addr, "server_url" => App::get_baseurl(),
1775                         "generation" => 1, "network" => NETWORK_DFRN);
1776
1777         update_gcontact($gcontact);
1778 }
1779
1780 /**
1781  * @brief Fetches users of given GNU Social server
1782  *
1783  * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1784  *
1785  * @param str $server Server address
1786  */
1787 function gs_fetch_users($server) {
1788
1789         logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1790
1791         $url = $server."/main/statistics";
1792
1793         $result = z_fetch_url($url);
1794         if (!$result["success"])
1795                 return false;
1796
1797         $statistics = json_decode($result["body"]);
1798
1799         if (is_object($statistics->config)) {
1800                 if ($statistics->config->instance_with_ssl)
1801                         $server = "https://";
1802                 else
1803                         $server = "http://";
1804
1805                 $server .= $statistics->config->instance_address;
1806
1807                 $hostname = $statistics->config->instance_address;
1808         } else {
1809                 if ($statistics->instance_with_ssl)
1810                         $server = "https://";
1811                 else
1812                         $server = "http://";
1813
1814                 $server .= $statistics->instance_address;
1815
1816                 $hostname = $statistics->instance_address;
1817         }
1818
1819         if (is_object($statistics->users))
1820                 foreach ($statistics->users AS $nick => $user) {
1821                         $profile_url = $server."/".$user->nickname;
1822
1823                         $contact = array("url" => $profile_url,
1824                                         "name" => $user->fullname,
1825                                         "addr" => $user->nickname."@".$hostname,
1826                                         "nick" => $user->nickname,
1827                                         "about" => $user->bio,
1828                                         "network" => NETWORK_OSTATUS,
1829                                         "photo" => App::get_baseurl()."/images/person-175.jpg");
1830                         get_gcontact_id($contact);
1831                 }
1832 }
1833
1834 /**
1835  * @brief Asking GNU Social server on a regular base for their user data
1836  *
1837  */
1838 function gs_discover() {
1839
1840         $requery_days = intval(get_config("system", "poco_requery_days"));
1841
1842         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1843
1844         $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",
1845                 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1846
1847         if (!$r)
1848                 return;
1849
1850         foreach ($r AS $server) {
1851                 gs_fetch_users($server["url"]);
1852                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1853         }
1854 }
1855 ?>