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