]> git.mxchange.org Git - friendica.git/blob - include/socgraph.php
4881ac28e8bc5c688dbcf1382a60349aa83fb9a9
[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                                 }
788                         }
789         }
790
791         if (!$failure) {
792                 // Test for Statusnet
793                 // Will also return data for Friendica and GNU Social - but it will be overwritten later
794                 // The "not implemented" is a special treatment for really, really old Friendica versions
795                 $serverret = z_fetch_url($server_url."/api/statusnet/version.json");
796                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
797                         $platform = "StatusNet";
798                         $version = trim($serverret["body"], '"');
799                         $network = NETWORK_OSTATUS;
800                 }
801
802                 // Test for GNU Social
803                 $serverret = z_fetch_url($server_url."/api/gnusocial/version.json");
804                 if ($serverret["success"] AND ($serverret["body"] != '{"error":"not implemented"}') AND ($serverret["body"] != '') AND (strlen($serverret["body"]) < 250)) {
805                         $platform = "GNU Social";
806                         $version = trim($serverret["body"], '"');
807                         $network = NETWORK_OSTATUS;
808                 }
809
810                 $serverret = z_fetch_url($server_url."/api/statusnet/config.json");
811                 if ($serverret["success"]) {
812                         $data = json_decode($serverret["body"]);
813
814                         if (isset($data->site->server)) {
815                                 $last_contact = datetime_convert();
816
817                                 if (isset($data->site->hubzilla)) {
818                                         $platform = $data->site->hubzilla->PLATFORM_NAME;
819                                         $version = $data->site->hubzilla->RED_VERSION;
820                                         $network = NETWORK_DIASPORA;
821                                 }
822                                 if (isset($data->site->redmatrix)) {
823                                         if (isset($data->site->redmatrix->PLATFORM_NAME))
824                                                 $platform = $data->site->redmatrix->PLATFORM_NAME;
825                                         elseif (isset($data->site->redmatrix->RED_PLATFORM))
826                                                 $platform = $data->site->redmatrix->RED_PLATFORM;
827
828                                         $version = $data->site->redmatrix->RED_VERSION;
829                                         $network = NETWORK_DIASPORA;
830                                 }
831                                 if (isset($data->site->friendica)) {
832                                         $platform = $data->site->friendica->FRIENDICA_PLATFORM;
833                                         $version = $data->site->friendica->FRIENDICA_VERSION;
834                                         $network = NETWORK_DFRN;
835                                 }
836
837                                 $site_name = $data->site->name;
838
839                                 $data->site->closed = poco_to_boolean($data->site->closed);
840                                 $data->site->private = poco_to_boolean($data->site->private);
841                                 $data->site->inviteonly = poco_to_boolean($data->site->inviteonly);
842
843                                 if (!$data->site->closed AND !$data->site->private and $data->site->inviteonly)
844                                         $register_policy = REGISTER_APPROVE;
845                                 elseif (!$data->site->closed AND !$data->site->private)
846                                         $register_policy = REGISTER_OPEN;
847                                 else
848                                         $register_policy = REGISTER_CLOSED;
849                         }
850                 }
851         }
852
853         // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
854         if (!$failure) {
855                 $serverret = z_fetch_url($server_url."/statistics.json");
856                 if ($serverret["success"]) {
857                         $data = json_decode($serverret["body"]);
858                         if ($version == "")
859                                 $version = $data->version;
860
861                         $site_name = $data->name;
862
863                         if (isset($data->network) AND ($platform == ""))
864                                 $platform = $data->network;
865
866                         if ($platform == "Diaspora")
867                                 $network = NETWORK_DIASPORA;
868
869                         if ($data->registrations_open)
870                                 $register_policy = REGISTER_OPEN;
871                         else
872                                 $register_policy = REGISTER_CLOSED;
873
874                         if (isset($data->version))
875                                 $last_contact = datetime_convert();
876                 }
877         }
878
879         // Check for noscrape
880         // Friendica servers could be detected as OStatus servers
881         if (!$failure AND in_array($network, array(NETWORK_DFRN, NETWORK_OSTATUS))) {
882                 $serverret = z_fetch_url($server_url."/friendica/json");
883
884                 if (!$serverret["success"])
885                         $serverret = z_fetch_url($server_url."/friendika/json");
886
887                 if ($serverret["success"]) {
888                         $data = json_decode($serverret["body"]);
889
890                         if (isset($data->version)) {
891                                 $last_contact = datetime_convert();
892                                 $network = NETWORK_DFRN;
893
894                                 $noscrape = $data->no_scrape_url;
895                                 $version = $data->version;
896                                 $site_name = $data->site_name;
897                                 $info = $data->info;
898                                 $register_policy_str = $data->register_policy;
899                                 $platform = $data->platform;
900
901                                 switch ($register_policy_str) {
902                                         case "REGISTER_CLOSED":
903                                                 $register_policy = REGISTER_CLOSED;
904                                                 break;
905                                         case "REGISTER_APPROVE":
906                                                 $register_policy = REGISTER_APPROVE;
907                                                 break;
908                                         case "REGISTER_OPEN":
909                                                 $register_policy = REGISTER_OPEN;
910                                                 break;
911                                 }
912                         }
913                 }
914         }
915
916         // Look for poco
917         if (!$failure) {
918                 $serverret = z_fetch_url($server_url."/poco");
919                 if ($serverret["success"]) {
920                         $data = json_decode($serverret["body"]);
921                         if (isset($data->totalResults)) {
922                                 $poco = $server_url."/poco";
923                                 $last_contact = datetime_convert();
924                         }
925                 }
926         }
927
928         // Check again if the server exists
929         $servers = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", dbesc(normalise_link($server_url)));
930
931         if ($servers)
932                  q("UPDATE `gserver` SET `url` = '%s', `version` = '%s', `site_name` = '%s', `info` = '%s', `register_policy` = %d, `poco` = '%s', `noscrape` = '%s',
933                         `network` = '%s', `platform` = '%s', `last_contact` = '%s', `last_failure` = '%s' WHERE `nurl` = '%s'",
934                         dbesc($server_url),
935                         dbesc($version),
936                         dbesc($site_name),
937                         dbesc($info),
938                         intval($register_policy),
939                         dbesc($poco),
940                         dbesc($noscrape),
941                         dbesc($network),
942                         dbesc($platform),
943                         dbesc($last_contact),
944                         dbesc($last_failure),
945                         dbesc(normalise_link($server_url))
946                 );
947         else
948                 q("INSERT INTO `gserver` (`url`, `nurl`, `version`, `site_name`, `info`, `register_policy`, `poco`, `noscrape`, `network`, `platform`, `created`, `last_contact`, `last_failure`)
949                                         VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
950                                 dbesc($server_url),
951                                 dbesc(normalise_link($server_url)),
952                                 dbesc($version),
953                                 dbesc($site_name),
954                                 dbesc($info),
955                                 intval($register_policy),
956                                 dbesc($poco),
957                                 dbesc($noscrape),
958                                 dbesc($network),
959                                 dbesc($platform),
960                                 dbesc(datetime_convert()),
961                                 dbesc($last_contact),
962                                 dbesc($last_failure),
963                                 dbesc(datetime_convert())
964                 );
965
966         logger("End discovery for server ".$server_url, LOGGER_DEBUG);
967
968         return !$failure;
969 }
970
971 function poco_contact_from_body($body, $created, $cid, $uid) {
972         preg_replace_callback("/\[share(.*?)\].*?\[\/share\]/ism",
973                 function ($match) use ($created, $cid, $uid){
974                         return(sub_poco_from_share($match, $created, $cid, $uid));
975                 }, $body);
976 }
977
978 function sub_poco_from_share($share, $created, $cid, $uid) {
979         $profile = "";
980         preg_match("/profile='(.*?)'/ism", $share[1], $matches);
981         if ($matches[1] != "")
982                 $profile = $matches[1];
983
984         preg_match('/profile="(.*?)"/ism', $share[1], $matches);
985         if ($matches[1] != "")
986                 $profile = $matches[1];
987
988         if ($profile == "")
989                 return;
990
991         logger("prepare poco_check for profile ".$profile, LOGGER_DEBUG);
992         poco_check($profile, "", "", "", "", "", "", "", "", $created, 3, $cid, $uid);
993 }
994
995 function poco_store($item) {
996
997         // Isn't it public?
998         if ($item['private'])
999                 return;
1000
1001         // Or is it from a network where we don't store the global contacts?
1002         if (!in_array($item["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, NETWORK_STATUSNET, "")))
1003                 return;
1004
1005         // Is it a global copy?
1006         $store_gcontact = ($item["uid"] == 0);
1007
1008         // Is it a comment on a global copy?
1009         if (!$store_gcontact AND ($item["uri"] != $item["parent-uri"])) {
1010                 $q = q("SELECT `id` FROM `item` WHERE `uri`='%s' AND `uid` = 0", $item["parent-uri"]);
1011                 $store_gcontact = count($q);
1012         }
1013
1014         if (!$store_gcontact)
1015                 return;
1016
1017         // "3" means: We don't know this contact directly (Maybe a reshared item)
1018         $generation = 3;
1019         $network = "";
1020         $profile_url = $item["author-link"];
1021
1022         // Is it a user from our server?
1023         $q = q("SELECT `id` FROM `contact` WHERE `self` AND `nurl` = '%s' LIMIT 1",
1024                 dbesc(normalise_link($item["author-link"])));
1025         if (count($q)) {
1026                 logger("Our user (generation 1): ".$item["author-link"], LOGGER_DEBUG);
1027                 $generation = 1;
1028                 $network = NETWORK_DFRN;
1029         } else { // Is it a contact from a user on our server?
1030                 $q = q("SELECT `network`, `url` FROM `contact` WHERE `uid` != 0 AND `network` != ''
1031                         AND (`nurl` = '%s' OR `alias` IN ('%s', '%s')) AND `network` != '%s' LIMIT 1",
1032                         dbesc(normalise_link($item["author-link"])),
1033                         dbesc(normalise_link($item["author-link"])),
1034                         dbesc($item["author-link"]),
1035                         dbesc(NETWORK_STATUSNET));
1036                 if (count($q)) {
1037                         $generation = 2;
1038                         $network = $q[0]["network"];
1039                         $profile_url = $q[0]["url"];
1040                         logger("Known contact (generation 2): ".$profile_url, LOGGER_DEBUG);
1041                 }
1042         }
1043
1044         if ($generation == 3)
1045                 logger("Unknown contact (generation 3): ".$item["author-link"], LOGGER_DEBUG);
1046
1047         poco_check($profile_url, $item["author-name"], $network, $item["author-avatar"], "", "", "", "", "", $item["received"], $generation, $item["contact-id"], $item["uid"]);
1048
1049         // Maybe its a body with a shared item? Then extract a global contact from it.
1050         poco_contact_from_body($item["body"], $item["received"], $item["contact-id"], $item["uid"]);
1051 }
1052
1053 function count_common_friends($uid,$cid) {
1054
1055         $r = q("SELECT count(*) as `total`
1056                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1057                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1058                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1059                 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
1060                 intval($cid),
1061                 intval($uid),
1062                 intval($uid),
1063                 intval($cid)
1064         );
1065
1066 //      logger("count_common_friends: $uid $cid {$r[0]['total']}");
1067         if(count($r))
1068                 return $r[0]['total'];
1069         return 0;
1070
1071 }
1072
1073
1074 function common_friends($uid,$cid,$start = 0,$limit=9999,$shuffle = false) {
1075
1076         if($shuffle)
1077                 $sql_extra = " order by rand() ";
1078         else
1079                 $sql_extra = " order by `gcontact`.`name` asc ";
1080
1081         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1082                 FROM `glink`
1083                 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
1084                 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
1085                 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
1086                         AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
1087                         AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
1088                         AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1089                         $sql_extra LIMIT %d, %d",
1090                 intval($cid),
1091                 intval($uid),
1092                 intval($uid),
1093                 intval($cid),
1094                 intval($start),
1095                 intval($limit)
1096         );
1097
1098         return $r;
1099
1100 }
1101
1102
1103 function count_common_friends_zcid($uid,$zcid) {
1104
1105         $r = q("SELECT count(*) as `total`
1106                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1107                 where `glink`.`zcid` = %d
1108                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
1109                 intval($zcid),
1110                 intval($uid)
1111         );
1112
1113         if(count($r))
1114                 return $r[0]['total'];
1115         return 0;
1116
1117 }
1118
1119 function common_friends_zcid($uid,$zcid,$start = 0, $limit = 9999,$shuffle = false) {
1120
1121         if($shuffle)
1122                 $sql_extra = " order by rand() ";
1123         else
1124                 $sql_extra = " order by `gcontact`.`name` asc ";
1125
1126         $r = q("SELECT `gcontact`.*
1127                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1128                 where `glink`.`zcid` = %d
1129                 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) 
1130                 $sql_extra limit %d, %d",
1131                 intval($zcid),
1132                 intval($uid),
1133                 intval($start),
1134                 intval($limit)
1135         );
1136
1137         return $r;
1138
1139 }
1140
1141
1142 function count_all_friends($uid,$cid) {
1143
1144         $r = q("SELECT count(*) as `total`
1145                 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1146                 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
1147                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
1148                 intval($cid),
1149                 intval($uid)
1150         );
1151
1152         if(count($r))
1153                 return $r[0]['total'];
1154         return 0;
1155
1156 }
1157
1158
1159 function all_friends($uid,$cid,$start = 0, $limit = 80) {
1160
1161         $r = q("SELECT `gcontact`.*, `contact`.`id` AS `cid`
1162                 FROM `glink`
1163                 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
1164                 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
1165                 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
1166                 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
1167                 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
1168                 intval($uid),
1169                 intval($cid),
1170                 intval($uid),
1171                 intval($start),
1172                 intval($limit)
1173         );
1174
1175         return $r;
1176 }
1177
1178
1179
1180 function suggestion_query($uid, $start = 0, $limit = 80) {
1181
1182         if(! $uid)
1183                 return array();
1184
1185         $network = array(NETWORK_DFRN);
1186
1187         if (get_config('system','diaspora_enabled'))
1188                 $network[] = NETWORK_DIASPORA;
1189
1190         if (!get_config('system','ostatus_disabled'))
1191                 $network[] = NETWORK_OSTATUS;
1192
1193         $sql_network = implode("', '", $network);
1194         //$sql_network = "'".$sql_network."', ''";
1195         $sql_network = "'".$sql_network."'";
1196
1197         $r = q("SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
1198                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1199                 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
1200                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1201                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1202                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1203                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1204                 AND `gcontact`.`network` IN (%s)
1205                 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
1206                 intval($uid),
1207                 intval($uid),
1208                 intval($uid),
1209                 intval($uid),
1210                 $sql_network,
1211                 intval($start),
1212                 intval($limit)
1213         );
1214
1215         if(count($r) && count($r) >= ($limit -1))
1216                 return $r;
1217
1218         $r2 = q("SELECT gcontact.* FROM gcontact
1219                 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
1220                 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
1221                 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
1222                 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
1223                 AND `gcontact`.`updated` != '0000-00-00 00:00:00'
1224                 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
1225                 AND `gcontact`.`network` IN (%s)
1226                 ORDER BY rand() LIMIT %d, %d",
1227                 intval($uid),
1228                 intval($uid),
1229                 intval($uid),
1230                 $sql_network,
1231                 intval($start),
1232                 intval($limit)
1233         );
1234
1235         $list = array();
1236         foreach ($r2 AS $suggestion)
1237                 $list[$suggestion["nurl"]] = $suggestion;
1238
1239         foreach ($r AS $suggestion)
1240                 $list[$suggestion["nurl"]] = $suggestion;
1241
1242         while (sizeof($list) > ($limit))
1243                 array_pop($list);
1244
1245         return $list;
1246 }
1247
1248 function update_suggestions() {
1249
1250         $a = get_app();
1251
1252         $done = array();
1253
1254         /// TODO Check if it is really neccessary to poll the own server
1255         poco_load(0,0,0,$a->get_baseurl() . '/poco');
1256
1257         $done[] = $a->get_baseurl() . '/poco';
1258
1259         if(strlen(get_config('system','directory'))) {
1260                 $x = fetch_url(get_server()."/pubsites");
1261                 if($x) {
1262                         $j = json_decode($x);
1263                         if($j->entries) {
1264                                 foreach($j->entries as $entry) {
1265
1266                                         poco_check_server($entry->url);
1267
1268                                         $url = $entry->url . '/poco';
1269                                         if(! in_array($url,$done))
1270                                                 poco_load(0,0,0,$entry->url . '/poco');
1271                                 }
1272                         }
1273                 }
1274         }
1275
1276         // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
1277         $r = q("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
1278                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA)
1279         );
1280
1281         if(count($r)) {
1282                 foreach($r as $rr) {
1283                         $base = substr($rr['poco'],0,strrpos($rr['poco'],'/'));
1284                         if(! in_array($base,$done))
1285                                 poco_load(0,0,0,$base);
1286                 }
1287         }
1288 }
1289
1290 function poco_discover_federation() {
1291         $last = get_config('poco','last_federation_discovery');
1292
1293         if($last) {
1294                 $next = $last + (24 * 60 * 60);
1295                 if($next > time())
1296                         return;
1297         }
1298
1299         $serverdata = fetch_url("http://the-federation.info/pods.json");
1300
1301         if (!$serverdata)
1302                 return;
1303
1304         $servers = json_decode($serverdata);
1305
1306         foreach($servers->pods AS $server)
1307                 poco_check_server("https://".$server->host);
1308
1309         set_config('poco','last_federation_discovery', time());
1310
1311 }
1312
1313 function poco_discover($complete = false) {
1314
1315         // Update the server list
1316         poco_discover_federation();
1317
1318         $no_of_queries = 5;
1319
1320         $requery_days = intval(get_config("system", "poco_requery_days"));
1321
1322         if ($requery_days == 0)
1323                 $requery_days = 7;
1324
1325         $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1326
1327         $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));
1328         if ($r)
1329                 foreach ($r AS $server) {
1330
1331                         if (!poco_check_server($server["url"], $server["network"])) {
1332                                 // The server is not reachable? Okay, then we will try it later
1333                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1334                                 continue;
1335                         }
1336
1337                         // Fetch all users from the other server
1338                         $url = $server["poco"]."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1339
1340                         logger("Fetch all users from the server ".$server["nurl"], LOGGER_DEBUG);
1341
1342                         $retdata = z_fetch_url($url);
1343                         if ($retdata["success"]) {
1344                                 $data = json_decode($retdata["body"]);
1345
1346                                 poco_discover_server($data, 2);
1347
1348                                 if (get_config('system','poco_discovery') > 1) {
1349
1350                                         $timeframe = get_config('system','poco_discovery_since');
1351                                         if ($timeframe == 0)
1352                                                 $timeframe = 30;
1353
1354                                         $updatedSince = date("Y-m-d H:i:s", time() - $timeframe * 86400);
1355
1356                                         // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1357                                         $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1358
1359                                         $success = false;
1360
1361                                         $retdata = z_fetch_url($url);
1362                                         if ($retdata["success"]) {
1363                                                 logger("Fetch all global contacts from the server ".$server["nurl"], LOGGER_DEBUG);
1364                                                 $success = poco_discover_server(json_decode($retdata["body"]));
1365                                         }
1366
1367                                         if (!$success AND (get_config('system','poco_discovery') > 2)) {
1368                                                 logger("Fetch contacts from users of the server ".$server["nurl"], LOGGER_DEBUG);
1369                                                 poco_discover_server_users($data, $server);
1370                                         }
1371                                 }
1372
1373                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1374                                 if (!$complete AND (--$no_of_queries == 0))
1375                                         break;
1376                         } else {
1377                                 // If the server hadn't replied correctly, then force a sanity check
1378                                 poco_check_server($server["url"], $server["network"], true);
1379
1380                                 // If we couldn't reach the server, we will try it some time later
1381                                 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
1382                         }
1383                 }
1384 }
1385
1386 function poco_discover_server_users($data, $server) {
1387
1388         if (!isset($data->entry))
1389                 return;
1390
1391         foreach ($data->entry AS $entry) {
1392                 $username = "";
1393                 if (isset($entry->urls)) {
1394                         foreach($entry->urls as $url)
1395                                 if($url->type == 'profile') {
1396                                         $profile_url = $url->value;
1397                                         $urlparts = parse_url($profile_url);
1398                                         $username = end(explode("/", $urlparts["path"]));
1399                                 }
1400                 }
1401                 if ($username != "") {
1402                         logger("Fetch contacts for the user ".$username." from the server ".$server["nurl"], LOGGER_DEBUG);
1403
1404                         // Fetch all contacts from a given user from the other server
1405                         $url = $server["poco"]."/".$username."/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,generation";
1406
1407                         $retdata = z_fetch_url($url);
1408                         if ($retdata["success"])
1409                                 poco_discover_server(json_decode($retdata["body"]), 3);
1410                 }
1411         }
1412 }
1413
1414 function poco_discover_server($data, $default_generation = 0) {
1415
1416         if (!isset($data->entry) OR !count($data->entry))
1417                 return false;
1418
1419         $success = false;
1420
1421         foreach ($data->entry AS $entry) {
1422                 $profile_url = '';
1423                 $profile_photo = '';
1424                 $connect_url = '';
1425                 $name = '';
1426                 $network = '';
1427                 $updated = '0000-00-00 00:00:00';
1428                 $location = '';
1429                 $about = '';
1430                 $keywords = '';
1431                 $gender = '';
1432                 $generation = $default_generation;
1433
1434                 $name = $entry->displayName;
1435
1436                 if(isset($entry->urls)) {
1437                         foreach($entry->urls as $url) {
1438                                 if($url->type == 'profile') {
1439                                         $profile_url = $url->value;
1440                                         continue;
1441                                 }
1442                                 if($url->type == 'webfinger') {
1443                                         $connect_url = str_replace('acct:' , '', $url->value);
1444                                         continue;
1445                                 }
1446                         }
1447                 }
1448
1449                 if(isset($entry->photos)) {
1450                         foreach($entry->photos as $photo) {
1451                                 if($photo->type == 'profile') {
1452                                         $profile_photo = $photo->value;
1453                                         continue;
1454                                 }
1455                         }
1456                 }
1457
1458                 if(isset($entry->updated))
1459                         $updated = date("Y-m-d H:i:s", strtotime($entry->updated));
1460
1461                 if(isset($entry->network))
1462                         $network = $entry->network;
1463
1464                 if(isset($entry->currentLocation))
1465                         $location = $entry->currentLocation;
1466
1467                 if(isset($entry->aboutMe))
1468                         $about = html2bbcode($entry->aboutMe);
1469
1470                 if(isset($entry->gender))
1471                         $gender = $entry->gender;
1472
1473                 if(isset($entry->generation) AND ($entry->generation > 0))
1474                         $generation = ++$entry->generation;
1475
1476                 if(isset($entry->tags))
1477                         foreach($entry->tags as $tag)
1478                                 $keywords = implode(", ", $tag);
1479
1480                 if ($generation > 0) {
1481                         $success = true;
1482
1483                         logger("Store profile ".$profile_url, LOGGER_DEBUG);
1484                         poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, 0, 0, 0);
1485                         logger("Done for profile ".$profile_url, LOGGER_DEBUG);
1486                 }
1487         }
1488         return $success;
1489 }
1490
1491 function get_gcontact_id($contact) {
1492
1493         $gcontact_id = 0;
1494
1495         if ($contact["network"] == NETWORK_STATUSNET)
1496                 $contact["network"] = NETWORK_OSTATUS;
1497
1498         $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1499                 dbesc(normalise_link($contact["url"])));
1500
1501         if ($r)
1502                 $gcontact_id = $r[0]["id"];
1503         else {
1504                 q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `generation`)
1505                         VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
1506                         dbesc($contact["name"]),
1507                         dbesc($contact["nick"]),
1508                         dbesc($contact["addr"]),
1509                         dbesc($contact["network"]),
1510                         dbesc($contact["url"]),
1511                         dbesc(normalise_link($contact["url"])),
1512                         dbesc($contact["photo"]),
1513                         dbesc(datetime_convert()),
1514                         dbesc(datetime_convert()),
1515                         dbesc($contact["location"]),
1516                         dbesc($contact["about"]),
1517                         intval($contact["generation"])
1518                 );
1519
1520                 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1521                         dbesc(normalise_link($contact["url"])));
1522
1523                 if ($r)
1524                         $gcontact_id = $r[0]["id"];
1525         }
1526
1527         return $gcontact_id;
1528 }
1529
1530 function update_gcontact($contact) {
1531
1532         $gcontact_id = get_gcontact_id($contact);
1533
1534         if (!$gcontact_id)
1535                 return false;
1536
1537         $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`, `hide`, `nsfw`
1538                 FROM `gcontact` WHERE `id` = %d LIMIT 1",
1539                 intval($gcontact_id));
1540
1541         if ($contact["generation"] == 0)
1542                 $contact["generation"] = $r[0]["generation"];
1543
1544         if ($contact["photo"] == "")
1545                 $contact["photo"] = $r[0]["photo"];
1546
1547         if ($contact["name"] == "")
1548                 $contact["name"] = $r[0]["name"];
1549
1550         if ($contact["nick"] == "")
1551                 $contact["nick"] = $r[0]["nick"];
1552
1553         if ($contact["addr"] == "")
1554                 $contact["addr"] = $r[0]["addr"];
1555
1556         if ($contact["location"] =="")
1557                 $contact["location"] = $r[0]["location"];
1558
1559         if ($contact["about"] =="")
1560                 $contact["about"] = $r[0]["about"];
1561
1562         if ($contact["birthday"] =="")
1563                 $contact["birthday"] = $r[0]["birthday"];
1564
1565         if ($contact["gender"] =="")
1566                 $contact["gender"] = $r[0]["gender"];
1567
1568         if ($contact["keywords"] =="")
1569                 $contact["keywords"] = $r[0]["keywords"];
1570
1571         if (!isset($contact["hide"]))
1572                 $contact["hide"] = $r[0]["hide"];
1573
1574         if (!isset($contact["nsfw"]))
1575                 $contact["nsfw"] = $r[0]["nsfw"];
1576
1577         if ($contact["network"] == NETWORK_STATUSNET)
1578                 $contact["network"] = NETWORK_OSTATUS;
1579
1580         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
1581                 ($contact["birthday"] != $r[0]["birthday"]) OR ($contact["gender"] != $r[0]["gender"]) OR ($contact["keywords"] != $r[0]["keywords"]) OR
1582                 ($contact["hide"] != $r[0]["hide"]) OR ($contact["nsfw"] != $r[0]["nsfw"]) OR
1583                 ($contact["location"] != $r[0]["location"]) OR ($contact["about"] != $r[0]["about"]) OR ($contact["generation"] < $r[0]["generation"])) {
1584
1585                 q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s',
1586                                         `birthday` = '%s', `gender` = '%s', `keywords` = %d, `hide` = %d, `nsfw` = %d,
1587                                         `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s'
1588                                 WHERE `nurl` = '%s' AND `network` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
1589                         dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["addr"]),
1590                         dbesc($contact["birthday"]), dbesc($contact["gender"]), dbesc($contact["keywords"]),
1591                         intval($contact["hide"]), intval($contact["nsfw"]),
1592                         dbesc($contact["location"]), dbesc($contact["about"]), intval($contact["generation"]), dbesc(datetime_convert()),
1593                         dbesc(normalise_link($contact["url"])), dbesc($contact["network"]), intval($contact["generation"]));
1594         }
1595
1596         return $gcontact_id;
1597 }
1598 ?>