]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
ff9467748f2edcbb8947535b7611d243918f7356
[friendica.git] / include / socgraph.php
1 <?php
2 /**
3  * @file include/socgraph.php
4  * 
5  * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6  * @todo Fetch profile data from profile page for Redmatrix users
7  * @todo Detect if it is a forum
8  */
9
10 require_once('include/datetime.php');
11 require_once("include/Scrape.php");
12 require_once("include/network.php");
13 require_once("include/html2bbcode.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
16
17 /*
18  * poco_load
19  *
20  * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
21  * and add the entries to the gcontact (Global Contact) table, or update existing entries
22  * if anything (name or photo) has changed.
23  * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
24  *
25  * Once the global contact is stored add (if necessary) the contact linkage which associates
26  * the given uid, cid to the global contact entry. There can be many uid/cid combinations
27  * pointing to the same global contact id.
28  *
29  */
30
31
32
33
34 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
35
36         $a = get_app();
37
38         if($cid) {
39                 if((! $url) || (! $uid)) {
40                         $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
41                                 intval($cid)
42                         );
43                         if (dbm::is_result($r)) {
44                                 $url = $r[0]['poco'];
45                                 $uid = $r[0]['uid'];
46                         }
47                 }
48                 if(! $uid)
49                         return;
50         }
51
52         if(! $url)
53                 return;
54
55         $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ;
56
57         logger('poco_load: ' . $url, LOGGER_DEBUG);
58
59         $s = fetch_url($url);
60
61         logger('poco_load: returns ' . $s, LOGGER_DATA);
62
63         logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
64
65         if(($a->get_curl_code() > 299) || (! $s))
66                 return;
67
68         $j = json_decode($s);
69
70         logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
71
72         if(! isset($j->entry))
73                 return;
74
75         $total = 0;
76         foreach($j->entry as $entry) {
77
78                 $total ++;
79                 $profile_url = '';
80                 $profile_photo = '';
81                 $connect_url = '';
82                 $name = '';
83                 $network = '';
84                 $updated = '0000-00-00 00:00:00';
85                 $location = '';
86                 $about = '';
87                 $keywords = '';
88                 $gender = '';
89                 $contact_type = -1;
90                 $generation = 0;
91
92                 $name = $entry->displayName;
93
94                 if (isset($entry->urls)) {
95                         foreach ($entry->urls as $url) {
96                                 if ($url->type == 'profile') {
97                                         $profile_url = $url->value;
98                                         continue;
99                                 }
100                                 if ($url->type == 'webfinger') {
101                                         $connect_url = str_replace('acct:' , '', $url->value);
102                                         continue;
103                                 }
104                         }
105                 }
106                 if (isset($entry->photos)) {
107                         foreach ($entry->photos as $photo) {
108                                 if ($photo->type == 'profile') {
109                                         $profile_photo = $photo->value;
110                                         continue;
111                                 }
112                         }
113                 }
114
115                 if (isset($entry->updated)) {
116                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
117                 }
118
119                 if (isset($entry->network)) {
120                         $network = $entry->network;
121                 }
122
123                 if (isset($entry->currentLocation)) {
124                         $location = $entry->currentLocation;
125                 }
126
127                 if (isset($entry->aboutMe)) {
128                         $about = html2bbcode($entry->aboutMe);
129                 }
130
131                 if (isset($entry->gender)) {
132                         $gender = $entry->gender;
133                 }
134
135                 if (isset($entry->generation) AND ($entry->generation > 0)) {
136                         $generation = ++$entry->generation;
137                 }
138
139                 if (isset($entry->tags)) {
140                         foreach($entry->tags as $tag) {
141                                 $keywords = implode(", ", $tag);
142                         }
143                 }
144
145                 if (isset($entry->contactType) AND ($entry->contactType >= 0))
146                         $contact_type = $entry->contactType;
147
148                 // If you query a Friendica server for its profiles, the network has to be Friendica
149                 /// TODO It could also be a Redmatrix server
150                 //if ($uid == 0)
151                 //      $network = NETWORK_DFRN;
152
153                 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
154
155                 $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
156                 update_gcontact($gcontact);
157
158                 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
159                 // Deactivated because we now update Friendica contacts in dfrn.php
160                 //if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
161                 //      q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
162                 //              WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
163                 //              dbesc($location),
164                 //              dbesc($about),
165                 //              dbesc($keywords),
166                 //              dbesc($gender),
167                 //              dbesc(normalise_link($profile_url)),
168                 //              dbesc(NETWORK_DFRN));
169         }
170         logger("poco_load: loaded $total entries",LOGGER_DEBUG);
171
172         q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
173                 intval($cid),
174                 intval($uid),
175                 intval($zcid)
176         );
177
178 }
179
180 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
181
182         // Generation:
183         //  0: No definition
184         //  1: Profiles on this server
185         //  2: Contacts of profiles on this server
186         //  3: Contacts of contacts of profiles on this server
187         //  4: ...
188
189         $gcid = "";
190
191         if ($profile_url == "")
192                 return $gcid;
193
194         $urlparts = parse_url($profile_url);
195         if (!isset($urlparts["scheme"]))
196                 return $gcid;
197
198         if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
199                                                 "identi.ca", "alpha.app.net")))
200                 return $gcid;
201
202         // Don't store the statusnet connector as network
203         // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
204         if ($network == NETWORK_STATUSNET)
205                 $network = "";
206
207         // Assure that there are no parameter fragments in the profile url
208         if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
209                 $profile_url = clean_contact_url($profile_url);
210
211         $alternate = poco_alternate_ostatus_url($profile_url);
212
213         $orig_updated = $updated;
214
215         // The global contacts should contain the original picture, not the cached one
216         if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link(App::get_baseurl()."/photo/"))) {
217                 $profile_photo = "";
218         }
219
220         $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
221                 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
222         );
223         if (dbm::is_result($r)) {
224                 $network = $r[0]["network"];
225         }
226
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 == "0000-00-00 00:00:00")
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 = "0000-00-00 00:00:00";
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"] == "0000-00-00 00:00:00")
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 = "0000-00-00 00:00:00";
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_detect_friendica_server($body) {
684         $server = false;
685
686         $doc = new \DOMDocument();
687         @$doc->loadHTML($body);
688         $xpath = new \DomXPath($doc);
689
690         $list = $xpath->query("//meta[@name]");
691
692         foreach ($list as $node) {
693                 $attr = array();
694                 if ($node->attributes->length) {
695                         foreach ($node->attributes as $attribute) {
696                                 $attr[$attribute->name] = $attribute->value;
697                         }
698                 }
699                 if ($attr['name'] == 'generator') {
700                         $version_part = explode(" ", $attr['content']);
701                         if (count($version_part) == 2) {
702                                 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
703                                         $server = array();
704                                         $server["platform"] = $version_part[0];
705                                         $server["version"] = $version_part[1];
706                                         $server["network"] = NETWORK_DFRN;
707                                 }
708                         }
709                 }
710         }
711
712         if (!$server) {
713                 return false;
714         }
715
716         $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
717         return $server;
718 }
719
720 function poco_check_server($server_url, $network = "", $force = false) {
721
722         // Unify the server address
723         $server_url = trim($server_url, "/");
724         $server_url = str_replace("/index.php", "", $server_url);
725
726         if ($server_url == "")
727                 return false;
728
729         $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
730         if ($servers) {
731
732                 if ($servers[0]["created"] == "0000-00-00 00:00:00")
733                         q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
734                                 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
735
736                 $poco = $servers[0]["poco"];
737                 $noscrape = $servers[0]["noscrape"];
738
739                 if ($network == "")
740                         $network = $servers[0]["network"];
741
742                 $last_contact = $servers[0]["last_contact"];
743                 $last_failure = $servers[0]["last_failure"];
744                 $version = $servers[0]["version"];
745                 $platform = $servers[0]["platform"];
746                 $site_name = $servers[0]["site_name"];
747                 $info = $servers[0]["info"];
748                 $register_policy = $servers[0]["register_policy"];
749
750                 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
751                         logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
752                         return ($last_contact >= $last_failure);
753                 }
754         } else {
755                 $poco = "";
756                 $noscrape = "";
757                 $version = "";
758                 $platform = "";
759                 $site_name = "";
760                 $info = "";
761                 $register_policy = -1;
762
763                 $last_contact = "0000-00-00 00:00:00";
764                 $last_failure = "0000-00-00 00:00:00";
765         }
766         logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
767
768         $failure = false;
769         $possible_failure = false;
770         $orig_last_failure = $last_failure;
771         $orig_last_contact = $last_contact;
772
773         // Check if the page is accessible via SSL.
774         $server_url = str_replace("http://", "https://", $server_url);
775         $serverret = z_fetch_url($server_url."/.well-known/host-meta");
776
777         // Maybe the page is unencrypted only?
778         $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
779         if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
780                 $server_url = str_replace("https://", "http://", $server_url);
781                 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
782
783                 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
784         }
785
786         if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
787                 // Workaround for bad configured servers (known nginx problem)
788                 if ($serverret["debug"]["http_code"] != "403") {
789                         $last_failure = datetime_convert();
790                         $failure = true;
791                 }
792                 $possible_failure = true;
793         } elseif ($network == NETWORK_DIASPORA)
794                 $last_contact = datetime_convert();
795
796         if (!$failure) {
797                 // Test for Diaspora
798                 $serverret = z_fetch_url($server_url);
799
800                 if (!$serverret["success"] OR ($serverret["body"] == "")) {
801                         $last_failure = datetime_convert();
802                         $failure = true;
803                 } else {
804                         $lines = explode("\n",$serverret["header"]);
805                         if(count($lines)) {
806                                 foreach($lines as $line) {
807                                         $line = trim($line);
808                                         if(stristr($line,'X-Diaspora-Version:')) {
809                                                 $platform = "Diaspora";
810                                                 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
811                                                 $version = trim(str_replace("x-diaspora-version:", "", $version));
812                                                 $network = NETWORK_DIASPORA;
813                                                 $versionparts = explode("-", $version);
814                                                 $version = $versionparts[0];
815                                                 $last_contact = datetime_convert();
816                                         }
817
818                                         if(stristr($line,'Server: Mastodon')) {
819                                                 $platform = "Mastodon";
820                                                 $network = NETWORK_OSTATUS;
821                                                 // Mastodon doesn't reveal version numbers
822                                                 $version = "";
823                                                 $last_contact = datetime_convert();
824                                         }
825                                 }
826                         }
827
828                         $friendica_server = poco_detect_friendica_server($serverret["body"]);
829                         if ($friendica_server) {
830                                 $platform = $friendica_server['platform'];
831                                 $network = $friendica_server['network'];
832                                 $version = $friendica_server['version'];
833                                 $site_name = $friendica_server['site_name'];
834                                 $last_contact = datetime_convert();
835                         }
836                 }
837         }
838
839         if (!$failure) {
840                 // Test for Statusnet
841                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
842                 // The "not implemented" is a special treatment for really, really old Friendica versions
843                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
844                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
845                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
846                         $platform = "StatusNet";
847                         $version = trim($serverret["body"], '"');
848                         $network = NETWORK_OSTATUS;
849                         $last_contact = datetime_convert();
850                 }
851
852                 // Test for GNU Social
853                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
854                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
855                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
856                         $platform = "GNU Social";
857                         $version = trim($serverret["body"], '"');
858                         $network = NETWORK_OSTATUS;
859                         $last_contact = datetime_convert();
860                 }
861
862                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
863                 if ($serverret["success"]) {
864                         $data = json_decode($serverret["body"]);
865                         if (isset($data->site->server)) {
866                                 $last_contact = datetime_convert();
867
868                                 if (isset($data->site->hubzilla)) {
869                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
870                                         $version = $data->site->hubzilla->RED_VERSION;
871                                         $network = NETWORK_DIASPORA;
872                                 }
873                                 if (isset($data->site->redmatrix)) {
874                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
875                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
876                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
877                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
878
879                                         $version = $data->site->redmatrix->RED_VERSION;
880                                         $network = NETWORK_DIASPORA;
881                                 }
882                                 if (isset($data->site->friendica)) {
883                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
884                                         $version = $data->site->friendica->FRIENDICA_VERSION;
885                                         $network = NETWORK_DFRN;
886                                 }
887
888                                 $site_name = $data->site->name;
889
890                                 $data->site->closed = poco_to_boolean($data->site->closed);
891                                 $data->site->private = poco_to_boolean($data->site->private);
892                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
893
894                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
895                                         $register_policy = REGISTER_APPROVE;
896                                 elseif (!$data->site->closed AND !$data->site->private)
897                                         $register_policy = REGISTER_OPEN;
898                                 else
899                                         $register_policy = REGISTER_CLOSED;
900                         }
901                 }
902         }
903
904
905         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
906         if (!$failure) {
907                 $serverret = z_fetch_url($server_url."/statistics.json");
908                 if ($serverret["success"]) {
909                         $data = json_decode($serverret["body"]);
910                         if ($version == "")
911                                 $version = $data->version;
912
913                         $site_name = $data->name;
914
915                         if (isset($data->network) AND ($platform == ""))
916                                 $platform = $data->network;
917
918                         if ($platform == "Diaspora")
919                                 $network = NETWORK_DIASPORA;
920
921                         if ($data->registrations_open)
922                                 $register_policy = REGISTER_OPEN;
923                         else
924                                 $register_policy = REGISTER_CLOSED;
925
926                         if (isset($data->version))
927                                 $last_contact = datetime_convert();
928                 }
929         }
930
931         // Check for noscrape
932         // Friendica servers could be detected as OStatus servers
933         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
934                 $serverret = z_fetch_url($server_url."/friendica/json");
935
936                 if (!$serverret["success"])
937                         $serverret = z_fetch_url($server_url."/friendika/json");
938
939                 if ($serverret["success"]) {
940                         $data = json_decode($serverret["body"]);
941
942                         if (isset($data->version)) {
943                                 $last_contact = datetime_convert();
944                                 $network = NETWORK_DFRN;
945
946                                 $noscrape = $data->no_scrape_url;
947                                 $version = $data->version;
948                                 $site_name = $data->site_name;
949                                 $info = $data->info;
950                                 $register_policy_str = $data->register_policy;
951                                 $platform = $data->platform;
952
953                                 switch ($register_policy_str) {
954                                         case "REGISTER_CLOSED":
955                                                 $register_policy = REGISTER_CLOSED;
956                                                 break;
957                                         case "REGISTER_APPROVE":
958                                                 $register_policy = REGISTER_APPROVE;
959                                                 break;
960                                         case "REGISTER_OPEN":
961                                                 $register_policy = REGISTER_OPEN;
962                                                 break;
963                                 }
964                         }
965                 }
966         }
967
968         // Look for poco
969         if (!$failure) {
970                 $serverret = z_fetch_url($server_url."/poco");
971                 if ($serverret["success"]) {
972                         $data = json_decode($serverret["body"]);
973                         if (isset($data->totalResults)) {
974                                 $poco = $server_url."/poco";
975                                 $last_contact = datetime_convert();
976                         }
977                 }
978         }
979
980         if ($possible_failure AND !$failure) {
981                 $last_failure = datetime_convert();
982                 $failure = true;
983         }
984
985         if ($failure) {
986                 $last_contact = $orig_last_contact;
987         } else {
988                 $last_failure = $orig_last_failure;
989         }
990
991         if (($last_contact <= $last_failure) AND !$failure) {
992                 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
993         } else if (($last_contact >= $last_failure) AND $failure) {
994                 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
995         }
996
997         // Check again if the server exists
998         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
999
1000         $version = strip_tags($version);
1001         $site_name = strip_tags($site_name);
1002         $info = strip_tags($info);
1003         $platform = strip_tags($platform);
1004
1005         if ($servers)
1006                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1007                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1008                         dbesc($server_url),
1009                         dbesc($version),
1010                         dbesc($site_name),
1011                         dbesc($info),
1012                         intval($register_policy),
1013                         dbesc($poco),
1014                         dbesc($noscrape),
1015                         dbesc($network),
1016                         dbesc($platform),
1017                         dbesc($last_contact),
1018                         dbesc($last_failure),
1019                         dbesc(normalise_link($server_url))
1020                 );
1021         else
1022                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1023                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1024                                 dbesc($server_url),
1025                                 dbesc(normalise_link($server_url)),
1026                                 dbesc($version),
1027                                 dbesc($site_name),
1028                                 dbesc($info),
1029                                 intval($register_policy),
1030                                 dbesc($poco),
1031                                 dbesc($noscrape),
1032                                 dbesc($network),
1033                                 dbesc($platform),
1034                                 dbesc(datetime_convert()),
1035                                 dbesc($last_contact),
1036                                 dbesc($last_failure),
1037                                 dbesc(datetime_convert())
1038                 );
1039
1040         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
1041
1042         return !$failure;
1043 }
1044
1045 function count_common_friends($uid,$cid) {
1046
1047         $r = q("SELECT count(*) as `total`
1048                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1049                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1050                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1051                 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1052                 intval($cid),
1053                 intval($uid),
1054                 intval($uid),
1055                 intval($cid)
1056         );
1057
1058 //      logger("count_common_friends: $uid $cid {$r[0]['total']}");
1059         if (dbm::is_result($r))
1060                 return $r[0]['total'];
1061         return 0;
1062
1063 }
1064
1065
1066 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1067
1068         if($shuffle)
1069                 $sql_extra = " order by rand() ";
1070         else
1071                 $sql_extra = " order by `gcontact`.`name` asc ";
1072
1073         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1074                 FROM `glink`
1075                 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1076                 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1077                 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1078                         AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1079                         AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1080                         AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1081                         $sql_extra LIMIT %d, %d",
1082                 intval($cid),
1083                 intval($uid),
1084                 intval($uid),
1085                 intval($cid),
1086                 intval($start),
1087                 intval($limit)
1088         );
1089
1090         return $r;
1091
1092 }
1093
1094
1095 function count_common_friends_zcid($uid,$zcid) {
1096
1097         $r = q("SELECT count(*) as `total`
1098                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1099                 where `glink`.`zcid` = %d
1100                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1101                 intval($zcid),
1102                 intval($uid)
1103         );
1104
1105         if (dbm::is_result($r))
1106                 return $r[0]['total'];
1107         return 0;
1108
1109 }
1110
1111 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1112
1113         if($shuffle)
1114                 $sql_extra = " order by rand() ";
1115         else
1116                 $sql_extra = " order by `gcontact`.`name` asc ";
1117
1118         $r = q("SELECT `gcontact`.*
1119                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1120                 where `glink`.`zcid` = %d
1121                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) 
1122                 $sql_extra limit %d, %d",
1123                 intval($zcid),
1124                 intval($uid),
1125                 intval($start),
1126                 intval($limit)
1127         );
1128
1129         return $r;
1130
1131 }
1132
1133
1134 function count_all_friends($uid,$cid) {
1135
1136         $r = q("SELECT count(*) as `total`
1137                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1138                 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1139                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1140                 intval($cid),
1141                 intval($uid)
1142         );
1143
1144         if (dbm::is_result($r))
1145                 return $r[0]['total'];
1146         return 0;
1147
1148 }
1149
1150
1151 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1152
1153         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1154                 FROM `glink`
1155                 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1156                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1157                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1158                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1159                 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1160                 intval($uid),
1161                 intval($cid),
1162                 intval($uid),
1163                 intval($start),
1164                 intval($limit)
1165         );
1166
1167         return $r;
1168 }
1169
1170
1171
1172 function suggestion_query($uid, $start = 0, $limit = 80) {
1173
1174         if (!$uid) {
1175                 return array();
1176         }
1177
1178 // Uncommented because the result of the queries are to big to store it in the cache.
1179 // We need to decide if we want to change the db column type or if we want to delete it.
1180 //      $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1181 //      if (!is_null($list)) {
1182 //              return $list;
1183 //      }
1184
1185         $network = array(NETWORK_DFRN);
1186
1187         if (get_config('system','diaspora_enabled'))
1188                 $network[] = NETWORK_DIASPORA;
1189
1190         if (!get_config('system','ostatus_disabled'))
1191                 $network[] = NETWORK_OSTATUS;
1192
1193         $sql_network = implode("', '", $network);
1194         $sql_network = "'".$sql_network."'";
1195
1196         /// @todo This query is really slow
1197         // By now we cache the data for five minutes
1198         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1199                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1200                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1201                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1202                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1203                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1204                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1205                 AND `gcontact`.`network` IN (%s)
1206                 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1207                 intval($uid),
1208                 intval($uid),
1209                 intval($uid),
1210                 intval($uid),
1211                 $sql_network,
1212                 intval($start),
1213                 intval($limit)
1214         );
1215
1216         if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1217 // Uncommented because the result of the queries are to big to store it in the cache.
1218 // We need to decide if we want to change the db column type or if we want to delete it.
1219 //              Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1220
1221                 return $r;
1222         }
1223
1224         $r2 = q("SELECT gcontact.* FROM gcontact
1225                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1226                 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1227                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1228                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1229                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1230                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1231                 AND `gcontact`.`network` IN (%s)
1232                 ORDER BY rand() LIMIT %d, %d",
1233                 intval($uid),
1234                 intval($uid),
1235                 intval($uid),
1236                 $sql_network,
1237                 intval($start),
1238                 intval($limit)
1239         );
1240
1241         $list = array();
1242         foreach ($r2 AS $suggestion)
1243                 $list[$suggestion["nurl"]] = $suggestion;
1244
1245         foreach ($r AS $suggestion)
1246                 $list[$suggestion["nurl"]] = $suggestion;
1247
1248         while (sizeof($list) > ($limit))
1249                 array_pop($list);
1250
1251 // Uncommented because the result of the queries are to big to store it in the cache.
1252 // We need to decide if we want to change the db column type or if we want to delete it.
1253 //      Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1254         return $list;
1255 }
1256
1257 function update_suggestions() {
1258
1259         $a = get_app();
1260
1261         $done = array();
1262
1263         /// @TODO Check if it is really neccessary to poll the own server
1264         poco_load(0,0,0,App::get_baseurl() . '/poco');
1265
1266         $done[] = App::get_baseurl() . '/poco';
1267
1268         if (strlen(get_config('system','directory'))) {
1269                 $x = fetch_url(get_server()."/pubsites");
1270                 if ($x) {
1271                         $j = json_decode($x);
1272                         if ($j->entries) {
1273                                 foreach ($j->entries as $entry) {
1274
1275                                         poco_check_server($entry->url);
1276
1277                                         $url = $entry->url . '/poco';
1278                                         if (! in_array($url,$done)) {
1279                                                 poco_load(0,0,0,$entry->url . '/poco');
1280                                         }
1281                                 }
1282                         }
1283                 }
1284         }
1285
1286         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1287         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1288                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1289         );
1290
1291         if (dbm::is_result($r)) {
1292                 foreach ($r as $rr) {
1293                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1294                         if(! in_array($base,$done))
1295                                 poco_load(0,0,0,$base);
1296                 }
1297         }
1298 }
1299
1300 function poco_discover_federation() {
1301         $last = get_config('poco','last_federation_discovery');
1302
1303         if ($last) {
1304                 $next = $last + (24 * 60 * 60);
1305                 if($next > time())
1306                         return;
1307         }
1308
1309         // Discover Friendica, Hubzilla and Diaspora servers
1310         $serverdata = fetch_url("http://the-federation.info/pods.json");
1311
1312         if ($serverdata) {
1313                 $servers = json_decode($serverdata);
1314
1315                 foreach($servers->pods AS $server)
1316                         poco_check_server("https://".$server->host);
1317         }
1318
1319         // Discover GNU Social Servers
1320         if (!get_config('system','ostatus_disabled')) {
1321                 $serverdata = "http://gstools.org/api/get_open_instances/";
1322
1323                 $result = z_fetch_url($serverdata);
1324                 if ($result["success"]) {
1325                         $servers = json_decode($result["body"]);
1326
1327                         foreach($servers->data AS $server)
1328                                 poco_check_server($server->instance_address);
1329                 }
1330         }
1331
1332         set_config('poco','last_federation_discovery', time());
1333 }
1334
1335 function poco_discover($complete = false) {
1336
1337         // Update the server list
1338         poco_discover_federation();
1339
1340         $no_of_queries = 5;
1341
1342         $requery_days = intval(get_config("system", "poco_requery_days"));
1343
1344         if ($requery_days == 0)
1345                 $requery_days = 7;
1346
1347         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1348
1349         $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));
1350         if ($r)
1351                 foreach ($r AS $server) {
1352
1353                         if (!poco_check_server($server["url"], $server["network"])) {
1354                                 // The server is not reachable? Okay, then we will try it later
1355                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1356                                 continue;
1357                         }
1358
1359                         // Fetch all users from the other server
1360                         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1361
1362                         logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1363
1364                         $retdata = z_fetch_url($url);
1365                         if ($retdata["success"]) {
1366                                 $data = json_decode($retdata["body"]);
1367
1368                                 poco_discover_server($data, 2);
1369
1370                                 if (get_config('system','poco_discovery') > 1) {
1371
1372                                         $timeframe = get_config('system','poco_discovery_since');
1373                                         if ($timeframe == 0)
1374                                                 $timeframe = 30;
1375
1376                                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1377
1378                                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1379                                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1380
1381                                         $success = false;
1382
1383                                         $retdata = z_fetch_url($url);
1384                                         if ($retdata["success"]) {
1385                                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1386                                                 $success = poco_discover_server(json_decode($retdata["body"]));
1387                                         }
1388
1389                                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1390                                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1391                                                 poco_discover_server_users($data, $server);
1392                                         }
1393                                 }
1394
1395                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1396                                 if (!$complete AND (--$no_of_queries == 0))
1397                                         break;
1398                         } else {
1399                                 // If the server hadn't replied correctly, then force a sanity check
1400                                 poco_check_server($server["url"], $server["network"], true);
1401
1402                                 // If we couldn't reach the server, we will try it some time later
1403                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1404                         }
1405                 }
1406 }
1407
1408 function poco_discover_server_users($data, $server) {
1409
1410         if (!isset($data->entry))
1411                 return;
1412
1413         foreach ($data->entry AS $entry) {
1414                 $username = "";
1415                 if (isset($entry->urls)) {
1416                         foreach($entry->urls as $url)
1417                                 if ($url->type == 'profile') {
1418                                         $profile_url = $url->value;
1419                                         $urlparts = parse_url($profile_url);
1420                                         $username = end(explode("/", $urlparts["path"]));
1421                                 }
1422                 }
1423                 if ($username != "") {
1424                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1425
1426                         // Fetch all contacts from a given user from the other server
1427                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1428
1429                         $retdata = z_fetch_url($url);
1430                         if ($retdata["success"])
1431                                 poco_discover_server(json_decode($retdata["body"]), 3);
1432                 }
1433         }
1434 }
1435
1436 function poco_discover_server($data, $default_generation = 0) {
1437
1438         if (!isset($data->entry) OR !count($data->entry))
1439                 return false;
1440
1441         $success = false;
1442
1443         foreach ($data->entry AS $entry) {
1444                 $profile_url = '';
1445                 $profile_photo = '';
1446                 $connect_url = '';
1447                 $name = '';
1448                 $network = '';
1449                 $updated = '0000-00-00 00:00:00';
1450                 $location = '';
1451                 $about = '';
1452                 $keywords = '';
1453                 $gender = '';
1454                 $contact_type = -1;
1455                 $generation = $default_generation;
1456
1457                 $name = $entry->displayName;
1458
1459                 if (isset($entry->urls)) {
1460                         foreach($entry->urls as $url) {
1461                                 if ($url->type == 'profile') {
1462                                         $profile_url = $url->value;
1463                                         continue;
1464                                 }
1465                                 if ($url->type == 'webfinger') {
1466                                         $connect_url = str_replace('acct:' , '', $url->value);
1467                                         continue;
1468                                 }
1469                         }
1470                 }
1471
1472                 if (isset($entry->photos)) {
1473                         foreach ($entry->photos as $photo) {
1474                                 if ($photo->type == 'profile') {
1475                                         $profile_photo = $photo->value;
1476                                         continue;
1477                                 }
1478                         }
1479                 }
1480
1481                 if (isset($entry->updated)) {
1482                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1483                 }
1484
1485                 if(isset($entry->network)) {
1486                         $network = $entry->network;
1487                 }
1488
1489                 if(isset($entry->currentLocation)) {
1490                         $location = $entry->currentLocation;
1491                 }
1492
1493                 if(isset($entry->aboutMe)) {
1494                         $about = html2bbcode($entry->aboutMe);
1495                 }
1496
1497                 if(isset($entry->gender)) {
1498                         $gender = $entry->gender;
1499                 }
1500
1501                 if(isset($entry->generation) AND ($entry->generation > 0)) {
1502                         $generation = ++$entry->generation;
1503                 }
1504
1505                 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1506                         $contact_type = $entry->contactType;
1507                 }
1508
1509                 if(isset($entry->tags)) {
1510                         foreach ($entry->tags as $tag) {
1511                                 $keywords = implode(", ", $tag);
1512                         }
1513                 }
1514
1515                 if ($generation > 0) {
1516                         $success = true;
1517
1518                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1519                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1520
1521                         $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
1522                         update_gcontact($gcontact);
1523
1524                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1525                 }
1526         }
1527         return $success;
1528 }
1529
1530 /**
1531  * @brief Removes unwanted parts from a contact url
1532  *
1533  * @param string $url Contact url
1534  * @return string Contact url with the wanted parts
1535  */
1536 function clean_contact_url($url) {
1537         $parts = parse_url($url);
1538
1539         if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1540                 return $url;
1541
1542         $new_url = $parts["scheme"]."://".$parts["host"];
1543
1544         if (isset($parts["port"]))
1545                 $new_url .= ":".$parts["port"];
1546
1547         if (isset($parts["path"]))
1548                 $new_url .= $parts["path"];
1549
1550         if ($new_url != $url)
1551                 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1552
1553         return $new_url;
1554 }
1555
1556 /**
1557  * @brief Replace alternate OStatus user format with the primary one
1558  *
1559  * @param arr $contact contact array (called by reference)
1560  */
1561 function fix_alternate_contact_address(&$contact) {
1562         if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1563                 $data = probe_url($contact["url"]);
1564                 if ($contact["network"] == NETWORK_OSTATUS) {
1565                         logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1566                         $contact["url"] = $data["url"];
1567                         $contact["addr"] = $data["addr"];
1568                         $contact["alias"] = $data["alias"];
1569                         $contact["server_url"] = $data["baseurl"];
1570                 }
1571         }
1572 }
1573
1574 /**
1575  * @brief Fetch the gcontact id, add an entry if not existed
1576  *
1577  * @param arr $contact contact array
1578  * @return bool|int Returns false if not found, integer if contact was found
1579  */
1580 function get_gcontact_id($contact) {
1581
1582         $gcontact_id = 0;
1583         $doprobing = false;
1584
1585         if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1586                 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1587                 return false;
1588         }
1589
1590         if ($contact["network"] == NETWORK_STATUSNET)
1591                 $contact["network"] = NETWORK_OSTATUS;
1592
1593         // All new contacts are hidden by default
1594         if (!isset($contact["hide"]))
1595                 $contact["hide"] = true;
1596
1597         // Replace alternate OStatus user format with the primary one
1598         fix_alternate_contact_address($contact);
1599
1600         // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1601         if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1602                 $contact["url"] = clean_contact_url($contact["url"]);
1603
1604         $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
1605                 dbesc(normalise_link($contact["url"])));
1606
1607         if ($r) {
1608                 $gcontact_id = $r[0]["id"];
1609
1610                 // Update every 90 days
1611                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
1612                         $last_failure_str = $r[0]["last_failure"];
1613                         $last_failure = strtotime($r[0]["last_failure"]);
1614                         $last_contact_str = $r[0]["last_contact"];
1615                         $last_contact = strtotime($r[0]["last_contact"]);
1616                         $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
1617                 }
1618         } else {
1619                 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
1620                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
1621                         dbesc($contact["name"]),
1622                         dbesc($contact["nick"]),
1623                         dbesc($contact["addr"]),
1624                         dbesc($contact["network"]),
1625                         dbesc($contact["url"]),
1626                         dbesc(normalise_link($contact["url"])),
1627                         dbesc($contact["photo"]),
1628                         dbesc(datetime_convert()),
1629                         dbesc(datetime_convert()),
1630                         dbesc($contact["location"]),
1631                         dbesc($contact["about"]),
1632                         intval($contact["hide"]),
1633                         intval($contact["generation"])
1634                 );
1635
1636                 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1637                         dbesc(normalise_link($contact["url"])));
1638
1639                 if ($r) {
1640                         $gcontact_id = $r[0]["id"];
1641
1642                         $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
1643                 }
1644         }
1645
1646         if ($doprobing) {
1647                 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
1648                 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
1649         }
1650
1651         if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1652          q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1653                 dbesc(normalise_link($contact["url"])),
1654                 intval($gcontact_id));
1655
1656         return $gcontact_id;
1657 }
1658
1659 /**
1660  * @brief Updates the gcontact table from a given array
1661  *
1662  * @param arr $contact contact array
1663  * @return bool|int Returns false if not found, integer if contact was found
1664  */
1665 function update_gcontact($contact) {
1666
1667         // Check for invalid "contact-type" value
1668         if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
1669                 $contact['contact-type'] = 0;
1670         }
1671
1672         /// @todo update contact table as well
1673
1674         $gcontact_id = get_gcontact_id($contact);
1675
1676         if (!$gcontact_id)
1677                 return false;
1678
1679         $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1680                         `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1681                 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1682                 intval($gcontact_id));
1683
1684         // Get all field names
1685         $fields = array();
1686         foreach ($r[0] AS $field => $data)
1687                 $fields[$field] = $data;
1688
1689         unset($fields["url"]);
1690         unset($fields["updated"]);
1691         unset($fields["hide"]);
1692
1693         // Bugfix: We had an error in the storing of keywords which lead to the "0"
1694         // This value is still transmitted via poco.
1695         if ($contact["keywords"] == "0")
1696                 unset($contact["keywords"]);
1697
1698         if ($r[0]["keywords"] == "0")
1699                 $r[0]["keywords"] = "";
1700
1701         // assign all unassigned fields from the database entry
1702         foreach ($fields AS $field => $data)
1703                 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1704                         $contact[$field] = $r[0][$field];
1705
1706         if (!isset($contact["hide"]))
1707                 $contact["hide"] = $r[0]["hide"];
1708
1709         $fields["hide"] = $r[0]["hide"];
1710
1711         if ($contact["network"] == NETWORK_STATUSNET)
1712                 $contact["network"] = NETWORK_OSTATUS;
1713
1714         // Replace alternate OStatus user format with the primary one
1715         fix_alternate_contact_address($contact);
1716
1717         if (!isset($contact["updated"]))
1718                 $contact["updated"] = datetime_convert();
1719
1720         if ($contact["server_url"] == "") {
1721                 $server_url = $contact["url"];
1722
1723                 $server_url = matching_url($server_url, $contact["alias"]);
1724                 if ($server_url != "")
1725                         $contact["server_url"] = $server_url;
1726
1727                 $server_url = matching_url($server_url, $contact["photo"]);
1728                 if ($server_url != "")
1729                         $contact["server_url"] = $server_url;
1730
1731                 $server_url = matching_url($server_url, $contact["notify"]);
1732                 if ($server_url != "")
1733                         $contact["server_url"] = $server_url;
1734         } else
1735                 $contact["server_url"] = normalise_link($contact["server_url"]);
1736
1737         if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1738                 $hostname = str_replace("http://", "", $contact["server_url"]);
1739                 $contact["addr"] = $contact["nick"]."@".$hostname;
1740         }
1741
1742         // Check if any field changed
1743         $update = false;
1744         unset($fields["generation"]);
1745
1746         if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1747                 foreach ($fields AS $field => $data)
1748                         if ($contact[$field] != $r[0][$field]) {
1749                                 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1750                                 $update = true;
1751                         }
1752
1753                 if ($contact["generation"] < $r[0]["generation"]) {
1754                         logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1755                         $update = true;
1756                 }
1757         }
1758
1759         if ($update) {
1760                 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
1761
1762                 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1763                                         `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1764                                         `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
1765                                         `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1766                                         `server_url` = '%s', `connect` = '%s'
1767                                 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1768                         dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1769                         dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1770                         dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1771                         intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
1772                         dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
1773                         dbesc($contact["about"]), intval($contact["generation"]), dbesc($contact["updated"]),
1774                         dbesc($contact["server_url"]), dbesc($contact["connect"]),
1775                         dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1776
1777
1778                 // Now update the contact entry with the user id "0" as well.
1779                 // This is used for the shadow copies of public items.
1780                 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1781                         dbesc(normalise_link($contact["url"])));
1782
1783                 if ($r) {
1784                         logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1785
1786                         update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1787
1788                         q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1789                                                 `network` = '%s', `bd` = '%s', `gender` = '%s',
1790                                                 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
1791                                                 `url` = '%s', `location` = '%s', `about` = '%s'
1792                                         WHERE `id` = %d",
1793                                 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1794                                 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1795                                 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
1796                                 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1797                                 intval($r[0]["id"]));
1798                 }
1799         }
1800
1801         return $gcontact_id;
1802 }
1803
1804 /**
1805  * @brief Updates the gcontact entry from probe
1806  *
1807  * @param str $url profile link
1808  */
1809 function update_gcontact_from_probe($url) {
1810         $data = probe_url($url);
1811
1812         if (in_array($data["network"], array(NETWORK_PHANTOM))) {
1813                 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1814                 return;
1815         }
1816
1817         update_gcontact($data);
1818 }
1819
1820 /**
1821  * @brief Update the gcontact entry for a given user id
1822  *
1823  * @param int $uid User ID
1824  */
1825 function update_gcontact_for_user($uid) {
1826         $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1827                         `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1828                         `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1829                         `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1830                         `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1831                 FROM `profile`
1832                         INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1833                         INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1834                 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1835                 intval($uid));
1836
1837         $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
1838                                                 "country-name" => $r[0]["country-name"]));
1839
1840         // The "addr" field was added in 3.4.3 so it can be empty for older users
1841         if ($r[0]["addr"] != "")
1842                 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
1843         else
1844                 $addr = $r[0]["addr"];
1845
1846         $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
1847                         "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
1848                         "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1849                         "notify" => $r[0]["notify"], "url" => $r[0]["url"],
1850                         "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
1851                         "nick" => $r[0]["nickname"], "addr" => $addr,
1852                         "connect" => $addr, "server_url" => App::get_baseurl(),
1853                         "generation" => 1, "network" => NETWORK_DFRN);
1854
1855         update_gcontact($gcontact);
1856 }
1857
1858 /**
1859  * @brief Fetches users of given GNU Social server
1860  *
1861  * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1862  *
1863  * @param str $server Server address
1864  */
1865 function gs_fetch_users($server) {
1866
1867         logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1868
1869         $url = $server."/main/statistics";
1870
1871         $result = z_fetch_url($url);
1872         if (!$result["success"])
1873                 return false;
1874
1875         $statistics = json_decode($result["body"]);
1876
1877         if (is_object($statistics->config)) {
1878                 if ($statistics->config->instance_with_ssl)
1879                         $server = "https://";
1880                 else
1881                         $server = "http://";
1882
1883                 $server .= $statistics->config->instance_address;
1884
1885                 $hostname = $statistics->config->instance_address;
1886         } else {
1887                 if ($statistics->instance_with_ssl)
1888                         $server = "https://";
1889                 else
1890                         $server = "http://";
1891
1892                 $server .= $statistics->instance_address;
1893
1894                 $hostname = $statistics->instance_address;
1895         }
1896
1897         if (is_object($statistics->users))
1898                 foreach ($statistics->users AS $nick => $user) {
1899                         $profile_url = $server."/".$user->nickname;
1900
1901                         $contact = array("url" => $profile_url,
1902                                         "name" => $user->fullname,
1903                                         "addr" => $user->nickname."@".$hostname,
1904                                         "nick" => $user->nickname,
1905                                         "about" => $user->bio,
1906                                         "network" => NETWORK_OSTATUS,
1907                                         "photo" => App::get_baseurl()."/images/person-175.jpg");
1908                         get_gcontact_id($contact);
1909                 }
1910 }
1911
1912 /**
1913  * @brief Asking GNU Social server on a regular base for their user data
1914  *
1915  */
1916 function gs_discover() {
1917
1918         $requery_days = intval(get_config("system", "poco_requery_days"));
1919
1920         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1921
1922         $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",
1923                 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1924
1925         if (!$r)
1926                 return;
1927
1928         foreach ($r AS $server) {
1929                 gs_fetch_users($server["url"]);
1930                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1931         }
1932 }
1933 ?>