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