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