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