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