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