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