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