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