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