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