]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
Added documention
[friendica.git] / include / socgraph.php
1 <?php
2 /**
3  * @file include/socgraph.php
4  * 
5  * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6  * @todo Fetch profile data from profile page for Redmatrix users
7  * @todo Detect if it is a forum
8  */
9
10 require_once('include/datetime.php');
11 require_once("include/Scrape.php");
12 require_once("include/network.php");
13 require_once("include/html2bbcode.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
16
17 /*
18  * poco_load
19  *
20  * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
21  * and add the entries to the gcontact (Global Contact) table, or update existing entries
22  * if anything (name or photo) has changed.
23  * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
24  *
25  * Once the global contact is stored add (if necessary) the contact linkage which associates
26  * the given uid, cid to the global contact entry. There can be many uid/cid combinations
27  * pointing to the same global contact id.
28  *
29  */
30
31
32
33
34 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
35
36         $a = get_app();
37
38         if($cid) {
39                 if((! $url) || (! $uid)) {
40                         $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
41                                 intval($cid)
42                         );
43                         if (dbm::is_result($r)) {
44                                 $url = $r[0]['poco'];
45                                 $uid = $r[0]['uid'];
46                         }
47                 }
48                 if(! $uid)
49                         return;
50         }
51
52         if(! $url)
53                 return;
54
55         $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ;
56
57         logger('poco_load: ' . $url, LOGGER_DEBUG);
58
59         $s = fetch_url($url);
60
61         logger('poco_load: returns ' . $s, LOGGER_DATA);
62
63         logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
64
65         if(($a->get_curl_code() > 299) || (! $s))
66                 return;
67
68         $j = json_decode($s);
69
70         logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
71
72         if(! isset($j->entry))
73                 return;
74
75         $total = 0;
76         foreach($j->entry as $entry) {
77
78                 $total ++;
79                 $profile_url = '';
80                 $profile_photo = '';
81                 $connect_url = '';
82                 $name = '';
83                 $network = '';
84                 $updated = NULL_DATE;
85                 $location = '';
86                 $about = '';
87                 $keywords = '';
88                 $gender = '';
89                 $contact_type = -1;
90                 $generation = 0;
91
92                 $name = $entry->displayName;
93
94                 if (isset($entry->urls)) {
95                         foreach ($entry->urls as $url) {
96                                 if ($url->type == 'profile') {
97                                         $profile_url = $url->value;
98                                         continue;
99                                 }
100                                 if ($url->type == 'webfinger') {
101                                         $connect_url = str_replace('acct:' , '', $url->value);
102                                         continue;
103                                 }
104                         }
105                 }
106                 if (isset($entry->photos)) {
107                         foreach ($entry->photos as $photo) {
108                                 if ($photo->type == 'profile') {
109                                         $profile_photo = $photo->value;
110                                         continue;
111                                 }
112                         }
113                 }
114
115                 if (isset($entry->updated)) {
116                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
117                 }
118
119                 if (isset($entry->network)) {
120                         $network = $entry->network;
121                 }
122
123                 if (isset($entry->currentLocation)) {
124                         $location = $entry->currentLocation;
125                 }
126
127                 if (isset($entry->aboutMe)) {
128                         $about = html2bbcode($entry->aboutMe);
129                 }
130
131                 if (isset($entry->gender)) {
132                         $gender = $entry->gender;
133                 }
134
135                 if (isset($entry->generation) AND ($entry->generation > 0)) {
136                         $generation = ++$entry->generation;
137                 }
138
139                 if (isset($entry->tags)) {
140                         foreach($entry->tags as $tag) {
141                                 $keywords = implode(", ", $tag);
142                         }
143                 }
144
145                 if (isset($entry->contactType) AND ($entry->contactType >= 0))
146                         $contact_type = $entry->contactType;
147
148                 // If you query a Friendica server for its profiles, the network has to be Friendica
149                 /// TODO It could also be a Redmatrix server
150                 //if ($uid == 0)
151                 //      $network = NETWORK_DFRN;
152
153                 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
154
155                 $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
156                 update_gcontact($gcontact);
157
158                 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
159                 // Deactivated because we now update Friendica contacts in dfrn.php
160                 //if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
161                 //      q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
162                 //              WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
163                 //              dbesc($location),
164                 //              dbesc($about),
165                 //              dbesc($keywords),
166                 //              dbesc($gender),
167                 //              dbesc(normalise_link($profile_url)),
168                 //              dbesc(NETWORK_DFRN));
169         }
170         logger("poco_load: loaded $total entries",LOGGER_DEBUG);
171
172         q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
173                 intval($cid),
174                 intval($uid),
175                 intval($zcid)
176         );
177
178 }
179
180 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
181
182         // Generation:
183         //  0: No definition
184         //  1: Profiles on this server
185         //  2: Contacts of profiles on this server
186         //  3: Contacts of contacts of profiles on this server
187         //  4: ...
188
189         $gcid = "";
190
191         if ($profile_url == "")
192                 return $gcid;
193
194         $urlparts = parse_url($profile_url);
195         if (!isset($urlparts["scheme"]))
196                 return $gcid;
197
198         if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
199                                                 "identi.ca", "alpha.app.net")))
200                 return $gcid;
201
202         // Don't store the statusnet connector as network
203         // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
204         if ($network == NETWORK_STATUSNET)
205                 $network = "";
206
207         // Assure that there are no parameter fragments in the profile url
208         if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
209                 $profile_url = clean_contact_url($profile_url);
210
211         $alternate = poco_alternate_ostatus_url($profile_url);
212
213         $orig_updated = $updated;
214
215         // The global contacts should contain the original picture, not the cached one
216         if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link(App::get_baseurl()."/photo/"))) {
217                 $profile_photo = "";
218         }
219
220         $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
221                 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
222         );
223         if (dbm::is_result($r)) {
224                 $network = $r[0]["network"];
225         }
226
227         if (($network == "") OR ($network == NETWORK_OSTATUS)) {
228                 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
229                         dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
230                 );
231                 if (dbm::is_result($r)) {
232                         $network = $r[0]["network"];
233                         //$profile_url = $r[0]["url"];
234                 }
235         }
236
237         $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
238                 dbesc(normalise_link($profile_url))
239         );
240
241         if (count($x)) {
242                 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET)) {
243                         $network = $x[0]["network"];
244                 }
245                 if ($updated <= NULL_DATE) {
246                         $updated = $x[0]["updated"];
247                 }
248                 $created = $x[0]["created"];
249                 $server_url = $x[0]["server_url"];
250                 $nick = $x[0]["nick"];
251                 $addr = $x[0]["addr"];
252                 $alias =  $x[0]["alias"];
253                 $notify =  $x[0]["notify"];
254         } else {
255                 $created = NULL_DATE;
256                 $server_url = "";
257
258                 $urlparts = parse_url($profile_url);
259                 $nick = end(explode("/", $urlparts["path"]));
260                 $addr = "";
261                 $alias = "";
262                 $notify = "";
263         }
264
265         if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
266                 AND poco_reachable($profile_url, $server_url, $network, false)) {
267                 $data = probe_url($profile_url);
268
269                 $orig_profile = $profile_url;
270
271                 $network = $data["network"];
272                 $name = $data["name"];
273                 $nick = $data["nick"];
274                 $addr = $data["addr"];
275                 $alias = $data["alias"];
276                 $notify = $data["notify"];
277                 $profile_url = $data["url"];
278                 $profile_photo = $data["photo"];
279                 $server_url = $data["baseurl"];
280
281                 if ($alternate AND ($network == NETWORK_OSTATUS)) {
282                         // Delete the old entry - if it exists
283                         $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
284                         if ($r) {
285                                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
286                                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
287                         }
288
289                         // possibly create a new entry
290                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
291                 }
292         }
293
294         if ($alternate AND ($network == NETWORK_OSTATUS))
295                 return $gcid;
296
297         if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
298                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
299                         dbesc($network),
300                         dbesc(normalise_link($profile_url))
301                 );
302         }
303
304         if (($name == "") OR ($profile_photo == ""))
305                 return $gcid;
306
307         if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
308                 return $gcid;
309
310         logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
311
312         // We check the server url to be sure that it is a real one
313         $server_url2 = poco_detect_server($profile_url);
314
315         // We are no sure that it is a correct URL. So we use it in the future
316         if ($server_url2 != "") {
317                 $server_url = $server_url2;
318         }
319
320         // The server URL doesn't seem to be valid, so we don't store it.
321         if (!poco_check_server($server_url, $network)) {
322                 $server_url = "";
323         }
324
325         $gcontact = array("url" => $profile_url,
326                         "addr" => $addr,
327                         "alias" => $alias,
328                         "name" => $name,
329                         "network" => $network,
330                         "photo" => $profile_photo,
331                         "about" => $about,
332                         "location" => $location,
333                         "gender" => $gender,
334                         "keywords" => $keywords,
335                         "server_url" => $server_url,
336                         "connect" => $connect_url,
337                         "notify" => $notify,
338                         "updated" => $updated,
339                         "generation" => $generation);
340
341         $gcid = update_gcontact($gcontact);
342
343         if(!$gcid)
344                 return $gcid;
345
346         $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
347                 intval($cid),
348                 intval($uid),
349                 intval($gcid),
350                 intval($zcid)
351         );
352         if (! dbm::is_result($r)) {
353                 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
354                         intval($cid),
355                         intval($uid),
356                         intval($gcid),
357                         intval($zcid),
358                         dbesc(datetime_convert())
359                 );
360         } else {
361                 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
362                         dbesc(datetime_convert()),
363                         intval($cid),
364                         intval($uid),
365                         intval($gcid),
366                         intval($zcid)
367                 );
368         }
369
370         return $gcid;
371 }
372
373 function poco_reachable($profile, $server = "", $network = "", $force = false) {
374
375         if ($server == "")
376                 $server = poco_detect_server($profile);
377
378         if ($server == "")
379                 return true;
380
381         return poco_check_server($server, $network, $force);
382 }
383
384 function poco_detect_server($profile) {
385
386         // Try to detect the server path based upon some known standard paths
387         $server_url = "";
388
389         if ($server_url == "") {
390                 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
391                 if ($friendica != $profile) {
392                         $server_url = $friendica;
393                         $network = NETWORK_DFRN;
394                 }
395         }
396
397         if ($server_url == "") {
398                 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
399                 if ($diaspora != $profile) {
400                         $server_url = $diaspora;
401                         $network = NETWORK_DIASPORA;
402                 }
403         }
404
405         if ($server_url == "") {
406                 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
407                 if ($red != $profile) {
408                         $server_url = $red;
409                         $network = NETWORK_DIASPORA;
410                 }
411         }
412
413         // Mastodon
414         if ($server_url == "") {
415                 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
416                 if ($mastodon != $profile) {
417                         $server_url = $mastodon;
418                         $network = NETWORK_OSTATUS;
419                 }
420         }
421
422         // Numeric OStatus variant
423         if ($server_url == "") {
424                 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
425                 if ($ostatus != $profile) {
426                         $server_url = $ostatus;
427                         $network = NETWORK_OSTATUS;
428                 }
429         }
430
431         // Wild guess
432         if ($server_url == "") {
433                 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
434                 if ($base != $profile) {
435                         $server_url = $base;
436                         $network = NETWORK_PHANTOM;
437                 }
438         }
439
440         if ($server_url == "") {
441                 return "";
442         }
443
444         $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
445                 dbesc(normalise_link($server_url)));
446         if (dbm::is_result($r)) {
447                 return $server_url;
448         }
449
450         // Fetch the host-meta to check if this really is a server
451         $serverret = z_fetch_url($server_url."/.well-known/host-meta");
452         if (!$serverret["success"]) {
453                 return "";
454         }
455
456         return $server_url;
457 }
458
459 function poco_alternate_ostatus_url($url) {
460         return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
461 }
462
463 function poco_last_updated($profile, $force = false) {
464
465         $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
466                         dbesc(normalise_link($profile)));
467
468         if ($gcontacts[0]["created"] <= NULL_DATE) {
469                 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
470                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
471         }
472         if ($gcontacts[0]["server_url"] != "") {
473                 $server_url = $gcontacts[0]["server_url"];
474         }
475         if (($server_url == '') OR ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"])) {
476                 $server_url = poco_detect_server($profile);
477         }
478
479         if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
480                 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
481                 return false;
482         }
483
484         if ($server_url != "") {
485                 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
486
487                         if ($force)
488                                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
489                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
490
491                         logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
492                         return false;
493                 }
494
495                 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
496                         dbesc($server_url), dbesc(normalise_link($profile)));
497         }
498
499         if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
500                 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
501                         dbesc(normalise_link($server_url)));
502
503                 if ($server)
504                         q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
505                                 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
506                 else
507                         return false;
508         }
509
510         // noscrape is really fast so we don't cache the call.
511         if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
512
513                 //  Use noscrape if possible
514                 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
515
516                 if ($server) {
517                         $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
518
519                          if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
520
521                                 $noscrape = json_decode($noscraperet["body"], true);
522
523                                 if (is_array($noscrape)) {
524                                         $contact = array("url" => $profile,
525                                                         "network" => $server[0]["network"],
526                                                         "generation" => $gcontacts[0]["generation"]);
527
528                                         if (isset($noscrape["fn"]))
529                                                 $contact["name"] = $noscrape["fn"];
530
531                                         if (isset($noscrape["comm"]))
532                                                 $contact["community"] = $noscrape["comm"];
533
534                                         if (isset($noscrape["tags"])) {
535                                                 $keywords = implode(" ", $noscrape["tags"]);
536                                                 if ($keywords != "")
537                                                         $contact["keywords"] = $keywords;
538                                         }
539
540                                         $location = formatted_location($noscrape);
541                                         if ($location)
542                                                 $contact["location"] = $location;
543
544                                         if (isset($noscrape["dfrn-notify"]))
545                                                 $contact["notify"] = $noscrape["dfrn-notify"];
546
547                                         // Remove all fields that are not present in the gcontact table
548                                         unset($noscrape["fn"]);
549                                         unset($noscrape["key"]);
550                                         unset($noscrape["homepage"]);
551                                         unset($noscrape["comm"]);
552                                         unset($noscrape["tags"]);
553                                         unset($noscrape["locality"]);
554                                         unset($noscrape["region"]);
555                                         unset($noscrape["country-name"]);
556                                         unset($noscrape["contacts"]);
557                                         unset($noscrape["dfrn-request"]);
558                                         unset($noscrape["dfrn-confirm"]);
559                                         unset($noscrape["dfrn-notify"]);
560                                         unset($noscrape["dfrn-poll"]);
561
562                                         // Set the date of the last contact
563                                         /// @todo By now the function "update_gcontact" doesn't work with this field
564                                         //$contact["last_contact"] = datetime_convert();
565
566                                         $contact = array_merge($contact, $noscrape);
567
568                                         update_gcontact($contact);
569
570                                         if (trim($noscrape["updated"]) != "") {
571                                                 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
572                                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
573
574                                                 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
575
576                                                 return $noscrape["updated"];
577                                         }
578                                 }
579                         }
580                 }
581         }
582
583         // If we only can poll the feed, then we only do this once a while
584         if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"],  $gcontacts[0]["last_contact"])) {
585                 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
586                 return $gcontacts[0]["updated"];
587         }
588
589         $data = probe_url($profile);
590
591         // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
592         // Then check the other link and delete this one
593         if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
594                 (normalise_link($profile) == normalise_link($data["alias"])) AND
595                 (normalise_link($profile) != normalise_link($data["url"]))) {
596
597                 // Delete the old entry
598                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
599                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
600
601                 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
602                                 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
603
604                 poco_last_updated($data["url"], $force);
605
606                 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
607                 return false;
608         }
609
610         if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
611                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
612                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
613
614                 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
615                 return false;
616         }
617
618         $contact = array("generation" => $gcontacts[0]["generation"]);
619
620         $contact = array_merge($contact, $data);
621
622         $contact["server_url"] = $data["baseurl"];
623
624         unset($contact["batch"]);
625         unset($contact["poll"]);
626         unset($contact["request"]);
627         unset($contact["confirm"]);
628         unset($contact["poco"]);
629         unset($contact["priority"]);
630         unset($contact["pubkey"]);
631         unset($contact["baseurl"]);
632
633         update_gcontact($contact);
634
635         $feedret = z_fetch_url($data["poll"]);
636
637         if (!$feedret["success"]) {
638                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
639                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
640
641                 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
642                 return false;
643         }
644
645         $doc = new DOMDocument();
646         @$doc->loadXML($feedret["body"]);
647
648         $xpath = new DomXPath($doc);
649         $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
650
651         $entries = $xpath->query('/atom:feed/atom:entry');
652
653         $last_updated = "";
654
655         foreach ($entries AS $entry) {
656                 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
657                 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
658
659                 if ($last_updated < $published)
660                         $last_updated = $published;
661
662                 if ($last_updated < $updated)
663                         $last_updated = $updated;
664         }
665
666         // Maybe there aren't any entries. Then check if it is a valid feed
667         if ($last_updated == "") {
668                 if ($xpath->query('/atom:feed')->length > 0) {
669                         $last_updated = NULL_DATE;
670                 }
671         }
672         q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
673                 dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
674
675         if (($gcontacts[0]["generation"] == 0))
676                 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
677                         dbesc(normalise_link($profile)));
678
679         logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
680
681         return($last_updated);
682 }
683
684 function poco_do_update($created, $updated, $last_failure,  $last_contact) {
685         $now = strtotime(datetime_convert());
686
687         if ($updated > $last_contact)
688                 $contact_time = strtotime($updated);
689         else
690                 $contact_time = strtotime($last_contact);
691
692         $failure_time = strtotime($last_failure);
693         $created_time = strtotime($created);
694
695         // If there is no "created" time then use the current time
696         if ($created_time <= 0)
697                 $created_time = $now;
698
699         // If the last contact was less than 24 hours then don't update
700         if (($now - $contact_time) < (60 * 60 * 24))
701                 return false;
702
703         // If the last failure was less than 24 hours then don't update
704         if (($now - $failure_time) < (60 * 60 * 24))
705                 return false;
706
707         // If the last contact was less than a week ago and the last failure is older than a week then don't update
708         //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
709         //      return false;
710
711         // 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
712         if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
713                 return false;
714
715         // 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
716         if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
717                 return false;
718
719         return true;
720 }
721
722 function poco_to_boolean($val) {
723         if (($val == "true") OR ($val == 1))
724                 return(true);
725         if (($val == "false") OR ($val == 0))
726                 return(false);
727
728         return ($val);
729 }
730
731 /**
732  * @brief Detect server type (Hubzilla or Friendica) via the poco data
733  *
734  * @param object $data POCO data
735  * @return array Server data
736  */
737 function poco_detect_poco_data($data) {
738         $server = false;
739
740         if (!isset($data->entry)) {
741                 return false;
742         }
743
744         if (count($data->entry) == 0) {
745                 return false;
746         }
747
748         if (!isset($data->entry[0]->urls)) {
749                 return false;
750         }
751
752         if (count($data->entry[0]->urls) == 0) {
753                 return false;
754         }
755
756         foreach ($data->entry[0]->urls AS $url) {
757                 if ($url->type == 'zot') {
758                         $server = array();
759                         $server["platform"] = 'Hubzilla';
760                         $server["network"] = NETWORK_DIASPORA;
761                         return $server;
762                 }
763         }
764         return false;
765 }
766
767 /**
768  * @brief Detect server type by using the nodeinfo data
769  *
770  * @param string $server_url address of the server
771  * @return array Server data
772  */
773 function poco_fetch_nodeinfo($server_url) {
774         $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
775         if (!$serverret["success"]) {
776                 return false;
777         }
778
779         $nodeinfo = json_decode($serverret['body']);
780
781         if (!is_object($nodeinfo)) {
782                 return false;
783         }
784
785         if (!is_array($nodeinfo->links)) {
786                 return false;
787         }
788
789         $nodeinfo_url = '';
790
791         foreach ($nodeinfo->links AS $link) {
792                 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
793                         $nodeinfo_url = $link->href;
794                 }
795         }
796
797         if ($nodeinfo_url == '') {
798                 return false;
799         }
800
801         $serverret = z_fetch_url($nodeinfo_url);
802         if (!$serverret["success"]) {
803                 return false;
804         }
805
806         $nodeinfo = json_decode($serverret['body']);
807
808         if (!is_object($nodeinfo)) {
809                 return false;
810         }
811
812         $server = array();
813
814         $server['register_policy'] = REGISTER_CLOSED;
815
816         if (is_bool($nodeinfo->openRegistrations) AND $nodeinfo->openRegistrations) {
817                 $server['register_policy'] = REGISTER_OPEN;
818         }
819
820         if (is_object($nodeinfo->software)) {
821                 if (isset($nodeinfo->software->name)) {
822                         $server['platform'] = $nodeinfo->software->name;
823                 }
824
825                 if (isset($nodeinfo->software->version)) {
826                         $server['version'] = $nodeinfo->software->version;
827                         // Version numbers on Nodeinfo are presented with additional info, e.g.:
828                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
829                         $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
830                 }
831         }
832
833         if (is_object($nodeinfo->metadata)) {
834                 if (isset($nodeinfo->metadata->nodeName)) {
835                         $server['site_name'] = $nodeinfo->metadata->nodeName;
836                 }
837         }
838
839         $diaspora = false;
840         $friendica = false;
841         $gnusocial = false;
842
843         if (is_array($nodeinfo->protocols->inbound)) {
844                 foreach ($nodeinfo->protocols->inbound AS $inbound) {
845                         if ($inbound == 'diaspora') {
846                                 $diaspora = true;
847                         }
848                         if ($inbound == 'friendica') {
849                                 $friendica = true;
850                         }
851                         if ($inbound == 'gnusocial') {
852                                 $gnusocial = true;
853                         }
854                 }
855         }
856
857         if ($gnusocial) {
858                 $server['network'] = NETWORK_OSTATUS;
859         }
860         if ($diaspora) {
861                 $server['network'] = NETWORK_DIASPORA;
862         }
863         if ($friendica) {
864                 $server['network'] = NETWORK_DFRN;
865         }
866
867         if (!$server) {
868                 return false;
869         }
870
871         return $server;
872 }
873
874 /**
875  * @brief Detect server type (Hubzilla or Friendica) via the front page body
876  *
877  * @param string $body Front page of the server
878  * @return array Server data
879  */
880 function poco_detect_server_type($body) {
881         $server = false;
882
883         $doc = new \DOMDocument();
884         @$doc->loadHTML($body);
885         $xpath = new \DomXPath($doc);
886
887         $list = $xpath->query("//meta[@name]");
888
889         foreach ($list as $node) {
890                 $attr = array();
891                 if ($node->attributes->length) {
892                         foreach ($node->attributes as $attribute) {
893                                 $attr[$attribute->name] = $attribute->value;
894                         }
895                 }
896                 if ($attr['name'] == 'generator') {
897                         $version_part = explode(" ", $attr['content']);
898                         if (count($version_part) == 2) {
899                                 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
900                                         $server = array();
901                                         $server["platform"] = $version_part[0];
902                                         $server["version"] = $version_part[1];
903                                         $server["network"] = NETWORK_DFRN;
904                                 }
905                         }
906                 }
907         }
908
909         if (!$server) {
910                 $list = $xpath->query("//meta[@property]");
911
912                 foreach ($list as $node) {
913                         $attr = array();
914                         if ($node->attributes->length) {
915                                 foreach ($node->attributes as $attribute) {
916                                         $attr[$attribute->name] = $attribute->value;
917                                 }
918                         }
919                         if ($attr['property'] == 'generator') {
920                                 if (in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
921                                         $server = array();
922                                         $server["platform"] = $attr['content'];
923                                         $server["version"] = "";
924                                         $server["network"] = NETWORK_DIASPORA;
925                                 }
926                         }
927                 }
928         }
929
930         if (!$server) {
931                 return false;
932         }
933
934         $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
935         return $server;
936 }
937
938 function poco_check_server($server_url, $network = "", $force = false) {
939
940         // Unify the server address
941         $server_url = trim($server_url, "/");
942         $server_url = str_replace("/index.php", "", $server_url);
943
944         if ($server_url == "")
945                 return false;
946
947         $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
948         if (dbm::is_result($servers)) {
949
950                 if ($servers[0]["created"] <= NULL_DATE) {
951                         q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
952                                 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
953                 }
954                 $poco = $servers[0]["poco"];
955                 $noscrape = $servers[0]["noscrape"];
956
957                 if ($network == "")
958                         $network = $servers[0]["network"];
959
960                 $last_contact = $servers[0]["last_contact"];
961                 $last_failure = $servers[0]["last_failure"];
962                 $version = $servers[0]["version"];
963                 $platform = $servers[0]["platform"];
964                 $site_name = $servers[0]["site_name"];
965                 $info = $servers[0]["info"];
966                 $register_policy = $servers[0]["register_policy"];
967
968                 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
969                         logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
970                         return ($last_contact >= $last_failure);
971                 }
972         } else {
973                 $poco = "";
974                 $noscrape = "";
975                 $version = "";
976                 $platform = "";
977                 $site_name = "";
978                 $info = "";
979                 $register_policy = -1;
980
981                 $last_contact = NULL_DATE;
982                 $last_failure = NULL_DATE;
983         }
984         logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
985
986         $failure = false;
987         $possible_failure = false;
988         $orig_last_failure = $last_failure;
989         $orig_last_contact = $last_contact;
990
991         // Check if the page is accessible via SSL.
992         $orig_server_url = $server_url;
993         $server_url = str_replace("http://", "https://", $server_url);
994
995         // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
996         $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
997
998         // Quit if there is a timeout.
999         // But we want to make sure to only quit if we are mostly sure that this server url fits.
1000         if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
1001                 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1002                 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1003                 return false;
1004         }
1005
1006         // Maybe the page is unencrypted only?
1007         $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1008         if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1009                 $server_url = str_replace("https://", "http://", $server_url);
1010
1011                 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1012                 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1013
1014                 // Quit if there is a timeout
1015                 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1016                         logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1017                         return false;
1018                 }
1019
1020                 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1021         }
1022
1023         if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1024                 // Workaround for bad configured servers (known nginx problem)
1025                 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1026                         $last_failure = datetime_convert();
1027                         $failure = true;
1028                 }
1029                 $possible_failure = true;
1030         } elseif ($network == NETWORK_DIASPORA)
1031                 $last_contact = datetime_convert();
1032
1033         // If the server has no possible failure we reset the cached data
1034         if (!$possible_failure) {
1035                 $version = "";
1036                 $platform = "";
1037                 $site_name = "";
1038                 $info = "";
1039                 $register_policy = -1;
1040         }
1041
1042         // Look for poco
1043         if (!$failure) {
1044                 $serverret = z_fetch_url($server_url."/poco");
1045                 if ($serverret["success"]) {
1046                         $data = json_decode($serverret["body"]);
1047                         if (isset($data->totalResults)) {
1048                                 $poco = $server_url."/poco";
1049                                 $last_contact = datetime_convert();
1050
1051                                 $server = poco_detect_poco_data($data);
1052                                 if ($server) {
1053                                         $platform = $server['platform'];
1054                                         $network = $server['network'];
1055                                         $version = '';
1056                                         $site_name = '';
1057                                 }
1058                         }
1059                 }
1060         }
1061
1062         if (!$failure) {
1063                 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1064                 $serverret = z_fetch_url($server_url);
1065
1066                 if (!$serverret["success"] OR ($serverret["body"] == "")) {
1067                         $last_failure = datetime_convert();
1068                         $failure = true;
1069                 } else {
1070                         $server = poco_detect_server_type($serverret["body"]);
1071                         if ($server) {
1072                                 $platform = $server['platform'];
1073                                 $network = $server['network'];
1074                                 $version = $server['version'];
1075                                 $site_name = $server['site_name'];
1076                                 $last_contact = datetime_convert();
1077                         }
1078
1079                         $lines = explode("\n",$serverret["header"]);
1080                         if(count($lines)) {
1081                                 foreach($lines as $line) {
1082                                         $line = trim($line);
1083                                         if(stristr($line,'X-Diaspora-Version:')) {
1084                                                 $platform = "Diaspora";
1085                                                 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1086                                                 $version = trim(str_replace("x-diaspora-version:", "", $version));
1087                                                 $network = NETWORK_DIASPORA;
1088                                                 $versionparts = explode("-", $version);
1089                                                 $version = $versionparts[0];
1090                                                 $last_contact = datetime_convert();
1091                                         }
1092
1093                                         if(stristr($line,'Server: Mastodon')) {
1094                                                 $platform = "Mastodon";
1095                                                 $network = NETWORK_OSTATUS;
1096                                                 // Mastodon doesn't reveal version numbers
1097                                                 $version = "";
1098                                                 $last_contact = datetime_convert();
1099                                         }
1100                                 }
1101                         }
1102                 }
1103         }
1104
1105         if (!$failure AND ($poco == "")) {
1106                 // Test for Statusnet
1107                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1108                 // The "not implemented" is a special treatment for really, really old Friendica versions
1109                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1110                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1111                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1112                         $platform = "StatusNet";
1113                         // Remove junk that some GNU Social servers return
1114                         $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1115                         $version = trim($version, '"');
1116                         $network = NETWORK_OSTATUS;
1117                         $last_contact = datetime_convert();
1118                 }
1119
1120                 // Test for GNU Social
1121                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1122                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1123                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1124                         $platform = "GNU Social";
1125                         // Remove junk that some GNU Social servers return
1126                         $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1127                         $version = trim($version, '"');
1128                         $network = NETWORK_OSTATUS;
1129                         $last_contact = datetime_convert();
1130                 }
1131         }
1132
1133         if (!$failure) {
1134                 // Test for Hubzilla, Redmatrix or Friendica
1135                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1136                 if ($serverret["success"]) {
1137                         $data = json_decode($serverret["body"]);
1138                         if (isset($data->site->server)) {
1139                                 $last_contact = datetime_convert();
1140
1141                                 if (isset($data->site->platform)) {
1142                                         $platform = $data->site->platform->PLATFORM_NAME;
1143                                         $version = $data->site->platform->STD_VERSION;
1144                                         $network = NETWORK_DIASPORA;
1145                                 }
1146                                 if (isset($data->site->BlaBlaNet)) {
1147                                         $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1148                                         $version = $data->site->BlaBlaNet->STD_VERSION;
1149                                         $network = NETWORK_DIASPORA;
1150                                 }
1151                                 if (isset($data->site->hubzilla)) {
1152                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
1153                                         $version = $data->site->hubzilla->RED_VERSION;
1154                                         $network = NETWORK_DIASPORA;
1155                                 }
1156                                 if (isset($data->site->redmatrix)) {
1157                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
1158                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
1159                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
1160                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
1161
1162                                         $version = $data->site->redmatrix->RED_VERSION;
1163                                         $network = NETWORK_DIASPORA;
1164                                 }
1165                                 if (isset($data->site->friendica)) {
1166                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1167                                         $version = $data->site->friendica->FRIENDICA_VERSION;
1168                                         $network = NETWORK_DFRN;
1169                                 }
1170
1171                                 $site_name = $data->site->name;
1172
1173                                 $data->site->closed = poco_to_boolean($data->site->closed);
1174                                 $data->site->private = poco_to_boolean($data->site->private);
1175                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1176
1177                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
1178                                         $register_policy = REGISTER_APPROVE;
1179                                 elseif (!$data->site->closed AND !$data->site->private)
1180                                         $register_policy = REGISTER_OPEN;
1181                                 else
1182                                         $register_policy = REGISTER_CLOSED;
1183                         }
1184                 }
1185         }
1186
1187
1188         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1189         if (!$failure) {
1190                 $serverret = z_fetch_url($server_url."/statistics.json");
1191                 if ($serverret["success"]) {
1192                         $data = json_decode($serverret["body"]);
1193                         if (isset($data->version)) {
1194                                 $version = $data->version;
1195                                 // Version numbers on statistics.json are presented with additional info, e.g.:
1196                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1197                                 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1198                         }
1199
1200                         $site_name = $data->name;
1201
1202                         if (isset($data->network)) {
1203                                 $platform = $data->network;
1204                         }
1205
1206                         if ($platform == "Diaspora") {
1207                                 $network = NETWORK_DIASPORA;
1208                         }
1209
1210                         if ($data->registrations_open) {
1211                                 $register_policy = REGISTER_OPEN;
1212                         } else {
1213                                 $register_policy = REGISTER_CLOSED;
1214                         }
1215
1216                         if (isset($data->version))
1217                                 $last_contact = datetime_convert();
1218                 }
1219         }
1220
1221         // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1222         if (!$failure) {
1223                 $server = poco_fetch_nodeinfo($server_url);
1224                 if ($server) {
1225                         $register_policy = $server['register_policy'];
1226
1227                         if (isset($server['platform'])) {
1228                                 $platform = $server['platform'];
1229                         }
1230
1231                         if (isset($server['network'])) {
1232                                 $network = $server['network'];
1233                         }
1234
1235                         if (isset($server['version'])) {
1236                                 $version = $server['version'];
1237                         }
1238
1239                         if (isset($server['site_name'])) {
1240                                 $site_name = $server['site_name'];
1241                         }
1242
1243                         $last_contact = datetime_convert();
1244                 }
1245         }
1246
1247         // Check for noscrape
1248         // Friendica servers could be detected as OStatus servers
1249         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1250                 $serverret = z_fetch_url($server_url."/friendica/json");
1251
1252                 if (!$serverret["success"])
1253                         $serverret = z_fetch_url($server_url."/friendika/json");
1254
1255                 if ($serverret["success"]) {
1256                         $data = json_decode($serverret["body"]);
1257
1258                         if (isset($data->version)) {
1259                                 $last_contact = datetime_convert();
1260                                 $network = NETWORK_DFRN;
1261
1262                                 $noscrape = $data->no_scrape_url;
1263                                 $version = $data->version;
1264                                 $site_name = $data->site_name;
1265                                 $info = $data->info;
1266                                 $register_policy_str = $data->register_policy;
1267                                 $platform = $data->platform;
1268
1269                                 switch ($register_policy_str) {
1270                                         case "REGISTER_CLOSED":
1271                                                 $register_policy = REGISTER_CLOSED;
1272                                                 break;
1273                                         case "REGISTER_APPROVE":
1274                                                 $register_policy = REGISTER_APPROVE;
1275                                                 break;
1276                                         case "REGISTER_OPEN":
1277                                                 $register_policy = REGISTER_OPEN;
1278                                                 break;
1279                                 }
1280                         }
1281                 }
1282         }
1283
1284         if ($possible_failure AND !$failure) {
1285                 $last_failure = datetime_convert();
1286                 $failure = true;
1287         }
1288
1289         if ($failure) {
1290                 $last_contact = $orig_last_contact;
1291         } else {
1292                 $last_failure = $orig_last_failure;
1293         }
1294
1295         if (($last_contact <= $last_failure) AND !$failure) {
1296                 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1297         } else if (($last_contact >= $last_failure) AND $failure) {
1298                 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1299         }
1300
1301         // Check again if the server exists
1302         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1303
1304         $version = strip_tags($version);
1305         $site_name = strip_tags($site_name);
1306         $info = strip_tags($info);
1307         $platform = strip_tags($platform);
1308
1309         if ($servers) {
1310                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1311                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1312                         dbesc($server_url),
1313                         dbesc($version),
1314                         dbesc($site_name),
1315                         dbesc($info),
1316                         intval($register_policy),
1317                         dbesc($poco),
1318                         dbesc($noscrape),
1319                         dbesc($network),
1320                         dbesc($platform),
1321                         dbesc($last_contact),
1322                         dbesc($last_failure),
1323                         dbesc(normalise_link($server_url))
1324                 );
1325         } elseif (!$failure) {
1326                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1327                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1328                                 dbesc($server_url),
1329                                 dbesc(normalise_link($server_url)),
1330                                 dbesc($version),
1331                                 dbesc($site_name),
1332                                 dbesc($info),
1333                                 intval($register_policy),
1334                                 dbesc($poco),
1335                                 dbesc($noscrape),
1336                                 dbesc($network),
1337                                 dbesc($platform),
1338                                 dbesc(datetime_convert()),
1339                                 dbesc($last_contact),
1340                                 dbesc($last_failure),
1341                                 dbesc(datetime_convert())
1342                 );
1343         }
1344         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
1345
1346         return !$failure;
1347 }
1348
1349 function count_common_friends($uid,$cid) {
1350
1351         $r = q("SELECT count(*) as `total`
1352                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1353                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1354                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1355                 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1356                 intval($cid),
1357                 intval($uid),
1358                 intval($uid),
1359                 intval($cid)
1360         );
1361
1362 //      logger("count_common_friends: $uid $cid {$r[0]['total']}");
1363         if (dbm::is_result($r))
1364                 return $r[0]['total'];
1365         return 0;
1366
1367 }
1368
1369
1370 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1371
1372         if($shuffle)
1373                 $sql_extra = " order by rand() ";
1374         else
1375                 $sql_extra = " order by `gcontact`.`name` asc ";
1376
1377         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1378                 FROM `glink`
1379                 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1380                 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1381                 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1382                         AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1383                         AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1384                         AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1385                         $sql_extra LIMIT %d, %d",
1386                 intval($cid),
1387                 intval($uid),
1388                 intval($uid),
1389                 intval($cid),
1390                 intval($start),
1391                 intval($limit)
1392         );
1393
1394         return $r;
1395
1396 }
1397
1398
1399 function count_common_friends_zcid($uid,$zcid) {
1400
1401         $r = q("SELECT count(*) as `total`
1402                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1403                 where `glink`.`zcid` = %d
1404                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1405                 intval($zcid),
1406                 intval($uid)
1407         );
1408
1409         if (dbm::is_result($r))
1410                 return $r[0]['total'];
1411         return 0;
1412
1413 }
1414
1415 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1416
1417         if($shuffle)
1418                 $sql_extra = " order by rand() ";
1419         else
1420                 $sql_extra = " order by `gcontact`.`name` asc ";
1421
1422         $r = q("SELECT `gcontact`.*
1423                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1424                 where `glink`.`zcid` = %d
1425                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) 
1426                 $sql_extra limit %d, %d",
1427                 intval($zcid),
1428                 intval($uid),
1429                 intval($start),
1430                 intval($limit)
1431         );
1432
1433         return $r;
1434
1435 }
1436
1437
1438 function count_all_friends($uid,$cid) {
1439
1440         $r = q("SELECT count(*) as `total`
1441                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1442                 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1443                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1444                 intval($cid),
1445                 intval($uid)
1446         );
1447
1448         if (dbm::is_result($r))
1449                 return $r[0]['total'];
1450         return 0;
1451
1452 }
1453
1454
1455 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1456
1457         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1458                 FROM `glink`
1459                 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1460                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1461                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1462                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1463                 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1464                 intval($uid),
1465                 intval($cid),
1466                 intval($uid),
1467                 intval($start),
1468                 intval($limit)
1469         );
1470
1471         return $r;
1472 }
1473
1474
1475
1476 function suggestion_query($uid, $start = 0, $limit = 80) {
1477
1478         if (!$uid) {
1479                 return array();
1480         }
1481
1482 // Uncommented because the result of the queries are to big to store it in the cache.
1483 // We need to decide if we want to change the db column type or if we want to delete it.
1484 //      $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1485 //      if (!is_null($list)) {
1486 //              return $list;
1487 //      }
1488
1489         $network = array(NETWORK_DFRN);
1490
1491         if (get_config('system','diaspora_enabled'))
1492                 $network[] = NETWORK_DIASPORA;
1493
1494         if (!get_config('system','ostatus_disabled'))
1495                 $network[] = NETWORK_OSTATUS;
1496
1497         $sql_network = implode("', '", $network);
1498         $sql_network = "'".$sql_network."'";
1499
1500         /// @todo This query is really slow
1501         // By now we cache the data for five minutes
1502         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1503                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1504                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1505                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1506                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1507                 AND `gcontact`.`updated` >= '%s'
1508                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1509                 AND `gcontact`.`network` IN (%s)
1510                 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1511                 intval($uid),
1512                 intval($uid),
1513                 intval($uid),
1514                 intval($uid),
1515                 dbesc(NULL_DATE),
1516                 $sql_network,
1517                 intval($start),
1518                 intval($limit)
1519         );
1520
1521         if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1522 // Uncommented because the result of the queries are to big to store it in the cache.
1523 // We need to decide if we want to change the db column type or if we want to delete it.
1524 //              Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1525
1526                 return $r;
1527         }
1528
1529         $r2 = q("SELECT gcontact.* FROM gcontact
1530                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1531                 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1532                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1533                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1534                 AND `gcontact`.`updated` >= '%s'
1535                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1536                 AND `gcontact`.`network` IN (%s)
1537                 ORDER BY rand() LIMIT %d, %d",
1538                 intval($uid),
1539                 intval($uid),
1540                 intval($uid),
1541                 dbesc(NULL_DATE),
1542                 $sql_network,
1543                 intval($start),
1544                 intval($limit)
1545         );
1546
1547         $list = array();
1548         foreach ($r2 AS $suggestion)
1549                 $list[$suggestion["nurl"]] = $suggestion;
1550
1551         foreach ($r AS $suggestion)
1552                 $list[$suggestion["nurl"]] = $suggestion;
1553
1554         while (sizeof($list) > ($limit))
1555                 array_pop($list);
1556
1557 // Uncommented because the result of the queries are to big to store it in the cache.
1558 // We need to decide if we want to change the db column type or if we want to delete it.
1559 //      Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1560         return $list;
1561 }
1562
1563 function update_suggestions() {
1564
1565         $a = get_app();
1566
1567         $done = array();
1568
1569         /// @TODO Check if it is really neccessary to poll the own server
1570         poco_load(0,0,0,App::get_baseurl() . '/poco');
1571
1572         $done[] = App::get_baseurl() . '/poco';
1573
1574         if (strlen(get_config('system','directory'))) {
1575                 $x = fetch_url(get_server()."/pubsites");
1576                 if ($x) {
1577                         $j = json_decode($x);
1578                         if ($j->entries) {
1579                                 foreach ($j->entries as $entry) {
1580
1581                                         poco_check_server($entry->url);
1582
1583                                         $url = $entry->url . '/poco';
1584                                         if (! in_array($url,$done)) {
1585                                                 poco_load(0,0,0,$entry->url . '/poco');
1586                                         }
1587                                 }
1588                         }
1589                 }
1590         }
1591
1592         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1593         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1594                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1595         );
1596
1597         if (dbm::is_result($r)) {
1598                 foreach ($r as $rr) {
1599                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1600                         if(! in_array($base,$done))
1601                                 poco_load(0,0,0,$base);
1602                 }
1603         }
1604 }
1605
1606 /**
1607  * @brief Fetch server list from remote servers and adds them when they are new.
1608  *
1609  * @param string $poco URL to the POCO endpoint
1610  */
1611 function poco_fetch_serverlist($poco) {
1612         $serverret = z_fetch_url($poco."/@server");
1613         if (!$serverret["success"]) {
1614                 return;
1615         }
1616         $serverlist = json_decode($serverret['body']);
1617
1618         if (!is_array($serverlist)) {
1619                 return;
1620         }
1621
1622         foreach ($serverlist AS $server) {
1623                 $server_url = str_replace("/index.php", "", $server->url);
1624
1625                 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1626                 if (!dbm::is_result($r)) {
1627                         logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1628                         proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($server_url));
1629                 }
1630         }
1631 }
1632
1633 function poco_discover_federation() {
1634         $last = get_config('poco','last_federation_discovery');
1635
1636         if ($last) {
1637                 $next = $last + (24 * 60 * 60);
1638                 if($next > time())
1639                         return;
1640         }
1641
1642         // Discover Friendica, Hubzilla and Diaspora servers
1643         $serverdata = fetch_url("http://the-federation.info/pods.json");
1644
1645         if ($serverdata) {
1646                 $servers = json_decode($serverdata);
1647
1648                 foreach ($servers->pods AS $server) {
1649                         proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode("https://".$server->host));
1650                 }
1651         }
1652
1653         // Currently disabled, since the service isn't available anymore.
1654         // It is not removed since I hope that there will be a successor.
1655         // Discover GNU Social Servers.
1656         //if (!get_config('system','ostatus_disabled')) {
1657         //      $serverdata = "http://gstools.org/api/get_open_instances/";
1658
1659         //      $result = z_fetch_url($serverdata);
1660         //      if ($result["success"]) {
1661         //              $servers = json_decode($result["body"]);
1662
1663         //              foreach($servers->data AS $server)
1664         //                      poco_check_server($server->instance_address);
1665         //      }
1666         //}
1667
1668         set_config('poco','last_federation_discovery', time());
1669 }
1670
1671 function poco_discover_single_server($id) {
1672         $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1673         if (!dbm::is_result($r)) {
1674                 return false;
1675         }
1676
1677         $server = $r[0];
1678
1679         // Discover new servers out there (Works from Friendica version 3.5.2)
1680         poco_fetch_serverlist($server["poco"]);
1681
1682         // Fetch all users from the other server
1683         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1684
1685         logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1686
1687         $retdata = z_fetch_url($url);
1688         if ($retdata["success"]) {
1689                 $data = json_decode($retdata["body"]);
1690
1691                 poco_discover_server($data, 2);
1692
1693                 if (get_config('system','poco_discovery') > 1) {
1694
1695                         $timeframe = get_config('system','poco_discovery_since');
1696                         if ($timeframe == 0) {
1697                                 $timeframe = 30;
1698                         }
1699
1700                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1701
1702                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1703                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1704
1705                         $success = false;
1706
1707                         $retdata = z_fetch_url($url);
1708                         if ($retdata["success"]) {
1709                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1710                                 $success = poco_discover_server(json_decode($retdata["body"]));
1711                         }
1712
1713                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1714                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1715                                 poco_discover_server_users($data, $server);
1716                         }
1717                 }
1718
1719                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1720
1721                 return true;
1722         } else {
1723                 // If the server hadn't replied correctly, then force a sanity check
1724                 poco_check_server($server["url"], $server["network"], true);
1725
1726                 // If we couldn't reach the server, we will try it some time later
1727                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1728
1729                 return false;
1730         }
1731 }
1732
1733 function poco_discover($complete = false) {
1734
1735         // Update the server list
1736         poco_discover_federation();
1737
1738         $no_of_queries = 5;
1739
1740         $requery_days = intval(get_config("system", "poco_requery_days"));
1741
1742         if ($requery_days == 0)
1743                 $requery_days = 7;
1744
1745         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1746
1747         $r = q("SELECT `id`, `url`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
1748         if (dbm::is_result($r)) {
1749                 foreach ($r AS $server) {
1750
1751                         if (!poco_check_server($server["url"], $server["network"])) {
1752                                 // The server is not reachable? Okay, then we will try it later
1753                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1754                                 continue;
1755                         }
1756
1757                         logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1758                         proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", $server['id']);
1759
1760                         if (!$complete AND (--$no_of_queries == 0)) {
1761                                 break;
1762                         }
1763                 }
1764         }
1765 }
1766
1767 function poco_discover_server_users($data, $server) {
1768
1769         if (!isset($data->entry))
1770                 return;
1771
1772         foreach ($data->entry AS $entry) {
1773                 $username = "";
1774                 if (isset($entry->urls)) {
1775                         foreach($entry->urls as $url)
1776                                 if ($url->type == 'profile') {
1777                                         $profile_url = $url->value;
1778                                         $urlparts = parse_url($profile_url);
1779                                         $username = end(explode("/", $urlparts["path"]));
1780                                 }
1781                 }
1782                 if ($username != "") {
1783                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1784
1785                         // Fetch all contacts from a given user from the other server
1786                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1787
1788                         $retdata = z_fetch_url($url);
1789                         if ($retdata["success"])
1790                                 poco_discover_server(json_decode($retdata["body"]), 3);
1791                 }
1792         }
1793 }
1794
1795 function poco_discover_server($data, $default_generation = 0) {
1796
1797         if (!isset($data->entry) OR !count($data->entry))
1798                 return false;
1799
1800         $success = false;
1801
1802         foreach ($data->entry AS $entry) {
1803                 $profile_url = '';
1804                 $profile_photo = '';
1805                 $connect_url = '';
1806                 $name = '';
1807                 $network = '';
1808                 $updated = NULL_DATE;
1809                 $location = '';
1810                 $about = '';
1811                 $keywords = '';
1812                 $gender = '';
1813                 $contact_type = -1;
1814                 $generation = $default_generation;
1815
1816                 $name = $entry->displayName;
1817
1818                 if (isset($entry->urls)) {
1819                         foreach($entry->urls as $url) {
1820                                 if ($url->type == 'profile') {
1821                                         $profile_url = $url->value;
1822                                         continue;
1823                                 }
1824                                 if ($url->type == 'webfinger') {
1825                                         $connect_url = str_replace('acct:' , '', $url->value);
1826                                         continue;
1827                                 }
1828                         }
1829                 }
1830
1831                 if (isset($entry->photos)) {
1832                         foreach ($entry->photos as $photo) {
1833                                 if ($photo->type == 'profile') {
1834                                         $profile_photo = $photo->value;
1835                                         continue;
1836                                 }
1837                         }
1838                 }
1839
1840                 if (isset($entry->updated)) {
1841                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1842                 }
1843
1844                 if(isset($entry->network)) {
1845                         $network = $entry->network;
1846                 }
1847
1848                 if(isset($entry->currentLocation)) {
1849                         $location = $entry->currentLocation;
1850                 }
1851
1852                 if(isset($entry->aboutMe)) {
1853                         $about = html2bbcode($entry->aboutMe);
1854                 }
1855
1856                 if(isset($entry->gender)) {
1857                         $gender = $entry->gender;
1858                 }
1859
1860                 if(isset($entry->generation) AND ($entry->generation > 0)) {
1861                         $generation = ++$entry->generation;
1862                 }
1863
1864                 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1865                         $contact_type = $entry->contactType;
1866                 }
1867
1868                 if(isset($entry->tags)) {
1869                         foreach ($entry->tags as $tag) {
1870                                 $keywords = implode(", ", $tag);
1871                         }
1872                 }
1873
1874                 if ($generation > 0) {
1875                         $success = true;
1876
1877                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1878                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1879
1880                         $gcontact = array("url" => $profile_url, "contact-type" => $contact_type, "generation" => $generation);
1881                         update_gcontact($gcontact);
1882
1883                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1884                 }
1885         }
1886         return $success;
1887 }
1888
1889 /**
1890  * @brief Removes unwanted parts from a contact url
1891  *
1892  * @param string $url Contact url
1893  * @return string Contact url with the wanted parts
1894  */
1895 function clean_contact_url($url) {
1896         $parts = parse_url($url);
1897
1898         if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1899                 return $url;
1900
1901         $new_url = $parts["scheme"]."://".$parts["host"];
1902
1903         if (isset($parts["port"]))
1904                 $new_url .= ":".$parts["port"];
1905
1906         if (isset($parts["path"]))
1907                 $new_url .= $parts["path"];
1908
1909         if ($new_url != $url)
1910                 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1911
1912         return $new_url;
1913 }
1914
1915 /**
1916  * @brief Replace alternate OStatus user format with the primary one
1917  *
1918  * @param arr $contact contact array (called by reference)
1919  */
1920 function fix_alternate_contact_address(&$contact) {
1921         if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1922                 $data = probe_url($contact["url"]);
1923                 if ($contact["network"] == NETWORK_OSTATUS) {
1924                         logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1925                         $contact["url"] = $data["url"];
1926                         $contact["addr"] = $data["addr"];
1927                         $contact["alias"] = $data["alias"];
1928                         $contact["server_url"] = $data["baseurl"];
1929                 }
1930         }
1931 }
1932
1933 /**
1934  * @brief Fetch the gcontact id, add an entry if not existed
1935  *
1936  * @param arr $contact contact array
1937  * @return bool|int Returns false if not found, integer if contact was found
1938  */
1939 function get_gcontact_id($contact) {
1940
1941         $gcontact_id = 0;
1942         $doprobing = false;
1943
1944         if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1945                 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1946                 return false;
1947         }
1948
1949         if ($contact["network"] == NETWORK_STATUSNET)
1950                 $contact["network"] = NETWORK_OSTATUS;
1951
1952         // All new contacts are hidden by default
1953         if (!isset($contact["hide"]))
1954                 $contact["hide"] = true;
1955
1956         // Replace alternate OStatus user format with the primary one
1957         fix_alternate_contact_address($contact);
1958
1959         // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1960         if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1961                 $contact["url"] = clean_contact_url($contact["url"]);
1962
1963         $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
1964                 dbesc(normalise_link($contact["url"])));
1965
1966         if ($r) {
1967                 $gcontact_id = $r[0]["id"];
1968
1969                 // Update every 90 days
1970                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
1971                         $last_failure_str = $r[0]["last_failure"];
1972                         $last_failure = strtotime($r[0]["last_failure"]);
1973                         $last_contact_str = $r[0]["last_contact"];
1974                         $last_contact = strtotime($r[0]["last_contact"]);
1975                         $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
1976                 }
1977         } else {
1978                 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
1979                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
1980                         dbesc($contact["name"]),
1981                         dbesc($contact["nick"]),
1982                         dbesc($contact["addr"]),
1983                         dbesc($contact["network"]),
1984                         dbesc($contact["url"]),
1985                         dbesc(normalise_link($contact["url"])),
1986                         dbesc($contact["photo"]),
1987                         dbesc(datetime_convert()),
1988                         dbesc(datetime_convert()),
1989                         dbesc($contact["location"]),
1990                         dbesc($contact["about"]),
1991                         intval($contact["hide"]),
1992                         intval($contact["generation"])
1993                 );
1994
1995                 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1996                         dbesc(normalise_link($contact["url"])));
1997
1998                 if ($r) {
1999                         $gcontact_id = $r[0]["id"];
2000
2001                         $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2002                 }
2003         }
2004
2005         if ($doprobing) {
2006                 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2007                 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
2008         }
2009
2010         if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
2011          q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
2012                 dbesc(normalise_link($contact["url"])),
2013                 intval($gcontact_id));
2014
2015         return $gcontact_id;
2016 }
2017
2018 /**
2019  * @brief Updates the gcontact table from a given array
2020  *
2021  * @param arr $contact contact array
2022  * @return bool|int Returns false if not found, integer if contact was found
2023  */
2024 function update_gcontact($contact) {
2025
2026         // Check for invalid "contact-type" value
2027         if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
2028                 $contact['contact-type'] = 0;
2029         }
2030
2031         /// @todo update contact table as well
2032
2033         $gcontact_id = get_gcontact_id($contact);
2034
2035         if (!$gcontact_id)
2036                 return false;
2037
2038         $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2039                         `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2040                 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2041                 intval($gcontact_id));
2042
2043         // Get all field names
2044         $fields = array();
2045         foreach ($r[0] AS $field => $data)
2046                 $fields[$field] = $data;
2047
2048         unset($fields["url"]);
2049         unset($fields["updated"]);
2050         unset($fields["hide"]);
2051
2052         // Bugfix: We had an error in the storing of keywords which lead to the "0"
2053         // This value is still transmitted via poco.
2054         if ($contact["keywords"] == "0")
2055                 unset($contact["keywords"]);
2056
2057         if ($r[0]["keywords"] == "0")
2058                 $r[0]["keywords"] = "";
2059
2060         // assign all unassigned fields from the database entry
2061         foreach ($fields AS $field => $data)
2062                 if (!isset($contact[$field]) OR ($contact[$field] == ""))
2063                         $contact[$field] = $r[0][$field];
2064
2065         if (!isset($contact["hide"]))
2066                 $contact["hide"] = $r[0]["hide"];
2067
2068         $fields["hide"] = $r[0]["hide"];
2069
2070         if ($contact["network"] == NETWORK_STATUSNET)
2071                 $contact["network"] = NETWORK_OSTATUS;
2072
2073         // Replace alternate OStatus user format with the primary one
2074         fix_alternate_contact_address($contact);
2075
2076         if (!isset($contact["updated"]))
2077                 $contact["updated"] = datetime_convert();
2078
2079         if ($contact["server_url"] == "") {
2080                 $server_url = $contact["url"];
2081
2082                 $server_url = matching_url($server_url, $contact["alias"]);
2083                 if ($server_url != "")
2084                         $contact["server_url"] = $server_url;
2085
2086                 $server_url = matching_url($server_url, $contact["photo"]);
2087                 if ($server_url != "")
2088                         $contact["server_url"] = $server_url;
2089
2090                 $server_url = matching_url($server_url, $contact["notify"]);
2091                 if ($server_url != "")
2092                         $contact["server_url"] = $server_url;
2093         } else
2094                 $contact["server_url"] = normalise_link($contact["server_url"]);
2095
2096         if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
2097                 $hostname = str_replace("http://", "", $contact["server_url"]);
2098                 $contact["addr"] = $contact["nick"]."@".$hostname;
2099         }
2100
2101         // Check if any field changed
2102         $update = false;
2103         unset($fields["generation"]);
2104
2105         if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
2106                 foreach ($fields AS $field => $data)
2107                         if ($contact[$field] != $r[0][$field]) {
2108                                 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2109                                 $update = true;
2110                         }
2111
2112                 if ($contact["generation"] < $r[0]["generation"]) {
2113                         logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2114                         $update = true;
2115                 }
2116         }
2117
2118         if ($update) {
2119                 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2120
2121                 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
2122                                         `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
2123                                         `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
2124                                         `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
2125                                         `server_url` = '%s', `connect` = '%s'
2126                                 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
2127                         dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
2128                         dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
2129                         dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
2130                         intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
2131                         dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
2132                         dbesc($contact["about"]), intval($contact["generation"]), dbesc($contact["updated"]),
2133                         dbesc($contact["server_url"]), dbesc($contact["connect"]),
2134                         dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
2135
2136
2137                 // Now update the contact entry with the user id "0" as well.
2138                 // This is used for the shadow copies of public items.
2139                 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2140                         dbesc(normalise_link($contact["url"])));
2141
2142                 if ($r) {
2143                         logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
2144
2145                         update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2146
2147                         q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
2148                                                 `network` = '%s', `bd` = '%s', `gender` = '%s',
2149                                                 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
2150                                                 `url` = '%s', `location` = '%s', `about` = '%s'
2151                                         WHERE `id` = %d",
2152                                 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
2153                                 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
2154                                 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
2155                                 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
2156                                 intval($r[0]["id"]));
2157                 }
2158         }
2159
2160         return $gcontact_id;
2161 }
2162
2163 /**
2164  * @brief Updates the gcontact entry from probe
2165  *
2166  * @param str $url profile link
2167  */
2168 function update_gcontact_from_probe($url) {
2169         $data = probe_url($url);
2170
2171         if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2172                 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
2173                 return;
2174         }
2175
2176         update_gcontact($data);
2177 }
2178
2179 /**
2180  * @brief Update the gcontact entry for a given user id
2181  *
2182  * @param int $uid User ID
2183  */
2184 function update_gcontact_for_user($uid) {
2185         $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2186                         `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2187                         `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2188                         `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2189                         `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2190                 FROM `profile`
2191                         INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2192                         INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2193                 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2194                 intval($uid));
2195
2196         $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2197                                                 "country-name" => $r[0]["country-name"]));
2198
2199         // The "addr" field was added in 3.4.3 so it can be empty for older users
2200         if ($r[0]["addr"] != "")
2201                 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
2202         else
2203                 $addr = $r[0]["addr"];
2204
2205         $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2206                         "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2207                         "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2208                         "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2209                         "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
2210                         "nick" => $r[0]["nickname"], "addr" => $addr,
2211                         "connect" => $addr, "server_url" => App::get_baseurl(),
2212                         "generation" => 1, "network" => NETWORK_DFRN);
2213
2214         update_gcontact($gcontact);
2215 }
2216
2217 /**
2218  * @brief Fetches users of given GNU Social server
2219  *
2220  * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2221  *
2222  * @param str $server Server address
2223  */
2224 function gs_fetch_users($server) {
2225
2226         logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2227
2228         $url = $server."/main/statistics";
2229
2230         $result = z_fetch_url($url);
2231         if (!$result["success"])
2232                 return false;
2233
2234         $statistics = json_decode($result["body"]);
2235
2236         if (is_object($statistics->config)) {
2237                 if ($statistics->config->instance_with_ssl)
2238                         $server = "https://";
2239                 else
2240                         $server = "http://";
2241
2242                 $server .= $statistics->config->instance_address;
2243
2244                 $hostname = $statistics->config->instance_address;
2245         } else {
2246                 if ($statistics->instance_with_ssl)
2247                         $server = "https://";
2248                 else
2249                         $server = "http://";
2250
2251                 $server .= $statistics->instance_address;
2252
2253                 $hostname = $statistics->instance_address;
2254         }
2255
2256         if (is_object($statistics->users))
2257                 foreach ($statistics->users AS $nick => $user) {
2258                         $profile_url = $server."/".$user->nickname;
2259
2260                         $contact = array("url" => $profile_url,
2261                                         "name" => $user->fullname,
2262                                         "addr" => $user->nickname."@".$hostname,
2263                                         "nick" => $user->nickname,
2264                                         "about" => $user->bio,
2265                                         "network" => NETWORK_OSTATUS,
2266                                         "photo" => App::get_baseurl()."/images/person-175.jpg");
2267                         get_gcontact_id($contact);
2268                 }
2269 }
2270
2271 /**
2272  * @brief Asking GNU Social server on a regular base for their user data
2273  *
2274  */
2275 function gs_discover() {
2276
2277         $requery_days = intval(get_config("system", "poco_requery_days"));
2278
2279         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2280
2281         $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",
2282                 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2283
2284         if (!$r)
2285                 return;
2286
2287         foreach ($r AS $server) {
2288                 gs_fetch_users($server["url"]);
2289                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2290         }
2291 }
2292
2293 /**
2294  * @brief Returns a list of all known servers
2295  * @return array List of server urls
2296  */
2297 function poco_serverlist() {
2298         $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2299                 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2300                 ORDER BY `last_contact`
2301                 LIMIT 1000",
2302                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2303         if (!dbm::is_result($r)) {
2304                 return false;
2305         }
2306         return $r;
2307 }
2308 ?>