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