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