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