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