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