]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
Avoid "array_merge" warning.
[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 ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
726                         $platform = "StatusNet";
727                         $version = trim($serverret["body"], '"');
728                         $network = NETWORK_OSTATUS;
729                 }
730
731                 // Test for GNU Social
732                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
733                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
734                         $platform = "GNU Social";
735                         $version = trim($serverret["body"], '"');
736                         $network = NETWORK_OSTATUS;
737                 }
738
739                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
740                 if ($serverret["success"]) {
741                         $data = json_decode($serverret["body"]);
742
743                         if (isset($data->site->server)) {
744                                 $last_contact = datetime_convert();
745
746                                 if (isset($data->site->hubzilla)) {
747                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
748                                         $version = $data->site->hubzilla->RED_VERSION;
749                                         $network = NETWORK_DIASPORA;
750                                 }
751                                 if (isset($data->site->redmatrix)) {
752                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
753                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
754                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
755                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
756
757                                         $version = $data->site->redmatrix->RED_VERSION;
758                                         $network = NETWORK_DIASPORA;
759                                 }
760                                 if (isset($data->site->friendica)) {
761                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
762                                         $version = $data->site->friendica->FRIENDICA_VERSION;
763                                         $network = NETWORK_DFRN;
764                                 }
765
766                                 $site_name = $data->site->name;
767
768                                 $data->site->closed = poco_to_boolean($data->site->closed);
769                                 $data->site->private = poco_to_boolean($data->site->private);
770                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
771
772                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
773                                         $register_policy = REGISTER_APPROVE;
774                                 elseif (!$data->site->closed AND !$data->site->private)
775                                         $register_policy = REGISTER_OPEN;
776                                 else
777                                         $register_policy = REGISTER_CLOSED;
778                         }
779                 }
780         }
781
782         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
783         if (!$failure) {
784                 $serverret = z_fetch_url($server_url."/statistics.json");
785                 if ($serverret["success"]) {
786                         $data = json_decode($serverret["body"]);
787                         if ($version == "")
788                                 $version = $data->version;
789
790                         $site_name = $data->name;
791
792                         if (isset($data->network) AND ($platform == ""))
793                                 $platform = $data->network;
794
795                         if ($platform == "Diaspora")
796                                 $network = NETWORK_DIASPORA;
797
798                         if ($data->registrations_open)
799                                 $register_policy = REGISTER_OPEN;
800                         else
801                                 $register_policy = REGISTER_CLOSED;
802
803                         if (isset($data->version))
804                                 $last_contact = datetime_convert();
805                 }
806         }
807
808         // Check for noscrape
809         // Friendica servers could be detected as OStatus servers
810         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
811                 $serverret = z_fetch_url($server_url."/friendica/json");
812
813                 if (!$serverret["success"])
814                         $serverret = z_fetch_url($server_url."/friendika/json");
815
816                 if ($serverret["success"]) {
817                         $data = json_decode($serverret["body"]);
818
819                         if (isset($data->version)) {
820                                 $last_contact = datetime_convert();
821                                 $network = NETWORK_DFRN;
822
823                                 $noscrape = $data->no_scrape_url;
824                                 $version = $data->version;
825                                 $site_name = $data->site_name;
826                                 $info = $data->info;
827                                 $register_policy_str = $data->register_policy;
828                                 $platform = $data->platform;
829
830                                 switch ($register_policy_str) {
831                                         case "REGISTER_CLOSED":
832                                                 $register_policy = REGISTER_CLOSED;
833                                                 break;
834                                         case "REGISTER_APPROVE":
835                                                 $register_policy = REGISTER_APPROVE;
836                                                 break;
837                                         case "REGISTER_OPEN":
838                                                 $register_policy = REGISTER_OPEN;
839                                                 break;
840                                 }
841                         }
842                 }
843         }
844
845         // Look for poco
846         if (!$failure) {
847                 $serverret = z_fetch_url($server_url."/poco");
848                 if ($serverret["success"]) {
849                         $data = json_decode($serverret["body"]);
850                         if (isset($data->totalResults)) {
851                                 $poco = $server_url."/poco";
852                                 $last_contact = datetime_convert();
853                         }
854                 }
855         }
856
857         // Check again if the server exists
858         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
859
860         if ($servers)
861                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
862                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
863                         dbesc($server_url),
864                         dbesc($version),
865                         dbesc($site_name),
866                         dbesc($info),
867                         intval($register_policy),
868                         dbesc($poco),
869                         dbesc($noscrape),
870                         dbesc($network),
871                         dbesc($platform),
872                         dbesc($last_contact),
873                         dbesc($last_failure),
874                         dbesc(normalise_link($server_url))
875                 );
876         else
877                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
878                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
879                                 dbesc($server_url),
880                                 dbesc(normalise_link($server_url)),
881                                 dbesc($version),
882                                 dbesc($site_name),
883                                 dbesc($info),
884                                 intval($register_policy),
885                                 dbesc($poco),
886                                 dbesc($noscrape),
887                                 dbesc($network),
888                                 dbesc($platform),
889                                 dbesc(datetime_convert()),
890                                 dbesc($last_contact),
891                                 dbesc($last_failure),
892                                 dbesc(datetime_convert())
893                 );
894
895         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
896
897         return !$failure;
898 }
899
900 function count_common_friends($uid,$cid) {
901
902         $r = q("SELECT count(*) as `total`
903                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
904                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
905                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
906                 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
907                 intval($cid),
908                 intval($uid),
909                 intval($uid),
910                 intval($cid)
911         );
912
913 //      logger("count_common_friends: $uid $cid {$r[0]['total']}");
914         if(count($r))
915                 return $r[0]['total'];
916         return 0;
917
918 }
919
920
921 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
922
923         if($shuffle)
924                 $sql_extra = " order by rand() ";
925         else
926                 $sql_extra = " order by `gcontact`.`name` asc ";
927
928         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
929                 FROM `glink`
930                 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
931                 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
932                 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
933                         AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
934                         AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
935                         AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
936                         $sql_extra LIMIT %d, %d",
937                 intval($cid),
938                 intval($uid),
939                 intval($uid),
940                 intval($cid),
941                 intval($start),
942                 intval($limit)
943         );
944
945         return $r;
946
947 }
948
949
950 function count_common_friends_zcid($uid,$zcid) {
951
952         $r = q("SELECT count(*) as `total`
953                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
954                 where `glink`.`zcid` = %d
955                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
956                 intval($zcid),
957                 intval($uid)
958         );
959
960         if(count($r))
961                 return $r[0]['total'];
962         return 0;
963
964 }
965
966 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
967
968         if($shuffle)
969                 $sql_extra = " order by rand() ";
970         else
971                 $sql_extra = " order by `gcontact`.`name` asc ";
972
973         $r = q("SELECT `gcontact`.*
974                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
975                 where `glink`.`zcid` = %d
976                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) 
977                 $sql_extra limit %d, %d",
978                 intval($zcid),
979                 intval($uid),
980                 intval($start),
981                 intval($limit)
982         );
983
984         return $r;
985
986 }
987
988
989 function count_all_friends($uid,$cid) {
990
991         $r = q("SELECT count(*) as `total`
992                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
993                 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
994                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
995                 intval($cid),
996                 intval($uid)
997         );
998
999         if(count($r))
1000                 return $r[0]['total'];
1001         return 0;
1002
1003 }
1004
1005
1006 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1007
1008         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1009                 FROM `glink`
1010                 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1011                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1012                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1013                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1014                 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1015                 intval($uid),
1016                 intval($cid),
1017                 intval($uid),
1018                 intval($start),
1019                 intval($limit)
1020         );
1021
1022         return $r;
1023 }
1024
1025
1026
1027 function suggestion_query($uid, $start = 0, $limit = 80) {
1028
1029         if(! $uid)
1030                 return array();
1031
1032         $network = array(NETWORK_DFRN);
1033
1034         if (get_config('system','diaspora_enabled'))
1035                 $network[] = NETWORK_DIASPORA;
1036
1037         if (!get_config('system','ostatus_disabled'))
1038                 $network[] = NETWORK_OSTATUS;
1039
1040         $sql_network = implode("', '", $network);
1041         //$sql_network = "'".$sql_network."', ''";
1042         $sql_network = "'".$sql_network."'";
1043
1044         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1045                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1046                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1047                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1048                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1049                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1050                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1051                 AND `gcontact`.`network` IN (%s)
1052                 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1053                 intval($uid),
1054                 intval($uid),
1055                 intval($uid),
1056                 intval($uid),
1057                 $sql_network,
1058                 intval($start),
1059                 intval($limit)
1060         );
1061
1062         if(count($r) && count($r) >= ($limit -1))
1063                 return $r;
1064
1065         $r2 = q("SELECT gcontact.* FROM gcontact
1066                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1067                 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1068                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1069                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1070                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1071                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1072                 AND `gcontact`.`network` IN (%s)
1073                 ORDER BY rand() LIMIT %d, %d",
1074                 intval($uid),
1075                 intval($uid),
1076                 intval($uid),
1077                 $sql_network,
1078                 intval($start),
1079                 intval($limit)
1080         );
1081
1082         $list = array();
1083         foreach ($r2 AS $suggestion)
1084                 $list[$suggestion["nurl"]] = $suggestion;
1085
1086         foreach ($r AS $suggestion)
1087                 $list[$suggestion["nurl"]] = $suggestion;
1088
1089         while (sizeof($list) > ($limit))
1090                 array_pop($list);
1091
1092         return $list;
1093 }
1094
1095 function update_suggestions() {
1096
1097         $a = get_app();
1098
1099         $done = array();
1100
1101         /// TODO Check if it is really neccessary to poll the own server
1102         poco_load(0,0,0,$a->get_baseurl() . '/poco');
1103
1104         $done[] = $a->get_baseurl() . '/poco';
1105
1106         if(strlen(get_config('system','directory'))) {
1107                 $x = fetch_url(get_server()."/pubsites");
1108                 if($x) {
1109                         $j = json_decode($x);
1110                         if($j->entries) {
1111                                 foreach($j->entries as $entry) {
1112
1113                                         poco_check_server($entry->url);
1114
1115                                         $url = $entry->url . '/poco';
1116                                         if(! in_array($url,$done))
1117                                                 poco_load(0,0,0,$entry->url . '/poco');
1118                                 }
1119                         }
1120                 }
1121         }
1122
1123         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1124         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1125                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1126         );
1127
1128         if(count($r)) {
1129                 foreach($r as $rr) {
1130                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1131                         if(! in_array($base,$done))
1132                                 poco_load(0,0,0,$base);
1133                 }
1134         }
1135 }
1136
1137 function poco_discover_federation() {
1138         $last = get_config('poco','last_federation_discovery');
1139
1140         if($last) {
1141                 $next = $last + (24 * 60 * 60);
1142                 if($next > time())
1143                         return;
1144         }
1145
1146         // Discover Friendica, Hubzilla and Diaspora servers
1147         $serverdata = fetch_url("http://the-federation.info/pods.json");
1148
1149         if ($serverdata) {
1150                 $servers = json_decode($serverdata);
1151
1152                 foreach($servers->pods AS $server)
1153                         poco_check_server("https://".$server->host);
1154         }
1155
1156         // Discover GNU Social Servers
1157         if (!get_config('system','ostatus_disabled')) {
1158                 $serverdata = "http://gstools.org/api/get_open_instances/";
1159
1160                 $result = z_fetch_url($serverdata);
1161                 if ($result["success"]) {
1162                         $servers = json_decode($result["body"]);
1163
1164                         foreach($servers->data AS $server)
1165                                 poco_check_server($server->instance_address);
1166                 }
1167         }
1168
1169         set_config('poco','last_federation_discovery', time());
1170 }
1171
1172 function poco_discover($complete = false) {
1173
1174         // Update the server list
1175         poco_discover_federation();
1176
1177         $no_of_queries = 5;
1178
1179         $requery_days = intval(get_config("system", "poco_requery_days"));
1180
1181         if ($requery_days == 0)
1182                 $requery_days = 7;
1183
1184         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1185
1186         $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));
1187         if ($r)
1188                 foreach ($r AS $server) {
1189
1190                         if (!poco_check_server($server["url"], $server["network"])) {
1191                                 // The server is not reachable? Okay, then we will try it later
1192                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1193                                 continue;
1194                         }
1195
1196                         // Fetch all users from the other server
1197                         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1198
1199                         logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1200
1201                         $retdata = z_fetch_url($url);
1202                         if ($retdata["success"]) {
1203                                 $data = json_decode($retdata["body"]);
1204
1205                                 poco_discover_server($data, 2);
1206
1207                                 if (get_config('system','poco_discovery') > 1) {
1208
1209                                         $timeframe = get_config('system','poco_discovery_since');
1210                                         if ($timeframe == 0)
1211                                                 $timeframe = 30;
1212
1213                                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1214
1215                                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1216                                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1217
1218                                         $success = false;
1219
1220                                         $retdata = z_fetch_url($url);
1221                                         if ($retdata["success"]) {
1222                                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1223                                                 $success = poco_discover_server(json_decode($retdata["body"]));
1224                                         }
1225
1226                                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1227                                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1228                                                 poco_discover_server_users($data, $server);
1229                                         }
1230                                 }
1231
1232                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1233                                 if (!$complete AND (--$no_of_queries == 0))
1234                                         break;
1235                         } else {
1236                                 // If the server hadn't replied correctly, then force a sanity check
1237                                 poco_check_server($server["url"], $server["network"], true);
1238
1239                                 // If we couldn't reach the server, we will try it some time later
1240                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1241                         }
1242                 }
1243 }
1244
1245 function poco_discover_server_users($data, $server) {
1246
1247         if (!isset($data->entry))
1248                 return;
1249
1250         foreach ($data->entry AS $entry) {
1251                 $username = "";
1252                 if (isset($entry->urls)) {
1253                         foreach($entry->urls as $url)
1254                                 if($url->type == 'profile') {
1255                                         $profile_url = $url->value;
1256                                         $urlparts = parse_url($profile_url);
1257                                         $username = end(explode("/", $urlparts["path"]));
1258                                 }
1259                 }
1260                 if ($username != "") {
1261                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1262
1263                         // Fetch all contacts from a given user from the other server
1264                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1265
1266                         $retdata = z_fetch_url($url);
1267                         if ($retdata["success"])
1268                                 poco_discover_server(json_decode($retdata["body"]), 3);
1269                 }
1270         }
1271 }
1272
1273 function poco_discover_server($data, $default_generation = 0) {
1274
1275         if (!isset($data->entry) OR !count($data->entry))
1276                 return false;
1277
1278         $success = false;
1279
1280         foreach ($data->entry AS $entry) {
1281                 $profile_url = '';
1282                 $profile_photo = '';
1283                 $connect_url = '';
1284                 $name = '';
1285                 $network = '';
1286                 $updated = '0000-00-00 00:00:00';
1287                 $location = '';
1288                 $about = '';
1289                 $keywords = '';
1290                 $gender = '';
1291                 $generation = $default_generation;
1292
1293                 $name = $entry->displayName;
1294
1295                 if(isset($entry->urls)) {
1296                         foreach($entry->urls as $url) {
1297                                 if($url->type == 'profile') {
1298                                         $profile_url = $url->value;
1299                                         continue;
1300                                 }
1301                                 if($url->type == 'webfinger') {
1302                                         $connect_url = str_replace('acct:' , '', $url->value);
1303                                         continue;
1304                                 }
1305                         }
1306                 }
1307
1308                 if(isset($entry->photos)) {
1309                         foreach($entry->photos as $photo) {
1310                                 if($photo->type == 'profile') {
1311                                         $profile_photo = $photo->value;
1312                                         continue;
1313                                 }
1314                         }
1315                 }
1316
1317                 if(isset($entry->updated))
1318                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1319
1320                 if(isset($entry->network))
1321                         $network = $entry->network;
1322
1323                 if(isset($entry->currentLocation))
1324                         $location = $entry->currentLocation;
1325
1326                 if(isset($entry->aboutMe))
1327                         $about = html2bbcode($entry->aboutMe);
1328
1329                 if(isset($entry->gender))
1330                         $gender = $entry->gender;
1331
1332                 if(isset($entry->generation) AND ($entry->generation > 0))
1333                         $generation = ++$entry->generation;
1334
1335                 if(isset($entry->tags))
1336                         foreach($entry->tags as $tag)
1337                                 $keywords = implode(", ", $tag);
1338
1339                 if ($generation > 0) {
1340                         $success = true;
1341
1342                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1343                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1344                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1345                 }
1346         }
1347         return $success;
1348 }
1349
1350 /**
1351  * @brief Fetch the gcontact id, add an entry if not existed
1352  *
1353  * @param arr $contact contact array
1354  * @return bool|int Returns false if not found, integer if contact was found
1355  */
1356 function get_gcontact_id($contact) {
1357
1358         $gcontact_id = 0;
1359
1360         if ($contact["network"] == NETWORK_STATUSNET)
1361                 $contact["network"] = NETWORK_OSTATUS;
1362
1363         $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1364                 dbesc(normalise_link($contact["url"])));
1365
1366         if ($r)
1367                 $gcontact_id = $r[0]["id"];
1368         else {
1369                 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `generation`)
1370                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
1371                         dbesc($contact["name"]),
1372                         dbesc($contact["nick"]),
1373                         dbesc($contact["addr"]),
1374                         dbesc($contact["network"]),
1375                         dbesc($contact["url"]),
1376                         dbesc(normalise_link($contact["url"])),
1377                         dbesc($contact["photo"]),
1378                         dbesc(datetime_convert()),
1379                         dbesc(datetime_convert()),
1380                         dbesc($contact["location"]),
1381                         dbesc($contact["about"]),
1382                         intval($contact["generation"])
1383                 );
1384
1385                 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
1386                         dbesc(normalise_link($contact["url"])));
1387
1388                 if ($r)
1389                         $gcontact_id = $r[0]["id"];
1390         }
1391
1392         if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
1393          q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
1394                 dbesc(normalise_link($contact["url"])),
1395                 intval($gcontact_id));
1396
1397         return $gcontact_id;
1398 }
1399
1400 /**
1401  * @brief Updates the gcontact table from a given array
1402  *
1403  * @param arr $contact contact array
1404  * @return bool|int Returns false if not found, integer if contact was found
1405  */
1406 function update_gcontact($contact) {
1407
1408         /// @todo update contact table as well
1409
1410         $gcontact_id = get_gcontact_id($contact);
1411
1412         if (!$gcontact_id)
1413                 return false;
1414
1415         $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
1416                         `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
1417                 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1418                 intval($gcontact_id));
1419
1420         // Get all field names
1421         $fields = array();
1422         foreach ($r[0] AS $field => $data)
1423                 $fields[$field] = $data;
1424
1425         unset($fields["url"]);
1426         unset($fields["updated"]);
1427
1428         // Bugfix: We had an error in the storing of keywords which lead to the "0"
1429         // This value is still transmitted via poco.
1430         if ($contact["keywords"] == "0")
1431                 unset($contact["keywords"]);
1432
1433         if ($r[0]["keywords"] == "0")
1434                 $r[0]["keywords"] = "";
1435
1436         // assign all unassigned fields from the database entry
1437         foreach ($fields AS $field => $data)
1438                 if (!isset($contact[$field]) OR ($contact[$field] == ""))
1439                         $contact[$field] = $r[0][$field];
1440
1441         if ($contact["network"] == NETWORK_STATUSNET)
1442                 $contact["network"] = NETWORK_OSTATUS;
1443
1444         if (!isset($contact["updated"]))
1445                 $contact["updated"] = datetime_convert();
1446
1447         if ($contact["server_url"] == "") {
1448                 $server_url = $contact["url"];
1449
1450                 $server_url = matching_url($server_url, $contact["alias"]);
1451                 if ($server_url != "")
1452                         $contact["server_url"] = $server_url;
1453
1454                 $server_url = matching_url($server_url, $contact["photo"]);
1455                 if ($server_url != "")
1456                         $contact["server_url"] = $server_url;
1457
1458                 $server_url = matching_url($server_url, $contact["notify"]);
1459                 if ($server_url != "")
1460                         $contact["server_url"] = $server_url;
1461         } else
1462                 $contact["server_url"] = normalise_link($contact["server_url"]);
1463
1464         if (($contact["addr"] == "") AND ($contact["server_url"] != "") AND ($contact["nick"] != "")) {
1465                 $hostname = str_replace("http://", "", $contact["server_url"]);
1466                 $contact["addr"] = $contact["nick"]."@".$hostname;
1467         }
1468
1469         // Check if any field changed
1470         $update = false;
1471         unset($fields["generation"]);
1472
1473         if ((($contact["generation"] > 0) AND ($contact["generation"] <= $r[0]["generation"])) OR ($r[0]["generation"] == 0)) {
1474                 foreach ($fields AS $field => $data)
1475                         if ($contact[$field] != $r[0][$field]) {
1476                                 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
1477                                 $update = true;
1478                         }
1479
1480                 if ($contact["generation"] < $r[0]["generation"]) {
1481                         logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
1482                         $update = true;
1483                 }
1484         }
1485
1486         if ($update) {
1487                 logger("Update gcontact for ".$contact["url"]." Callstack: ".App::callstack(), LOGGER_DEBUG);
1488
1489                 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
1490                                         `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
1491                                         `alias` = '%s', `notify` = '%s', `url` = '%s',
1492                                         `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
1493                                         `server_url` = '%s', `connect` = '%s'
1494                                 WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1495                         dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
1496                         dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
1497                         dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
1498                         intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
1499                         dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
1500                         intval($contact["generation"]), dbesc($contact["updated"]),
1501                         dbesc($contact["server_url"]), dbesc($contact["connect"]),
1502                         dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
1503
1504
1505                 // Now update the contact entry with the user id "0" as well.
1506                 // This is used for the shadow copies of public items.
1507                 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
1508                         dbesc(normalise_link($contact["url"])));
1509
1510                 if ($r) {
1511                         logger("Update shadow contact ".$r[0]["id"], LOGGER_DEBUG);
1512
1513                         update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
1514
1515                         q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s',
1516                                                 `network` = '%s', `bd` = '%s', `gender` = '%s',
1517                                                 `keywords` = '%s', `alias` = '%s', `url` = '%s',
1518                                                 `location` = '%s', `about` = '%s'
1519                                         WHERE `id` = %d",
1520                                 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1521                                 dbesc($contact["network"]), dbesc($contact["birthday"]), dbesc($contact["gender"]),
1522                                 dbesc($contact["keywords"]), dbesc($contact["alias"]), dbesc($contact["url"]),
1523                                 dbesc($contact["location"]), dbesc($contact["about"]), intval($r[0]["id"]));
1524                 }
1525         }
1526
1527         return $gcontact_id;
1528 }
1529
1530 /**
1531  * @brief Updates the gcontact entry from probe
1532  *
1533  * @param str $url profile link
1534  */
1535 function update_gcontact_from_probe($url) {
1536         $data = probe_url($url);
1537
1538         if ($data["network"] == NETWORK_PHANTOM)
1539                 return;
1540
1541         update_gcontact($data);
1542 }
1543
1544 /**
1545  * @brief Fetches users of given GNU Social server
1546  *
1547  * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
1548  *
1549  * @param str $server Server address
1550  */
1551 function gs_fetch_users($server) {
1552
1553         logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
1554
1555         $a = get_app();
1556
1557         $url = $server."/main/statistics";
1558
1559         $result = z_fetch_url($url);
1560         if (!$result["success"])
1561                 return false;
1562
1563         $statistics = json_decode($result["body"]);
1564
1565         if (is_object($statistics->config)) {
1566                 if ($statistics->config->instance_with_ssl)
1567                         $server = "https://";
1568                 else
1569                         $server = "http://";
1570
1571                 $server .= $statistics->config->instance_address;
1572
1573                 $hostname = $statistics->config->instance_address;
1574         } else {
1575                 if ($statistics->instance_with_ssl)
1576                         $server = "https://";
1577                 else
1578                         $server = "http://";
1579
1580                 $server .= $statistics->instance_address;
1581
1582                 $hostname = $statistics->instance_address;
1583         }
1584
1585         if (is_object($statistics->users))
1586                 foreach ($statistics->users AS $nick => $user) {
1587                         $profile_url = $server."/".$user->nickname;
1588
1589                         $contact = array("url" => $profile_url,
1590                                         "name" => $user->fullname,
1591                                         "addr" => $user->nickname."@".$hostname,
1592                                         "nick" => $user->nickname,
1593                                         "about" => $user->bio,
1594                                         "network" => NETWORK_OSTATUS,
1595                                         "photo" => $a->get_baseurl()."/images/person-175.jpg");
1596                         get_gcontact_id($contact);
1597                 }
1598 }
1599
1600 /**
1601  * @brief Asking GNU Social server on a regular base for their user data
1602  *
1603  */
1604 function gs_discover() {
1605
1606         $requery_days = intval(get_config("system", "poco_requery_days"));
1607
1608         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1609
1610         $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",
1611                 dbesc(NETWORK_OSTATUS), dbesc($last_update));
1612
1613         if (!$r)
1614                 return;
1615
1616         foreach ($r AS $server) {
1617                 gs_fetch_users($server["url"]);
1618                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1619         }
1620 }
1621 ?>