]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
Merge pull request #2002 from annando/1511-cid
[friendica.git] / include / socgraph.php
1 <?php
2
3 require_once('include/datetime.php');
4 require_once("include/Scrape.php");
5 require_once("include/html2bbcode.php");
6
7 /*
8  To-Do:
9  - Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
10  - Fetch profile data from profile page for Redmatrix users
11  - Detect if it is a forum
12 */
13
14 /*
15  * poco_load
16  *
17  * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
18  * and add the entries to the gcontact (Global Contact) table, or update existing entries
19  * if anything (name or photo) has changed.
20  * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
21  *
22  * Once the global contact is stored add (if necessary) the contact linkage which associates
23  * the given uid, cid to the global contact entry. There can be many uid/cid combinations
24  * pointing to the same global contact id.
25  *
26  */
27
28
29
30
31 function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
32
33         $a = get_app();
34
35         if($cid) {
36                 if((! $url) || (! $uid)) {
37                         $r = q("select `poco`, `uid` from `contact` where `id` = %d limit 1",
38                                 intval($cid)
39                         );
40                         if(count($r)) {
41                                 $url = $r[0]['poco'];
42                                 $uid = $r[0]['uid'];
43                         }
44                 }
45                 if(! $uid)
46                         return;
47         }
48
49         if(! $url)
50                 return;
51
52         $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') ;
53
54         logger('poco_load: ' . $url, LOGGER_DEBUG);
55
56         $s = fetch_url($url);
57
58         logger('poco_load: returns ' . $s, LOGGER_DATA);
59
60         logger('poco_load: return code: ' . $a->get_curl_code(), LOGGER_DEBUG);
61
62         if(($a->get_curl_code() > 299) || (! $s))
63                 return;
64
65         $j = json_decode($s);
66
67         logger('poco_load: json: ' . print_r($j,true),LOGGER_DATA);
68
69         if(! isset($j->entry))
70                 return;
71
72         $total = 0;
73         foreach($j->entry as $entry) {
74
75                 $total ++;
76                 $profile_url = '';
77                 $profile_photo = '';
78                 $connect_url = '';
79                 $name = '';
80                 $network = '';
81                 $updated = '0000-00-00 00:00:00';
82                 $location = '';
83                 $about = '';
84                 $keywords = '';
85                 $gender = '';
86                 $generation = 0;
87
88                 $name = $entry->displayName;
89
90                 if(isset($entry->urls)) {
91                         foreach($entry->urls as $url) {
92                                 if($url->type == 'profile') {
93                                         $profile_url = $url->value;
94                                         continue;
95                                 }
96                                 if($url->type == 'webfinger') {
97                                         $connect_url = str_replace('acct:' , '', $url->value);
98                                         continue;
99                                 }
100                         }
101                 }
102                 if(isset($entry->photos)) {
103                         foreach($entry->photos as $photo) {
104                                 if($photo->type == 'profile') {
105                                         $profile_photo = $photo->value;
106                                         continue;
107                                 }
108                         }
109                 }
110
111                 if(isset($entry->updated))
112                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
113
114                 if(isset($entry->network))
115                         $network = $entry->network;
116
117                 if(isset($entry->currentLocation))
118                         $location = $entry->currentLocation;
119
120                 if(isset($entry->aboutMe))
121                         $about = html2bbcode($entry->aboutMe);
122
123                 if(isset($entry->gender))
124                         $gender = $entry->gender;
125
126                 if(isset($entry->generation) AND ($entry->generation > 0))
127                         $generation = ++$entry->generation;
128
129                 if(isset($entry->tags))
130                         foreach($entry->tags as $tag)
131                                 $keywords = implode(", ", $tag);
132
133                 // If you query a Friendica server for its profiles, the network has to be Friendica
134                 // To-Do: It could also be a Redmatrix server
135                 //if ($uid == 0)
136                 //      $network = NETWORK_DFRN;
137
138                 poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
139
140                 // Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
141                 if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
142                         q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
143                                 WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
144                                 dbesc($location),
145                                 dbesc($about),
146                                 dbesc($keywords),
147                                 dbesc($gender),
148                                 dbesc(normalise_link($profile_url)),
149                                 dbesc(NETWORK_DFRN));
150         }
151         logger("poco_load: loaded $total entries",LOGGER_DEBUG);
152
153         q("DELETE FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `zcid` = %d AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY",
154                 intval($cid),
155                 intval($uid),
156                 intval($zcid)
157         );
158
159 }
160
161 function poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid = 0, $uid = 0, $zcid = 0) {
162
163         $a = get_app();
164
165         // Generation:
166         //  0: No definition
167         //  1: Profiles on this server
168         //  2: Contacts of profiles on this server
169         //  3: Contacts of contacts of profiles on this server
170         //  4: ...
171
172         $gcid = "";
173
174         $alternate = poco_alternate_ostatus_url($profile_url);
175
176         if ($profile_url == "")
177                 return $gcid;
178
179         $urlparts = parse_url($profile_url);
180         if (!isset($urlparts["scheme"]))
181                 return $gcid;
182
183         if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com",
184                                                 "identi.ca", "alpha.app.net")))
185                 return $gcid;
186
187         $orig_updated = $updated;
188
189         // Don't store the statusnet connector as network
190         // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
191         if ($network == NETWORK_STATUSNET)
192                 $network = "";
193
194         // The global contacts should contain the original picture, not the cached one
195         if (($generation != 1) AND stristr(normalise_link($profile_photo), normalise_link($a->get_baseurl()."/photo/")))
196                 $profile_photo = "";
197
198         $r = q("SELECT `network` FROM `contact` WHERE `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
199                 dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
200         );
201         if(count($r))
202                 $network = $r[0]["network"];
203
204         if (($network == "") OR ($network == NETWORK_OSTATUS)) {
205                 $r = q("SELECT `network`, `url` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
206                         dbesc($profile_url), dbesc(normalise_link($profile_url)), dbesc(NETWORK_STATUSNET)
207                 );
208                 if(count($r)) {
209                         $network = $r[0]["network"];
210                         //$profile_url = $r[0]["url"];
211                 }
212         }
213
214         $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
215                 dbesc(normalise_link($profile_url))
216         );
217
218         if (count($x)) {
219                 if (($network == "") AND ($x[0]["network"] != NETWORK_STATUSNET))
220                         $network = $x[0]["network"];
221
222                 if ($updated == "0000-00-00 00:00:00")
223                         $updated = $x[0]["updated"];
224
225                 $created = $x[0]["created"];
226                 $server_url = $x[0]["server_url"];
227                 $nick = $x[0]["nick"];
228         } else {
229                 $created = "0000-00-00 00:00:00";
230                 $server_url = "";
231
232                 $urlparts = parse_url($profile_url);
233                 $nick = end(explode("/", $urlparts["path"]));
234         }
235
236         if ((($network == "") OR ($name == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
237                 AND poco_reachable($profile_url, $server_url, $network, false)) {
238                 $data = probe_url($profile_url);
239
240                 $orig_profile = $profile_url;
241
242                 $network = $data["network"];
243                 $name = $data["name"];
244                 $nick = $data["nick"];
245                 $profile_url = $data["url"];
246                 $profile_photo = $data["photo"];
247                 $server_url = $data["baseurl"];
248
249                 if ($alternate AND ($network == NETWORK_OSTATUS)) {
250                         // Delete the old entry - if it exists
251                         $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
252                         if ($r) {
253                                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
254                                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
255                         }
256
257                         // possibly create a new entry
258                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
259                 }
260         }
261
262         if ($alternate AND ($network == NETWORK_OSTATUS))
263                 return $gcid;
264
265         if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
266                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
267                         dbesc($network),
268                         dbesc(normalise_link($profile_url))
269                 );
270         }
271
272         if (($name == "") OR ($profile_photo == ""))
273                 return $gcid;
274
275         if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
276                 return $gcid;
277
278         logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
279
280         poco_check_server($server_url, $network);
281
282         if(count($x)) {
283                 $gcid = $x[0]['id'];
284
285                 if (($location == "") AND ($x[0]['location'] != ""))
286                         $location = $x[0]['location'];
287
288                 if (($about == "") AND ($x[0]['about'] != ""))
289                         $about = $x[0]['about'];
290
291                 if (($gender == "") AND ($x[0]['gender'] != ""))
292                         $gender = $x[0]['gender'];
293
294                 if (($keywords == "") AND ($x[0]['keywords'] != ""))
295                         $keywords = $x[0]['keywords'];
296
297                 if (($generation == 0) AND ($x[0]['generation'] > 0))
298                         $generation = $x[0]['generation'];
299
300                 if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
301                         q("UPDATE `gcontact` SET `name` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
302                                 `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d
303                                 WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
304                                 dbesc($name),
305                                 dbesc($network),
306                                 dbesc($profile_photo),
307                                 dbesc($connect_url),
308                                 dbesc($profile_url),
309                                 dbesc($server_url),
310                                 dbesc($updated),
311                                 dbesc($location),
312                                 dbesc($about),
313                                 dbesc($keywords),
314                                 dbesc($gender),
315                                 intval($generation),
316                                 intval($generation),
317                                 dbesc(normalise_link($profile_url))
318                         );
319                 }
320         } else {
321                 q("INSERT INTO `gcontact` (`name`, `nick`, `network`, `url`, `nurl`, `photo`, `connect`, `server_url`, `created`, `updated`, `location`, `about`, `keywords`, `gender`, `generation`)
322                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
323                         dbesc($name),
324                         dbesc($nick),
325                         dbesc($network),
326                         dbesc($profile_url),
327                         dbesc(normalise_link($profile_url)),
328                         dbesc($profile_photo),
329                         dbesc($connect_url),
330                         dbesc($server_url),
331                         dbesc(datetime_convert()),
332                         dbesc($updated),
333                         dbesc($location),
334                         dbesc($about),
335                         dbesc($keywords),
336                         dbesc($gender),
337                         intval($generation)
338                 );
339                 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
340                         dbesc(normalise_link($profile_url))
341                 );
342                 if(count($x))
343                         $gcid = $x[0]['id'];
344         }
345
346         if(! $gcid)
347                 return $gcid;
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(! count($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         // For unknown reasons there are sometimes duplicates
374         q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
375                 NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
376                 dbesc(normalise_link($profile_url)),
377                 intval($gcid)
378         );
379
380         return $gcid;
381 }
382
383 function poco_reachable($profile, $server = "", $network = "", $force = false) {
384
385         if ($server == "")
386                 $server = poco_detect_server($profile);
387
388         if ($server == "")
389                 return true;
390
391         return poco_check_server($server, $network, $force);
392 }
393
394 function poco_detect_server($profile) {
395
396         // Try to detect the server path based upon some known standard paths
397         $server_url = "";
398
399         if ($server_url == "") {
400                 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
401                 if ($friendica != $profile) {
402                         $server_url = $friendica;
403                         $network = NETWORK_DFRN;
404                 }
405         }
406
407         if ($server_url == "") {
408                 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
409                 if ($diaspora != $profile) {
410                         $server_url = $diaspora;
411                         $network = NETWORK_DIASPORA;
412                 }
413         }
414
415         if ($server_url == "") {
416                 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
417                 if ($red != $profile) {
418                         $server_url = $red;
419                         $network = NETWORK_DIASPORA;
420                 }
421         }
422
423         return $server_url;
424 }
425
426 function poco_alternate_ostatus_url($url) {
427         return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
428 }
429
430 function poco_last_updated($profile, $force = false) {
431
432         $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
433                         dbesc(normalise_link($profile)));
434
435         if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
436                 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
437                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
438
439         if ($gcontacts[0]["server_url"] != "")
440                 $server_url = $gcontacts[0]["server_url"];
441         else
442                 $server_url = poco_detect_server($profile);
443
444         if ($server_url != "") {
445                 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
446
447                         if ($force)
448                                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
449                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
450
451                         return false;
452                 }
453
454                 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
455                         dbesc($server_url), dbesc(normalise_link($profile)));
456         }
457
458         if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
459                 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
460                         dbesc(normalise_link($server_url)));
461
462                 if ($server)
463                         q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
464                                 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
465                 else
466                         return;
467         }
468
469         // noscrape is really fast so we don't cache the call.
470         if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
471
472                 //  Use noscrape if possible
473                 $server = q("SELECT `noscrape` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
474
475                 if ($server) {
476                         $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
477
478                          if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
479
480                                 $noscrape = json_decode($noscraperet["body"], true);
481
482                                 if (($noscrape["fn"] != "") AND ($noscrape["fn"] != $gcontacts[0]["name"]))
483                                         q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
484                                                 dbesc($noscrape["fn"]), dbesc(normalise_link($profile)));
485
486                                 if (($noscrape["photo"] != "") AND ($noscrape["photo"] != $gcontacts[0]["photo"]))
487                                         q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
488                                                 dbesc($noscrape["photo"]), dbesc(normalise_link($profile)));
489
490                                 if (($noscrape["updated"] != "") AND ($noscrape["updated"] != $gcontacts[0]["updated"]))
491                                         q("UPDATE `gcontact` SET `updated` = '%s' WHERE `nurl` = '%s'",
492                                                 dbesc($noscrape["updated"]), dbesc(normalise_link($profile)));
493
494                                 if (($noscrape["gender"] != "") AND ($noscrape["gender"] != $gcontacts[0]["gender"]))
495                                         q("UPDATE `gcontact` SET `gender` = '%s' WHERE `nurl` = '%s'",
496                                                 dbesc($noscrape["gender"]), dbesc(normalise_link($profile)));
497
498                                 if (($noscrape["pdesc"] != "") AND ($noscrape["pdesc"] != $gcontacts[0]["about"]))
499                                         q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
500                                                 dbesc($noscrape["pdesc"]), dbesc(normalise_link($profile)));
501
502                                 if (($noscrape["about"] != "") AND ($noscrape["about"] != $gcontacts[0]["about"]))
503                                         q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
504                                                 dbesc($noscrape["about"]), dbesc(normalise_link($profile)));
505
506                                 if (isset($noscrape["comm"]) AND ($noscrape["comm"] != $gcontacts[0]["community"]))
507                                         q("UPDATE `gcontact` SET `community` = %d WHERE `nurl` = '%s'",
508                                                 intval($noscrape["comm"]), dbesc(normalise_link($profile)));
509
510                                 if (isset($noscrape["tags"]))
511                                         $keywords = implode(" ", $noscrape["tags"]);
512                                 else
513                                         $keywords = "";
514
515                                 if (($keywords != "") AND ($keywords != $gcontacts[0]["keywords"]))
516                                         q("UPDATE `gcontact` SET `keywords` = '%s' WHERE `nurl` = '%s'",
517                                                 dbesc($keywords), dbesc(normalise_link($profile)));
518
519                                 $location = $noscrape["locality"];
520
521                                 if ($noscrape["region"] != "") {
522                                         if ($location != "")
523                                                 $location .= ", ";
524
525                                         $location .= $noscrape["region"];
526                                 }
527
528                                 if ($noscrape["country-name"] != "") {
529                                         if ($location != "")
530                                                 $location .= ", ";
531
532                                         $location .= $noscrape["country-name"];
533                                 }
534
535                                 if (($location != "") AND ($location != $gcontacts[0]["location"]))
536                                         q("UPDATE `gcontact` SET `location` = '%s' WHERE `nurl` = '%s'",
537                                                 dbesc($location), dbesc(normalise_link($profile)));
538
539                                 // If we got data from noscrape then mark the contact as reachable
540                                 if (is_array($noscrape) AND count($noscrape))
541                                         q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
542                                                 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
543
544                                 return $noscrape["updated"];
545                         }
546                 }
547         }
548
549         // If we only can poll the feed, then we only do this once a while
550         if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"],  $gcontacts[0]["last_contact"]))
551                 return $gcontacts[0]["updated"];
552
553         $data = probe_url($profile);
554
555         // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
556         // Then check the other link and delete this one
557         if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
558                 (normalise_link($profile) == normalise_link($data["alias"])) AND
559                 (normalise_link($profile) != normalise_link($data["url"]))) {
560
561                 // Delete the old entry
562                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
563                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
564
565                 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
566                                 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
567
568                 poco_last_updated($data["url"], $force);
569
570                 return false;
571         }
572
573         if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
574                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
575                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
576                 return false;
577         }
578
579         if (($data["name"] != "") AND ($data["name"] != $gcontacts[0]["name"]))
580                 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
581                         dbesc($data["name"]), dbesc(normalise_link($profile)));
582
583         if (($data["nick"] != "") AND ($data["nick"] != $gcontacts[0]["nick"]))
584                 q("UPDATE `gcontact` SET `nick` = '%s' WHERE `nurl` = '%s'",
585                         dbesc($data["nick"]), dbesc(normalise_link($profile)));
586
587         if (($data["addr"] != "") AND ($data["addr"] != $gcontacts[0]["connect"]))
588                 q("UPDATE `gcontact` SET `connect` = '%s' WHERE `nurl` = '%s'",
589                         dbesc($data["addr"]), dbesc(normalise_link($profile)));
590
591         if (($data["photo"] != "") AND ($data["photo"] != $gcontacts[0]["photo"]))
592                 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
593                         dbesc($data["photo"]), dbesc(normalise_link($profile)));
594
595         if (($data["baseurl"] != "") AND ($data["baseurl"] != $gcontacts[0]["server_url"]))
596                 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
597                         dbesc($data["baseurl"]), dbesc(normalise_link($profile)));
598
599         $feedret = z_fetch_url($data["poll"]);
600
601         if (!$feedret["success"]) {
602                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
603                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
604                 return false;
605         }
606
607         $doc = new DOMDocument();
608         @$doc->loadXML($feedret["body"]);
609
610         $xpath = new DomXPath($doc);
611         $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
612
613         $entries = $xpath->query('/atom:feed/atom:entry');
614
615         $last_updated = "";
616
617         foreach ($entries AS $entry) {
618                 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
619                 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
620
621                 if ($last_updated < $published)
622                         $last_updated = $published;
623
624                 if ($last_updated < $updated)
625                         $last_updated = $updated;
626         }
627
628         // Maybe there aren't any entries. Then check if it is a valid feed
629         if ($last_updated == "")
630                 if ($xpath->query('/atom:feed')->length > 0)
631                         $last_updated = "0000-00-00 00:00:00";
632
633         q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
634                 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
635
636         if (($gcontacts[0]["generation"] == 0))
637                 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
638                         dbesc(normalise_link($profile)));
639
640         return($last_updated);
641 }
642
643 function poco_do_update($created, $updated, $last_failure,  $last_contact) {
644         $now = strtotime(datetime_convert());
645
646         if ($updated > $last_contact)
647                 $contact_time = strtotime($updated);
648         else
649                 $contact_time = strtotime($last_contact);
650
651         $failure_time = strtotime($last_failure);
652         $created_time = strtotime($created);
653
654         // If there is no "created" time then use the current time
655         if ($created_time <= 0)
656                 $created_time = $now;
657
658         // If the last contact was less than 24 hours then don't update
659         if (($now - $contact_time) < (60 * 60 * 24))
660                 return false;
661
662         // If the last failure was less than 24 hours then don't update
663         if (($now - $failure_time) < (60 * 60 * 24))
664                 return false;
665
666         // If the last contact was less than a week ago and the last failure is older than a week then don't update
667         //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
668         //      return false;
669
670         // 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
671         if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
672                 return false;
673
674         // 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
675         if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
676                 return false;
677
678         return true;
679 }
680
681 function poco_to_boolean($val) {
682         if (($val == "true") OR ($val == 1))
683                 return(true);
684         if (($val == "false") OR ($val == 0))
685                 return(false);
686
687         return ($val);
688 }
689
690 function poco_check_server($server_url, $network = "", $force = false) {
691
692         if ($server_url == "")
693                 return false;
694
695         $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
696         if ($servers) {
697
698                 if ($servers[0]["created"] == "0000-00-00 00:00:00")
699                         q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
700                                 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
701
702                 $poco = $servers[0]["poco"];
703                 $noscrape = $servers[0]["noscrape"];
704
705                 if ($network == "")
706                         $network = $servers[0]["network"];
707
708                 $last_contact = $servers[0]["last_contact"];
709                 $last_failure = $servers[0]["last_failure"];
710                 $version = $servers[0]["version"];
711                 $platform = $servers[0]["platform"];
712                 $site_name = $servers[0]["site_name"];
713                 $info = $servers[0]["info"];
714                 $register_policy = $servers[0]["register_policy"];
715
716                 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
717                         logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
718                         return ($last_contact >= $last_failure);
719                 }
720         } else {
721                 $poco = "";
722                 $noscrape = "";
723                 $version = "";
724                 $platform = "";
725                 $site_name = "";
726                 $info = "";
727                 $register_policy = -1;
728
729                 $last_contact = "0000-00-00 00:00:00";
730                 $last_failure = "0000-00-00 00:00:00";
731         }
732         logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
733
734         $failure = false;
735         $orig_last_failure = $last_failure;
736
737         // Check if the page is accessible via SSL.
738         $server_url = str_replace("http://", "https://", $server_url);
739         $serverret = z_fetch_url($server_url."/.well-known/host-meta");
740
741         // Maybe the page is unencrypted only?
742         $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
743         if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
744                 $server_url = str_replace("https://", "http://", $server_url);
745                 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
746
747                 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
748         }
749
750         if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
751                 // Workaround for bad configured servers (known nginx problem)
752                 if ($serverret["debug"]["http_code"] != "403") {
753                         $last_failure = datetime_convert();
754                         $failure = true;
755                 }
756         } elseif ($network == NETWORK_DIASPORA)
757                 $last_contact = datetime_convert();
758
759         if (!$failure) {
760                 // Test for Diaspora
761                 $serverret = z_fetch_url($server_url);
762
763                 $lines = explode("\n",$serverret["header"]);
764                 if(count($lines))
765                         foreach($lines as $line) {
766                                 $line = trim($line);
767                                 if(stristr($line,'X-Diaspora-Version:')) {
768                                         $platform = "Diaspora";
769                                         $version = trim(str_replace("X-Diaspora-Version:", "", $line));
770                                         $version = trim(str_replace("x-diaspora-version:", "", $version));
771                                         $network = NETWORK_DIASPORA;
772                                 }
773                         }
774         }
775
776         if (!$failure) {
777                 // Test for Statusnet
778                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
779                 // The "not implemented" is a special treatment for really, really old Friendica versions
780                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
781                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
782                         $platform = "StatusNet";
783                         $version = trim($serverret["body"], '"');
784                         $network = NETWORK_OSTATUS;
785                 }
786
787                 // Test for GNU Social
788                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
789                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
790                         $platform = "GNU Social";
791                         $version = trim($serverret["body"], '"');
792                         $network = NETWORK_OSTATUS;
793                 }
794
795                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
796                 if ($serverret["success"]) {
797                         $data = json_decode($serverret["body"]);
798
799                         if (isset($data->site->server)) {
800                                 $last_contact = datetime_convert();
801
802                                 if (isset($data->site->hubzilla)) {
803                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
804                                         $version = $data->site->hubzilla->RED_VERSION;
805                                         $network = NETWORK_DIASPORA;
806                                 }
807                                 if (isset($data->site->redmatrix)) {
808                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
809                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
810                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
811                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
812
813                                         $version = $data->site->redmatrix->RED_VERSION;
814                                         $network = NETWORK_DIASPORA;
815                                 }
816                                 if (isset($data->site->friendica)) {
817                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
818                                         $version = $data->site->friendica->FRIENDICA_VERSION;
819                                         $network = NETWORK_DFRN;
820                                 }
821
822                                 $site_name = $data->site->name;
823
824                                 $data->site->closed = poco_to_boolean($data->site->closed);
825                                 $data->site->private = poco_to_boolean($data->site->private);
826                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
827
828                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
829                                         $register_policy = REGISTER_APPROVE;
830                                 elseif (!$data->site->closed AND !$data->site->private)
831                                         $register_policy = REGISTER_OPEN;
832                                 else
833                                         $register_policy = REGISTER_CLOSED;
834                         }
835                 }
836         }
837
838         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
839         if (!$failure) {
840                 $serverret = z_fetch_url($server_url."/statistics.json");
841                 if ($serverret["success"]) {
842                         $data = json_decode($serverret["body"]);
843                         if ($version == "")
844                                 $version = $data->version;
845
846                         $site_name = $data->name;
847
848                         if (isset($data->network) AND ($platform == ""))
849                                 $platform = $data->network;
850
851                         if ($platform == "Diaspora")
852                                 $network = NETWORK_DIASPORA;
853
854                         if ($data->registrations_open)
855                                 $register_policy = REGISTER_OPEN;
856                         else
857                                 $register_policy = REGISTER_CLOSED;
858
859                         if (isset($data->version))
860                                 $last_contact = datetime_convert();
861                 }
862         }
863
864         // Check for noscrape
865         // Friendica servers could be detected as OStatus servers
866         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
867                 $serverret = z_fetch_url($server_url."/friendica/json");
868
869                 if (!$serverret["success"])
870                         $serverret = z_fetch_url($server_url."/friendika/json");
871
872                 if ($serverret["success"]) {
873                         $data = json_decode($serverret["body"]);
874
875                         if (isset($data->version)) {
876                                 $last_contact = datetime_convert();
877                                 $network = NETWORK_DFRN;
878
879                                 $noscrape = $data->no_scrape_url;
880                                 $version = $data->version;
881                                 $site_name = $data->site_name;
882                                 $info = $data->info;
883                                 $register_policy_str = $data->register_policy;
884                                 $platform = $data->platform;
885
886                                 switch ($register_policy_str) {
887                                         case "REGISTER_CLOSED":
888                                                 $register_policy = REGISTER_CLOSED;
889                                                 break;
890                                         case "REGISTER_APPROVE":
891                                                 $register_policy = REGISTER_APPROVE;
892                                                 break;
893                                         case "REGISTER_OPEN":
894                                                 $register_policy = REGISTER_OPEN;
895                                                 break;
896                                 }
897                         }
898                 }
899         }
900
901         // Look for poco
902         if (!$failure) {
903                 $serverret = z_fetch_url($server_url."/poco");
904                 if ($serverret["success"]) {
905                         $data = json_decode($serverret["body"]);
906                         if (isset($data->totalResults)) {
907                                 $poco = $server_url."/poco";
908                                 $last_contact = datetime_convert();
909                         }
910                 }
911         }
912
913         // Check again if the server exists
914         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
915
916         if ($servers)
917                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
918                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
919                         dbesc($server_url),
920                         dbesc($version),
921                         dbesc($site_name),
922                         dbesc($info),
923                         intval($register_policy),
924                         dbesc($poco),
925                         dbesc($noscrape),
926                         dbesc($network),
927                         dbesc($platform),
928                         dbesc($last_contact),
929                         dbesc($last_failure),
930                         dbesc(normalise_link($server_url))
931                 );
932         else
933                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
934                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
935                                 dbesc($server_url),
936                                 dbesc(normalise_link($server_url)),
937                                 dbesc($version),
938                                 dbesc($site_name),
939                                 dbesc($info),
940                                 intval($register_policy),
941                                 dbesc($poco),
942                                 dbesc($noscrape),
943                                 dbesc($network),
944                                 dbesc($platform),
945                                 dbesc(datetime_convert()),
946                                 dbesc($last_contact),
947                                 dbesc($last_failure),
948                                 dbesc(datetime_convert())
949                 );
950
951         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
952
953         return !$failure;
954 }
955
956 function poco_contact_from_body($body, $created, $cid, $uid) {
957         preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
958                 function ($match) use ($created, $cid, $uid){
959                         return(sub_poco_from_share($match, $created, $cid, $uid));
960                 }, $body);
961 }
962
963 function sub_poco_from_share($share, $created, $cid, $uid) {
964         $profile = "";
965         preg_match("/profile='(.*?)'/ism", $share[1], $matches);
966         if ($matches[1] != "")
967                 $profile = $matches[1];
968
969         preg_match('/profile="(.*?)"/ism', $share[1], $matches);
970         if ($matches[1] != "")
971                 $profile = $matches[1];
972
973         if ($profile == "")
974                 return;
975
976         logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
977         poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
978 }
979
980 function poco_store($item) {
981
982         // Isn't it public?
983         if ($item['private'])
984                 return;
985
986         // Or is it from a network where we don't store the global contacts?
987         if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
988                 return;
989
990         // Is it a global copy?
991         $store_gcontact = ($item["uid"] == 0);
992
993         // Is it a comment on a global copy?
994         if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
995                 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
996                 $store_gcontact = count($q);
997         }
998
999         if (!$store_gcontact)
1000                 return;
1001
1002         // "3" means: We don't know this contact directly (Maybe a reshared item)
1003         $generation = 3;
1004         $network = "";
1005         $profile_url = $item["author-link"];
1006
1007         // Is it a user from our server?
1008         $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
1009                 dbesc(normalise_link($item["author-link"])));
1010         if (count($q)) {
1011                 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
1012                 $generation = 1;
1013                 $network = NETWORK_DFRN;
1014         } else { // Is it a contact from a user on our server?
1015                 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
1016                         AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
1017                         dbesc(normalise_link($item["author-link"])),
1018                         dbesc(normalise_link($item["author-link"])),
1019                         dbesc($item["author-link"]),
1020                         dbesc(NETWORK_STATUSNET));
1021                 if (count($q)) {
1022                         $generation = 2;
1023                         $network = $q[0]["network"];
1024                         $profile_url = $q[0]["url"];
1025                         logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
1026                 }
1027         }
1028
1029         if ($generation == 3)
1030                 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
1031
1032         poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
1033
1034         // Maybe its a body with a shared item? Then extract a global contact from it.
1035         poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1036 }
1037
1038 function count_common_friends($uid,$cid) {
1039
1040         $r = q("SELECT count(*) as `total`
1041                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1042                 where `glink`.`cid` = %d and `glink`.`uid` = %d
1043                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1044                 intval($cid),
1045                 intval($uid),
1046                 intval($uid),
1047                 intval($cid)
1048         );
1049
1050 //      logger("count_common_friends: $uid $cid {$r[0]['total']}");
1051         if(count($r))
1052                 return $r[0]['total'];
1053         return 0;
1054
1055 }
1056
1057
1058 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1059
1060         if($shuffle)
1061                 $sql_extra = " order by rand() ";
1062         else
1063                 $sql_extra = " order by `gcontact`.`name` asc ";
1064
1065         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1066                 FROM `glink`
1067                 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1068                 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1069                 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1070                         AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1071                         AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1072                         $sql_extra LIMIT %d, %d",
1073                 intval($cid),
1074                 intval($uid),
1075                 intval($uid),
1076                 intval($cid),
1077                 intval($start),
1078                 intval($limit)
1079         );
1080
1081         return $r;
1082
1083 }
1084
1085
1086 function count_common_friends_zcid($uid,$zcid) {
1087
1088         $r = q("SELECT count(*) as `total`
1089                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1090                 where `glink`.`zcid` = %d
1091                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1092                 intval($zcid),
1093                 intval($uid)
1094         );
1095
1096         if(count($r))
1097                 return $r[0]['total'];
1098         return 0;
1099
1100 }
1101
1102 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1103
1104         if($shuffle)
1105                 $sql_extra = " order by rand() ";
1106         else
1107                 $sql_extra = " order by `gcontact`.`name` asc ";
1108
1109         $r = q("SELECT `gcontact`.*
1110                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1111                 where `glink`.`zcid` = %d
1112                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) 
1113                 $sql_extra limit %d, %d",
1114                 intval($zcid),
1115                 intval($uid),
1116                 intval($start),
1117                 intval($limit)
1118         );
1119
1120         return $r;
1121
1122 }
1123
1124
1125 function count_all_friends($uid,$cid) {
1126
1127         $r = q("SELECT count(*) as `total`
1128                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1129                 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
1130                 intval($cid),
1131                 intval($uid)
1132         );
1133
1134         if(count($r))
1135                 return $r[0]['total'];
1136         return 0;
1137
1138 }
1139
1140
1141 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1142
1143         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1144                 FROM `glink`
1145                 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1146                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1147                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d
1148                 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1149                 intval($uid),
1150                 intval($cid),
1151                 intval($uid),
1152                 intval($start),
1153                 intval($limit)
1154         );
1155
1156         return $r;
1157 }
1158
1159
1160
1161 function suggestion_query($uid, $start = 0, $limit = 80) {
1162
1163         if(! $uid)
1164                 return array();
1165
1166         $network = array(NETWORK_DFRN);
1167
1168         if (get_config('system','diaspora_enabled'))
1169                 $network[] = NETWORK_DIASPORA;
1170
1171         if (!get_config('system','ostatus_disabled'))
1172                 $network[] = NETWORK_OSTATUS;
1173
1174         $sql_network = implode("', '", $network);
1175         //$sql_network = "'".$sql_network."', ''";
1176         $sql_network = "'".$sql_network."'";
1177
1178         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1179                 INNER JOIN glink on glink.gcid = gcontact.id
1180                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1181                 and not gcontact.name in ( select name from contact where uid = %d )
1182                 and not gcontact.id in ( select gcid from gcign where uid = %d )
1183                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1184                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1185                 AND `gcontact`.`network` IN (%s)
1186                 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
1187                 intval($uid),
1188                 intval($uid),
1189                 intval($uid),
1190                 intval($uid),
1191                 $sql_network,
1192                 intval($start),
1193                 intval($limit)
1194         );
1195
1196         if(count($r) && count($r) >= ($limit -1))
1197                 return $r;
1198
1199         $r2 = q("SELECT gcontact.* from gcontact
1200                 INNER JOIN glink on glink.gcid = gcontact.id
1201                 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
1202                 and not gcontact.name in ( select name from contact where uid = %d )
1203                 and not gcontact.id in ( select gcid from gcign where uid = %d )
1204                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1205                 AND `gcontact`.`network` IN (%s)
1206                 order by rand() limit %d, %d ",
1207                 intval($uid),
1208                 intval($uid),
1209                 intval($uid),
1210                 $sql_network,
1211                 intval($start),
1212                 intval($limit)
1213         );
1214
1215         $list = array();
1216         foreach ($r2 AS $suggestion)
1217                 $list[$suggestion["nurl"]] = $suggestion;
1218
1219         foreach ($r AS $suggestion)
1220                 $list[$suggestion["nurl"]] = $suggestion;
1221
1222         return $list;
1223 }
1224
1225 function update_suggestions() {
1226
1227         $a = get_app();
1228
1229         $done = array();
1230
1231         // To-Do: Check if it is really neccessary to poll the own server
1232         poco_load(0,0,0,$a->get_baseurl() . '/poco');
1233
1234         $done[] = $a->get_baseurl() . '/poco';
1235
1236         if(strlen(get_config('system','directory'))) {
1237                 $x = fetch_url(get_server()."/pubsites");
1238                 if($x) {
1239                         $j = json_decode($x);
1240                         if($j->entries) {
1241                                 foreach($j->entries as $entry) {
1242
1243                                         poco_check_server($entry->url);
1244
1245                                         $url = $entry->url . '/poco';
1246                                         if(! in_array($url,$done))
1247                                                 poco_load(0,0,0,$entry->url . '/poco');
1248                                 }
1249                         }
1250                 }
1251         }
1252
1253         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1254         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1255                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1256         );
1257
1258         if(count($r)) {
1259                 foreach($r as $rr) {
1260                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1261                         if(! in_array($base,$done))
1262                                 poco_load(0,0,0,$base);
1263                 }
1264         }
1265 }
1266
1267 function poco_discover_federation() {
1268         $last = get_config('poco','last_federation_discovery');
1269
1270         if($last) {
1271                 $next = $last + (24 * 60 * 60);
1272                 if($next > time())
1273                         return;
1274         }
1275
1276         $serverdata = fetch_url("http://the-federation.info/pods.json");
1277
1278         if (!$serverdata)
1279                 return;
1280
1281         $servers = json_decode($serverdata);
1282
1283         foreach($servers->pods AS $server)
1284                 poco_check_server("https://".$server->host);
1285
1286         set_config('poco','last_federation_discovery', time());
1287
1288 }
1289
1290 function poco_discover($complete = false) {
1291
1292         // Update the server list
1293         poco_discover_federation();
1294
1295         $no_of_queries = 5;
1296
1297         $requery_days = intval(get_config("system", "poco_requery_days"));
1298
1299         if ($requery_days == 0)
1300                 $requery_days = 7;
1301
1302         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1303
1304         $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));
1305         if ($r)
1306                 foreach ($r AS $server) {
1307
1308                         if (!poco_check_server($server["url"], $server["network"])) {
1309                                 // The server is not reachable? Okay, then we will try it later
1310                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1311                                 continue;
1312                         }
1313
1314                         // Fetch all users from the other server
1315                         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1316
1317                         logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1318
1319                         $retdata = z_fetch_url($url);
1320                         if ($retdata["success"]) {
1321                                 $data = json_decode($retdata["body"]);
1322
1323                                 poco_discover_server($data, 2);
1324
1325                                 if (get_config('system','poco_discovery') > 1) {
1326
1327                                         $timeframe = get_config('system','poco_discovery_since');
1328                                         if ($timeframe == 0)
1329                                                 $timeframe = 30;
1330
1331                                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1332
1333                                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1334                                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1335
1336                                         $success = false;
1337
1338                                         $retdata = z_fetch_url($url);
1339                                         if ($retdata["success"]) {
1340                                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1341                                                 $success = poco_discover_server(json_decode($retdata["body"]));
1342                                         }
1343
1344                                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1345                                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1346                                                 poco_discover_server_users($data, $server);
1347                                         }
1348                                 }
1349
1350                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1351                                 if (!$complete AND (--$no_of_queries == 0))
1352                                         break;
1353                         } else {
1354                                 // If the server hadn't replied correctly, then force a sanity check
1355                                 poco_check_server($server["url"], $server["network"], true);
1356
1357                                 // If we couldn't reach the server, we will try it some time later
1358                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1359                         }
1360                 }
1361 }
1362
1363 function poco_discover_server_users($data, $server) {
1364
1365         if (!isset($data->entry))
1366                 return;
1367
1368         foreach ($data->entry AS $entry) {
1369                 $username = "";
1370                 if (isset($entry->urls)) {
1371                         foreach($entry->urls as $url)
1372                                 if($url->type == 'profile') {
1373                                         $profile_url = $url->value;
1374                                         $urlparts = parse_url($profile_url);
1375                                         $username = end(explode("/", $urlparts["path"]));
1376                                 }
1377                 }
1378                 if ($username != "") {
1379                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1380
1381                         // Fetch all contacts from a given user from the other server
1382                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1383
1384                         $retdata = z_fetch_url($url);
1385                         if ($retdata["success"])
1386                                 poco_discover_server(json_decode($retdata["body"]), 3);
1387                 }
1388         }
1389 }
1390
1391 function poco_discover_server($data, $default_generation = 0) {
1392
1393         if (!isset($data->entry) OR !count($data->entry))
1394                 return false;
1395
1396         $success = false;
1397
1398         foreach ($data->entry AS $entry) {
1399                 $profile_url = '';
1400                 $profile_photo = '';
1401                 $connect_url = '';
1402                 $name = '';
1403                 $network = '';
1404                 $updated = '0000-00-00 00:00:00';
1405                 $location = '';
1406                 $about = '';
1407                 $keywords = '';
1408                 $gender = '';
1409                 $generation = $default_generation;
1410
1411                 $name = $entry->displayName;
1412
1413                 if(isset($entry->urls)) {
1414                         foreach($entry->urls as $url) {
1415                                 if($url->type == 'profile') {
1416                                         $profile_url = $url->value;
1417                                         continue;
1418                                 }
1419                                 if($url->type == 'webfinger') {
1420                                         $connect_url = str_replace('acct:' , '', $url->value);
1421                                         continue;
1422                                 }
1423                         }
1424                 }
1425
1426                 if(isset($entry->photos)) {
1427                         foreach($entry->photos as $photo) {
1428                                 if($photo->type == 'profile') {
1429                                         $profile_photo = $photo->value;
1430                                         continue;
1431                                 }
1432                         }
1433                 }
1434
1435                 if(isset($entry->updated))
1436                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1437
1438                 if(isset($entry->network))
1439                         $network = $entry->network;
1440
1441                 if(isset($entry->currentLocation))
1442                         $location = $entry->currentLocation;
1443
1444                 if(isset($entry->aboutMe))
1445                         $about = html2bbcode($entry->aboutMe);
1446
1447                 if(isset($entry->gender))
1448                         $gender = $entry->gender;
1449
1450                 if(isset($entry->generation) AND ($entry->generation > 0))
1451                         $generation = ++$entry->generation;
1452
1453                 if(isset($entry->tags))
1454                         foreach($entry->tags as $tag)
1455                                 $keywords = implode(", ", $tag);
1456
1457                 if ($generation > 0) {
1458                         $success = true;
1459
1460                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1461                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1462                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1463                 }
1464         }
1465         return $success;
1466 }
1467 ?>