]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
71257c51b717724f8346212d3b137d5c10c3b9bf
[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 use \Friendica\Core\Config;
11
12 require_once('include/datetime.php');
13 require_once("include/Scrape.php");
14 require_once("include/network.php");
15 require_once("include/html2bbcode.php");
16 require_once("include/Contact.php");
17 require_once("include/Photo.php");
18
19 /**
20  * @brief Fetch POCO data
21  *
22  * @param integer $cid Contact ID
23  * @param integer $uid User ID
24  * @param integer $zcid Global Contact ID
25  * @param integer $url POCO address that should be polled
26  *
27  * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
28  * and add the entries to the gcontact (Global Contact) table, or update existing entries
29  * if anything (name or photo) has changed.
30  * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
31  *
32  * Once the global contact is stored add (if necessary) the contact linkage which associates
33  * the given uid, cid to the global contact entry. There can be many uid/cid combinations
34  * pointing to the same global contact id.
35  *
36  */
37 function poco_load($cid, $uid = 0, $zcid = 0, $url = null) {
38         // Call the function "poco_load_worker" via the worker
39         proc_run(PRIORITY_LOW, "include/discover_poco.php", "poco_load", intval($cid), intval($uid), intval($zcid), base64_encode($url));
40 }
41
42 /**
43  * @brief Fetch POCO data from the worker
44  *
45  * @param integer $cid Contact ID
46  * @param integer $uid User ID
47  * @param integer $zcid Global Contact ID
48  * @param integer $url POCO address that should be polled
49  *
50  */
51 function poco_load_worker($cid, $uid, $zcid, $url) {
52         $a = get_app();
53
54         if($cid) {
55                 if((! $url) || (! $uid)) {
56                         $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
57                                 intval($cid)
58                         );
59                         if (dbm::is_result($r)) {
60                                 $url = $r[0]['poco'];
61                                 $uid = $r[0]['uid'];
62                         }
63                 }
64                 if(! $uid)
65                         return;
66         }
67
68         if(! $url)
69                 return;
70
71         $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') ;
72
73         logger('poco_load: ' . $url, LOGGER_DEBUG);
74
75         $s = fetch_url($url);
76
77         logger('poco_load: returns ' . $s, LOGGER_DATA);
78
79         logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
80
81         if(($a->get_curl_code() > 299) || (! $s))
82                 return;
83
84         $j = json_decode($s);
85
86         logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
87
88         if(! isset($j->entry))
89                 return;
90
91         $total = 0;
92         foreach($j->entry as $entry) {
93
94                 $total ++;
95                 $profile_url = '';
96                 $profile_photo = '';
97                 $connect_url = '';
98                 $name = '';
99                 $network = '';
100                 $updated = NULL_DATE;
101                 $location = '';
102                 $about = '';
103                 $keywords = '';
104                 $gender = '';
105                 $contact_type = -1;
106                 $generation = 0;
107
108                 $name = $entry->displayName;
109
110                 if (isset($entry->urls)) {
111                         foreach ($entry->urls as $url) {
112                                 if ($url->type == 'profile') {
113                                         $profile_url = $url->value;
114                                         continue;
115                                 }
116                                 if ($url->type == 'webfinger') {
117                                         $connect_url = str_replace('acct:' , '', $url->value);
118                                         continue;
119                                 }
120                         }
121                 }
122                 if (isset($entry->photos)) {
123                         foreach ($entry->photos as $photo) {
124                                 if ($photo->type == 'profile') {
125                                         $profile_photo = $photo->value;
126                                         continue;
127                                 }
128                         }
129                 }
130
131                 if (isset($entry->updated)) {
132                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
133                 }
134
135                 if (isset($entry->network)) {
136                         $network = $entry->network;
137                 }
138
139                 if (isset($entry->currentLocation)) {
140                         $location = $entry->currentLocation;
141                 }
142
143                 if (isset($entry->aboutMe)) {
144                         $about = html2bbcode($entry->aboutMe);
145                 }
146
147                 if (isset($entry->gender)) {
148                         $gender = $entry->gender;
149                 }
150
151                 if (isset($entry->generation) AND ($entry->generation > 0)) {
152                         $generation = ++$entry->generation;
153                 }
154
155                 if (isset($entry->tags)) {
156                         foreach($entry->tags as $tag) {
157                                 $keywords = implode(", ", $tag);
158                         }
159                 }
160
161                 if (isset($entry->contactType) AND ($entry->contactType >= 0))
162                         $contact_type = $entry->contactType;
163
164                 $gcontact = array("url" => $profile_url,
165                                 "name" => $name,
166                                 "network" => $network,
167                                 "photo" => $profile_photo,
168                                 "about" => $about,
169                                 "location" => $location,
170                                 "gender" => $gender,
171                                 "keywords" => $keywords,
172                                 "connect" => $connect_url,
173                                 "updated" => $updated,
174                                 "contact-type" => $contact_type,
175                                 "generation" => $generation);
176
177                 try {
178                         $gcontact = sanitize_gcontact($gcontact);
179                         $gcid = update_gcontact($gcontact);
180
181                         link_gcontact($gcid, $uid, $cid, $zcid);
182                 } catch (Exception $e) {
183                         logger($e->getMessage(), LOGGER_DEBUG);
184                 }
185         }
186         logger("poco_load: loaded $total entries",LOGGER_DEBUG);
187
188         q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
189                 intval($cid),
190                 intval($uid),
191                 intval($zcid)
192         );
193
194 }
195 /**
196  * @brief Sanitize the given gcontact data
197  *
198  * @param array $gcontact array with gcontact data
199  * @throw Exception
200  *
201  * Generation:
202  *  0: No definition
203  *  1: Profiles on this server
204  *  2: Contacts of profiles on this server
205  *  3: Contacts of contacts of profiles on this server
206  *  4: ...
207  *
208  */
209 function sanitize_gcontact($gcontact) {
210
211         if ($gcontact['url'] == "") {
212                 throw new Exception('URL is empty');
213         }
214
215         $urlparts = parse_url($gcontact['url']);
216         if (!isset($urlparts["scheme"])) {
217                 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
218         }
219
220         if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
221                                                 "identi.ca", "alpha.app.net"))) {
222                 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
223         }
224
225         // Don't store the statusnet connector as network
226         // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
227         if ($gcontact['network'] == NETWORK_STATUSNET) {
228                 $gcontact['network'] = "";
229         }
230
231         // Assure that there are no parameter fragments in the profile url
232         if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
233                 $gcontact['url'] = clean_contact_url($gcontact['url']);
234         }
235
236         $alternate = poco_alternate_ostatus_url($gcontact['url']);
237
238         // The global contacts should contain the original picture, not the cached one
239         if (($gcontact['generation'] != 1) AND stristr(normalise_link($gcontact['photo']), normalise_link(App::get_baseurl()."/photo/"))) {
240                 $gcontact['photo'] = "";
241         }
242
243         if (!isset($gcontact['network'])) {
244                 $r = q("SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
245                         dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
246                 );
247                 if (dbm::is_result($r)) {
248                         $gcontact['network'] = $r[0]["network"];
249                 }
250
251                 if (($gcontact['network'] == "") OR ($gcontact['network'] == NETWORK_OSTATUS)) {
252                         $r = q("SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
253                                 dbesc($gcontact['url']), dbesc(normalise_link($gcontact['url'])), dbesc(NETWORK_STATUSNET)
254                         );
255                         if (dbm::is_result($r)) {
256                                 $gcontact['network'] = $r[0]["network"];
257                         }
258                 }
259         }
260
261         $gcontact['server_url'] = '';
262         $gcontact['network'] = '';
263
264         $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
265                 dbesc(normalise_link($gcontact['url']))
266         );
267
268         if (count($x)) {
269                 if (!isset($gcontact['network']) AND ($x[0]["network"] != NETWORK_STATUSNET)) {
270                         $gcontact['network'] = $x[0]["network"];
271                 }
272                 if ($gcontact['updated'] <= NULL_DATE) {
273                         $gcontact['updated'] = $x[0]["updated"];
274                 }
275                 if (!isset($gcontact['server_url']) AND (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
276                         $gcontact['server_url'] = $x[0]["server_url"];
277                 }
278                 if (!isset($gcontact['addr'])) {
279                         $gcontact['addr'] = $x[0]["addr"];
280                 }
281         }
282
283         if ((!isset($gcontact['network']) OR !isset($gcontact['name']) OR !isset($gcontact['addr']) OR !isset($gcontact['photo']) OR !isset($gcontact['server_url']) OR $alternate)
284                 AND poco_reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)) {
285                 $data = Probe::uri($gcontact['url']);
286
287                 if ($data["network"] == NETWORK_PHANTOM) {
288                         throw new Exception('Probing for URL '.$gcontact['url'].' failed');
289                 }
290
291                 $orig_profile = $gcontact['url'];
292
293                 $gcontact["server_url"] = $data["baseurl"];
294
295                 $gcontact = array_merge($gcontact, $data);
296
297                 if ($alternate AND ($gcontact['network'] == NETWORK_OSTATUS)) {
298                         // Delete the old entry - if it exists
299                         $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
300                         if ($r) {
301                                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
302                                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
303                         }
304                 }
305         }
306
307         if (!isset($gcontact['name']) OR !isset($gcontact['photo'])) {
308                 throw new Exception('No name and photo for URL '.$gcontact['url']);
309         }
310
311         if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
312                 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
313         }
314
315         if (!isset($gcontact['server_url'])) {
316                 // We check the server url to be sure that it is a real one
317                 $server_url = poco_detect_server($gcontact['url']);
318
319                 // We are now sure that it is a correct URL. So we use it in the future
320                 if ($server_url != "") {
321                         $gcontact['server_url'] = $server_url;
322                 }
323         }
324
325         // The server URL doesn't seem to be valid, so we don't store it.
326         if (!poco_check_server($gcontact['server_url'], $gcontact['network'])) {
327                 $gcontact['server_url'] = "";
328         }
329
330         return $gcontact;
331 }
332
333 /**
334  * @brief Link the gcontact entry with user, contact and global contact
335  *
336  * @param integer $gcid Global contact ID
337  * @param integer $cid Contact ID
338  * @param integer $uid User ID
339  * @param integer $zcid Global Contact ID
340  * *
341  */
342 function link_gcontact($gcid, $uid = 0, $cid = 0, $zcid = 0) {
343
344         if ($gcid <= 0) {
345                 return;
346         }
347
348         $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
349                 intval($cid),
350                 intval($uid),
351                 intval($gcid),
352                 intval($zcid)
353         );
354         if (!dbm::is_result($r)) {
355                 q("INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
356                         intval($cid),
357                         intval($uid),
358                         intval($gcid),
359                         intval($zcid),
360                         dbesc(datetime_convert())
361                 );
362         } else {
363                 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
364                         dbesc(datetime_convert()),
365                         intval($cid),
366                         intval($uid),
367                         intval($gcid),
368                         intval($zcid)
369                 );
370         }
371 }
372
373 function poco_reachable($profile, $server = "", $network = "", $force = false) {
374
375         if ($server == "")
376                 $server = poco_detect_server($profile);
377
378         if ($server == "")
379                 return true;
380
381         return poco_check_server($server, $network, $force);
382 }
383
384 function poco_detect_server($profile) {
385
386         // Try to detect the server path based upon some known standard paths
387         $server_url = "";
388
389         if ($server_url == "") {
390                 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
391                 if ($friendica != $profile) {
392                         $server_url = $friendica;
393                         $network = NETWORK_DFRN;
394                 }
395         }
396
397         if ($server_url == "") {
398                 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
399                 if ($diaspora != $profile) {
400                         $server_url = $diaspora;
401                         $network = NETWORK_DIASPORA;
402                 }
403         }
404
405         if ($server_url == "") {
406                 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
407                 if ($red != $profile) {
408                         $server_url = $red;
409                         $network = NETWORK_DIASPORA;
410                 }
411         }
412
413         // Mastodon
414         if ($server_url == "") {
415                 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
416                 if ($mastodon != $profile) {
417                         $server_url = $mastodon;
418                         $network = NETWORK_OSTATUS;
419                 }
420         }
421
422         // Numeric OStatus variant
423         if ($server_url == "") {
424                 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
425                 if ($ostatus != $profile) {
426                         $server_url = $ostatus;
427                         $network = NETWORK_OSTATUS;
428                 }
429         }
430
431         // Wild guess
432         if ($server_url == "") {
433                 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
434                 if ($base != $profile) {
435                         $server_url = $base;
436                         $network = NETWORK_PHANTOM;
437                 }
438         }
439
440         if ($server_url == "") {
441                 return "";
442         }
443
444         $r = q("SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
445                 dbesc(normalise_link($server_url)));
446         if (dbm::is_result($r)) {
447                 return $server_url;
448         }
449
450         // Fetch the host-meta to check if this really is a server
451         $serverret = z_fetch_url($server_url."/.well-known/host-meta");
452         if (!$serverret["success"]) {
453                 return "";
454         }
455
456         return $server_url;
457 }
458
459 function poco_alternate_ostatus_url($url) {
460         return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
461 }
462
463 function poco_last_updated($profile, $force = false) {
464
465         $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
466                         dbesc(normalise_link($profile)));
467
468         if (!dbm::is_result($gcontacts)) {
469                 return false;
470         }
471
472         $contact = array("url" => $profile);
473
474         if ($gcontacts[0]["created"] <= NULL_DATE) {
475                 $contact['created'] = datetime_convert();
476         }
477
478         if ($force) {
479                 $server_url = normalise_link(poco_detect_server($profile));
480         }
481
482         if (($server_url == '') AND ($gcontacts[0]["server_url"] != "")) {
483                 $server_url = $gcontacts[0]["server_url"];
484         }
485
486         if (!$force AND (($server_url == '') OR ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
487                 $server_url = normalise_link(poco_detect_server($profile));
488         }
489
490         if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
491                 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
492                 return false;
493         }
494
495         if ($server_url != "") {
496                 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
497                         if ($force) {
498                                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
499                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
500                         }
501
502                         logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
503                         return false;
504                 }
505                 $contact['server_url'] = $server_url;
506         }
507
508         if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
509                 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
510                         dbesc(normalise_link($server_url)));
511
512                 if ($server) {
513                         $contact['network'] = $server[0]["network"];
514                 } else {
515                         return false;
516                 }
517         }
518
519         // noscrape is really fast so we don't cache the call.
520         if (($server_url != "") AND ($gcontacts[0]["nick"] != "")) {
521
522                 //  Use noscrape if possible
523                 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($server_url)));
524
525                 if ($server) {
526                         $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
527
528                         if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
529
530                                 $noscrape = json_decode($noscraperet["body"], true);
531
532                                 if (is_array($noscrape)) {
533                                         $contact["network"] = $server[0]["network"];
534
535                                         if (isset($noscrape["fn"])) {
536                                                 $contact["name"] = $noscrape["fn"];
537                                         }
538                                         if (isset($noscrape["comm"])) {
539                                                 $contact["community"] = $noscrape["comm"];
540                                         }
541                                         if (isset($noscrape["tags"])) {
542                                                 $keywords = implode(" ", $noscrape["tags"]);
543                                                 if ($keywords != "") {
544                                                         $contact["keywords"] = $keywords;
545                                                 }
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
595                 update_gcontact($contact);
596                 return $gcontacts[0]["updated"];
597         }
598
599         $data = Probe::uri($profile);
600
601         // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
602         // Then check the other link and delete this one
603         if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
604                 (normalise_link($profile) == normalise_link($data["alias"])) AND
605                 (normalise_link($profile) != normalise_link($data["url"]))) {
606
607                 // Delete the old entry
608                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
609                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
610
611                 $gcontact = array_merge($gcontacts[0], $data);
612
613                 $gcontact["server_url"] = $data["baseurl"];
614
615                 try {
616                         $gcontact = sanitize_gcontact($gcontact);
617                         update_gcontact($gcontact);
618
619                         poco_last_updated($data["url"], $force);
620                 } catch (Exception $e) {
621                         logger($e->getMessage(), LOGGER_DEBUG);
622                 }
623
624                 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
625                 return false;
626         }
627
628         if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
629                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
630                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
631
632                 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
633                 return false;
634         }
635
636         $contact = array_merge($contact, $data);
637
638         $contact["server_url"] = $data["baseurl"];
639
640         update_gcontact($contact);
641
642         $feedret = z_fetch_url($data["poll"]);
643
644         if (!$feedret["success"]) {
645                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
646                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
647
648                 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
649                 return false;
650         }
651
652         $doc = new DOMDocument();
653         @$doc->loadXML($feedret["body"]);
654
655         $xpath = new DomXPath($doc);
656         $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
657
658         $entries = $xpath->query('/atom:feed/atom:entry');
659
660         $last_updated = "";
661
662         foreach ($entries AS $entry) {
663                 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
664                 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
665
666                 if ($last_updated < $published)
667                         $last_updated = $published;
668
669                 if ($last_updated < $updated)
670                         $last_updated = $updated;
671         }
672
673         // Maybe there aren't any entries. Then check if it is a valid feed
674         if ($last_updated == "") {
675                 if ($xpath->query('/atom:feed')->length > 0) {
676                         $last_updated = NULL_DATE;
677                 }
678         }
679         q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
680                 dbesc(dbm::date($last_updated)), dbesc(dbm::date()), dbesc(normalise_link($profile)));
681
682         if (($gcontacts[0]["generation"] == 0)) {
683                 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
684                         dbesc(normalise_link($profile)));
685         }
686
687         logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
688
689         return($last_updated);
690 }
691
692 function poco_do_update($created, $updated, $last_failure,  $last_contact) {
693         $now = strtotime(datetime_convert());
694
695         if ($updated > $last_contact)
696                 $contact_time = strtotime($updated);
697         else
698                 $contact_time = strtotime($last_contact);
699
700         $failure_time = strtotime($last_failure);
701         $created_time = strtotime($created);
702
703         // If there is no "created" time then use the current time
704         if ($created_time <= 0)
705                 $created_time = $now;
706
707         // If the last contact was less than 24 hours then don't update
708         if (($now - $contact_time) < (60 * 60 * 24))
709                 return false;
710
711         // If the last failure was less than 24 hours then don't update
712         if (($now - $failure_time) < (60 * 60 * 24))
713                 return false;
714
715         // If the last contact was less than a week ago and the last failure is older than a week then don't update
716         //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
717         //      return false;
718
719         // 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
720         if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
721                 return false;
722
723         // 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
724         if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
725                 return false;
726
727         return true;
728 }
729
730 function poco_to_boolean($val) {
731         if (($val == "true") OR ($val == 1))
732                 return(true);
733         if (($val == "false") OR ($val == 0))
734                 return(false);
735
736         return ($val);
737 }
738
739 /**
740  * @brief Detect server type (Hubzilla or Friendica) via the poco data
741  *
742  * @param object $data POCO data
743  * @return array Server data
744  */
745 function poco_detect_poco_data($data) {
746         $server = false;
747
748         if (!isset($data->entry)) {
749                 return false;
750         }
751
752         if (count($data->entry) == 0) {
753                 return false;
754         }
755
756         if (!isset($data->entry[0]->urls)) {
757                 return false;
758         }
759
760         if (count($data->entry[0]->urls) == 0) {
761                 return false;
762         }
763
764         foreach ($data->entry[0]->urls AS $url) {
765                 if ($url->type == 'zot') {
766                         $server = array();
767                         $server["platform"] = 'Hubzilla';
768                         $server["network"] = NETWORK_DIASPORA;
769                         return $server;
770                 }
771         }
772         return false;
773 }
774
775 /**
776  * @brief Detect server type by using the nodeinfo data
777  *
778  * @param string $server_url address of the server
779  * @return array Server data
780  */
781 function poco_fetch_nodeinfo($server_url) {
782         $serverret = z_fetch_url($server_url."/.well-known/nodeinfo");
783         if (!$serverret["success"]) {
784                 return false;
785         }
786
787         $nodeinfo = json_decode($serverret['body']);
788
789         if (!is_object($nodeinfo)) {
790                 return false;
791         }
792
793         if (!is_array($nodeinfo->links)) {
794                 return false;
795         }
796
797         $nodeinfo_url = '';
798
799         foreach ($nodeinfo->links AS $link) {
800                 if ($link->rel == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
801                         $nodeinfo_url = $link->href;
802                 }
803         }
804
805         if ($nodeinfo_url == '') {
806                 return false;
807         }
808
809         $serverret = z_fetch_url($nodeinfo_url);
810         if (!$serverret["success"]) {
811                 return false;
812         }
813
814         $nodeinfo = json_decode($serverret['body']);
815
816         if (!is_object($nodeinfo)) {
817                 return false;
818         }
819
820         $server = array();
821
822         $server['register_policy'] = REGISTER_CLOSED;
823
824         if (is_bool($nodeinfo->openRegistrations) AND $nodeinfo->openRegistrations) {
825                 $server['register_policy'] = REGISTER_OPEN;
826         }
827
828         if (is_object($nodeinfo->software)) {
829                 if (isset($nodeinfo->software->name)) {
830                         $server['platform'] = $nodeinfo->software->name;
831                 }
832
833                 if (isset($nodeinfo->software->version)) {
834                         $server['version'] = $nodeinfo->software->version;
835                         // Version numbers on Nodeinfo are presented with additional info, e.g.:
836                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
837                         $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
838                 }
839         }
840
841         if (is_object($nodeinfo->metadata)) {
842                 if (isset($nodeinfo->metadata->nodeName)) {
843                         $server['site_name'] = $nodeinfo->metadata->nodeName;
844                 }
845         }
846
847         $diaspora = false;
848         $friendica = false;
849         $gnusocial = false;
850
851         if (is_array($nodeinfo->protocols->inbound)) {
852                 foreach ($nodeinfo->protocols->inbound AS $inbound) {
853                         if ($inbound == 'diaspora') {
854                                 $diaspora = true;
855                         }
856                         if ($inbound == 'friendica') {
857                                 $friendica = true;
858                         }
859                         if ($inbound == 'gnusocial') {
860                                 $gnusocial = true;
861                         }
862                 }
863         }
864
865         if ($gnusocial) {
866                 $server['network'] = NETWORK_OSTATUS;
867         }
868         if ($diaspora) {
869                 $server['network'] = NETWORK_DIASPORA;
870         }
871         if ($friendica) {
872                 $server['network'] = NETWORK_DFRN;
873         }
874
875         if (!$server) {
876                 return false;
877         }
878
879         return $server;
880 }
881
882 /**
883  * @brief Detect server type (Hubzilla or Friendica) via the front page body
884  *
885  * @param string $body Front page of the server
886  * @return array Server data
887  */
888 function poco_detect_server_type($body) {
889         $server = false;
890
891         $doc = new \DOMDocument();
892         @$doc->loadHTML($body);
893         $xpath = new \DomXPath($doc);
894
895         $list = $xpath->query("//meta[@name]");
896
897         foreach ($list as $node) {
898                 $attr = array();
899                 if ($node->attributes->length) {
900                         foreach ($node->attributes as $attribute) {
901                                 $attr[$attribute->name] = $attribute->value;
902                         }
903                 }
904                 if ($attr['name'] == 'generator') {
905                         $version_part = explode(" ", $attr['content']);
906                         if (count($version_part) == 2) {
907                                 if (in_array($version_part[0], array("Friendika", "Friendica"))) {
908                                         $server = array();
909                                         $server["platform"] = $version_part[0];
910                                         $server["version"] = $version_part[1];
911                                         $server["network"] = NETWORK_DFRN;
912                                 }
913                         }
914                 }
915         }
916
917         if (!$server) {
918                 $list = $xpath->query("//meta[@property]");
919
920                 foreach ($list as $node) {
921                         $attr = array();
922                         if ($node->attributes->length) {
923                                 foreach ($node->attributes as $attribute) {
924                                         $attr[$attribute->name] = $attribute->value;
925                                 }
926                         }
927                         if ($attr['property'] == 'generator') {
928                                 if (in_array($attr['content'], array("hubzilla", "BlaBlaNet"))) {
929                                         $server = array();
930                                         $server["platform"] = $attr['content'];
931                                         $server["version"] = "";
932                                         $server["network"] = NETWORK_DIASPORA;
933                                 }
934                         }
935                 }
936         }
937
938         if (!$server) {
939                 return false;
940         }
941
942         $server["site_name"] = $xpath->evaluate($element."//head/title/text()", $context)->item(0)->nodeValue;
943         return $server;
944 }
945
946 function poco_check_server($server_url, $network = "", $force = false) {
947
948         // Unify the server address
949         $server_url = trim($server_url, "/");
950         $server_url = str_replace("/index.php", "", $server_url);
951
952         if ($server_url == "")
953                 return false;
954
955         $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
956         if (dbm::is_result($servers)) {
957
958                 if ($servers[0]["created"] <= NULL_DATE) {
959                         q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
960                                 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
961                 }
962                 $poco = $servers[0]["poco"];
963                 $noscrape = $servers[0]["noscrape"];
964
965                 if ($network == "")
966                         $network = $servers[0]["network"];
967
968                 $last_contact = $servers[0]["last_contact"];
969                 $last_failure = $servers[0]["last_failure"];
970                 $version = $servers[0]["version"];
971                 $platform = $servers[0]["platform"];
972                 $site_name = $servers[0]["site_name"];
973                 $info = $servers[0]["info"];
974                 $register_policy = $servers[0]["register_policy"];
975
976                 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
977                         logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
978                         return ($last_contact >= $last_failure);
979                 }
980         } else {
981                 $poco = "";
982                 $noscrape = "";
983                 $version = "";
984                 $platform = "";
985                 $site_name = "";
986                 $info = "";
987                 $register_policy = -1;
988
989                 $last_contact = NULL_DATE;
990                 $last_failure = NULL_DATE;
991         }
992         logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
993
994         $failure = false;
995         $possible_failure = false;
996         $orig_last_failure = $last_failure;
997         $orig_last_contact = $last_contact;
998
999         // Check if the page is accessible via SSL.
1000         $orig_server_url = $server_url;
1001         $server_url = str_replace("http://", "https://", $server_url);
1002
1003         // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1004         $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1005
1006         // Quit if there is a timeout.
1007         // But we want to make sure to only quit if we are mostly sure that this server url fits.
1008         if (dbm::is_result($servers) AND ($orig_server_url == $server_url) AND
1009                 ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1010                 logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1011                 return false;
1012         }
1013
1014         // Maybe the page is unencrypted only?
1015         $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1016         if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1017                 $server_url = str_replace("https://", "http://", $server_url);
1018
1019                 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1020                 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1021
1022                 // Quit if there is a timeout
1023                 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1024                         logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1025                         return false;
1026                 }
1027
1028                 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1029         }
1030
1031         if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1032                 // Workaround for bad configured servers (known nginx problem)
1033                 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1034                         $last_failure = datetime_convert();
1035                         $failure = true;
1036                 }
1037                 $possible_failure = true;
1038         } elseif ($network == NETWORK_DIASPORA)
1039                 $last_contact = datetime_convert();
1040
1041         // If the server has no possible failure we reset the cached data
1042         if (!$possible_failure) {
1043                 $version = "";
1044                 $platform = "";
1045                 $site_name = "";
1046                 $info = "";
1047                 $register_policy = -1;
1048         }
1049
1050         // Look for poco
1051         if (!$failure) {
1052                 $serverret = z_fetch_url($server_url."/poco");
1053                 if ($serverret["success"]) {
1054                         $data = json_decode($serverret["body"]);
1055                         if (isset($data->totalResults)) {
1056                                 $poco = $server_url."/poco";
1057                                 $last_contact = datetime_convert();
1058
1059                                 $server = poco_detect_poco_data($data);
1060                                 if ($server) {
1061                                         $platform = $server['platform'];
1062                                         $network = $server['network'];
1063                                         $version = '';
1064                                         $site_name = '';
1065                                 }
1066                         }
1067                 }
1068         }
1069
1070         if (!$failure) {
1071                 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1072                 $serverret = z_fetch_url($server_url);
1073
1074                 if (!$serverret["success"] OR ($serverret["body"] == "")) {
1075                         $last_failure = datetime_convert();
1076                         $failure = true;
1077                 } else {
1078                         $server = poco_detect_server_type($serverret["body"]);
1079                         if ($server) {
1080                                 $platform = $server['platform'];
1081                                 $network = $server['network'];
1082                                 $version = $server['version'];
1083                                 $site_name = $server['site_name'];
1084                                 $last_contact = datetime_convert();
1085                         }
1086
1087                         $lines = explode("\n",$serverret["header"]);
1088                         if(count($lines)) {
1089                                 foreach($lines as $line) {
1090                                         $line = trim($line);
1091                                         if(stristr($line,'X-Diaspora-Version:')) {
1092                                                 $platform = "Diaspora";
1093                                                 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1094                                                 $version = trim(str_replace("x-diaspora-version:", "", $version));
1095                                                 $network = NETWORK_DIASPORA;
1096                                                 $versionparts = explode("-", $version);
1097                                                 $version = $versionparts[0];
1098                                                 $last_contact = datetime_convert();
1099                                         }
1100
1101                                         if(stristr($line,'Server: Mastodon')) {
1102                                                 $platform = "Mastodon";
1103                                                 $network = NETWORK_OSTATUS;
1104                                                 // Mastodon doesn't reveal version numbers
1105                                                 $version = "";
1106                                                 $last_contact = datetime_convert();
1107                                         }
1108                                 }
1109                         }
1110                 }
1111         }
1112
1113         if (!$failure AND ($poco == "")) {
1114                 // Test for Statusnet
1115                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1116                 // The "not implemented" is a special treatment for really, really old Friendica versions
1117                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1118                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1119                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1120                         $platform = "StatusNet";
1121                         // Remove junk that some GNU Social servers return
1122                         $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1123                         $version = trim($version, '"');
1124                         $network = NETWORK_OSTATUS;
1125                         $last_contact = datetime_convert();
1126                 }
1127
1128                 // Test for GNU Social
1129                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1130                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1131                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1132                         $platform = "GNU Social";
1133                         // Remove junk that some GNU Social servers return
1134                         $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1135                         $version = trim($version, '"');
1136                         $network = NETWORK_OSTATUS;
1137                         $last_contact = datetime_convert();
1138                 }
1139
1140                 // Test for Mastodon
1141                 $serverret = z_fetch_url($server_url."/api/v1/instance");
1142                 if ($serverret["success"] AND ($serverret["body"] != '')) {
1143                         $data = json_decode($serverret["body"]);
1144                         if (isset($data->version)) {
1145                                 $platform = "Mastodon";
1146                                 $version = $data->version;
1147                                 $site_name = $data->title;
1148                                 $info = $data->description;
1149                                 $network = NETWORK_OSTATUS;
1150                                 $last_contact = datetime_convert();
1151                         }
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         // Disvover Mastodon servers
1676         if (!Config::get('system','ostatus_disabled')) {
1677                 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1678
1679                 if ($serverdata) {
1680                         $servers = json_decode($serverdata);
1681
1682                         foreach ($servers AS $server) {
1683                                 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1684                                 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($url));
1685                         }
1686                 }
1687         }
1688
1689         // Currently disabled, since the service isn't available anymore.
1690         // It is not removed since I hope that there will be a successor.
1691         // Discover GNU Social Servers.
1692         //if (!get_config('system','ostatus_disabled')) {
1693         //      $serverdata = "http://gstools.org/api/get_open_instances/";
1694
1695         //      $result = z_fetch_url($serverdata);
1696         //      if ($result["success"]) {
1697         //              $servers = json_decode($result["body"]);
1698
1699         //              foreach($servers->data AS $server)
1700         //                      poco_check_server($server->instance_address);
1701         //      }
1702         //}
1703
1704         set_config('poco','last_federation_discovery', time());
1705 }
1706
1707 function poco_discover_single_server($id) {
1708         $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1709         if (!dbm::is_result($r)) {
1710                 return false;
1711         }
1712
1713         $server = $r[0];
1714
1715         // Discover new servers out there (Works from Friendica version 3.5.2)
1716         poco_fetch_serverlist($server["poco"]);
1717
1718         // Fetch all users from the other server
1719         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1720
1721         logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1722
1723         $retdata = z_fetch_url($url);
1724         if ($retdata["success"]) {
1725                 $data = json_decode($retdata["body"]);
1726
1727                 poco_discover_server($data, 2);
1728
1729                 if (get_config('system','poco_discovery') > 1) {
1730
1731                         $timeframe = get_config('system','poco_discovery_since');
1732                         if ($timeframe == 0) {
1733                                 $timeframe = 30;
1734                         }
1735
1736                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1737
1738                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1739                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1740
1741                         $success = false;
1742
1743                         $retdata = z_fetch_url($url);
1744                         if ($retdata["success"]) {
1745                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1746                                 $success = poco_discover_server(json_decode($retdata["body"]));
1747                         }
1748
1749                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1750                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1751                                 poco_discover_server_users($data, $server);
1752                         }
1753                 }
1754
1755                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1756
1757                 return true;
1758         } else {
1759                 // If the server hadn't replied correctly, then force a sanity check
1760                 poco_check_server($server["url"], $server["network"], true);
1761
1762                 // If we couldn't reach the server, we will try it some time later
1763                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1764
1765                 return false;
1766         }
1767 }
1768
1769 function poco_discover($complete = false) {
1770
1771         // Update the server list
1772         poco_discover_federation();
1773
1774         $no_of_queries = 5;
1775
1776         $requery_days = intval(get_config("system", "poco_requery_days"));
1777
1778         if ($requery_days == 0) {
1779                 $requery_days = 7;
1780         }
1781         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1782
1783         $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));
1784         if (dbm::is_result($r)) {
1785                 foreach ($r AS $server) {
1786
1787                         if (!poco_check_server($server["url"], $server["network"])) {
1788                                 // The server is not reachable? Okay, then we will try it later
1789                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1790                                 continue;
1791                         }
1792
1793                         logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1794                         proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
1795
1796                         if (!$complete AND (--$no_of_queries == 0)) {
1797                                 break;
1798                         }
1799                 }
1800         }
1801 }
1802
1803 function poco_discover_server_users($data, $server) {
1804
1805         if (!isset($data->entry))
1806                 return;
1807
1808         foreach ($data->entry AS $entry) {
1809                 $username = "";
1810                 if (isset($entry->urls)) {
1811                         foreach($entry->urls as $url)
1812                                 if ($url->type == 'profile') {
1813                                         $profile_url = $url->value;
1814                                         $urlparts = parse_url($profile_url);
1815                                         $username = end(explode("/", $urlparts["path"]));
1816                                 }
1817                 }
1818                 if ($username != "") {
1819                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1820
1821                         // Fetch all contacts from a given user from the other server
1822                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1823
1824                         $retdata = z_fetch_url($url);
1825                         if ($retdata["success"])
1826                                 poco_discover_server(json_decode($retdata["body"]), 3);
1827                 }
1828         }
1829 }
1830
1831 function poco_discover_server($data, $default_generation = 0) {
1832
1833         if (!isset($data->entry) OR !count($data->entry))
1834                 return false;
1835
1836         $success = false;
1837
1838         foreach ($data->entry AS $entry) {
1839                 $profile_url = '';
1840                 $profile_photo = '';
1841                 $connect_url = '';
1842                 $name = '';
1843                 $network = '';
1844                 $updated = NULL_DATE;
1845                 $location = '';
1846                 $about = '';
1847                 $keywords = '';
1848                 $gender = '';
1849                 $contact_type = -1;
1850                 $generation = $default_generation;
1851
1852                 $name = $entry->displayName;
1853
1854                 if (isset($entry->urls)) {
1855                         foreach($entry->urls as $url) {
1856                                 if ($url->type == 'profile') {
1857                                         $profile_url = $url->value;
1858                                         continue;
1859                                 }
1860                                 if ($url->type == 'webfinger') {
1861                                         $connect_url = str_replace('acct:' , '', $url->value);
1862                                         continue;
1863                                 }
1864                         }
1865                 }
1866
1867                 if (isset($entry->photos)) {
1868                         foreach ($entry->photos as $photo) {
1869                                 if ($photo->type == 'profile') {
1870                                         $profile_photo = $photo->value;
1871                                         continue;
1872                                 }
1873                         }
1874                 }
1875
1876                 if (isset($entry->updated)) {
1877                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1878                 }
1879
1880                 if(isset($entry->network)) {
1881                         $network = $entry->network;
1882                 }
1883
1884                 if(isset($entry->currentLocation)) {
1885                         $location = $entry->currentLocation;
1886                 }
1887
1888                 if(isset($entry->aboutMe)) {
1889                         $about = html2bbcode($entry->aboutMe);
1890                 }
1891
1892                 if(isset($entry->gender)) {
1893                         $gender = $entry->gender;
1894                 }
1895
1896                 if(isset($entry->generation) AND ($entry->generation > 0)) {
1897                         $generation = ++$entry->generation;
1898                 }
1899
1900                 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1901                         $contact_type = $entry->contactType;
1902                 }
1903
1904                 if(isset($entry->tags)) {
1905                         foreach ($entry->tags as $tag) {
1906                                 $keywords = implode(", ", $tag);
1907                         }
1908                 }
1909
1910                 if ($generation > 0) {
1911                         $success = true;
1912
1913                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1914
1915                         $gcontact = array("url" => $profile_url,
1916                                         "name" => $name,
1917                                         "network" => $network,
1918                                         "photo" => $profile_photo,
1919                                         "about" => $about,
1920                                         "location" => $location,
1921                                         "gender" => $gender,
1922                                         "keywords" => $keywords,
1923                                         "connect" => $connect_url,
1924                                         "updated" => $updated,
1925                                         "contact-type" => $contact_type,
1926                                         "generation" => $generation);
1927
1928                         try {
1929                                 $gcontact = sanitize_gcontact($gcontact);
1930                                 update_gcontact($gcontact);
1931                         } catch (Exception $e) {
1932                                 logger($e->getMessage(), LOGGER_DEBUG);
1933                         }
1934
1935                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1936                 }
1937         }
1938         return $success;
1939 }
1940
1941 /**
1942  * @brief Removes unwanted parts from a contact url
1943  *
1944  * @param string $url Contact url
1945  * @return string Contact url with the wanted parts
1946  */
1947 function clean_contact_url($url) {
1948         $parts = parse_url($url);
1949
1950         if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1951                 return $url;
1952
1953         $new_url = $parts["scheme"]."://".$parts["host"];
1954
1955         if (isset($parts["port"]))
1956                 $new_url .= ":".$parts["port"];
1957
1958         if (isset($parts["path"]))
1959                 $new_url .= $parts["path"];
1960
1961         if ($new_url != $url)
1962                 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1963
1964         return $new_url;
1965 }
1966
1967 /**
1968  * @brief Replace alternate OStatus user format with the primary one
1969  *
1970  * @param arr $contact contact array (called by reference)
1971  */
1972 function fix_alternate_contact_address(&$contact) {
1973         if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1974                 $data = probe_url($contact["url"]);
1975                 if ($contact["network"] == NETWORK_OSTATUS) {
1976                         logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1977                         $contact["url"] = $data["url"];
1978                         $contact["addr"] = $data["addr"];
1979                         $contact["alias"] = $data["alias"];
1980                         $contact["server_url"] = $data["baseurl"];
1981                 }
1982         }
1983 }
1984
1985 /**
1986  * @brief Fetch the gcontact id, add an entry if not existed
1987  *
1988  * @param arr $contact contact array
1989  * @return bool|int Returns false if not found, integer if contact was found
1990  */
1991 function get_gcontact_id($contact) {
1992
1993         $gcontact_id = 0;
1994         $doprobing = false;
1995
1996         if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1997                 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1998                 return false;
1999         }
2000
2001         if ($contact["network"] == NETWORK_STATUSNET)
2002                 $contact["network"] = NETWORK_OSTATUS;
2003
2004         // All new contacts are hidden by default
2005         if (!isset($contact["hide"]))
2006                 $contact["hide"] = true;
2007
2008         // Replace alternate OStatus user format with the primary one
2009         fix_alternate_contact_address($contact);
2010
2011         // Remove unwanted parts from the contact url (e.g. "?zrl=...")
2012         if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
2013                 $contact["url"] = clean_contact_url($contact["url"]);
2014
2015         $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
2016                 dbesc(normalise_link($contact["url"])));
2017
2018         if ($r) {
2019                 $gcontact_id = $r[0]["id"];
2020
2021                 // Update every 90 days
2022                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
2023                         $last_failure_str = $r[0]["last_failure"];
2024                         $last_failure = strtotime($r[0]["last_failure"]);
2025                         $last_contact_str = $r[0]["last_contact"];
2026                         $last_contact = strtotime($r[0]["last_contact"]);
2027                         $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
2028                 }
2029         } else {
2030                 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
2031                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
2032                         dbesc($contact["name"]),
2033                         dbesc($contact["nick"]),
2034                         dbesc($contact["addr"]),
2035                         dbesc($contact["network"]),
2036                         dbesc($contact["url"]),
2037                         dbesc(normalise_link($contact["url"])),
2038                         dbesc($contact["photo"]),
2039                         dbesc(datetime_convert()),
2040                         dbesc(datetime_convert()),
2041                         dbesc($contact["location"]),
2042                         dbesc($contact["about"]),
2043                         intval($contact["hide"]),
2044                         intval($contact["generation"])
2045                 );
2046
2047                 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
2048                         dbesc(normalise_link($contact["url"])));
2049
2050                 if ($r) {
2051                         $gcontact_id = $r[0]["id"];
2052
2053                         $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2054                 }
2055         }
2056
2057         if ($doprobing) {
2058                 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2059                 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
2060         }
2061
2062         if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
2063          q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
2064                 dbesc(normalise_link($contact["url"])),
2065                 intval($gcontact_id));
2066
2067         return $gcontact_id;
2068 }
2069
2070 /**
2071  * @brief Updates the gcontact table from a given array
2072  *
2073  * @param arr $contact contact array
2074  * @return bool|int Returns false if not found, integer if contact was found
2075  */
2076 function update_gcontact($contact) {
2077
2078         // Check for invalid "contact-type" value
2079         if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
2080                 $contact['contact-type'] = 0;
2081         }
2082
2083         /// @todo update contact table as well
2084
2085         $gcontact_id = get_gcontact_id($contact);
2086
2087         if (!$gcontact_id)
2088                 return false;
2089
2090         $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2091                         `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2092                 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2093                 intval($gcontact_id));
2094
2095         // Get all field names
2096         $fields = array();
2097         foreach ($r[0] AS $field => $data)
2098                 $fields[$field] = $data;
2099
2100         unset($fields["url"]);
2101         unset($fields["updated"]);
2102         unset($fields["hide"]);
2103
2104         // Bugfix: We had an error in the storing of keywords which lead to the "0"
2105         // This value is still transmitted via poco.
2106         if ($contact["keywords"] == "0")
2107                 unset($contact["keywords"]);
2108
2109         if ($r[0]["keywords"] == "0")
2110                 $r[0]["keywords"] = "";
2111
2112         // assign all unassigned fields from the database entry
2113         foreach ($fields AS $field => $data)
2114                 if (!isset($contact[$field]) OR ($contact[$field] == ""))
2115                         $contact[$field] = $r[0][$field];
2116
2117         if (!isset($contact["hide"]))
2118                 $contact["hide"] = $r[0]["hide"];
2119
2120         $fields["hide"] = $r[0]["hide"];
2121
2122         if ($contact["network"] == NETWORK_STATUSNET)
2123                 $contact["network"] = NETWORK_OSTATUS;
2124
2125         // Replace alternate OStatus user format with the primary one
2126         fix_alternate_contact_address($contact);
2127
2128         if (!isset($contact["updated"]))
2129                 $contact["updated"] = dbm::date();
2130
2131         if ($contact["server_url"] == "") {
2132                 $server_url = $contact["url"];
2133
2134                 $server_url = matching_url($server_url, $contact["alias"]);
2135                 if ($server_url != "")
2136                         $contact["server_url"] = $server_url;
2137
2138                 $server_url = matching_url($server_url, $contact["photo"]);
2139                 if ($server_url != "")
2140                         $contact["server_url"] = $server_url;
2141
2142                 $server_url = matching_url($server_url, $contact["notify"]);
2143                 if ($server_url != "")
2144                         $contact["server_url"] = $server_url;
2145         } else
2146                 $contact["server_url"] = normalise_link($contact["server_url"]);
2147
2148         if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
2149                 $hostname = str_replace("http://", "", $contact["server_url"]);
2150                 $contact["addr"] = $contact["nick"]."@".$hostname;
2151         }
2152
2153         // Check if any field changed
2154         $update = false;
2155         unset($fields["generation"]);
2156
2157         if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
2158                 foreach ($fields AS $field => $data)
2159                         if ($contact[$field] != $r[0][$field]) {
2160                                 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2161                                 $update = true;
2162                         }
2163
2164                 if ($contact["generation"] < $r[0]["generation"]) {
2165                         logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2166                         $update = true;
2167                 }
2168         }
2169
2170         if ($update) {
2171                 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2172
2173                 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
2174                                         `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
2175                                         `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
2176                                         `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
2177                                         `server_url` = '%s', `connect` = '%s'
2178                                 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
2179                         dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
2180                         dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
2181                         dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
2182                         intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
2183                         dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
2184                         dbesc($contact["about"]), intval($contact["generation"]), dbesc(dbm::date($contact["updated"])),
2185                         dbesc($contact["server_url"]), dbesc($contact["connect"]),
2186                         dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
2187
2188
2189                 // Now update the contact entry with the user id "0" as well.
2190                 // This is used for the shadow copies of public items.
2191                 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2192                         dbesc(normalise_link($contact["url"])));
2193
2194                 if ($r) {
2195                         logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
2196
2197                         update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2198
2199                         q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
2200                                                 `network` = '%s', `bd` = '%s', `gender` = '%s',
2201                                                 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
2202                                                 `url` = '%s', `location` = '%s', `about` = '%s'
2203                                         WHERE `id` = %d",
2204                                 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
2205                                 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
2206                                 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
2207                                 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
2208                                 intval($r[0]["id"]));
2209                 }
2210         }
2211
2212         return $gcontact_id;
2213 }
2214
2215 /**
2216  * @brief Updates the gcontact entry from probe
2217  *
2218  * @param str $url profile link
2219  */
2220 function update_gcontact_from_probe($url) {
2221         $data = probe_url($url);
2222
2223         if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2224                 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
2225                 return;
2226         }
2227
2228         $data["server_url"] = $data["baseurl"];
2229
2230         update_gcontact($data);
2231 }
2232
2233 /**
2234  * @brief Update the gcontact entry for a given user id
2235  *
2236  * @param int $uid User ID
2237  */
2238 function update_gcontact_for_user($uid) {
2239         $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2240                         `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2241                         `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2242                         `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2243                         `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2244                 FROM `profile`
2245                         INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2246                         INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2247                 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2248                 intval($uid));
2249
2250         $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2251                                                 "country-name" => $r[0]["country-name"]));
2252
2253         // The "addr" field was added in 3.4.3 so it can be empty for older users
2254         if ($r[0]["addr"] != "")
2255                 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
2256         else
2257                 $addr = $r[0]["addr"];
2258
2259         $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2260                         "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2261                         "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2262                         "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2263                         "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
2264                         "nick" => $r[0]["nickname"], "addr" => $addr,
2265                         "connect" => $addr, "server_url" => App::get_baseurl(),
2266                         "generation" => 1, "network" => NETWORK_DFRN);
2267
2268         update_gcontact($gcontact);
2269 }
2270
2271 /**
2272  * @brief Fetches users of given GNU Social server
2273  *
2274  * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2275  *
2276  * @param str $server Server address
2277  */
2278 function gs_fetch_users($server) {
2279
2280         logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2281
2282         $url = $server."/main/statistics";
2283
2284         $result = z_fetch_url($url);
2285         if (!$result["success"])
2286                 return false;
2287
2288         $statistics = json_decode($result["body"]);
2289
2290         if (is_object($statistics->config)) {
2291                 if ($statistics->config->instance_with_ssl)
2292                         $server = "https://";
2293                 else
2294                         $server = "http://";
2295
2296                 $server .= $statistics->config->instance_address;
2297
2298                 $hostname = $statistics->config->instance_address;
2299         } else {
2300                 if ($statistics->instance_with_ssl)
2301                         $server = "https://";
2302                 else
2303                         $server = "http://";
2304
2305                 $server .= $statistics->instance_address;
2306
2307                 $hostname = $statistics->instance_address;
2308         }
2309
2310         if (is_object($statistics->users))
2311                 foreach ($statistics->users AS $nick => $user) {
2312                         $profile_url = $server."/".$user->nickname;
2313
2314                         $contact = array("url" => $profile_url,
2315                                         "name" => $user->fullname,
2316                                         "addr" => $user->nickname."@".$hostname,
2317                                         "nick" => $user->nickname,
2318                                         "about" => $user->bio,
2319                                         "network" => NETWORK_OSTATUS,
2320                                         "photo" => App::get_baseurl()."/images/person-175.jpg");
2321                         get_gcontact_id($contact);
2322                 }
2323 }
2324
2325 /**
2326  * @brief Asking GNU Social server on a regular base for their user data
2327  *
2328  */
2329 function gs_discover() {
2330
2331         $requery_days = intval(get_config("system", "poco_requery_days"));
2332
2333         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2334
2335         $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",
2336                 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2337
2338         if (!$r)
2339                 return;
2340
2341         foreach ($r AS $server) {
2342                 gs_fetch_users($server["url"]);
2343                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2344         }
2345 }
2346
2347 /**
2348  * @brief Returns a list of all known servers
2349  * @return array List of server urls
2350  */
2351 function poco_serverlist() {
2352         $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2353                 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2354                 ORDER BY `last_contact`
2355                 LIMIT 1000",
2356                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2357         if (!dbm::is_result($r)) {
2358                 return false;
2359         }
2360         return $r;
2361 }
2362 ?>