]> git.mxchange.org Git - friendica.git/blob - src/Model/GContact.php
Merge pull request #8939 from MrPetovan/task/8906-frio-viewas-redesign
[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\Search;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Network\Probe;
35 use Friendica\Protocol\ActivityPub;
36 use Friendica\Protocol\PortableContact;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\Network;
39 use Friendica\Util\Strings;
40
41 /**
42  * This class handles GlobalContact related functions
43  */
44 class GContact
45 {
46         /**
47          * Search global contact table by nick or name
48          *
49          * @param string $search Name or nick
50          * @param string $mode   Search mode (e.g. "community")
51          *
52          * @return array with search results
53          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
54          */
55         public static function searchByName($search, $mode = '')
56         {
57                 if (empty($search)) {
58                         return [];
59                 }
60
61                 // check supported networks
62                 if (DI::config()->get('system', 'diaspora_enabled')) {
63                         $diaspora = Protocol::DIASPORA;
64                 } else {
65                         $diaspora = Protocol::DFRN;
66                 }
67
68                 if (!DI::config()->get('system', 'ostatus_disabled')) {
69                         $ostatus = Protocol::OSTATUS;
70                 } else {
71                         $ostatus = Protocol::DFRN;
72                 }
73
74                 // check if we search only communities or every contact
75                 if ($mode === 'community') {
76                         $extra_sql = ' AND `community`';
77                 } else {
78                         $extra_sql = '';
79                 }
80
81                 $search .= '%';
82
83                 $results = DBA::p("SELECT `nurl` FROM `gcontact`
84                         WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
85                                 NOT `failed` AND
86                                 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
87                                 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
88                         Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
89                 );
90
91                 $gcontacts = [];
92                 while ($result = DBA::fetch($results)) {
93                         $urlparts = parse_url($result['nurl']);
94
95                         // Ignore results that look strange.
96                         // For historic reasons the gcontact table does contain some garbage.
97                         if (empty($result['nurl']) || !empty($urlparts['query']) || !empty($urlparts['fragment'])) {
98                                 continue;
99                         }
100
101                         $gcontacts[] = Contact::getByURLForUser($result['nurl'], local_user());
102                 }
103                 DBA::close($results);
104                 return $gcontacts;
105         }
106
107         /**
108          * Link the gcontact entry with user, contact and global contact
109          *
110          * @param integer $gcid Global contact ID
111          * @param integer $uid  User ID
112          * @param integer $cid  Contact ID
113          * @param integer $zcid Global Contact ID
114          * @return void
115          * @throws Exception
116          */
117         public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
118         {
119                 if ($gcid <= 0) {
120                         return;
121                 }
122
123                 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
124                 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
125         }
126
127         /**
128          * Sanitize the given gcontact data
129          *
130          * Generation:
131          *  0: No definition
132          *  1: Profiles on this server
133          *  2: Contacts of profiles on this server
134          *  3: Contacts of contacts of profiles on this server
135          *  4: ...
136          *
137          * @param array $gcontact array with gcontact data
138          * @return array $gcontact
139          * @throws Exception
140          */
141         public static function sanitize($gcontact)
142         {
143                 if (empty($gcontact['url'])) {
144                         throw new Exception('URL is empty');
145                 }
146
147                 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
148
149                 $urlparts = parse_url($gcontact['url']);
150                 if (empty($urlparts['scheme'])) {
151                         throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
152                 }
153
154                 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
155                         throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
156                 }
157
158                 // Don't store the statusnet connector as network
159                 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
160                 if ($gcontact['network'] == Protocol::STATUSNET) {
161                         $gcontact['network'] = '';
162                 }
163
164                 // Assure that there are no parameter fragments in the profile url
165                 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
166                         $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
167                 }
168
169                 // The global contacts should contain the original picture, not the cached one
170                 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(DI::baseUrl() . '/photo/'))) {
171                         $gcontact['photo'] = '';
172                 }
173
174                 if (empty($gcontact['network'])) {
175                         $gcontact['network'] = '';
176
177                         $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
178                                 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
179                         $contact = DBA::selectFirst('contact', ['network'], $condition);
180                         if (DBA::isResult($contact)) {
181                                 $gcontact['network'] = $contact['network'];
182                         }
183
184                         if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
185                                 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
186                                         $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
187                                 $contact = DBA::selectFirst('contact', ['network'], $condition);
188                                 if (DBA::isResult($contact)) {
189                                         $gcontact['network'] = $contact['network'];
190                                 }
191                         }
192                 }
193
194                 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
195                 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
196                 if (DBA::isResult($gcnt)) {
197                         if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
198                                 $gcontact['network'] = $gcnt['network'];
199                         }
200                         if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
201                                 $gcontact['updated'] = $gcnt['updated'];
202                         }
203                         if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
204                                 $gcontact['server_url'] = $gcnt['server_url'];
205                         }
206                         if (!isset($gcontact['addr'])) {
207                                 $gcontact['addr'] = $gcnt['addr'];
208                         }
209                 }
210
211                 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
212                         && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
213                 ) {
214                         $data = Probe::uri($gcontact['url']);
215
216                         if ($data['network'] == Protocol::PHANTOM) {
217                                 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
218                         }
219
220                         $gcontact['server_url'] = $data['baseurl'];
221                         $gcontact['failed'] = false;
222
223                         $gcontact = array_merge($gcontact, $data);
224                 }
225
226                 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
227                         throw new Exception('No name and photo for URL '.$gcontact['url']);
228                 }
229
230                 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
231                         throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
232                 }
233
234                 if (empty($gcontact['server_url'])) {
235                         // We check the server url to be sure that it is a real one
236                         $server_url = self::getBasepath($gcontact['url']);
237
238                         // We are now sure that it is a correct URL. So we use it in the future
239                         if ($server_url != '') {
240                                 $gcontact['server_url'] = $server_url;
241                         }
242                 }
243
244                 // The server URL doesn't seem to be valid, so we don't store it.
245                 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
246                         $gcontact['server_url'] = '';
247                 }
248
249                 return $gcontact;
250         }
251
252         /**
253          * @param integer $uid id
254          * @param integer $cid id
255          * @return integer
256          * @throws Exception
257          */
258         public static function countCommonFriends($uid, $cid)
259         {
260                 $r = q(
261                         "SELECT count(*) as `total`
262                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
263                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
264                         NOT `gcontact`.`failed`
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 NOT `gcontact`.`failed`
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                         NOT `gcontact`.`failed`",
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                         NOT `gcontact`.`failed`
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 NOT `gcontact`.`failed`
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 NOT `gcontact`.`failed`
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 = DI::httpRequest()->fetch(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                 DBA::close($contacts);
553         }
554
555         /**
556          * Removes unwanted parts from a contact url
557          *
558          * @param string $url Contact url
559          *
560          * @return string Contact url with the wanted parts
561          * @throws Exception
562          */
563         public static function cleanContactUrl($url)
564         {
565                 $parts = parse_url($url);
566
567                 if (empty($parts['scheme']) || empty($parts['host'])) {
568                         return $url;
569                 }
570
571                 $new_url = $parts['scheme'] . '://' . $parts['host'];
572
573                 if (!empty($parts['port'])) {
574                         $new_url .= ':' . $parts['port'];
575                 }
576
577                 if (!empty($parts['path'])) {
578                         $new_url .= $parts['path'];
579                 }
580
581                 if ($new_url != $url) {
582                         Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
583                 }
584
585                 return $new_url;
586         }
587
588         /**
589          * Fetch the gcontact id, add an entry if not existed
590          *
591          * @param array $contact contact array
592          *
593          * @return bool|int Returns false if not found, integer if contact was found
594          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
595          * @throws \ImagickException
596          */
597         public static function getId($contact)
598         {
599                 if (empty($contact['network'])) {
600                         Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
601                         return false;
602                 }
603
604                 if (in_array($contact['network'], [Protocol::PHANTOM])) {
605                         Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
606                         return false;
607                 }
608
609                 if ($contact['network'] == Protocol::STATUSNET) {
610                         $contact['network'] = Protocol::OSTATUS;
611                 }
612
613                 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
614                 if (in_array($contact['network'], Protocol::FEDERATED)) {
615                         $contact['url'] = self::cleanContactUrl($contact['url']);
616                 }
617
618                 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
619                 $gcontact = DBA::selectFirst('gcontact', ['id'], $condition, ['order' => ['id']]);
620                 if (DBA::isResult($gcontact)) {
621                         return $gcontact['id'];
622                 }
623
624                 $contact['location'] = $contact['location'] ?? '';
625                 $contact['about'] = $contact['about'] ?? '';
626                 $contact['generation'] = $contact['generation'] ?? 0;
627                 $contact['hide'] = $contact['hide'] ?? true;
628
629                 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
630                         'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
631                         'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
632                         'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation'], 'failed' => false];
633
634                 DBA::insert('gcontact', $fields);
635
636                 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
637                 $gcontact = DBA::selectFirst('gcontact', ['id'], $condition, ['order' => ['id']]);
638                 if (!DBA::isResult($gcontact)) {
639                         Logger::info('GContact creation failed', $fields);
640                         // Shouldn't happen
641                         return 0;
642                 }
643                 return $gcontact['id'];
644         }
645
646         /**
647          * Updates the gcontact table from a given array
648          *
649          * @param array $contact contact array
650          *
651          * @return bool|int Returns false if not found, integer if contact was found
652          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
653          * @throws \ImagickException
654          */
655         public static function update($contact)
656         {
657                 // Check for invalid "contact-type" value
658                 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
659                         $contact['contact-type'] = 0;
660                 }
661
662                 /// @todo update contact table as well
663
664                 $gcontact_id = self::getId($contact);
665
666                 if (!$gcontact_id) {
667                         return false;
668                 }
669
670                 $public_contact = DBA::selectFirst('gcontact', [
671                         'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'keywords', 'gsid', 'failed',
672                         'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
673                 ], ['id' => $gcontact_id]);
674
675                 if (!DBA::isResult($public_contact)) {
676                         return false;
677                 }
678
679                 // Get all field names
680                 $fields = [];
681                 foreach ($public_contact as $field => $data) {
682                         $fields[$field] = $data;
683                 }
684
685                 unset($fields['url']);
686                 unset($fields['updated']);
687                 unset($fields['hide']);
688
689                 // Bugfix: We had an error in the storing of keywords which lead to the "0"
690                 // This value is still transmitted via poco.
691                 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
692                         unset($contact['keywords']);
693                 }
694
695                 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
696                         $public_contact['keywords'] = '';
697                 }
698
699                 // assign all unassigned fields from the database entry
700                 foreach ($fields as $field => $data) {
701                         if (empty($contact[$field])) {
702                                 $contact[$field] = $public_contact[$field];
703                         }
704                 }
705
706                 if (!isset($contact['hide'])) {
707                         $contact['hide'] = $public_contact['hide'];
708                 }
709
710                 $fields['hide'] = $public_contact['hide'];
711
712                 if ($contact['network'] == Protocol::STATUSNET) {
713                         $contact['network'] = Protocol::OSTATUS;
714                 }
715
716                 if (!isset($contact['updated'])) {
717                         $contact['updated'] = DateTimeFormat::utcNow();
718                 }
719
720                 if ($contact['network'] == Protocol::TWITTER) {
721                         $contact['server_url'] = 'http://twitter.com';
722                 }
723
724                 if (empty($contact['server_url'])) {
725                         $data = Probe::uri($contact['url']);
726                         if ($data['network'] != Protocol::PHANTOM) {
727                                 $contact['server_url'] = $data['baseurl'];
728                         }
729                 } else {
730                         $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
731                 }
732
733                 if (!empty($contact['server_url']) && empty($contact['gsid'])) {
734                         $contact['gsid'] = GServer::getID($contact['server_url']);
735                 }
736
737                 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
738                         $hostname = str_replace('http://', '', $contact['server_url']);
739                         $contact['addr'] = $contact['nick'] . '@' . $hostname;
740                 }
741
742                 // Check if any field changed
743                 $update = false;
744                 unset($fields['generation']);
745
746                 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
747                         foreach ($fields as $field => $data) {
748                                 if ($contact[$field] != $public_contact[$field]) {
749                                         Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
750                                         $update = true;
751                                 }
752                         }
753
754                         if ($contact['generation'] < $public_contact['generation']) {
755                                 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
756                                 $update = true;
757                         }
758                 }
759
760                 if ($update) {
761                         Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
762                         $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
763                                         Strings::normaliseLink($contact['url']), $contact['generation']];
764                         $contact['updated'] = DateTimeFormat::utc($contact['updated']);
765
766                         $updated = [
767                                 'photo' => $contact['photo'], 'name' => $contact['name'],
768                                 'nick' => $contact['nick'], 'addr' => $contact['addr'],
769                                 'network' => $contact['network'], 'birthday' => $contact['birthday'],
770                                 'keywords' => $contact['keywords'],
771                                 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
772                                 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
773                                 'notify' => $contact['notify'], 'url' => $contact['url'],
774                                 'location' => $contact['location'], 'about' => $contact['about'],
775                                 'generation' => $contact['generation'], 'updated' => $contact['updated'],
776                                 'server_url' => $contact['server_url'], 'connect' => $contact['connect'],
777                                 'failed' => $contact['failed'], 'gsid' => $contact['gsid']
778                         ];
779
780                         DBA::update('gcontact', $updated, $condition, $fields);
781                 }
782
783                 return $gcontact_id;
784         }
785
786         /**
787          * Set the last date that the contact had posted something
788          *
789          * @param string $data  Probing result
790          * @param bool   $force force updating
791          */
792         public static function setLastUpdate(array $data, bool $force = false)
793         {
794                 // Fetch the global contact
795                 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
796                         ['nurl' => Strings::normaliseLink($data['url'])]);
797                 if (!DBA::isResult($gcontact)) {
798                         return;
799                 }
800
801                 if (!$force && !GServer::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
802                         Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
803                         return;
804                 }
805
806                 if (self::updateFromNoScrape($data)) {
807                         return;
808                 }
809
810                 if (!empty($data['outbox'])) {
811                         self::updateFromOutbox($data['outbox'], $data);
812                 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
813                         self::updateFromOutbox($data['poll'], $data);
814                 } elseif (!empty($data['poll'])) {
815                         self::updateFromFeed($data);
816                 }
817         }
818
819         /**
820          * Update a global contact via the "noscrape" endpoint
821          *
822          * @param string $data Probing result
823          *
824          * @return bool 'true' if update was successful or the server was unreachable
825          */
826         private static function updateFromNoScrape(array $data)
827         {
828                 // Check the 'noscrape' endpoint when it is a Friendica server
829                 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
830                 Strings::normaliseLink($data['baseurl'])]);
831                 if (!DBA::isResult($gserver)) {
832                         return false;
833                 }
834
835                 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
836
837                 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
838                         $noscrape = json_decode($curlResult->getBody(), true);
839                         if (!empty($noscrape) && !empty($noscrape['updated'])) {
840                                 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
841                                 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
842                                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
843                                 return true;
844                         }
845                 } elseif ($curlResult->isTimeout()) {
846                         // On a timeout return the existing value, but mark the contact as failure
847                         $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
848                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
849                         return true;
850                 }
851                 return false;
852         }
853
854         /**
855          * Update a global contact via an ActivityPub Outbox
856          *
857          * @param string $feed
858          * @param array  $data Probing result
859          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
860          */
861         private static function updateFromOutbox(string $feed, array $data)
862         {
863                 $outbox = ActivityPub::fetchContent($feed);
864                 if (empty($outbox)) {
865                         return;
866                 }
867
868                 if (!empty($outbox['orderedItems'])) {
869                         $items = $outbox['orderedItems'];
870                 } elseif (!empty($outbox['first']['orderedItems'])) {
871                         $items = $outbox['first']['orderedItems'];
872                 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
873                         self::updateFromOutbox($outbox['first']['href'], $data);
874                         return;
875                 } elseif (!empty($outbox['first'])) {
876                         if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
877                                 self::updateFromOutbox($outbox['first'], $data);
878                         } else {
879                                 Logger::warning('Unexpected data', ['outbox' => $outbox]);
880                         }
881                         return;
882                 } else {
883                         $items = [];
884                 }
885
886                 $last_updated = '';
887                 foreach ($items as $activity) {
888                         if (!empty($activity['published'])) {
889                                 $published =  DateTimeFormat::utc($activity['published']);
890                         } elseif (!empty($activity['object']['published'])) {
891                                 $published =  DateTimeFormat::utc($activity['object']['published']);
892                         } else {
893                                 continue;
894                         }
895
896                         if ($last_updated < $published) {
897                                 $last_updated = $published;
898                         }
899                 }
900
901                 if (empty($last_updated)) {
902                         return;
903                 }
904
905                 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
906                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
907         }
908
909         /**
910          * Update a global contact via an XML feed
911          *
912          * @param string $data Probing result
913          */
914         private static function updateFromFeed(array $data)
915         {
916                 // Search for the newest entry in the feed
917                 $curlResult = DI::httpRequest()->get($data['poll']);
918                 if (!$curlResult->isSuccess()) {
919                         $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
920                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
921
922                         Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
923                         return;
924                 }
925
926                 $doc = new DOMDocument();
927                 @$doc->loadXML($curlResult->getBody());
928
929                 $xpath = new DOMXPath($doc);
930                 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
931
932                 $entries = $xpath->query('/atom:feed/atom:entry');
933
934                 $last_updated = '';
935
936                 foreach ($entries as $entry) {
937                         $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
938                         $updated_item   = $xpath->query('atom:updated/text()'  , $entry)->item(0);
939                         $published      = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
940                         $updated        = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
941
942                         if (empty($published) || empty($updated)) {
943                                 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
944                                 continue;
945                         }
946
947                         if ($last_updated < $published) {
948                                 $last_updated = $published;
949                         }
950
951                         if ($last_updated < $updated) {
952                                 $last_updated = $updated;
953                         }
954                 }
955
956                 if (empty($last_updated)) {
957                         return;
958                 }
959
960                 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
961                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
962         }
963         /**
964          * Updates the gcontact entry from a given public contact id
965          *
966          * @param integer $cid contact id
967          * @return void
968          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
969          * @throws \ImagickException
970          */
971         public static function updateFromPublicContactID($cid)
972         {
973                 self::updateFromPublicContact(['id' => $cid]);
974         }
975
976         /**
977          * Updates the gcontact entry from a given public contact url
978          *
979          * @param string $url contact url
980          * @return integer gcontact id
981          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
982          * @throws \ImagickException
983          */
984         public static function updateFromPublicContactURL($url)
985         {
986                 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
987         }
988
989         /**
990          * Helper function for updateFromPublicContactID and updateFromPublicContactURL
991          *
992          * @param array $condition contact condition
993          * @return integer gcontact id
994          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
995          * @throws \ImagickException
996          */
997         private static function updateFromPublicContact($condition)
998         {
999                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords',
1000                         'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
1001                         'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
1002                         'baseurl', 'gsid', 'sensitive', 'unsearchable', 'failed'];
1003
1004                 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
1005                 if (!DBA::isResult($contact)) {
1006                         return 0;
1007                 }
1008
1009                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'generation',
1010                         'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
1011                         'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
1012                         'server_url', 'gsid', 'nsfw', 'hide', 'id', 'failed'];
1013
1014                 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1015                 $do_insert = !DBA::isResult($old_gcontact);
1016                 if ($do_insert) {
1017                         $old_gcontact = [];
1018                 }
1019
1020                 $gcontact = [];
1021
1022                 // These fields are identical in both contact and gcontact
1023                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gsid',
1024                         'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated', 'failed'];
1025
1026                 foreach ($fields as $field) {
1027                         $gcontact[$field] = $contact[$field];
1028                 }
1029
1030                 // These fields are having different names but the same content
1031                 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1032                 $gcontact['nsfw'] = $contact['sensitive'];
1033                 $gcontact['hide'] = $contact['unsearchable'];
1034                 $gcontact['archived'] = $contact['archive'];
1035                 $gcontact['archive_date'] = $contact['term-date'];
1036                 $gcontact['birthday'] = $contact['bd'];
1037                 $gcontact['photo'] = $contact['avatar'];
1038                 $gcontact['last_contact'] = $contact['success_update'];
1039                 $gcontact['last_failure'] = $contact['failure_update'];
1040                 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1041
1042                 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1043                         if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1044                                 unset($gcontact[$field]);
1045                         }
1046                 }
1047
1048                 if (!$gcontact['archived']) {
1049                         $gcontact['archive_date'] = DBA::NULL_DATETIME;
1050                 }
1051
1052                 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1053                         && ($old_gcontact['created'] <= $gcontact['created'])) {
1054                         unset($gcontact['created']);
1055                 }
1056
1057                 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1058                         unset($gcontact['birthday']);
1059                 }
1060
1061                 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1062                         $gcontact['generation'] = 2; // We fetched the data directly from the other server
1063                 }
1064
1065                 if (!$do_insert) {
1066                         DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1067                         return $old_gcontact['id'];
1068                 } elseif (!$gcontact['archived']) {
1069                         DBA::insert('gcontact', $gcontact);
1070                         return DBA::lastInsertId();
1071                 }
1072         }
1073
1074         /**
1075          * Updates the gcontact entry from probe
1076          *
1077          * @param string  $url   profile link
1078          * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1079          *
1080          * @return boolean 'true' when contact had been updated
1081          *
1082          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1083          * @throws \ImagickException
1084          */
1085         public static function updateFromProbe($url, $force = false)
1086         {
1087                 $data = Probe::uri($url, $force);
1088
1089                 if (in_array($data['network'], [Protocol::PHANTOM])) {
1090                         $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
1091                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1092                         Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1093                         return false;
1094                 }
1095
1096                 $data['server_url'] = $data['baseurl'];
1097                 $data['failed'] = false;
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                                 'keywords' => $userdata['pub_keywords'],
1137                                 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
1138                                 "notify" => $userdata['notify'], 'url' => $userdata['url'],
1139                                 "hide" => !$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 = DI::httpRequest()->get($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 NOT `failed`
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 NOT `failed`
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 }