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