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