]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Check fpr duplicated contacts upon inserting them
[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        $param               parameter 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($param, $on_duplicate_update = false)
150         {
151                 $ret = DBA::insert('contact', $param, $on_duplicate_update);
152                 $contact = DBA::selectFirst('contact', ['nurl', 'uid', 'id'], ['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::handleDuplicates($contact['nurl'], $contact['uid'], $contact['id']);
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',
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'];
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'];
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
731                 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
732                 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
733                 $fields['nurl'] = Strings::normaliseLink($fields['url']);
734                 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
735                 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
736                 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
737                 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
738                 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
739                 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
740
741                 $update = false;
742
743                 foreach ($fields as $field => $content) {
744                         if ($self[$field] != $content) {
745                                 $update = true;
746                         }
747                 }
748
749                 if ($update) {
750                         if ($fields['name'] != $self['name']) {
751                                 $fields['name-date'] = DateTimeFormat::utcNow();
752                         }
753                         $fields['updated'] = DateTimeFormat::utcNow();
754                         DBA::update('contact', $fields, ['id' => $self['id']]);
755
756                         // Update the public contact as well
757                         DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
758
759                         // Update the profile
760                         $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
761                                 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
762                         DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
763                 }
764         }
765
766         /**
767          * @brief Marks a contact for removal
768          *
769          * @param int $id contact id
770          * @return null
771          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
772          */
773         public static function remove($id)
774         {
775                 // We want just to make sure that we don't delete our "self" contact
776                 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
777                 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
778                         return;
779                 }
780
781                 // Archive the contact
782                 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
783
784                 // Delete it in the background
785                 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
786         }
787
788         /**
789          * @brief Sends an unfriend message. Does not remove the contact
790          *
791          * @param array   $user     User unfriending
792          * @param array   $contact  Contact unfriended
793          * @param boolean $dissolve Remove the contact on the remote side
794          * @return void
795          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
796          * @throws \ImagickException
797          */
798         public static function terminateFriendship(array $user, array $contact, $dissolve = false)
799         {
800                 if (empty($contact['network'])) {
801                         return;
802                 }
803
804                 $protocol = $contact['network'];
805                 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
806                         $protocol = Protocol::ACTIVITYPUB;
807                 }
808
809                 if (($protocol == Protocol::DFRN) && $dissolve) {
810                         DFRN::deliver($user, $contact, 'placeholder', true);
811                 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
812                         // create an unfollow slap
813                         $item = [];
814                         $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
815                         $item['follow'] = $contact["url"];
816                         $item['body'] = '';
817                         $item['title'] = '';
818                         $item['guid'] = '';
819                         $item['tag'] = '';
820                         $item['attach'] = '';
821                         $slap = OStatus::salmon($item, $user);
822
823                         if (!empty($contact['notify'])) {
824                                 Salmon::slapper($user, $contact['notify'], $slap);
825                         }
826                 } elseif ($protocol == Protocol::DIASPORA) {
827                         Diaspora::sendUnshare($user, $contact);
828                 } elseif ($protocol == Protocol::ACTIVITYPUB) {
829                         ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
830
831                         if ($dissolve) {
832                                 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
833                         }
834                 }
835         }
836
837         /**
838          * @brief Marks a contact for archival after a communication issue delay
839          *
840          * Contact has refused to recognise us as a friend. We will start a countdown.
841          * If they still don't recognise us in 32 days, the relationship is over,
842          * and we won't waste any more time trying to communicate with them.
843          * This provides for the possibility that their database is temporarily messed
844          * up or some other transient event and that there's a possibility we could recover from it.
845          *
846          * @param array $contact contact to mark for archival
847          * @return null
848          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
849          */
850         public static function markForArchival(array $contact)
851         {
852                 if (!isset($contact['url']) && !empty($contact['id'])) {
853                         $fields = ['id', 'url', 'archive', 'self', 'term-date'];
854                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
855                         if (!DBA::isResult($contact)) {
856                                 return;
857                         }
858                 } elseif (!isset($contact['url'])) {
859                         Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
860                 }
861
862                 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
863
864                 // Contact already archived or "self" contact? => nothing to do
865                 if ($contact['archive'] || $contact['self']) {
866                         return;
867                 }
868
869                 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
870                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
871                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
872                 } else {
873                         /* @todo
874                          * We really should send a notification to the owner after 2-3 weeks
875                          * so they won't be surprised when the contact vanishes and can take
876                          * remedial action if this was a serious mistake or glitch
877                          */
878
879                         /// @todo Check for contact vitality via probing
880                         $archival_days = Config::get('system', 'archival_days', 32);
881
882                         $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
883                         if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
884                                 /* Relationship is really truly dead. archive them rather than
885                                  * delete, though if the owner tries to unarchive them we'll start
886                                  * the whole process over again.
887                                  */
888                                 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
889                                 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
890                                 GContact::updateFromPublicContactURL($contact['url']);
891                         }
892                 }
893         }
894
895         /**
896          * @brief Cancels the archival countdown
897          *
898          * @see   Contact::markForArchival()
899          *
900          * @param array $contact contact to be unmarked for archival
901          * @return null
902          * @throws \Exception
903          */
904         public static function unmarkForArchival(array $contact)
905         {
906                 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
907                 $exists = DBA::exists('contact', $condition);
908
909                 // We don't need to update, we never marked this contact for archival
910                 if (!$exists) {
911                         return;
912                 }
913
914                 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
915
916                 if (!isset($contact['url']) && !empty($contact['id'])) {
917                         $fields = ['id', 'url', 'batch'];
918                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
919                         if (!DBA::isResult($contact)) {
920                                 return;
921                         }
922                 }
923
924                 // It's a miracle. Our dead contact has inexplicably come back to life.
925                 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
926                 DBA::update('contact', $fields, ['id' => $contact['id']]);
927                 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
928                 GContact::updateFromPublicContactURL($contact['url']);
929
930                 if (!empty($contact['batch'])) {
931                         $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
932                         DBA::update('contact', $fields, $condition);
933                 }
934         }
935
936         /**
937          * @brief Get contact data for a given profile link
938          *
939          * The function looks at several places (contact table and gcontact table) for the contact
940          * It caches its result for the same script execution to prevent duplicate calls
941          *
942          * @param string $url     The profile link
943          * @param int    $uid     User id
944          * @param array  $default If not data was found take this data as default value
945          *
946          * @return array Contact data
947          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
948          */
949         public static function getDetailsByURL($url, $uid = -1, array $default = [])
950         {
951                 static $cache = [];
952
953                 if ($url == '') {
954                         return $default;
955                 }
956
957                 if ($uid == -1) {
958                         $uid = local_user();
959                 }
960
961                 if (isset($cache[$url][$uid])) {
962                         return $cache[$url][$uid];
963                 }
964
965                 $ssl_url = str_replace('http://', 'https://', $url);
966
967                 // Fetch contact data from the contact table for the given user
968                 $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`,
969                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
970                 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
971                 $r = DBA::toArray($s);
972
973                 // Fetch contact data from the contact table for the given user, checking with the alias
974                 if (!DBA::isResult($r)) {
975                         $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`,
976                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
977                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
978                         $r = DBA::toArray($s);
979                 }
980
981                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
982                 if (!DBA::isResult($r)) {
983                         $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`,
984                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
985                         FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
986                         $r = DBA::toArray($s);
987                 }
988
989                 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
990                 if (!DBA::isResult($r)) {
991                         $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`,
992                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
993                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
994                         $r = DBA::toArray($s);
995                 }
996
997                 // Fetch the data from the gcontact table
998                 if (!DBA::isResult($r)) {
999                         $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`,
1000                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1001                         FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
1002                         $r = DBA::toArray($s);
1003                 }
1004
1005                 if (DBA::isResult($r)) {
1006                         // If there is more than one entry we filter out the connector networks
1007                         if (count($r) > 1) {
1008                                 foreach ($r as $id => $result) {
1009                                         if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1010                                                 unset($r[$id]);
1011                                         }
1012                                 }
1013                         }
1014
1015                         $profile = array_shift($r);
1016
1017                         // "bd" always contains the upcoming birthday of a contact.
1018                         // "birthday" might contain the birthday including the year of birth.
1019                         if ($profile["birthday"] > DBA::NULL_DATE) {
1020                                 $bd_timestamp = strtotime($profile["birthday"]);
1021                                 $month = date("m", $bd_timestamp);
1022                                 $day = date("d", $bd_timestamp);
1023
1024                                 $current_timestamp = time();
1025                                 $current_year = date("Y", $current_timestamp);
1026                                 $current_month = date("m", $current_timestamp);
1027                                 $current_day = date("d", $current_timestamp);
1028
1029                                 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1030                                 $current = $current_year . "-" . $current_month . "-" . $current_day;
1031
1032                                 if ($profile["bd"] < $current) {
1033                                         $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1034                                 }
1035                         } else {
1036                                 $profile["bd"] = DBA::NULL_DATE;
1037                         }
1038                 } else {
1039                         $profile = $default;
1040                 }
1041
1042                 if (empty($profile["photo"]) && isset($default["photo"])) {
1043                         $profile["photo"] = $default["photo"];
1044                 }
1045
1046                 if (empty($profile["name"]) && isset($default["name"])) {
1047                         $profile["name"] = $default["name"];
1048                 }
1049
1050                 if (empty($profile["network"]) && isset($default["network"])) {
1051                         $profile["network"] = $default["network"];
1052                 }
1053
1054                 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1055                         $profile["thumb"] = $profile["photo"];
1056                 }
1057
1058                 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1059                         $profile["micro"] = $profile["thumb"];
1060                 }
1061
1062                 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
1063                         && in_array($profile["network"], Protocol::FEDERATED)
1064                 ) {
1065                         Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1066                 }
1067
1068                 // Show contact details of Diaspora contacts only if connected
1069                 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
1070                         $profile["location"] = "";
1071                         $profile["about"] = "";
1072                         $profile["gender"] = "";
1073                         $profile["birthday"] = DBA::NULL_DATE;
1074                 }
1075
1076                 $cache[$url][$uid] = $profile;
1077
1078                 return $profile;
1079         }
1080
1081         /**
1082          * @brief Get contact data for a given address
1083          *
1084          * The function looks at several places (contact table and gcontact table) for the contact
1085          *
1086          * @param string $addr The profile link
1087          * @param int    $uid  User id
1088          *
1089          * @return array Contact data
1090          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1091          * @throws \ImagickException
1092          */
1093         public static function getDetailsByAddr($addr, $uid = -1)
1094         {
1095                 if ($addr == '') {
1096                         return [];
1097                 }
1098
1099                 if ($uid == -1) {
1100                         $uid = local_user();
1101                 }
1102
1103                 // Fetch contact data from the contact table for the given user
1104                 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1105                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1106                         FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1107                         DBA::escape($addr),
1108                         intval($uid)
1109                 );
1110                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1111                 if (!DBA::isResult($r)) {
1112                         $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1113                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1114                                 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1115                                 DBA::escape($addr)
1116                         );
1117                 }
1118
1119                 // Fetch the data from the gcontact table
1120                 if (!DBA::isResult($r)) {
1121                         $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`,
1122                                 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1123                                 FROM `gcontact` WHERE `addr` = '%s'",
1124                                 DBA::escape($addr)
1125                         );
1126                 }
1127
1128                 if (!DBA::isResult($r)) {
1129                         $data = Probe::uri($addr);
1130
1131                         $profile = self::getDetailsByURL($data['url'], $uid);
1132                 } else {
1133                         $profile = $r[0];
1134                 }
1135
1136                 return $profile;
1137         }
1138
1139         /**
1140          * @brief Returns the data array for the photo menu of a given contact
1141          *
1142          * @param array $contact contact
1143          * @param int   $uid     optional, default 0
1144          * @return array
1145          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1146          * @throws \ImagickException
1147          */
1148         public static function photoMenu(array $contact, $uid = 0)
1149         {
1150                 $pm_url = '';
1151                 $status_link = '';
1152                 $photos_link = '';
1153                 $contact_drop_link = '';
1154                 $poke_link = '';
1155
1156                 if ($uid == 0) {
1157                         $uid = local_user();
1158                 }
1159
1160                 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1161                         if ($uid == 0) {
1162                                 $profile_link = self::magicLink($contact['url']);
1163                                 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1164
1165                                 return $menu;
1166                         }
1167
1168                         // Look for our own contact if the uid doesn't match and isn't public
1169                         $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1170                         if (DBA::isResult($contact_own)) {
1171                                 return self::photoMenu($contact_own, $uid);
1172                         }
1173                 }
1174
1175                 $sparkle = false;
1176                 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1177                         $sparkle = true;
1178                         $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1179                 } else {
1180                         $profile_link = $contact['url'];
1181                 }
1182
1183                 if ($profile_link === 'mailbox') {
1184                         $profile_link = '';
1185                 }
1186
1187                 if ($sparkle) {
1188                         $status_link = $profile_link . '?tab=status';
1189                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1190                         $profile_link = $profile_link . '?tab=profile';
1191                 }
1192
1193                 if (self::canReceivePrivateMessages($contact)) {
1194                         $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1195                 }
1196
1197                 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1198                         $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1199                 }
1200
1201                 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1202
1203                 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1204
1205                 if (!$contact['self']) {
1206                         $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1207                 }
1208
1209                 /**
1210                  * Menu array:
1211                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1212                  */
1213                 if (empty($contact['uid'])) {
1214                         $connlnk = 'follow/?url=' . $contact['url'];
1215                         $menu = [
1216                                 'profile' => [L10n::t('View Profile'),   $profile_link, true],
1217                                 'network' => [L10n::t('Network Posts'),  $posts_link,   false],
1218                                 'edit'    => [L10n::t('View Contact'),   $contact_url,  false],
1219                                 'follow'  => [L10n::t('Connect/Follow'), $connlnk,      true],
1220                         ];
1221                 } else {
1222                         $menu = [
1223                                 'status'  => [L10n::t('View Status'),   $status_link,       true],
1224                                 'profile' => [L10n::t('View Profile'),  $profile_link,      true],
1225                                 'photos'  => [L10n::t('View Photos'),   $photos_link,       true],
1226                                 'network' => [L10n::t('Network Posts'), $posts_link,        false],
1227                                 'edit'    => [L10n::t('View Contact'),  $contact_url,       false],
1228                                 'drop'    => [L10n::t('Drop Contact'),  $contact_drop_link, false],
1229                                 'pm'      => [L10n::t('Send PM'),       $pm_url,            false],
1230                                 'poke'    => [L10n::t('Poke'),          $poke_link,         false],
1231                         ];
1232                 }
1233
1234                 $args = ['contact' => $contact, 'menu' => &$menu];
1235
1236                 Hook::callAll('contact_photo_menu', $args);
1237
1238                 $menucondensed = [];
1239
1240                 foreach ($menu as $menuname => $menuitem) {
1241                         if ($menuitem[1] != '') {
1242                                 $menucondensed[$menuname] = $menuitem;
1243                         }
1244                 }
1245
1246                 return $menucondensed;
1247         }
1248
1249         /**
1250          * @brief Returns ungrouped contact count or list for user
1251          *
1252          * Returns either the total number of ungrouped contacts for the given user
1253          * id or a paginated list of ungrouped contacts.
1254          *
1255          * @param int $uid uid
1256          * @return array
1257          * @throws \Exception
1258          */
1259         public static function getUngroupedList($uid)
1260         {
1261                 return q("SELECT *
1262                            FROM `contact`
1263                            WHERE `uid` = %d
1264                            AND NOT `self`
1265                            AND NOT `deleted`
1266                            AND NOT `blocked`
1267                            AND NOT `pending`
1268                            AND `id` NOT IN (
1269                                 SELECT DISTINCT(`contact-id`)
1270                                 FROM `group_member`
1271                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1272                                 WHERE `group`.`uid` = %d
1273                            )", intval($uid), intval($uid));
1274         }
1275
1276         /**
1277          * Have a look at all contact tables for a given profile url.
1278          * This function works as a replacement for probing the contact.
1279          *
1280          * @param string  $url Contact URL
1281          * @param integer $cid Contact ID
1282          *
1283          * @return array Contact array in the "probe" structure
1284         */
1285         private static function getProbeDataFromDatabase($url, $cid = null)
1286         {
1287                 // The link could be provided as http although we stored it as https
1288                 $ssl_url = str_replace('http://', 'https://', $url);
1289
1290                 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1291                         'photo', 'keywords', 'location', 'about', 'network',
1292                         'priority', 'batch', 'request', 'confirm', 'poco'];
1293
1294                 if (!empty($cid)) {
1295                         $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1296                         if (DBA::isResult($data)) {
1297                                 return $data;
1298                         }
1299                 }
1300
1301                 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1302
1303                 if (!DBA::isResult($data)) {
1304                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1305                         $data = DBA::selectFirst('contact', $fields, $condition);
1306                 }
1307
1308                 if (DBA::isResult($data)) {
1309                         // For security reasons we don't fetch key data from our users
1310                         $data["pubkey"] = '';
1311                         return $data;
1312                 }
1313
1314                 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1315                         'photo', 'keywords', 'location', 'about', 'network'];
1316                 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1317
1318                 if (!DBA::isResult($data)) {
1319                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1320                         $data = DBA::selectFirst('contact', $fields, $condition);
1321                 }
1322
1323                 if (DBA::isResult($data)) {
1324                         $data["pubkey"] = '';
1325                         $data["poll"] = '';
1326                         $data["priority"] = 0;
1327                         $data["batch"] = '';
1328                         $data["request"] = '';
1329                         $data["confirm"] = '';
1330                         $data["poco"] = '';
1331                         return $data;
1332                 }
1333
1334                 $data = ActivityPub::probeProfile($url, false);
1335                 if (!empty($data)) {
1336                         return $data;
1337                 }
1338
1339                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1340                         'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1341                 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1342
1343                 if (!DBA::isResult($data)) {
1344                         $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1345                         $data = DBA::selectFirst('contact', $fields, $condition);
1346                 }
1347
1348                 if (DBA::isResult($data)) {
1349                         $data["pubkey"] = '';
1350                         $data["keywords"] = '';
1351                         $data["location"] = '';
1352                         $data["about"] = '';
1353                         $data["poco"] = '';
1354                         return $data;
1355                 }
1356
1357                 return [];
1358         }
1359
1360         /**
1361          * @brief Fetch the contact id for a given URL and user
1362          *
1363          * First lookup in the contact table to find a record matching either `url`, `nurl`,
1364          * `addr` or `alias`.
1365          *
1366          * If there's no record and we aren't looking for a public contact, we quit.
1367          * If there's one, we check that it isn't time to update the picture else we
1368          * directly return the found contact id.
1369          *
1370          * Second, we probe the provided $url whether it's http://server.tld/profile or
1371          * nick@server.tld. We quit if we can't get any info back.
1372          *
1373          * Third, we create the contact record if it doesn't exist
1374          *
1375          * Fourth, we update the existing record with the new data (avatar, alias, nick)
1376          * if there's any updates
1377          *
1378          * @param string  $url       Contact URL
1379          * @param integer $uid       The user id for the contact (0 = public contact)
1380          * @param boolean $no_update Don't update the contact
1381          * @param array   $default   Default value for creating the contact when every else fails
1382          * @param boolean $in_loop   Internally used variable to prevent an endless loop
1383          *
1384          * @return integer Contact ID
1385          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1386          * @throws \ImagickException
1387          */
1388         public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1389         {
1390                 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1391
1392                 $contact_id = 0;
1393
1394                 if ($url == '') {
1395                         return 0;
1396                 }
1397
1398                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1399                 // We first try the nurl (http://server.tld/nick), most common case
1400                 $fields = ['id', 'avatar', 'updated', 'network'];
1401                 $options = ['order' => ['id']];
1402                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1403
1404                 // Then the addr (nick@server.tld)
1405                 if (!DBA::isResult($contact)) {
1406                         $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1407                 }
1408
1409                 // Then the alias (which could be anything)
1410                 if (!DBA::isResult($contact)) {
1411                         // The link could be provided as http although we stored it as https
1412                         $ssl_url = str_replace('http://', 'https://', $url);
1413                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1414                         $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1415                 }
1416
1417                 if (DBA::isResult($contact)) {
1418                         $contact_id = $contact["id"];
1419
1420                         // Update the contact every 7 days
1421                         $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1422
1423                         // We force the update if the avatar is empty
1424                         if (empty($contact['avatar'])) {
1425                                 $update_contact = true;
1426                         }
1427
1428                         // Update the contact in the background if needed but it is called by the frontend
1429                         if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1430                                 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1431                         }
1432
1433                         if (!$update_contact || $no_update) {
1434                                 return $contact_id;
1435                         }
1436                 } elseif ($uid != 0) {
1437                         // Non-existing user-specific contact, exiting
1438                         return 0;
1439                 }
1440
1441                 if ($no_update && empty($default)) {
1442                         // When we don't want to update, we look if we know this contact in any way
1443                         $data = self::getProbeDataFromDatabase($url, $contact_id);
1444                         $background_update = true;
1445                 } elseif ($no_update && !empty($default['network'])) {
1446                         // If there are default values, take these
1447                         $data = $default;
1448                         $background_update = false;
1449                 } else {
1450                         $data = [];
1451                         $background_update = false;
1452                 }
1453
1454                 if (empty($data)) {
1455                         $data = Probe::uri($url, "", $uid);
1456
1457                         // Ensure that there is a gserver entry
1458                         if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1459                                 PortableContact::checkServer($data['baseurl']);
1460                         }
1461                 }
1462
1463                 // Take the default values when probing failed
1464                 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1465                         $data = array_merge($data, $default);
1466                 }
1467
1468                 if (empty($data)) {
1469                         return 0;
1470                 }
1471
1472                 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1473                         $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1474                 }
1475
1476                 if (!$contact_id) {
1477                         $fields = [
1478                                 'uid'       => $uid,
1479                                 'created'   => DateTimeFormat::utcNow(),
1480                                 'url'       => $data['url'],
1481                                 'nurl'      => Strings::normaliseLink($data['url']),
1482                                 'addr'      => defaults($data, 'addr', ''),
1483                                 'alias'     => defaults($data, 'alias', ''),
1484                                 'notify'    => defaults($data, 'notify', ''),
1485                                 'poll'      => defaults($data, 'poll', ''),
1486                                 'name'      => defaults($data, 'name', ''),
1487                                 'nick'      => defaults($data, 'nick', ''),
1488                                 'photo'     => defaults($data, 'photo', ''),
1489                                 'keywords'  => defaults($data, 'keywords', ''),
1490                                 'location'  => defaults($data, 'location', ''),
1491                                 'about'     => defaults($data, 'about', ''),
1492                                 'network'   => $data['network'],
1493                                 'pubkey'    => defaults($data, 'pubkey', ''),
1494                                 'rel'       => self::SHARING,
1495                                 'priority'  => defaults($data, 'priority', 0),
1496                                 'batch'     => defaults($data, 'batch', ''),
1497                                 'request'   => defaults($data, 'request', ''),
1498                                 'confirm'   => defaults($data, 'confirm', ''),
1499                                 'poco'      => defaults($data, 'poco', ''),
1500                                 'baseurl'   => defaults($data, 'baseurl', ''),
1501                                 'name-date' => DateTimeFormat::utcNow(),
1502                                 'uri-date'  => DateTimeFormat::utcNow(),
1503                                 'avatar-date' => DateTimeFormat::utcNow(),
1504                                 'writable'  => 1,
1505                                 'blocked'   => 0,
1506                                 'readonly'  => 0,
1507                                 'pending'   => 0];
1508
1509                         $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1510
1511                         // Before inserting we do check if the entry does exist now.
1512                         $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1513                         if (!DBA::isResult($contact)) {
1514                                 Logger::info('Create new contact', $fields);
1515
1516                                 self::insert($fields);
1517
1518                                 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1519                                 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1520                                 if (!DBA::isResult($contact)) {
1521                                         Logger::info('Contact creation failed', $fields);
1522                                         // Shouldn't happen
1523                                         return 0;
1524                                 }
1525                         } else {
1526                                 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1527                         }
1528
1529                         $contact_id = $contact["id"];
1530                 }
1531
1532                 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1533                         self::updateAvatar($data['photo'], $uid, $contact_id);
1534                 }
1535
1536                 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1537                         if ($background_update) {
1538                                 // Update in the background when we fetched the data solely from the database
1539                                 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1540                         } else {
1541                                 // Else do a direct update
1542                                 self::updateFromProbe($contact_id, '', false);
1543
1544                                 // Update the gcontact entry
1545                                 if ($uid == 0) {
1546                                         GContact::updateFromPublicContactID($contact_id);
1547                                 }
1548                         }
1549                 } else {
1550                         $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1551                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1552
1553                         // This condition should always be true
1554                         if (!DBA::isResult($contact)) {
1555                                 return $contact_id;
1556                         }
1557
1558                         $updated = [
1559                                 'url' => $data['url'],
1560                                 'nurl' => Strings::normaliseLink($data['url']),
1561                                 'updated' => DateTimeFormat::utcNow()
1562                         ];
1563
1564                         $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1565
1566                         foreach ($fields as $field) {
1567                                 $updated[$field] = defaults($data, $field, $contact[$field]);
1568                         }
1569
1570                         if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1571                                 $updated['uri-date'] = DateTimeFormat::utcNow();
1572                         }
1573
1574                         if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1575                                 $updated['name-date'] = DateTimeFormat::utcNow();
1576                         }
1577
1578                         DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1579                 }
1580
1581                 return $contact_id;
1582         }
1583
1584         /**
1585          * @brief Checks if the contact is archived
1586          *
1587          * @param int $cid contact id
1588          *
1589          * @return boolean Is the contact archived?
1590          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1591          */
1592         public static function isArchived(int $cid)
1593         {
1594                 if ($cid == 0) {
1595                         return false;
1596                 }
1597
1598                 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1599                 if (!DBA::isResult($contact)) {
1600                         return false;
1601                 }
1602
1603                 if ($contact['archive']) {
1604                         return true;
1605                 }
1606
1607                 // Check status of ActivityPub endpoints
1608                 $apcontact = APContact::getByURL($contact['url'], false);
1609                 if (!empty($apcontact)) {
1610                         if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1611                                 return true;
1612                         }
1613
1614                         if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1615                                 return true;
1616                         }
1617                 }
1618
1619                 // Check status of Diaspora endpoints
1620                 if (!empty($contact['batch'])) {
1621                         return DBA::exists('contact', ['archive' => true, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY]);
1622                 }
1623
1624                 return false;
1625         }
1626
1627         /**
1628          * @brief Checks if the contact is blocked
1629          *
1630          * @param int $cid contact id
1631          *
1632          * @return boolean Is the contact blocked?
1633          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1634          */
1635         public static function isBlocked($cid)
1636         {
1637                 if ($cid == 0) {
1638                         return false;
1639                 }
1640
1641                 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1642                 if (!DBA::isResult($blocked)) {
1643                         return false;
1644                 }
1645
1646                 if (Network::isUrlBlocked($blocked['url'])) {
1647                         return true;
1648                 }
1649
1650                 return (bool) $blocked['blocked'];
1651         }
1652
1653         /**
1654          * @brief Checks if the contact is hidden
1655          *
1656          * @param int $cid contact id
1657          *
1658          * @return boolean Is the contact hidden?
1659          * @throws \Exception
1660          */
1661         public static function isHidden($cid)
1662         {
1663                 if ($cid == 0) {
1664                         return false;
1665                 }
1666
1667                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1668                 if (!DBA::isResult($hidden)) {
1669                         return false;
1670                 }
1671                 return (bool) $hidden['hidden'];
1672         }
1673
1674         /**
1675          * @brief Returns posts from a given contact url
1676          *
1677          * @param string $contact_url Contact URL
1678          *
1679          * @param bool   $thread_mode
1680          * @param int    $update
1681          * @return string posts in HTML
1682          * @throws \Exception
1683          */
1684         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1685         {
1686                 $a = self::getApp();
1687
1688                 $cid = self::getIdForURL($contact_url);
1689
1690                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1691                 if (!DBA::isResult($contact)) {
1692                         return '';
1693                 }
1694
1695                 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1696                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1697                 } else {
1698                         $sql = "`item`.`uid` = ?";
1699                 }
1700
1701                 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1702
1703                 if ($thread_mode) {
1704                         $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1705                                 $cid, GRAVITY_PARENT, local_user()];
1706                 } else {
1707                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1708                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1709                 }
1710
1711                 $pager = new Pager($a->query_string);
1712
1713                 $params = ['order' => ['received' => true],
1714                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1715
1716                 if ($thread_mode) {
1717                         $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1718
1719                         $items = Item::inArray($r);
1720
1721                         $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1722                 } else {
1723                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1724
1725                         $items = Item::inArray($r);
1726
1727                         $o = conversation($a, $items, $pager, 'contact-posts', false);
1728                 }
1729
1730                 if (!$update) {
1731                         $o .= $pager->renderMinimal(count($items));
1732                 }
1733
1734                 return $o;
1735         }
1736
1737         /**
1738          * @brief Returns the account type name
1739          *
1740          * The function can be called with either the user or the contact array
1741          *
1742          * @param array $contact contact or user array
1743          * @return string
1744          */
1745         public static function getAccountType(array $contact)
1746         {
1747                 // There are several fields that indicate that the contact or user is a forum
1748                 // "page-flags" is a field in the user table,
1749                 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1750                 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1751                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1752                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1753                         || (isset($contact['forum']) && intval($contact['forum']))
1754                         || (isset($contact['prv']) && intval($contact['prv']))
1755                         || (isset($contact['community']) && intval($contact['community']))
1756                 ) {
1757                         $type = self::TYPE_COMMUNITY;
1758                 } else {
1759                         $type = self::TYPE_PERSON;
1760                 }
1761
1762                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1763                 if (isset($contact["contact-type"])) {
1764                         $type = $contact["contact-type"];
1765                 }
1766
1767                 if (isset($contact["account-type"])) {
1768                         $type = $contact["account-type"];
1769                 }
1770
1771                 switch ($type) {
1772                         case self::TYPE_ORGANISATION:
1773                                 $account_type = L10n::t("Organisation");
1774                                 break;
1775
1776                         case self::TYPE_NEWS:
1777                                 $account_type = L10n::t('News');
1778                                 break;
1779
1780                         case self::TYPE_COMMUNITY:
1781                                 $account_type = L10n::t("Forum");
1782                                 break;
1783
1784                         default:
1785                                 $account_type = "";
1786                                 break;
1787                 }
1788
1789                 return $account_type;
1790         }
1791
1792         /**
1793          * @brief Blocks a contact
1794          *
1795          * @param int $cid
1796          * @return bool
1797          * @throws \Exception
1798          */
1799         public static function block($cid, $reason = null)
1800         {
1801                 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1802
1803                 return $return;
1804         }
1805
1806         /**
1807          * @brief Unblocks a contact
1808          *
1809          * @param int $cid
1810          * @return bool
1811          * @throws \Exception
1812          */
1813         public static function unblock($cid)
1814         {
1815                 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1816
1817                 return $return;
1818         }
1819
1820         /**
1821          * @brief Updates the avatar links in a contact only if needed
1822          *
1823          * @param string $avatar Link to avatar picture
1824          * @param int    $uid    User id of contact owner
1825          * @param int    $cid    Contact id
1826          * @param bool   $force  force picture update
1827          *
1828          * @return array Returns array of the different avatar sizes
1829          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1830          * @throws \ImagickException
1831          */
1832         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1833         {
1834                 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1835                 if (!DBA::isResult($contact)) {
1836                         return false;
1837                 } else {
1838                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1839                 }
1840
1841                 if (($contact["avatar"] != $avatar) || $force) {
1842                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1843
1844                         if ($photos) {
1845                                 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1846                                 DBA::update('contact', $fields, ['id' => $cid]);
1847
1848                                 // Update the public contact (contact id = 0)
1849                                 if ($uid != 0) {
1850                                         $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1851                                         if (DBA::isResult($pcontact)) {
1852                                                 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1853                                         }
1854                                 }
1855
1856                                 return $photos;
1857                         }
1858                 }
1859
1860                 return $data;
1861         }
1862
1863         /**
1864          * @brief Helper function for "updateFromProbe". Updates personal and public contact
1865          *
1866          * @param integer $id      contact id
1867          * @param integer $uid     user id
1868          * @param string  $url     The profile URL of the contact
1869          * @param array   $fields  The fields that are updated
1870          *
1871          * @throws \Exception
1872          */
1873         private static function updateContact($id, $uid, $url, array $fields)
1874         {
1875                 if (!DBA::update('contact', $fields, ['id' => $id])) {
1876                         Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1877                         return;
1878                 }
1879
1880                 // Search for duplicated contacts and get rid of them
1881                 if (self::handleDuplicates(Strings::normaliseLink($url), $uid, $id) || ($uid != 0)) {
1882                         return;
1883                 }
1884
1885                 // Update the corresponding gcontact entry
1886                 GContact::updateFromPublicContactID($id);
1887
1888                 // Archive or unarchive the contact. We only need to do this for the public contact.
1889                 // The archive/unarchive function will update the personal contacts by themselves.
1890                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1891                 if (!DBA::isResult($contact)) {
1892                         Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1893                         return;
1894                 }
1895
1896                 if (!empty($fields['success_update'])) {
1897                         self::unmarkForArchival($contact);
1898                 } elseif (!empty($fields['failure_update'])) {
1899                         self::markForArchival($contact);
1900                 }
1901
1902                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1903
1904                 // These contacts are sharing with us, we don't poll them.
1905                 // This means that we don't set the update fields in "OnePoll.php".
1906                 $condition['rel'] = self::SHARING;
1907                 DBA::update('contact', $fields, $condition);
1908
1909                 unset($fields['last-update']);
1910                 unset($fields['success_update']);
1911                 unset($fields['failure_update']);
1912
1913                 if (empty($fields)) {
1914                         return;
1915                 }
1916
1917                 // We are polling these contacts, so we mustn't set the update fields here.
1918                 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1919                 DBA::update('contact', $fields, $condition);
1920         }
1921
1922         /**
1923          * Check and remove duplicate contact entries
1924          *
1925          * @param integer $contact_id Contact ID
1926          * @throws \Exception
1927          */
1928         public static function handleDuplicateByID($contact_id)
1929         {
1930                 $contact = DBA::selectFirst('contact', ['nurl', 'uid', 'id'], ['id' => $contact_id]);
1931                 if (!DBA::isResult($contact)) {
1932                         return $ret;
1933                 }
1934
1935                 // Search for duplicated contacts and get rid of them
1936                 self::handleDuplicates($contact['nurl'], $contact['uid'], $contact['id']);
1937
1938                 return $ret;
1939         }
1940
1941         /**
1942          * @brief Helper function for "updateFromProbe". Remove duplicated contacts
1943          *
1944          * @param string  $nurl  Normalised contact url
1945          * @param integer $uid   User id
1946          * @param integer $id    Contact id of a duplicate
1947          * @return boolean
1948          * @throws \Exception
1949          */
1950         private static function handleDuplicates($nurl, $uid, $id)
1951         {
1952                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1953                 $count = DBA::count('contact', $condition);
1954                 if ($count <= 1) {
1955                         return false;
1956                 }
1957
1958                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1959                 if (!DBA::isResult($first_contact)) {
1960                         // Shouldn't happen - so we handle it
1961                         return false;
1962                 }
1963
1964                 $first = $first_contact['id'];
1965                 Logger::info('Found duplicates', ['count' => $count, 'id' => $id, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1966                 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1967                         // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1968                         Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1969                         return false;
1970                 }
1971
1972                 // Find all duplicates
1973                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1974                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1975                 while ($duplicate = DBA::fetch($duplicates)) {
1976                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1977                                 continue;
1978                         }
1979
1980                         Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1981                 }
1982                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1983                 return true;
1984         }
1985
1986         /**
1987          * @param integer $id      contact id
1988          * @param string  $network Optional network we are probing for
1989          * @param boolean $force   Optional forcing of network probing (otherwise we use the cached data)
1990          * @return boolean
1991          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1992          * @throws \ImagickException
1993          */
1994         public static function updateFromProbe($id, $network = '', $force = false)
1995         {
1996                 /*
1997                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1998                   This will reliably kill your communication with old Friendica contacts.
1999                  */
2000
2001                 // These fields aren't updated by this routine:
2002                 // 'xmpp', 'sensitive'
2003
2004                 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2005                         'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2006                         'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2007                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2008                 if (!DBA::isResult($contact)) {
2009                         return false;
2010                 }
2011
2012                 $uid = $contact['uid'];
2013                 unset($contact['uid']);
2014
2015                 $pubkey = $contact['pubkey'];
2016                 unset($contact['pubkey']);
2017
2018                 $contact['photo'] = $contact['avatar'];
2019                 unset($contact['avatar']);
2020
2021                 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2022
2023                 $updated = DateTimeFormat::utcNow();
2024
2025                 // We must not try to update relay contacts via probe. They are no real contacts.
2026                 // We check after the probing to be able to correct falsely detected contact types.
2027                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2028                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2029                         self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2030                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2031                         return true;
2032                 }
2033
2034                 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
2035                 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
2036                         (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
2037                         if ($force && ($uid == 0)) {
2038                                 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2039                         }
2040                         return false;
2041                 }
2042
2043                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2044                         $ret['unsearchable'] = $ret['hide'];
2045                 }
2046
2047                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2048                         $ret['forum'] = false;
2049                         $ret['prv'] = false;
2050                         $ret['contact-type'] = $ret['account-type'];
2051                         if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2052                                 $apcontact = APContact::getByURL($ret['url'], false);
2053                                 if (isset($apcontact['manually-approve'])) {
2054                                         $ret['forum'] = (bool)!$apcontact['manually-approve'];
2055                                         $ret['prv'] = (bool)!$ret['forum'];
2056                                 }
2057                         }
2058                 }
2059
2060                 $new_pubkey = $ret['pubkey'];
2061
2062                 $update = false;
2063
2064                 // make sure to not overwrite existing values with blank entries except some technical fields
2065                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2066                 foreach ($ret as $key => $val) {
2067                         if (!array_key_exists($key, $contact)) {
2068                                 unset($ret[$key]);
2069                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2070                                 $ret[$key] = $contact[$key];
2071                         } elseif ($ret[$key] != $contact[$key]) {
2072                                 $update = true;
2073                         }
2074                 }
2075
2076                 if ($ret['network'] != Protocol::FEED) {
2077                         self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2078                 }
2079
2080                 if (!$update) {
2081                         if ($force) {
2082                                 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2083                         }
2084                         return true;
2085                 }
2086
2087                 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2088                 $ret['updated'] = $updated;
2089
2090                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2091                 if (empty($pubkey) && !empty($new_pubkey)) {
2092                         $ret['pubkey'] = $new_pubkey;
2093                 }
2094
2095                 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2096                         $ret['uri-date'] = DateTimeFormat::utcNow();
2097                 }
2098
2099                 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2100                         $ret['name-date'] = $updated;
2101                 }
2102
2103                 if ($force && ($uid == 0)) {
2104                         $ret['last-update'] = $updated;
2105                         $ret['success_update'] = $updated;
2106                 }
2107
2108                 unset($ret['photo']);
2109
2110                 self::updateContact($id, $uid, $ret['url'], $ret);
2111
2112                 return true;
2113         }
2114
2115         public static function updateFromProbeByURL($url, $force = false)
2116         {
2117                 $id = self::getIdForURL($url);
2118
2119                 if (empty($id)) {
2120                         return $id;
2121                 }
2122
2123                 self::updateFromProbe($id, '', $force);
2124
2125                 return $id;
2126         }
2127
2128         /**
2129          * Detects if a given contact array belongs to a legacy DFRN connection
2130          *
2131          * @param array $contact
2132          * @return boolean
2133          */
2134         public static function isLegacyDFRNContact($contact)
2135         {
2136                 // Newer Friendica contacts are connected via AP, then these fields aren't set
2137                 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2138         }
2139
2140         /**
2141          * Detects the communication protocol for a given contact url.
2142          * This is used to detect Friendica contacts that we can communicate via AP.
2143          *
2144          * @param string $url contact url
2145          * @param string $network Network of that contact
2146          * @return string with protocol
2147          */
2148         public static function getProtocol($url, $network)
2149         {
2150                 if ($network != Protocol::DFRN) {
2151                         return $network;
2152                 }
2153
2154                 $apcontact = APContact::getByURL($url);
2155                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2156                         return Protocol::ACTIVITYPUB;
2157                 } else {
2158                         return $network;
2159                 }
2160         }
2161
2162         /**
2163          * Takes a $uid and a url/handle and adds a new contact
2164          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2165          * dfrn_request page.
2166          *
2167          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2168          *
2169          * Returns an array
2170          * $return['success'] boolean true if successful
2171          * $return['message'] error text if success is false.
2172          *
2173          * @brief Takes a $uid and a url/handle and adds a new contact
2174          * @param int    $uid
2175          * @param string $url
2176          * @param bool   $interactive
2177          * @param string $network
2178          * @return array
2179          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2180          * @throws \ImagickException
2181          */
2182         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2183         {
2184                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2185
2186                 $a = \get_app();
2187
2188                 // remove ajax junk, e.g. Twitter
2189                 $url = str_replace('/#!/', '/', $url);
2190
2191                 if (!Network::isUrlAllowed($url)) {
2192                         $result['message'] = L10n::t('Disallowed profile URL.');
2193                         return $result;
2194                 }
2195
2196                 if (Network::isUrlBlocked($url)) {
2197                         $result['message'] = L10n::t('Blocked domain');
2198                         return $result;
2199                 }
2200
2201                 if (!$url) {
2202                         $result['message'] = L10n::t('Connect URL missing.');
2203                         return $result;
2204                 }
2205
2206                 $arr = ['url' => $url, 'contact' => []];
2207
2208                 Hook::callAll('follow', $arr);
2209
2210                 if (empty($arr)) {
2211                         $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2212                         return $result;
2213                 }
2214
2215                 if (!empty($arr['contact']['name'])) {
2216                         $ret = $arr['contact'];
2217                 } else {
2218                         $ret = Probe::uri($url, $network, $uid, false);
2219                 }
2220
2221                 if (($network != '') && ($ret['network'] != $network)) {
2222                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2223                         return $result;
2224                 }
2225
2226                 // check if we already have a contact
2227                 // the poll url is more reliable than the profile url, as we may have
2228                 // indirect links or webfinger links
2229
2230                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2231                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2232                 if (!DBA::isResult($contact)) {
2233                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2234                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2235                 }
2236
2237                 $protocol = self::getProtocol($url, $ret['network']);
2238
2239                 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2240                         if ($interactive) {
2241                                 if (strlen($a->getURLPath())) {
2242                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2243                                 } else {
2244                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2245                                 }
2246
2247                                 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2248
2249                                 // NOTREACHED
2250                         }
2251                 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2252                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2253                         $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2254                         return $result;
2255                 }
2256
2257                 // This extra param just confuses things, remove it
2258                 if ($protocol === Protocol::DIASPORA) {
2259                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2260                 }
2261
2262                 // do we have enough information?
2263                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2264                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2265                         if (empty($ret['poll'])) {
2266                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2267                         }
2268                         if (empty($ret['name'])) {
2269                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2270                         }
2271                         if (empty($ret['url'])) {
2272                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2273                         }
2274                         if (strpos($url, '@') !== false) {
2275                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2276                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2277                         }
2278                         return $result;
2279                 }
2280
2281                 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2282                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2283                         $ret['notify'] = '';
2284                 }
2285
2286                 if (!$ret['notify']) {
2287                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2288                 }
2289
2290                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2291
2292                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2293
2294                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2295
2296                 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2297
2298                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2299                         $writeable = 1;
2300                 }
2301
2302                 if (DBA::isResult($contact)) {
2303                         // update contact
2304                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2305
2306                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2307                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2308                 } else {
2309                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2310
2311                         // create contact record
2312                         self::insert([
2313                                 'uid'     => $uid,
2314                                 'created' => DateTimeFormat::utcNow(),
2315                                 'url'     => $ret['url'],
2316                                 'nurl'    => Strings::normaliseLink($ret['url']),
2317                                 'addr'    => $ret['addr'],
2318                                 'alias'   => $ret['alias'],
2319                                 'batch'   => $ret['batch'],
2320                                 'notify'  => $ret['notify'],
2321                                 'poll'    => $ret['poll'],
2322                                 'poco'    => $ret['poco'],
2323                                 'name'    => $ret['name'],
2324                                 'nick'    => $ret['nick'],
2325                                 'network' => $ret['network'],
2326                                 'baseurl' => $ret['baseurl'],
2327                                 'protocol' => $protocol,
2328                                 'pubkey'  => $ret['pubkey'],
2329                                 'rel'     => $new_relation,
2330                                 'priority'=> $ret['priority'],
2331                                 'writable'=> $writeable,
2332                                 'hidden'  => $hidden,
2333                                 'blocked' => 0,
2334                                 'readonly'=> 0,
2335                                 'pending' => $pending,
2336                                 'subhub'  => $subhub
2337                         ]);
2338                 }
2339
2340                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2341                 if (!DBA::isResult($contact)) {
2342                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2343                         return $result;
2344                 }
2345
2346                 $contact_id = $contact['id'];
2347                 $result['cid'] = $contact_id;
2348
2349                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2350
2351                 // Update the avatar
2352                 self::updateAvatar($ret['photo'], $uid, $contact_id);
2353
2354                 // pull feed and consume it, which should subscribe to the hub.
2355
2356                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2357
2358                 $owner = User::getOwnerDataById($uid);
2359
2360                 if (DBA::isResult($owner)) {
2361                         if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2362                                 // create a follow slap
2363                                 $item = [];
2364                                 $item['verb'] = ACTIVITY_FOLLOW;
2365                                 $item['follow'] = $contact["url"];
2366                                 $item['body'] = '';
2367                                 $item['title'] = '';
2368                                 $item['guid'] = '';
2369                                 $item['tag'] = '';
2370                                 $item['attach'] = '';
2371
2372                                 $slap = OStatus::salmon($item, $owner);
2373
2374                                 if (!empty($contact['notify'])) {
2375                                         Salmon::slapper($owner, $contact['notify'], $slap);
2376                                 }
2377                         } elseif ($protocol == Protocol::DIASPORA) {
2378                                 $ret = Diaspora::sendShare($a->user, $contact);
2379                                 Logger::log('share returns: ' . $ret);
2380                         } elseif ($protocol == Protocol::ACTIVITYPUB) {
2381                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2382                                 if (empty($activity_id)) {
2383                                         // This really should never happen
2384                                         return false;
2385                                 }
2386
2387                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2388                                 Logger::log('Follow returns: ' . $ret);
2389                         }
2390                 }
2391
2392                 $result['success'] = true;
2393                 return $result;
2394         }
2395
2396         /**
2397          * @brief Updated contact's SSL policy
2398          *
2399          * @param array  $contact    Contact array
2400          * @param string $new_policy New policy, valid: self,full
2401          *
2402          * @return array Contact array with updated values
2403          * @throws \Exception
2404          */
2405         public static function updateSslPolicy(array $contact, $new_policy)
2406         {
2407                 $ssl_changed = false;
2408                 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2409                         $ssl_changed = true;
2410                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
2411                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
2412                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
2413                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
2414                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
2415                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
2416                 }
2417
2418                 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2419                         $ssl_changed = true;
2420                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
2421                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
2422                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
2423                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
2424                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
2425                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
2426                 }
2427
2428                 if ($ssl_changed) {
2429                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2430                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
2431                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2432                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2433                 }
2434
2435                 return $contact;
2436         }
2437
2438         /**
2439          * @param array  $importer Owner (local user) data
2440          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2441          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2442          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2443          * @param string $note     Introduction additional message
2444          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2445          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2446          * @throws \ImagickException
2447          */
2448         public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2449         {
2450                 // Should always be set
2451                 if (empty($datarray['author-id'])) {
2452                         return false;
2453                 }
2454
2455                 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2456                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2457                 if (!DBA::isResult($pub_contact)) {
2458                         // Should never happen
2459                         return false;
2460                 }
2461
2462                 // Contact is blocked at node-level
2463                 if (self::isBlocked($datarray['author-id'])) {
2464                         return false;
2465                 }
2466
2467                 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2468                 $name = $pub_contact['name'];
2469                 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2470                 $nick = $pub_contact['nick'];
2471                 $network = $pub_contact['network'];
2472
2473                 // Ensure that we don't create a new contact when there already is one
2474                 $cid = self::getIdForURL($url, $importer['uid']);
2475                 if (!empty($cid)) {
2476                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2477                 }
2478
2479                 if (!empty($contact)) {
2480                         if (!empty($contact['pending'])) {
2481                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2482                                 return null;
2483                         }
2484
2485                         // Contact is blocked at user-level
2486                         if (!empty($contact['id']) && !empty($importer['id']) &&
2487                                 self::isBlockedByUser($contact['id'], $importer['id'])) {
2488                                 return false;
2489                         }
2490
2491                         // Make sure that the existing contact isn't archived
2492                         self::unmarkForArchival($contact);
2493
2494                         if (($contact['rel'] == self::SHARING)
2495                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2496                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2497                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2498                         }
2499
2500                         return true;
2501                 } else {
2502                         // send email notification to owner?
2503                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2504                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2505                                 return null;
2506                         }
2507
2508                         // create contact record
2509                         DBA::insert('contact', [
2510                                 'uid'      => $importer['uid'],
2511                                 'created'  => DateTimeFormat::utcNow(),
2512                                 'url'      => $url,
2513                                 'nurl'     => Strings::normaliseLink($url),
2514                                 'name'     => $name,
2515                                 'nick'     => $nick,
2516                                 'photo'    => $photo,
2517                                 'network'  => $network,
2518                                 'rel'      => self::FOLLOWER,
2519                                 'blocked'  => 0,
2520                                 'readonly' => 0,
2521                                 'pending'  => 1,
2522                                 'writable' => 1,
2523                         ]);
2524
2525                         $contact_record = [
2526                                 'id' => DBA::lastInsertId(),
2527                                 'network' => $network,
2528                                 'name' => $name,
2529                                 'url' => $url,
2530                                 'photo' => $photo
2531                         ];
2532
2533                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2534
2535                         /// @TODO Encapsulate this into a function/method
2536                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2537                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2538                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2539                                 // create notification
2540                                 $hash = Strings::getRandomHex();
2541
2542                                 if (is_array($contact_record)) {
2543                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2544                                                                 'blocked' => false, 'knowyou' => false, 'note' => $note,
2545                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2546                                 }
2547
2548                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2549
2550                                 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2551                                         in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2552
2553                                         notification([
2554                                                 'type'         => NOTIFY_INTRO,
2555                                                 'notify_flags' => $user['notify-flags'],
2556                                                 'language'     => $user['language'],
2557                                                 'to_name'      => $user['username'],
2558                                                 'to_email'     => $user['email'],
2559                                                 'uid'          => $user['uid'],
2560                                                 'link'         => System::baseUrl() . '/notifications/intro',
2561                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2562                                                 'source_link'  => $contact_record['url'],
2563                                                 'source_photo' => $contact_record['photo'],
2564                                                 'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2565                                                 'otype'        => 'intro'
2566                                         ]);
2567                                 }
2568                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2569                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2570                                 DBA::update('contact', ['pending' => false], $condition);
2571
2572                                 return true;
2573                         }
2574                 }
2575
2576                 return null;
2577         }
2578
2579         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2580         {
2581                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2582                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2583                 } else {
2584                         Contact::remove($contact['id']);
2585                 }
2586         }
2587
2588         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2589         {
2590                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2591                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2592                 } else {
2593                         Contact::remove($contact['id']);
2594                 }
2595         }
2596
2597         /**
2598          * @brief Create a birthday event.
2599          *
2600          * Update the year and the birthday.
2601          */
2602         public static function updateBirthdays()
2603         {
2604                 $condition = [
2605                         '`bd` != ""
2606                         AND `bd` > "0001-01-01"
2607                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2608                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2609                         AND NOT `contact`.`pending`
2610                         AND NOT `contact`.`hidden`
2611                         AND NOT `contact`.`blocked`
2612                         AND NOT `contact`.`archive`
2613                         AND NOT `contact`.`deleted`',
2614                         Contact::SHARING,
2615                         Contact::FRIEND
2616                 ];
2617
2618                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2619
2620                 while ($contact = DBA::fetch($contacts)) {
2621                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2622
2623                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2624
2625                         if (Event::createBirthday($contact, $nextbd)) {
2626                                 // update bdyear
2627                                 DBA::update(
2628                                         'contact',
2629                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2630                                         ['id' => $contact['id']]
2631                                 );
2632                         }
2633                 }
2634         }
2635
2636         /**
2637          * Remove the unavailable contact ids from the provided list
2638          *
2639          * @param array $contact_ids Contact id list
2640          * @throws \Exception
2641          */
2642         public static function pruneUnavailable(array &$contact_ids)
2643         {
2644                 if (empty($contact_ids)) {
2645                         return;
2646                 }
2647
2648                 $str = DBA::escape(implode(',', $contact_ids));
2649
2650                 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2651
2652                 $return = [];
2653                 while($contact = DBA::fetch($stmt)) {
2654                         $return[] = $contact['id'];
2655                 }
2656
2657                 DBA::close($stmt);
2658
2659                 $contact_ids = $return;
2660         }
2661
2662         /**
2663          * @brief Returns a magic link to authenticate remote visitors
2664          *
2665          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2666          *
2667          * @param string $contact_url The address of the target contact profile
2668          * @param string $url         An url that we will be redirected to after the authentication
2669          *
2670          * @return string with "redir" link
2671          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2672          * @throws \ImagickException
2673          */
2674         public static function magicLink($contact_url, $url = '')
2675         {
2676                 if (!local_user() && !remote_user()) {
2677                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2678                 }
2679
2680                 $data = self::getProbeDataFromDatabase($contact_url);
2681                 if (empty($data)) {
2682                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2683                 }
2684
2685                 // Prevents endless loop in case only a non-public contact exists for the contact URL
2686                 unset($data['uid']);
2687
2688                 return self::magicLinkByContact($data, $contact_url);
2689         }
2690
2691         /**
2692          * @brief Returns a magic link to authenticate remote visitors
2693          *
2694          * @param integer $cid The contact id of the target contact profile
2695          * @param string  $url An url that we will be redirected to after the authentication
2696          *
2697          * @return string with "redir" link
2698          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2699          * @throws \ImagickException
2700          */
2701         public static function magicLinkbyId($cid, $url = '')
2702         {
2703                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2704
2705                 return self::magicLinkByContact($contact, $url);
2706         }
2707
2708         /**
2709          * @brief Returns a magic link to authenticate remote visitors
2710          *
2711          * @param array  $contact The contact array with "uid", "network" and "url"
2712          * @param string $url     An url that we will be redirected to after the authentication
2713          *
2714          * @return string with "redir" link
2715          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2716          * @throws \ImagickException
2717          */
2718         public static function magicLinkByContact($contact, $url = '')
2719         {
2720                 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2721                         return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2722                 }
2723
2724                 // Only redirections to the same host do make sense
2725                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2726                         return $url;
2727                 }
2728
2729                 if (!empty($contact['uid'])) {
2730                         return self::magicLink($contact['url'], $url);
2731                 }
2732
2733                 if (empty($contact['id'])) {
2734                         return $url ?: $contact['url'];
2735                 }
2736
2737                 $redirect = 'redir/' . $contact['id'];
2738
2739                 if ($url != '') {
2740                         $redirect .= '?url=' . $url;
2741                 }
2742
2743                 return $redirect;
2744         }
2745
2746         /**
2747          * Remove a contact from all groups
2748          *
2749          * @param integer $contact_id
2750          *
2751          * @return boolean Success
2752          */
2753         public static function removeFromGroups($contact_id)
2754         {
2755                 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2756         }
2757
2758         /**
2759          * Is the contact a forum?
2760          *
2761          * @param integer $contactid ID of the contact
2762          *
2763          * @return boolean "true" if it is a forum
2764          */
2765         public static function isForum($contactid)
2766         {
2767                 $fields = ['forum', 'prv'];
2768                 $condition = ['id' => $contactid];
2769                 $contact = DBA::selectFirst('contact', $fields, $condition);
2770                 if (!DBA::isResult($contact)) {
2771                         return false;
2772                 }
2773
2774                 // Is it a forum?
2775                 return ($contact['forum'] || $contact['prv']);
2776         }
2777
2778         /**
2779          * Can the remote contact receive private messages?
2780          *
2781          * @param array $contact
2782          * @return bool
2783          */
2784         public static function canReceivePrivateMessages(array $contact)
2785         {
2786                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2787                 $self = $contact['self'] ?? false;
2788
2789                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2790         }
2791 }