]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
Fix require_once format
[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 require_once("include/Scrape.php");
13
14 require_once 'include/datetime.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                 dba::p("UPDATE `gserver` SET `last_failure` = ? WHERE `nurl` = ?", datetime_convert(), normalise_link($server_url));
1013                 return false;
1014         }
1015
1016         // Maybe the page is unencrypted only?
1017         $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1018         if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1019                 $server_url = str_replace("https://", "http://", $server_url);
1020
1021                 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1022                 $serverret = z_fetch_url($server_url."/.well-known/host-meta", false, $redirects, array('timeout' => 20));
1023
1024                 // Quit if there is a timeout
1025                 if ($serverret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1026                         logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG);
1027                         dba::p("UPDATE `gserver` SET `last_failure` = ? WHERE `nurl` = ?", datetime_convert(), normalise_link($server_url));
1028                         return false;
1029                 }
1030
1031                 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1032         }
1033
1034         if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
1035                 // Workaround for bad configured servers (known nginx problem)
1036                 if (!in_array($serverret["debug"]["http_code"], array("403", "404"))) {
1037                         $failure = true;
1038                 }
1039                 $possible_failure = true;
1040         }
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                                 $server = poco_detect_poco_data($data);
1059                                 if ($server) {
1060                                         $platform = $server['platform'];
1061                                         $network = $server['network'];
1062                                         $version = '';
1063                                         $site_name = '';
1064                                 }
1065                         }
1066                 }
1067         }
1068
1069         if (!$failure) {
1070                 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1071                 $serverret = z_fetch_url($server_url);
1072
1073                 if (!$serverret["success"] OR ($serverret["body"] == "")) {
1074                         $failure = true;
1075                 } else {
1076                         $server = poco_detect_server_type($serverret["body"]);
1077                         if ($server) {
1078                                 $platform = $server['platform'];
1079                                 $network = $server['network'];
1080                                 $version = $server['version'];
1081                                 $site_name = $server['site_name'];
1082                         }
1083
1084                         $lines = explode("\n",$serverret["header"]);
1085                         if(count($lines)) {
1086                                 foreach($lines as $line) {
1087                                         $line = trim($line);
1088                                         if(stristr($line,'X-Diaspora-Version:')) {
1089                                                 $platform = "Diaspora";
1090                                                 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1091                                                 $version = trim(str_replace("x-diaspora-version:", "", $version));
1092                                                 $network = NETWORK_DIASPORA;
1093                                                 $versionparts = explode("-", $version);
1094                                                 $version = $versionparts[0];
1095                                         }
1096
1097                                         if(stristr($line,'Server: Mastodon')) {
1098                                                 $platform = "Mastodon";
1099                                                 $network = NETWORK_OSTATUS;
1100                                         }
1101                                 }
1102                         }
1103                 }
1104         }
1105
1106         if (!$failure AND ($poco == "")) {
1107                 // Test for Statusnet
1108                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1109                 // The "not implemented" is a special treatment for really, really old Friendica versions
1110                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
1111                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1112                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1113                         $platform = "StatusNet";
1114                         // Remove junk that some GNU Social servers return
1115                         $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1116                         $version = trim($version, '"');
1117                         $network = NETWORK_OSTATUS;
1118                 }
1119
1120                 // Test for GNU Social
1121                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
1122                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
1123                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
1124                         $platform = "GNU Social";
1125                         // Remove junk that some GNU Social servers return
1126                         $version = str_replace(chr(239).chr(187).chr(191), "", $serverret["body"]);
1127                         $version = trim($version, '"');
1128                         $network = NETWORK_OSTATUS;
1129                 }
1130
1131                 // Test for Mastodon
1132                 $serverret = z_fetch_url($server_url."/api/v1/instance");
1133                 if ($serverret["success"] AND ($serverret["body"] != '')) {
1134                         $data = json_decode($serverret["body"]);
1135                         if (isset($data->version)) {
1136                                 $platform = "Mastodon";
1137                                 $version = $data->version;
1138                                 $site_name = $data->title;
1139                                 $info = $data->description;
1140                                 $network = NETWORK_OSTATUS;
1141                         }
1142                 }
1143         }
1144
1145         if (!$failure) {
1146                 // Test for Hubzilla, Redmatrix or Friendica
1147                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
1148                 if ($serverret["success"]) {
1149                         $data = json_decode($serverret["body"]);
1150                         if (isset($data->site->server)) {
1151                                 if (isset($data->site->platform)) {
1152                                         $platform = $data->site->platform->PLATFORM_NAME;
1153                                         $version = $data->site->platform->STD_VERSION;
1154                                         $network = NETWORK_DIASPORA;
1155                                 }
1156                                 if (isset($data->site->BlaBlaNet)) {
1157                                         $platform = $data->site->BlaBlaNet->PLATFORM_NAME;
1158                                         $version = $data->site->BlaBlaNet->STD_VERSION;
1159                                         $network = NETWORK_DIASPORA;
1160                                 }
1161                                 if (isset($data->site->hubzilla)) {
1162                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
1163                                         $version = $data->site->hubzilla->RED_VERSION;
1164                                         $network = NETWORK_DIASPORA;
1165                                 }
1166                                 if (isset($data->site->redmatrix)) {
1167                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
1168                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
1169                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
1170                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
1171
1172                                         $version = $data->site->redmatrix->RED_VERSION;
1173                                         $network = NETWORK_DIASPORA;
1174                                 }
1175                                 if (isset($data->site->friendica)) {
1176                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
1177                                         $version = $data->site->friendica->FRIENDICA_VERSION;
1178                                         $network = NETWORK_DFRN;
1179                                 }
1180
1181                                 $site_name = $data->site->name;
1182
1183                                 $data->site->closed = poco_to_boolean($data->site->closed);
1184                                 $data->site->private = poco_to_boolean($data->site->private);
1185                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
1186
1187                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
1188                                         $register_policy = REGISTER_APPROVE;
1189                                 elseif (!$data->site->closed AND !$data->site->private)
1190                                         $register_policy = REGISTER_OPEN;
1191                                 else
1192                                         $register_policy = REGISTER_CLOSED;
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         }
1226
1227         // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1228         if (!$failure) {
1229                 $server = poco_fetch_nodeinfo($server_url);
1230                 if ($server) {
1231                         $register_policy = $server['register_policy'];
1232
1233                         if (isset($server['platform'])) {
1234                                 $platform = $server['platform'];
1235                         }
1236
1237                         if (isset($server['network'])) {
1238                                 $network = $server['network'];
1239                         }
1240
1241                         if (isset($server['version'])) {
1242                                 $version = $server['version'];
1243                         }
1244
1245                         if (isset($server['site_name'])) {
1246                                 $site_name = $server['site_name'];
1247                         }
1248                 }
1249         }
1250
1251         // Check for noscrape
1252         // Friendica servers could be detected as OStatus servers
1253         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
1254                 $serverret = z_fetch_url($server_url."/friendica/json");
1255
1256                 if (!$serverret["success"])
1257                         $serverret = z_fetch_url($server_url."/friendika/json");
1258
1259                 if ($serverret["success"]) {
1260                         $data = json_decode($serverret["body"]);
1261
1262                         if (isset($data->version)) {
1263                                 $network = NETWORK_DFRN;
1264
1265                                 $noscrape = $data->no_scrape_url;
1266                                 $version = $data->version;
1267                                 $site_name = $data->site_name;
1268                                 $info = $data->info;
1269                                 $register_policy_str = $data->register_policy;
1270                                 $platform = $data->platform;
1271
1272                                 switch ($register_policy_str) {
1273                                         case "REGISTER_CLOSED":
1274                                                 $register_policy = REGISTER_CLOSED;
1275                                                 break;
1276                                         case "REGISTER_APPROVE":
1277                                                 $register_policy = REGISTER_APPROVE;
1278                                                 break;
1279                                         case "REGISTER_OPEN":
1280                                                 $register_policy = REGISTER_OPEN;
1281                                                 break;
1282                                 }
1283                         }
1284                 }
1285         }
1286
1287         if ($possible_failure AND !$failure) {
1288                 $failure = true;
1289         }
1290
1291         if ($failure) {
1292                 $last_contact = $orig_last_contact;
1293                 $last_failure = datetime_convert();
1294         } else {
1295                 $last_contact = datetime_convert();
1296                 $last_failure = $orig_last_failure;
1297         }
1298
1299         if (($last_contact <= $last_failure) AND !$failure) {
1300                 logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG);
1301         } else if (($last_contact >= $last_failure) AND $failure) {
1302                 logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG);
1303         }
1304
1305         // Check again if the server exists
1306         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1307
1308         $version = strip_tags($version);
1309         $site_name = strip_tags($site_name);
1310         $info = strip_tags($info);
1311         $platform = strip_tags($platform);
1312
1313         if ($servers) {
1314                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
1315                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
1316                         dbesc($server_url),
1317                         dbesc($version),
1318                         dbesc($site_name),
1319                         dbesc($info),
1320                         intval($register_policy),
1321                         dbesc($poco),
1322                         dbesc($noscrape),
1323                         dbesc($network),
1324                         dbesc($platform),
1325                         dbesc($last_contact),
1326                         dbesc($last_failure),
1327                         dbesc(normalise_link($server_url))
1328                 );
1329         } elseif (!$failure) {
1330                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
1331                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
1332                                 dbesc($server_url),
1333                                 dbesc(normalise_link($server_url)),
1334                                 dbesc($version),
1335                                 dbesc($site_name),
1336                                 dbesc($info),
1337                                 intval($register_policy),
1338                                 dbesc($poco),
1339                                 dbesc($noscrape),
1340                                 dbesc($network),
1341                                 dbesc($platform),
1342                                 dbesc(datetime_convert()),
1343                                 dbesc($last_contact),
1344                                 dbesc($last_failure),
1345                                 dbesc(datetime_convert())
1346                 );
1347         }
1348         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
1349
1350         return !$failure;
1351 }
1352
1353 function count_common_friends($uid,$cid) {
1354
1355         $r = q("SELECT count(*) as `total`
1356                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1357                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1358                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1359                 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1360                 intval($cid),
1361                 intval($uid),
1362                 intval($uid),
1363                 intval($cid)
1364         );
1365
1366 //      logger("count_common_friends: $uid $cid {$r[0]['total']}");
1367         if (dbm::is_result($r))
1368                 return $r[0]['total'];
1369         return 0;
1370
1371 }
1372
1373
1374 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1375
1376         if($shuffle)
1377                 $sql_extra = " order by rand() ";
1378         else
1379                 $sql_extra = " order by `gcontact`.`name` asc ";
1380
1381         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1382                 FROM `glink`
1383                 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1384                 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1385                 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1386                         AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1387                         AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1388                         AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1389                         $sql_extra LIMIT %d, %d",
1390                 intval($cid),
1391                 intval($uid),
1392                 intval($uid),
1393                 intval($cid),
1394                 intval($start),
1395                 intval($limit)
1396         );
1397
1398         return $r;
1399
1400 }
1401
1402
1403 function count_common_friends_zcid($uid,$zcid) {
1404
1405         $r = q("SELECT count(*) as `total`
1406                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1407                 where `glink`.`zcid` = %d
1408                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1409                 intval($zcid),
1410                 intval($uid)
1411         );
1412
1413         if (dbm::is_result($r))
1414                 return $r[0]['total'];
1415         return 0;
1416
1417 }
1418
1419 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1420
1421         if($shuffle)
1422                 $sql_extra = " order by rand() ";
1423         else
1424                 $sql_extra = " order by `gcontact`.`name` asc ";
1425
1426         $r = q("SELECT `gcontact`.*
1427                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1428                 where `glink`.`zcid` = %d
1429                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
1430                 $sql_extra limit %d, %d",
1431                 intval($zcid),
1432                 intval($uid),
1433                 intval($start),
1434                 intval($limit)
1435         );
1436
1437         return $r;
1438
1439 }
1440
1441
1442 function count_all_friends($uid,$cid) {
1443
1444         $r = q("SELECT count(*) as `total`
1445                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1446                 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1447                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1448                 intval($cid),
1449                 intval($uid)
1450         );
1451
1452         if (dbm::is_result($r))
1453                 return $r[0]['total'];
1454         return 0;
1455
1456 }
1457
1458
1459 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1460
1461         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1462                 FROM `glink`
1463                 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1464                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1465                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1466                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1467                 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1468                 intval($uid),
1469                 intval($cid),
1470                 intval($uid),
1471                 intval($start),
1472                 intval($limit)
1473         );
1474
1475         return $r;
1476 }
1477
1478
1479
1480 function suggestion_query($uid, $start = 0, $limit = 80) {
1481
1482         if (!$uid) {
1483                 return array();
1484         }
1485
1486 // Uncommented because the result of the queries are to big to store it in the cache.
1487 // We need to decide if we want to change the db column type or if we want to delete it.
1488 //      $list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
1489 //      if (!is_null($list)) {
1490 //              return $list;
1491 //      }
1492
1493         $network = array(NETWORK_DFRN);
1494
1495         if (get_config('system','diaspora_enabled'))
1496                 $network[] = NETWORK_DIASPORA;
1497
1498         if (!get_config('system','ostatus_disabled'))
1499                 $network[] = NETWORK_OSTATUS;
1500
1501         $sql_network = implode("', '", $network);
1502         $sql_network = "'".$sql_network."'";
1503
1504         /// @todo This query is really slow
1505         // By now we cache the data for five minutes
1506         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1507                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1508                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1509                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1510                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1511                 AND `gcontact`.`updated` >= '%s'
1512                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1513                 AND `gcontact`.`network` IN (%s)
1514                 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1515                 intval($uid),
1516                 intval($uid),
1517                 intval($uid),
1518                 intval($uid),
1519                 dbesc(NULL_DATE),
1520                 $sql_network,
1521                 intval($start),
1522                 intval($limit)
1523         );
1524
1525         if (dbm::is_result($r) && count($r) >= ($limit -1)) {
1526 // Uncommented because the result of the queries are to big to store it in the cache.
1527 // We need to decide if we want to change the db column type or if we want to delete it.
1528 //              Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
1529
1530                 return $r;
1531         }
1532
1533         $r2 = q("SELECT gcontact.* FROM gcontact
1534                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1535                 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1536                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1537                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1538                 AND `gcontact`.`updated` >= '%s'
1539                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1540                 AND `gcontact`.`network` IN (%s)
1541                 ORDER BY rand() LIMIT %d, %d",
1542                 intval($uid),
1543                 intval($uid),
1544                 intval($uid),
1545                 dbesc(NULL_DATE),
1546                 $sql_network,
1547                 intval($start),
1548                 intval($limit)
1549         );
1550
1551         $list = array();
1552         foreach ($r2 AS $suggestion)
1553                 $list[$suggestion["nurl"]] = $suggestion;
1554
1555         foreach ($r AS $suggestion)
1556                 $list[$suggestion["nurl"]] = $suggestion;
1557
1558         while (sizeof($list) > ($limit))
1559                 array_pop($list);
1560
1561 // Uncommented because the result of the queries are to big to store it in the cache.
1562 // We need to decide if we want to change the db column type or if we want to delete it.
1563 //      Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
1564         return $list;
1565 }
1566
1567 function update_suggestions() {
1568
1569         $a = get_app();
1570
1571         $done = array();
1572
1573         /// @TODO Check if it is really neccessary to poll the own server
1574         poco_load(0,0,0,App::get_baseurl() . '/poco');
1575
1576         $done[] = App::get_baseurl() . '/poco';
1577
1578         if (strlen(get_config('system','directory'))) {
1579                 $x = fetch_url(get_server()."/pubsites");
1580                 if ($x) {
1581                         $j = json_decode($x);
1582                         if ($j->entries) {
1583                                 foreach ($j->entries as $entry) {
1584
1585                                         poco_check_server($entry->url);
1586
1587                                         $url = $entry->url . '/poco';
1588                                         if (! in_array($url,$done)) {
1589                                                 poco_load(0,0,0,$entry->url . '/poco');
1590                                         }
1591                                 }
1592                         }
1593                 }
1594         }
1595
1596         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1597         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1598                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1599         );
1600
1601         if (dbm::is_result($r)) {
1602                 foreach ($r as $rr) {
1603                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1604                         if(! in_array($base,$done))
1605                                 poco_load(0,0,0,$base);
1606                 }
1607         }
1608 }
1609
1610 /**
1611  * @brief Fetch server list from remote servers and adds them when they are new.
1612  *
1613  * @param string $poco URL to the POCO endpoint
1614  */
1615 function poco_fetch_serverlist($poco) {
1616         $serverret = z_fetch_url($poco."/@server");
1617         if (!$serverret["success"]) {
1618                 return;
1619         }
1620         $serverlist = json_decode($serverret['body']);
1621
1622         if (!is_array($serverlist)) {
1623                 return;
1624         }
1625
1626         foreach ($serverlist AS $server) {
1627                 $server_url = str_replace("/index.php", "", $server->url);
1628
1629                 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
1630                 if (!dbm::is_result($r)) {
1631                         logger("Call server check for server ".$server_url, LOGGER_DEBUG);
1632                         proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($server_url));
1633                 }
1634         }
1635 }
1636
1637 function poco_discover_federation() {
1638         $last = get_config('poco','last_federation_discovery');
1639
1640         if ($last) {
1641                 $next = $last + (24 * 60 * 60);
1642                 if($next > time())
1643                         return;
1644         }
1645
1646         // Discover Friendica, Hubzilla and Diaspora servers
1647         $serverdata = fetch_url("http://the-federation.info/pods.json");
1648
1649         if ($serverdata) {
1650                 $servers = json_decode($serverdata);
1651
1652                 foreach ($servers->pods AS $server) {
1653                         proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode("https://".$server->host));
1654                 }
1655         }
1656
1657         // Disvover Mastodon servers
1658         if (!Config::get('system','ostatus_disabled')) {
1659                 $serverdata = fetch_url("https://instances.mastodon.xyz/instances.json");
1660
1661                 if ($serverdata) {
1662                         $servers = json_decode($serverdata);
1663
1664                         foreach ($servers AS $server) {
1665                                 $url = (is_null($server->https_score) ? 'http' : 'https').'://'.$server->name;
1666                                 proc_run(PRIORITY_LOW, "include/discover_poco.php", "server", base64_encode($url));
1667                         }
1668                 }
1669         }
1670
1671         // Currently disabled, since the service isn't available anymore.
1672         // It is not removed since I hope that there will be a successor.
1673         // Discover GNU Social Servers.
1674         //if (!get_config('system','ostatus_disabled')) {
1675         //      $serverdata = "http://gstools.org/api/get_open_instances/";
1676
1677         //      $result = z_fetch_url($serverdata);
1678         //      if ($result["success"]) {
1679         //              $servers = json_decode($result["body"]);
1680
1681         //              foreach($servers->data AS $server)
1682         //                      poco_check_server($server->instance_address);
1683         //      }
1684         //}
1685
1686         set_config('poco','last_federation_discovery', time());
1687 }
1688
1689 function poco_discover_single_server($id) {
1690         $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1691         if (!dbm::is_result($r)) {
1692                 return false;
1693         }
1694
1695         $server = $r[0];
1696
1697         // Discover new servers out there (Works from Friendica version 3.5.2)
1698         poco_fetch_serverlist($server["poco"]);
1699
1700         // Fetch all users from the other server
1701         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1702
1703         logger("Fetch all users from the server ".$server["url"], LOGGER_DEBUG);
1704
1705         $retdata = z_fetch_url($url);
1706         if ($retdata["success"]) {
1707                 $data = json_decode($retdata["body"]);
1708
1709                 poco_discover_server($data, 2);
1710
1711                 if (get_config('system','poco_discovery') > 1) {
1712
1713                         $timeframe = get_config('system','poco_discovery_since');
1714                         if ($timeframe == 0) {
1715                                 $timeframe = 30;
1716                         }
1717
1718                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1719
1720                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1721                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1722
1723                         $success = false;
1724
1725                         $retdata = z_fetch_url($url);
1726                         if ($retdata["success"]) {
1727                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1728                                 $success = poco_discover_server(json_decode($retdata["body"]));
1729                         }
1730
1731                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1732                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1733                                 poco_discover_server_users($data, $server);
1734                         }
1735                 }
1736
1737                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1738
1739                 return true;
1740         } else {
1741                 // If the server hadn't replied correctly, then force a sanity check
1742                 poco_check_server($server["url"], $server["network"], true);
1743
1744                 // If we couldn't reach the server, we will try it some time later
1745                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1746
1747                 return false;
1748         }
1749 }
1750
1751 function poco_discover($complete = false) {
1752
1753         // Update the server list
1754         poco_discover_federation();
1755
1756         $no_of_queries = 5;
1757
1758         $requery_days = intval(get_config("system", "poco_requery_days"));
1759
1760         if ($requery_days == 0) {
1761                 $requery_days = 7;
1762         }
1763         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1764
1765         $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));
1766         if (dbm::is_result($r)) {
1767                 foreach ($r AS $server) {
1768
1769                         if (!poco_check_server($server["url"], $server["network"])) {
1770                                 // The server is not reachable? Okay, then we will try it later
1771                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1772                                 continue;
1773                         }
1774
1775                         logger('Update directory from server '.$server['url'].' with ID '.$server['id'], LOGGER_DEBUG);
1776                         proc_run(PRIORITY_LOW, "include/discover_poco.php", "update_server_directory", intval($server['id']));
1777
1778                         if (!$complete AND (--$no_of_queries == 0)) {
1779                                 break;
1780                         }
1781                 }
1782         }
1783 }
1784
1785 function poco_discover_server_users($data, $server) {
1786
1787         if (!isset($data->entry))
1788                 return;
1789
1790         foreach ($data->entry AS $entry) {
1791                 $username = "";
1792                 if (isset($entry->urls)) {
1793                         foreach($entry->urls as $url)
1794                                 if ($url->type == 'profile') {
1795                                         $profile_url = $url->value;
1796                                         $urlparts = parse_url($profile_url);
1797                                         $username = end(explode("/", $urlparts["path"]));
1798                                 }
1799                 }
1800                 if ($username != "") {
1801                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1802
1803                         // Fetch all contacts from a given user from the other server
1804                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1805
1806                         $retdata = z_fetch_url($url);
1807                         if ($retdata["success"])
1808                                 poco_discover_server(json_decode($retdata["body"]), 3);
1809                 }
1810         }
1811 }
1812
1813 function poco_discover_server($data, $default_generation = 0) {
1814
1815         if (!isset($data->entry) OR !count($data->entry))
1816                 return false;
1817
1818         $success = false;
1819
1820         foreach ($data->entry AS $entry) {
1821                 $profile_url = '';
1822                 $profile_photo = '';
1823                 $connect_url = '';
1824                 $name = '';
1825                 $network = '';
1826                 $updated = NULL_DATE;
1827                 $location = '';
1828                 $about = '';
1829                 $keywords = '';
1830                 $gender = '';
1831                 $contact_type = -1;
1832                 $generation = $default_generation;
1833
1834                 $name = $entry->displayName;
1835
1836                 if (isset($entry->urls)) {
1837                         foreach($entry->urls as $url) {
1838                                 if ($url->type == 'profile') {
1839                                         $profile_url = $url->value;
1840                                         continue;
1841                                 }
1842                                 if ($url->type == 'webfinger') {
1843                                         $connect_url = str_replace('acct:' , '', $url->value);
1844                                         continue;
1845                                 }
1846                         }
1847                 }
1848
1849                 if (isset($entry->photos)) {
1850                         foreach ($entry->photos as $photo) {
1851                                 if ($photo->type == 'profile') {
1852                                         $profile_photo = $photo->value;
1853                                         continue;
1854                                 }
1855                         }
1856                 }
1857
1858                 if (isset($entry->updated)) {
1859                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1860                 }
1861
1862                 if(isset($entry->network)) {
1863                         $network = $entry->network;
1864                 }
1865
1866                 if(isset($entry->currentLocation)) {
1867                         $location = $entry->currentLocation;
1868                 }
1869
1870                 if(isset($entry->aboutMe)) {
1871                         $about = html2bbcode($entry->aboutMe);
1872                 }
1873
1874                 if(isset($entry->gender)) {
1875                         $gender = $entry->gender;
1876                 }
1877
1878                 if(isset($entry->generation) AND ($entry->generation > 0)) {
1879                         $generation = ++$entry->generation;
1880                 }
1881
1882                 if(isset($entry->contactType) AND ($entry->contactType >= 0)) {
1883                         $contact_type = $entry->contactType;
1884                 }
1885
1886                 if(isset($entry->tags)) {
1887                         foreach ($entry->tags as $tag) {
1888                                 $keywords = implode(", ", $tag);
1889                         }
1890                 }
1891
1892                 if ($generation > 0) {
1893                         $success = true;
1894
1895                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1896
1897                         $gcontact = array("url" => $profile_url,
1898                                         "name" => $name,
1899                                         "network" => $network,
1900                                         "photo" => $profile_photo,
1901                                         "about" => $about,
1902                                         "location" => $location,
1903                                         "gender" => $gender,
1904                                         "keywords" => $keywords,
1905                                         "connect" => $connect_url,
1906                                         "updated" => $updated,
1907                                         "contact-type" => $contact_type,
1908                                         "generation" => $generation);
1909
1910                         try {
1911                                 $gcontact = sanitize_gcontact($gcontact);
1912                                 update_gcontact($gcontact);
1913                         } catch (Exception $e) {
1914                                 logger($e->getMessage(), LOGGER_DEBUG);
1915                         }
1916
1917                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1918                 }
1919         }
1920         return $success;
1921 }
1922
1923 /**
1924  * @brief Removes unwanted parts from a contact url
1925  *
1926  * @param string $url Contact url
1927  * @return string Contact url with the wanted parts
1928  */
1929 function clean_contact_url($url) {
1930         $parts = parse_url($url);
1931
1932         if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1933                 return $url;
1934
1935         $new_url = $parts["scheme"]."://".$parts["host"];
1936
1937         if (isset($parts["port"]))
1938                 $new_url .= ":".$parts["port"];
1939
1940         if (isset($parts["path"]))
1941                 $new_url .= $parts["path"];
1942
1943         if ($new_url != $url)
1944                 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1945
1946         return $new_url;
1947 }
1948
1949 /**
1950  * @brief Replace alternate OStatus user format with the primary one
1951  *
1952  * @param arr $contact contact array (called by reference)
1953  */
1954 function fix_alternate_contact_address(&$contact) {
1955         if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1956                 $data = probe_url($contact["url"]);
1957                 if ($contact["network"] == NETWORK_OSTATUS) {
1958                         logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1959                         $contact["url"] = $data["url"];
1960                         $contact["addr"] = $data["addr"];
1961                         $contact["alias"] = $data["alias"];
1962                         $contact["server_url"] = $data["baseurl"];
1963                 }
1964         }
1965 }
1966
1967 /**
1968  * @brief Fetch the gcontact id, add an entry if not existed
1969  *
1970  * @param arr $contact contact array
1971  * @return bool|int Returns false if not found, integer if contact was found
1972  */
1973 function get_gcontact_id($contact) {
1974
1975         $gcontact_id = 0;
1976         $doprobing = false;
1977
1978         if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1979                 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1980                 return false;
1981         }
1982
1983         if ($contact["network"] == NETWORK_STATUSNET)
1984                 $contact["network"] = NETWORK_OSTATUS;
1985
1986         // All new contacts are hidden by default
1987         if (!isset($contact["hide"]))
1988                 $contact["hide"] = true;
1989
1990         // Replace alternate OStatus user format with the primary one
1991         fix_alternate_contact_address($contact);
1992
1993         // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1994         if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1995                 $contact["url"] = clean_contact_url($contact["url"]);
1996
1997         $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 2",
1998                 dbesc(normalise_link($contact["url"])));
1999
2000         if ($r) {
2001                 $gcontact_id = $r[0]["id"];
2002
2003                 // Update every 90 days
2004                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
2005                         $last_failure_str = $r[0]["last_failure"];
2006                         $last_failure = strtotime($r[0]["last_failure"]);
2007                         $last_contact_str = $r[0]["last_contact"];
2008                         $last_contact = strtotime($r[0]["last_contact"]);
2009                         $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
2010                 }
2011         } else {
2012                 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
2013                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
2014                         dbesc($contact["name"]),
2015                         dbesc($contact["nick"]),
2016                         dbesc($contact["addr"]),
2017                         dbesc($contact["network"]),
2018                         dbesc($contact["url"]),
2019                         dbesc(normalise_link($contact["url"])),
2020                         dbesc($contact["photo"]),
2021                         dbesc(datetime_convert()),
2022                         dbesc(datetime_convert()),
2023                         dbesc($contact["location"]),
2024                         dbesc($contact["about"]),
2025                         intval($contact["hide"]),
2026                         intval($contact["generation"])
2027                 );
2028
2029                 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
2030                         dbesc(normalise_link($contact["url"])));
2031
2032                 if ($r) {
2033                         $gcontact_id = $r[0]["id"];
2034
2035                         $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
2036                 }
2037         }
2038
2039         if ($doprobing) {
2040                 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
2041                 proc_run(PRIORITY_LOW, 'include/gprobe.php', bin2hex($contact["url"]));
2042         }
2043
2044         if ((dbm::is_result($r)) AND (count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
2045          q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
2046                 dbesc(normalise_link($contact["url"])),
2047                 intval($gcontact_id));
2048
2049         return $gcontact_id;
2050 }
2051
2052 /**
2053  * @brief Updates the gcontact table from a given array
2054  *
2055  * @param arr $contact contact array
2056  * @return bool|int Returns false if not found, integer if contact was found
2057  */
2058 function update_gcontact($contact) {
2059
2060         // Check for invalid "contact-type" value
2061         if (isset($contact['contact-type']) AND (intval($contact['contact-type']) < 0)) {
2062                 $contact['contact-type'] = 0;
2063         }
2064
2065         /// @todo update contact table as well
2066
2067         $gcontact_id = get_gcontact_id($contact);
2068
2069         if (!$gcontact_id)
2070                 return false;
2071
2072         $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
2073                         `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
2074                 FROM `gcontact` WHERE `id` = %d LIMIT 1",
2075                 intval($gcontact_id));
2076
2077         // Get all field names
2078         $fields = array();
2079         foreach ($r[0] AS $field => $data)
2080                 $fields[$field] = $data;
2081
2082         unset($fields["url"]);
2083         unset($fields["updated"]);
2084         unset($fields["hide"]);
2085
2086         // Bugfix: We had an error in the storing of keywords which lead to the "0"
2087         // This value is still transmitted via poco.
2088         if ($contact["keywords"] == "0")
2089                 unset($contact["keywords"]);
2090
2091         if ($r[0]["keywords"] == "0")
2092                 $r[0]["keywords"] = "";
2093
2094         // assign all unassigned fields from the database entry
2095         foreach ($fields AS $field => $data)
2096                 if (!isset($contact[$field]) OR ($contact[$field] == ""))
2097                         $contact[$field] = $r[0][$field];
2098
2099         if (!isset($contact["hide"]))
2100                 $contact["hide"] = $r[0]["hide"];
2101
2102         $fields["hide"] = $r[0]["hide"];
2103
2104         if ($contact["network"] == NETWORK_STATUSNET)
2105                 $contact["network"] = NETWORK_OSTATUS;
2106
2107         // Replace alternate OStatus user format with the primary one
2108         fix_alternate_contact_address($contact);
2109
2110         if (!isset($contact["updated"]))
2111                 $contact["updated"] = dbm::date();
2112
2113         if ($contact["server_url"] == "") {
2114                 $server_url = $contact["url"];
2115
2116                 $server_url = matching_url($server_url, $contact["alias"]);
2117                 if ($server_url != "")
2118                         $contact["server_url"] = $server_url;
2119
2120                 $server_url = matching_url($server_url, $contact["photo"]);
2121                 if ($server_url != "")
2122                         $contact["server_url"] = $server_url;
2123
2124                 $server_url = matching_url($server_url, $contact["notify"]);
2125                 if ($server_url != "")
2126                         $contact["server_url"] = $server_url;
2127         } else
2128                 $contact["server_url"] = normalise_link($contact["server_url"]);
2129
2130         if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
2131                 $hostname = str_replace("http://", "", $contact["server_url"]);
2132                 $contact["addr"] = $contact["nick"]."@".$hostname;
2133         }
2134
2135         // Check if any field changed
2136         $update = false;
2137         unset($fields["generation"]);
2138
2139         if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
2140                 foreach ($fields AS $field => $data)
2141                         if ($contact[$field] != $r[0][$field]) {
2142                                 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
2143                                 $update = true;
2144                         }
2145
2146                 if ($contact["generation"] < $r[0]["generation"]) {
2147                         logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
2148                         $update = true;
2149                 }
2150         }
2151
2152         if ($update) {
2153                 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
2154
2155                 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
2156                                         `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
2157                                         `contact-type` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s',
2158                                         `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
2159                                         `server_url` = '%s', `connect` = '%s'
2160                                 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
2161                         dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
2162                         dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
2163                         dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
2164                         intval($contact["nsfw"]), intval($contact["contact-type"]), dbesc($contact["alias"]),
2165                         dbesc($contact["notify"]), dbesc($contact["url"]), dbesc($contact["location"]),
2166                         dbesc($contact["about"]), intval($contact["generation"]), dbesc(dbm::date($contact["updated"])),
2167                         dbesc($contact["server_url"]), dbesc($contact["connect"]),
2168                         dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
2169
2170
2171                 // Now update the contact entry with the user id "0" as well.
2172                 // This is used for the shadow copies of public items.
2173                 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
2174                         dbesc(normalise_link($contact["url"])));
2175
2176                 if ($r) {
2177                         logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
2178
2179                         update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
2180
2181                         q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
2182                                                 `network` = '%s', `bd` = '%s', `gender` = '%s',
2183                                                 `keywords` = '%s', `alias` = '%s', `contact-type` = %d,
2184                                                 `url` = '%s', `location` = '%s', `about` = '%s'
2185                                         WHERE `id` = %d",
2186                                 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
2187                                 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
2188                                 dbesc($contact["keywords"]), dbesc($contact["alias"]), intval($contact["contact-type"]),
2189                                 dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
2190                                 intval($r[0]["id"]));
2191                 }
2192         }
2193
2194         return $gcontact_id;
2195 }
2196
2197 /**
2198  * @brief Updates the gcontact entry from probe
2199  *
2200  * @param str $url profile link
2201  */
2202 function update_gcontact_from_probe($url) {
2203         $data = probe_url($url);
2204
2205         if (in_array($data["network"], array(NETWORK_PHANTOM))) {
2206                 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
2207                 return;
2208         }
2209
2210         $data["server_url"] = $data["baseurl"];
2211
2212         update_gcontact($data);
2213 }
2214
2215 /**
2216  * @brief Update the gcontact entry for a given user id
2217  *
2218  * @param int $uid User ID
2219  */
2220 function update_gcontact_for_user($uid) {
2221         $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
2222                         `profile`.`name`, `profile`.`about`, `profile`.`gender`,
2223                         `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
2224                         `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
2225                         `contact`.`notify`, `contact`.`url`, `contact`.`addr`
2226                 FROM `profile`
2227                         INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
2228                         INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
2229                 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
2230                 intval($uid));
2231
2232         $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
2233                                                 "country-name" => $r[0]["country-name"]));
2234
2235         // The "addr" field was added in 3.4.3 so it can be empty for older users
2236         if ($r[0]["addr"] != "")
2237                 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
2238         else
2239                 $addr = $r[0]["addr"];
2240
2241         $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
2242                         "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
2243                         "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
2244                         "notify" => $r[0]["notify"], "url" => $r[0]["url"],
2245                         "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
2246                         "nick" => $r[0]["nickname"], "addr" => $addr,
2247                         "connect" => $addr, "server_url" => App::get_baseurl(),
2248                         "generation" => 1, "network" => NETWORK_DFRN);
2249
2250         update_gcontact($gcontact);
2251 }
2252
2253 /**
2254  * @brief Fetches users of given GNU Social server
2255  *
2256  * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
2257  *
2258  * @param str $server Server address
2259  */
2260 function gs_fetch_users($server) {
2261
2262         logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
2263
2264         $url = $server."/main/statistics";
2265
2266         $result = z_fetch_url($url);
2267         if (!$result["success"])
2268                 return false;
2269
2270         $statistics = json_decode($result["body"]);
2271
2272         if (is_object($statistics->config)) {
2273                 if ($statistics->config->instance_with_ssl)
2274                         $server = "https://";
2275                 else
2276                         $server = "http://";
2277
2278                 $server .= $statistics->config->instance_address;
2279
2280                 $hostname = $statistics->config->instance_address;
2281         } else {
2282                 if ($statistics->instance_with_ssl)
2283                         $server = "https://";
2284                 else
2285                         $server = "http://";
2286
2287                 $server .= $statistics->instance_address;
2288
2289                 $hostname = $statistics->instance_address;
2290         }
2291
2292         if (is_object($statistics->users))
2293                 foreach ($statistics->users AS $nick => $user) {
2294                         $profile_url = $server."/".$user->nickname;
2295
2296                         $contact = array("url" => $profile_url,
2297                                         "name" => $user->fullname,
2298                                         "addr" => $user->nickname."@".$hostname,
2299                                         "nick" => $user->nickname,
2300                                         "about" => $user->bio,
2301                                         "network" => NETWORK_OSTATUS,
2302                                         "photo" => App::get_baseurl()."/images/person-175.jpg");
2303                         get_gcontact_id($contact);
2304                 }
2305 }
2306
2307 /**
2308  * @brief Asking GNU Social server on a regular base for their user data
2309  *
2310  */
2311 function gs_discover() {
2312
2313         $requery_days = intval(get_config("system", "poco_requery_days"));
2314
2315         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
2316
2317         $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",
2318                 dbesc(NETWORK_OSTATUS), dbesc($last_update));
2319
2320         if (!$r)
2321                 return;
2322
2323         foreach ($r AS $server) {
2324                 gs_fetch_users($server["url"]);
2325                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
2326         }
2327 }
2328
2329 /**
2330  * @brief Returns a list of all known servers
2331  * @return array List of server urls
2332  */
2333 function poco_serverlist() {
2334         $r = q("SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
2335                 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
2336                 ORDER BY `last_contact`
2337                 LIMIT 1000",
2338                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
2339         if (!dbm::is_result($r)) {
2340                 return false;
2341         }
2342         return $r;
2343 }