]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
Merge pull request #1853 from annando/1508-search-forum
[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, true)) {
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 ($data["network"] == NETWORK_FEED)) {
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                 $last_failure = datetime_convert();
752                 $failure = true;
753         } elseif ($network == NETWORK_DIASPORA)
754                 $last_contact = datetime_convert();
755
756         if (!$failure) {
757                 // Test for Diaspora
758                 $serverret = z_fetch_url($server_url);
759
760                 $lines = explode("\n",$serverret["header"]);
761                 if(count($lines))
762                         foreach($lines as $line) {
763                                 $line = trim($line);
764                                 if(stristr($line,'X-Diaspora-Version:')) {
765                                         $platform = "Diaspora";
766                                         $version = trim(str_replace("X-Diaspora-Version:", "", $line));
767                                         $version = trim(str_replace("x-diaspora-version:", "", $version));
768                                         $network = NETWORK_DIASPORA;
769                                 }
770                         }
771         }
772
773         if (!$failure) {
774                 // Test for Statusnet
775                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
776                 // The "not implemented" is a special treatment for really, really old Friendica versions
777                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
778                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
779                         $platform = "StatusNet";
780                         $version = trim($serverret["body"], '"');
781                         $network = NETWORK_OSTATUS;
782                 }
783
784                 // Test for GNU Social
785                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
786                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
787                         $platform = "GNU Social";
788                         $version = trim($serverret["body"], '"');
789                         $network = NETWORK_OSTATUS;
790                 }
791
792                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
793                 if ($serverret["success"]) {
794                         $data = json_decode($serverret["body"]);
795
796                         if (isset($data->site->server)) {
797                                 $last_contact = datetime_convert();
798
799                                 if (isset($data->site->hubzilla)) {
800                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
801                                         $version = $data->site->hubzilla->RED_VERSION;
802                                         $network = NETWORK_DIASPORA;
803                                 }
804                                 if (isset($data->site->redmatrix)) {
805                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
806                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
807                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
808                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
809
810                                         $version = $data->site->redmatrix->RED_VERSION;
811                                         $network = NETWORK_DIASPORA;
812                                 }
813                                 if (isset($data->site->friendica)) {
814                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
815                                         $version = $data->site->friendica->FRIENDICA_VERSION;
816                                         $network = NETWORK_DFRN;
817                                 }
818
819                                 $site_name = $data->site->name;
820
821                                 $data->site->closed = poco_to_boolean($data->site->closed);
822                                 $data->site->private = poco_to_boolean($data->site->private);
823                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
824
825                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
826                                         $register_policy = REGISTER_APPROVE;
827                                 elseif (!$data->site->closed AND !$data->site->private)
828                                         $register_policy = REGISTER_OPEN;
829                                 else
830                                         $register_policy = REGISTER_CLOSED;
831                         }
832                 }
833         }
834
835         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
836         if (!$failure) {
837                 $serverret = z_fetch_url($server_url."/statistics.json");
838                 if ($serverret["success"]) {
839                         $data = json_decode($serverret["body"]);
840                         if ($version == "")
841                                 $version = $data->version;
842
843                         $site_name = $data->name;
844
845                         if (isset($data->network) AND ($platform == ""))
846                                 $platform = $data->network;
847
848                         if ($platform == "Diaspora")
849                                 $network = NETWORK_DIASPORA;
850
851                         if ($data->registrations_open)
852                                 $register_policy = REGISTER_OPEN;
853                         else
854                                 $register_policy = REGISTER_CLOSED;
855
856                         if (isset($data->version))
857                                 $last_contact = datetime_convert();
858                 }
859         }
860
861         // Check for noscrape
862         // Friendica servers could be detected as OStatus servers
863         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
864                 $serverret = z_fetch_url($server_url."/friendica/json");
865
866                 if (!$serverret["success"])
867                         $serverret = z_fetch_url($server_url."/friendika/json");
868
869                 if ($serverret["success"]) {
870                         $data = json_decode($serverret["body"]);
871
872                         if (isset($data->version)) {
873                                 $last_contact = datetime_convert();
874                                 $network = NETWORK_DFRN;
875
876                                 $noscrape = $data->no_scrape_url;
877                                 $version = $data->version;
878                                 $site_name = $data->site_name;
879                                 $info = $data->info;
880                                 $register_policy_str = $data->register_policy;
881                                 $platform = $data->platform;
882
883                                 switch ($register_policy_str) {
884                                         case "REGISTER_CLOSED":
885                                                 $register_policy = REGISTER_CLOSED;
886                                                 break;
887                                         case "REGISTER_APPROVE":
888                                                 $register_policy = REGISTER_APPROVE;
889                                                 break;
890                                         case "REGISTER_OPEN":
891                                                 $register_policy = REGISTER_OPEN;
892                                                 break;
893                                 }
894                         }
895                 }
896         }
897
898         // Look for poco
899         if (!$failure) {
900                 $serverret = z_fetch_url($server_url."/poco");
901                 if ($serverret["success"]) {
902                         $data = json_decode($serverret["body"]);
903                         if (isset($data->totalResults)) {
904                                 $poco = $server_url."/poco";
905                                 $last_contact = datetime_convert();
906                         }
907                 }
908         }
909
910         // Check again if the server exists
911         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
912
913         if ($servers)
914                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
915                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
916                         dbesc($server_url),
917                         dbesc($version),
918                         dbesc($site_name),
919                         dbesc($info),
920                         intval($register_policy),
921                         dbesc($poco),
922                         dbesc($noscrape),
923                         dbesc($network),
924                         dbesc($platform),
925                         dbesc($last_contact),
926                         dbesc($last_failure),
927                         dbesc(normalise_link($server_url))
928                 );
929         else
930                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
931                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
932                                 dbesc($server_url),
933                                 dbesc(normalise_link($server_url)),
934                                 dbesc($version),
935                                 dbesc($site_name),
936                                 dbesc($info),
937                                 intval($register_policy),
938                                 dbesc($poco),
939                                 dbesc($noscrape),
940                                 dbesc($network),
941                                 dbesc($platform),
942                                 dbesc(datetime_convert()),
943                                 dbesc($last_contact),
944                                 dbesc($last_failure),
945                                 dbesc(datetime_convert())
946                 );
947
948         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
949
950         return !$failure;
951 }
952
953 function poco_contact_from_body($body, $created, $cid, $uid) {
954         preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
955                 function ($match) use ($created, $cid, $uid){
956                         return(sub_poco_from_share($match, $created, $cid, $uid));
957                 }, $body);
958 }
959
960 function sub_poco_from_share($share, $created, $cid, $uid) {
961         $profile = "";
962         preg_match("/profile='(.*?)'/ism", $share[1], $matches);
963         if ($matches[1] != "")
964                 $profile = $matches[1];
965
966         preg_match('/profile="(.*?)"/ism', $share[1], $matches);
967         if ($matches[1] != "")
968                 $profile = $matches[1];
969
970         if ($profile == "")
971                 return;
972
973         logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
974         poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
975 }
976
977 function poco_store($item) {
978
979         // Isn't it public?
980         if ($item['private'])
981                 return;
982
983         // Or is it from a network where we don't store the global contacts?
984         if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
985                 return;
986
987         // Is it a global copy?
988         $store_gcontact = ($item["uid"] == 0);
989
990         // Is it a comment on a global copy?
991         if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
992                 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
993                 $store_gcontact = count($q);
994         }
995
996         if (!$store_gcontact)
997                 return;
998
999         // "3" means: We don't know this contact directly (Maybe a reshared item)
1000         $generation = 3;
1001         $network = "";
1002         $profile_url = $item["author-link"];
1003
1004         // Is it a user from our server?
1005         $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
1006                 dbesc(normalise_link($item["author-link"])));
1007         if (count($q)) {
1008                 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
1009                 $generation = 1;
1010                 $network = NETWORK_DFRN;
1011         } else { // Is it a contact from a user on our server?
1012                 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
1013                         AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
1014                         dbesc(normalise_link($item["author-link"])),
1015                         dbesc(normalise_link($item["author-link"])),
1016                         dbesc($item["author-link"]),
1017                         dbesc(NETWORK_STATUSNET));
1018                 if (count($q)) {
1019                         $generation = 2;
1020                         $network = $q[0]["network"];
1021                         $profile_url = $q[0]["url"];
1022                         logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
1023                 }
1024         }
1025
1026         if ($generation == 3)
1027                 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
1028
1029         poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
1030
1031         // Maybe its a body with a shared item? Then extract a global contact from it.
1032         poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1033 }
1034
1035 function count_common_friends($uid,$cid) {
1036
1037         $r = q("SELECT count(*) as `total`
1038                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1039                 where `glink`.`cid` = %d and `glink`.`uid` = %d
1040                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1041                 intval($cid),
1042                 intval($uid),
1043                 intval($uid),
1044                 intval($cid)
1045         );
1046
1047 //      logger("count_common_friends: $uid $cid {$r[0]['total']}"); 
1048         if(count($r))
1049                 return $r[0]['total'];
1050         return 0;
1051
1052 }
1053
1054
1055 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1056
1057         if($shuffle)
1058                 $sql_extra = " order by rand() ";
1059         else
1060                 $sql_extra = " order by `gcontact`.`name` asc ";
1061
1062         $r = q("SELECT `gcontact`.*
1063                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1064                 where `glink`.`cid` = %d and `glink`.`uid` = %d
1065                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) 
1066                 $sql_extra limit %d, %d",
1067                 intval($cid),
1068                 intval($uid),
1069                 intval($uid),
1070                 intval($cid),
1071                 intval($start),
1072                 intval($limit)
1073         );
1074
1075         return $r;
1076
1077 }
1078
1079
1080 function count_common_friends_zcid($uid,$zcid) {
1081
1082         $r = q("SELECT count(*) as `total`
1083                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1084                 where `glink`.`zcid` = %d
1085                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1086                 intval($zcid),
1087                 intval($uid)
1088         );
1089
1090         if(count($r))
1091                 return $r[0]['total'];
1092         return 0;
1093
1094 }
1095
1096 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1097
1098         if($shuffle)
1099                 $sql_extra = " order by rand() ";
1100         else
1101                 $sql_extra = " order by `gcontact`.`name` asc ";
1102
1103         $r = q("SELECT `gcontact`.*
1104                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1105                 where `glink`.`zcid` = %d
1106                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) 
1107                 $sql_extra limit %d, %d",
1108                 intval($zcid),
1109                 intval($uid),
1110                 intval($start),
1111                 intval($limit)
1112         );
1113
1114         return $r;
1115
1116 }
1117
1118
1119 function count_all_friends($uid,$cid) {
1120
1121         $r = q("SELECT count(*) as `total`
1122                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1123                 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
1124                 intval($cid),
1125                 intval($uid)
1126         );
1127
1128         if(count($r))
1129                 return $r[0]['total'];
1130         return 0;
1131
1132 }
1133
1134
1135 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1136
1137         $r = q("SELECT `gcontact`.*
1138                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1139                 where `glink`.`cid` = %d and `glink`.`uid` = %d
1140                 order by `gcontact`.`name` asc LIMIT %d, %d ",
1141                 intval($cid),
1142                 intval($uid),
1143                 intval($start),
1144                 intval($limit)
1145         );
1146
1147         return $r;
1148 }
1149
1150
1151
1152 function suggestion_query($uid, $start = 0, $limit = 80) {
1153
1154         if(! $uid)
1155                 return array();
1156
1157         $network = array(NETWORK_DFRN);
1158
1159         if (get_config('system','diaspora_enabled'))
1160                 $network[] = NETWORK_DIASPORA;
1161
1162         if (!get_config('system','ostatus_disabled'))
1163                 $network[] = NETWORK_OSTATUS;
1164
1165         $sql_network = implode("', '", $network);
1166         //$sql_network = "'".$sql_network."', ''";
1167         $sql_network = "'".$sql_network."'";
1168
1169         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1170                 INNER JOIN glink on glink.gcid = gcontact.id
1171                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1172                 and not gcontact.name in ( select name from contact where uid = %d )
1173                 and not gcontact.id in ( select gcid from gcign where uid = %d )
1174                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1175                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1176                 AND `gcontact`.`network` IN (%s)
1177                 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
1178                 intval($uid),
1179                 intval($uid),
1180                 intval($uid),
1181                 intval($uid),
1182                 $sql_network,
1183                 intval($start),
1184                 intval($limit)
1185         );
1186
1187         if(count($r) && count($r) >= ($limit -1))
1188                 return $r;
1189
1190         $r2 = q("SELECT gcontact.* from gcontact
1191                 INNER JOIN glink on glink.gcid = gcontact.id
1192                 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
1193                 and not gcontact.name in ( select name from contact where uid = %d )
1194                 and not gcontact.id in ( select gcid from gcign where uid = %d )
1195                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1196                 AND `gcontact`.`network` IN (%s)
1197                 order by rand() limit %d, %d ",
1198                 intval($uid),
1199                 intval($uid),
1200                 intval($uid),
1201                 $sql_network,
1202                 intval($start),
1203                 intval($limit)
1204         );
1205
1206         $list = array();
1207         foreach ($r2 AS $suggestion)
1208                 $list[$suggestion["nurl"]] = $suggestion;
1209
1210         foreach ($r AS $suggestion)
1211                 $list[$suggestion["nurl"]] = $suggestion;
1212
1213         return $list;
1214 }
1215
1216 function update_suggestions() {
1217
1218         $a = get_app();
1219
1220         $done = array();
1221
1222         // To-Do: Check if it is really neccessary to poll the own server
1223         poco_load(0,0,0,$a->get_baseurl() . '/poco');
1224
1225         $done[] = $a->get_baseurl() . '/poco';
1226
1227         if(strlen(get_config('system','directory_submit_url'))) {
1228                 $x = fetch_url(get_server()."/pubsites");
1229                 if($x) {
1230                         $j = json_decode($x);
1231                         if($j->entries) {
1232                                 foreach($j->entries as $entry) {
1233
1234                                         poco_check_server($entry->url);
1235
1236                                         $url = $entry->url . '/poco';
1237                                         if(! in_array($url,$done))
1238                                                 poco_load(0,0,0,$entry->url . '/poco');
1239                                 }
1240                         }
1241                 }
1242         }
1243
1244         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1245         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1246                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1247         );
1248
1249         if(count($r)) {
1250                 foreach($r as $rr) {
1251                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1252                         if(! in_array($base,$done))
1253                                 poco_load(0,0,0,$base);
1254                 }
1255         }
1256 }
1257
1258 function poco_discover($complete = false) {
1259
1260         $no_of_queries = 5;
1261
1262         $last_update = date("c", time() - (60 * 60 * 6)); // 24
1263         $last_update = date("c", time() - (60 * 60 * 24)); // 24
1264
1265         $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));
1266         if ($r)
1267                 foreach ($r AS $server) {
1268
1269                         if (!poco_check_server($server["url"], $server["network"]))
1270                                 continue;
1271
1272                         // Fetch all users from the other server
1273                         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1274
1275                         logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1276
1277                         $retdata = z_fetch_url($url);
1278                         if ($retdata["success"]) {
1279                                 $data = json_decode($retdata["body"]);
1280
1281                                 poco_discover_server($data, 2);
1282
1283                                 if (get_config('system','poco_discovery') > 1) {
1284
1285                                         $timeframe = get_config('system','poco_discovery_since');
1286                                         if ($timeframe == 0)
1287                                                 $timeframe = 30;
1288
1289                                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1290
1291                                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1292                                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1293
1294                                         $success = false;
1295
1296                                         $retdata = z_fetch_url($url);
1297                                         if ($retdata["success"]) {
1298                                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1299                                                 $success = poco_discover_server(json_decode($retdata["body"]));
1300                                         }
1301
1302                                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1303                                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1304                                                 poco_discover_server_users($data, $server);
1305                                         }
1306                                 }
1307
1308                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1309                                 if (!$complete AND (--$no_of_queries == 0))
1310                                         break;
1311                         } else  // If the server hadn't replied correctly, then force a sanity check
1312                                 poco_check_server($server["url"], $server["network"], true);
1313                 }
1314 }
1315
1316 function poco_discover_server_users($data, $server) {
1317
1318         if (!isset($data->entry))
1319                 return;
1320
1321         foreach ($data->entry AS $entry) {
1322                 $username = "";
1323                 if (isset($entry->urls)) {
1324                         foreach($entry->urls as $url)
1325                                 if($url->type == 'profile') {
1326                                         $profile_url = $url->value;
1327                                         $urlparts = parse_url($profile_url);
1328                                         $username = end(explode("/", $urlparts["path"]));
1329                                 }
1330                 }
1331                 if ($username != "") {
1332                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1333
1334                         // Fetch all contacts from a given user from the other server
1335                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1336
1337                         $retdata = z_fetch_url($url);
1338                         if ($retdata["success"])
1339                                 poco_discover_server(json_decode($retdata["body"]), 3);
1340                 }
1341         }
1342 }
1343
1344 function poco_discover_server($data, $default_generation = 0) {
1345
1346         if (!isset($data->entry) OR !count($data->entry))
1347                 return false;
1348
1349         $success = false;
1350
1351         foreach ($data->entry AS $entry) {
1352                 $profile_url = '';
1353                 $profile_photo = '';
1354                 $connect_url = '';
1355                 $name = '';
1356                 $network = '';
1357                 $updated = '0000-00-00 00:00:00';
1358                 $location = '';
1359                 $about = '';
1360                 $keywords = '';
1361                 $gender = '';
1362                 $generation = $default_generation;
1363
1364                 $name = $entry->displayName;
1365
1366                 if(isset($entry->urls)) {
1367                         foreach($entry->urls as $url) {
1368                                 if($url->type == 'profile') {
1369                                         $profile_url = $url->value;
1370                                         continue;
1371                                 }
1372                                 if($url->type == 'webfinger') {
1373                                         $connect_url = str_replace('acct:' , '', $url->value);
1374                                         continue;
1375                                 }
1376                         }
1377                 }
1378
1379                 if(isset($entry->photos)) {
1380                         foreach($entry->photos as $photo) {
1381                                 if($photo->type == 'profile') {
1382                                         $profile_photo = $photo->value;
1383                                         continue;
1384                                 }
1385                         }
1386                 }
1387
1388                 if(isset($entry->updated))
1389                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1390
1391                 if(isset($entry->network))
1392                         $network = $entry->network;
1393
1394                 if(isset($entry->currentLocation))
1395                         $location = $entry->currentLocation;
1396
1397                 if(isset($entry->aboutMe))
1398                         $about = html2bbcode($entry->aboutMe);
1399
1400                 if(isset($entry->gender))
1401                         $gender = $entry->gender;
1402
1403                 if(isset($entry->generation) AND ($entry->generation > 0))
1404                         $generation = ++$entry->generation;
1405
1406                 if(isset($entry->tags))
1407                         foreach($entry->tags as $tag)
1408                                 $keywords = implode(", ", $tag);
1409
1410                 if ($generation > 0) {
1411                         $success = true;
1412
1413                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1414                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1415                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1416                 }
1417         }
1418         return $success;
1419 }
1420 ?>