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