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