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