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