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