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