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