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