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