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