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