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