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