]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
Some small Diaspora changes
[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                                 if (is_array($noscrape)) {
442                                         $contact = array("url" => $profile,
443                                                         "network" => $server[0]["network"],
444                                                         "generation" => $gcontacts[0]["generation"]);
445
446                                         $contact["name"] = $noscrape["fn"];
447                                         $contact["community"] = $noscrape["comm"];
448
449                                         if (isset($noscrape["tags"])) {
450                                                 $keywords = implode(" ", $noscrape["tags"]);
451                                                 if ($keywords != "")
452                                                         $contact["keywords"] = $keywords;
453                                         }
454
455                                         $location = formatted_location($noscrape);
456                                         if ($location)
457                                                 $contact["location"] = $location;
458
459                                         $contact["notify"] = $noscrape["dfrn-notify"];
460
461                                         // Remove all fields that are not present in the gcontact table
462                                         unset($noscrape["fn"]);
463                                         unset($noscrape["key"]);
464                                         unset($noscrape["homepage"]);
465                                         unset($noscrape["comm"]);
466                                         unset($noscrape["tags"]);
467                                         unset($noscrape["locality"]);
468                                         unset($noscrape["region"]);
469                                         unset($noscrape["country-name"]);
470                                         unset($noscrape["contacts"]);
471                                         unset($noscrape["dfrn-request"]);
472                                         unset($noscrape["dfrn-confirm"]);
473                                         unset($noscrape["dfrn-notify"]);
474                                         unset($noscrape["dfrn-poll"]);
475
476                                         $contact = array_merge($contact, $noscrape);
477
478                                         update_gcontact($contact);
479
480                                         return $noscrape["updated"];
481                                 }
482                         }
483                 }
484         }
485
486         // If we only can poll the feed, then we only do this once a while
487         if (!$force AND !poco_do_update($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"],  $gcontacts[0]["last_contact"]))
488                 return $gcontacts[0]["updated"];
489
490         $data = probe_url($profile);
491
492         // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
493         // Then check the other link and delete this one
494         if (($data["network"] == NETWORK_OSTATUS) AND poco_alternate_ostatus_url($profile) AND
495                 (normalise_link($profile) == normalise_link($data["alias"])) AND
496                 (normalise_link($profile) != normalise_link($data["url"]))) {
497
498                 // Delete the old entry
499                 q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($profile)));
500                 q("DELETE FROM `glink` WHERE `gcid` = %d", intval($gcontacts[0]["id"]));
501
502                 poco_check($data["url"], $data["name"], $data["network"], $data["photo"], $gcontacts[0]["about"], $gcontacts[0]["location"],
503                                 $gcontacts[0]["gender"], $gcontacts[0]["keywords"], $data["addr"], $gcontacts[0]["updated"], $gcontacts[0]["generation"]);
504
505                 poco_last_updated($data["url"], $force);
506
507                 return false;
508         }
509
510         if (($data["poll"] == "") OR (in_array($data["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
511                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
512                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
513                 return false;
514         }
515
516         $contact = array("generation" => $gcontacts[0]["generation"]);
517
518         $contact = array_merge($contact, $data);
519
520         $contact["server_url"] = $data["baseurl"];
521
522         unset($contact["batch"]);
523         unset($contact["poll"]);
524         unset($contact["request"]);
525         unset($contact["confirm"]);
526         unset($contact["poco"]);
527         unset($contact["priority"]);
528         unset($contact["pubkey"]);
529         unset($contact["baseurl"]);
530
531         update_gcontact($contact);
532
533         $feedret = z_fetch_url($data["poll"]);
534
535         if (!$feedret["success"]) {
536                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
537                         dbesc(datetime_convert()), dbesc(normalise_link($profile)));
538                 return false;
539         }
540
541         $doc = new DOMDocument();
542         @$doc->loadXML($feedret["body"]);
543
544         $xpath = new DomXPath($doc);
545         $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
546
547         $entries = $xpath->query('/atom:feed/atom:entry');
548
549         $last_updated = "";
550
551         foreach ($entries AS $entry) {
552                 $published = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
553                 $updated = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
554
555                 if ($last_updated < $published)
556                         $last_updated = $published;
557
558                 if ($last_updated < $updated)
559                         $last_updated = $updated;
560         }
561
562         // Maybe there aren't any entries. Then check if it is a valid feed
563         if ($last_updated == "")
564                 if ($xpath->query('/atom:feed')->length > 0)
565                         $last_updated = "0000-00-00 00:00:00";
566
567         q("UPDATE `gcontact` SET `updated` = '%s', `last_contact` = '%s' WHERE `nurl` = '%s'",
568                 dbesc($last_updated), dbesc(datetime_convert()), dbesc(normalise_link($profile)));
569
570         if (($gcontacts[0]["generation"] == 0))
571                 q("UPDATE `gcontact` SET `generation` = 9 WHERE `nurl` = '%s'",
572                         dbesc(normalise_link($profile)));
573
574         return($last_updated);
575 }
576
577 function poco_do_update($created, $updated, $last_failure,  $last_contact) {
578         $now = strtotime(datetime_convert());
579
580         if ($updated > $last_contact)
581                 $contact_time = strtotime($updated);
582         else
583                 $contact_time = strtotime($last_contact);
584
585         $failure_time = strtotime($last_failure);
586         $created_time = strtotime($created);
587
588         // If there is no "created" time then use the current time
589         if ($created_time <= 0)
590                 $created_time = $now;
591
592         // If the last contact was less than 24 hours then don't update
593         if (($now - $contact_time) < (60 * 60 * 24))
594                 return false;
595
596         // If the last failure was less than 24 hours then don't update
597         if (($now - $failure_time) < (60 * 60 * 24))
598                 return false;
599
600         // If the last contact was less than a week ago and the last failure is older than a week then don't update
601         //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) AND ($contact_time > $failure_time))
602         //      return false;
603
604         // If the last contact time was more than a week ago and the contact was created more than a week ago, then only try once a week
605         if ((($now - $contact_time) > (60 * 60 * 24 * 7)) AND (($now - $created_time) > (60 * 60 * 24 * 7)) AND (($now - $failure_time) < (60 * 60 * 24 * 7)))
606                 return false;
607
608         // If the last contact time was more than a month ago and the contact was created more than a month ago, then only try once a month
609         if ((($now - $contact_time) > (60 * 60 * 24 * 30)) AND (($now - $created_time) > (60 * 60 * 24 * 30)) AND (($now - $failure_time) < (60 * 60 * 24 * 30)))
610                 return false;
611
612         return true;
613 }
614
615 function poco_to_boolean($val) {
616         if (($val == "true") OR ($val == 1))
617                 return(true);
618         if (($val == "false") OR ($val == 0))
619                 return(false);
620
621         return ($val);
622 }
623
624 function poco_check_server($server_url, $network = "", $force = false) {
625
626         // Unify the server address
627         $server_url = trim($server_url, "/");
628         $server_url = str_replace("/index.php", "", $server_url);
629
630         if ($server_url == "")
631                 return false;
632
633         $servers = q("SELECT * FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
634         if ($servers) {
635
636                 if ($servers[0]["created"] == "0000-00-00 00:00:00")
637                         q("UPDATE `gserver` SET `created` = '%s' WHERE `nurl` = '%s'",
638                                 dbesc(datetime_convert()), dbesc(normalise_link($server_url)));
639
640                 $poco = $servers[0]["poco"];
641                 $noscrape = $servers[0]["noscrape"];
642
643                 if ($network == "")
644                         $network = $servers[0]["network"];
645
646                 $last_contact = $servers[0]["last_contact"];
647                 $last_failure = $servers[0]["last_failure"];
648                 $version = $servers[0]["version"];
649                 $platform = $servers[0]["platform"];
650                 $site_name = $servers[0]["site_name"];
651                 $info = $servers[0]["info"];
652                 $register_policy = $servers[0]["register_policy"];
653
654                 if (!$force AND !poco_do_update($servers[0]["created"], "", $last_failure, $last_contact)) {
655                         logger("Use cached data for server ".$server_url, LOGGER_DEBUG);
656                         return ($last_contact >= $last_failure);
657                 }
658         } else {
659                 $poco = "";
660                 $noscrape = "";
661                 $version = "";
662                 $platform = "";
663                 $site_name = "";
664                 $info = "";
665                 $register_policy = -1;
666
667                 $last_contact = "0000-00-00 00:00:00";
668                 $last_failure = "0000-00-00 00:00:00";
669         }
670         logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$servers[0]["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG);
671
672         $failure = false;
673         $orig_last_failure = $last_failure;
674
675         // Check if the page is accessible via SSL.
676         $server_url = str_replace("http://", "https://", $server_url);
677         $serverret = z_fetch_url($server_url."/.well-known/host-meta");
678
679         // Maybe the page is unencrypted only?
680         $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
681         if (!$serverret["success"] OR ($serverret["body"] == "") OR (@sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
682                 $server_url = str_replace("https://", "http://", $server_url);
683                 $serverret = z_fetch_url($server_url."/.well-known/host-meta");
684
685                 $xmlobj = @simplexml_load_string($serverret["body"],'SimpleXMLElement',0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
686         }
687
688         if (!$serverret["success"] OR ($serverret["body"] == "") OR (sizeof($xmlobj) == 0) OR !is_object($xmlobj)) {
689                 // Workaround for bad configured servers (known nginx problem)
690                 if ($serverret["debug"]["http_code"] != "403") {
691                         $last_failure = datetime_convert();
692                         $failure = true;
693                 }
694         } elseif ($network == NETWORK_DIASPORA)
695                 $last_contact = datetime_convert();
696
697         if (!$failure) {
698                 // Test for Diaspora
699                 $serverret = z_fetch_url($server_url);
700
701                 if (!$serverret["success"] OR ($serverret["body"] == ""))
702                         $failure = true;
703                 else {
704                         $lines = explode("\n",$serverret["header"]);
705                         if(count($lines))
706                                 foreach($lines as $line) {
707                                         $line = trim($line);
708                                         if(stristr($line,'X-Diaspora-Version:')) {
709                                                 $platform = "Diaspora";
710                                                 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
711                                                 $version = trim(str_replace("x-diaspora-version:", "", $version));
712                                                 $network = NETWORK_DIASPORA;
713                                                 $versionparts = explode("-", $version);
714                                                 $version = $versionparts[0];
715                                         }
716                                 }
717                 }
718         }
719
720         if (!$failure) {
721                 // Test for Statusnet
722                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
723                 // The "not implemented" is a special treatment for really, really old Friendica versions
724                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
725                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
726                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
727                         $platform = "StatusNet";
728                         $version = trim($serverret["body"], '"');
729                         $network = NETWORK_OSTATUS;
730                 }
731
732                 // Test for GNU Social
733                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
734                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND
735                         ($serverret["body"] != '') AND (strlen($serverret["body"]) < 30)) {
736                         $platform = "GNU Social";
737                         $version = trim($serverret["body"], '"');
738                         $network = NETWORK_OSTATUS;
739                 }
740
741                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
742                 if ($serverret["success"]) {
743                         $data = json_decode($serverret["body"]);
744
745                         if (isset($data->site->server)) {
746                                 $last_contact = datetime_convert();
747
748                                 if (isset($data->site->hubzilla)) {
749                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
750                                         $version = $data->site->hubzilla->RED_VERSION;
751                                         $network = NETWORK_DIASPORA;
752                                 }
753                                 if (isset($data->site->redmatrix)) {
754                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
755                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
756                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
757                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
758
759                                         $version = $data->site->redmatrix->RED_VERSION;
760                                         $network = NETWORK_DIASPORA;
761                                 }
762                                 if (isset($data->site->friendica)) {
763                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
764                                         $version = $data->site->friendica->FRIENDICA_VERSION;
765                                         $network = NETWORK_DFRN;
766                                 }
767
768                                 $site_name = $data->site->name;
769
770                                 $data->site->closed = poco_to_boolean($data->site->closed);
771                                 $data->site->private = poco_to_boolean($data->site->private);
772                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
773
774                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
775                                         $register_policy = REGISTER_APPROVE;
776                                 elseif (!$data->site->closed AND !$data->site->private)
777                                         $register_policy = REGISTER_OPEN;
778                                 else
779                                         $register_policy = REGISTER_CLOSED;
780                         }
781                 }
782         }
783
784         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
785         if (!$failure) {
786                 $serverret = z_fetch_url($server_url."/statistics.json");
787                 if ($serverret["success"]) {
788                         $data = json_decode($serverret["body"]);
789                         if ($version == "")
790                                 $version = $data->version;
791
792                         $site_name = $data->name;
793
794                         if (isset($data->network) AND ($platform == ""))
795                                 $platform = $data->network;
796
797                         if ($platform == "Diaspora")
798                                 $network = NETWORK_DIASPORA;
799
800                         if ($data->registrations_open)
801                                 $register_policy = REGISTER_OPEN;
802                         else
803                                 $register_policy = REGISTER_CLOSED;
804
805                         if (isset($data->version))
806                                 $last_contact = datetime_convert();
807                 }
808         }
809
810         // Check for noscrape
811         // Friendica servers could be detected as OStatus servers
812         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
813                 $serverret = z_fetch_url($server_url."/friendica/json");
814
815                 if (!$serverret["success"])
816                         $serverret = z_fetch_url($server_url."/friendika/json");
817
818                 if ($serverret["success"]) {
819                         $data = json_decode($serverret["body"]);
820
821                         if (isset($data->version)) {
822                                 $last_contact = datetime_convert();
823                                 $network = NETWORK_DFRN;
824
825                                 $noscrape = $data->no_scrape_url;
826                                 $version = $data->version;
827                                 $site_name = $data->site_name;
828                                 $info = $data->info;
829                                 $register_policy_str = $data->register_policy;
830                                 $platform = $data->platform;
831
832                                 switch ($register_policy_str) {
833                                         case "REGISTER_CLOSED":
834                                                 $register_policy = REGISTER_CLOSED;
835                                                 break;
836                                         case "REGISTER_APPROVE":
837                                                 $register_policy = REGISTER_APPROVE;
838                                                 break;
839                                         case "REGISTER_OPEN":
840                                                 $register_policy = REGISTER_OPEN;
841                                                 break;
842                                 }
843                         }
844                 }
845         }
846
847         // Look for poco
848         if (!$failure) {
849                 $serverret = z_fetch_url($server_url."/poco");
850                 if ($serverret["success"]) {
851                         $data = json_decode($serverret["body"]);
852                         if (isset($data->totalResults)) {
853                                 $poco = $server_url."/poco";
854                                 $last_contact = datetime_convert();
855                         }
856                 }
857         }
858
859         // Check again if the server exists
860         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
861
862         $version = strip_tags($version);
863         $site_name = strip_tags($site_name);
864         $info = strip_tags($info);
865         $platform = strip_tags($platform);
866
867         if ($servers)
868                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
869                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
870                         dbesc($server_url),
871                         dbesc($version),
872                         dbesc($site_name),
873                         dbesc($info),
874                         intval($register_policy),
875                         dbesc($poco),
876                         dbesc($noscrape),
877                         dbesc($network),
878                         dbesc($platform),
879                         dbesc($last_contact),
880                         dbesc($last_failure),
881                         dbesc(normalise_link($server_url))
882                 );
883         else
884                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
885                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
886                                 dbesc($server_url),
887                                 dbesc(normalise_link($server_url)),
888                                 dbesc($version),
889                                 dbesc($site_name),
890                                 dbesc($info),
891                                 intval($register_policy),
892                                 dbesc($poco),
893                                 dbesc($noscrape),
894                                 dbesc($network),
895                                 dbesc($platform),
896                                 dbesc(datetime_convert()),
897                                 dbesc($last_contact),
898                                 dbesc($last_failure),
899                                 dbesc(datetime_convert())
900                 );
901
902         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
903
904         return !$failure;
905 }
906
907 function count_common_friends($uid,$cid) {
908
909         $r = q("SELECT count(*) as `total`
910                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
911                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
912                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
913                 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
914                 intval($cid),
915                 intval($uid),
916                 intval($uid),
917                 intval($cid)
918         );
919
920 //      logger("count_common_friends: $uid $cid {$r[0]['total']}");
921         if(count($r))
922                 return $r[0]['total'];
923         return 0;
924
925 }
926
927
928 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
929
930         if($shuffle)
931                 $sql_extra = " order by rand() ";
932         else
933                 $sql_extra = " order by `gcontact`.`name` asc ";
934
935         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
936                 FROM `glink`
937                 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
938                 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
939                 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
940                         AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
941                         AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
942                         AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
943                         $sql_extra LIMIT %d, %d",
944                 intval($cid),
945                 intval($uid),
946                 intval($uid),
947                 intval($cid),
948                 intval($start),
949                 intval($limit)
950         );
951
952         return $r;
953
954 }
955
956
957 function count_common_friends_zcid($uid,$zcid) {
958
959         $r = q("SELECT count(*) as `total`
960                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
961                 where `glink`.`zcid` = %d
962                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
963                 intval($zcid),
964                 intval($uid)
965         );
966
967         if(count($r))
968                 return $r[0]['total'];
969         return 0;
970
971 }
972
973 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
974
975         if($shuffle)
976                 $sql_extra = " order by rand() ";
977         else
978                 $sql_extra = " order by `gcontact`.`name` asc ";
979
980         $r = q("SELECT `gcontact`.*
981                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
982                 where `glink`.`zcid` = %d
983                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) 
984                 $sql_extra limit %d, %d",
985                 intval($zcid),
986                 intval($uid),
987                 intval($start),
988                 intval($limit)
989         );
990
991         return $r;
992
993 }
994
995
996 function count_all_friends($uid,$cid) {
997
998         $r = q("SELECT count(*) as `total`
999                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1000                 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1001                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1002                 intval($cid),
1003                 intval($uid)
1004         );
1005
1006         if(count($r))
1007                 return $r[0]['total'];
1008         return 0;
1009
1010 }
1011
1012
1013 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1014
1015         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1016                 FROM `glink`
1017                 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1018                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1019                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1020                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1021                 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1022                 intval($uid),
1023                 intval($cid),
1024                 intval($uid),
1025                 intval($start),
1026                 intval($limit)
1027         );
1028
1029         return $r;
1030 }
1031
1032
1033
1034 function suggestion_query($uid, $start = 0, $limit = 80) {
1035
1036         if(! $uid)
1037                 return array();
1038
1039         $network = array(NETWORK_DFRN);
1040
1041         if (get_config('system','diaspora_enabled'))
1042                 $network[] = NETWORK_DIASPORA;
1043
1044         if (!get_config('system','ostatus_disabled'))
1045                 $network[] = NETWORK_OSTATUS;
1046
1047         $sql_network = implode("', '", $network);
1048         //$sql_network = "'".$sql_network."', ''";
1049         $sql_network = "'".$sql_network."'";
1050
1051         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1052                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1053                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1054                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1055                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1056                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1057                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1058                 AND `gcontact`.`network` IN (%s)
1059                 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1060                 intval($uid),
1061                 intval($uid),
1062                 intval($uid),
1063                 intval($uid),
1064                 $sql_network,
1065                 intval($start),
1066                 intval($limit)
1067         );
1068
1069         if(count($r) && count($r) >= ($limit -1))
1070                 return $r;
1071
1072         $r2 = q("SELECT gcontact.* FROM gcontact
1073                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1074                 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1075                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1076                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1077                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1078                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1079                 AND `gcontact`.`network` IN (%s)
1080                 ORDER BY rand() LIMIT %d, %d",
1081                 intval($uid),
1082                 intval($uid),
1083                 intval($uid),
1084                 $sql_network,
1085                 intval($start),
1086                 intval($limit)
1087         );
1088
1089         $list = array();
1090         foreach ($r2 AS $suggestion)
1091                 $list[$suggestion["nurl"]] = $suggestion;
1092
1093         foreach ($r AS $suggestion)
1094                 $list[$suggestion["nurl"]] = $suggestion;
1095
1096         while (sizeof($list) > ($limit))
1097                 array_pop($list);
1098
1099         return $list;
1100 }
1101
1102 function update_suggestions() {
1103
1104         $a = get_app();
1105
1106         $done = array();
1107
1108         /// TODO Check if it is really neccessary to poll the own server
1109         poco_load(0,0,0,$a->get_baseurl() . '/poco');
1110
1111         $done[] = $a->get_baseurl() . '/poco';
1112
1113         if(strlen(get_config('system','directory'))) {
1114                 $x = fetch_url(get_server()."/pubsites");
1115                 if($x) {
1116                         $j = json_decode($x);
1117                         if($j->entries) {
1118                                 foreach($j->entries as $entry) {
1119
1120                                         poco_check_server($entry->url);
1121
1122                                         $url = $entry->url . '/poco';
1123                                         if(! in_array($url,$done))
1124                                                 poco_load(0,0,0,$entry->url . '/poco');
1125                                 }
1126                         }
1127                 }
1128         }
1129
1130         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1131         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1132                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1133         );
1134
1135         if(count($r)) {
1136                 foreach($r as $rr) {
1137                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1138                         if(! in_array($base,$done))
1139                                 poco_load(0,0,0,$base);
1140                 }
1141         }
1142 }
1143
1144 function poco_discover_federation() {
1145         $last = get_config('poco','last_federation_discovery');
1146
1147         if($last) {
1148                 $next = $last + (24 * 60 * 60);
1149                 if($next > time())
1150                         return;
1151         }
1152
1153         // Discover Friendica, Hubzilla and Diaspora servers
1154         $serverdata = fetch_url("http://the-federation.info/pods.json");
1155
1156         if ($serverdata) {
1157                 $servers = json_decode($serverdata);
1158
1159                 foreach($servers->pods AS $server)
1160                         poco_check_server("https://".$server->host);
1161         }
1162
1163         // Discover GNU Social Servers
1164         if (!get_config('system','ostatus_disabled')) {
1165                 $serverdata = "http://gstools.org/api/get_open_instances/";
1166
1167                 $result = z_fetch_url($serverdata);
1168                 if ($result["success"]) {
1169                         $servers = json_decode($result["body"]);
1170
1171                         foreach($servers->data AS $server)
1172                                 poco_check_server($server->instance_address);
1173                 }
1174         }
1175
1176         set_config('poco','last_federation_discovery', time());
1177 }
1178
1179 function poco_discover($complete = false) {
1180
1181         // Update the server list
1182         poco_discover_federation();
1183
1184         $no_of_queries = 5;
1185
1186         $requery_days = intval(get_config("system", "poco_requery_days"));
1187
1188         if ($requery_days == 0)
1189                 $requery_days = 7;
1190
1191         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1192
1193         $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));
1194         if ($r)
1195                 foreach ($r AS $server) {
1196
1197                         if (!poco_check_server($server["url"], $server["network"])) {
1198                                 // The server is not reachable? Okay, then we will try it later
1199                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1200                                 continue;
1201                         }
1202
1203                         // Fetch all users from the other server
1204                         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1205
1206                         logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1207
1208                         $retdata = z_fetch_url($url);
1209                         if ($retdata["success"]) {
1210                                 $data = json_decode($retdata["body"]);
1211
1212                                 poco_discover_server($data, 2);
1213
1214                                 if (get_config('system','poco_discovery') > 1) {
1215
1216                                         $timeframe = get_config('system','poco_discovery_since');
1217                                         if ($timeframe == 0)
1218                                                 $timeframe = 30;
1219
1220                                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1221
1222                                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1223                                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1224
1225                                         $success = false;
1226
1227                                         $retdata = z_fetch_url($url);
1228                                         if ($retdata["success"]) {
1229                                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1230                                                 $success = poco_discover_server(json_decode($retdata["body"]));
1231                                         }
1232
1233                                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1234                                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1235                                                 poco_discover_server_users($data, $server);
1236                                         }
1237                                 }
1238
1239                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1240                                 if (!$complete AND (--$no_of_queries == 0))
1241                                         break;
1242                         } else {
1243                                 // If the server hadn't replied correctly, then force a sanity check
1244                                 poco_check_server($server["url"], $server["network"], true);
1245
1246                                 // If we couldn't reach the server, we will try it some time later
1247                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1248                         }
1249                 }
1250 }
1251
1252 function poco_discover_server_users($data, $server) {
1253
1254         if (!isset($data->entry))
1255                 return;
1256
1257         foreach ($data->entry AS $entry) {
1258                 $username = "";
1259                 if (isset($entry->urls)) {
1260                         foreach($entry->urls as $url)
1261                                 if($url->type == 'profile') {
1262                                         $profile_url = $url->value;
1263                                         $urlparts = parse_url($profile_url);
1264                                         $username = end(explode("/", $urlparts["path"]));
1265                                 }
1266                 }
1267                 if ($username != "") {
1268                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1269
1270                         // Fetch all contacts from a given user from the other server
1271                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1272
1273                         $retdata = z_fetch_url($url);
1274                         if ($retdata["success"])
1275                                 poco_discover_server(json_decode($retdata["body"]), 3);
1276                 }
1277         }
1278 }
1279
1280 function poco_discover_server($data, $default_generation = 0) {
1281
1282         if (!isset($data->entry) OR !count($data->entry))
1283                 return false;
1284
1285         $success = false;
1286
1287         foreach ($data->entry AS $entry) {
1288                 $profile_url = '';
1289                 $profile_photo = '';
1290                 $connect_url = '';
1291                 $name = '';
1292                 $network = '';
1293                 $updated = '0000-00-00 00:00:00';
1294                 $location = '';
1295                 $about = '';
1296                 $keywords = '';
1297                 $gender = '';
1298                 $generation = $default_generation;
1299
1300                 $name = $entry->displayName;
1301
1302                 if(isset($entry->urls)) {
1303                         foreach($entry->urls as $url) {
1304                                 if($url->type == 'profile') {
1305                                         $profile_url = $url->value;
1306                                         continue;
1307                                 }
1308                                 if($url->type == 'webfinger') {
1309                                         $connect_url = str_replace('acct:' , '', $url->value);
1310                                         continue;
1311                                 }
1312                         }
1313                 }
1314
1315                 if(isset($entry->photos)) {
1316                         foreach($entry->photos as $photo) {
1317                                 if($photo->type == 'profile') {
1318                                         $profile_photo = $photo->value;
1319                                         continue;
1320                                 }
1321                         }
1322                 }
1323
1324                 if(isset($entry->updated))
1325                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1326
1327                 if(isset($entry->network))
1328                         $network = $entry->network;
1329
1330                 if(isset($entry->currentLocation))
1331                         $location = $entry->currentLocation;
1332
1333                 if(isset($entry->aboutMe))
1334                         $about = html2bbcode($entry->aboutMe);
1335
1336                 if(isset($entry->gender))
1337                         $gender = $entry->gender;
1338
1339                 if(isset($entry->generation) AND ($entry->generation > 0))
1340                         $generation = ++$entry->generation;
1341
1342                 if(isset($entry->tags))
1343                         foreach($entry->tags as $tag)
1344                                 $keywords = implode(", ", $tag);
1345
1346                 if ($generation > 0) {
1347                         $success = true;
1348
1349                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1350                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1351                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1352                 }
1353         }
1354         return $success;
1355 }
1356
1357 /**
1358  * @brief Removes unwanted parts from a contact url
1359  *
1360  * @param string $url Contact url
1361  * @return string Contact url with the wanted parts
1362  */
1363 function clean_contact_url($url) {
1364         $parts = parse_url($url);
1365
1366         if (!isset($parts["scheme"]) OR !isset($parts["host"]))
1367                 return $url;
1368
1369         $new_url = $parts["scheme"]."://".$parts["host"];
1370
1371         if (isset($parts["port"]))
1372                 $new_url .= ":".$parts["port"];
1373
1374         if (isset($parts["path"]))
1375                 $new_url .= $parts["path"];
1376
1377         return $new_url;
1378 }
1379
1380 /**
1381  * @brief Fetch the gcontact id, add an entry if not existed
1382  *
1383  * @param arr $contact contact array
1384  * @return bool|int Returns false if not found, integer if contact was found
1385  */
1386 function get_gcontact_id($contact) {
1387
1388         $gcontact_id = 0;
1389
1390         if ($contact["network"] == NETWORK_STATUSNET)
1391                 $contact["network"] = NETWORK_OSTATUS;
1392
1393         // Remove unwanted parts from the contact url (e.g. "?zrl=...")
1394         $contact["url"] = clean_contact_url($contact["url"]);
1395
1396         $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1397                 dbesc(normalise_link($contact["url"])));
1398
1399         if ($r)
1400                 $gcontact_id = $r[0]["id"];
1401         else {
1402                 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `generation`)
1403                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
1404                         dbesc($contact["name"]),
1405                         dbesc($contact["nick"]),
1406                         dbesc($contact["addr"]),
1407                         dbesc($contact["network"]),
1408                         dbesc($contact["url"]),
1409                         dbesc(normalise_link($contact["url"])),
1410                         dbesc($contact["photo"]),
1411                         dbesc(datetime_convert()),
1412                         dbesc(datetime_convert()),
1413                         dbesc($contact["location"]),
1414                         dbesc($contact["about"]),
1415                         intval($contact["generation"])
1416                 );
1417
1418                 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1419                         dbesc(normalise_link($contact["url"])));
1420
1421                 if ($r)
1422                         $gcontact_id = $r[0]["id"];
1423         }
1424
1425         if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1426          q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1427                 dbesc(normalise_link($contact["url"])),
1428                 intval($gcontact_id));
1429
1430         return $gcontact_id;
1431 }
1432
1433 /**
1434  * @brief Updates the gcontact table from a given array
1435  *
1436  * @param arr $contact contact array
1437  * @return bool|int Returns false if not found, integer if contact was found
1438  */
1439 function update_gcontact($contact) {
1440
1441         /// @todo update contact table as well
1442
1443         $gcontact_id = get_gcontact_id($contact);
1444
1445         if (!$gcontact_id)
1446                 return false;
1447
1448         $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1449                         `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1450                 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1451                 intval($gcontact_id));
1452
1453         // Get all field names
1454         $fields = array();
1455         foreach ($r[0] AS $field => $data)
1456                 $fields[$field] = $data;
1457
1458         unset($fields["url"]);
1459         unset($fields["updated"]);
1460
1461         // Bugfix: We had an error in the storing of keywords which lead to the "0"
1462         // This value is still transmitted via poco.
1463         if ($contact["keywords"] == "0")
1464                 unset($contact["keywords"]);
1465
1466         if ($r[0]["keywords"] == "0")
1467                 $r[0]["keywords"] = "";
1468
1469         // assign all unassigned fields from the database entry
1470         foreach ($fields AS $field => $data)
1471                 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1472                         $contact[$field] = $r[0][$field];
1473
1474         if ($contact["network"] == NETWORK_STATUSNET)
1475                 $contact["network"] = NETWORK_OSTATUS;
1476
1477         if (!isset($contact["updated"]))
1478                 $contact["updated"] = datetime_convert();
1479
1480         if ($contact["server_url"] == "") {
1481                 $server_url = $contact["url"];
1482
1483                 $server_url = matching_url($server_url, $contact["alias"]);
1484                 if ($server_url != "")
1485                         $contact["server_url"] = $server_url;
1486
1487                 $server_url = matching_url($server_url, $contact["photo"]);
1488                 if ($server_url != "")
1489                         $contact["server_url"] = $server_url;
1490
1491                 $server_url = matching_url($server_url, $contact["notify"]);
1492                 if ($server_url != "")
1493                         $contact["server_url"] = $server_url;
1494         } else
1495                 $contact["server_url"] = normalise_link($contact["server_url"]);
1496
1497         if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1498                 $hostname = str_replace("http://", "", $contact["server_url"]);
1499                 $contact["addr"] = $contact["nick"]."@".$hostname;
1500         }
1501
1502         // Check if any field changed
1503         $update = false;
1504         unset($fields["generation"]);
1505
1506         if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1507                 foreach ($fields AS $field => $data)
1508                         if ($contact[$field] != $r[0][$field]) {
1509                                 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1510                                 $update = true;
1511                         }
1512
1513                 if ($contact["generation"] < $r[0]["generation"]) {
1514                         logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1515                         $update = true;
1516                 }
1517         }
1518
1519         if ($update) {
1520                 logger("Update gcontact for ".$contact["url"]." Callstack: ".App::callstack(), LOGGER_DEBUG);
1521
1522                 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1523                                         `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1524                                         `alias` = '%s', `notify` = '%s', `url` = '%s',
1525                                         `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1526                                         `server_url` = '%s', `connect` = '%s'
1527                                 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1528                         dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1529                         dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1530                         dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1531                         intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
1532                         dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1533                         intval($contact["generation"]), dbesc($contact["updated"]),
1534                         dbesc($contact["server_url"]), dbesc($contact["connect"]),
1535                         dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1536
1537
1538                 // Now update the contact entry with the user id "0" as well.
1539                 // This is used for the shadow copies of public items.
1540                 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1541                         dbesc(normalise_link($contact["url"])));
1542
1543                 if ($r) {
1544                         logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1545
1546                         update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1547
1548                         q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1549                                                 `network` = '%s', `bd` = '%s', `gender` = '%s',
1550                                                 `keywords` = '%s', `alias` = '%s', `url` = '%s',
1551                                                 `location` = '%s', `about` = '%s'
1552                                         WHERE `id` = %d",
1553                                 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1554                                 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1555                                 dbesc($contact["keywords"]), dbesc($contact["alias"]), dbesc($contact["url"]),
1556                                 dbesc($contact["location"]), dbesc($contact["about"]), intval($r[0]["id"]));
1557                 }
1558         }
1559
1560         return $gcontact_id;
1561 }
1562
1563 /**
1564  * @brief Updates the gcontact entry from probe
1565  *
1566  * @param str $url profile link
1567  */
1568 function update_gcontact_from_probe($url) {
1569         $data = probe_url($url);
1570
1571         if ($data["network"] == NETWORK_PHANTOM)
1572                 return;
1573
1574         update_gcontact($data);
1575 }
1576
1577 /**
1578  * @brief Fetches users of given GNU Social server
1579  *
1580  * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1581  *
1582  * @param str $server Server address
1583  */
1584 function gs_fetch_users($server) {
1585
1586         logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1587
1588         $a = get_app();
1589
1590         $url = $server."/main/statistics";
1591
1592         $result = z_fetch_url($url);
1593         if (!$result["success"])
1594                 return false;
1595
1596         $statistics = json_decode($result["body"]);
1597
1598         if (is_object($statistics->config)) {
1599                 if ($statistics->config->instance_with_ssl)
1600                         $server = "https://";
1601                 else
1602                         $server = "http://";
1603
1604                 $server .= $statistics->config->instance_address;
1605
1606                 $hostname = $statistics->config->instance_address;
1607         } else {
1608                 if ($statistics->instance_with_ssl)
1609                         $server = "https://";
1610                 else
1611                         $server = "http://";
1612
1613                 $server .= $statistics->instance_address;
1614
1615                 $hostname = $statistics->instance_address;
1616         }
1617
1618         if (is_object($statistics->users))
1619                 foreach ($statistics->users AS $nick => $user) {
1620                         $profile_url = $server."/".$user->nickname;
1621
1622                         $contact = array("url" => $profile_url,
1623                                         "name" => $user->fullname,
1624                                         "addr" => $user->nickname."@".$hostname,
1625                                         "nick" => $user->nickname,
1626                                         "about" => $user->bio,
1627                                         "network" => NETWORK_OSTATUS,
1628                                         "photo" => $a->get_baseurl()."/images/person-175.jpg");
1629                         get_gcontact_id($contact);
1630                 }
1631 }
1632
1633 /**
1634  * @brief Asking GNU Social server on a regular base for their user data
1635  *
1636  */
1637 function gs_discover() {
1638
1639         $requery_days = intval(get_config("system", "poco_requery_days"));
1640
1641         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1642
1643         $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",
1644                 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1645
1646         if (!$r)
1647                 return;
1648
1649         foreach ($r AS $server) {
1650                 gs_fetch_users($server["url"]);
1651                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1652         }
1653 }
1654 ?>