]> git.mxchange.org Git - friendica.git/blob - src/Model/GContact.php
Merge pull request #8271 from MrPetovan/bug/8229-frio-mobile-back-to-top
[friendica.git] / src / Model / GContact.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Exception;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Core\Search;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Network\Probe;
34 use Friendica\Protocol\ActivityPub;
35 use Friendica\Protocol\PortableContact;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
39
40 /**
41  * This class handles GlobalContact related functions
42  */
43 class GContact
44 {
45         /**
46          * Search global contact table by nick or name
47          *
48          * @param string $search Name or nick
49          * @param string $mode   Search mode (e.g. "community")
50          *
51          * @return array with search results
52          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
53          */
54         public static function searchByName($search, $mode = '')
55         {
56                 if (empty($search)) {
57                         return [];
58                 }
59
60                 // check supported networks
61                 if (DI::config()->get('system', 'diaspora_enabled')) {
62                         $diaspora = Protocol::DIASPORA;
63                 } else {
64                         $diaspora = Protocol::DFRN;
65                 }
66
67                 if (!DI::config()->get('system', 'ostatus_disabled')) {
68                         $ostatus = Protocol::OSTATUS;
69                 } else {
70                         $ostatus = Protocol::DFRN;
71                 }
72
73                 // check if we search only communities or every contact
74                 if ($mode === 'community') {
75                         $extra_sql = ' AND `community`';
76                 } else {
77                         $extra_sql = '';
78                 }
79
80                 $search .= '%';
81
82                 $results = DBA::p("SELECT `nurl` FROM `gcontact`
83                         WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
84                                 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
85                                 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
86                                 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
87                         Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
88                 );
89
90                 $gcontacts = [];
91                 while ($result = DBA::fetch($results)) {
92                         $urlparts = parse_url($result['nurl']);
93
94                         // Ignore results that look strange.
95                         // For historic reasons the gcontact table does contain some garbage.
96                         if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
97                                 continue;
98                         }
99
100                         $gcontacts[] = Contact::getDetailsByURL($result['nurl'], local_user());
101                 }
102                 return $gcontacts;
103         }
104
105         /**
106          * Link the gcontact entry with user, contact and global contact
107          *
108          * @param integer $gcid Global contact ID
109          * @param integer $uid  User ID
110          * @param integer $cid  Contact ID
111          * @param integer $zcid Global Contact ID
112          * @return void
113          * @throws Exception
114          */
115         public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
116         {
117                 if ($gcid <= 0) {
118                         return;
119                 }
120
121                 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
122                 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
123         }
124
125         /**
126          * Sanitize the given gcontact data
127          *
128          * Generation:
129          *  0: No definition
130          *  1: Profiles on this server
131          *  2: Contacts of profiles on this server
132          *  3: Contacts of contacts of profiles on this server
133          *  4: ...
134          *
135          * @param array $gcontact array with gcontact data
136          * @return array $gcontact
137          * @throws Exception
138          */
139         public static function sanitize($gcontact)
140         {
141                 if (empty($gcontact['url'])) {
142                         throw new Exception('URL is empty');
143                 }
144
145                 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
146
147                 $urlparts = parse_url($gcontact['url']);
148                 if (empty($urlparts['scheme'])) {
149                         throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
150                 }
151
152                 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
153                         throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
154                 }
155
156                 // Don't store the statusnet connector as network
157                 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
158                 if ($gcontact['network'] == Protocol::STATUSNET) {
159                         $gcontact['network'] = '';
160                 }
161
162                 // Assure that there are no parameter fragments in the profile url
163                 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
164                         $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
165                 }
166
167                 // The global contacts should contain the original picture, not the cached one
168                 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(DI::baseUrl() . '/photo/'))) {
169                         $gcontact['photo'] = '';
170                 }
171
172                 if (empty($gcontact['network'])) {
173                         $gcontact['network'] = '';
174
175                         $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
176                                 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
177                         $contact = DBA::selectFirst('contact', ['network'], $condition);
178                         if (DBA::isResult($contact)) {
179                                 $gcontact['network'] = $contact['network'];
180                         }
181
182                         if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
183                                 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
184                                         $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
185                                 $contact = DBA::selectFirst('contact', ['network'], $condition);
186                                 if (DBA::isResult($contact)) {
187                                         $gcontact['network'] = $contact['network'];
188                                 }
189                         }
190                 }
191
192                 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
193                 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
194                 if (DBA::isResult($gcnt)) {
195                         if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
196                                 $gcontact['network'] = $gcnt['network'];
197                         }
198                         if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
199                                 $gcontact['updated'] = $gcnt['updated'];
200                         }
201                         if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
202                                 $gcontact['server_url'] = $gcnt['server_url'];
203                         }
204                         if (!isset($gcontact['addr'])) {
205                                 $gcontact['addr'] = $gcnt['addr'];
206                         }
207                 }
208
209                 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
210                         && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
211                 ) {
212                         $data = Probe::uri($gcontact['url']);
213
214                         if ($data['network'] == Protocol::PHANTOM) {
215                                 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
216                         }
217
218                         $orig_profile = $gcontact['url'];
219
220                         $gcontact['server_url'] = $data['baseurl'];
221
222                         $gcontact = array_merge($gcontact, $data);
223                 }
224
225                 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
226                         throw new Exception('No name and photo for URL '.$gcontact['url']);
227                 }
228
229                 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
230                         throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
231                 }
232
233                 if (empty($gcontact['server_url'])) {
234                         // We check the server url to be sure that it is a real one
235                         $server_url = self::getBasepath($gcontact['url']);
236
237                         // We are now sure that it is a correct URL. So we use it in the future
238                         if ($server_url != '') {
239                                 $gcontact['server_url'] = $server_url;
240                         }
241                 }
242
243                 // The server URL doesn't seem to be valid, so we don't store it.
244                 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
245                         $gcontact['server_url'] = '';
246                 }
247
248                 return $gcontact;
249         }
250
251         /**
252          * @param integer $uid id
253          * @param integer $cid id
254          * @return integer
255          * @throws Exception
256          */
257         public static function countCommonFriends($uid, $cid)
258         {
259                 $r = q(
260                         "SELECT count(*) as `total`
261                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
262                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
263                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
264                         (`gcontact`.`updated` >= `gcontact`.`last_failure`))
265                         AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
266                         intval($cid),
267                         intval($uid),
268                         intval($uid),
269                         intval($cid)
270                 );
271
272                 if (DBA::isResult($r)) {
273                         return $r[0]['total'];
274                 }
275                 return 0;
276         }
277
278         /**
279          * @param integer $uid  id
280          * @param integer $zcid zcid
281          * @return integer
282          * @throws Exception
283          */
284         public static function countCommonFriendsZcid($uid, $zcid)
285         {
286                 $r = q(
287                         "SELECT count(*) as `total`
288                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
289                         where `glink`.`zcid` = %d
290                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
291                         intval($zcid),
292                         intval($uid)
293                 );
294
295                 if (DBA::isResult($r)) {
296                         return $r[0]['total'];
297                 }
298
299                 return 0;
300         }
301
302         /**
303          * @param integer $uid     user
304          * @param integer $cid     cid
305          * @param integer $start   optional, default 0
306          * @param integer $limit   optional, default 9999
307          * @param boolean $shuffle optional, default false
308          * @return object
309          * @throws Exception
310          */
311         public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
312         {
313                 if ($shuffle) {
314                         $sql_extra = " order by rand() ";
315                 } else {
316                         $sql_extra = " order by `gcontact`.`name` asc ";
317                 }
318
319                 $r = q(
320                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
321                         FROM `glink`
322                         INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
323                         INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
324                         WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
325                                 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
326                                 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
327                                 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
328                                 $sql_extra LIMIT %d, %d",
329                         intval($cid),
330                         intval($uid),
331                         intval($uid),
332                         intval($cid),
333                         intval($start),
334                         intval($limit)
335                 );
336
337                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
338                 return $r;
339         }
340
341         /**
342          * @param integer $uid     user
343          * @param integer $zcid    zcid
344          * @param integer $start   optional, default 0
345          * @param integer $limit   optional, default 9999
346          * @param boolean $shuffle optional, default false
347          * @return object
348          * @throws Exception
349          */
350         public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
351         {
352                 if ($shuffle) {
353                         $sql_extra = " order by rand() ";
354                 } else {
355                         $sql_extra = " order by `gcontact`.`name` asc ";
356                 }
357
358                 $r = q(
359                         "SELECT `gcontact`.*
360                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
361                         where `glink`.`zcid` = %d
362                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
363                         $sql_extra limit %d, %d",
364                         intval($zcid),
365                         intval($uid),
366                         intval($start),
367                         intval($limit)
368                 );
369
370                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
371                 return $r;
372         }
373
374         /**
375          * @param integer $uid user
376          * @param integer $cid cid
377          * @return integer
378          * @throws Exception
379          */
380         public static function countAllFriends($uid, $cid)
381         {
382                 $r = q(
383                         "SELECT count(*) as `total`
384                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
385                         where `glink`.`cid` = %d and `glink`.`uid` = %d AND
386                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
387                         intval($cid),
388                         intval($uid)
389                 );
390
391                 if (DBA::isResult($r)) {
392                         return $r[0]['total'];
393                 }
394
395                 return 0;
396         }
397
398         /**
399          * @param integer $uid   user
400          * @param integer $cid   cid
401          * @param integer $start optional, default 0
402          * @param integer $limit optional, default 80
403          * @return array
404          * @throws Exception
405          */
406         public static function allFriends($uid, $cid, $start = 0, $limit = 80)
407         {
408                 $r = q(
409                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
410                         FROM `glink`
411                         INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
412                         LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
413                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
414                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
415                         ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
416                         intval($uid),
417                         intval($cid),
418                         intval($uid),
419                         intval($start),
420                         intval($limit)
421                 );
422
423                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
424                 return $r;
425         }
426
427         /**
428          * @param int     $uid   user
429          * @param integer $start optional, default 0
430          * @param integer $limit optional, default 80
431          * @return array
432          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
433          */
434         public static function suggestionQuery($uid, $start = 0, $limit = 80)
435         {
436                 if (!$uid) {
437                         return [];
438                 }
439
440                 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
441
442                 if (DI::config()->get('system', 'diaspora_enabled')) {
443                         $network[] = Protocol::DIASPORA;
444                 }
445
446                 if (!DI::config()->get('system', 'ostatus_disabled')) {
447                         $network[] = Protocol::OSTATUS;
448                 }
449
450                 $sql_network = "'" . implode("', '", $network) . "'";
451
452                 /// @todo This query is really slow
453                 // By now we cache the data for five minutes
454                 $r = q(
455                         "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
456                         INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
457                         where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
458                         AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
459                         AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
460                         AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
461                         AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
462                         AND `gcontact`.`network` IN (%s)
463                         GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
464                         intval($uid),
465                         intval($uid),
466                         intval($uid),
467                         intval($uid),
468                         DBA::NULL_DATETIME,
469                         $sql_network,
470                         intval($start),
471                         intval($limit)
472                 );
473
474                 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
475                         return $r;
476                 }
477
478                 $r2 = q(
479                         "SELECT gcontact.* FROM gcontact
480                         INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
481                         WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
482                         AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
483                         AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
484                         AND `gcontact`.`updated` >= '%s'
485                         AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
486                         AND `gcontact`.`network` IN (%s)
487                         ORDER BY rand() LIMIT %d, %d",
488                         intval($uid),
489                         intval($uid),
490                         intval($uid),
491                         DBA::NULL_DATETIME,
492                         $sql_network,
493                         intval($start),
494                         intval($limit)
495                 );
496
497                 $list = [];
498                 foreach ($r2 as $suggestion) {
499                         $list[$suggestion['nurl']] = $suggestion;
500                 }
501
502                 foreach ($r as $suggestion) {
503                         $list[$suggestion['nurl']] = $suggestion;
504                 }
505
506                 while (sizeof($list) > ($limit)) {
507                         array_pop($list);
508                 }
509
510                 return $list;
511         }
512
513         /**
514          * @return void
515          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
516          */
517         public static function updateSuggestions()
518         {
519                 $done = [];
520
521                 /// @TODO Check if it is really neccessary to poll the own server
522                 PortableContact::loadWorker(0, 0, 0, DI::baseUrl() . '/poco');
523
524                 $done[] = DI::baseUrl() . '/poco';
525
526                 if (strlen(DI::config()->get('system', 'directory'))) {
527                         $x = Network::fetchUrl(Search::getGlobalDirectory() . '/pubsites');
528                         if (!empty($x)) {
529                                 $j = json_decode($x);
530                                 if (!empty($j->entries)) {
531                                         foreach ($j->entries as $entry) {
532                                                 GServer::check($entry->url);
533
534                                                 $url = $entry->url . '/poco';
535                                                 if (!in_array($url, $done)) {
536                                                         PortableContact::loadWorker(0, 0, 0, $url);
537                                                         $done[] = $url;
538                                                 }
539                                         }
540                                 }
541                         }
542                 }
543
544                 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
545                 $contacts = DBA::p("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN (?, ?)", Protocol::DFRN, Protocol::DIASPORA);
546                 while ($contact = DBA::fetch($contacts)) {
547                         $base = substr($contact['poco'], 0, strrpos($contact['poco'], '/'));
548                         if (!in_array($base, $done)) {
549                                 PortableContact::loadWorker(0, 0, 0, $base);
550                         }
551                 }
552         }
553
554         /**
555          * Removes unwanted parts from a contact url
556          *
557          * @param string $url Contact url
558          *
559          * @return string Contact url with the wanted parts
560          * @throws Exception
561          */
562         public static function cleanContactUrl($url)
563         {
564                 $parts = parse_url($url);
565
566                 if (empty($parts['scheme']) || empty($parts['host'])) {
567                         return $url;
568                 }
569
570                 $new_url = $parts['scheme'] . '://' . $parts['host'];
571
572                 if (!empty($parts['port'])) {
573                         $new_url .= ':' . $parts['port'];
574                 }
575
576                 if (!empty($parts['path'])) {
577                         $new_url .= $parts['path'];
578                 }
579
580                 if ($new_url != $url) {
581                         Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
582                 }
583
584                 return $new_url;
585         }
586
587         /**
588          * Fetch the gcontact id, add an entry if not existed
589          *
590          * @param array $contact contact array
591          *
592          * @return bool|int Returns false if not found, integer if contact was found
593          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
594          * @throws \ImagickException
595          */
596         public static function getId($contact)
597         {
598                 $gcontact_id = 0;
599
600                 if (empty($contact['network'])) {
601                         Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
602                         return false;
603                 }
604
605                 if (in_array($contact['network'], [Protocol::PHANTOM])) {
606                         Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
607                         return false;
608                 }
609
610                 if ($contact['network'] == Protocol::STATUSNET) {
611                         $contact['network'] = Protocol::OSTATUS;
612                 }
613
614                 // All new contacts are hidden by default
615                 if (!isset($contact['hide'])) {
616                         $contact['hide'] = true;
617                 }
618
619                 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
620                 if (in_array($contact['network'], Protocol::FEDERATED)) {
621                         $contact['url'] = self::cleanContactUrl($contact['url']);
622                 }
623
624                 DBA::lock('gcontact');
625                 $fields = ['id', 'last_contact', 'last_failure', 'network'];
626                 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
627                 if (DBA::isResult($gcnt)) {
628                         $gcontact_id = $gcnt['id'];
629                 } else {
630                         $contact['location'] = $contact['location'] ?? '';
631                         $contact['about'] = $contact['about'] ?? '';
632                         $contact['generation'] = $contact['generation'] ?? 0;
633
634                         $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
635                                 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
636                                 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
637                                 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation']];
638
639                         DBA::insert('gcontact', $fields);
640
641                         $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
642                         $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
643                         if (DBA::isResult($cnt)) {
644                                 $gcontact_id = $cnt['id'];
645                         }
646                 }
647                 DBA::unlock();
648
649                 return $gcontact_id;
650         }
651
652         /**
653          * Updates the gcontact table from a given array
654          *
655          * @param array $contact contact array
656          *
657          * @return bool|int Returns false if not found, integer if contact was found
658          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
659          * @throws \ImagickException
660          */
661         public static function update($contact)
662         {
663                 // Check for invalid "contact-type" value
664                 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
665                         $contact['contact-type'] = 0;
666                 }
667
668                 /// @todo update contact table as well
669
670                 $gcontact_id = self::getId($contact);
671
672                 if (!$gcontact_id) {
673                         return false;
674                 }
675
676                 $public_contact = DBA::selectFirst('gcontact', [
677                         'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'gender', 'keywords',
678                         'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
679                 ], ['id' => $gcontact_id]);
680
681                 if (!DBA::isResult($public_contact)) {
682                         return false;
683                 }
684
685                 // Get all field names
686                 $fields = [];
687                 foreach ($public_contact as $field => $data) {
688                         $fields[$field] = $data;
689                 }
690
691                 unset($fields['url']);
692                 unset($fields['updated']);
693                 unset($fields['hide']);
694
695                 // Bugfix: We had an error in the storing of keywords which lead to the "0"
696                 // This value is still transmitted via poco.
697                 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
698                         unset($contact['keywords']);
699                 }
700
701                 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
702                         $public_contact['keywords'] = '';
703                 }
704
705                 // assign all unassigned fields from the database entry
706                 foreach ($fields as $field => $data) {
707                         if (empty($contact[$field])) {
708                                 $contact[$field] = $public_contact[$field];
709                         }
710                 }
711
712                 if (!isset($contact['hide'])) {
713                         $contact['hide'] = $public_contact['hide'];
714                 }
715
716                 $fields['hide'] = $public_contact['hide'];
717
718                 if ($contact['network'] == Protocol::STATUSNET) {
719                         $contact['network'] = Protocol::OSTATUS;
720                 }
721
722                 if (!isset($contact['updated'])) {
723                         $contact['updated'] = DateTimeFormat::utcNow();
724                 }
725
726                 if ($contact['network'] == Protocol::TWITTER) {
727                         $contact['server_url'] = 'http://twitter.com';
728                 }
729
730                 if (empty($contact['server_url'])) {
731                         $data = Probe::uri($contact['url']);
732                         if ($data['network'] != Protocol::PHANTOM) {
733                                 $contact['server_url'] = $data['baseurl'];
734                         }
735                 } else {
736                         $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
737                 }
738
739                 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
740                         $hostname = str_replace('http://', '', $contact['server_url']);
741                         $contact['addr'] = $contact['nick'] . '@' . $hostname;
742                 }
743
744                 // Check if any field changed
745                 $update = false;
746                 unset($fields['generation']);
747
748                 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
749                         foreach ($fields as $field => $data) {
750                                 if ($contact[$field] != $public_contact[$field]) {
751                                         Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
752                                         $update = true;
753                                 }
754                         }
755
756                         if ($contact['generation'] < $public_contact['generation']) {
757                                 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
758                                 $update = true;
759                         }
760                 }
761
762                 if ($update) {
763                         Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
764                         $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
765                                         Strings::normaliseLink($contact['url']), $contact['generation']];
766                         $contact['updated'] = DateTimeFormat::utc($contact['updated']);
767
768                         $updated = [
769                                 'photo' => $contact['photo'], 'name' => $contact['name'],
770                                 'nick' => $contact['nick'], 'addr' => $contact['addr'],
771                                 'network' => $contact['network'], 'birthday' => $contact['birthday'],
772                                 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
773                                 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
774                                 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
775                                 'notify' => $contact['notify'], 'url' => $contact['url'],
776                                 'location' => $contact['location'], 'about' => $contact['about'],
777                                 'generation' => $contact['generation'], 'updated' => $contact['updated'],
778                                 'server_url' => $contact['server_url'], 'connect' => $contact['connect']
779                         ];
780
781                         DBA::update('gcontact', $updated, $condition, $fields);
782                 }
783
784                 return $gcontact_id;
785         }
786
787         /**
788          * Set the last date that the contact had posted something
789          *
790          * @param string $data  Probing result
791          * @param bool   $force force updating
792          */
793         public static function setLastUpdate(array $data, bool $force = false)
794         {
795                 // Fetch the global contact
796                 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
797                         ['nurl' => Strings::normaliseLink($data['url'])]);
798                 if (!DBA::isResult($gcontact)) {
799                         return;
800                 }
801
802                 if (!$force && !GServer::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
803                         Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
804                         return;
805                 }
806
807                 if (self::updateFromNoScrape($data)) {
808                         return;
809                 }
810
811                 if (!empty($data['outbox'])) {
812                         self::updateFromOutbox($data['outbox'], $data);
813                 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
814                         self::updateFromOutbox($data['poll'], $data);
815                 } elseif (!empty($data['poll'])) {
816                         self::updateFromFeed($data);
817                 }
818         }
819
820         /**
821          * Update a global contact via the "noscrape" endpoint
822          *
823          * @param string $data Probing result
824          *
825          * @return bool 'true' if update was successful or the server was unreachable
826          */
827         private static function updateFromNoScrape(array $data)
828         {
829                 // Check the 'noscrape' endpoint when it is a Friendica server
830                 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
831                 Strings::normaliseLink($data['baseurl'])]);
832                 if (!DBA::isResult($gserver)) {
833                         return false;
834                 }
835
836                 $curlResult = Network::curl($gserver['noscrape'] . '/' . $data['nick']);
837
838                 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
839                         $noscrape = json_decode($curlResult->getBody(), true);
840                         if (!empty($noscrape) && !empty($noscrape['updated'])) {
841                                 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
842                                 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
843                                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
844                                 return true;
845                         }
846                 } elseif ($curlResult->isTimeout()) {
847                         // On a timeout return the existing value, but mark the contact as failure
848                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
849                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
850                         return true;
851                 }
852                 return false;
853         }
854
855         /**
856          * Update a global contact via an ActivityPub Outbox
857          *
858          * @param string $feed
859          * @param array  $data Probing result
860          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
861          */
862         private static function updateFromOutbox(string $feed, array $data)
863         {
864                 $outbox = ActivityPub::fetchContent($feed);
865                 if (empty($outbox)) {
866                         return;
867                 }
868
869                 if (!empty($outbox['orderedItems'])) {
870                         $items = $outbox['orderedItems'];
871                 } elseif (!empty($outbox['first']['orderedItems'])) {
872                         $items = $outbox['first']['orderedItems'];
873                 } elseif (!empty($outbox['first']['href'])) {
874                         self::updateFromOutbox($outbox['first']['href'], $data);
875                         return;
876                 } elseif (!empty($outbox['first'])) {
877                         if (is_string($outbox['first'])) {
878                                 self::updateFromOutbox($outbox['first'], $data);
879                         } else {
880                                 Logger::warning('Unexpected data', ['outbox' => $outbox]);
881                         }
882                         return;
883                 } else {
884                         $items = [];
885                 }
886
887                 $last_updated = '';
888                 foreach ($items as $activity) {
889                         if (!empty($activity['published'])) {
890                                 $published =  DateTimeFormat::utc($activity['published']);
891                         } elseif (!empty($activity['object']['published'])) {
892                                 $published =  DateTimeFormat::utc($activity['object']['published']);
893                         } else {
894                                 continue;
895                         }
896
897                         if ($last_updated < $published) {
898                                 $last_updated = $published;
899                         }
900                 }
901
902                 if (empty($last_updated)) {
903                         return;
904                 }
905
906                 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
907                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
908         }
909
910         /**
911          * Update a global contact via an XML feed
912          *
913          * @param string $data Probing result
914          */
915         private static function updateFromFeed(array $data)
916         {
917                 // Search for the newest entry in the feed
918                 $curlResult = Network::curl($data['poll']);
919                 if (!$curlResult->isSuccess()) {
920                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
921                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
922
923                         Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
924                         return;
925                 }
926
927                 $doc = new DOMDocument();
928                 @$doc->loadXML($curlResult->getBody());
929
930                 $xpath = new DOMXPath($doc);
931                 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
932
933                 $entries = $xpath->query('/atom:feed/atom:entry');
934
935                 $last_updated = '';
936
937                 foreach ($entries as $entry) {
938                         $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
939                         $updated_item   = $xpath->query('atom:updated/text()'  , $entry)->item(0);
940                         $published      = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
941                         $updated        = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
942
943                         if (empty($published) || empty($updated)) {
944                                 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
945                                 continue;
946                         }
947
948                         if ($last_updated < $published) {
949                                 $last_updated = $published;
950                         }
951
952                         if ($last_updated < $updated) {
953                                 $last_updated = $updated;
954                         }
955                 }
956
957                 if (empty($last_updated)) {
958                         return;
959                 }
960
961                 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
962                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
963         }
964         /**
965          * Updates the gcontact entry from a given public contact id
966          *
967          * @param integer $cid contact id
968          * @return void
969          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
970          * @throws \ImagickException
971          */
972         public static function updateFromPublicContactID($cid)
973         {
974                 self::updateFromPublicContact(['id' => $cid]);
975         }
976
977         /**
978          * Updates the gcontact entry from a given public contact url
979          *
980          * @param string $url contact url
981          * @return integer gcontact id
982          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
983          * @throws \ImagickException
984          */
985         public static function updateFromPublicContactURL($url)
986         {
987                 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
988         }
989
990         /**
991          * Helper function for updateFromPublicContactID and updateFromPublicContactURL
992          *
993          * @param array $condition contact condition
994          * @return integer gcontact id
995          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996          * @throws \ImagickException
997          */
998         private static function updateFromPublicContact($condition)
999         {
1000                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
1001                         'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
1002                         'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
1003                         'baseurl', 'sensitive', 'unsearchable'];
1004
1005                 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
1006                 if (!DBA::isResult($contact)) {
1007                         return 0;
1008                 }
1009
1010                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender', 'generation',
1011                         'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
1012                         'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
1013                         'server_url', 'nsfw', 'hide', 'id'];
1014
1015                 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1016                 $do_insert = !DBA::isResult($old_gcontact);
1017                 if ($do_insert) {
1018                         $old_gcontact = [];
1019                 }
1020
1021                 $gcontact = [];
1022
1023                 // These fields are identical in both contact and gcontact
1024                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
1025                         'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
1026
1027                 foreach ($fields as $field) {
1028                         $gcontact[$field] = $contact[$field];
1029                 }
1030
1031                 // These fields are having different names but the same content
1032                 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1033                 $gcontact['nsfw'] = $contact['sensitive'];
1034                 $gcontact['hide'] = $contact['unsearchable'];
1035                 $gcontact['archived'] = $contact['archive'];
1036                 $gcontact['archive_date'] = $contact['term-date'];
1037                 $gcontact['birthday'] = $contact['bd'];
1038                 $gcontact['photo'] = $contact['avatar'];
1039                 $gcontact['last_contact'] = $contact['success_update'];
1040                 $gcontact['last_failure'] = $contact['failure_update'];
1041                 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1042
1043                 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1044                         if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1045                                 unset($gcontact[$field]);
1046                         }
1047                 }
1048
1049                 if (!$gcontact['archived']) {
1050                         $gcontact['archive_date'] = DBA::NULL_DATETIME;
1051                 }
1052
1053                 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1054                         && ($old_gcontact['created'] <= $gcontact['created'])) {
1055                         unset($gcontact['created']);
1056                 }
1057
1058                 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1059                         unset($gcontact['birthday']);
1060                 }
1061
1062                 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1063                         $gcontact['generation'] = 2; // We fetched the data directly from the other server
1064                 }
1065
1066                 if (!$do_insert) {
1067                         DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1068                         return $old_gcontact['id'];
1069                 } elseif (!$gcontact['archived']) {
1070                         DBA::insert('gcontact', $gcontact);
1071                         return DBA::lastInsertId();
1072                 }
1073         }
1074
1075         /**
1076          * Updates the gcontact entry from probe
1077          *
1078          * @param string  $url   profile link
1079          * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1080          *
1081          * @return boolean 'true' when contact had been updated
1082          *
1083          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1084          * @throws \ImagickException
1085          */
1086         public static function updateFromProbe($url, $force = false)
1087         {
1088                 $data = Probe::uri($url, $force);
1089
1090                 if (in_array($data['network'], [Protocol::PHANTOM])) {
1091                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
1092                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1093                         Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1094                         return false;
1095                 }
1096
1097                 $data['server_url'] = $data['baseurl'];
1098
1099                 self::update($data);
1100
1101                 // Set the date of the latest post
1102                 self::setLastUpdate($data, $force);
1103
1104                 return true;
1105         }
1106
1107         /**
1108          * Update the gcontact entry for a given user id
1109          *
1110          * @param int $uid User ID
1111          * @return bool
1112          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1113          * @throws \ImagickException
1114          */
1115         public static function updateForUser($uid)
1116         {
1117                 $profile = Profile::getByUID($uid);
1118                 if (empty($profile)) {
1119                         Logger::error('Cannot find profile', ['uid' => $uid]);
1120                         return false;
1121                 }
1122
1123                 $user = User::getOwnerDataById($uid);
1124                 if (empty($user)) {
1125                         Logger::error('Cannot find user', ['uid' => $uid]);
1126                         return false;
1127                 }
1128
1129                 $userdata = array_merge($profile, $user);
1130
1131                 $location = Profile::formatLocation(
1132                         ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
1133                 );
1134
1135                 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
1136                                 'gender' => '', 'keywords' => $userdata['pub_keywords'],
1137                                 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
1138                                 "notify" => $userdata['notify'], 'url' => $userdata['url'],
1139                                 "hide" => ($userdata['hidewall'] || !$userdata['net-publish']),
1140                                 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
1141                                 "connect" => $userdata['addr'], "server_url" => DI::baseUrl(),
1142                                 "generation" => 1, 'network' => Protocol::DFRN];
1143
1144                 self::update($gcontact);
1145         }
1146
1147         /**
1148          * Get the basepath for a given contact link
1149          *
1150          * @param string $url The gcontact link
1151          * @param boolean $dont_update Don't update the contact
1152          *
1153          * @return string basepath
1154          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1155          * @throws \ImagickException
1156          */
1157         public static function getBasepath($url, $dont_update = false)
1158         {
1159                 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1160                 if (!empty($gcontact['server_url'])) {
1161                         return $gcontact['server_url'];
1162                 } elseif ($dont_update) {
1163                         return '';
1164                 }
1165
1166                 self::updateFromProbe($url, true);
1167
1168                 // Fetch the result
1169                 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1170                 if (empty($gcontact['server_url'])) {
1171                         Logger::info('No baseurl for gcontact', ['url' => $url]);
1172                         return '';
1173                 }
1174
1175                 Logger::info('Found baseurl for gcontact', ['url' => $url, 'baseurl' => $gcontact['server_url']]);
1176                 return $gcontact['server_url'];
1177         }
1178
1179         /**
1180          * Fetches users of given GNU Social server
1181          *
1182          * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1183          *
1184          * @param string $server Server address
1185          * @return bool
1186          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1187          * @throws \ImagickException
1188          */
1189         public static function fetchGsUsers($server)
1190         {
1191                 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1192
1193                 $url = $server . '/main/statistics';
1194
1195                 $curlResult = Network::curl($url);
1196                 if (!$curlResult->isSuccess()) {
1197                         return false;
1198                 }
1199
1200                 $statistics = json_decode($curlResult->getBody());
1201
1202                 if (!empty($statistics->config->instance_address)) {
1203                         if (!empty($statistics->config->instance_with_ssl)) {
1204                                 $server = 'https://';
1205                         } else {
1206                                 $server = 'http://';
1207                         }
1208
1209                         $server .= $statistics->config->instance_address;
1210
1211                         $hostname = $statistics->config->instance_address;
1212                 } elseif (!empty($statistics->instance_address)) {
1213                         if (!empty($statistics->instance_with_ssl)) {
1214                                 $server = 'https://';
1215                         } else {
1216                                 $server = 'http://';
1217                         }
1218
1219                         $server .= $statistics->instance_address;
1220
1221                         $hostname = $statistics->instance_address;
1222                 }
1223
1224                 if (!empty($statistics->users)) {
1225                         foreach ($statistics->users as $nick => $user) {
1226                                 $profile_url = $server . '/' . $user->nickname;
1227
1228                                 $contact = ['url' => $profile_url,
1229                                                 'name' => $user->fullname,
1230                                                 'addr' => $user->nickname . '@' . $hostname,
1231                                                 'nick' => $user->nickname,
1232                                                 "network" => Protocol::OSTATUS,
1233                                                 'photo' => DI::baseUrl() . '/images/person-300.jpg'];
1234
1235                                 if (isset($user->bio)) {
1236                                         $contact['about'] = $user->bio;
1237                                 }
1238
1239                                 self::getId($contact);
1240                         }
1241                 }
1242         }
1243
1244         /**
1245          * Asking GNU Social server on a regular base for their user data
1246          *
1247          * @return void
1248          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1249          * @throws \ImagickException
1250          */
1251         public static function discoverGsUsers()
1252         {
1253                 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1254
1255                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1256
1257                 $r = DBA::select('gserver', ['nurl', 'url'], [
1258                         '`network` = ?
1259                         AND `last_contact` >= `last_failure`
1260                         AND `last_poco_query` < ?',
1261                         Protocol::OSTATUS,
1262                         $last_update
1263                 ], [
1264                         'limit' => 5,
1265                         'order' => ['RAND()']
1266                 ]);
1267
1268                 if (!DBA::isResult($r)) {
1269                         return;
1270                 }
1271
1272                 foreach ($r as $server) {
1273                         self::fetchGsUsers($server['url']);
1274                         DBA::update('gserver', ['last_poco_query' => DateTimeFormat::utcNow()], ['nurl' => $server['nurl']]);
1275                 }
1276         }
1277
1278         /**
1279          * Returns a random, global contact of the current node
1280          *
1281          * @return string The profile URL
1282          * @throws Exception
1283          */
1284         public static function getRandomUrl()
1285         {
1286                 $r = DBA::selectFirst('gcontact', ['url'], [
1287                         '`network` = ? 
1288                         AND `last_contact` >= `last_failure`  
1289                         AND `updated` > ?',
1290                         Protocol::DFRN,
1291                         DateTimeFormat::utc('now - 1 month'),
1292                 ], ['order' => ['RAND()']]);
1293
1294                 if (DBA::isResult($r)) {
1295                         return $r['url'];
1296                 }
1297
1298                 return '';
1299         }
1300 }