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