]> git.mxchange.org Git - friendica.git/blob - src/Model/GContact.php
New function to keep the self contact updated
[friendica.git] / src / Model / GContact.php
1 <?php
2
3 /**
4  * @file src/Model/GlobalContact.php
5  * @brief This file includes the GlobalContact class with directory related functions
6  */
7 namespace Friendica\Model;
8
9 use Friendica\Core\Config;
10 use Friendica\Core\System;
11 use Friendica\Core\Worker;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Profile;
15 use Friendica\Network\Probe;
16 use Friendica\Protocol\PortableContact;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Network;
19 use dba;
20 use Exception;
21
22 require_once 'include/dba.php';
23 require_once 'include/html2bbcode.php';
24
25 /**
26  * @brief This class handles GlobalContact related functions
27  */
28 class GContact
29 {
30         /**
31          * @brief Search global contact table by nick or name
32          *
33          * @param string $search Name or nick
34          * @param string $mode   Search mode (e.g. "community")
35          *
36          * @return array with search results
37          */
38         public static function searchByName($search, $mode = '')
39         {
40                 if (empty($search)) {
41                         return [];
42                 }
43
44                 // check supported networks
45                 if (Config::get('system', 'diaspora_enabled')) {
46                         $diaspora = NETWORK_DIASPORA;
47                 } else {
48                         $diaspora = NETWORK_DFRN;
49                 }
50
51                 if (!Config::get('system', 'ostatus_disabled')) {
52                         $ostatus = NETWORK_OSTATUS;
53                 } else {
54                         $ostatus = NETWORK_DFRN;
55                 }
56
57                 // check if we search only communities or every contact
58                 if ($mode === "community") {
59                         $extra_sql = " AND `community`";
60                 } else {
61                         $extra_sql = "";
62                 }
63
64                 $search .= "%";
65
66                 $results = dba::p("SELECT `nurl` FROM `gcontact`
67                         WHERE NOT `hide` AND `network` IN (?, ?, ?) AND
68                                 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
69                                 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
70                                 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
71                         NETWORK_DFRN, $ostatus, $diaspora, $search, $search, $search
72                 );
73
74                 $gcontacts = [];
75                 while ($result = dba::fetch($results)) {
76                         $urlparts = parse_url($result["nurl"]);
77
78                         // Ignore results that look strange.
79                         // For historic reasons the gcontact table does contain some garbage.
80                         if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
81                                 continue;
82                         }
83
84                         $gcontacts[] = Contact::getDetailsByURL($result["nurl"], local_user());
85                 }
86                 return $gcontacts;
87         }
88
89         /**
90          * @brief Link the gcontact entry with user, contact and global contact
91          *
92          * @param integer $gcid Global contact ID
93          * @param integer $uid  User ID
94          * @param integer $cid  Contact ID
95          * @param integer $zcid Global Contact ID
96          * @return void
97          */
98         public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
99         {
100                 if ($gcid <= 0) {
101                         return;
102                 }
103
104                 $r = q(
105                         "SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
106                         intval($cid),
107                         intval($uid),
108                         intval($gcid),
109                         intval($zcid)
110                 );
111
112                 if (!DBM::is_result($r)) {
113                         q(
114                                 "INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
115                                 intval($cid),
116                                 intval($uid),
117                                 intval($gcid),
118                                 intval($zcid),
119                                 dbesc(DateTimeFormat::utcNow())
120                         );
121                 } else {
122                         q(
123                                 "UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
124                                 dbesc(DateTimeFormat::utcNow()),
125                                 intval($cid),
126                                 intval($uid),
127                                 intval($gcid),
128                                 intval($zcid)
129                         );
130                 }
131         }
132
133         /**
134          * @brief Sanitize the given gcontact data
135          *
136          * @param array $gcontact array with gcontact data
137          * @throw Exception
138          *
139          * Generation:
140          *  0: No definition
141          *  1: Profiles on this server
142          *  2: Contacts of profiles on this server
143          *  3: Contacts of contacts of profiles on this server
144          *  4: ...
145          * @return array $gcontact
146          */
147         public static function sanitize($gcontact)
148         {
149                 if ($gcontact['url'] == "") {
150                         throw new Exception('URL is empty');
151                 }
152
153                 $urlparts = parse_url($gcontact['url']);
154                 if (!isset($urlparts["scheme"])) {
155                         throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
156                 }
157
158                 if (in_array($urlparts["host"], ["www.facebook.com", "facebook.com", "twitter.com", "identi.ca", "alpha.app.net"])) {
159                         throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
160                 }
161
162                 // Don't store the statusnet connector as network
163                 // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
164                 if ($gcontact['network'] == NETWORK_STATUSNET) {
165                         $gcontact['network'] = "";
166                 }
167
168                 // Assure that there are no parameter fragments in the profile url
169                 if (in_array($gcontact['network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
170                         $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
171                 }
172
173                 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
174
175                 // The global contacts should contain the original picture, not the cached one
176                 if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
177                         $gcontact['photo'] = "";
178                 }
179
180                 if (!isset($gcontact['network'])) {
181                         $r = q(
182                                 "SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
183                                 dbesc(normalise_link($gcontact['url'])),
184                                 dbesc(NETWORK_STATUSNET)
185                         );
186                         if (DBM::is_result($r)) {
187                                 $gcontact['network'] = $r[0]["network"];
188                         }
189
190                         if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
191                                 $r = q(
192                                         "SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
193                                         dbesc($gcontact['url']),
194                                         dbesc(normalise_link($gcontact['url'])),
195                                         dbesc(NETWORK_STATUSNET)
196                                 );
197                                 if (DBM::is_result($r)) {
198                                         $gcontact['network'] = $r[0]["network"];
199                                 }
200                         }
201                 }
202
203                 $gcontact['server_url'] = '';
204                 $gcontact['network'] = '';
205
206                 $x = q(
207                         "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
208                         dbesc(normalise_link($gcontact['url']))
209                 );
210
211                 if (DBM::is_result($x)) {
212                         if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
213                                 $gcontact['network'] = $x[0]["network"];
214                         }
215                         if ($gcontact['updated'] <= NULL_DATE) {
216                                 $gcontact['updated'] = $x[0]["updated"];
217                         }
218                         if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
219                                 $gcontact['server_url'] = $x[0]["server_url"];
220                         }
221                         if (!isset($gcontact['addr'])) {
222                                 $gcontact['addr'] = $x[0]["addr"];
223                         }
224                 }
225
226                 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
227                         && PortableContact::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
228                 ) {
229                         $data = Probe::uri($gcontact['url']);
230
231                         if ($data["network"] == NETWORK_PHANTOM) {
232                                 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
233                         }
234
235                         $orig_profile = $gcontact['url'];
236
237                         $gcontact["server_url"] = $data["baseurl"];
238
239                         $gcontact = array_merge($gcontact, $data);
240
241                         if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
242                                 // Delete the old entry - if it exists
243                                 $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
244                                 if (DBM::is_result($r)) {
245                                         q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
246                                         q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
247                                 }
248                         }
249                 }
250
251                 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
252                         throw new Exception('No name and photo for URL '.$gcontact['url']);
253                 }
254
255                 if (!in_array($gcontact['network'], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA])) {
256                         throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
257                 }
258
259                 if (!isset($gcontact['server_url'])) {
260                         // We check the server url to be sure that it is a real one
261                         $server_url = PortableContact::detectServer($gcontact['url']);
262
263                         // We are now sure that it is a correct URL. So we use it in the future
264                         if ($server_url != "") {
265                                 $gcontact['server_url'] = $server_url;
266                         }
267                 }
268
269                 // The server URL doesn't seem to be valid, so we don't store it.
270                 if (!PortableContact::checkServer($gcontact['server_url'], $gcontact['network'])) {
271                         $gcontact['server_url'] = "";
272                 }
273
274                 return $gcontact;
275         }
276
277         /**
278          * @param integer $uid id
279          * @param integer $cid id
280          * @return integer
281          */
282         public static function countCommonFriends($uid, $cid)
283         {
284                 $r = q(
285                         "SELECT count(*) as `total`
286                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
287                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
288                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
289                         (`gcontact`.`updated` >= `gcontact`.`last_failure`))
290                         AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
291                         intval($cid),
292                         intval($uid),
293                         intval($uid),
294                         intval($cid)
295                 );
296
297                 // logger("countCommonFriends: $uid $cid {$r[0]['total']}");
298                 if (DBM::is_result($r)) {
299                         return $r[0]['total'];
300                 }
301                 return 0;
302         }
303
304         /**
305          * @param integer $uid  id
306          * @param integer $zcid zcid
307          * @return integer
308          */
309         public static function countCommonFriendsZcid($uid, $zcid)
310         {
311                 $r = q(
312                         "SELECT count(*) as `total`
313                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
314                         where `glink`.`zcid` = %d
315                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
316                         intval($zcid),
317                         intval($uid)
318                 );
319
320                 if (DBM::is_result($r)) {
321                         return $r[0]['total'];
322                 }
323
324                 return 0;
325         }
326
327         /**
328          * @param integer $uid     user
329          * @param integer $cid     cid
330          * @param integer $start   optional, default 0
331          * @param integer $limit   optional, default 9999
332          * @param boolean $shuffle optional, default false
333          * @return object
334          */
335         public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
336         {
337                 if ($shuffle) {
338                         $sql_extra = " order by rand() ";
339                 } else {
340                         $sql_extra = " order by `gcontact`.`name` asc ";
341                 }
342
343                 $r = q(
344                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
345                         FROM `glink`
346                         INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
347                         INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
348                         WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
349                                 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
350                                 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
351                                 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
352                                 $sql_extra LIMIT %d, %d",
353                         intval($cid),
354                         intval($uid),
355                         intval($uid),
356                         intval($cid),
357                         intval($start),
358                         intval($limit)
359                 );
360
361                 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
362                 return $r;
363         }
364
365         /**
366          * @param integer $uid     user
367          * @param integer $zcid    zcid
368          * @param integer $start   optional, default 0
369          * @param integer $limit   optional, default 9999
370          * @param boolean $shuffle optional, default false
371          * @return object
372          */
373         public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
374         {
375                 if ($shuffle) {
376                         $sql_extra = " order by rand() ";
377                 } else {
378                         $sql_extra = " order by `gcontact`.`name` asc ";
379                 }
380
381                 $r = q(
382                         "SELECT `gcontact`.*
383                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
384                         where `glink`.`zcid` = %d
385                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
386                         $sql_extra limit %d, %d",
387                         intval($zcid),
388                         intval($uid),
389                         intval($start),
390                         intval($limit)
391                 );
392
393                 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
394                 return $r;
395         }
396
397         /**
398          * @param integer $uid user
399          * @param integer $cid cid
400          * @return integer
401          */
402         public static function countAllFriends($uid, $cid)
403         {
404                 $r = q(
405                         "SELECT count(*) as `total`
406                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
407                         where `glink`.`cid` = %d and `glink`.`uid` = %d AND
408                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
409                         intval($cid),
410                         intval($uid)
411                 );
412
413                 if (DBM::is_result($r)) {
414                         return $r[0]['total'];
415                 }
416
417                 return 0;
418         }
419
420         /**
421          * @param integer $uid   user
422          * @param integer $cid   cid
423          * @param integer $start optional, default 0
424          * @param integer $limit optional, default 80
425          * @return array
426          */
427         public static function allFriends($uid, $cid, $start = 0, $limit = 80)
428         {
429                 $r = q(
430                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
431                         FROM `glink`
432                         INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
433                         LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
434                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
435                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
436                         ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
437                         intval($uid),
438                         intval($cid),
439                         intval($uid),
440                         intval($start),
441                         intval($limit)
442                 );
443
444                 /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
445                 return $r;
446         }
447
448         /**
449          * @param object  $uid   user
450          * @param integer $start optional, default 0
451          * @param integer $limit optional, default 80
452          * @return array
453          */
454         public static function suggestionQuery($uid, $start = 0, $limit = 80)
455         {
456                 if (!$uid) {
457                         return [];
458                 }
459
460                 /*
461                 * Uncommented because the result of the queries are to big to store it in the cache.
462                 * We need to decide if we want to change the db column type or if we want to delete it.
463                 */
464                 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
465                 //if (!is_null($list)) {
466                 //      return $list;
467                 //}
468
469                 $network = [NETWORK_DFRN];
470
471                 if (Config::get('system', 'diaspora_enabled')) {
472                         $network[] = NETWORK_DIASPORA;
473                 }
474
475                 if (!Config::get('system', 'ostatus_disabled')) {
476                         $network[] = NETWORK_OSTATUS;
477                 }
478
479                 $sql_network = implode("', '", $network);
480                 $sql_network = "'".$sql_network."'";
481
482                 /// @todo This query is really slow
483                 // By now we cache the data for five minutes
484                 $r = q(
485                         "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
486                         INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
487                         where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
488                         AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
489                         AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
490                         AND `gcontact`.`updated` >= '%s'
491                         AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
492                         AND `gcontact`.`network` IN (%s)
493                         GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
494                         intval($uid),
495                         intval($uid),
496                         intval($uid),
497                         intval($uid),
498                         dbesc(NULL_DATE),
499                         $sql_network,
500                         intval($start),
501                         intval($limit)
502                 );
503
504                 if (DBM::is_result($r) && count($r) >= ($limit -1)) {
505                         /*
506                         * Uncommented because the result of the queries are to big to store it in the cache.
507                         * We need to decide if we want to change the db column type or if we want to delete it.
508                         */
509                         //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
510
511                         return $r;
512                 }
513
514                 $r2 = q(
515                         "SELECT gcontact.* FROM gcontact
516                         INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
517                         WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
518                         AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
519                         AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
520                         AND `gcontact`.`updated` >= '%s'
521                         AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
522                         AND `gcontact`.`network` IN (%s)
523                         ORDER BY rand() LIMIT %d, %d",
524                         intval($uid),
525                         intval($uid),
526                         intval($uid),
527                         dbesc(NULL_DATE),
528                         $sql_network,
529                         intval($start),
530                         intval($limit)
531                 );
532
533                 $list = [];
534                 foreach ($r2 as $suggestion) {
535                         $list[$suggestion["nurl"]] = $suggestion;
536                 }
537
538                 foreach ($r as $suggestion) {
539                         $list[$suggestion["nurl"]] = $suggestion;
540                 }
541
542                 while (sizeof($list) > ($limit)) {
543                         array_pop($list);
544                 }
545
546                 /*
547                 * Uncommented because the result of the queries are to big to store it in the cache.
548                 * We need to decide if we want to change the db column type or if we want to delete it.
549                 */
550                 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
551                 return $list;
552         }
553
554         /**
555          * @return void
556          */
557         public static function updateSuggestions()
558         {
559                 $a = get_app();
560
561                 $done = [];
562
563                 /// @TODO Check if it is really neccessary to poll the own server
564                 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
565
566                 $done[] = System::baseUrl() . '/poco';
567
568                 if (strlen(Config::get('system', 'directory'))) {
569                         $x = Network::fetchUrl(get_server()."/pubsites");
570                         if ($x) {
571                                 $j = json_decode($x);
572                                 if ($j->entries) {
573                                         foreach ($j->entries as $entry) {
574                                                 PortableContact::checkServer($entry->url);
575
576                                                 $url = $entry->url . '/poco';
577                                                 if (! in_array($url, $done)) {
578                                                         PortableContact::loadWorker(0, 0, 0, $entry->url . '/poco');
579                                                 }
580                                         }
581                                 }
582                         }
583                 }
584
585                 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
586                 $r = q(
587                         "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
588                         dbesc(NETWORK_DFRN),
589                         dbesc(NETWORK_DIASPORA)
590                 );
591
592                 if (DBM::is_result($r)) {
593                         foreach ($r as $rr) {
594                                 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
595                                 if (! in_array($base, $done)) {
596                                         PortableContact::loadWorker(0, 0, 0, $base);
597                                 }
598                         }
599                 }
600         }
601
602         /**
603          * @brief Removes unwanted parts from a contact url
604          *
605          * @param string $url Contact url
606          *
607          * @return string Contact url with the wanted parts
608          */
609         public static function cleanContactUrl($url)
610         {
611                 $parts = parse_url($url);
612
613                 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
614                         return $url;
615                 }
616
617                 $new_url = $parts["scheme"]."://".$parts["host"];
618
619                 if (isset($parts["port"])) {
620                         $new_url .= ":".$parts["port"];
621                 }
622
623                 if (isset($parts["path"])) {
624                         $new_url .= $parts["path"];
625                 }
626
627                 if ($new_url != $url) {
628                         logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
629                 }
630
631                 return $new_url;
632         }
633
634         /**
635          * @brief Replace alternate OStatus user format with the primary one
636          *
637          * @param array $contact contact array (called by reference)
638          * @return void
639          */
640         public static function fixAlternateContactAddress(&$contact)
641         {
642                 if (($contact["network"] == NETWORK_OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
643                         $data = Probe::uri($contact["url"]);
644                         if ($contact["network"] == NETWORK_OSTATUS) {
645                                 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
646                                 $contact["url"] = $data["url"];
647                                 $contact["addr"] = $data["addr"];
648                                 $contact["alias"] = $data["alias"];
649                                 $contact["server_url"] = $data["baseurl"];
650                         }
651                 }
652         }
653
654         /**
655          * @brief Fetch the gcontact id, add an entry if not existed
656          *
657          * @param array $contact contact array
658          *
659          * @return bool|int Returns false if not found, integer if contact was found
660          */
661         public static function getId($contact)
662         {
663                 $gcontact_id = 0;
664                 $doprobing = false;
665                 $last_failure_str = '';
666                 $last_contact_str = '';
667
668                 if (in_array($contact["network"], [NETWORK_PHANTOM])) {
669                         logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
670                         return false;
671                 }
672
673                 if ($contact["network"] == NETWORK_STATUSNET) {
674                         $contact["network"] = NETWORK_OSTATUS;
675                 }
676
677                 // All new contacts are hidden by default
678                 if (!isset($contact["hide"])) {
679                         $contact["hide"] = true;
680                 }
681
682                 // Replace alternate OStatus user format with the primary one
683                 self::fixAlternateContactAddress($contact);
684
685                 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
686                 if (in_array($contact["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
687                         $contact["url"] = self::cleanContactUrl($contact["url"]);
688                 }
689
690                 dba::lock('gcontact');
691                 $r = q(
692                         "SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
693                         dbesc(normalise_link($contact["url"]))
694                 );
695
696                 if (DBM::is_result($r)) {
697                         $gcontact_id = $r[0]["id"];
698
699                         // Update every 90 days
700                         if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
701                                 $last_failure_str = $r[0]["last_failure"];
702                                 $last_failure = strtotime($r[0]["last_failure"]);
703                                 $last_contact_str = $r[0]["last_contact"];
704                                 $last_contact = strtotime($r[0]["last_contact"]);
705                                 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
706                         }
707                 } else {
708                         q(
709                                 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
710                                 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
711                                 dbesc($contact["name"]),
712                                 dbesc($contact["nick"]),
713                                 dbesc($contact["addr"]),
714                                 dbesc($contact["network"]),
715                                 dbesc($contact["url"]),
716                                 dbesc(normalise_link($contact["url"])),
717                                 dbesc($contact["photo"]),
718                                 dbesc(DateTimeFormat::utcNow()),
719                                 dbesc(DateTimeFormat::utcNow()),
720                                 dbesc($contact["location"]),
721                                 dbesc($contact["about"]),
722                                 intval($contact["hide"]),
723                                 intval($contact["generation"])
724                         );
725
726                         $r = q(
727                                 "SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
728                                 dbesc(normalise_link($contact["url"]))
729                         );
730
731                         if (DBM::is_result($r)) {
732                                 $gcontact_id = $r[0]["id"];
733
734                                 $doprobing = in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""]);
735                         }
736                 }
737                 dba::unlock();
738
739                 if ($doprobing) {
740                         logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
741                         Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
742                 }
743
744                 return $gcontact_id;
745         }
746
747         /**
748          * @brief Updates the gcontact table from a given array
749          *
750          * @param array $contact contact array
751          *
752          * @return bool|int Returns false if not found, integer if contact was found
753          */
754         public static function update($contact)
755         {
756                 // Check for invalid "contact-type" value
757                 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
758                         $contact['contact-type'] = 0;
759                 }
760
761                 /// @todo update contact table as well
762
763                 $gcontact_id = self::getId($contact);
764
765                 if (!$gcontact_id) {
766                         return false;
767                 }
768
769                 $public_contact = q(
770                         "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
771                                 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
772                         FROM `gcontact` WHERE `id` = %d LIMIT 1",
773                         intval($gcontact_id)
774                 );
775
776                 // Get all field names
777                 $fields = [];
778                 foreach ($public_contact[0] as $field => $data) {
779                         $fields[$field] = $data;
780                 }
781
782                 unset($fields["url"]);
783                 unset($fields["updated"]);
784                 unset($fields["hide"]);
785
786                 // Bugfix: We had an error in the storing of keywords which lead to the "0"
787                 // This value is still transmitted via poco.
788                 if ($contact["keywords"] == "0") {
789                         unset($contact["keywords"]);
790                 }
791
792                 if ($public_contact[0]["keywords"] == "0") {
793                         $public_contact[0]["keywords"] = "";
794                 }
795
796                 // assign all unassigned fields from the database entry
797                 foreach ($fields as $field => $data) {
798                         if (!isset($contact[$field]) || ($contact[$field] == "")) {
799                                 $contact[$field] = $public_contact[0][$field];
800                         }
801                 }
802
803                 if (!isset($contact["hide"])) {
804                         $contact["hide"] = $public_contact[0]["hide"];
805                 }
806
807                 $fields["hide"] = $public_contact[0]["hide"];
808
809                 if ($contact["network"] == NETWORK_STATUSNET) {
810                         $contact["network"] = NETWORK_OSTATUS;
811                 }
812
813                 // Replace alternate OStatus user format with the primary one
814                 self::fixAlternateContactAddress($contact);
815
816                 if (!isset($contact["updated"])) {
817                         $contact["updated"] = DBM::date();
818                 }
819
820                 if ($contact["network"] == NETWORK_TWITTER) {
821                         $contact["server_url"] = 'http://twitter.com';
822                 }
823
824                 if ($contact["server_url"] == "") {
825                         $data = Probe::uri($contact["url"]);
826                         if ($data["network"] != NETWORK_PHANTOM) {
827                                 $contact["server_url"] = $data['baseurl'];
828                         }
829                 } else {
830                         $contact["server_url"] = normalise_link($contact["server_url"]);
831                 }
832
833                 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
834                         $hostname = str_replace("http://", "", $contact["server_url"]);
835                         $contact["addr"] = $contact["nick"]."@".$hostname;
836                 }
837
838                 // Check if any field changed
839                 $update = false;
840                 unset($fields["generation"]);
841
842                 if ((($contact["generation"] > 0) && ($contact["generation"] <= $public_contact[0]["generation"])) || ($public_contact[0]["generation"] == 0)) {
843                         foreach ($fields as $field => $data) {
844                                 if ($contact[$field] != $public_contact[0][$field]) {
845                                         logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$public_contact[0][$field]."'", LOGGER_DEBUG);
846                                         $update = true;
847                                 }
848                         }
849
850                         if ($contact["generation"] < $public_contact[0]["generation"]) {
851                                 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$public_contact[0]["generation"]."'", LOGGER_DEBUG);
852                                 $update = true;
853                         }
854                 }
855
856                 if ($update) {
857                         logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
858                         $condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
859                                         normalise_link($contact["url"]), $contact["generation"]];
860                         $contact["updated"] = DBM::date($contact["updated"]);
861
862                         $updated = ['photo' => $contact['photo'], 'name' => $contact['name'],
863                                         'nick' => $contact['nick'], 'addr' => $contact['addr'],
864                                         'network' => $contact['network'], 'birthday' => $contact['birthday'],
865                                         'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
866                                         'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
867                                         'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
868                                         'notify' => $contact['notify'], 'url' => $contact['url'],
869                                         'location' => $contact['location'], 'about' => $contact['about'],
870                                         'generation' => $contact['generation'], 'updated' => $contact['updated'],
871                                         'server_url' => $contact['server_url'], 'connect' => $contact['connect']];
872
873                         dba::update('gcontact', $updated, $condition, $fields);
874
875                         // Now update the contact entry with the user id "0" as well.
876                         // This is used for the shadow copies of public items.
877
878                         $public_contact = dba::selectFirst('contact', ['id'], ['nurl' => normalise_link($contact["url"]), 'uid' => 0]);
879                         if (DBM::is_result($public_contact)) {
880                                 logger("Update public contact ".$public_contact["id"], LOGGER_DEBUG);
881
882                                 Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]);
883
884                                 $fields = ['name', 'nick', 'addr',
885                                                 'network', 'bd', 'gender',
886                                                 'keywords', 'alias', 'contact-type',
887                                                 'url', 'location', 'about'];
888                                 $old_contact = dba::selectFirst('contact', $fields, ['id' => $public_contact["id"]]);
889
890                                 // Update it with the current values
891                                 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'],
892                                                 'addr' => $contact['addr'], 'network' => $contact['network'],
893                                                 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
894                                                 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
895                                                 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
896                                                 'location' => $contact['location'], 'about' => $contact['about']];
897
898                                 dba::update('contact', $fields, ['id' => $public_contact["id"]], $old_contact);
899                         }
900                 }
901
902                 return $gcontact_id;
903         }
904
905         /**
906          * @brief Updates the gcontact entry from probe
907          *
908          * @param string $url profile link
909          * @return void
910          */
911         public static function updateFromProbe($url)
912         {
913                 $data = Probe::uri($url);
914
915                 if (in_array($data["network"], [NETWORK_PHANTOM])) {
916                         logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
917                         return;
918                 }
919
920                 $data["server_url"] = $data["baseurl"];
921
922                 self::update($data);
923         }
924
925         /**
926          * @brief Update the gcontact entry for a given user id
927          *
928          * @param int $uid User ID
929          * @return void
930          */
931         public static function updateForUser($uid)
932         {
933                 $r = q(
934                         "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
935                                 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
936                                 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
937                                 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
938                                 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
939                         FROM `profile`
940                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
941                                 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
942                         WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
943                         intval($uid)
944                 );
945
946                 $location = Profile::formatLocation(
947                         ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
948                 );
949
950                 // The "addr" field was added in 3.4.3 so it can be empty for older users
951                 if ($r[0]["addr"] != "") {
952                         $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], "", System::baseUrl());
953                 } else {
954                         $addr = $r[0]["addr"];
955                 }
956
957                 $gcontact = ["name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
958                                 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
959                                 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
960                                 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
961                                 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
962                                 "nick" => $r[0]["nickname"], "addr" => $addr,
963                                 "connect" => $addr, "server_url" => System::baseUrl(),
964                                 "generation" => 1, "network" => NETWORK_DFRN];
965
966                 self::update($gcontact);
967         }
968
969         /**
970          * @brief Fetches users of given GNU Social server
971          *
972          * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
973          *
974          * @param string $server Server address
975          * @return void
976          */
977         public static function fetchGsUsers($server)
978         {
979                 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
980
981                 $url = $server."/main/statistics";
982
983                 $result = Network::curl($url);
984                 if (!$result["success"]) {
985                         return false;
986                 }
987
988                 $statistics = json_decode($result["body"]);
989
990                 if (is_object($statistics->config)) {
991                         if ($statistics->config->instance_with_ssl) {
992                                 $server = "https://";
993                         } else {
994                                 $server = "http://";
995                         }
996
997                         $server .= $statistics->config->instance_address;
998
999                         $hostname = $statistics->config->instance_address;
1000                 } else {
1001                         /// @TODO is_object() above means here no object, still $statistics is being used as object
1002                         if ($statistics->instance_with_ssl) {
1003                                 $server = "https://";
1004                         } else {
1005                                 $server = "http://";
1006                         }
1007
1008                         $server .= $statistics->instance_address;
1009
1010                         $hostname = $statistics->instance_address;
1011                 }
1012
1013                 if (is_object($statistics->users)) {
1014                         foreach ($statistics->users as $nick => $user) {
1015                                 $profile_url = $server."/".$user->nickname;
1016
1017                                 $contact = ["url" => $profile_url,
1018                                                 "name" => $user->fullname,
1019                                                 "addr" => $user->nickname."@".$hostname,
1020                                                 "nick" => $user->nickname,
1021                                                 "about" => $user->bio,
1022                                                 "network" => NETWORK_OSTATUS,
1023                                                 "photo" => System::baseUrl()."/images/person-175.jpg"];
1024                                 self::getId($contact);
1025                         }
1026                 }
1027         }
1028
1029         /**
1030          * @brief Asking GNU Social server on a regular base for their user data
1031          * @return void
1032          */
1033         public static function discoverGsUsers()
1034         {
1035                 $requery_days = intval(Config::get("system", "poco_requery_days"));
1036
1037                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1038
1039                 $r = q(
1040                         "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
1041                         dbesc(NETWORK_OSTATUS),
1042                         dbesc($last_update)
1043                 );
1044
1045                 if (!DBM::is_result($r)) {
1046                         return;
1047                 }
1048
1049                 foreach ($r as $server) {
1050                         self::fetchGsUsers($server["url"]);
1051                         q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(DateTimeFormat::utcNow()), dbesc($server["nurl"]));
1052                 }
1053         }
1054
1055         /**
1056          * @return string
1057          */
1058         public static function getRandomUrl()
1059         {
1060                 $r = q(
1061                         "SELECT `url` FROM `gcontact` WHERE `network` = '%s'
1062                                         AND `last_contact` >= `last_failure`
1063                                         AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
1064                                 ORDER BY rand() LIMIT 1",
1065                         dbesc(NETWORK_DFRN)
1066                 );
1067
1068                 if (DBM::is_result($r)) {
1069                         return dirname($r[0]['url']);
1070                 }
1071
1072                 return '';
1073         }
1074 }