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