]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
Automatically refresh after two minutes when system is overloaded
[friendica.git] / include / socgraph.php
1 <?php
2 /**
3  * @file include/socgraph.php
4  * 
5  * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6  * @todo Fetch profile data from profile page for Redmatrix users
7  * @todo Detect if it is a forum
8  */
9
10 require_once('include/datetime.php');
11 require_once("include/Scrape.php");
12 require_once("include/html2bbcode.php");
13 require_once("include/Contact.php");
14 require_once("include/Photo.php");
15
16 /*
17  * poco_load
18  *
19  * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
20  * and add the entries to the gcontact (Global Contact) table, or update existing entries
21  * if anything (name or photo) has changed.
22  * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
23  *
24  * Once the global contact is stored add (if necessary) the contact linkage which associates
25  * the given uid, cid to the global contact entry. There can be many uid/cid combinations
26  * pointing to the same global contact id.
27  *
28  */
29
30
31
32
33 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
34
35         $a = get_app();
36
37         if($cid) {
38                 if((! $url) || (! $uid)) {
39                         $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
40                                 intval($cid)
41                         );
42                         if(count($r)) {
43                                 $url = $r[0]['poco'];
44                                 $uid = $r[0]['uid'];
45                         }
46                 }
47                 if(! $uid)
48                         return;
49         }
50
51         if(! $url)
52                 return;
53
54         $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation') ;
55
56         logger('poco_load: ' . $url, LOGGER_DEBUG);
57
58         $s = fetch_url($url);
59
60         logger('poco_load: returns ' . $s, LOGGER_DATA);
61
62         logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
63
64         if(($a->get_curl_code() > 299) || (! $s))
65                 return;
66
67         $j = json_decode($s);
68
69         logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
70
71         if(! isset($j->entry))
72                 return;
73
74         $total = 0;
75         foreach($j->entry as $entry) {
76
77                 $total ++;
78                 $profile_url = '';
79                 $profile_photo = '';
80                 $connect_url = '';
81                 $name = '';
82                 $network = '';
83                 $updated = '0000-00-00 00:00:00';
84                 $location = '';
85                 $about = '';
86                 $keywords = '';
87                 $gender = '';
88                 $generation = 0;
89
90                 $name = $entry->displayName;
91
92                 if(isset($entry->urls)) {
93                         foreach($entry->urls as $url) {
94                                 if($url->type == 'profile') {
95                                         $profile_url = $url->value;
96                                         continue;
97                                 }
98                                 if($url->type == 'webfinger') {
99                                         $connect_url = str_replace('acct:' , '', $url->value);
100                                         continue;
101                                 }
102                         }
103                 }
104                 if(isset($entry->photos)) {
105                         foreach($entry->photos as $photo) {
106                                 if($photo->type == 'profile') {
107                                         $profile_photo = $photo->value;
108                                         continue;
109                                 }
110                         }
111                 }
112
113                 if(isset($entry->updated))
114                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
115
116                 if(isset($entry->network))
117                         $network = $entry->network;
118
119                 if(isset($entry->currentLocation))
120                         $location = $entry->currentLocation;
121
122                 if(isset($entry->aboutMe))
123                         $about = html2bbcode($entry->aboutMe);
124
125                 if(isset($entry->gender))
126                         $gender = $entry->gender;
127
128                 if(isset($entry->generation) AND ($entry->generation > 0))
129                         $generation = ++$entry->generation;
130
131                 if(isset($entry->tags))
132                         foreach($entry->tags as $tag)
133                                 $keywords = implode(", ", $tag);
134
135                 // If you query a Friendica server for its profiles, the network has to be Friendica
136                 /// TODO It could also be a Redmatrix server
137                 //if ($uid == 0)
138                 //      $network = NETWORK_DFRN;
139
140                 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
141
142                 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
143                 // Deactivated because we now update Friendica contacts in dfrn.php
144                 //if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
145                 //      q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
146                 //              WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
147                 //              dbesc($location),
148                 //              dbesc($about),
149                 //              dbesc($keywords),
150                 //              dbesc($gender),
151                 //              dbesc(normalise_link($profile_url)),
152                 //              dbesc(NETWORK_DFRN));
153         }
154         logger("poco_load: loaded $total entries",LOGGER_DEBUG);
155
156         q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
157                 intval($cid),
158                 intval($uid),
159                 intval($zcid)
160         );
161
162 }
163
164 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
165
166         $a = get_app();
167
168         // Generation:
169         //  0: No definition
170         //  1: Profiles on this server
171         //  2: Contacts of profiles on this server
172         //  3: Contacts of contacts of profiles on this server
173         //  4: ...
174
175         $gcid = "";
176
177         if ($profile_url == "")
178                 return $gcid;
179
180         $urlparts = parse_url($profile_url);
181         if (!isset($urlparts["scheme"]))
182                 return $gcid;
183
184         if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
185                                                 "identi.ca", "alpha.app.net")))
186                 return $gcid;
187
188         // Don't store the statusnet connector as network
189         // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
190         if ($network == NETWORK_STATUSNET)
191                 $network = "";
192
193         // Assure that there are no parameter fragments in the profile url
194         if (in_array($network, array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
195                 $profile_url = clean_contact_url($profile_url);
196
197         $alternate = poco_alternate_ostatus_url($profile_url);
198
199         $orig_updated = $updated;
200
201         // The global contacts should contain the original picture, not the cached one
202         if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link($a->get_baseurl()."/photo/")))
203                 $profile_photo = "";
204
205         $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
206                 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
207         );
208         if(count($r))
209                 $network = $r[0]["network"];
210
211         if (($network == "") OR ($network == NETWORK_OSTATUS)) {
212                 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
213                         dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
214                 );
215                 if(count($r)) {
216                         $network = $r[0]["network"];
217                         //$profile_url = $r[0]["url"];
218                 }
219         }
220
221         $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
222                 dbesc(normalise_link($profile_url))
223         );
224
225         if (count($x)) {
226                 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
227                         $network = $x[0]["network"];
228
229                 if ($updated == "0000-00-00 00:00:00")
230                         $updated = $x[0]["updated"];
231
232                 $created = $x[0]["created"];
233                 $server_url = $x[0]["server_url"];
234                 $nick = $x[0]["nick"];
235                 $addr = $x[0]["addr"];
236                 $alias =  $x[0]["alias"];
237                 $notify =  $x[0]["notify"];
238         } else {
239                 $created = "0000-00-00 00:00:00";
240                 $server_url = "";
241
242                 $urlparts = parse_url($profile_url);
243                 $nick = end(explode("/", $urlparts["path"]));
244                 $addr = "";
245                 $alias = "";
246                 $notify = "";
247         }
248
249         if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
250                 AND poco_reachable($profile_url, $server_url, $network, false)) {
251                 $data = probe_url($profile_url);
252
253                 $orig_profile = $profile_url;
254
255                 $network = $data["network"];
256                 $name = $data["name"];
257                 $nick = $data["nick"];
258                 $addr = $data["addr"];
259                 $alias = $data["alias"];
260                 $notify = $data["notify"];
261                 $profile_url = $data["url"];
262                 $profile_photo = $data["photo"];
263                 $server_url = $data["baseurl"];
264
265                 if ($alternate AND ($network == NETWORK_OSTATUS)) {
266                         // Delete the old entry - if it exists
267                         $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
268                         if ($r) {
269                                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
270                                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
271                         }
272
273                         // possibly create a new entry
274                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
275                 }
276         }
277
278         if ($alternate AND ($network == NETWORK_OSTATUS))
279                 return $gcid;
280
281         if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
282                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
283                         dbesc($network),
284                         dbesc(normalise_link($profile_url))
285                 );
286         }
287
288         if (($name == "") OR ($profile_photo == ""))
289                 return $gcid;
290
291         if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
292                 return $gcid;
293
294         logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
295
296         poco_check_server($server_url, $network);
297
298         $gcontact = array("url" => $profile_url,
299                         "addr" => $addr,
300                         "alias" => $alias,
301                         "name" => $name,
302                         "network" => $network,
303                         "photo" => $profile_photo,
304                         "about" => $about,
305                         "location" => $location,
306                         "gender" => $gender,
307                         "keywords" => $keywords,
308                         "server_url" => $server_url,
309                         "connect" => $connect_url,
310                         "notify" => $notify,
311                         "updated" => $updated,
312                         "generation" => $generation);
313
314         $gcid = update_gcontact($gcontact);
315
316         if(!$gcid)
317                 return $gcid;
318
319         $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
320                 intval($cid),
321                 intval($uid),
322                 intval($gcid),
323                 intval($zcid)
324         );
325         if(! count($r)) {
326                 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
327                         intval($cid),
328                         intval($uid),
329                         intval($gcid),
330                         intval($zcid),
331                         dbesc(datetime_convert())
332                 );
333         } else {
334                 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
335                         dbesc(datetime_convert()),
336                         intval($cid),
337                         intval($uid),
338                         intval($gcid),
339                         intval($zcid)
340                 );
341         }
342
343         return $gcid;
344 }
345
346 function poco_reachable($profile, $server = "", $network = "", $force = false) {
347
348         if ($server == "")
349                 $server = poco_detect_server($profile);
350
351         if ($server == "")
352                 return true;
353
354         return poco_check_server($server, $network, $force);
355 }
356
357 function poco_detect_server($profile) {
358
359         // Try to detect the server path based upon some known standard paths
360         $server_url = "";
361
362         if ($server_url == "") {
363                 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
364                 if ($friendica != $profile) {
365                         $server_url = $friendica;
366                         $network = NETWORK_DFRN;
367                 }
368         }
369
370         if ($server_url == "") {
371                 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
372                 if ($diaspora != $profile) {
373                         $server_url = $diaspora;
374                         $network = NETWORK_DIASPORA;
375                 }
376         }
377
378         if ($server_url == "") {
379                 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
380                 if ($red != $profile) {
381                         $server_url = $red;
382                         $network = NETWORK_DIASPORA;
383                 }
384         }
385
386         return $server_url;
387 }
388
389 function poco_alternate_ostatus_url($url) {
390         return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
391 }
392
393 function poco_last_updated($profile, $force = false) {
394
395         $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
396                         dbesc(normalise_link($profile)));
397
398         if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
399                 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
400                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
401
402         if ($gcontacts[0]["server_url"] != "")
403                 $server_url = $gcontacts[0]["server_url"];
404         else
405                 $server_url = poco_detect_server($profile);
406
407         if (!in_array($gcontacts[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_FEED, NETWORK_OSTATUS, ""))) {
408                 logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
409                 return false;
410         }
411
412         if ($server_url != "") {
413                 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
414
415                         if ($force)
416                                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
417                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
418
419                         logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG);
420                         return false;
421                 }
422
423                 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
424                         dbesc($server_url), dbesc(normalise_link($profile)));
425         }
426
427         if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
428                 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
429                         dbesc(normalise_link($server_url)));
430
431                 if ($server)
432                         q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
433                                 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
434                 else
435                         return false;
436         }
437
438         // noscrape is really fast so we don't cache the call.
439         if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
440
441                 //  Use noscrape if possible
442                 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
443
444                 if ($server) {
445                         $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
446
447                          if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
448
449                                 $noscrape = json_decode($noscraperet["body"], true);
450
451                                 if (is_array($noscrape)) {
452                                         $contact = array("url" => $profile,
453                                                         "network" => $server[0]["network"],
454                                                         "generation" => $gcontacts[0]["generation"]);
455
456                                         if (isset($noscrape["fn"]))
457                                                 $contact["name"] = $noscrape["fn"];
458
459                                         if (isset($noscrape["comm"]))
460                                                 $contact["community"] = $noscrape["comm"];
461
462                                         if (isset($noscrape["tags"])) {
463                                                 $keywords = implode(" ", $noscrape["tags"]);
464                                                 if ($keywords != "")
465                                                         $contact["keywords"] = $keywords;
466                                         }
467
468                                         $location = formatted_location($noscrape);
469                                         if ($location)
470                                                 $contact["location"] = $location;
471
472                                         if (isset($noscrape["dfrn-notify"]))
473                                                 $contact["notify"] = $noscrape["dfrn-notify"];
474
475                                         // Remove all fields that are not present in the gcontact table
476                                         unset($noscrape["fn"]);
477                                         unset($noscrape["key"]);
478                                         unset($noscrape["homepage"]);
479                                         unset($noscrape["comm"]);
480                                         unset($noscrape["tags"]);
481                                         unset($noscrape["locality"]);
482                                         unset($noscrape["region"]);
483                                         unset($noscrape["country-name"]);
484                                         unset($noscrape["contacts"]);
485                                         unset($noscrape["dfrn-request"]);
486                                         unset($noscrape["dfrn-confirm"]);
487                                         unset($noscrape["dfrn-notify"]);
488                                         unset($noscrape["dfrn-poll"]);
489
490                                         // Set the date of the last contact
491                                         /// @todo By now the function "update_gcontact" doesn't work with this field
492                                         //$contact["last_contact"] = datetime_convert();
493
494                                         $contact = array_merge($contact, $noscrape);
495
496                                         update_gcontact($contact);
497
498                                         if (trim($noscrape["updated"]) != "") {
499                                                 q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
500                                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
501
502                                                 logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG);
503
504                                                 return $noscrape["updated"];
505                                         }
506                                 }
507                         }
508                 }
509         }
510
511         // If we only can poll the feed, then we only do this once a while
512         if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"],  $gcontacts[0]["last_contact"])) {
513                 logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG);
514                 return $gcontacts[0]["updated"];
515         }
516
517         $data = probe_url($profile);
518
519         // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
520         // Then check the other link and delete this one
521         if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
522                 (normalise_link($profile) == normalise_link($data["alias"])) AND
523                 (normalise_link($profile) != normalise_link($data["url"]))) {
524
525                 // Delete the old entry
526                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
527                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
528
529                 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
530                                 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
531
532                 poco_last_updated($data["url"], $force);
533
534                 logger("Profile ".$profile." was deleted", LOGGER_DEBUG);
535                 return false;
536         }
537
538         if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
539                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
540                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
541
542                 logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG);
543                 return false;
544         }
545
546         $contact = array("generation" => $gcontacts[0]["generation"]);
547
548         $contact = array_merge($contact, $data);
549
550         $contact["server_url"] = $data["baseurl"];
551
552         unset($contact["batch"]);
553         unset($contact["poll"]);
554         unset($contact["request"]);
555         unset($contact["confirm"]);
556         unset($contact["poco"]);
557         unset($contact["priority"]);
558         unset($contact["pubkey"]);
559         unset($contact["baseurl"]);
560
561         update_gcontact($contact);
562
563         $feedret = z_fetch_url($data["poll"]);
564
565         if (!$feedret["success"]) {
566                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
567                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
568
569                 logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG);
570                 return false;
571         }
572
573         $doc = new DOMDocument();
574         @$doc->loadXML($feedret["body"]);
575
576         $xpath = new DomXPath($doc);
577         $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
578
579         $entries = $xpath->query('/atom:feed/atom:entry');
580
581         $last_updated = "";
582
583         foreach ($entries AS $entry) {
584                 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
585                 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
586
587                 if ($last_updated < $published)
588                         $last_updated = $published;
589
590                 if ($last_updated < $updated)
591                         $last_updated = $updated;
592         }
593
594         // Maybe there aren't any entries. Then check if it is a valid feed
595         if ($last_updated == "")
596                 if ($xpath->query('/atom:feed')->length > 0)
597                         $last_updated = "0000-00-00 00:00:00";
598
599         q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
600                 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
601
602         if (($gcontacts[0]["generation"] == 0))
603                 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
604                         dbesc(normalise_link($profile)));
605
606         logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG);
607
608         return($last_updated);
609 }
610
611 function poco_do_update($created, $updated, $last_failure,  $last_contact) {
612         $now = strtotime(datetime_convert());
613
614         if ($updated > $last_contact)
615                 $contact_time = strtotime($updated);
616         else
617                 $contact_time = strtotime($last_contact);
618
619         $failure_time = strtotime($last_failure);
620         $created_time = strtotime($created);
621
622         // If there is no "created" time then use the current time
623         if ($created_time <= 0)
624                 $created_time = $now;
625
626         // If the last contact was less than 24 hours then don't update
627         if (($now - $contact_time) < (60 * 60 * 24))
628                 return false;
629
630         // If the last failure was less than 24 hours then don't update
631         if (($now - $failure_time) < (60 * 60 * 24))
632                 return false;
633
634         // If the last contact was less than a week ago and the last failure is older than a week then don't update
635         //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
636         //      return false;
637
638         // 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
639         if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
640                 return false;
641
642         // 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
643         if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
644                 return false;
645
646         return true;
647 }
648
649 function poco_to_boolean($val) {
650         if (($val == "true") OR ($val == 1))
651                 return(true);
652         if (($val == "false") OR ($val == 0))
653                 return(false);
654
655         return ($val);
656 }
657
658 function poco_check_server($server_url, $network = "", $force = false) {
659
660         // Unify the server address
661         $server_url = trim($server_url, "/");
662         $server_url = str_replace("/index.php", "", $server_url);
663
664         if ($server_url == "")
665                 return false;
666
667         $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
668         if ($servers) {
669
670                 if ($servers[0]["created"] == "0000-00-00 00:00:00")
671                         q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
672                                 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
673
674                 $poco = $servers[0]["poco"];
675                 $noscrape = $servers[0]["noscrape"];
676
677                 if ($network == "")
678                         $network = $servers[0]["network"];
679
680                 $last_contact = $servers[0]["last_contact"];
681                 $last_failure = $servers[0]["last_failure"];
682                 $version = $servers[0]["version"];
683                 $platform = $servers[0]["platform"];
684                 $site_name = $servers[0]["site_name"];
685                 $info = $servers[0]["info"];
686                 $register_policy = $servers[0]["register_policy"];
687
688                 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
689                         logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
690                         return ($last_contact >= $last_failure);
691                 }
692         } else {
693                 $poco = "";
694                 $noscrape = "";
695                 $version = "";
696                 $platform = "";
697                 $site_name = "";
698                 $info = "";
699                 $register_policy = -1;
700
701                 $last_contact = "0000-00-00 00:00:00";
702                 $last_failure = "0000-00-00 00:00:00";
703         }
704         logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
705
706         $failure = false;
707         $orig_last_failure = $last_failure;
708
709         // Check if the page is accessible via SSL.
710         $server_url = str_replace("http://", "https://", $server_url);
711         $serverret = z_fetch_url($server_url."/.well-known/host-meta");
712
713         // Maybe the page is unencrypted only?
714         $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
715         if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
716                 $server_url = str_replace("https://", "http://", $server_url);
717                 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
718
719                 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
720         }
721
722         if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
723                 // Workaround for bad configured servers (known nginx problem)
724                 if ($serverret["debug"]["http_code"] != "403") {
725                         $last_failure = datetime_convert();
726                         $failure = true;
727                 }
728         } elseif ($network == NETWORK_DIASPORA)
729                 $last_contact = datetime_convert();
730
731         if (!$failure) {
732                 // Test for Diaspora
733                 $serverret = z_fetch_url($server_url);
734
735                 if (!$serverret["success"] OR ($serverret["body"] == ""))
736                         $failure = true;
737                 else {
738                         $lines = explode("\n",$serverret["header"]);
739                         if(count($lines))
740                                 foreach($lines as $line) {
741                                         $line = trim($line);
742                                         if(stristr($line,'X-Diaspora-Version:')) {
743                                                 $platform = "Diaspora";
744                                                 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
745                                                 $version = trim(str_replace("x-diaspora-version:", "", $version));
746                                                 $network = NETWORK_DIASPORA;
747                                                 $versionparts = explode("-", $version);
748                                                 $version = $versionparts[0];
749                                         }
750                                 }
751                 }
752         }
753
754         if (!$failure) {
755                 // Test for Statusnet
756                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
757                 // The "not implemented" is a special treatment for really, really old Friendica versions
758                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
759                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
760                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
761                         $platform = "StatusNet";
762                         $version = trim($serverret["body"], '"');
763                         $network = NETWORK_OSTATUS;
764                 }
765
766                 // Test for GNU Social
767                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
768                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
769                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
770                         $platform = "GNU Social";
771                         $version = trim($serverret["body"], '"');
772                         $network = NETWORK_OSTATUS;
773                 }
774
775                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
776                 if ($serverret["success"]) {
777                         $data = json_decode($serverret["body"]);
778
779                         if (isset($data->site->server)) {
780                                 $last_contact = datetime_convert();
781
782                                 if (isset($data->site->hubzilla)) {
783                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
784                                         $version = $data->site->hubzilla->RED_VERSION;
785                                         $network = NETWORK_DIASPORA;
786                                 }
787                                 if (isset($data->site->redmatrix)) {
788                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
789                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
790                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
791                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
792
793                                         $version = $data->site->redmatrix->RED_VERSION;
794                                         $network = NETWORK_DIASPORA;
795                                 }
796                                 if (isset($data->site->friendica)) {
797                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
798                                         $version = $data->site->friendica->FRIENDICA_VERSION;
799                                         $network = NETWORK_DFRN;
800                                 }
801
802                                 $site_name = $data->site->name;
803
804                                 $data->site->closed = poco_to_boolean($data->site->closed);
805                                 $data->site->private = poco_to_boolean($data->site->private);
806                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
807
808                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
809                                         $register_policy = REGISTER_APPROVE;
810                                 elseif (!$data->site->closed AND !$data->site->private)
811                                         $register_policy = REGISTER_OPEN;
812                                 else
813                                         $register_policy = REGISTER_CLOSED;
814                         }
815                 }
816         }
817
818         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
819         if (!$failure) {
820                 $serverret = z_fetch_url($server_url."/statistics.json");
821                 if ($serverret["success"]) {
822                         $data = json_decode($serverret["body"]);
823                         if ($version == "")
824                                 $version = $data->version;
825
826                         $site_name = $data->name;
827
828                         if (isset($data->network) AND ($platform == ""))
829                                 $platform = $data->network;
830
831                         if ($platform == "Diaspora")
832                                 $network = NETWORK_DIASPORA;
833
834                         if ($data->registrations_open)
835                                 $register_policy = REGISTER_OPEN;
836                         else
837                                 $register_policy = REGISTER_CLOSED;
838
839                         if (isset($data->version))
840                                 $last_contact = datetime_convert();
841                 }
842         }
843
844         // Check for noscrape
845         // Friendica servers could be detected as OStatus servers
846         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
847                 $serverret = z_fetch_url($server_url."/friendica/json");
848
849                 if (!$serverret["success"])
850                         $serverret = z_fetch_url($server_url."/friendika/json");
851
852                 if ($serverret["success"]) {
853                         $data = json_decode($serverret["body"]);
854
855                         if (isset($data->version)) {
856                                 $last_contact = datetime_convert();
857                                 $network = NETWORK_DFRN;
858
859                                 $noscrape = $data->no_scrape_url;
860                                 $version = $data->version;
861                                 $site_name = $data->site_name;
862                                 $info = $data->info;
863                                 $register_policy_str = $data->register_policy;
864                                 $platform = $data->platform;
865
866                                 switch ($register_policy_str) {
867                                         case "REGISTER_CLOSED":
868                                                 $register_policy = REGISTER_CLOSED;
869                                                 break;
870                                         case "REGISTER_APPROVE":
871                                                 $register_policy = REGISTER_APPROVE;
872                                                 break;
873                                         case "REGISTER_OPEN":
874                                                 $register_policy = REGISTER_OPEN;
875                                                 break;
876                                 }
877                         }
878                 }
879         }
880
881         // Look for poco
882         if (!$failure) {
883                 $serverret = z_fetch_url($server_url."/poco");
884                 if ($serverret["success"]) {
885                         $data = json_decode($serverret["body"]);
886                         if (isset($data->totalResults)) {
887                                 $poco = $server_url."/poco";
888                                 $last_contact = datetime_convert();
889                         }
890                 }
891         }
892
893         // Check again if the server exists
894         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
895
896         $version = strip_tags($version);
897         $site_name = strip_tags($site_name);
898         $info = strip_tags($info);
899         $platform = strip_tags($platform);
900
901         if ($servers)
902                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
903                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
904                         dbesc($server_url),
905                         dbesc($version),
906                         dbesc($site_name),
907                         dbesc($info),
908                         intval($register_policy),
909                         dbesc($poco),
910                         dbesc($noscrape),
911                         dbesc($network),
912                         dbesc($platform),
913                         dbesc($last_contact),
914                         dbesc($last_failure),
915                         dbesc(normalise_link($server_url))
916                 );
917         else
918                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
919                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
920                                 dbesc($server_url),
921                                 dbesc(normalise_link($server_url)),
922                                 dbesc($version),
923                                 dbesc($site_name),
924                                 dbesc($info),
925                                 intval($register_policy),
926                                 dbesc($poco),
927                                 dbesc($noscrape),
928                                 dbesc($network),
929                                 dbesc($platform),
930                                 dbesc(datetime_convert()),
931                                 dbesc($last_contact),
932                                 dbesc($last_failure),
933                                 dbesc(datetime_convert())
934                 );
935
936         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
937
938         return !$failure;
939 }
940
941 function count_common_friends($uid,$cid) {
942
943         $r = q("SELECT count(*) as `total`
944                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
945                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
946                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
947                 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
948                 intval($cid),
949                 intval($uid),
950                 intval($uid),
951                 intval($cid)
952         );
953
954 //      logger("count_common_friends: $uid $cid {$r[0]['total']}");
955         if(count($r))
956                 return $r[0]['total'];
957         return 0;
958
959 }
960
961
962 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
963
964         if($shuffle)
965                 $sql_extra = " order by rand() ";
966         else
967                 $sql_extra = " order by `gcontact`.`name` asc ";
968
969         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
970                 FROM `glink`
971                 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
972                 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
973                 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
974                         AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
975                         AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
976                         AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
977                         $sql_extra LIMIT %d, %d",
978                 intval($cid),
979                 intval($uid),
980                 intval($uid),
981                 intval($cid),
982                 intval($start),
983                 intval($limit)
984         );
985
986         return $r;
987
988 }
989
990
991 function count_common_friends_zcid($uid,$zcid) {
992
993         $r = q("SELECT count(*) as `total`
994                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
995                 where `glink`.`zcid` = %d
996                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
997                 intval($zcid),
998                 intval($uid)
999         );
1000
1001         if(count($r))
1002                 return $r[0]['total'];
1003         return 0;
1004
1005 }
1006
1007 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1008
1009         if($shuffle)
1010                 $sql_extra = " order by rand() ";
1011         else
1012                 $sql_extra = " order by `gcontact`.`name` asc ";
1013
1014         $r = q("SELECT `gcontact`.*
1015                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1016                 where `glink`.`zcid` = %d
1017                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) 
1018                 $sql_extra limit %d, %d",
1019                 intval($zcid),
1020                 intval($uid),
1021                 intval($start),
1022                 intval($limit)
1023         );
1024
1025         return $r;
1026
1027 }
1028
1029
1030 function count_all_friends($uid,$cid) {
1031
1032         $r = q("SELECT count(*) as `total`
1033                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1034                 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1035                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1036                 intval($cid),
1037                 intval($uid)
1038         );
1039
1040         if(count($r))
1041                 return $r[0]['total'];
1042         return 0;
1043
1044 }
1045
1046
1047 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1048
1049         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1050                 FROM `glink`
1051                 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1052                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1053                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1054                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1055                 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1056                 intval($uid),
1057                 intval($cid),
1058                 intval($uid),
1059                 intval($start),
1060                 intval($limit)
1061         );
1062
1063         return $r;
1064 }
1065
1066
1067
1068 function suggestion_query($uid, $start = 0, $limit = 80) {
1069
1070         if(! $uid)
1071                 return array();
1072
1073         $network = array(NETWORK_DFRN);
1074
1075         if (get_config('system','diaspora_enabled'))
1076                 $network[] = NETWORK_DIASPORA;
1077
1078         if (!get_config('system','ostatus_disabled'))
1079                 $network[] = NETWORK_OSTATUS;
1080
1081         $sql_network = implode("', '", $network);
1082         //$sql_network = "'".$sql_network."', ''";
1083         $sql_network = "'".$sql_network."'";
1084
1085         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1086                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1087                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1088                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1089                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1090                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1091                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1092                 AND `gcontact`.`network` IN (%s)
1093                 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1094                 intval($uid),
1095                 intval($uid),
1096                 intval($uid),
1097                 intval($uid),
1098                 $sql_network,
1099                 intval($start),
1100                 intval($limit)
1101         );
1102
1103         if(count($r) && count($r) >= ($limit -1))
1104                 return $r;
1105
1106         $r2 = q("SELECT gcontact.* FROM gcontact
1107                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1108                 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1109                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1110                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1111                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1112                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1113                 AND `gcontact`.`network` IN (%s)
1114                 ORDER BY rand() LIMIT %d, %d",
1115                 intval($uid),
1116                 intval($uid),
1117                 intval($uid),
1118                 $sql_network,
1119                 intval($start),
1120                 intval($limit)
1121         );
1122
1123         $list = array();
1124         foreach ($r2 AS $suggestion)
1125                 $list[$suggestion["nurl"]] = $suggestion;
1126
1127         foreach ($r AS $suggestion)
1128                 $list[$suggestion["nurl"]] = $suggestion;
1129
1130         while (sizeof($list) > ($limit))
1131                 array_pop($list);
1132
1133         return $list;
1134 }
1135
1136 function update_suggestions() {
1137
1138         $a = get_app();
1139
1140         $done = array();
1141
1142         /// TODO Check if it is really neccessary to poll the own server
1143         poco_load(0,0,0,$a->get_baseurl() . '/poco');
1144
1145         $done[] = $a->get_baseurl() . '/poco';
1146
1147         if(strlen(get_config('system','directory'))) {
1148                 $x = fetch_url(get_server()."/pubsites");
1149                 if($x) {
1150                         $j = json_decode($x);
1151                         if($j->entries) {
1152                                 foreach($j->entries as $entry) {
1153
1154                                         poco_check_server($entry->url);
1155
1156                                         $url = $entry->url . '/poco';
1157                                         if(! in_array($url,$done))
1158                                                 poco_load(0,0,0,$entry->url . '/poco');
1159                                 }
1160                         }
1161                 }
1162         }
1163
1164         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1165         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1166                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1167         );
1168
1169         if(count($r)) {
1170                 foreach($r as $rr) {
1171                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1172                         if(! in_array($base,$done))
1173                                 poco_load(0,0,0,$base);
1174                 }
1175         }
1176 }
1177
1178 function poco_discover_federation() {
1179         $last = get_config('poco','last_federation_discovery');
1180
1181         if($last) {
1182                 $next = $last + (24 * 60 * 60);
1183                 if($next > time())
1184                         return;
1185         }
1186
1187         // Discover Friendica, Hubzilla and Diaspora servers
1188         $serverdata = fetch_url("http://the-federation.info/pods.json");
1189
1190         if ($serverdata) {
1191                 $servers = json_decode($serverdata);
1192
1193                 foreach($servers->pods AS $server)
1194                         poco_check_server("https://".$server->host);
1195         }
1196
1197         // Discover GNU Social Servers
1198         if (!get_config('system','ostatus_disabled')) {
1199                 $serverdata = "http://gstools.org/api/get_open_instances/";
1200
1201                 $result = z_fetch_url($serverdata);
1202                 if ($result["success"]) {
1203                         $servers = json_decode($result["body"]);
1204
1205                         foreach($servers->data AS $server)
1206                                 poco_check_server($server->instance_address);
1207                 }
1208         }
1209
1210         set_config('poco','last_federation_discovery', time());
1211 }
1212
1213 function poco_discover($complete = false) {
1214
1215         // Update the server list
1216         poco_discover_federation();
1217
1218         $no_of_queries = 5;
1219
1220         $requery_days = intval(get_config("system", "poco_requery_days"));
1221
1222         if ($requery_days == 0)
1223                 $requery_days = 7;
1224
1225         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1226
1227         $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `poco` != '' AND `last_poco_query` < '%s' ORDER BY RAND()", dbesc($last_update));
1228         if ($r)
1229                 foreach ($r AS $server) {
1230
1231                         if (!poco_check_server($server["url"], $server["network"])) {
1232                                 // The server is not reachable? Okay, then we will try it later
1233                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1234                                 continue;
1235                         }
1236
1237                         // Fetch all users from the other server
1238                         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1239
1240                         logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1241
1242                         $retdata = z_fetch_url($url);
1243                         if ($retdata["success"]) {
1244                                 $data = json_decode($retdata["body"]);
1245
1246                                 poco_discover_server($data, 2);
1247
1248                                 if (get_config('system','poco_discovery') > 1) {
1249
1250                                         $timeframe = get_config('system','poco_discovery_since');
1251                                         if ($timeframe == 0)
1252                                                 $timeframe = 30;
1253
1254                                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1255
1256                                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1257                                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1258
1259                                         $success = false;
1260
1261                                         $retdata = z_fetch_url($url);
1262                                         if ($retdata["success"]) {
1263                                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1264                                                 $success = poco_discover_server(json_decode($retdata["body"]));
1265                                         }
1266
1267                                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1268                                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1269                                                 poco_discover_server_users($data, $server);
1270                                         }
1271                                 }
1272
1273                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1274                                 if (!$complete AND (--$no_of_queries == 0))
1275                                         break;
1276                         } else {
1277                                 // If the server hadn't replied correctly, then force a sanity check
1278                                 poco_check_server($server["url"], $server["network"], true);
1279
1280                                 // If we couldn't reach the server, we will try it some time later
1281                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1282                         }
1283                 }
1284 }
1285
1286 function poco_discover_server_users($data, $server) {
1287
1288         if (!isset($data->entry))
1289                 return;
1290
1291         foreach ($data->entry AS $entry) {
1292                 $username = "";
1293                 if (isset($entry->urls)) {
1294                         foreach($entry->urls as $url)
1295                                 if($url->type == 'profile') {
1296                                         $profile_url = $url->value;
1297                                         $urlparts = parse_url($profile_url);
1298                                         $username = end(explode("/", $urlparts["path"]));
1299                                 }
1300                 }
1301                 if ($username != "") {
1302                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1303
1304                         // Fetch all contacts from a given user from the other server
1305                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1306
1307                         $retdata = z_fetch_url($url);
1308                         if ($retdata["success"])
1309                                 poco_discover_server(json_decode($retdata["body"]), 3);
1310                 }
1311         }
1312 }
1313
1314 function poco_discover_server($data, $default_generation = 0) {
1315
1316         if (!isset($data->entry) OR !count($data->entry))
1317                 return false;
1318
1319         $success = false;
1320
1321         foreach ($data->entry AS $entry) {
1322                 $profile_url = '';
1323                 $profile_photo = '';
1324                 $connect_url = '';
1325                 $name = '';
1326                 $network = '';
1327                 $updated = '0000-00-00 00:00:00';
1328                 $location = '';
1329                 $about = '';
1330                 $keywords = '';
1331                 $gender = '';
1332                 $generation = $default_generation;
1333
1334                 $name = $entry->displayName;
1335
1336                 if(isset($entry->urls)) {
1337                         foreach($entry->urls as $url) {
1338                                 if($url->type == 'profile') {
1339                                         $profile_url = $url->value;
1340                                         continue;
1341                                 }
1342                                 if($url->type == 'webfinger') {
1343                                         $connect_url = str_replace('acct:' , '', $url->value);
1344                                         continue;
1345                                 }
1346                         }
1347                 }
1348
1349                 if(isset($entry->photos)) {
1350                         foreach($entry->photos as $photo) {
1351                                 if($photo->type == 'profile') {
1352                                         $profile_photo = $photo->value;
1353                                         continue;
1354                                 }
1355                         }
1356                 }
1357
1358                 if(isset($entry->updated))
1359                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1360
1361                 if(isset($entry->network))
1362                         $network = $entry->network;
1363
1364                 if(isset($entry->currentLocation))
1365                         $location = $entry->currentLocation;
1366
1367                 if(isset($entry->aboutMe))
1368                         $about = html2bbcode($entry->aboutMe);
1369
1370                 if(isset($entry->gender))
1371                         $gender = $entry->gender;
1372
1373                 if(isset($entry->generation) AND ($entry->generation > 0))
1374                         $generation = ++$entry->generation;
1375
1376                 if(isset($entry->tags))
1377                         foreach($entry->tags as $tag)
1378                                 $keywords = implode(", ", $tag);
1379
1380                 if ($generation > 0) {
1381                         $success = true;
1382
1383                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1384                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1385                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1386                 }
1387         }
1388         return $success;
1389 }
1390
1391 /**
1392  * @brief Removes unwanted parts from a contact url
1393  *
1394  * @param string $url Contact url
1395  * @return string Contact url with the wanted parts
1396  */
1397 function clean_contact_url($url) {
1398         $parts = parse_url($url);
1399
1400         if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1401                 return $url;
1402
1403         $new_url = $parts["scheme"]."://".$parts["host"];
1404
1405         if (isset($parts["port"]))
1406                 $new_url .= ":".$parts["port"];
1407
1408         if (isset($parts["path"]))
1409                 $new_url .= $parts["path"];
1410
1411         if ($new_url != $url)
1412                 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".App::callstack(), LOGGER_DEBUG);
1413
1414         return $new_url;
1415 }
1416
1417 /**
1418  * @brief Replace alternate OStatus user format with the primary one
1419  *
1420  * @param arr $contact contact array (called by reference)
1421  */
1422 function fix_alternate_contact_address(&$contact) {
1423         if (($contact["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($contact["url"])) {
1424                 $data = probe_url($contact["url"]);
1425                 if ($contact["network"] == NETWORK_OSTATUS) {
1426                         logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1427                         $contact["url"] = $data["url"];
1428                         $contact["addr"] = $data["addr"];
1429                         $contact["alias"] = $data["alias"];
1430                         $contact["server_url"] = $data["baseurl"];
1431                 }
1432         }
1433 }
1434
1435 /**
1436  * @brief Fetch the gcontact id, add an entry if not existed
1437  *
1438  * @param arr $contact contact array
1439  * @return bool|int Returns false if not found, integer if contact was found
1440  */
1441 function get_gcontact_id($contact) {
1442
1443         $gcontact_id = 0;
1444         $doprobing = false;
1445
1446         if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
1447                 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1448                 return false;
1449         }
1450
1451         if ($contact["network"] == NETWORK_STATUSNET)
1452                 $contact["network"] = NETWORK_OSTATUS;
1453
1454         // All new contacts are hidden by default
1455         if (!isset($contact["hide"]))
1456                 $contact["hide"] = true;
1457
1458         // Replace alternate OStatus user format with the primary one
1459         fix_alternate_contact_address($contact);
1460
1461         // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1462         if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
1463                 $contact["url"] = clean_contact_url($contact["url"]);
1464
1465         $r = q("SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1466                 dbesc(normalise_link($contact["url"])));
1467
1468         if ($r) {
1469                 $gcontact_id = $r[0]["id"];
1470
1471                 // Update every 90 days
1472                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
1473                         $last_failure_str = $r[0]["last_failure"];
1474                         $last_failure = strtotime($r[0]["last_failure"]);
1475                         $last_contact_str = $r[0]["last_contact"];
1476                         $last_contact = strtotime($r[0]["last_contact"]);
1477                         $doprobing = (((time() - $last_contact) > (90 * 86400)) AND ((time() - $last_failure) > (90 * 86400)));
1478                 }
1479         } else {
1480                 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
1481                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
1482                         dbesc($contact["name"]),
1483                         dbesc($contact["nick"]),
1484                         dbesc($contact["addr"]),
1485                         dbesc($contact["network"]),
1486                         dbesc($contact["url"]),
1487                         dbesc(normalise_link($contact["url"])),
1488                         dbesc($contact["photo"]),
1489                         dbesc(datetime_convert()),
1490                         dbesc(datetime_convert()),
1491                         dbesc($contact["location"]),
1492                         dbesc($contact["about"]),
1493                         intval($contact["hide"]),
1494                         intval($contact["generation"])
1495                 );
1496
1497                 $r = q("SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1498                         dbesc(normalise_link($contact["url"])));
1499
1500                 if ($r) {
1501                         $gcontact_id = $r[0]["id"];
1502
1503                         $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
1504                 }
1505         }
1506
1507         if ($doprobing) {
1508                 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
1509                 proc_run('php', 'include/gprobe.php', bin2hex($contact["url"]));
1510         }
1511
1512         if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1513          q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1514                 dbesc(normalise_link($contact["url"])),
1515                 intval($gcontact_id));
1516
1517         return $gcontact_id;
1518 }
1519
1520 /**
1521  * @brief Updates the gcontact table from a given array
1522  *
1523  * @param arr $contact contact array
1524  * @return bool|int Returns false if not found, integer if contact was found
1525  */
1526 function update_gcontact($contact) {
1527
1528         /// @todo update contact table as well
1529
1530         $gcontact_id = get_gcontact_id($contact);
1531
1532         if (!$gcontact_id)
1533                 return false;
1534
1535         $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1536                         `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1537                 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1538                 intval($gcontact_id));
1539
1540         // Get all field names
1541         $fields = array();
1542         foreach ($r[0] AS $field => $data)
1543                 $fields[$field] = $data;
1544
1545         unset($fields["url"]);
1546         unset($fields["updated"]);
1547         unset($fields["hide"]);
1548
1549         // Bugfix: We had an error in the storing of keywords which lead to the "0"
1550         // This value is still transmitted via poco.
1551         if ($contact["keywords"] == "0")
1552                 unset($contact["keywords"]);
1553
1554         if ($r[0]["keywords"] == "0")
1555                 $r[0]["keywords"] = "";
1556
1557         // assign all unassigned fields from the database entry
1558         foreach ($fields AS $field => $data)
1559                 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1560                         $contact[$field] = $r[0][$field];
1561
1562         if (!isset($contact["hide"]))
1563                 $contact["hide"] = $r[0]["hide"];
1564
1565         $fields["hide"] = $r[0]["hide"];
1566
1567         if ($contact["network"] == NETWORK_STATUSNET)
1568                 $contact["network"] = NETWORK_OSTATUS;
1569
1570         // Replace alternate OStatus user format with the primary one
1571         fix_alternate_contact_address($contact);
1572
1573         if (!isset($contact["updated"]))
1574                 $contact["updated"] = datetime_convert();
1575
1576         if ($contact["server_url"] == "") {
1577                 $server_url = $contact["url"];
1578
1579                 $server_url = matching_url($server_url, $contact["alias"]);
1580                 if ($server_url != "")
1581                         $contact["server_url"] = $server_url;
1582
1583                 $server_url = matching_url($server_url, $contact["photo"]);
1584                 if ($server_url != "")
1585                         $contact["server_url"] = $server_url;
1586
1587                 $server_url = matching_url($server_url, $contact["notify"]);
1588                 if ($server_url != "")
1589                         $contact["server_url"] = $server_url;
1590         } else
1591                 $contact["server_url"] = normalise_link($contact["server_url"]);
1592
1593         if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1594                 $hostname = str_replace("http://", "", $contact["server_url"]);
1595                 $contact["addr"] = $contact["nick"]."@".$hostname;
1596         }
1597
1598         // Check if any field changed
1599         $update = false;
1600         unset($fields["generation"]);
1601
1602         if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1603                 foreach ($fields AS $field => $data)
1604                         if ($contact[$field] != $r[0][$field]) {
1605                                 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1606                                 $update = true;
1607                         }
1608
1609                 if ($contact["generation"] < $r[0]["generation"]) {
1610                         logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1611                         $update = true;
1612                 }
1613         }
1614
1615         if ($update) {
1616                 logger("Update gcontact for ".$contact["url"]." Callstack: ".App::callstack(), LOGGER_DEBUG);
1617
1618                 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1619                                         `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1620                                         `alias` = '%s', `notify` = '%s', `url` = '%s',
1621                                         `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1622                                         `server_url` = '%s', `connect` = '%s'
1623                                 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1624                         dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1625                         dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1626                         dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1627                         intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
1628                         dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1629                         intval($contact["generation"]), dbesc($contact["updated"]),
1630                         dbesc($contact["server_url"]), dbesc($contact["connect"]),
1631                         dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1632
1633
1634                 // Now update the contact entry with the user id "0" as well.
1635                 // This is used for the shadow copies of public items.
1636                 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1637                         dbesc(normalise_link($contact["url"])));
1638
1639                 if ($r) {
1640                         logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1641
1642                         update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1643
1644                         q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1645                                                 `network` = '%s', `bd` = '%s', `gender` = '%s',
1646                                                 `keywords` = '%s', `alias` = '%s', `url` = '%s',
1647                                                 `location` = '%s', `about` = '%s'
1648                                         WHERE `id` = %d",
1649                                 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1650                                 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1651                                 dbesc($contact["keywords"]), dbesc($contact["alias"]), dbesc($contact["url"]),
1652                                 dbesc($contact["location"]), dbesc($contact["about"]), intval($r[0]["id"]));
1653                 }
1654         }
1655
1656         return $gcontact_id;
1657 }
1658
1659 /**
1660  * @brief Updates the gcontact entry from probe
1661  *
1662  * @param str $url profile link
1663  */
1664 function update_gcontact_from_probe($url) {
1665         $data = probe_url($url);
1666
1667         if (in_array($data["network"], array(NETWORK_PHANTOM))) {
1668                 logger("Invalid network for contact url ".$data["url"]." - Called by: ".App::callstack(), LOGGER_DEBUG);
1669                 return;
1670         }
1671
1672         update_gcontact($data);
1673 }
1674
1675 /**
1676  * @brief Update the gcontact entry for a given user id
1677  *
1678  * @param int $uid User ID
1679  */
1680 function update_gcontact_for_user($uid) {
1681         $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1682                         `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1683                         `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1684                         `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1685                         `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1686                 FROM `profile`
1687                         INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1688                         INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1689                 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1690                 intval($uid));
1691
1692         $location = formatted_location(array("locality" => $r[0]["locality"], "region" => $r[0]["region"],
1693                                                 "country-name" => $r[0]["country-name"]));
1694
1695         // The "addr" field was added in 3.4.3 so it can be empty for older users
1696         if ($r[0]["addr"] != "")
1697                 $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", App::get_baseurl());
1698         else
1699                 $addr = $r[0]["addr"];
1700
1701         $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
1702                         "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
1703                         "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1704                         "notify" => $r[0]["notify"], "url" => $r[0]["url"],
1705                         "hide" => ($r[0]["hidewall"] OR !$r[0]["net-publish"]),
1706                         "nick" => $r[0]["nickname"], "addr" => $addr,
1707                         "connect" => $addr, "server_url" => App::get_baseurl(),
1708                         "generation" => 1, "network" => NETWORK_DFRN);
1709
1710         update_gcontact($gcontact);
1711 }
1712
1713 /**
1714  * @brief Fetches users of given GNU Social server
1715  *
1716  * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1717  *
1718  * @param str $server Server address
1719  */
1720 function gs_fetch_users($server) {
1721
1722         logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1723
1724         $a = get_app();
1725
1726         $url = $server."/main/statistics";
1727
1728         $result = z_fetch_url($url);
1729         if (!$result["success"])
1730                 return false;
1731
1732         $statistics = json_decode($result["body"]);
1733
1734         if (is_object($statistics->config)) {
1735                 if ($statistics->config->instance_with_ssl)
1736                         $server = "https://";
1737                 else
1738                         $server = "http://";
1739
1740                 $server .= $statistics->config->instance_address;
1741
1742                 $hostname = $statistics->config->instance_address;
1743         } else {
1744                 if ($statistics->instance_with_ssl)
1745                         $server = "https://";
1746                 else
1747                         $server = "http://";
1748
1749                 $server .= $statistics->instance_address;
1750
1751                 $hostname = $statistics->instance_address;
1752         }
1753
1754         if (is_object($statistics->users))
1755                 foreach ($statistics->users AS $nick => $user) {
1756                         $profile_url = $server."/".$user->nickname;
1757
1758                         $contact = array("url" => $profile_url,
1759                                         "name" => $user->fullname,
1760                                         "addr" => $user->nickname."@".$hostname,
1761                                         "nick" => $user->nickname,
1762                                         "about" => $user->bio,
1763                                         "network" => NETWORK_OSTATUS,
1764                                         "photo" => $a->get_baseurl()."/images/person-175.jpg");
1765                         get_gcontact_id($contact);
1766                 }
1767 }
1768
1769 /**
1770  * @brief Asking GNU Social server on a regular base for their user data
1771  *
1772  */
1773 function gs_discover() {
1774
1775         $requery_days = intval(get_config("system", "poco_requery_days"));
1776
1777         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1778
1779         $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",
1780                 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1781
1782         if (!$r)
1783                 return;
1784
1785         foreach ($r AS $server) {
1786                 gs_fetch_users($server["url"]);
1787                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1788         }
1789 }
1790 ?>