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