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