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