]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
UserSession class [4] - Refactor src/Model/ files
[friendica.git] / src / Model / Contact.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
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 Friendica\Contact\Avatar;
25 use Friendica\Contact\Introduction\Exception\IntroductionNotFoundException;
26 use Friendica\Content\Pager;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Renderer;
32 use Friendica\Core\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\Database;
35 use Friendica\Database\DBA;
36 use Friendica\DI;
37 use Friendica\Network\HTTPException;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Images;
43 use Friendica\Util\Network;
44 use Friendica\Util\Proxy;
45 use Friendica\Util\Strings;
46
47 /**
48  * functions for interacting with a contact
49  */
50 class Contact
51 {
52         const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
53         const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
54         const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
55
56         /**
57          * @}
58          */
59
60         const LOCK_INSERT = 'contact-insert';
61
62         /**
63          * Account types
64          *
65          * TYPE_UNKNOWN - unknown type
66          *
67          * TYPE_PERSON - the account belongs to a person
68          *      Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
69          *
70          * TYPE_ORGANISATION - the account belongs to an organisation
71          *      Associated page type: PAGE_SOAPBOX
72          *
73          * TYPE_NEWS - the account is a news reflector
74          *      Associated page type: PAGE_SOAPBOX
75          *
76          * TYPE_COMMUNITY - the account is community forum
77          *      Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
78          *
79          * TYPE_RELAY - the account is a relay
80          *      This will only be assigned to contacts, not to user accounts
81          * @{
82          */
83         const TYPE_UNKNOWN =     -1;
84         const TYPE_PERSON =       User::ACCOUNT_TYPE_PERSON;
85         const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
86         const TYPE_NEWS =         User::ACCOUNT_TYPE_NEWS;
87         const TYPE_COMMUNITY =    User::ACCOUNT_TYPE_COMMUNITY;
88         const TYPE_RELAY =        User::ACCOUNT_TYPE_RELAY;
89         /**
90          * @}
91          */
92
93         /**
94          * Contact_is
95          *
96          * Relationship types
97          * @{
98          */
99         const NOTHING  = 0;
100         const FOLLOWER = 1;
101         const SHARING  = 2;
102         const FRIEND   = 3;
103         const SELF     = 4;
104         /**
105          * @}
106          */
107
108          const MIRROR_DEACTIVATED = 0;
109          const MIRROR_FORWARDED = 1;
110          const MIRROR_OWN_POST = 2;
111          const MIRROR_NATIVE_RESHARE = 3;
112
113          /**
114          * @param array $fields    Array of selected fields, empty for all
115          * @param array $condition Array of fields for condition
116          * @param array $params    Array of several parameters
117          * @return array
118          * @throws \Exception
119          */
120         public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
121         {
122                 return DBA::selectToArray('contact', $fields, $condition, $params);
123         }
124
125         /**
126          * @param array $fields    Array of selected fields, empty for all
127          * @param array $condition Array of fields for condition
128          * @param array $params    Array of several parameters
129          * @return array|bool
130          * @throws \Exception
131          */
132         public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
133         {
134                 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
135
136                 return $contact;
137         }
138
139         /**
140          * @param array $fields    Array of selected fields, empty for all
141          * @param array $condition Array of fields for condition
142          * @param array $params    Array of several parameters
143          * @return array|bool
144          * @throws \Exception
145          */
146         public static function selectFirstAccount(array $fields = [], array $condition = [], array $params = [])
147         {
148                 return DBA::selectFirst('account-view', $fields, $condition, $params);
149         }
150
151         /**
152          * Insert a row into the contact table
153          * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
154          *
155          * @param array $fields         field array
156          * @param int   $duplicate_mode Do an update on a duplicate entry
157          *
158          * @return int  id of the created contact
159          * @throws \Exception
160          */
161         public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
162         {
163                 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
164                         $fields['gsid'] = GServer::getID($fields['baseurl'], true);
165                 }
166
167                 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
168
169                 if (empty($fields['created'])) {
170                         $fields['created'] = DateTimeFormat::utcNow();
171                 }
172
173                 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
174                 DBA::insert('contact', $fields, $duplicate_mode);
175                 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
176                 if (!DBA::isResult($contact)) {
177                         // Shouldn't happen
178                         Logger::warning('Created contact could not be found', ['fields' => $fields]);
179                         return 0;
180                 }
181
182                 $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
183                 DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
184                 $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
185                 if (empty($account_user['id'])) {
186                         Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
187                 } elseif ($account_user['id'] != $contact['id']) {
188                         $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
189                         if (!empty($duplicate['id'])) {
190                                 $ret = Contact::deleteById($contact['id']);
191                                 Logger::notice('Deleted duplicated contact', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $duplicate['id'], 'uid' => $duplicate['uid'], 'uri-id' => $duplicate['uri-id'], 'url' => $duplicate['url']]);
192                                 $contact = $duplicate;
193                         } else {
194                                 $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
195                                 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
196                         }
197                 }
198
199                 Contact\User::insertForContactArray($contact);
200
201                 return $contact['id'];
202         }
203
204         /**
205          * Delete contact by id
206          *
207          * @param integer $id
208          * @return boolean
209          */
210         public static function deleteById(int $id): bool
211         {
212                 Logger::debug('Delete contact', ['id' => $id]);
213                 DBA::delete('account-user', ['id' => $id]);
214                 return DBA::delete('contact', ['id' => $id]);
215         }
216
217         /**
218          * Updates rows in the contact table
219          *
220          * @param array         $fields     contains the fields that are updated
221          * @param array         $condition  condition array with the key values
222          * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate, false = don't update identical fields)
223          *
224          * @return boolean was the update successfull?
225          * @throws \Exception
226          * @todo Let's get rid of boolean type of $old_fields
227          */
228         public static function update(array $fields, array $condition, $old_fields = [])
229         {
230                 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
231                 $ret = DBA::update('contact', $fields, $condition, $old_fields);
232
233                 // Apply changes to the "user-contact" table on dedicated fields
234                 Contact\User::updateByContactUpdate($fields, $condition);
235
236                 return $ret;
237         }
238
239         /**
240          * @param integer $id     Contact ID
241          * @param array   $fields Array of selected fields, empty for all
242          * @return array|boolean Contact record if it exists, false otherwise
243          * @throws \Exception
244          */
245         public static function getById(int $id, array $fields = [])
246         {
247                 return DBA::selectFirst('contact', $fields, ['id' => $id]);
248         }
249
250         /**
251          * Fetch the first contact with the provided uri-id.
252          *
253          * @param integer $uri_id uri-id of the contact
254          * @param array   $fields Array of selected fields, empty for all
255          * @return array|boolean Contact record if it exists, false otherwise
256          * @throws \Exception
257          */
258         public static function getByUriId(int $uri_id, array $fields = [])
259         {
260                 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
261         }
262
263         /**
264          * Fetch all remote contacts for a given contact url
265          *
266          * @param string $url The URL of the contact
267          * @param array  $fields The wanted fields
268          *
269          * @return array all remote contacts
270          *
271          * @throws \Exception
272          */
273         public static function getVisitorByUrl(string $url, array $fields = ['id', 'uid']): array
274         {
275                 $remote = [];
276
277                 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($url), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
278                 while ($contact = DBA::fetch($remote_contacts)) {
279                         if (($contact['uid'] == 0) || Contact\User::isBlocked($contact['id'], $contact['uid'])) {
280                                 continue;
281                         }
282                         $remote[$contact['uid']] = $contact['id'];
283                 }
284                 DBA::close($remote_contacts);
285
286                 return $remote;
287         }
288
289         /**
290          * Fetches a contact by a given url
291          *
292          * @param string  $url    profile url
293          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
294          * @param array   $fields Field list
295          * @param integer $uid    User ID of the contact
296          * @return array contact array
297          */
298         public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
299         {
300                 if ($update || is_null($update)) {
301                         $cid = self::getIdForURL($url, $uid, $update);
302                         if (empty($cid)) {
303                                 return [];
304                         }
305
306                         $contact = self::getById($cid, $fields);
307                         if (empty($contact)) {
308                                 return [];
309                         }
310                         return $contact;
311                 }
312
313                 // Add internal fields
314                 $removal = [];
315                 if (!empty($fields)) {
316                         foreach (['id', 'next-update', 'network'] as $internal) {
317                                 if (!in_array($internal, $fields)) {
318                                         $fields[] = $internal;
319                                         $removal[] = $internal;
320                                 }
321                         }
322                 }
323
324                 // We first try the nurl (http://server.tld/nick), most common case
325                 $options = ['order' => ['id']];
326                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
327
328                 // Then the addr (nick@server.tld)
329                 if (!DBA::isResult($contact)) {
330                         $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
331                 }
332
333                 // Then the alias (which could be anything)
334                 if (!DBA::isResult($contact)) {
335                         // The link could be provided as http although we stored it as https
336                         $ssl_url = str_replace('http://', 'https://', $url);
337                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
338                         $contact = DBA::selectFirst('contact', $fields, $condition, $options);
339                 }
340
341                 if (!DBA::isResult($contact)) {
342                         return [];
343                 }
344
345                 // Update the contact in the background if needed
346                 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
347                         Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
348                 }
349
350                 // Remove the internal fields
351                 foreach ($removal as $internal) {
352                         unset($contact[$internal]);
353                 }
354
355                 return $contact;
356         }
357
358         /**
359          * Fetches a contact for a given user by a given url.
360          * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
361          *
362          * @param string  $url    profile url
363          * @param integer $uid    User ID of the contact
364          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
365          * @param array   $fields Field list
366          * @return array contact array
367          */
368         public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
369         {
370                 if ($uid != 0) {
371                         $contact = self::getByURL($url, $update, $fields, $uid);
372                         if (!empty($contact)) {
373                                 if (!empty($contact['id'])) {
374                                         $contact['cid'] = $contact['id'];
375                                         $contact['zid'] = 0;
376                                 }
377                                 return $contact;
378                         }
379                 }
380
381                 $contact = self::getByURL($url, $update, $fields);
382                 if (!empty($contact['id'])) {
383                         $contact['cid'] = 0;
384                         $contact['zid'] = $contact['id'];
385                 }
386                 return $contact;
387         }
388
389         /**
390          * Checks if a contact uses a specific platform
391          *
392          * @param string $url
393          * @param string $platform
394          * @return boolean
395          */
396         public static function isPlatform(string $url, string $platform): bool
397         {
398                 return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
399         }
400
401         /**
402          * Tests if the given contact is a follower
403          *
404          * @param int  $cid    Either public contact id or user's contact id
405          * @param int  $uid    User ID
406          * @param bool $strict If "true" then contact mustn't be set to pending or readonly
407          *
408          * @return boolean is the contact id a follower?
409          * @throws HTTPException\InternalServerErrorException
410          * @throws \ImagickException
411          */
412         public static function isFollower(int $cid, int $uid, bool $strict = false): bool
413         {
414                 if (Contact\User::isBlocked($cid, $uid)) {
415                         return false;
416                 }
417
418                 $cdata = self::getPublicAndUserContactID($cid, $uid);
419                 if (empty($cdata['user'])) {
420                         return false;
421                 }
422
423                 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
424                 if ($strict) {
425                         $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
426                 }
427                 return DBA::exists('contact', $condition);
428         }
429
430         /**
431          * Tests if the given contact url is a follower
432          *
433          * @param string $url    Contact URL
434          * @param int    $uid    User ID
435          * @param bool   $strict If "true" then contact mustn't be set to pending or readonly
436          *
437          * @return boolean is the contact id a follower?
438          * @throws HTTPException\InternalServerErrorException
439          * @throws \ImagickException
440          */
441         public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
442         {
443                 $cid = self::getIdForURL($url, $uid);
444
445                 if (empty($cid)) {
446                         return false;
447                 }
448
449                 return self::isFollower($cid, $uid, $strict);
450         }
451
452         /**
453          * Tests if the given user shares with the given contact
454          *
455          * @param int  $cid    Either public contact id or user's contact id
456          * @param int  $uid    User ID
457          * @param bool $strict If "true" then contact mustn't be set to pending or readonly
458          *
459          * @return boolean is the contact sharing with given user?
460          * @throws HTTPException\InternalServerErrorException
461          * @throws \ImagickException
462          */
463         public static function isSharing(int $cid, int $uid, bool $strict = false): bool
464         {
465                 if (Contact\User::isBlocked($cid, $uid)) {
466                         return false;
467                 }
468
469                 $cdata = self::getPublicAndUserContactID($cid, $uid);
470                 if (empty($cdata['user'])) {
471                         return false;
472                 }
473
474                 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
475                 if ($strict) {
476                         $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
477                 }
478                 return DBA::exists('contact', $condition);
479         }
480
481         /**
482          * Tests if the given user follow the given contact url
483          *
484          * @param string $url    Contact URL
485          * @param int    $uid    User ID
486          * @param bool   $strict If "true" then contact mustn't be set to pending or readonly
487          *
488          * @return boolean is the contact url being followed?
489          * @throws HTTPException\InternalServerErrorException
490          * @throws \ImagickException
491          */
492         public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
493         {
494                 $cid = self::getIdForURL($url, $uid);
495
496                 if (empty($cid)) {
497                         return false;
498                 }
499
500                 return self::isSharing($cid, $uid, $strict);
501         }
502
503         /**
504          * Get the basepath for a given contact link
505          *
506          * @param string $url The contact link
507          * @param boolean $dont_update Don't update the contact
508          *
509          * @return string basepath
510          * @throws HTTPException\InternalServerErrorException
511          * @throws \ImagickException
512          */
513         public static function getBasepath(string $url, bool $dont_update = false): string
514         {
515                 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
516                 if (!DBA::isResult($contact)) {
517                         return '';
518                 }
519
520                 if (!empty($contact['baseurl'])) {
521                         return $contact['baseurl'];
522                 } elseif ($dont_update) {
523                         return '';
524                 }
525
526                 // Update the existing contact
527                 self::updateFromProbe($contact['id']);
528
529                 // And fetch the result
530                 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
531                 if (empty($contact['baseurl'])) {
532                         Logger::info('No baseurl for contact', ['url' => $url]);
533                         return '';
534                 }
535
536                 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
537                 return $contact['baseurl'];
538         }
539
540         /**
541          * Check if the given contact url is on the same server
542          *
543          * @param string $url The contact link
544          *
545          * @return boolean Is it the same server?
546          */
547         public static function isLocal(string $url): bool
548         {
549                 if (!parse_url($url, PHP_URL_SCHEME)) {
550                         $addr_parts = explode('@', $url);
551                         return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
552                 }
553
554                 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
555         }
556
557         /**
558          * Check if the given contact ID is on the same server
559          *
560          * @param string $url The contact link
561          * @return boolean Is it the same server?
562          */
563         public static function isLocalById(int $cid): bool
564         {
565                 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
566                 if (!DBA::isResult($contact)) {
567                         return false;
568                 }
569
570                 if (empty($contact['baseurl'])) {
571                         $baseurl = self::getBasepath($contact['url'], true);
572                 } else {
573                         $baseurl = $contact['baseurl'];
574                 }
575
576                 return Strings::compareLink($baseurl, DI::baseUrl());
577         }
578
579         /**
580          * Returns the public contact id of the given user id
581          *
582          * @param  integer $uid User ID
583          *
584          * @return integer|boolean Public contact id for given user id
585          * @throws \Exception
586          */
587         public static function getPublicIdByUserId(int $uid)
588         {
589                 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
590                 if (!DBA::isResult($self)) {
591                         return false;
592                 }
593                 return self::getIdForURL($self['url']);
594         }
595
596         /**
597          * Returns the contact id for the user and the public contact id for a given contact id
598          *
599          * @param int $cid Either public contact id or user's contact id
600          * @param int $uid User ID
601          *
602          * @return array with public and user's contact id
603          * @throws HTTPException\InternalServerErrorException
604          * @throws \ImagickException
605          */
606         public static function getPublicAndUserContactID(int $cid, int $uid): array
607         {
608                 // We have to use the legacy function as long as the post update hasn't finished
609                 if (DI::config()->get('system', 'post_update_version') < 1427) {
610                         return self::legacyGetPublicAndUserContactID($cid, $uid);
611                 }
612
613                 if (empty($uid) || empty($cid)) {
614                         return [];
615                 }
616
617                 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
618                 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
619                         return [];
620                 }
621
622                 $pcid = $contact['pid'];
623                 if ($contact['uid'] == $uid) {
624                         $ucid = $contact['id'];
625                 } else {
626                         $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
627                         if (DBA::isResult($contact)) {
628                                 $ucid = $contact['id'];
629                         } else {
630                                 $ucid = 0;
631                         }
632                 }
633
634                 return ['public' => $pcid, 'user' => $ucid];
635         }
636
637         /**
638          * Helper function for "getPublicAndUserContactID"
639          *
640          * @param int $cid Either public contact id or user's contact id
641          * @param int $uid User ID
642          * @return array with public and user's contact id
643          * @throws HTTPException\InternalServerErrorException
644          * @throws \ImagickException
645          */
646         private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
647         {
648                 if (empty($uid) || empty($cid)) {
649                         return [];
650                 }
651
652                 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
653                 if (!DBA::isResult($contact)) {
654                         return [];
655                 }
656
657                 // We quit when the user id don't match the user id of the provided contact
658                 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
659                         return [];
660                 }
661
662                 if ($contact['uid'] != 0) {
663                         $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
664                         if (empty($pcid)) {
665                                 return [];
666                         }
667                         $ucid = $contact['id'];
668                 } else {
669                         $pcid = $contact['id'];
670                         $ucid = self::getIdForURL($contact['url'], $uid);
671                 }
672
673                 return ['public' => $pcid, 'user' => $ucid];
674         }
675
676         /**
677          * Returns contact details for a given contact id in combination with a user id
678          *
679          * @param int $cid A contact ID
680          * @param int $uid The User ID
681          * @param array $fields The selected fields for the contact
682          * @return array The contact details
683          *
684          * @throws \Exception
685          */
686         public static function getContactForUser(int $cid, int $uid, array $fields = []): array
687         {
688                 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
689
690                 if (!DBA::isResult($contact)) {
691                         return [];
692                 } else {
693                         return $contact;
694                 }
695         }
696
697         /**
698          * Creates the self-contact for the provided user id
699          *
700          * @param int $uid
701          * @return bool Operation success
702          * @throws HTTPException\InternalServerErrorException
703          */
704         public static function createSelfFromUserId(int $uid): bool
705         {
706                 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
707                         ['uid' => $uid, 'account_expired' => false]);
708                 if (!DBA::isResult($user)) {
709                         return false;
710                 }
711
712                 $contact = [
713                         'uid'         => $user['uid'],
714                         'created'     => DateTimeFormat::utcNow(),
715                         'self'        => 1,
716                         'name'        => $user['username'],
717                         'nick'        => $user['nickname'],
718                         'pubkey'      => $user['pubkey'],
719                         'prvkey'      => $user['prvkey'],
720                         'photo'       => User::getAvatarUrl($user),
721                         'thumb'       => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
722                         'micro'       => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
723                         'blocked'     => 0,
724                         'pending'     => 0,
725                         'url'         => DI::baseUrl() . '/profile/' . $user['nickname'],
726                         'nurl'        => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
727                         'addr'        => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
728                         'request'     => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
729                         'notify'      => DI::baseUrl() . '/dfrn_notify/'  . $user['nickname'],
730                         'poll'        => DI::baseUrl() . '/dfrn_poll/'    . $user['nickname'],
731                         'confirm'     => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
732                         'poco'        => DI::baseUrl() . '/poco/'         . $user['nickname'],
733                         'name-date'   => DateTimeFormat::utcNow(),
734                         'uri-date'    => DateTimeFormat::utcNow(),
735                         'avatar-date' => DateTimeFormat::utcNow(),
736                         'closeness'   => 0
737                 ];
738
739                 $return = true;
740
741                 // Only create the entry if it doesn't exist yet
742                 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
743                         $return = (bool)self::insert($contact);
744                 }
745
746                 // Create the public contact
747                 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
748                         $contact['self']   = false;
749                         $contact['uid']    = 0;
750                         $contact['prvkey'] = null;
751
752                         self::insert($contact, Database::INSERT_IGNORE);
753                 }
754
755                 return $return;
756         }
757
758         /**
759          * Updates the self-contact for the provided user id
760          *
761          * @param int   $uid
762          * @param bool  $update_avatar Force the avatar update
763          * @return bool "true" if updated
764          * @throws HTTPException\InternalServerErrorException
765          */
766         public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
767         {
768                 $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
769                         'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
770                         'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
771                 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
772                 if (!DBA::isResult($self)) {
773                         return false;
774                 }
775
776                 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
777                 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
778                 if (!DBA::isResult($user)) {
779                         return false;
780                 }
781
782                 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
783                         'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
784                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
785                 if (!DBA::isResult($profile)) {
786                         return false;
787                 }
788
789                 $file_suffix = 'jpg';
790                 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
791
792                 $fields = [
793                         'name'         => $profile['name'],
794                         'nick'         => $user['nickname'],
795                         'avatar-date'  => $self['avatar-date'],
796                         'location'     => Profile::formatLocation($profile),
797                         'about'        => $profile['about'],
798                         'keywords'     => $profile['pub_keywords'],
799                         'contact-type' => $user['account-type'],
800                         'prvkey'       => $user['prvkey'],
801                         'pubkey'       => $user['pubkey'],
802                         'xmpp'         => $profile['xmpp'],
803                         'matrix'       => $profile['matrix'],
804                         'network'      => Protocol::DFRN,
805                         'url'          => $url,
806                         // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
807                         'nurl'         => Strings::normaliseLink($url),
808                         'uri-id'       => ItemURI::getIdByURI($url),
809                         'addr'         => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
810                         'request'      => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
811                         'notify'       => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
812                         'poll'         => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
813                         'confirm'      => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
814                         'poco'         => DI::baseUrl() . '/poco/' . $user['nickname'],
815                 ];
816
817
818                 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
819                 if (DBA::isResult($avatar)) {
820                         if ($update_avatar) {
821                                 $fields['avatar-date'] = DateTimeFormat::utcNow();
822                         }
823
824                         // Creating the path to the avatar, beginning with the file suffix
825                         $types = Images::supportedTypes();
826                         if (isset($types[$avatar['type']])) {
827                                 $file_suffix = $types[$avatar['type']];
828                         }
829
830                         // We are adding a timestamp value so that other systems won't use cached content
831                         $timestamp = strtotime($fields['avatar-date']);
832
833                         $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
834                         $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
835
836                         $fields['photo'] = $prefix . '4' . $suffix;
837                         $fields['thumb'] = $prefix . '5' . $suffix;
838                         $fields['micro'] = $prefix . '6' . $suffix;
839                 } else {
840                         // We hadn't found a photo entry, so we use the default avatar
841                         $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
842                         $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
843                         $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
844                 }
845
846                 $fields['avatar'] = User::getAvatarUrl($user);
847                 $fields['header'] = User::getBannerUrl($user);
848                 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
849                 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
850                 $fields['unsearchable'] = !$profile['net-publish'];
851                 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
852
853                 $update = false;
854
855                 foreach ($fields as $field => $content) {
856                         if ($self[$field] != $content) {
857                                 $update = true;
858                         }
859                 }
860
861                 if ($update) {
862                         if ($fields['name'] != $self['name']) {
863                                 $fields['name-date'] = DateTimeFormat::utcNow();
864                         }
865                         $fields['updated'] = DateTimeFormat::utcNow();
866                         self::update($fields, ['id' => $self['id']]);
867
868                         // Update the other contacts as well
869                         unset($fields['prvkey']);
870                         $fields['self'] = false;
871                         self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
872
873                         // Update the profile
874                         $fields = [
875                                 'photo' => User::getAvatarUrl($user),
876                                 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
877                         ];
878
879                         DBA::update('profile', $fields, ['uid' => $uid]);
880                 }
881
882                 return $update;
883         }
884
885         /**
886          * Marks a contact for removal
887          *
888          * @param int $id contact id
889          * @return void
890          * @throws HTTPException\InternalServerErrorException
891          */
892         public static function remove(int $id)
893         {
894                 // We want just to make sure that we don't delete our "self" contact
895                 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
896                 if (!DBA::isResult($contact)) {
897                         return;
898                 }
899
900                 DBA::delete('account-user', ['id' => $id]);
901
902                 self::clearFollowerFollowingEndpointCache($contact['uid']);
903
904                 // Archive the contact
905                 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
906
907                 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
908                         Avatar::deleteCache($contact);
909                 }
910
911                 // Delete it in the background
912                 Worker::add(Worker::PRIORITY_MEDIUM, 'Contact\Remove', $id);
913         }
914
915         /**
916          * Unfollow the remote contact
917          *
918          * @param array $contact Target user-specific contact (uid != 0) array
919          * @return void
920          * @throws HTTPException\InternalServerErrorException
921          * @throws \ImagickException
922          */
923         public static function unfollow(array $contact): void
924         {
925                 if (empty($contact['network'])) {
926                         throw new \InvalidArgumentException('Empty network in contact array');
927                 }
928
929                 if (empty($contact['uid'])) {
930                         throw new \InvalidArgumentException('Unexpected public contact record');
931                 }
932
933                 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
934                         $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
935                         if (!empty($cdata['public'])) {
936                                 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
937                         }
938                 }
939
940                 self::removeSharer($contact);
941         }
942
943         /**
944          * Revoke follow privileges of the remote user contact
945          *
946          * The local relationship is updated immediately, the eventual remote server is messaged in the background.
947          *
948          * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
949          * @return void
950          * @throws HTTPException\InternalServerErrorException
951          * @throws \ImagickException
952          */
953         public static function revokeFollow(array $contact): void
954         {
955                 if (empty($contact['network'])) {
956                         throw new \InvalidArgumentException('Empty network in contact array');
957                 }
958
959                 if (empty($contact['uid'])) {
960                         throw new \InvalidArgumentException('Unexpected public contact record');
961                 }
962
963                 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
964                         $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
965                         if (!empty($cdata['public'])) {
966                                 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
967                         }
968                 }
969
970                 self::removeFollower($contact);
971         }
972
973         /**
974          * Completely severs a relationship with a contact
975          *
976          * @param array $contact User-specific contact (uid != 0) array
977          * @return void
978          * @throws HTTPException\InternalServerErrorException
979          * @throws \ImagickException
980          */
981         public static function terminateFriendship(array $contact)
982         {
983                 if (empty($contact['network'])) {
984                         throw new \InvalidArgumentException('Empty network in contact array');
985                 }
986
987                 if (empty($contact['uid'])) {
988                         throw new \InvalidArgumentException('Unexpected public contact record');
989                 }
990
991                 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
992
993                 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
994                         Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
995                 }
996
997                 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
998                         Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
999                 }
1000
1001                 self::remove($contact['id']);
1002         }
1003
1004         private static function clearFollowerFollowingEndpointCache(int $uid)
1005         {
1006                 if (empty($uid)) {
1007                         return;
1008                 }
1009
1010                 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
1011                 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
1012         }
1013
1014         /**
1015          * Marks a contact for archival after a communication issue delay
1016          *
1017          * Contact has refused to recognise us as a friend. We will start a countdown.
1018          * If they still don't recognise us in 32 days, the relationship is over,
1019          * and we won't waste any more time trying to communicate with them.
1020          * This provides for the possibility that their database is temporarily messed
1021          * up or some other transient event and that there's a possibility we could recover from it.
1022          *
1023          * @param array $contact contact to mark for archival
1024          * @return void
1025          * @throws HTTPException\InternalServerErrorException
1026          */
1027         public static function markForArchival(array $contact)
1028         {
1029                 if (!isset($contact['url']) && !empty($contact['id'])) {
1030                         $fields = ['id', 'url', 'archive', 'self', 'term-date'];
1031                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1032                         if (!DBA::isResult($contact)) {
1033                                 return;
1034                         }
1035                 } elseif (!isset($contact['url'])) {
1036                         Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
1037                 }
1038
1039                 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1040
1041                 // Contact already archived or "self" contact? => nothing to do
1042                 if ($contact['archive'] || $contact['self']) {
1043                         return;
1044                 }
1045
1046                 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1047                         self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1048                         self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1049                 } else {
1050                         /* @todo
1051                          * We really should send a notification to the owner after 2-3 weeks
1052                          * so they won't be surprised when the contact vanishes and can take
1053                          * remedial action if this was a serious mistake or glitch
1054                          */
1055
1056                         /// @todo Check for contact vitality via probing
1057                         $archival_days = DI::config()->get('system', 'archival_days', 32);
1058
1059                         $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1060                         if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1061                                 /* Relationship is really truly dead. archive them rather than
1062                                  * delete, though if the owner tries to unarchive them we'll start
1063                                  * the whole process over again.
1064                                  */
1065                                 self::update(['archive' => true], ['id' => $contact['id']]);
1066                                 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1067                         }
1068                 }
1069         }
1070
1071         /**
1072          * Cancels the archival countdown
1073          *
1074          * @see   Contact::markForArchival()
1075          *
1076          * @param array $contact contact to be unmarked for archival
1077          * @return void
1078          * @throws \Exception
1079          */
1080         public static function unmarkForArchival(array $contact)
1081         {
1082                 // Always unarchive the relay contact entry
1083                 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1084                         $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1085                         $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1086                         if (!DBA::exists('contact', array_merge($condition, $fields))) {
1087                                 self::update($fields, $condition);
1088                         }
1089                 }
1090
1091                 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1092                 $exists = DBA::exists('contact', $condition);
1093
1094                 // We don't need to update, we never marked this contact for archival
1095                 if (!$exists) {
1096                         return;
1097                 }
1098
1099                 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1100
1101                 if (!isset($contact['url']) && !empty($contact['id'])) {
1102                         $fields = ['id', 'url', 'batch'];
1103                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1104                         if (!DBA::isResult($contact)) {
1105                                 return;
1106                         }
1107                 }
1108
1109                 // It's a miracle. Our dead contact has inexplicably come back to life.
1110                 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1111                 self::update($fields, ['id' => $contact['id']]);
1112                 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1113         }
1114
1115         /**
1116          * Returns the data array for the photo menu of a given contact
1117          *
1118          * @param array $contact contact
1119          * @param int   $uid     optional, default 0
1120          * @return array
1121          * @throws HTTPException\InternalServerErrorException
1122          * @throws \ImagickException
1123          */
1124         public static function photoMenu(array $contact, int $uid = 0): array
1125         {
1126                 $pm_url = '';
1127                 $status_link = '';
1128                 $photos_link = '';
1129
1130                 if ($uid == 0) {
1131                         $uid = DI::userSession()->getLocalUserId();
1132                 }
1133
1134                 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1135                         if ($uid == 0) {
1136                                 $profile_link = self::magicLinkByContact($contact);
1137                                 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1138
1139                                 return $menu;
1140                         }
1141
1142                         // Look for our own contact if the uid doesn't match and isn't public
1143                         $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1144                         if (DBA::isResult($contact_own)) {
1145                                 return self::photoMenu($contact_own, $uid);
1146                         }
1147                 }
1148
1149                 $sparkle = false;
1150                 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1151                         $sparkle = true;
1152                         $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1153                 } else {
1154                         $profile_link = $contact['url'];
1155                 }
1156
1157                 if ($profile_link === 'mailbox') {
1158                         $profile_link = '';
1159                 }
1160
1161                 if ($sparkle) {
1162                         $status_link = $profile_link . '/status';
1163                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1164                         $profile_link = $profile_link . '/profile';
1165                 }
1166
1167                 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1168                         $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1169                 }
1170
1171                 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1172
1173                 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1174
1175                 $follow_link = '';
1176                 $unfollow_link = '';
1177                 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1178                         if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1179                                 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1180                         } elseif(!$contact['pending']) {
1181                                 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1182                         }
1183                 }
1184
1185                 /**
1186                  * Menu array:
1187                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1188                  */
1189                 if (empty($contact['uid'])) {
1190                         $menu = [
1191                                 'profile' => [DI::l10n()->t('View Profile')  , $profile_link , true],
1192                                 'network' => [DI::l10n()->t('Network Posts') , $posts_link   , false],
1193                                 'edit'    => [DI::l10n()->t('View Contact')  , $contact_url  , false],
1194                                 'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link  , true],
1195                                 'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link, true],
1196                         ];
1197                 } else {
1198                         $menu = [
1199                                 'status'  => [DI::l10n()->t('View Status')   , $status_link      , true],
1200                                 'profile' => [DI::l10n()->t('View Profile')  , $profile_link     , true],
1201                                 'photos'  => [DI::l10n()->t('View Photos')   , $photos_link      , true],
1202                                 'network' => [DI::l10n()->t('Network Posts') , $posts_link       , false],
1203                                 'edit'    => [DI::l10n()->t('View Contact')  , $contact_url      , false],
1204                                 'pm'      => [DI::l10n()->t('Send PM')       , $pm_url           , false],
1205                                 'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link      , true],
1206                                 'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link    , true],
1207                         ];
1208
1209                         if (!empty($contact['pending'])) {
1210                                 try {
1211                                         $intro = DI::intro()->selectForContact($contact['id']);
1212                                         $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1213                                 } catch (IntroductionNotFoundException $exception) {
1214                                         DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1215                                 }
1216                         }
1217                 }
1218
1219                 $args = ['contact' => $contact, 'menu' => &$menu];
1220
1221                 Hook::callAll('contact_photo_menu', $args);
1222
1223                 $menucondensed = [];
1224
1225                 foreach ($menu as $menuname => $menuitem) {
1226                         if ($menuitem[1] != '') {
1227                                 $menucondensed[$menuname] = $menuitem;
1228                         }
1229                 }
1230
1231                 return $menucondensed;
1232         }
1233
1234         /**
1235          * Fetch the contact id for a given URL and user
1236          *
1237          * First lookup in the contact table to find a record matching either `url`, `nurl`,
1238          * `addr` or `alias`.
1239          *
1240          * If there's no record and we aren't looking for a public contact, we quit.
1241          * If there's one, we check that it isn't time to update the picture else we
1242          * directly return the found contact id.
1243          *
1244          * Second, we probe the provided $url whether it's http://server.tld/profile or
1245          * nick@server.tld. We quit if we can't get any info back.
1246          *
1247          * Third, we create the contact record if it doesn't exist
1248          *
1249          * Fourth, we update the existing record with the new data (avatar, alias, nick)
1250          * if there's any updates
1251          *
1252          * @param string  $url       Contact URL
1253          * @param integer $uid       The user id for the contact (0 = public contact)
1254          * @param boolean $update    true = always update, false = never update, null = update when not found
1255          * @param array   $default   Default value for creating the contact when everything else fails
1256          *
1257          * @return integer Contact ID
1258          * @throws HTTPException\InternalServerErrorException
1259          * @throws \ImagickException
1260          */
1261         public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1262         {
1263                 $contact_id = 0;
1264
1265                 if (empty($url)) {
1266                         Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1267                         return 0;
1268                 }
1269
1270                 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update'], $uid);
1271
1272                 if (!empty($contact)) {
1273                         $contact_id = $contact['id'];
1274
1275                         if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1276                                 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
1277                         }
1278
1279                         if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1280                                 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1281                                 return $contact_id;
1282                         }
1283                 } elseif ($uid != 0) {
1284                         Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1285                         return 0;
1286                 } elseif (empty($default) && !is_null($update) && !$update) {
1287                         Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1288                         return 0;
1289                 }
1290
1291                 $data = [];
1292
1293                 if (empty($default['network']) || $update) {
1294                         $data = Probe::uri($url, '', $uid);
1295
1296                         // Take the default values when probing failed
1297                         if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1298                                 $data = array_merge($data, $default);
1299                         }
1300                 } elseif (!empty($default['network'])) {
1301                         $data = $default;
1302                 }
1303
1304                 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1305                         // Fetch data for the public contact via the first found personal contact
1306                         /// @todo Check if this case can happen at all (possibly with mail accounts?)
1307                         $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1308                                 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1309                                 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1310
1311                         $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1312                         if (!DBA::isResult($personal_contact)) {
1313                                 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1314                         }
1315
1316                         if (DBA::isResult($personal_contact)) {
1317                                 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1318                                 $data = $personal_contact;
1319                                 $data['photo'] = $personal_contact['avatar'];
1320                                 $data['account-type'] = $personal_contact['contact-type'];
1321                                 $data['hide'] = $personal_contact['unsearchable'];
1322                                 unset($data['avatar']);
1323                                 unset($data['contact-type']);
1324                                 unset($data['unsearchable']);
1325                         }
1326                 }
1327
1328                 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1329                         Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1330                         return 0;
1331                 }
1332
1333                 if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1334                         Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
1335                         return 0;
1336                 }
1337
1338                 if (!$contact_id) {
1339                         $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1340                         if (!empty($data['alias'])) {
1341                                 $urls[] = Strings::normaliseLink($data['alias']);
1342                         }
1343                         $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1344                         if (!empty($contact['id'])) {
1345                                 $contact_id = $contact['id'];
1346                                 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1347                         }
1348                 }
1349
1350                 if (!$contact_id) {
1351                         // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1352                         $fields = [
1353                                 'uid'       => $uid,
1354                                 'url'       => $data['url'],
1355                                 'nurl'      => Strings::normaliseLink($data['url']),
1356                                 'network'   => $data['network'],
1357                                 'created'   => DateTimeFormat::utcNow(),
1358                                 'rel'       => self::SHARING,
1359                                 'writable'  => 1,
1360                                 'blocked'   => 0,
1361                                 'readonly'  => 0,
1362                                 'pending'   => 0];
1363
1364                         $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1365
1366                         // Before inserting we do check if the entry does exist now.
1367                         $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1368                         if (DBA::isResult($contact)) {
1369                                 $contact_id = $contact['id'];
1370                                 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1371                         } else {
1372                                 $contact_id = self::insert($fields);
1373                                 if ($contact_id) {
1374                                         Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1375                                 }
1376                         }
1377
1378                         if (!$contact_id) {
1379                                 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1380                                 return 0;
1381                         }
1382                 } else {
1383                         Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1384                 }
1385
1386                 if ($data['network'] == Protocol::DIASPORA) {
1387                         FContact::updateFromProbeArray($data);
1388                 }
1389
1390                 self::updateFromProbeArray($contact_id, $data);
1391
1392                 // Don't return a number for a deleted account
1393                 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1394                         Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1395                         return 0;
1396                 }
1397
1398                 return $contact_id;
1399         }
1400
1401         /**
1402          * Checks if the contact is archived
1403          *
1404          * @param int $cid contact id
1405          *
1406          * @return boolean Is the contact archived?
1407          * @throws HTTPException\InternalServerErrorException
1408          */
1409         public static function isArchived(int $cid): bool
1410         {
1411                 if ($cid == 0) {
1412                         return false;
1413                 }
1414
1415                 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1416                 if (!DBA::isResult($contact)) {
1417                         return false;
1418                 }
1419
1420                 if ($contact['archive']) {
1421                         return true;
1422                 }
1423
1424                 // Check status of ActivityPub endpoints
1425                 $apcontact = APContact::getByURL($contact['url'], false);
1426                 if (!empty($apcontact)) {
1427                         if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1428                                 return true;
1429                         }
1430
1431                         if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1432                                 return true;
1433                         }
1434                 }
1435
1436                 // Check status of Diaspora endpoints
1437                 if (!empty($contact['batch'])) {
1438                         $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1439                         return DBA::exists('contact', $condition);
1440                 }
1441
1442                 return false;
1443         }
1444
1445         /**
1446          * Checks if the contact is blocked
1447          *
1448          * @param int $cid contact id
1449          * @return boolean Is the contact blocked?
1450          * @throws HTTPException\InternalServerErrorException
1451          */
1452         public static function isBlocked(int $cid): bool
1453         {
1454                 if ($cid == 0) {
1455                         return false;
1456                 }
1457
1458                 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1459                 if (!DBA::isResult($blocked)) {
1460                         return false;
1461                 }
1462
1463                 if (Network::isUrlBlocked($blocked['url'])) {
1464                         return true;
1465                 }
1466
1467                 return (bool) $blocked['blocked'];
1468         }
1469
1470         /**
1471          * Checks if the contact is hidden
1472          *
1473          * @param int $cid contact id
1474          * @return boolean Is the contact hidden?
1475          * @throws \Exception
1476          */
1477         public static function isHidden(int $cid): bool
1478         {
1479                 if ($cid == 0) {
1480                         return false;
1481                 }
1482
1483                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1484                 if (!DBA::isResult($hidden)) {
1485                         return false;
1486                 }
1487                 return (bool) $hidden['hidden'];
1488         }
1489
1490         /**
1491          * Returns posts from a given contact url
1492          *
1493          * @param string $contact_url Contact URL
1494          * @param bool   $thread_mode
1495          * @param int    $update      Update mode
1496          * @param int    $parent      Item parent ID for the update mode
1497          * @param bool   $only_media  Only display media content
1498          * @return string posts in HTML
1499          * @throws \Exception
1500          */
1501         public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1502         {
1503                 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1504         }
1505
1506         /**
1507          * Returns posts from a given contact id
1508          *
1509          * @param int  $cid         Contact ID
1510          * @param bool $thread_mode
1511          * @param int  $update      Update mode
1512          * @param int  $parent      Item parent ID for the update mode
1513          * @param bool $only_media  Only display media content
1514          * @return string posts in HTML
1515          * @throws \Exception
1516          */
1517         public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1518         {
1519                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1520                 if (!DBA::isResult($contact)) {
1521                         return '';
1522                 }
1523
1524                 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1525                         $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1526                 } else {
1527                         $sql = "`uid` = ?";
1528                 }
1529
1530                 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1531
1532                 if ($thread_mode) {
1533                         $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
1534                                 $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), DI::userSession()->getLocalUserId()];
1535                 } else {
1536                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1537                                 $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()];
1538                 }
1539
1540                 if (!empty($parent)) {
1541                         $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1542                 } else {
1543                         $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1544                         if (!empty($last_received)) {
1545                                 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1546                         }
1547                 }
1548
1549                 if ($only_media) {
1550                         $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1551                                 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1552                 }
1553
1554                 if (DI::mode()->isMobile()) {
1555                         $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network',
1556                                 DI::config()->get('system', 'itemspage_network_mobile'));
1557                 } else {
1558                         $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network',
1559                                 DI::config()->get('system', 'itemspage_network'));
1560                 }
1561
1562                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1563
1564                 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1565
1566                 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1567                         $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1568                         $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1569                 } else {
1570                         $o = '';
1571                 }
1572
1573                 if ($thread_mode) {
1574                         $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1575                         $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1576
1577                         if ($pager->getStart() == 0) {
1578                                 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1579                                 if (!empty($cdata['public'])) {
1580                                         $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1581                                         $items = array_merge($items, $pinned);
1582                                 }
1583                         }
1584
1585                         $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
1586                 } else {
1587                         $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1588                         $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1589
1590                         if ($pager->getStart() == 0) {
1591                                 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1592                                 if (!empty($cdata['public'])) {
1593                                         $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1594                                                 $cdata['public'], Post\Collection::FEATURED];
1595                                         $pinned = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1596                                         $items = array_merge($pinned, $items);
1597                                 }
1598                         }
1599
1600                         $o .= DI::conversation()->create($items, 'contact-posts', $update);
1601                 }
1602
1603                 if (!$update) {
1604                         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1605                                 $o .= HTML::scrollLoader();
1606                         } else {
1607                                 $o .= $pager->renderMinimal(count($items));
1608                         }
1609                 }
1610
1611                 return $o;
1612         }
1613
1614         /**
1615          * Returns the account type name
1616          *
1617          * The function can be called with either the user or the contact array
1618          *
1619          * @param int $type type of contact or account
1620          * @return string
1621          */
1622         public static function getAccountType(int $type): string
1623         {
1624                 switch ($type) {
1625                         case self::TYPE_ORGANISATION:
1626                                 $account_type = DI::l10n()->t("Organisation");
1627                                 break;
1628
1629                         case self::TYPE_NEWS:
1630                                 $account_type = DI::l10n()->t('News');
1631                                 break;
1632
1633                         case self::TYPE_COMMUNITY:
1634                                 $account_type = DI::l10n()->t("Forum");
1635                                 break;
1636
1637                         default:
1638                                 $account_type = "";
1639                                 break;
1640                 }
1641
1642                 return $account_type;
1643         }
1644
1645         /**
1646          * Blocks a contact
1647          *
1648          * @param int $cid Contact id to block
1649          * @param string $reason Block reason
1650          * @return bool Whether it was successful
1651          */
1652         public static function block(int $cid, string $reason = null): bool
1653         {
1654                 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1655
1656                 return $return;
1657         }
1658
1659         /**
1660          * Unblocks a contact
1661          *
1662          * @param int $cid Contact id to unblock
1663          * @return bool Whether it was successfull
1664          */
1665         public static function unblock(int $cid): bool
1666         {
1667                 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1668
1669                 return $return;
1670         }
1671
1672         /**
1673          * Ensure that cached avatar exist
1674          *
1675          * @param integer $cid Contact id
1676          */
1677         public static function checkAvatarCache(int $cid)
1678         {
1679                 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1680                 if (!DBA::isResult($contact)) {
1681                         return;
1682                 }
1683
1684                 if (Network::isLocalLink($contact['url'])) {
1685                         return;
1686                 }
1687
1688                 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1689                         if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1690                                 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1691                                 self::updateAvatar($cid, $contact['avatar'], true);
1692                                 return;
1693                         }
1694                 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1695                         Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1696                         self::updateAvatar($cid, $contact['avatar'], true);
1697                         return;
1698                 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1699                         Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1700                         self::updateAvatar($cid, $contact['avatar'], true);
1701                 return;
1702                 }
1703         }
1704
1705         /**
1706          * Return the photo path for a given contact array in the given size
1707          *
1708          * @param array  $contact   contact array
1709          * @param string $size      Size of the avatar picture
1710          * @param bool   $no_update Don't perfom an update if no cached avatar was found
1711          * @return string photo path
1712          */
1713         private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1714         {
1715                 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1716
1717                 if (DI::config()->get('system', 'avatar_cache')) {
1718                         switch ($size) {
1719                                 case Proxy::SIZE_MICRO:
1720                                         if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1721                                                 return $contact['micro'];
1722                                         }
1723                                         break;
1724                                 case Proxy::SIZE_THUMB:
1725                                         if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1726                                                 return $contact['thumb'];
1727                                         }
1728                                         break;
1729                                 case Proxy::SIZE_SMALL:
1730                                         if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1731                                                 return $contact['photo'];
1732                                         }
1733                                         break;
1734                         }
1735                 }
1736
1737                 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1738         }
1739
1740         /**
1741          * Return the photo path for a given contact array
1742          *
1743          * @param array  $contact   Contact array
1744          * @param bool   $no_update Don't perfom an update if no cached avatar was found
1745          * @return string photo path
1746          */
1747         public static function getPhoto(array $contact, bool $no_update = false): string
1748         {
1749                 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1750         }
1751
1752         /**
1753          * Return the photo path (thumb size) for a given contact array
1754          *
1755          * @param array  $contact   Contact array
1756          * @param bool   $no_update Don't perfom an update if no cached avatar was found
1757          * @return string photo path
1758          */
1759         public static function getThumb(array $contact, bool $no_update = false): string
1760         {
1761                 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1762         }
1763
1764         /**
1765          * Return the photo path (micro size) for a given contact array
1766          *
1767          * @param array  $contact   Contact array
1768          * @param bool   $no_update Don't perfom an update if no cached avatar was found
1769          * @return string photo path
1770          */
1771         public static function getMicro(array $contact, bool $no_update = false): string
1772         {
1773                 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1774         }
1775
1776         /**
1777          * Check the given contact array for avatar cache fields
1778          *
1779          * @param array $contact
1780          * @param bool  $no_update Don't perfom an update if no cached avatar was found
1781          * @return array contact array with avatar cache fields
1782          */
1783         private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1784         {
1785                 $update = false;
1786                 $contact_fields = [];
1787                 $fields = ['photo', 'thumb', 'micro'];
1788                 foreach ($fields as $field) {
1789                         if (isset($contact[$field])) {
1790                                 $contact_fields[] = $field;
1791                         }
1792                         if (isset($contact[$field]) && empty($contact[$field])) {
1793                                 $update = true;
1794                         }
1795                 }
1796
1797                 if (!$update || $no_update) {
1798                         return $contact;
1799                 }
1800
1801                 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1802
1803                 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1804                         self::updateAvatar($contact['id'], $contact['avatar'], true);
1805
1806                         $new_contact = self::getById($contact['id'], $contact_fields);
1807                         if (DBA::isResult($new_contact)) {
1808                                 // We only update the cache fields
1809                                 $contact = array_merge($contact, $new_contact);
1810                         }
1811                 } elseif ($local && !empty($contact['avatar'])) {
1812                         return $contact;
1813                 }
1814
1815                 /// add the default avatars if the fields aren't filled
1816                 if (isset($contact['photo']) && empty($contact['photo'])) {
1817                         $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1818                 }
1819                 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1820                         $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1821                 }
1822                 if (isset($contact['micro']) && empty($contact['micro'])) {
1823                         $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1824                 }
1825
1826                 return $contact;
1827         }
1828
1829         /**
1830          * Fetch the default header for the given contact
1831          *
1832          * @param array $contact  contact array
1833          * @return string avatar URL
1834          */
1835         public static function getDefaultHeader(array $contact): string
1836         {
1837                 if (!empty($contact['header'])) {
1838                         return $contact['header'];
1839                 }
1840
1841                 if (!empty($contact['gsid'])) {
1842                         // Use default banners for certain platforms
1843                         $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1844                         $platform = strtolower($gserver['platform'] ?? '');
1845                 } else {
1846                         $platform = '';
1847                 }
1848
1849                 switch ($platform) {
1850                         case 'friendica':
1851                         case 'friendika':
1852                                 /**
1853                                  * Picture credits
1854                                  * @author  Lostinlight <https://mastodon.xyz/@lightone>
1855                                  * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1856                                  * @link    https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1857                                  */
1858                                 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1859                                 break;
1860                         case 'diaspora':
1861                                 /**
1862                                  * Picture credits
1863                                  * @author  John Liu <https://www.flickr.com/photos/8047705@N02/>
1864                                  * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1865                                  * @link    https://www.flickr.com/photos/8047705@N02/5572197407
1866                                  */
1867                                 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1868                                 break;
1869                         default:
1870                                 /**
1871                                  * Use a random picture.
1872                                  * The service provides random pictures from Unsplash.
1873                                  * @license https://unsplash.com/license
1874                                  */
1875                                 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1876                                 break;
1877                 }
1878
1879                 return $header;
1880         }
1881
1882         /**
1883          * Fetch the default avatar for the given contact and size
1884          *
1885          * @param array $contact  contact array
1886          * @param string $size    Size of the avatar picture
1887          * @return string avatar URL
1888          */
1889         public static function getDefaultAvatar(array $contact, string $size): string
1890         {
1891                 switch ($size) {
1892                         case Proxy::SIZE_MICRO:
1893                                 $avatar['size'] = 48;
1894                                 $default = self::DEFAULT_AVATAR_MICRO;
1895                                 break;
1896
1897                         case Proxy::SIZE_THUMB:
1898                                 $avatar['size'] = 80;
1899                                 $default = self::DEFAULT_AVATAR_THUMB;
1900                                 break;
1901
1902                         case Proxy::SIZE_SMALL:
1903                         default:
1904                                 $avatar['size'] = 300;
1905                                 $default = self::DEFAULT_AVATAR_PHOTO;
1906                                 break;
1907                 }
1908
1909                 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1910                         $platform = '';
1911                         $type     = Contact::TYPE_PERSON;
1912
1913                         if (!empty($contact['id'])) {
1914                                 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1915                                 $platform = $account['platform'] ?? '';
1916                                 $type     = $account['contact-type'] ?? Contact::TYPE_PERSON;
1917                         }
1918
1919                         if (empty($platform) && !empty($contact['uri-id'])) {
1920                                 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1921                                 $platform = $account['platform'] ?? '';
1922                                 $type     = $account['contact-type'] ?? Contact::TYPE_PERSON;
1923                         }
1924
1925                         switch ($platform) {
1926                                 case 'corgidon':
1927                                         /**
1928                                          * Picture credits
1929                                          * @license GNU Affero General Public License v3.0
1930                                          * @link    https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1931                                          */
1932                                         $default = '/images/default/corgidon.png';
1933                                         break;
1934
1935                                 case 'diaspora':
1936                                         /**
1937                                          * Picture credits
1938                                          * @license GNU Affero General Public License v3.0
1939                                          * @link    https://github.com/diaspora/diaspora/
1940                                          */
1941                                         $default = '/images/default/diaspora.png';
1942                                         break;
1943
1944                                 case 'gotosocial':
1945                                         /**
1946                                          * Picture credits
1947                                          * @license GNU Affero General Public License v3.0
1948                                          * @link    https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1949                                          */
1950                                         $default = '/images/default/gotosocial.svg';
1951                                         break;
1952
1953                                 case 'hometown':
1954                                         /**
1955                                          * Picture credits
1956                                          * @license GNU Affero General Public License v3.0
1957                                          * @link    https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
1958                                          */
1959                                         $default = '/images/default/hometown.png';
1960                                         break;
1961
1962                                 case 'koyuspace':
1963                                         /**
1964                                          * Picture credits
1965                                          * @license GNU Affero General Public License v3.0
1966                                          * @link    https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
1967                                          */
1968                                         $default = '/images/default/koyuspace.png';
1969                                         break;
1970
1971                                 case 'ecko':
1972                                 case 'qoto':
1973                                 case 'mastodon':
1974                                         /**
1975                                          * Picture credits
1976                                          * @license GNU Affero General Public License v3.0
1977                                          * @link    https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
1978                                          */
1979                                         $default = '/images/default/mastodon.png';
1980                                         break;
1981
1982                                 case 'peertube':
1983                                         if ($type == Contact::TYPE_COMMUNITY) {
1984                                                 /**
1985                                                  * Picture credits
1986                                                  * @license GNU Affero General Public License v3.0
1987                                                  * @link    https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
1988                                                  */
1989                                                 $default = '/images/default/peertube-channel.png';
1990                                         } else {
1991                                                 /**
1992                                                  * Picture credits
1993                                                  * @license GNU Affero General Public License v3.0
1994                                                  * @link    https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
1995                                                  */
1996                                                 $default = '/images/default/peertube-account.png';
1997                                         }
1998                                         break;
1999
2000                                 case 'pleroma':
2001                                         /**
2002                                          * Picture credits
2003                                          * @license GNU Affero General Public License v3.0
2004                                          * @link    https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
2005                                          */
2006                                         $default = '/images/default/pleroma.png';
2007                                         break;
2008
2009                                 case 'plume':
2010                                         /**
2011                                          * Picture credits
2012                                          * @license GNU Affero General Public License v3.0
2013                                          * @link    https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
2014                                          */
2015                                         $default = '/images/default/plume.png';
2016                                         break;
2017                         }
2018                         return DI::baseUrl() . $default;
2019                 }
2020
2021                 if (!empty($contact['xmpp'])) {
2022                         $avatar['email'] = $contact['xmpp'];
2023                 } elseif (!empty($contact['addr'])) {
2024                         $avatar['email'] = $contact['addr'];
2025                 } elseif (!empty($contact['url'])) {
2026                         $avatar['email'] = $contact['url'];
2027                 } else {
2028                         return DI::baseUrl() . $default;
2029                 }
2030
2031                 $avatar['url'] = '';
2032                 $avatar['success'] = false;
2033
2034                 Hook::callAll('avatar_lookup', $avatar);
2035
2036                 if ($avatar['success'] && !empty($avatar['url'])) {
2037                         return $avatar['url'];
2038                 }
2039
2040                 return DI::baseUrl() . $default;
2041         }
2042
2043         /**
2044          * Get avatar link for given contact id
2045          *
2046          * @param integer $cid     contact id
2047          * @param string  $size    One of the Proxy::SIZE_* constants
2048          * @param string  $updated Contact update date
2049          * @return string avatar link
2050          */
2051         public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
2052         {
2053                 // We have to fetch the "updated" variable when it wasn't provided
2054                 // The parameter can be provided to improve performance
2055                 if (empty($updated)) {
2056                         $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2057                         $updated = $account['updated'] ?? '';
2058                         $guid = $account['guid'] ?? '';
2059                 }
2060
2061                 $guid = urlencode($guid);
2062
2063                 $url = DI::baseUrl() . '/photo/contact/';
2064                 switch ($size) {
2065                         case Proxy::SIZE_MICRO:
2066                                 $url .= Proxy::PIXEL_MICRO . '/';
2067                                 break;
2068                         case Proxy::SIZE_THUMB:
2069                                 $url .= Proxy::PIXEL_THUMB . '/';
2070                                 break;
2071                         case Proxy::SIZE_SMALL:
2072                                 $url .= Proxy::PIXEL_SMALL . '/';
2073                                 break;
2074                         case Proxy::SIZE_MEDIUM:
2075                                 $url .= Proxy::PIXEL_MEDIUM . '/';
2076                                 break;
2077                         case Proxy::SIZE_LARGE:
2078                                 $url .= Proxy::PIXEL_LARGE . '/';
2079                                 break;
2080                 }
2081                 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2082         }
2083
2084         /**
2085          * Get avatar link for given contact URL
2086          *
2087          * @param string  $url  contact url
2088          * @param integer $uid  user id
2089          * @param string  $size One of the Proxy::SIZE_* constants
2090          * @return string avatar link
2091          */
2092         public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2093         {
2094                 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2095                         Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
2096                 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2097                 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2098         }
2099
2100         /**
2101          * Get header link for given contact id
2102          *
2103          * @param integer $cid     contact id
2104          * @param string  $size    One of the Proxy::SIZE_* constants
2105          * @param string  $updated Contact update date
2106          * @return string header link
2107          */
2108         public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
2109         {
2110                 // We have to fetch the "updated" variable when it wasn't provided
2111                 // The parameter can be provided to improve performance
2112                 if (empty($updated) || empty($guid)) {
2113                         $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2114                         $updated = $account['updated'] ?? '';
2115                         $guid = $account['guid'] ?? '';
2116                 }
2117
2118                 $guid = urlencode($guid);
2119
2120                 $url = DI::baseUrl() . '/photo/header/';
2121                 switch ($size) {
2122                         case Proxy::SIZE_MICRO:
2123                                 $url .= Proxy::PIXEL_MICRO . '/';
2124                                 break;
2125                         case Proxy::SIZE_THUMB:
2126                                 $url .= Proxy::PIXEL_THUMB . '/';
2127                                 break;
2128                         case Proxy::SIZE_SMALL:
2129                                 $url .= Proxy::PIXEL_SMALL . '/';
2130                                 break;
2131                         case Proxy::SIZE_MEDIUM:
2132                                 $url .= Proxy::PIXEL_MEDIUM . '/';
2133                                 break;
2134                         case Proxy::SIZE_LARGE:
2135                                 $url .= Proxy::PIXEL_LARGE . '/';
2136                                 break;
2137                 }
2138
2139                 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2140         }
2141
2142         /**
2143          * Updates the avatar links in a contact only if needed
2144          *
2145          * @param int    $cid          Contact id
2146          * @param string $avatar       Link to avatar picture
2147          * @param bool   $force        force picture update
2148          * @param bool   $create_cache Enforces the creation of cached avatar fields
2149          *
2150          * @return void
2151          * @throws HTTPException\InternalServerErrorException
2152          * @throws HTTPException\NotFoundException
2153          * @throws \ImagickException
2154          */
2155         public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2156         {
2157                 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2158                         ['id' => $cid, 'self' => false]);
2159                 if (!DBA::isResult($contact)) {
2160                         return;
2161                 }
2162
2163                 $uid = $contact['uid'];
2164
2165                 // Only update the cached photo links of public contacts when they already are cached
2166                 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2167                         if ($contact['avatar'] != $avatar) {
2168                                 self::update(['avatar' => $avatar], ['id' => $cid]);
2169                                 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2170                         }
2171                         return;
2172                 }
2173
2174                 // User contacts use are updated through the public contacts
2175                 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2176                         $pcid = self::getIdForURL($contact['url'], 0, false);
2177                         if (!empty($pcid)) {
2178                                 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2179                                 self::updateAvatar($pcid, $avatar, $force, true);
2180                                 return;
2181                         }
2182                 }
2183
2184                 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2185
2186                 if ($default_avatar) {
2187                         $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2188                 }
2189
2190                 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2191
2192                 // Local contact avatars don't need to be cached
2193                 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2194                         $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2195                 }
2196
2197                 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2198                         Avatar::deleteCache($contact);
2199
2200                         if ($default_avatar && Proxy::isLocalImage($avatar)) {
2201                                 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2202                                         'photo' => $avatar,
2203                                         'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2204                                         'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2205                                 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2206                         }
2207
2208                         // Use the data from the self account
2209                         if (empty($fields)) {
2210                                 $local_uid = User::getIdForURL($contact['url']);
2211                                 if (!empty($local_uid)) {
2212                                         $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2213                                         Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2214                                 }
2215                         }
2216
2217                         if (empty($fields)) {
2218                                 $update = ($contact['avatar'] != $avatar) || $force;
2219
2220                                 if (!$update) {
2221                                         $data = [
2222                                                 $contact['photo'] ?? '',
2223                                                 $contact['thumb'] ?? '',
2224                                                 $contact['micro'] ?? '',
2225                                         ];
2226
2227                                         foreach ($data as $image_uri) {
2228                                                 $image_rid = Photo::ridFromURI($image_uri);
2229                                                 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2230                                                         Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2231                                                         $update = true;
2232                                                 }
2233                                         }
2234                                 }
2235
2236                                 if ($update) {
2237                                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2238                                         if ($photos) {
2239                                                 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
2240                                                 $update = !empty($fields);
2241                                                 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2242                                         } else {
2243                                                 $update = false;
2244                                         }
2245                                 }
2246                         } else {
2247                                 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2248                         }
2249                 } else {
2250                         Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2251                         $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2252                         $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2253                 }
2254
2255                 if (!$update) {
2256                         return;
2257                 }
2258
2259                 $cids = [];
2260                 $uids = [];
2261                 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2262                         // Collect all user contacts of the given public contact
2263                         $personal_contacts = DBA::select('contact', ['id', 'uid'],
2264                                 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2265                         while ($personal_contact = DBA::fetch($personal_contacts)) {
2266                                 $cids[] = $personal_contact['id'];
2267                                 $uids[] = $personal_contact['uid'];
2268                         }
2269                         DBA::close($personal_contacts);
2270
2271                         if (!empty($cids)) {
2272                                 // Delete possibly existing cached user contact avatars
2273                                 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2274                         }
2275                 }
2276
2277                 $cids[] = $cid;
2278                 $uids[] = $uid;
2279                 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2280                 self::update($fields, ['id' => $cids]);
2281         }
2282
2283         public static function deleteContactByUrl(string $url)
2284         {
2285                 // Update contact data for all users
2286                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2287                 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2288                 while ($contact = DBA::fetch($contacts)) {
2289                         Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2290                         self::remove($contact['id']);
2291                 }
2292         }
2293
2294         /**
2295          * Helper function for "updateFromProbe". Updates personal and public contact
2296          *
2297          * @param integer $id     contact id
2298          * @param integer $uid    user id
2299          * @param integer $uri_id Uri-Id
2300          * @param string  $url    The profile URL of the contact
2301          * @param array   $fields The fields that are updated
2302          *
2303          * @throws \Exception
2304          */
2305         private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2306         {
2307                 if (!self::update($fields, ['id' => $id])) {
2308                         Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2309                         return;
2310                 }
2311
2312                 self::setAccountUser($id, $uid, $uri_id, $url);
2313
2314                 // Archive or unarchive the contact.
2315                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2316                 if (!DBA::isResult($contact)) {
2317                         Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2318                         return;
2319                 }
2320
2321                 if (isset($fields['failed'])) {
2322                         if ($fields['failed']) {
2323                                 self::markForArchival($contact);
2324                         } else {
2325                                 self::unmarkForArchival($contact);
2326                         }
2327                 }
2328
2329                 if ($contact['uid'] != 0) {
2330                         return;
2331                 }
2332
2333                 // Update contact data for all users
2334                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2335
2336                 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2337                 self::update($fields, $condition);
2338
2339                 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2340                 $condition['network'] = Protocol::OSTATUS;
2341
2342                 // If the contact failed, propagate the update fields to all contacts
2343                 if (empty($fields['failed'])) {
2344                         unset($fields['last-update']);
2345                         unset($fields['success_update']);
2346                         unset($fields['failure_update']);
2347                 }
2348
2349                 if (empty($fields)) {
2350                         return;
2351                 }
2352
2353                 self::update($fields, $condition);
2354         }
2355
2356         /**
2357          * Create or update an "account-user" entry
2358          *
2359          * @param integer $id
2360          * @param integer $uid
2361          * @param integer $uri_id
2362          * @param string $url
2363          * @return void
2364          */
2365         public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2366         {
2367                 if (empty($uri_id)) {
2368                         return;
2369                 }
2370
2371                 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2372                 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2373                         if ($account_user['uid'] == $uid) {
2374                                 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2375                                 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2376                         } else {
2377                                 // This should never happen
2378                                 Logger::warning('account-user exists for a different uri-id and uid', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2379                         }
2380                 }
2381
2382                 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2383                 if (!empty($account_user['id'])) {
2384                         if ($account_user['id'] == $id) {
2385                                 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2386                                 return;
2387                         } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2388                                 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2389                                 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2390                                 return;
2391                         }
2392                         Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2393                         Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2394                 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2395                         Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2396                 } else {
2397                         Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2398                 }
2399         }
2400
2401         /**
2402          * Remove duplicated contacts
2403          *
2404          * @param string  $nurl  Normalised contact url
2405          * @param integer $uid   User id
2406          * @return boolean
2407          * @throws \Exception
2408          */
2409         public static function removeDuplicates(string $nurl, int $uid)
2410         {
2411                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2412                 $count = DBA::count('contact', $condition);
2413                 if ($count <= 1) {
2414                         return false;
2415                 }
2416
2417                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2418                 if (!DBA::isResult($first_contact)) {
2419                         // Shouldn't happen - so we handle it
2420                         return false;
2421                 }
2422
2423                 $first = $first_contact['id'];
2424                 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2425
2426                 // Find all duplicates
2427                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2428                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2429                 while ($duplicate = DBA::fetch($duplicates)) {
2430                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2431                                 continue;
2432                         }
2433
2434                         Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2435                 }
2436                 DBA::close($duplicates);
2437                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2438                 return true;
2439         }
2440
2441         /**
2442          * Updates contact record by provided id and optional network
2443          *
2444          * @param integer $id      contact id
2445          * @param string  $network Optional network we are probing for
2446          * @return boolean
2447          * @throws HTTPException\InternalServerErrorException
2448          * @throws \ImagickException
2449          */
2450         public static function updateFromProbe(int $id, string $network = '')
2451         {
2452                 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2453                 if (!DBA::isResult($contact)) {
2454                         return false;
2455                 }
2456
2457                 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2458
2459                 if ($ret['network'] == Protocol::DIASPORA) {
2460                         FContact::updateFromProbeArray($ret);
2461                 }
2462
2463                 return self::updateFromProbeArray($id, $ret);
2464         }
2465
2466         /**
2467          * Checks if the given contact has got local data
2468          *
2469          * @param int   $id
2470          * @param array $contact
2471          *
2472          * @return boolean
2473          */
2474         private static function hasLocalData(int $id, array $contact): bool
2475         {
2476                 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2477                         // User contacts with the same uri-id exist
2478                         return true;
2479                 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2480                         // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2481                         return true;
2482                 }
2483                 if (DBA::exists('post-tag', ['cid' => $id])) {
2484                         // Is tagged in a post
2485                         return true;
2486                 }
2487                 if (DBA::exists('user-contact', ['cid' => $id])) {
2488                         // Has got user-contact data
2489                         return true;
2490                 }
2491                 if (Post::exists(['author-id' => $id])) {
2492                         // Posts with this author exist
2493                         return true;
2494                 }
2495                 if (Post::exists(['owner-id' => $id])) {
2496                         // Posts with this owner exist
2497                         return true;
2498                 }
2499                 if (Post::exists(['causer-id' => $id])) {
2500                         // Posts with this causer exist
2501                         return true;
2502                 }
2503                 // We don't have got this contact locally
2504                 return false;
2505         }
2506
2507         /**
2508          * Updates contact record by provided id and probed data
2509          *
2510          * @param integer $id      contact id
2511          * @param array   $ret     Probed data
2512          * @return boolean
2513          * @throws HTTPException\InternalServerErrorException
2514          * @throws \ImagickException
2515          */
2516         private static function updateFromProbeArray(int $id, array $ret): bool
2517         {
2518                 /*
2519                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2520                   This will reliably kill your communication with old Friendica contacts.
2521                  */
2522
2523                 // These fields aren't updated by this routine:
2524                 // 'sensitive'
2525
2526                 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2527                         'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2528                         'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2529                         'created', 'last-update'];
2530                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2531                 if (!DBA::isResult($contact)) {
2532                         return false;
2533                 }
2534
2535                 if (self::isLocal($ret['url'])) {
2536                         if ($contact['uid'] == 0) {
2537                                 Logger::info('Local contacts are not updated here.');
2538                         } else {
2539                                 self::updateFromPublicContact($id, $contact);
2540                         }
2541                         return true;
2542                 }
2543
2544                 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2545                         Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2546                         self::remove($id);
2547
2548                         // Delete all contacts with the same URL
2549                         self::deleteContactByUrl($ret['url']);
2550                         return true;
2551                 }
2552
2553                 $uid = $contact['uid'];
2554                 unset($contact['uid']);
2555
2556                 $uriid = $contact['uri-id'];
2557                 unset($contact['uri-id']);
2558
2559                 $pubkey = $contact['pubkey'];
2560                 unset($contact['pubkey']);
2561
2562                 $created = $contact['created'];
2563                 unset($contact['created']);
2564
2565                 $last_update = $contact['last-update'];
2566                 unset($contact['last-update']);
2567
2568                 $contact['photo'] = $contact['avatar'];
2569                 unset($contact['avatar']);
2570
2571                 $updated = DateTimeFormat::utcNow();
2572
2573                 $has_local_data = self::hasLocalData($id, $contact);
2574
2575                 if (!Probe::isProbable($ret['network'])) {
2576                         // Periodical checks are only done on federated contacts
2577                         $failed_next_update  = null;
2578                         $success_next_update = null;
2579                 } elseif ($has_local_data) {
2580                         $failed_next_update  = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2581                         $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2582                 } else {
2583                         $failed_next_update  = DateTimeFormat::utc('now +6 month');
2584                         $success_next_update = DateTimeFormat::utc('now +1 month');
2585                 }
2586
2587                 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2588                         Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2589                         self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
2590                         return false;
2591                 }
2592
2593                 // We must not try to update relay contacts via probe. They are no real contacts.
2594                 // We check after the probing to be able to correct falsely detected contact types.
2595                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2596                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2597                         self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
2598                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2599                         return true;
2600                 }
2601
2602                 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2603                 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2604                         self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
2605                         return false;
2606                 }
2607
2608                 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2609                         $cid = self::getIdForURL($ret['url'], 0, false);
2610                         if (!empty($cid) && ($cid != $id)) {
2611                                 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2612                                 return self::updateFromProbeArray($cid, $ret);
2613                         }
2614                 }
2615
2616                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2617                         $ret['unsearchable'] = $ret['hide'];
2618                 }
2619
2620                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2621                         $ret['forum'] = false;
2622                         $ret['prv'] = false;
2623                         $ret['contact-type'] = $ret['account-type'];
2624                         if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2625                                 $ret['forum'] = (bool)!$ret['manually-approve'];
2626                                 $ret['prv'] = (bool)!$ret['forum'];
2627                         }
2628                 }
2629
2630                 $new_pubkey = $ret['pubkey'] ?? '';
2631
2632                 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2633                         if ($ret['network'] == Protocol::ACTIVITYPUB) {
2634                                 $apcontact = APContact::getByURL($ret['url'], false);
2635                                 if (!empty($apcontact['featured'])) {
2636                                         Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2637                                 }
2638                         }
2639
2640                         $ret['last-item'] = Probe::getLastUpdate($ret);
2641                         Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2642                 }
2643
2644                 $update = false;
2645                 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
2646
2647                 // make sure to not overwrite existing values with blank entries except some technical fields
2648                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2649                 foreach ($ret as $key => $val) {
2650                         if (!array_key_exists($key, $contact)) {
2651                                 unset($ret[$key]);
2652                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2653                                 $ret[$key] = $contact[$key];
2654                         } elseif ($ret[$key] != $contact[$key]) {
2655                                 $update = true;
2656                         }
2657                 }
2658
2659                 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2660                         $update = true;
2661                 } else {
2662                         unset($ret['last-item']);
2663                 }
2664
2665                 if (empty($uriid)) {
2666                         $update = true;
2667                 }
2668
2669                 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2670                         self::updateAvatar($id, $ret['photo'], $update);
2671                 }
2672
2673                 if (!$update) {
2674                         self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
2675
2676                         if (Contact\Relation::isDiscoverable($ret['url'])) {
2677                                 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2678                         }
2679
2680                         // Update the public contact
2681                         if ($uid != 0) {
2682                                 $contact = self::getByURL($ret['url'], false, ['id']);
2683                                 if (!empty($contact['id'])) {
2684                                         self::updateFromProbeArray($contact['id'], $ret);
2685                                 }
2686                         }
2687
2688                         return true;
2689                 }
2690
2691                 $ret['uri-id']      = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2692                 $ret['nurl']        = Strings::normaliseLink($ret['url']);
2693                 $ret['updated']     = $updated;
2694                 $ret['failed']      = false;
2695                 $ret['next-update'] = $success_next_update;
2696                 $ret['local-data']  = $has_local_data;
2697
2698                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2699                 if (empty($pubkey) && !empty($new_pubkey)) {
2700                         $ret['pubkey'] = $new_pubkey;
2701                 }
2702
2703                 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2704                         $ret['uri-date'] = $updated;
2705                 }
2706
2707                 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2708                         $ret['name-date'] = $updated;
2709                 }
2710
2711                 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2712                         $ret['last-update'] = $updated;
2713                         $ret['success_update'] = $updated;
2714                 }
2715
2716                 unset($ret['photo']);
2717
2718                 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2719
2720                 if (Contact\Relation::isDiscoverable($ret['url'])) {
2721                         Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2722                 }
2723
2724                 return true;
2725         }
2726
2727         private static function updateFromPublicContact(int $id, array $contact)
2728         {
2729                 $public = self::getByURL($contact['url'], false);
2730
2731                 $fields = [];
2732
2733                 foreach ($contact as $field => $value) {
2734                         if ($field == 'uid') {
2735                                 continue;
2736                         }
2737                         if ($public[$field] != $value) {
2738                                 $fields[$field] = $public[$field];
2739                         }
2740                 }
2741                 if (!empty($fields)) {
2742                         self::update($fields, ['id' => $id, 'self' => false]);
2743                         Logger::info('Updating local contact', ['id' => $id]);
2744                 }
2745         }
2746
2747         /**
2748          * Updates contact record by provided URL
2749          *
2750          * @param integer $url contact url
2751          * @return integer Contact id
2752          * @throws HTTPException\InternalServerErrorException
2753          * @throws \ImagickException
2754          */
2755         public static function updateFromProbeByURL(string $url): int
2756         {
2757                 $id = self::getIdForURL($url);
2758
2759                 if (empty($id)) {
2760                         return $id;
2761                 }
2762
2763                 self::updateFromProbe($id);
2764
2765                 return $id;
2766         }
2767
2768         /**
2769          * Detects the communication protocol for a given contact url.
2770          * This is used to detect Friendica contacts that we can communicate via AP.
2771          *
2772          * @param string $url contact url
2773          * @param string $network Network of that contact
2774          * @return string with protocol
2775          */
2776         public static function getProtocol(string $url, string $network): string
2777         {
2778                 if ($network != Protocol::DFRN) {
2779                         return $network;
2780                 }
2781
2782                 $apcontact = APContact::getByURL($url);
2783                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2784                         return Protocol::ACTIVITYPUB;
2785                 } else {
2786                         return $network;
2787                 }
2788         }
2789
2790         /**
2791          * Takes a $uid and a url/handle and adds a new contact
2792          *
2793          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2794          * dfrn_request page.
2795          *
2796          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2797          *
2798          * Returns an array
2799          * $return['success'] boolean true if successful
2800          * $return['message'] error text if success is false.
2801          *
2802          * Takes a $uid and a url/handle and adds a new contact
2803          *
2804          * @param int    $uid         The user id the contact should be created for
2805          * @param string $url         The profile URL of the contact
2806          * @param string $network
2807          * @return array
2808          * @throws HTTPException\InternalServerErrorException
2809          * @throws HTTPException\NotFoundException
2810          * @throws \ImagickException
2811          */
2812         public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2813         {
2814                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2815
2816                 // remove ajax junk, e.g. Twitter
2817                 $url = str_replace('/#!/', '/', $url);
2818
2819                 if (!Network::isUrlAllowed($url)) {
2820                         $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2821                         return $result;
2822                 }
2823
2824                 if (Network::isUrlBlocked($url)) {
2825                         $result['message'] = DI::l10n()->t('Blocked domain');
2826                         return $result;
2827                 }
2828
2829                 if (!$url) {
2830                         $result['message'] = DI::l10n()->t('Connect URL missing.');
2831                         return $result;
2832                 }
2833
2834                 $arr = ['url' => $url, 'contact' => []];
2835
2836                 Hook::callAll('follow', $arr);
2837
2838                 if (empty($arr)) {
2839                         $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2840                         return $result;
2841                 }
2842
2843                 if (!empty($arr['contact']['name'])) {
2844                         $probed = false;
2845                         $ret = $arr['contact'];
2846                 } else {
2847                         $probed = true;
2848                         $ret = Probe::uri($url, $network, $uid);
2849
2850                         // Ensure that the public contact exists
2851                         if ($ret['network'] != Protocol::PHANTOM) {
2852                                 self::getIdForURL($url);
2853                         }
2854                 }
2855
2856                 if (($network != '') && ($ret['network'] != $network)) {
2857                         Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2858                         return $result;
2859                 }
2860
2861                 // check if we already have a contact
2862                 // the poll url is more reliable than the profile url, as we may have
2863                 // indirect links or webfinger links
2864
2865                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2866                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2867                 if (!DBA::isResult($contact)) {
2868                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2869                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2870                 }
2871
2872                 $protocol = self::getProtocol($ret['url'], $ret['network']);
2873
2874                 // This extra param just confuses things, remove it
2875                 if ($protocol === Protocol::DIASPORA) {
2876                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2877                 }
2878
2879                 // do we have enough information?
2880                 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2881                         $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
2882                         if (empty($ret['poll'])) {
2883                                 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
2884                         }
2885                         if (empty($ret['name'])) {
2886                                 $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
2887                         }
2888                         if (empty($ret['url'])) {
2889                                 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
2890                         }
2891                         if (strpos($ret['url'], '@') !== false) {
2892                                 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
2893                                 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
2894                         }
2895                         return $result;
2896                 }
2897
2898                 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2899                         $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
2900                         $ret['notify'] = '';
2901                 }
2902
2903                 if (!$ret['notify']) {
2904                         $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
2905                 }
2906
2907                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2908
2909                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2910
2911                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2912
2913                 $pending = false;
2914                 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2915                         $pending = (bool)$ret['manually-approve'];
2916                 }
2917
2918                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2919                         $writeable = 1;
2920                 }
2921
2922                 if (DBA::isResult($contact)) {
2923                         // update contact
2924                         $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2925
2926                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2927                         self::update($fields, ['id' => $contact['id']]);
2928                 } else {
2929                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2930
2931                         // create contact record
2932                         self::insert([
2933                                 'uid'     => $uid,
2934                                 'created' => DateTimeFormat::utcNow(),
2935                                 'url'     => $ret['url'],
2936                                 'nurl'    => Strings::normaliseLink($ret['url']),
2937                                 'addr'    => $ret['addr'],
2938                                 'alias'   => $ret['alias'],
2939                                 'batch'   => $ret['batch'],
2940                                 'notify'  => $ret['notify'],
2941                                 'poll'    => $ret['poll'],
2942                                 'poco'    => $ret['poco'],
2943                                 'name'    => $ret['name'],
2944                                 'nick'    => $ret['nick'],
2945                                 'network' => $ret['network'],
2946                                 'baseurl' => $ret['baseurl'],
2947                                 'gsid'    => $ret['gsid'] ?? null,
2948                                 'protocol' => $protocol,
2949                                 'pubkey'  => $ret['pubkey'],
2950                                 'rel'     => $new_relation,
2951                                 'priority'=> $ret['priority'],
2952                                 'writable'=> $writeable,
2953                                 'hidden'  => $hidden,
2954                                 'blocked' => 0,
2955                                 'readonly'=> 0,
2956                                 'pending' => $pending,
2957                                 'subhub'  => $subhub
2958                         ]);
2959                 }
2960
2961                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2962                 if (!DBA::isResult($contact)) {
2963                         $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
2964                         return $result;
2965                 }
2966
2967                 $contact_id = $contact['id'];
2968                 $result['cid'] = $contact_id;
2969
2970                 Group::addMember(User::getDefaultGroup($uid), $contact_id);
2971
2972                 // Update the avatar
2973                 self::updateAvatar($contact_id, $ret['photo']);
2974
2975                 // pull feed and consume it, which should subscribe to the hub.
2976                 if ($contact['network'] == Protocol::OSTATUS) {
2977                         Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2978                 }
2979
2980                 if ($probed) {
2981                         self::updateFromProbeArray($contact_id, $ret);
2982                 } else {
2983                         Worker::add(Worker::PRIORITY_HIGH, 'UpdateContact', $contact_id);
2984                 }
2985
2986                 $result['success'] = Protocol::follow($uid, $contact, $protocol);
2987
2988                 return $result;
2989         }
2990
2991         /**
2992          * @param array  $importer Owner (local user) data
2993          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2994          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2995          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2996          * @param string $note     Introduction additional message
2997          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2998          * @throws HTTPException\InternalServerErrorException
2999          * @throws \ImagickException
3000          */
3001         public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
3002         {
3003                 // Should always be set
3004                 if (empty($datarray['author-id'])) {
3005                         return false;
3006                 }
3007
3008                 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
3009                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
3010                 if (!DBA::isResult($pub_contact)) {
3011                         // Should never happen
3012                         return false;
3013                 }
3014
3015                 // Contact is blocked at node-level
3016                 if (self::isBlocked($datarray['author-id'])) {
3017                         return false;
3018                 }
3019
3020                 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
3021                 $name = $pub_contact['name'];
3022                 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3023                 $nick = $pub_contact['nick'];
3024                 $network = $pub_contact['network'];
3025
3026                 // Ensure that we don't create a new contact when there already is one
3027                 $cid = self::getIdForURL($url, $importer['uid']);
3028                 if (!empty($cid)) {
3029                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3030                 }
3031
3032                 self::clearFollowerFollowingEndpointCache($importer['uid']);
3033
3034                 if (!empty($contact)) {
3035                         if (!empty($contact['pending'])) {
3036                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3037                                 return null;
3038                         }
3039
3040                         // Contact is blocked at user-level
3041                         if (!empty($contact['id']) && !empty($importer['id']) &&
3042                                 Contact\User::isBlocked($contact['id'], $importer['id'])) {
3043                                 return false;
3044                         }
3045
3046                         // Make sure that the existing contact isn't archived
3047                         self::unmarkForArchival($contact);
3048
3049                         if (($contact['rel'] == self::SHARING)
3050                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
3051                                 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3052                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
3053                         }
3054
3055                         // Ensure to always have the correct network type, independent from the connection request method
3056                         self::updateFromProbe($contact['id']);
3057
3058                         Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3059
3060                         return true;
3061                 } else {
3062                         // send email notification to owner?
3063                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3064                                 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3065                                 return null;
3066                         }
3067
3068                         // create contact record
3069                         $contact_id = self::insert([
3070                                 'uid'      => $importer['uid'],
3071                                 'created'  => DateTimeFormat::utcNow(),
3072                                 'url'      => $url,
3073                                 'nurl'     => Strings::normaliseLink($url),
3074                                 'name'     => $name,
3075                                 'nick'     => $nick,
3076                                 'network'  => $network,
3077                                 'rel'      => self::FOLLOWER,
3078                                 'blocked'  => 0,
3079                                 'readonly' => 0,
3080                                 'pending'  => 1,
3081                                 'writable' => 1,
3082                         ]);
3083
3084                         // Ensure to always have the correct network type, independent from the connection request method
3085                         self::updateFromProbe($contact_id);
3086
3087                         self::updateAvatar($contact_id, $photo, true);
3088
3089                         Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3090
3091                         $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
3092
3093                         /// @TODO Encapsulate this into a function/method
3094                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3095                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3096                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3097                                 // create notification
3098                                 if (is_array($contact_record)) {
3099                                         $intro = DI::introFactory()->createNew(
3100                                                 $importer['uid'],
3101                                                 $contact_record['id'],
3102                                                 $note
3103                                         );
3104                                         DI::intro()->save($intro);
3105                                 }
3106
3107                                 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
3108
3109                                 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3110                                         DI::notify()->createFromArray([
3111                                                 'type'  => Notification\Type::INTRO,
3112                                                 'otype' => Notification\ObjectType::INTRO,
3113                                                 'verb'  => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3114                                                 'uid'   => $user['uid'],
3115                                                 'cid'   => $contact_record['id'],
3116                                                 'link'  => DI::baseUrl() . '/notifications/intros',
3117                                         ]);
3118                                 }
3119                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3120                                 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3121                                         self::createFromProbeForUser($importer['uid'], $url, $network);
3122                                 }
3123
3124                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3125                                 $fields = ['pending' => false];
3126                                 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3127                                         $fields['rel'] = self::FRIEND;
3128                                 }
3129
3130                                 self::update($fields, $condition);
3131
3132                                 return true;
3133                         }
3134                 }
3135
3136                 return null;
3137         }
3138
3139         /**
3140          * Update the local relationship when a local user loses a follower
3141          *
3142          * @param array $contact User-specific contact (uid != 0) array
3143          * @return void
3144          * @throws HTTPException\InternalServerErrorException
3145          * @throws \ImagickException
3146          */
3147         public static function removeFollower(array $contact)
3148         {
3149                 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3150                         self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3151                 } elseif (!empty($contact['id'])) {
3152                         self::remove($contact['id']);
3153                 } else {
3154                         DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3155                         return;
3156                 }
3157
3158                 self::clearFollowerFollowingEndpointCache($contact['uid']);
3159
3160                 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3161
3162                 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3163         }
3164
3165         /**
3166          * Update the local relationship when a local user unfollow a contact.
3167          * Removes the contact for sharing-only protocols (feed and mail).
3168          *
3169          * @param array $contact User-specific contact (uid != 0) array
3170          * @throws HTTPException\InternalServerErrorException
3171          */
3172         public static function removeSharer(array $contact)
3173         {
3174                 self::clearFollowerFollowingEndpointCache($contact['uid']);
3175
3176                 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3177                         self::remove($contact['id']);
3178                 } else {
3179                         self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
3180                 }
3181         }
3182
3183         /**
3184          * Create a birthday event.
3185          *
3186          * Update the year and the birthday.
3187          */
3188         public static function updateBirthdays()
3189         {
3190                 $condition = [
3191                         '`bd` > ?
3192                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3193                         AND NOT `contact`.`pending`
3194                         AND NOT `contact`.`hidden`
3195                         AND NOT `contact`.`blocked`
3196                         AND NOT `contact`.`archive`
3197                         AND NOT `contact`.`deleted`',
3198                         DBA::NULL_DATE,
3199                         self::SHARING,
3200                         self::FRIEND
3201                 ];
3202
3203                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3204
3205                 while ($contact = DBA::fetch($contacts)) {
3206                         Logger::notice('update_contact_birthday: ' . $contact['bd']);
3207
3208                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3209
3210                         if (Event::createBirthday($contact, $nextbd)) {
3211                                 // update bdyear
3212                                 DBA::update(
3213                                         'contact',
3214                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3215                                         ['id' => $contact['id']]
3216                                 );
3217                         }
3218                 }
3219                 DBA::close($contacts);
3220         }
3221
3222         /**
3223          * Remove the unavailable contact ids from the provided list
3224          *
3225          * @param array $contact_ids Contact id list
3226          * @return array
3227          * @throws \Exception
3228          */
3229         public static function pruneUnavailable(array $contact_ids): array
3230         {
3231                 if (empty($contact_ids)) {
3232                         return [];
3233                 }
3234
3235                 $contacts = self::selectToArray(['id'], [
3236                         'id'      => $contact_ids,
3237                         'blocked' => false,
3238                         'pending' => false,
3239                         'archive' => false,
3240                 ]);
3241
3242                 return array_column($contacts, 'id');
3243         }
3244
3245         /**
3246          * Returns a magic link to authenticate remote visitors
3247          *
3248          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
3249          *
3250          * @param string $contact_url The address of the target contact profile
3251          * @param string $url         An url that we will be redirected to after the authentication
3252          *
3253          * @return string with "redir" link
3254          * @throws HTTPException\InternalServerErrorException
3255          * @throws \ImagickException
3256          */
3257         public static function magicLink(string $contact_url, string $url = ''): string
3258         {
3259                 if (!DI::userSession()->isAuthenticated()) {
3260                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3261                 }
3262
3263                 $contact = self::getByURL($contact_url, false);
3264                 if (empty($contact)) {
3265                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3266                 }
3267
3268                 // Prevents endless loop in case only a non-public contact exists for the contact URL
3269                 unset($contact['uid']);
3270
3271                 return self::magicLinkByContact($contact, $url ?: $contact_url);
3272         }
3273
3274         /**
3275          * Returns a magic link to authenticate remote visitors
3276          *
3277          * @param integer $cid The contact id of the target contact profile
3278          * @param string  $url An url that we will be redirected to after the authentication
3279          *
3280          * @return string with "redir" link
3281          * @throws HTTPException\InternalServerErrorException
3282          * @throws \ImagickException
3283          */
3284         public static function magicLinkById(int $cid, string $url = ''): string
3285         {
3286                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3287
3288                 return self::magicLinkByContact($contact, $url);
3289         }
3290
3291         /**
3292          * Returns a magic link to authenticate remote visitors
3293          *
3294          * @param array  $contact The contact array with "uid", "network" and "url"
3295          * @param string $url     An url that we will be redirected to after the authentication
3296          *
3297          * @return string with "redir" link
3298          * @throws HTTPException\InternalServerErrorException
3299          * @throws \ImagickException
3300          */
3301         public static function magicLinkByContact(array $contact, string $url = ''): string
3302         {
3303                 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3304
3305                 if (!DI::userSession()->isAuthenticated()) {
3306                         return $destination;
3307                 }
3308
3309                 // Only redirections to the same host do make sense
3310                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3311                         return $url;
3312                 }
3313
3314                 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
3315                         return 'contact/' . $contact['id'] . '/conversations';
3316                 }
3317
3318                 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3319                         return $destination;
3320                 }
3321
3322                 if (empty($contact['id'])) {
3323                         return $destination;
3324                 }
3325
3326                 $redirect = 'redir/' . $contact['id'];
3327
3328                 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3329                         $redirect .= '?url=' . $url;
3330                 }
3331
3332                 return $redirect;
3333         }
3334
3335         /**
3336          * Is the contact a forum?
3337          *
3338          * @param integer $contactid ID of the contact
3339          *
3340          * @return boolean "true" if it is a forum
3341          */
3342         public static function isForum(int $contactid): bool
3343         {
3344                 $fields = ['contact-type'];
3345                 $condition = ['id' => $contactid];
3346                 $contact = DBA::selectFirst('contact', $fields, $condition);
3347                 if (!DBA::isResult($contact)) {
3348                         return false;
3349                 }
3350
3351                 // Is it a forum?
3352                 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3353         }
3354
3355         /**
3356          * Can the remote contact receive private messages?
3357          *
3358          * @param array $contact
3359          * @return bool
3360          */
3361         public static function canReceivePrivateMessages(array $contact): bool
3362         {
3363                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3364                 $self = $contact['self'] ?? false;
3365
3366                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3367         }
3368
3369         /**
3370          * Search contact table by nick or name
3371          *
3372          * @param string $search Name or nick
3373          * @param string $mode   Search mode (e.g. "community")
3374          * @param int    $uid    User ID
3375          *
3376          * @return array with search results
3377          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3378          */
3379         public static function searchByName(string $search, string $mode = '', int $uid = 0): array
3380         {
3381                 if (empty($search)) {
3382                         return [];
3383                 }
3384
3385                 // check supported networks
3386                 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3387                 if (DI::config()->get('system', 'diaspora_enabled')) {
3388                         $networks[] = Protocol::DIASPORA;
3389                 }
3390
3391                 if (!DI::config()->get('system', 'ostatus_disabled')) {
3392                         $networks[] = Protocol::OSTATUS;
3393                 }
3394
3395                 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3396
3397                 if ($uid == 0) {
3398                         $condition['blocked'] = false;
3399                 }
3400
3401                 // check if we search only communities or every contact
3402                 if ($mode === 'community') {
3403                         $condition['contact-type'] = self::TYPE_COMMUNITY;
3404                 }
3405
3406                 $search .= '%';
3407
3408                 $condition = DBA::mergeConditions($condition,
3409                         ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3410                         AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3411
3412                 $contacts = self::selectToArray([], $condition);
3413                 return $contacts;
3414         }
3415
3416         /**
3417          * Add public contacts from an array
3418          *
3419          * @param array $urls
3420          * @return array result "count", "added" and "updated"
3421          */
3422         public static function addByUrls(array $urls): array
3423         {
3424                 $added = 0;
3425                 $updated = 0;
3426                 $unchanged = 0;
3427                 $count = 0;
3428
3429                 foreach ($urls as $url) {
3430                         if (empty($url) || !is_string($url)) {
3431                                 continue;
3432                         }
3433                         $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3434                         if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3435                                 Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
3436                                 ++$added;
3437                         } elseif (!empty($contact['network']) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3438                                 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
3439                                 ++$updated;
3440                         } else {
3441                                 ++$unchanged;
3442                         }
3443                         ++$count;
3444                 }
3445
3446                 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3447         }
3448
3449         /**
3450          * Returns a random, global contact array of the current node
3451          *
3452          * @return array The profile array
3453          * @throws Exception
3454          */
3455         public static function getRandomContact(): array
3456         {
3457                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3458                         "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3459                         0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3460                 ], ['order' => ['RAND()']]);
3461
3462                 if (DBA::isResult($contact)) {
3463                         return $contact;
3464                 }
3465
3466                 return [];
3467         }
3468 }