]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Merge pull request #9411 from tobiasd/20201011-de
[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 NOTHING  = 0;
132         const FOLLOWER = 1;
133         const SHARING  = 2;
134         const FRIEND   = 3;
135         /**
136          * @}
137          */
138
139         /**
140          * @param array $fields    Array of selected fields, empty for all
141          * @param array $condition Array of fields for condition
142          * @param array $params    Array of several parameters
143          * @return array
144          * @throws \Exception
145          */
146         public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
147         {
148                 return DBA::selectToArray('contact', $fields, $condition, $params);
149         }
150
151         /**
152          * @param array $fields    Array of selected fields, empty for all
153          * @param array $condition Array of fields for condition
154          * @param array $params    Array of several parameters
155          * @return array
156          * @throws \Exception
157          */
158         public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
159         {
160                 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
161
162                 return $contact;
163         }
164
165         /**
166          * Insert a row into the contact table
167          * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
168          *
169          * @param array        $fields              field array
170          * @param bool         $on_duplicate_update Do an update on a duplicate entry
171          *
172          * @return boolean was the insert successful?
173          * @throws \Exception
174          */
175         public static function insert(array $fields, bool $on_duplicate_update = false)
176         {
177                 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
178                 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
179                 if (!DBA::isResult($contact)) {
180                         // Shouldn't happen
181                         return $ret;
182                 }
183
184                 // Search for duplicated contacts and get rid of them
185                 self::removeDuplicates($contact['nurl'], $contact['uid']);
186
187                 return $ret;
188         }
189
190         /**
191          * @param integer $id     Contact ID
192          * @param array   $fields Array of selected fields, empty for all
193          * @return array|boolean Contact record if it exists, false otherwise
194          * @throws \Exception
195          */
196         public static function getById($id, $fields = [])
197         {
198                 return DBA::selectFirst('contact', $fields, ['id' => $id]);
199         }
200
201         /**
202          * Fetches a contact by a given url
203          *
204          * @param string  $url    profile url
205          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
206          * @param array   $fields Field list
207          * @param integer $uid    User ID of the contact
208          * @return array contact array
209          */
210         public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
211         {
212                 if ($update || is_null($update)) {
213                         $cid = self::getIdForURL($url, $uid, $update);
214                         if (empty($cid)) {
215                                 return [];
216                         }
217
218                         $contact = self::getById($cid, $fields);
219                         if (empty($contact)) {
220                                 return [];
221                         }
222                         return $contact;
223                 }
224
225                 // Add internal fields
226                 $removal = [];
227                 if (!empty($fields)) {
228                         foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
229                                 if (!in_array($internal, $fields)) {
230                                         $fields[] = $internal;
231                                         $removal[] = $internal;
232                                 }
233                         }
234                 }
235
236                 // We first try the nurl (http://server.tld/nick), most common case
237                 $options = ['order' => ['id']];
238                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
239
240                 // Then the addr (nick@server.tld)
241                 if (!DBA::isResult($contact)) {
242                         $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
243                 }
244
245                 // Then the alias (which could be anything)
246                 if (!DBA::isResult($contact)) {
247                         // The link could be provided as http although we stored it as https
248                         $ssl_url = str_replace('http://', 'https://', $url);
249                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
250                         $contact = DBA::selectFirst('contact', $fields, $condition, $options);
251                 }
252                 
253                 if (!DBA::isResult($contact)) {
254                         return [];
255                 }
256
257                 // Update the contact in the background if needed
258                 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
259                 if (($updated < DateTimeFormat::utc('now -7 days')) && 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      Update mode 
1251          * @param int    $parent      Item parent ID for the update mode
1252          * @return string posts in HTML
1253          * @throws \Exception
1254          */
1255         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0, $parent = 0)
1256         {
1257                 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent);
1258         }
1259
1260         /**
1261          * Returns posts from a given contact id
1262          *
1263          * @param int  $cid         Contact ID
1264          * @param bool $thread_mode
1265          * @param int  $update      Update mode 
1266          * @param int  $parent     Item parent ID for the update mode
1267          * @return string posts in HTML
1268          * @throws \Exception
1269          */
1270         public static function getPostsFromId($cid, $thread_mode = false, $update = 0, $parent = 0)
1271         {
1272                 $a = DI::app();
1273
1274                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1275                 if (!DBA::isResult($contact)) {
1276                         return '';
1277                 }
1278
1279                 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1280                         $sql = "`item`.`uid` IN (0, ?)";
1281                 } else {
1282                         $sql = "`item`.`uid` = ?";
1283                 }
1284
1285                 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1286
1287                 if ($thread_mode) {
1288                         $condition = ["(`$contact_field` = ? OR (`causer-id` = ? AND `post-type` = ?)) AND `gravity` = ? AND " . $sql,
1289                                 $cid, $cid, Item::PT_ANNOUNCEMENT, GRAVITY_PARENT, local_user()];
1290                 } else {
1291                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1292                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1293                 }
1294
1295                 if (!empty($parent)) {
1296                         $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1297                 } else {
1298                         $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1299                         if (!empty($last_received)) {
1300                                 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1301                         }
1302                 }
1303
1304                 if (DI::mode()->isMobile()) {
1305                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1306                                 DI::config()->get('system', 'itemspage_network_mobile'));
1307                 } else {
1308                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1309                                 DI::config()->get('system', 'itemspage_network'));
1310                 }
1311
1312                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1313
1314                 $params = ['order' => ['received' => true], 'group_by' => ['uri-id'],
1315                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1316
1317                 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1318                         $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1319                         $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1320                 } else {
1321                         $o = '';
1322                 }
1323
1324                 if ($thread_mode) {             
1325                         $r = Item::selectForUser(local_user(), ['uri', 'gravity', 'parent-uri'], $condition, $params);
1326                         $items = [];
1327                         while ($item = DBA::fetch($r)) {
1328                                 if ($item['gravity'] != GRAVITY_PARENT) {
1329                                         $item['uri'] = $item['parent-uri'];
1330                                 }
1331                                 unset($item['parent-uri']);
1332                                 unset($item['gravity']);
1333                                 
1334                                 $items[] = $item;
1335                         }
1336                         DBA::close($r);
1337
1338                         $o .= conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1339                 } else {
1340                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1341
1342                         $items = Item::inArray($r);
1343
1344                         $o .= conversation($a, $items, 'contact-posts', $update);
1345                 }
1346
1347                 if (!$update) {
1348                         if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1349                                 $o .= HTML::scrollLoader();
1350                         } else {
1351                                 $o .= $pager->renderMinimal(count($items));
1352                         }
1353                 }
1354
1355                 return $o;
1356         }
1357
1358         /**
1359          * Returns the account type name
1360          *
1361          * The function can be called with either the user or the contact array
1362          *
1363          * @param array $contact contact or user array
1364          * @return string
1365          */
1366         public static function getAccountType(array $contact)
1367         {
1368                 // There are several fields that indicate that the contact or user is a forum
1369                 // "page-flags" is a field in the user table,
1370                 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1371                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1372                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1373                         || (isset($contact['forum']) && intval($contact['forum']))
1374                         || (isset($contact['prv']) && intval($contact['prv']))
1375                         || (isset($contact['community']) && intval($contact['community']))
1376                 ) {
1377                         $type = self::TYPE_COMMUNITY;
1378                 } else {
1379                         $type = self::TYPE_PERSON;
1380                 }
1381
1382                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1383                 if (isset($contact["contact-type"])) {
1384                         $type = $contact["contact-type"];
1385                 }
1386
1387                 if (isset($contact["account-type"])) {
1388                         $type = $contact["account-type"];
1389                 }
1390
1391                 switch ($type) {
1392                         case self::TYPE_ORGANISATION:
1393                                 $account_type = DI::l10n()->t("Organisation");
1394                                 break;
1395
1396                         case self::TYPE_NEWS:
1397                                 $account_type = DI::l10n()->t('News');
1398                                 break;
1399
1400                         case self::TYPE_COMMUNITY:
1401                                 $account_type = DI::l10n()->t("Forum");
1402                                 break;
1403
1404                         default:
1405                                 $account_type = "";
1406                                 break;
1407                 }
1408
1409                 return $account_type;
1410         }
1411
1412         /**
1413          * Blocks a contact
1414          *
1415          * @param int $cid
1416          * @return bool
1417          * @throws \Exception
1418          */
1419         public static function block($cid, $reason = null)
1420         {
1421                 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1422
1423                 return $return;
1424         }
1425
1426         /**
1427          * Unblocks a contact
1428          *
1429          * @param int $cid
1430          * @return bool
1431          * @throws \Exception
1432          */
1433         public static function unblock($cid)
1434         {
1435                 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1436
1437                 return $return;
1438         }
1439
1440         /**
1441          * Ensure that cached avatar exist
1442          *
1443          * @param integer $cid
1444          */
1445         public static function checkAvatarCache(int $cid)
1446         {
1447                 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1448                 if (!DBA::isResult($contact)) {
1449                         return;
1450                 }
1451
1452                 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1453                         return;
1454                 }
1455
1456                 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1457
1458                 self::updateAvatar($cid, $contact['avatar'], true);
1459         }
1460
1461         /**
1462          * Return the photo path for a given contact array in the given size
1463          *
1464          * @param array $contact  contact array
1465          * @param string $field   Fieldname of the photo in the contact array
1466          * @param string $default Default path when no picture had been found
1467          * @param string $size    Size of the avatar picture
1468          * @param string $avatar  Avatar path that is displayed when no photo had been found
1469          * @return string photo path
1470          */
1471         private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1472         {
1473                 if (!empty($contact)) {
1474                         $contact = self::checkAvatarCacheByArray($contact);
1475                         if (!empty($contact[$field])) {
1476                                 $avatar = $contact[$field];
1477                         }
1478                 }
1479
1480                 if (empty($avatar)) {
1481                         return $default;
1482                 }
1483
1484                 if (Proxy::isLocalImage($avatar)) {
1485                         return $avatar;
1486                 } else {
1487                         return Proxy::proxifyUrl($avatar, false, $size);
1488                 }
1489         }
1490
1491         /**
1492          * Return the photo path for a given contact array
1493          *
1494          * @param array $contact Contact array
1495          * @param string $avatar  Avatar path that is displayed when no photo had been found
1496          * @return string photo path
1497          */
1498         public static function getPhoto(array $contact, string $avatar = '')
1499         {
1500                 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO, Proxy::SIZE_SMALL, $avatar);
1501         }
1502
1503         /**
1504          * Return the photo path (thumb size) for a given contact array
1505          *
1506          * @param array $contact Contact array
1507          * @param string $avatar  Avatar path that is displayed when no photo had been found
1508          * @return string photo path
1509          */
1510         public static function getThumb(array $contact, string $avatar = '')
1511         {
1512                 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . self::DEFAULT_AVATAR_THUMB, Proxy::SIZE_THUMB, $avatar);
1513         }
1514
1515         /**
1516          * Return the photo path (micro size) for a given contact array
1517          *
1518          * @param array $contact Contact array
1519          * @param string $avatar  Avatar path that is displayed when no photo had been found
1520          * @return string photo path
1521          */
1522         public static function getMicro(array $contact, string $avatar = '')
1523         {
1524                 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . self::DEFAULT_AVATAR_MICRO, Proxy::SIZE_MICRO, $avatar);
1525         }
1526
1527         /**
1528          * Check the given contact array for avatar cache fields
1529          *
1530          * @param array $contact
1531          * @return array contact array with avatar cache fields
1532          */
1533         private static function checkAvatarCacheByArray(array $contact)
1534         {
1535                 $update = false;
1536                 $contact_fields = [];
1537                 $fields = ['photo', 'thumb', 'micro'];
1538                 foreach ($fields as $field) {
1539                         if (isset($contact[$field])) {
1540                                 $contact_fields[] = $field;
1541                         }
1542                         if (isset($contact[$field]) && empty($contact[$field])) {
1543                                 $update = true;
1544                         }
1545                 }
1546
1547                 if (!$update) {
1548                         return $contact;
1549                 }
1550
1551                 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1552                         self::updateAvatar($contact['id'], $contact['avatar'], true);
1553
1554                         $new_contact = self::getById($contact['id'], $contact_fields);
1555                         if (DBA::isResult($new_contact)) {
1556                                 // We only update the cache fields
1557                                 $contact = array_merge($contact, $new_contact);
1558                         }
1559                 }
1560
1561                 /// add the default avatars if the fields aren't filled
1562                 if (isset($contact['photo']) && empty($contact['photo'])) {
1563                         $contact['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
1564                 }
1565                 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1566                         $contact['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
1567                 }
1568                 if (isset($contact['micro']) && empty($contact['micro'])) {
1569                         $contact['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
1570                 }
1571
1572                 return $contact;
1573         }
1574
1575         /**
1576          * Updates the avatar links in a contact only if needed
1577          *
1578          * @param int    $cid          Contact id
1579          * @param string $avatar       Link to avatar picture
1580          * @param bool   $force        force picture update
1581          * @param bool   $create_cache Enforces the creation of cached avatar fields
1582          *
1583          * @return void
1584          * @throws HTTPException\InternalServerErrorException
1585          * @throws HTTPException\NotFoundException
1586          * @throws \ImagickException
1587          */
1588         public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1589         {
1590                 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl', 'url', 'network'], ['id' => $cid, 'self' => false]);
1591                 if (!DBA::isResult($contact)) {
1592                         return;
1593                 }
1594
1595                 $uid = $contact['uid'];
1596
1597                 // Only update the cached photo links of public contacts when they already are cached
1598                 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1599                         if ($contact['avatar'] != $avatar) {
1600                                 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1601                                 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1602                         }
1603                         return;
1604                 }
1605
1606                 // User contacts use are updated through the public contacts
1607                 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1608                         $pcid = self::getIdForURL($contact['url'], false);
1609                         if (!empty($pcid)) {
1610                                 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1611                                 self::updateAvatar($pcid, $avatar, $force, true);
1612                                 return;
1613                         }
1614                 }
1615                 
1616                 // Replace cached avatar pictures from the default avatar with the default avatars in different sizes
1617                 if (strpos($avatar, self::DEFAULT_AVATAR_PHOTO)) {
1618                         $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1619                                 'photo' => DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO,
1620                                 'thumb' => DI::baseUrl() . self::DEFAULT_AVATAR_THUMB,
1621                                 'micro' => DI::baseUrl() . self::DEFAULT_AVATAR_MICRO];
1622                         Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1623                 }
1624
1625                 // Use the data from the self account
1626                 if (empty($fields)) {
1627                         $local_uid = User::getIdForURL($contact['url']);
1628                         if (!empty($local_uid)) {
1629                                 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1630                                 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1631                         }
1632                 }
1633
1634                 if (empty($fields)) {
1635                         $update = ($contact['avatar'] != $avatar) || $force;
1636
1637                         if (!$update) {
1638                                 $data = [
1639                                         $contact['photo'] ?? '',
1640                                         $contact['thumb'] ?? '',
1641                                         $contact['micro'] ?? '',
1642                                 ];
1643                 
1644                                 foreach ($data as $image_uri) {
1645                                         $image_rid = Photo::ridFromURI($image_uri);
1646                                         if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1647                                                 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1648                                                 $update = true;
1649                                         }
1650                                 }
1651                         }
1652
1653                         if ($update) {
1654                                 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1655                                 if ($photos) {
1656                                         $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1657                                         $update = !empty($fields);
1658                                         Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1659                                 } else {
1660                                         $update = false;
1661                                 }
1662                         }
1663                 } else {
1664                         $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1665                 }
1666
1667                 if (!$update) {
1668                         return;
1669                 }
1670
1671                 $cids = [];
1672                 $uids = [];
1673                 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1674                         // Collect all user contacts of the given public contact
1675                         $personal_contacts = DBA::select('contact', ['id', 'uid'],
1676                                 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1677                         while ($personal_contact = DBA::fetch($personal_contacts)) {
1678                                 $cids[] = $personal_contact['id'];
1679                                 $uids[] = $personal_contact['uid'];
1680                         }
1681                         DBA::close($personal_contacts);
1682
1683                         if (!empty($cids)) {
1684                                 // Delete possibly existing cached user contact avatars
1685                                 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1686                         }
1687                 }
1688
1689                 $cids[] = $cid;
1690                 $uids[] = $uid;
1691                 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1692                 DBA::update('contact', $fields, ['id' => $cids]);
1693         }
1694
1695         /**
1696          * Helper function for "updateFromProbe". Updates personal and public contact
1697          *
1698          * @param integer $id      contact id
1699          * @param integer $uid     user id
1700          * @param string  $url     The profile URL of the contact
1701          * @param array   $fields  The fields that are updated
1702          *
1703          * @throws \Exception
1704          */
1705         private static function updateContact($id, $uid, $url, array $fields)
1706         {
1707                 if (!DBA::update('contact', $fields, ['id' => $id])) {
1708                         Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1709                         return;
1710                 }
1711
1712                 // Search for duplicated contacts and get rid of them
1713                 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1714                         return;
1715                 }
1716
1717                 // Archive or unarchive the contact. We only need to do this for the public contact.
1718                 // The archive/unarchive function will update the personal contacts by themselves.
1719                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1720                 if (!DBA::isResult($contact)) {
1721                         Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1722                         return;
1723                 }
1724
1725                 if (!empty($fields['success_update'])) {
1726                         self::unmarkForArchival($contact);
1727                 } elseif (!empty($fields['failure_update'])) {
1728                         self::markForArchival($contact);
1729                 }
1730
1731                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1732
1733                 // These contacts are sharing with us, we don't poll them.
1734                 // This means that we don't set the update fields in "OnePoll.php".
1735                 $condition['rel'] = self::SHARING;
1736                 DBA::update('contact', $fields, $condition);
1737
1738                 unset($fields['last-update']);
1739                 unset($fields['success_update']);
1740                 unset($fields['failure_update']);
1741
1742                 if (empty($fields)) {
1743                         return;
1744                 }
1745
1746                 // We are polling these contacts, so we mustn't set the update fields here.
1747                 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1748                 DBA::update('contact', $fields, $condition);
1749         }
1750
1751         /**
1752          * Remove duplicated contacts
1753          *
1754          * @param string  $nurl  Normalised contact url
1755          * @param integer $uid   User id
1756          * @return boolean
1757          * @throws \Exception
1758          */
1759         public static function removeDuplicates(string $nurl, int $uid)
1760         {
1761                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1762                 $count = DBA::count('contact', $condition);
1763                 if ($count <= 1) {
1764                         return false;
1765                 }
1766
1767                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1768                 if (!DBA::isResult($first_contact)) {
1769                         // Shouldn't happen - so we handle it
1770                         return false;
1771                 }
1772
1773                 $first = $first_contact['id'];
1774                 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1775                 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1776                         // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1777                         Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1778                         return false;
1779                 }
1780
1781                 // Find all duplicates
1782                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1783                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1784                 while ($duplicate = DBA::fetch($duplicates)) {
1785                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1786                                 continue;
1787                         }
1788
1789                         Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1790                 }
1791                 DBA::close($duplicates);
1792                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1793                 return true;
1794         }
1795
1796         /**
1797          * @param integer $id      contact id
1798          * @param string  $network Optional network we are probing for
1799          * @return boolean
1800          * @throws HTTPException\InternalServerErrorException
1801          * @throws \ImagickException
1802          */
1803         public static function updateFromProbe(int $id, string $network = '')
1804         {
1805                 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
1806                 if (!DBA::isResult($contact)) {
1807                         return false;
1808                 }
1809
1810                 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
1811                 return self::updateFromProbeArray($id, $ret);
1812         }
1813
1814         /**
1815          * @param integer $id      contact id
1816          * @param array   $ret     Probed data
1817          * @return boolean
1818          * @throws HTTPException\InternalServerErrorException
1819          * @throws \ImagickException
1820          */
1821         private static function updateFromProbeArray(int $id, array $ret)
1822         {
1823                 /*
1824                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1825                   This will reliably kill your communication with old Friendica contacts.
1826                  */
1827
1828                 // These fields aren't updated by this routine:
1829                 // 'xmpp', 'sensitive'
1830
1831                 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe', 'manually-approve',
1832                         'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1833                         'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item'];
1834                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1835                 if (!DBA::isResult($contact)) {
1836                         return false;
1837                 }
1838
1839                 $uid = $contact['uid'];
1840                 unset($contact['uid']);
1841
1842                 $pubkey = $contact['pubkey'];
1843                 unset($contact['pubkey']);
1844
1845                 $contact['photo'] = $contact['avatar'];
1846                 unset($contact['avatar']);
1847
1848                 $updated = DateTimeFormat::utcNow();
1849
1850                 // We must not try to update relay contacts via probe. They are no real contacts.
1851                 // We check after the probing to be able to correct falsely detected contact types.
1852                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1853                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1854                         self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1855                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1856                         return true;
1857                 }
1858
1859                 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1860                 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1861                         if ($uid == 0) {
1862                                 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1863                         }
1864                         return false;
1865                 }
1866
1867                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1868                         $ret['unsearchable'] = $ret['hide'];
1869                 }
1870
1871                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1872                         $ret['forum'] = false;
1873                         $ret['prv'] = false;
1874                         $ret['contact-type'] = $ret['account-type'];
1875                         if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
1876                                 $ret['forum'] = (bool)!$ret['manually-approve'];
1877                                 $ret['prv'] = (bool)!$ret['forum'];
1878                         }
1879                 }
1880
1881                 $new_pubkey = $ret['pubkey'] ?? '';
1882
1883                 if ($uid == 0) {
1884                         $ret['last-item'] = Probe::getLastUpdate($ret);
1885                         Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
1886                 }
1887
1888                 $update = false;
1889
1890                 // make sure to not overwrite existing values with blank entries except some technical fields
1891                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1892                 foreach ($ret as $key => $val) {
1893                         if (!array_key_exists($key, $contact)) {
1894                                 unset($ret[$key]);
1895                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1896                                 $ret[$key] = $contact[$key];
1897                         } elseif ($ret[$key] != $contact[$key]) {
1898                                 $update = true;
1899                         }
1900                 }
1901
1902                 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
1903                         $update = true;
1904                 } else {
1905                         unset($ret['last-item']);
1906                 }
1907
1908                 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1909                         self::updateAvatar($id, $ret['photo'], $update);
1910                 }
1911
1912                 if (!$update) {
1913                         self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1914
1915                         if (Contact\Relation::isDiscoverable($ret['url'])) {
1916                                 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1917                         }
1918         
1919                         // Update the public contact
1920                         if ($uid != 0) {
1921                                 $contact = self::getByURL($ret['url'], false, ['id']);
1922                                 if (!empty($contact['id'])) {
1923                                         self::updateFromProbeArray($contact['id'], $ret);
1924                                 }
1925                         }
1926
1927                         return true;
1928                 }
1929
1930                 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1931                 $ret['updated'] = $updated;
1932
1933                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1934                 if (empty($pubkey) && !empty($new_pubkey)) {
1935                         $ret['pubkey'] = $new_pubkey;
1936                 }
1937
1938                 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
1939                         $ret['uri-date'] = DateTimeFormat::utcNow();
1940                 }
1941
1942                 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
1943                         $ret['name-date'] = $updated;
1944                 }
1945
1946                 if ($uid == 0) {
1947                         $ret['last-update'] = $updated;
1948                         $ret['success_update'] = $updated;
1949                         $ret['failed'] = false;
1950                 }
1951
1952                 unset($ret['photo']);
1953
1954                 self::updateContact($id, $uid, $ret['url'], $ret);
1955
1956                 if (Contact\Relation::isDiscoverable($ret['url'])) {
1957                         Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1958                 }
1959
1960                 return true;
1961         }
1962
1963         /**
1964          * @param integer $url contact url
1965          * @return integer Contact id
1966          * @throws HTTPException\InternalServerErrorException
1967          * @throws \ImagickException
1968          */
1969         public static function updateFromProbeByURL($url)
1970         {
1971                 $id = self::getIdForURL($url);
1972
1973                 if (empty($id)) {
1974                         return $id;
1975                 }
1976
1977                 self::updateFromProbe($id);
1978
1979                 return $id;
1980         }
1981
1982         /**
1983          * Detects if a given contact array belongs to a legacy DFRN connection
1984          *
1985          * @param array $contact
1986          * @return boolean
1987          */
1988         public static function isLegacyDFRNContact($contact)
1989         {
1990                 // Newer Friendica contacts are connected via AP, then these fields aren't set
1991                 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1992         }
1993
1994         /**
1995          * Detects the communication protocol for a given contact url.
1996          * This is used to detect Friendica contacts that we can communicate via AP.
1997          *
1998          * @param string $url contact url
1999          * @param string $network Network of that contact
2000          * @return string with protocol
2001          */
2002         public static function getProtocol($url, $network)
2003         {
2004                 if ($network != Protocol::DFRN) {
2005                         return $network;
2006                 }
2007
2008                 $apcontact = APContact::getByURL($url);
2009                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2010                         return Protocol::ACTIVITYPUB;
2011                 } else {
2012                         return $network;
2013                 }
2014         }
2015
2016         /**
2017          * Takes a $uid and a url/handle and adds a new contact
2018          *
2019          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2020          * dfrn_request page.
2021          *
2022          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2023          *
2024          * Returns an array
2025          * $return['success'] boolean true if successful
2026          * $return['message'] error text if success is false.
2027          *
2028          * Takes a $uid and a url/handle and adds a new contact
2029          *
2030          * @param array  $user        The user the contact should be created for
2031          * @param string $url         The profile URL of the contact
2032          * @param bool   $interactive
2033          * @param string $network
2034          * @return array
2035          * @throws HTTPException\InternalServerErrorException
2036          * @throws HTTPException\NotFoundException
2037          * @throws \ImagickException
2038          */
2039         public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2040         {
2041                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2042
2043                 // remove ajax junk, e.g. Twitter
2044                 $url = str_replace('/#!/', '/', $url);
2045
2046                 if (!Network::isUrlAllowed($url)) {
2047                         $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2048                         return $result;
2049                 }
2050
2051                 if (Network::isUrlBlocked($url)) {
2052                         $result['message'] = DI::l10n()->t('Blocked domain');
2053                         return $result;
2054                 }
2055
2056                 if (!$url) {
2057                         $result['message'] = DI::l10n()->t('Connect URL missing.');
2058                         return $result;
2059                 }
2060
2061                 $arr = ['url' => $url, 'contact' => []];
2062
2063                 Hook::callAll('follow', $arr);
2064
2065                 if (empty($arr)) {
2066                         $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2067                         return $result;
2068                 }
2069
2070                 if (!empty($arr['contact']['name'])) {
2071                         $ret = $arr['contact'];
2072                 } else {
2073                         $ret = Probe::uri($url, $network, $user['uid']);
2074                 }
2075
2076                 if (($network != '') && ($ret['network'] != $network)) {
2077                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2078                         return $result;
2079                 }
2080
2081                 // check if we already have a contact
2082                 // the poll url is more reliable than the profile url, as we may have
2083                 // indirect links or webfinger links
2084
2085                 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2086                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2087                 if (!DBA::isResult($contact)) {
2088                         $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2089                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2090                 }
2091
2092                 $protocol = self::getProtocol($ret['url'], $ret['network']);
2093
2094                 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2095                         if ($interactive) {
2096                                 if (strlen(DI::baseUrl()->getUrlPath())) {
2097                                         $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2098                                 } else {
2099                                         $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2100                                 }
2101
2102                                 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2103
2104                                 // NOTREACHED
2105                         }
2106                 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2107                         $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2108                         $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2109                         return $result;
2110                 }
2111
2112                 // This extra param just confuses things, remove it
2113                 if ($protocol === Protocol::DIASPORA) {
2114                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2115                 }
2116
2117                 // do we have enough information?
2118                 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2119                         $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2120                         if (empty($ret['poll'])) {
2121                                 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2122                         }
2123                         if (empty($ret['name'])) {
2124                                 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2125                         }
2126                         if (empty($ret['url'])) {
2127                                 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2128                         }
2129                         if (strpos($ret['url'], '@') !== false) {
2130                                 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2131                                 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2132                         }
2133                         return $result;
2134                 }
2135
2136                 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2137                         $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2138                         $ret['notify'] = '';
2139                 }
2140
2141                 if (!$ret['notify']) {
2142                         $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2143                 }
2144
2145                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2146
2147                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2148
2149                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2150
2151                 $pending = false;
2152                 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2153                         $pending = (bool)$ret['manually-approve'];
2154                 }
2155
2156                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2157                         $writeable = 1;
2158                 }
2159
2160                 if (DBA::isResult($contact)) {
2161                         // update contact
2162                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2163
2164                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2165                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2166                 } else {
2167                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2168
2169                         // create contact record
2170                         self::insert([
2171                                 'uid'     => $user['uid'],
2172                                 'created' => DateTimeFormat::utcNow(),
2173                                 'url'     => $ret['url'],
2174                                 'nurl'    => Strings::normaliseLink($ret['url']),
2175                                 'addr'    => $ret['addr'],
2176                                 'alias'   => $ret['alias'],
2177                                 'batch'   => $ret['batch'],
2178                                 'notify'  => $ret['notify'],
2179                                 'poll'    => $ret['poll'],
2180                                 'poco'    => $ret['poco'],
2181                                 'name'    => $ret['name'],
2182                                 'nick'    => $ret['nick'],
2183                                 'network' => $ret['network'],
2184                                 'baseurl' => $ret['baseurl'],
2185                                 'gsid'    => $ret['gsid'] ?? null,
2186                                 'protocol' => $protocol,
2187                                 'pubkey'  => $ret['pubkey'],
2188                                 'rel'     => $new_relation,
2189                                 'priority'=> $ret['priority'],
2190                                 'writable'=> $writeable,
2191                                 'hidden'  => $hidden,
2192                                 'blocked' => 0,
2193                                 'readonly'=> 0,
2194                                 'pending' => $pending,
2195                                 'subhub'  => $subhub
2196                         ]);
2197                 }
2198
2199                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2200                 if (!DBA::isResult($contact)) {
2201                         $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2202                         return $result;
2203                 }
2204
2205                 $contact_id = $contact['id'];
2206                 $result['cid'] = $contact_id;
2207
2208                 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2209
2210                 // Update the avatar
2211                 self::updateAvatar($contact_id, $ret['photo']);
2212
2213                 // pull feed and consume it, which should subscribe to the hub.
2214
2215                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2216
2217                 $owner = User::getOwnerDataById($user['uid']);
2218
2219                 if (DBA::isResult($owner)) {
2220                         if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2221                                 // create a follow slap
2222                                 $item = [];
2223                                 $item['verb'] = Activity::FOLLOW;
2224                                 $item['gravity'] = GRAVITY_ACTIVITY;
2225                                 $item['follow'] = $contact["url"];
2226                                 $item['body'] = '';
2227                                 $item['title'] = '';
2228                                 $item['guid'] = '';
2229                                 $item['uri-id'] = 0;
2230                                 $item['attach'] = '';
2231
2232                                 $slap = OStatus::salmon($item, $owner);
2233
2234                                 if (!empty($contact['notify'])) {
2235                                         Salmon::slapper($owner, $contact['notify'], $slap);
2236                                 }
2237                         } elseif ($protocol == Protocol::DIASPORA) {
2238                                 $ret = Diaspora::sendShare($owner, $contact);
2239                                 Logger::log('share returns: ' . $ret);
2240                         } elseif ($protocol == Protocol::ACTIVITYPUB) {
2241                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2242                                 if (empty($activity_id)) {
2243                                         // This really should never happen
2244                                         return false;
2245                                 }
2246
2247                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2248                                 Logger::log('Follow returns: ' . $ret);
2249                         }
2250                 }
2251
2252                 $result['success'] = true;
2253                 return $result;
2254         }
2255
2256         /**
2257          * Updated contact's SSL policy
2258          *
2259          * @param array  $contact    Contact array
2260          * @param string $new_policy New policy, valid: self,full
2261          *
2262          * @return array Contact array with updated values
2263          * @throws \Exception
2264          */
2265         public static function updateSslPolicy(array $contact, $new_policy)
2266         {
2267                 $ssl_changed = false;
2268                 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2269                         $ssl_changed = true;
2270                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
2271                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
2272                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
2273                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
2274                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
2275                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
2276                 }
2277
2278                 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2279                         $ssl_changed = true;
2280                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
2281                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
2282                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
2283                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
2284                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
2285                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
2286                 }
2287
2288                 if ($ssl_changed) {
2289                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2290                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
2291                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2292                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2293                 }
2294
2295                 return $contact;
2296         }
2297
2298         /**
2299          * @param array  $importer Owner (local user) data
2300          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2301          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2302          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2303          * @param string $note     Introduction additional message
2304          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2305          * @throws HTTPException\InternalServerErrorException
2306          * @throws \ImagickException
2307          */
2308         public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2309         {
2310                 // Should always be set
2311                 if (empty($datarray['author-id'])) {
2312                         return false;
2313                 }
2314
2315                 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2316                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2317                 if (!DBA::isResult($pub_contact)) {
2318                         // Should never happen
2319                         return false;
2320                 }
2321
2322                 // Contact is blocked at node-level
2323                 if (self::isBlocked($datarray['author-id'])) {
2324                         return false;
2325                 }
2326
2327                 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2328                 $name = $pub_contact['name'];
2329                 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2330                 $nick = $pub_contact['nick'];
2331                 $network = $pub_contact['network'];
2332
2333                 // Ensure that we don't create a new contact when there already is one
2334                 $cid = self::getIdForURL($url, $importer['uid']);
2335                 if (!empty($cid)) {
2336                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2337                 }
2338
2339                 if (!empty($contact)) {
2340                         if (!empty($contact['pending'])) {
2341                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2342                                 return null;
2343                         }
2344
2345                         // Contact is blocked at user-level
2346                         if (!empty($contact['id']) && !empty($importer['id']) &&
2347                                 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2348                                 return false;
2349                         }
2350
2351                         // Make sure that the existing contact isn't archived
2352                         self::unmarkForArchival($contact);
2353
2354                         if (($contact['rel'] == self::SHARING)
2355                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2356                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2357                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2358                         }
2359
2360                         // Ensure to always have the correct network type, independent from the connection request method
2361                         self::updateFromProbe($contact['id']);
2362
2363                         return true;
2364                 } else {
2365                         // send email notification to owner?
2366                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2367                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2368                                 return null;
2369                         }
2370
2371                         // create contact record
2372                         DBA::insert('contact', [
2373                                 'uid'      => $importer['uid'],
2374                                 'created'  => DateTimeFormat::utcNow(),
2375                                 'url'      => $url,
2376                                 'nurl'     => Strings::normaliseLink($url),
2377                                 'name'     => $name,
2378                                 'nick'     => $nick,
2379                                 'network'  => $network,
2380                                 'rel'      => self::FOLLOWER,
2381                                 'blocked'  => 0,
2382                                 'readonly' => 0,
2383                                 'pending'  => 1,
2384                                 'writable' => 1,
2385                         ]);
2386
2387                         $contact_id = DBA::lastInsertId();
2388
2389                         // Ensure to always have the correct network type, independent from the connection request method
2390                         self::updateFromProbe($contact_id);
2391
2392                         self::updateAvatar($contact_id, $photo, true);
2393
2394                         $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2395
2396                         /// @TODO Encapsulate this into a function/method
2397                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2398                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2399                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2400                                 // create notification
2401                                 $hash = Strings::getRandomHex();
2402
2403                                 if (is_array($contact_record)) {
2404                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2405                                                                 'blocked' => false, 'knowyou' => false, 'note' => $note,
2406                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2407                                 }
2408
2409                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2410
2411                                 if (($user['notify-flags'] & Type::INTRO) &&
2412                                         in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2413
2414                                         notification([
2415                                                 'type'         => Type::INTRO,
2416                                                 'notify_flags' => $user['notify-flags'],
2417                                                 'language'     => $user['language'],
2418                                                 'to_name'      => $user['username'],
2419                                                 'to_email'     => $user['email'],
2420                                                 'uid'          => $user['uid'],
2421                                                 'link'         => DI::baseUrl() . '/notifications/intros',
2422                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2423                                                 'source_link'  => $contact_record['url'],
2424                                                 'source_photo' => $contact_record['photo'],
2425                                                 'verb'         => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2426                                                 'otype'        => 'intro'
2427                                         ]);
2428                                 }
2429                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2430                                 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2431                                         self::createFromProbe($importer, $url, false, $network);
2432                                 }
2433
2434                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2435                                 $fields = ['pending' => false];
2436                                 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2437                                         $fields['rel'] = Contact::FRIEND;
2438                                 }
2439
2440                                 DBA::update('contact', $fields, $condition);
2441
2442                                 return true;
2443                         }
2444                 }
2445
2446                 return null;
2447         }
2448
2449         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2450         {
2451                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2452                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2453                 } else {
2454                         Contact::remove($contact['id']);
2455                 }
2456         }
2457
2458         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2459         {
2460                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2461                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2462                 } else {
2463                         Contact::remove($contact['id']);
2464                 }
2465         }
2466
2467         /**
2468          * Create a birthday event.
2469          *
2470          * Update the year and the birthday.
2471          */
2472         public static function updateBirthdays()
2473         {
2474                 $condition = [
2475                         '`bd` != ""
2476                         AND `bd` > "0001-01-01"
2477                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2478                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2479                         AND NOT `contact`.`pending`
2480                         AND NOT `contact`.`hidden`
2481                         AND NOT `contact`.`blocked`
2482                         AND NOT `contact`.`archive`
2483                         AND NOT `contact`.`deleted`',
2484                         Contact::SHARING,
2485                         Contact::FRIEND
2486                 ];
2487
2488                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2489
2490                 while ($contact = DBA::fetch($contacts)) {
2491                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2492
2493                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2494
2495                         if (Event::createBirthday($contact, $nextbd)) {
2496                                 // update bdyear
2497                                 DBA::update(
2498                                         'contact',
2499                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2500                                         ['id' => $contact['id']]
2501                                 );
2502                         }
2503                 }
2504                 DBA::close($contacts);
2505         }
2506
2507         /**
2508          * Remove the unavailable contact ids from the provided list
2509          *
2510          * @param array $contact_ids Contact id list
2511          * @return array
2512          * @throws \Exception
2513          */
2514         public static function pruneUnavailable(array $contact_ids)
2515         {
2516                 if (empty($contact_ids)) {
2517                         return [];
2518                 }
2519
2520                 $contacts = Contact::selectToArray(['id'], [
2521                         'id'      => $contact_ids,
2522                         'blocked' => false,
2523                         'pending' => false,
2524                         'archive' => false,
2525                 ]);
2526
2527                 return array_column($contacts, 'id');
2528         }
2529
2530         /**
2531          * Returns a magic link to authenticate remote visitors
2532          *
2533          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2534          *
2535          * @param string $contact_url The address of the target contact profile
2536          * @param string $url         An url that we will be redirected to after the authentication
2537          *
2538          * @return string with "redir" link
2539          * @throws HTTPException\InternalServerErrorException
2540          * @throws \ImagickException
2541          */
2542         public static function magicLink($contact_url, $url = '')
2543         {
2544                 if (!Session::isAuthenticated()) {
2545                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2546                 }
2547
2548                 $contact = self::getByURL($contact_url, false);
2549                 if (empty($contact)) {
2550                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2551                 }
2552
2553                 // Prevents endless loop in case only a non-public contact exists for the contact URL
2554                 unset($contact['uid']);
2555
2556                 return self::magicLinkByContact($contact, $url ?: $contact_url);
2557         }
2558
2559         /**
2560          * Returns a magic link to authenticate remote visitors
2561          *
2562          * @param integer $cid The contact id of the target contact profile
2563          * @param string  $url An url that we will be redirected to after the authentication
2564          *
2565          * @return string with "redir" link
2566          * @throws HTTPException\InternalServerErrorException
2567          * @throws \ImagickException
2568          */
2569         public static function magicLinkbyId($cid, $url = '')
2570         {
2571                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2572
2573                 return self::magicLinkByContact($contact, $url);
2574         }
2575
2576         /**
2577          * Returns a magic link to authenticate remote visitors
2578          *
2579          * @param array  $contact The contact array with "uid", "network" and "url"
2580          * @param string $url     An url that we will be redirected to after the authentication
2581          *
2582          * @return string with "redir" link
2583          * @throws HTTPException\InternalServerErrorException
2584          * @throws \ImagickException
2585          */
2586         public static function magicLinkByContact($contact, $url = '')
2587         {
2588                 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2589
2590                 if (!Session::isAuthenticated()) {
2591                         return $destination;
2592                 }
2593
2594                 // Only redirections to the same host do make sense
2595                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2596                         return $url;
2597                 }
2598
2599                 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
2600                         return 'contact/' . $contact['id'] . '/conversations';
2601                 }
2602
2603                 if ($contact['network'] != Protocol::DFRN) {
2604                         return $destination;
2605                 }
2606
2607                 if (!empty($contact['uid'])) {
2608                         return self::magicLink($contact['url'], $url);
2609                 }
2610
2611                 if (empty($contact['id'])) {
2612                         return $destination;
2613                 }
2614
2615                 $redirect = 'redir/' . $contact['id'];
2616
2617                 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2618                         $redirect .= '?url=' . $url;
2619                 }
2620
2621                 return $redirect;
2622         }
2623
2624         /**
2625          * Is the contact a forum?
2626          *
2627          * @param integer $contactid ID of the contact
2628          *
2629          * @return boolean "true" if it is a forum
2630          */
2631         public static function isForum($contactid)
2632         {
2633                 $fields = ['forum', 'prv'];
2634                 $condition = ['id' => $contactid];
2635                 $contact = DBA::selectFirst('contact', $fields, $condition);
2636                 if (!DBA::isResult($contact)) {
2637                         return false;
2638                 }
2639
2640                 // Is it a forum?
2641                 return ($contact['forum'] || $contact['prv']);
2642         }
2643
2644         /**
2645          * Can the remote contact receive private messages?
2646          *
2647          * @param array $contact
2648          * @return bool
2649          */
2650         public static function canReceivePrivateMessages(array $contact)
2651         {
2652                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2653                 $self = $contact['self'] ?? false;
2654
2655                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2656         }
2657
2658         /**
2659          * Search contact table by nick or name
2660          *
2661          * @param string $search Name or nick
2662          * @param string $mode   Search mode (e.g. "community")
2663          *
2664          * @return array with search results
2665          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2666          */
2667         public static function searchByName($search, $mode = '')
2668         {
2669                 if (empty($search)) {
2670                         return [];
2671                 }
2672
2673                 // check supported networks
2674                 if (DI::config()->get('system', 'diaspora_enabled')) {
2675                         $diaspora = Protocol::DIASPORA;
2676                 } else {
2677                         $diaspora = Protocol::DFRN;
2678                 }
2679
2680                 if (!DI::config()->get('system', 'ostatus_disabled')) {
2681                         $ostatus = Protocol::OSTATUS;
2682                 } else {
2683                         $ostatus = Protocol::DFRN;
2684                 }
2685
2686                 // check if we search only communities or every contact
2687                 if ($mode === 'community') {
2688                         $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2689                 } else {
2690                         $extra_sql = '';
2691                 }
2692
2693                 $search .= '%';
2694
2695                 $results = DBA::p("SELECT * FROM `contact`
2696                         WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2697                                 NOT `failed` AND `uid` = ? AND
2698                                 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2699                                 ORDER BY `nurl` DESC LIMIT 1000",
2700                         Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2701                 );
2702
2703                 $contacts = DBA::toArray($results);
2704                 return $contacts;
2705         }
2706
2707         /**
2708          * Add public contacts from an array
2709          *
2710          * @param array $urls
2711          * @return array result "count", "added" and "updated"
2712          */
2713         public static function addByUrls(array $urls)
2714         {
2715                 $added = 0;
2716                 $updated = 0;
2717                 $unchanged = 0;
2718                 $count = 0;
2719
2720                 foreach ($urls as $url) {
2721                         $contact = Contact::getByURL($url, false, ['id', 'updated']);
2722                         if (empty($contact['id'])) {
2723                                 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2724                                 ++$added;
2725                         } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
2726                                 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2727                                 ++$updated;
2728                         } else {
2729                                 ++$unchanged;
2730                         }
2731                         ++$count;
2732                 }
2733
2734                 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
2735         }
2736
2737         /**
2738          * Returns a random, global contact of the current node
2739          *
2740          * @return string The profile URL
2741          * @throws Exception
2742          */
2743         public static function getRandomUrl()
2744         {
2745                 $r = DBA::selectFirst('contact', ['url'], [
2746                         "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2747                         0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2748                 ], ['order' => ['RAND()']]);
2749
2750                 if (DBA::isResult($r)) {
2751                         return $r['url'];
2752                 }
2753
2754                 return '';
2755         }
2756 }