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