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