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