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