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