]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
Merge remote-tracking branch 'upstream/develop' into 1508-poco-ostatus
[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                 $network = $data["network"];
241                 $name = $data["name"];
242                 $nick = $data["nick"];
243                 $profile_url = $data["url"];
244                 $profile_photo = $data["photo"];
245                 $server_url = $data["baseurl"];
246
247                 if ($alternate AND ($network == NETWORK_OSTATUS))
248                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
249         }
250
251         if ($alternate AND ($network == NETWORK_OSTATUS))
252                 return $gcid;
253
254         if (count($x) AND ($x[0]["network"] == "") AND ($network != "")) {
255                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
256                         dbesc($network),
257                         dbesc(normalise_link($profile_url))
258                 );
259         }
260
261         if (($name == "") OR ($profile_photo == ""))
262                 return $gcid;
263
264         if (!in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
265                 return $gcid;
266
267         logger("profile-check generation: ".$generation." Network: ".$network." URL: ".$profile_url." name: ".$name." avatar: ".$profile_photo, LOGGER_DEBUG);
268
269         poco_check_server($server_url, $network);
270
271         if(count($x)) {
272                 $gcid = $x[0]['id'];
273
274                 if (($location == "") AND ($x[0]['location'] != ""))
275                         $location = $x[0]['location'];
276
277                 if (($about == "") AND ($x[0]['about'] != ""))
278                         $about = $x[0]['about'];
279
280                 if (($gender == "") AND ($x[0]['gender'] != ""))
281                         $gender = $x[0]['gender'];
282
283                 if (($keywords == "") AND ($x[0]['keywords'] != ""))
284                         $keywords = $x[0]['keywords'];
285
286                 if (($generation == 0) AND ($x[0]['generation'] > 0))
287                         $generation = $x[0]['generation'];
288
289                 if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
290                         q("UPDATE `gcontact` SET `name` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
291                                 `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d
292                                 WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
293                                 dbesc($name),
294                                 dbesc($network),
295                                 dbesc($profile_photo),
296                                 dbesc($connect_url),
297                                 dbesc($profile_url),
298                                 dbesc($server_url),
299                                 dbesc($updated),
300                                 dbesc($location),
301                                 dbesc($about),
302                                 dbesc($keywords),
303                                 dbesc($gender),
304                                 intval($generation),
305                                 intval($generation),
306                                 dbesc(normalise_link($profile_url))
307                         );
308                 }
309         } else {
310                 q("INSERT INTO `gcontact` (`name`, `nick`, `network`, `url`, `nurl`, `photo`, `connect`, `server_url`, `created`, `updated`, `location`, `about`, `keywords`, `gender`, `generation`)
311                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
312                         dbesc($name),
313                         dbesc($nick),
314                         dbesc($network),
315                         dbesc($profile_url),
316                         dbesc(normalise_link($profile_url)),
317                         dbesc($profile_photo),
318                         dbesc($connect_url),
319                         dbesc($server_url),
320                         dbesc(datetime_convert()),
321                         dbesc($updated),
322                         dbesc($location),
323                         dbesc($about),
324                         dbesc($keywords),
325                         dbesc($gender),
326                         intval($generation)
327                 );
328                 $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
329                         dbesc(normalise_link($profile_url))
330                 );
331                 if(count($x))
332                         $gcid = $x[0]['id'];
333         }
334
335         if(! $gcid)
336                 return $gcid;
337
338         $r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
339                 intval($cid),
340                 intval($uid),
341                 intval($gcid),
342                 intval($zcid)
343         );
344         if(! count($r)) {
345                 q("INSERT INTO `glink` (`cid`,`uid`,`gcid`,`zcid`, `updated`) VALUES (%d,%d,%d,%d, '%s') ",
346                         intval($cid),
347                         intval($uid),
348                         intval($gcid),
349                         intval($zcid),
350                         dbesc(datetime_convert())
351                 );
352         } else {
353                 q("UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
354                         dbesc(datetime_convert()),
355                         intval($cid),
356                         intval($uid),
357                         intval($gcid),
358                         intval($zcid)
359                 );
360         }
361
362         // For unknown reasons there are sometimes duplicates
363         q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
364                 NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
365                 dbesc(normalise_link($profile_url)),
366                 intval($gcid)
367         );
368
369         return $gcid;
370 }
371
372 function poco_reachable($profile, $server = "", $network = "", $force = false) {
373
374         if ($server == "")
375                 $server = poco_detect_server($profile);
376
377         if ($server == "")
378                 return true;
379
380         return poco_check_server($server, $network, $force);
381 }
382
383 function poco_detect_server($profile) {
384
385         // Try to detect the server path based upon some known standard paths
386         $server_url = "";
387
388         if ($server_url == "") {
389                 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
390                 if ($friendica != $profile) {
391                         $server_url = $friendica;
392                         $network = NETWORK_DFRN;
393                 }
394         }
395
396         if ($server_url == "") {
397                 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
398                 if ($diaspora != $profile) {
399                         $server_url = $diaspora;
400                         $network = NETWORK_DIASPORA;
401                 }
402         }
403
404         if ($server_url == "") {
405                 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
406                 if ($red != $profile) {
407                         $server_url = $red;
408                         $network = NETWORK_DIASPORA;
409                 }
410         }
411
412         return $server_url;
413 }
414
415 function poco_alternate_ostatus_url($url) {
416         return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
417 }
418
419 function poco_last_updated($profile, $force = false) {
420
421         $gcontacts = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
422                         dbesc(normalise_link($profile)));
423
424         if ($gcontacts[0]["created"] == "0000-00-00 00:00:00")
425                 q("UPDATE `gcontact` SET `created` = '%s' WHERE `nurl` = '%s'",
426                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
427
428         if ($gcontacts[0]["server_url"] != "")
429                 $server_url = $gcontacts[0]["server_url"];
430         else
431                 $server_url = poco_detect_server($profile);
432
433         if ($server_url != "") {
434                 if (!poco_check_server($server_url, $gcontacts[0]["network"], $force)) {
435
436                         if ($force)
437                                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
438                                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
439
440                         return false;
441                 }
442
443                 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
444                         dbesc($server_url), dbesc(normalise_link($profile)));
445         }
446
447         if (in_array($gcontacts[0]["network"], array("", NETWORK_FEED))) {
448                 $server = q("SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
449                         dbesc(normalise_link($server_url)));
450
451                 if ($server)
452                         q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
453                                 dbesc($server[0]["network"]), dbesc(normalise_link($profile)));
454                 else
455                         return;
456         }
457
458         // noscrape is really fast so we don't cache the call.
459         if (($gcontacts[0]["server_url"] != "") AND ($gcontacts[0]["nick"] != "")) {
460
461                 //  Use noscrape if possible
462                 $server = q("SELECT `noscrape` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", dbesc(normalise_link($gcontacts[0]["server_url"])));
463
464                 if ($server) {
465                         $noscraperet = z_fetch_url($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
466
467                          if ($noscraperet["success"] AND ($noscraperet["body"] != "")) {
468
469                                 $noscrape = json_decode($noscraperet["body"], true);
470
471                                 if (($noscrape["fn"] != "") AND ($noscrape["fn"] != $gcontacts[0]["name"]))
472                                         q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
473                                                 dbesc($noscrape["fn"]), dbesc(normalise_link($profile)));
474
475                                 if (($noscrape["photo"] != "") AND ($noscrape["photo"] != $gcontacts[0]["photo"]))
476                                         q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
477                                                 dbesc($noscrape["photo"]), dbesc(normalise_link($profile)));
478
479                                 if (($noscrape["updated"] != "") AND ($noscrape["updated"] != $gcontacts[0]["updated"]))
480                                         q("UPDATE `gcontact` SET `updated` = '%s' WHERE `nurl` = '%s'",
481                                                 dbesc($noscrape["updated"]), dbesc(normalise_link($profile)));
482
483                                 if (($noscrape["gender"] != "") AND ($noscrape["gender"] != $gcontacts[0]["gender"]))
484                                         q("UPDATE `gcontact` SET `gender` = '%s' WHERE `nurl` = '%s'",
485                                                 dbesc($noscrape["gender"]), dbesc(normalise_link($profile)));
486
487                                 if (($noscrape["pdesc"] != "") AND ($noscrape["pdesc"] != $gcontacts[0]["about"]))
488                                         q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
489                                                 dbesc($noscrape["pdesc"]), dbesc(normalise_link($profile)));
490
491                                 if (($noscrape["about"] != "") AND ($noscrape["about"] != $gcontacts[0]["about"]))
492                                         q("UPDATE `gcontact` SET `about` = '%s' WHERE `nurl` = '%s'",
493                                                 dbesc($noscrape["about"]), dbesc(normalise_link($profile)));
494
495                                 if (isset($noscrape["comm"]) AND ($noscrape["comm"] != $gcontacts[0]["community"]))
496                                         q("UPDATE `gcontact` SET `community` = %d WHERE `nurl` = '%s'",
497                                                 intval($noscrape["comm"]), dbesc(normalise_link($profile)));
498
499                                 if (isset($noscrape["tags"]))
500                                         $keywords = implode(" ", $noscrape["tags"]);
501                                 else
502                                         $keywords = "";
503
504                                 if (($keywords != "") AND ($keywords != $gcontacts[0]["keywords"]))
505                                         q("UPDATE `gcontact` SET `keywords` = '%s' WHERE `nurl` = '%s'",
506                                                 dbesc($keywords), dbesc(normalise_link($profile)));
507
508                                 $location = $noscrape["locality"];
509
510                                 if ($noscrape["region"] != "") {
511                                         if ($location != "")
512                                                 $location .= ", ";
513
514                                         $location .= $noscrape["region"];
515                                 }
516
517                                 if ($noscrape["country-name"] != "") {
518                                         if ($location != "")
519                                                 $location .= ", ";
520
521                                         $location .= $noscrape["country-name"];
522                                 }
523
524                                 if (($location != "") AND ($location != $gcontacts[0]["location"]))
525                                         q("UPDATE `gcontact` SET `location` = '%s' WHERE `nurl` = '%s'",
526                                                 dbesc($location), dbesc(normalise_link($profile)));
527
528                                 // If we got data from noscrape then mark the contact as reachable
529                                 if (is_array($noscrape) AND count($noscrape))
530                                         q("UPDATE `gcontact` SET `last_contact` = '%s' WHERE `nurl` = '%s'",
531                                                 dbesc(datetime_convert()), dbesc(normalise_link($profile)));
532
533                                 return $noscrape["updated"];
534                         }
535                 }
536         }
537
538         // If we only can poll the feed, then we only do this once a while
539         if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"],  $gcontacts[0]["last_contact"]))
540                 return $gcontacts[0]["updated"];
541
542         $data = probe_url($profile);
543
544         // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
545         // Then check the other link and delete this one
546         if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
547                 (normalise_link($profile) == normalise_link($data["alias"])) AND
548                 (normalise_link($profile) != normalise_link($data["url"]))) {
549
550                 // Delete the old entry
551                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
552                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
553
554                 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
555                                 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
556
557                 poco_last_updated($data["url"], $force);
558
559                 return false;
560         }
561
562         if (($data["poll"] == "") OR ($data["network"] == NETWORK_FEED)) {
563                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
564                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
565                 return false;
566         }
567
568         if (($data["name"] != "") AND ($data["name"] != $gcontacts[0]["name"]))
569                 q("UPDATE `gcontact` SET `name` = '%s' WHERE `nurl` = '%s'",
570                         dbesc($data["name"]), dbesc(normalise_link($profile)));
571
572         if (($data["nick"] != "") AND ($data["nick"] != $gcontacts[0]["nick"]))
573                 q("UPDATE `gcontact` SET `nick` = '%s' WHERE `nurl` = '%s'",
574                         dbesc($data["nick"]), dbesc(normalise_link($profile)));
575
576         if (($data["addr"] != "") AND ($data["addr"] != $gcontacts[0]["connect"]))
577                 q("UPDATE `gcontact` SET `connect` = '%s' WHERE `nurl` = '%s'",
578                         dbesc($data["addr"]), dbesc(normalise_link($profile)));
579
580         if (($data["photo"] != "") AND ($data["photo"] != $gcontacts[0]["photo"]))
581                 q("UPDATE `gcontact` SET `photo` = '%s' WHERE `nurl` = '%s'",
582                         dbesc($data["photo"]), dbesc(normalise_link($profile)));
583
584         if (($data["baseurl"] != "") AND ($data["baseurl"] != $gcontacts[0]["server_url"]))
585                 q("UPDATE `gcontact` SET `server_url` = '%s' WHERE `nurl` = '%s'",
586                         dbesc($data["baseurl"]), dbesc(normalise_link($profile)));
587
588         $feedret = z_fetch_url($data["poll"]);
589
590         if (!$feedret["success"]) {
591                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
592                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
593                 return false;
594         }
595
596         $doc = new DOMDocument();
597         @$doc->loadXML($feedret["body"]);
598
599         $xpath = new DomXPath($doc);
600         $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
601
602         $entries = $xpath->query('/atom:feed/atom:entry');
603
604         $last_updated = "";
605
606         foreach ($entries AS $entry) {
607                 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
608                 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
609
610                 if ($last_updated < $published)
611                         $last_updated = $published;
612
613                 if ($last_updated < $updated)
614                         $last_updated = $updated;
615         }
616
617         // Maybe there aren't any entries. Then check if it is a valid feed
618         if ($last_updated == "")
619                 if ($xpath->query('/atom:feed')->length > 0)
620                         $last_updated = "0000-00-00 00:00:00";
621
622         q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
623                 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
624
625         if (($gcontacts[0]["generation"] == 0))
626                 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
627                         dbesc(normalise_link($profile)));
628
629         return($last_updated);
630 }
631
632 function poco_do_update($created, $updated, $last_failure,  $last_contact) {
633         $now = strtotime(datetime_convert());
634
635         if ($updated > $last_contact)
636                 $contact_time = strtotime($updated);
637         else
638                 $contact_time = strtotime($last_contact);
639
640         $failure_time = strtotime($last_failure);
641         $created_time = strtotime($created);
642
643         // If there is no "created" time then use the current time
644         if ($created_time <= 0)
645                 $created_time = $now;
646
647         // If the last contact was less than 24 hours then don't update
648         if (($now - $contact_time) < (60 * 60 * 24))
649                 return false;
650
651         // If the last failure was less than 24 hours then don't update
652         if (($now - $failure_time) < (60 * 60 * 24))
653                 return false;
654
655         // If the last contact was less than a week ago and the last failure is older than a week then don't update
656         //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
657         //      return false;
658
659         // 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
660         if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
661                 return false;
662
663         // 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
664         if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
665                 return false;
666
667         return true;
668 }
669
670 function poco_to_boolean($val) {
671         if (($val == "true") OR ($val == 1))
672                 return(true);
673         if (($val == "false") OR ($val == 0))
674                 return(false);
675
676         return ($val);
677 }
678
679 function poco_check_server($server_url, $network = "", $force = false) {
680
681         if ($server_url == "")
682                 return false;
683
684         $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
685         if ($servers) {
686
687                 if ($servers[0]["created"] == "0000-00-00 00:00:00")
688                         q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
689                                 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
690
691                 $poco = $servers[0]["poco"];
692                 $noscrape = $servers[0]["noscrape"];
693
694                 if ($network == "")
695                         $network = $servers[0]["network"];
696
697                 $last_contact = $servers[0]["last_contact"];
698                 $last_failure = $servers[0]["last_failure"];
699                 $version = $servers[0]["version"];
700                 $platform = $servers[0]["platform"];
701                 $site_name = $servers[0]["site_name"];
702                 $info = $servers[0]["info"];
703                 $register_policy = $servers[0]["register_policy"];
704
705                 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
706                         logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
707                         return ($last_contact >= $last_failure);
708                 }
709         } else {
710                 $poco = "";
711                 $noscrape = "";
712                 $version = "";
713                 $platform = "";
714                 $site_name = "";
715                 $info = "";
716                 $register_policy = -1;
717
718                 $last_contact = "0000-00-00 00:00:00";
719                 $last_failure = "0000-00-00 00:00:00";
720         }
721         logger("Server ".$server_url." is unknown. Start discovery.", LOGGER_DEBUG);
722
723         $failure = false;
724         $orig_last_failure = $last_failure;
725
726         // Check if the page is accessible via SSL.
727         $server_url = str_replace("http://", "https://", $server_url);
728         $serverret = z_fetch_url($server_url."/.well-known/host-meta");
729
730         // Maybe the page is unencrypted only?
731         $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
732         if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
733                 $server_url = str_replace("https://", "http://", $server_url);
734                 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
735
736                 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
737         }
738
739         if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
740                 $last_failure = datetime_convert();
741                 $failure = true;
742         } elseif ($network == NETWORK_DIASPORA)
743                 $last_contact = datetime_convert();
744
745         if (!$failure) {
746                 // Test for Diaspora
747                 $serverret = z_fetch_url($server_url);
748
749                 $lines = explode("\n",$serverret["header"]);
750                 if(count($lines))
751                         foreach($lines as $line) {
752                                 $line = trim($line);
753                                 if(stristr($line,'X-Diaspora-Version:')) {
754                                         $platform = "Diaspora";
755                                         $version = trim(str_replace("X-Diaspora-Version:", "", $line));
756                                         $version = trim(str_replace("x-diaspora-version:", "", $version));
757                                         $network = NETWORK_DIASPORA;
758                                 }
759                         }
760         }
761
762         if (!$failure) {
763                 // Test for Statusnet
764                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
765                 // The "not implemented" is a special treatment for really, really old Friendica versions
766                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
767                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
768                         $platform = "StatusNet";
769                         $version = trim($serverret["body"], '"');
770                         $network = NETWORK_OSTATUS;
771                 }
772
773                 // Test for GNU Social
774                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
775                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
776                         $platform = "GNU Social";
777                         $version = trim($serverret["body"], '"');
778                         $network = NETWORK_OSTATUS;
779                 }
780
781                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
782                 if ($serverret["success"]) {
783                         $data = json_decode($serverret["body"]);
784
785                         if (isset($data->site->server)) {
786                                 $last_contact = datetime_convert();
787
788                                 if (isset($data->site->hubzilla)) {
789                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
790                                         $version = $data->site->hubzilla->RED_VERSION;
791                                         $network = NETWORK_DIASPORA;
792                                 }
793                                 if (isset($data->site->redmatrix)) {
794                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
795                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
796                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
797                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
798
799                                         $version = $data->site->redmatrix->RED_VERSION;
800                                         $network = NETWORK_DIASPORA;
801                                 }
802                                 if (isset($data->site->friendica)) {
803                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
804                                         $version = $data->site->friendica->FRIENDICA_VERSION;
805                                         $network = NETWORK_DFRN;
806                                 }
807
808                                 $site_name = $data->site->name;
809
810                                 $data->site->closed = poco_to_boolean($data->site->closed);
811                                 $data->site->private = poco_to_boolean($data->site->private);
812                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
813
814                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
815                                         $register_policy = REGISTER_APPROVE;
816                                 elseif (!$data->site->closed AND !$data->site->private)
817                                         $register_policy = REGISTER_OPEN;
818                                 else
819                                         $register_policy = REGISTER_CLOSED;
820                         }
821                 }
822         }
823
824         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
825         if (!$failure) {
826                 $serverret = z_fetch_url($server_url."/statistics.json");
827                 if ($serverret["success"]) {
828                         $data = json_decode($serverret["body"]);
829                         if ($version == "")
830                                 $version = $data->version;
831
832                         $site_name = $data->name;
833
834                         if (isset($data->network) AND ($platform == ""))
835                                 $platform = $data->network;
836
837                         if ($platform == "Diaspora")
838                                 $network = NETWORK_DIASPORA;
839
840                         if ($data->registrations_open)
841                                 $register_policy = REGISTER_OPEN;
842                         else
843                                 $register_policy = REGISTER_CLOSED;
844
845                         if (isset($data->version))
846                                 $last_contact = datetime_convert();
847                 }
848         }
849
850         // Check for noscrape
851         // Friendica servers could be detected as OStatus servers
852         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
853                 $serverret = z_fetch_url($server_url."/friendica/json");
854
855                 if (!$serverret["success"])
856                         $serverret = z_fetch_url($server_url."/friendika/json");
857
858                 if ($serverret["success"]) {
859                         $data = json_decode($serverret["body"]);
860
861                         if (isset($data->version)) {
862                                 $last_contact = datetime_convert();
863                                 $network = NETWORK_DFRN;
864
865                                 $noscrape = $data->no_scrape_url;
866                                 $version = $data->version;
867                                 $site_name = $data->site_name;
868                                 $info = $data->info;
869                                 $register_policy_str = $data->register_policy;
870                                 $platform = $data->platform;
871
872                                 switch ($register_policy_str) {
873                                         case "REGISTER_CLOSED":
874                                                 $register_policy = REGISTER_CLOSED;
875                                                 break;
876                                         case "REGISTER_APPROVE":
877                                                 $register_policy = REGISTER_APPROVE;
878                                                 break;
879                                         case "REGISTER_OPEN":
880                                                 $register_policy = REGISTER_OPEN;
881                                                 break;
882                                 }
883                         }
884                 }
885         }
886
887         // Look for poco
888         if (!$failure) {
889                 $serverret = z_fetch_url($server_url."/poco");
890                 if ($serverret["success"]) {
891                         $data = json_decode($serverret["body"]);
892                         if (isset($data->totalResults)) {
893                                 $poco = $server_url."/poco";
894                                 $last_contact = datetime_convert();
895                         }
896                 }
897         }
898
899         // Check again if the server exists
900         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
901
902         if ($servers)
903                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
904                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
905                         dbesc($server_url),
906                         dbesc($version),
907                         dbesc($site_name),
908                         dbesc($info),
909                         intval($register_policy),
910                         dbesc($poco),
911                         dbesc($noscrape),
912                         dbesc($network),
913                         dbesc($platform),
914                         dbesc($last_contact),
915                         dbesc($last_failure),
916                         dbesc(normalise_link($server_url))
917                 );
918         else
919                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
920                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
921                                 dbesc($server_url),
922                                 dbesc(normalise_link($server_url)),
923                                 dbesc($version),
924                                 dbesc($site_name),
925                                 dbesc($info),
926                                 intval($register_policy),
927                                 dbesc($poco),
928                                 dbesc($noscrape),
929                                 dbesc($network),
930                                 dbesc($platform),
931                                 dbesc(datetime_convert()),
932                                 dbesc($last_contact),
933                                 dbesc($last_failure),
934                                 dbesc(datetime_convert())
935                 );
936
937         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
938
939         return !$failure;
940 }
941
942 function poco_contact_from_body($body, $created, $cid, $uid) {
943         preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
944                 function ($match) use ($created, $cid, $uid){
945                         return(sub_poco_from_share($match, $created, $cid, $uid));
946                 }, $body);
947 }
948
949 function sub_poco_from_share($share, $created, $cid, $uid) {
950         $profile = "";
951         preg_match("/profile='(.*?)'/ism", $share[1], $matches);
952         if ($matches[1] != "")
953                 $profile = $matches[1];
954
955         preg_match('/profile="(.*?)"/ism', $share[1], $matches);
956         if ($matches[1] != "")
957                 $profile = $matches[1];
958
959         if ($profile == "")
960                 return;
961
962         logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
963         poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
964 }
965
966 function poco_store($item) {
967
968         // Isn't it public?
969         if ($item['private'])
970                 return;
971
972         // Or is it from a network where we don't store the global contacts?
973         if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
974                 return;
975
976         // Is it a global copy?
977         $store_gcontact = ($item["uid"] == 0);
978
979         // Is it a comment on a global copy?
980         if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
981                 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
982                 $store_gcontact = count($q);
983         }
984
985         if (!$store_gcontact)
986                 return;
987
988         // "3" means: We don't know this contact directly (Maybe a reshared item)
989         $generation = 3;
990         $network = "";
991         $profile_url = $item["author-link"];
992
993         // Is it a user from our server?
994         $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
995                 dbesc(normalise_link($item["author-link"])));
996         if (count($q)) {
997                 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
998                 $generation = 1;
999                 $network = NETWORK_DFRN;
1000         } else { // Is it a contact from a user on our server?
1001                 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
1002                         AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
1003                         dbesc(normalise_link($item["author-link"])),
1004                         dbesc(normalise_link($item["author-link"])),
1005                         dbesc($item["author-link"]),
1006                         dbesc(NETWORK_STATUSNET));
1007                 if (count($q)) {
1008                         $generation = 2;
1009                         $network = $q[0]["network"];
1010                         $profile_url = $q[0]["url"];
1011                         logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
1012                 }
1013         }
1014
1015         if ($generation == 3)
1016                 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
1017
1018         poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
1019
1020         // Maybe its a body with a shared item? Then extract a global contact from it.
1021         poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1022 }
1023
1024 function count_common_friends($uid,$cid) {
1025
1026         $r = q("SELECT count(*) as `total`
1027                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1028                 where `glink`.`cid` = %d and `glink`.`uid` = %d
1029                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1030                 intval($cid),
1031                 intval($uid),
1032                 intval($uid),
1033                 intval($cid)
1034         );
1035
1036 //      logger("count_common_friends: $uid $cid {$r[0]['total']}"); 
1037         if(count($r))
1038                 return $r[0]['total'];
1039         return 0;
1040
1041 }
1042
1043
1044 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1045
1046         if($shuffle)
1047                 $sql_extra = " order by rand() ";
1048         else
1049                 $sql_extra = " order by `gcontact`.`name` asc ";
1050
1051         $r = q("SELECT `gcontact`.*
1052                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1053                 where `glink`.`cid` = %d and `glink`.`uid` = %d
1054                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) 
1055                 $sql_extra limit %d, %d",
1056                 intval($cid),
1057                 intval($uid),
1058                 intval($uid),
1059                 intval($cid),
1060                 intval($start),
1061                 intval($limit)
1062         );
1063
1064         return $r;
1065
1066 }
1067
1068
1069 function count_common_friends_zcid($uid,$zcid) {
1070
1071         $r = q("SELECT count(*) as `total`
1072                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1073                 where `glink`.`zcid` = %d
1074                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1075                 intval($zcid),
1076                 intval($uid)
1077         );
1078
1079         if(count($r))
1080                 return $r[0]['total'];
1081         return 0;
1082
1083 }
1084
1085 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1086
1087         if($shuffle)
1088                 $sql_extra = " order by rand() ";
1089         else
1090                 $sql_extra = " order by `gcontact`.`name` asc ";
1091
1092         $r = q("SELECT `gcontact`.*
1093                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1094                 where `glink`.`zcid` = %d
1095                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) 
1096                 $sql_extra limit %d, %d",
1097                 intval($zcid),
1098                 intval($uid),
1099                 intval($start),
1100                 intval($limit)
1101         );
1102
1103         return $r;
1104
1105 }
1106
1107
1108 function count_all_friends($uid,$cid) {
1109
1110         $r = q("SELECT count(*) as `total`
1111                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1112                 where `glink`.`cid` = %d and `glink`.`uid` = %d ",
1113                 intval($cid),
1114                 intval($uid)
1115         );
1116
1117         if(count($r))
1118                 return $r[0]['total'];
1119         return 0;
1120
1121 }
1122
1123
1124 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1125
1126         $r = q("SELECT `gcontact`.*
1127                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1128                 where `glink`.`cid` = %d and `glink`.`uid` = %d
1129                 order by `gcontact`.`name` asc LIMIT %d, %d ",
1130                 intval($cid),
1131                 intval($uid),
1132                 intval($start),
1133                 intval($limit)
1134         );
1135
1136         return $r;
1137 }
1138
1139
1140
1141 function suggestion_query($uid, $start = 0, $limit = 80) {
1142
1143         if(! $uid)
1144                 return array();
1145
1146         $network = array(NETWORK_DFRN);
1147
1148         if (get_config('system','diaspora_enabled'))
1149                 $network[] = NETWORK_DIASPORA;
1150
1151         if (!get_config('system','ostatus_disabled'))
1152                 $network[] = NETWORK_OSTATUS;
1153
1154         $sql_network = implode("', '", $network);
1155         //$sql_network = "'".$sql_network."', ''";
1156         $sql_network = "'".$sql_network."'";
1157
1158         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1159                 INNER JOIN glink on glink.gcid = gcontact.id
1160                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1161                 and not gcontact.name in ( select name from contact where uid = %d )
1162                 and not gcontact.id in ( select gcid from gcign where uid = %d )
1163                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1164                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1165                 AND `gcontact`.`network` IN (%s)
1166                 group by glink.gcid order by gcontact.updated desc,total desc limit %d, %d ",
1167                 intval($uid),
1168                 intval($uid),
1169                 intval($uid),
1170                 intval($uid),
1171                 $sql_network,
1172                 intval($start),
1173                 intval($limit)
1174         );
1175
1176         if(count($r) && count($r) >= ($limit -1))
1177                 return $r;
1178
1179         $r2 = q("SELECT gcontact.* from gcontact
1180                 INNER JOIN glink on glink.gcid = gcontact.id
1181                 where glink.uid = 0 and glink.cid = 0 and glink.zcid = 0 and not gcontact.nurl in ( select nurl from contact where uid = %d )
1182                 and not gcontact.name in ( select name from contact where uid = %d )
1183                 and not gcontact.id in ( select gcid from gcign where uid = %d )
1184                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1185                 AND `gcontact`.`network` IN (%s)
1186                 order by rand() limit %d, %d ",
1187                 intval($uid),
1188                 intval($uid),
1189                 intval($uid),
1190                 $sql_network,
1191                 intval($start),
1192                 intval($limit)
1193         );
1194
1195         $list = array();
1196         foreach ($r2 AS $suggestion)
1197                 $list[$suggestion["nurl"]] = $suggestion;
1198
1199         foreach ($r AS $suggestion)
1200                 $list[$suggestion["nurl"]] = $suggestion;
1201
1202         return $list;
1203 }
1204
1205 function update_suggestions() {
1206
1207         $a = get_app();
1208
1209         $done = array();
1210
1211         // To-Do: Check if it is really neccessary to poll the own server
1212         poco_load(0,0,0,$a->get_baseurl() . '/poco');
1213
1214         $done[] = $a->get_baseurl() . '/poco';
1215
1216         if(strlen(get_config('system','directory_submit_url'))) {
1217                 $x = fetch_url(get_server()."/pubsites");
1218                 if($x) {
1219                         $j = json_decode($x);
1220                         if($j->entries) {
1221                                 foreach($j->entries as $entry) {
1222
1223                                         poco_check_server($entry->url);
1224
1225                                         $url = $entry->url . '/poco';
1226                                         if(! in_array($url,$done))
1227                                                 poco_load(0,0,0,$entry->url . '/poco');
1228                                 }
1229                         }
1230                 }
1231         }
1232
1233         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1234         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1235                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1236         );
1237
1238         if(count($r)) {
1239                 foreach($r as $rr) {
1240                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1241                         if(! in_array($base,$done))
1242                                 poco_load(0,0,0,$base);
1243                 }
1244         }
1245 }
1246
1247 function poco_discover($complete = false) {
1248
1249         $no_of_queries = 5;
1250
1251         $last_update = date("c", time() - (60 * 60 * 6)); // 24
1252         $last_update = date("c", time() - (60 * 60 * 24)); // 24
1253
1254         $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));
1255         if ($r)
1256                 foreach ($r AS $server) {
1257
1258                         if (!poco_check_server($server["url"], $server["network"]))
1259                                 continue;
1260
1261                         // Fetch all users from the other server
1262                         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1263
1264                         logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1265
1266                         $retdata = z_fetch_url($url);
1267                         if ($retdata["success"]) {
1268                                 $data = json_decode($retdata["body"]);
1269
1270                                 poco_discover_server($data, 2);
1271
1272                                 if (get_config('system','poco_discovery') > 1) {
1273
1274                                         $timeframe = get_config('system','poco_discovery_since');
1275                                         if ($timeframe == 0)
1276                                                 $timeframe = 30;
1277
1278                                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1279
1280                                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1281                                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1282
1283                                         $success = false;
1284
1285                                         $retdata = z_fetch_url($url);
1286                                         if ($retdata["success"]) {
1287                                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1288                                                 $success = poco_discover_server(json_decode($retdata["body"]));
1289                                         }
1290
1291                                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1292                                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1293                                                 poco_discover_server_users($data, $server);
1294                                         }
1295                                 }
1296
1297                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1298                                 if (!$complete AND (--$no_of_queries == 0))
1299                                         break;
1300                         } else  // If the server hadn't replied correctly, then force a sanity check
1301                                 poco_check_server($server["url"], $server["network"], true);
1302                 }
1303 }
1304
1305 function poco_discover_server_users($data, $server) {
1306
1307         if (!isset($data->entry))
1308                 return;
1309
1310         foreach ($data->entry AS $entry) {
1311                 $username = "";
1312                 if (isset($entry->urls)) {
1313                         foreach($entry->urls as $url)
1314                                 if($url->type == 'profile') {
1315                                         $profile_url = $url->value;
1316                                         $urlparts = parse_url($profile_url);
1317                                         $username = end(explode("/", $urlparts["path"]));
1318                                 }
1319                 }
1320                 if ($username != "") {
1321                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1322
1323                         // Fetch all contacts from a given user from the other server
1324                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1325
1326                         $retdata = z_fetch_url($url);
1327                         if ($retdata["success"])
1328                                 poco_discover_server(json_decode($retdata["body"]), 3);
1329                 }
1330         }
1331 }
1332
1333 function poco_discover_server($data, $default_generation = 0) {
1334
1335         if (!isset($data->entry) OR !count($data->entry))
1336                 return false;
1337
1338         $success = false;
1339
1340         foreach ($data->entry AS $entry) {
1341                 $profile_url = '';
1342                 $profile_photo = '';
1343                 $connect_url = '';
1344                 $name = '';
1345                 $network = '';
1346                 $updated = '0000-00-00 00:00:00';
1347                 $location = '';
1348                 $about = '';
1349                 $keywords = '';
1350                 $gender = '';
1351                 $generation = $default_generation;
1352
1353                 $name = $entry->displayName;
1354
1355                 if(isset($entry->urls)) {
1356                         foreach($entry->urls as $url) {
1357                                 if($url->type == 'profile') {
1358                                         $profile_url = $url->value;
1359                                         continue;
1360                                 }
1361                                 if($url->type == 'webfinger') {
1362                                         $connect_url = str_replace('acct:' , '', $url->value);
1363                                         continue;
1364                                 }
1365                         }
1366                 }
1367
1368                 if(isset($entry->photos)) {
1369                         foreach($entry->photos as $photo) {
1370                                 if($photo->type == 'profile') {
1371                                         $profile_photo = $photo->value;
1372                                         continue;
1373                                 }
1374                         }
1375                 }
1376
1377                 if(isset($entry->updated))
1378                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1379
1380                 if(isset($entry->network))
1381                         $network = $entry->network;
1382
1383                 if(isset($entry->currentLocation))
1384                         $location = $entry->currentLocation;
1385
1386                 if(isset($entry->aboutMe))
1387                         $about = html2bbcode($entry->aboutMe);
1388
1389                 if(isset($entry->gender))
1390                         $gender = $entry->gender;
1391
1392                 if(isset($entry->generation) AND ($entry->generation > 0))
1393                         $generation = ++$entry->generation;
1394
1395                 if(isset($entry->tags))
1396                         foreach($entry->tags as $tag)
1397                                 $keywords = implode(", ", $tag);
1398
1399                 if ($generation > 0) {
1400                         $success = true;
1401
1402                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1403                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1404                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1405                 }
1406         }
1407         return $success;
1408 }
1409 ?>