]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
New contact table functions with check for duplicates
[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 array $contact The personal contact entry
1902          * @param array $fields  The fields that are updated
1903          * @throws \Exception
1904          */
1905         private static function updateContact($id, $uid, $url, array $fields)
1906         {
1907                 DBA::update('contact', $fields, ['id' => $id]);
1908
1909                 // Search for duplicated contacts and get rid of them
1910                 if (self::handleDuplicates(Strings::normaliseLink($url), $uid, $id) || ($uid != 0)) {
1911                         return;
1912                 }
1913
1914                 // Update the corresponding gcontact entry
1915                 GContact::updateFromPublicContactID($id);
1916
1917                 // Archive or unarchive the contact. We only need to do this for the public contact.
1918                 // The archive/unarchive function will update the personal contacts by themselves.
1919                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1920                 if (!empty($fields['success_update'])) {
1921                         self::unmarkForArchival($contact);
1922                 } elseif (!empty($fields['failure_update'])) {
1923                         self::markForArchival($contact);
1924                 }
1925
1926                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1927
1928                 // These contacts are sharing with us, we don't poll them.
1929                 // This means that we don't set the update fields in "OnePoll.php".
1930                 $condition['rel'] = self::SHARING;
1931                 DBA::update('contact', $fields, $condition);
1932
1933                 unset($fields['last-update']);
1934                 unset($fields['success_update']);
1935                 unset($fields['failure_update']);
1936
1937                 if (empty($fields)) {
1938                         return;
1939                 }
1940
1941                 // We are polling these contacts, so we mustn't set the update fields here.
1942                 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1943                 DBA::update('contact', $fields, $condition);
1944         }
1945
1946         /**
1947          * @brief Helper function for "updateFromProbe". Remove duplicated contacts
1948          *
1949          * @param string  $nurl  Normalised contact url
1950          * @param integer $uid   User id
1951          * @param integer $id    Contact id of a duplicate
1952          * @return boolean
1953          * @throws \Exception
1954          */
1955         private static function handleDuplicates($nurl, $uid, $id)
1956         {
1957                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1958                 $count = DBA::count('contact', $condition);
1959                 if ($count <= 1) {
1960                         return false;
1961                 }
1962
1963                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1964                 if (!DBA::isResult($first_contact)) {
1965                         // Shouldn't happen - so we handle it
1966                         return false;
1967                 }
1968
1969                 $first = $first_contact['id'];
1970                 Logger::info('Found duplicates', ['count' => $count, 'id' => $id, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1971                 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1972                         // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1973                         Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1974                         return false;
1975                 }
1976
1977                 // Find all duplicates
1978                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1979                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1980                 while ($duplicate = DBA::fetch($duplicates)) {
1981                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1982                                 continue;
1983                         }
1984
1985                         Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1986                 }
1987                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1988                 return true;
1989         }
1990
1991         /**
1992          * @param integer $id      contact id
1993          * @param string  $network Optional network we are probing for
1994          * @param boolean $force   Optional forcing of network probing (otherwise we use the cached data)
1995          * @return boolean
1996          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1997          * @throws \ImagickException
1998          */
1999         public static function updateFromProbe($id, $network = '', $force = false)
2000         {
2001                 /*
2002                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2003                   This will reliably kill your communication with old Friendica contacts.
2004                  */
2005
2006                 // These fields aren't updated by this routine:
2007                 // 'xmpp', 'sensitive'
2008
2009                 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2010                         'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2011                         'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2012                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2013                 if (!DBA::isResult($contact)) {
2014                         return false;
2015                 }
2016
2017                 $uid = $contact['uid'];
2018                 unset($contact['uid']);
2019
2020                 $pubkey = $contact['pubkey'];
2021                 unset($contact['pubkey']);
2022
2023                 $contact['photo'] = $contact['avatar'];
2024                 unset($contact['avatar']);
2025
2026                 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2027
2028                 $updated = DateTimeFormat::utcNow();
2029
2030                 // We must not try to update relay contacts via probe. They are no real contacts.
2031                 // We check after the probing to be able to correct falsely detected contact types.
2032                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2033                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2034                         self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2035                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2036                         return true;
2037                 }
2038
2039                 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
2040                 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
2041                         (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
2042                         if ($force && ($uid == 0)) {
2043                                 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2044                         }
2045                         return false;
2046                 }
2047
2048                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2049                         $ret['unsearchable'] = $ret['hide'];
2050                 }
2051
2052                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2053                         $ret['forum'] = false;
2054                         $ret['prv'] = false;
2055                         $ret['contact-type'] = $ret['account-type'];
2056                         if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2057                                 $apcontact = APContact::getByURL($ret['url'], false);
2058                                 if (isset($apcontact['manually-approve'])) {
2059                                         $ret['forum'] = (bool)!$apcontact['manually-approve'];
2060                                         $ret['prv'] = (bool)!$ret['forum'];
2061                                 }
2062                         }
2063                 }
2064
2065                 $new_pubkey = $ret['pubkey'];
2066
2067                 $update = false;
2068
2069                 // make sure to not overwrite existing values with blank entries except some technical fields
2070                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2071                 foreach ($ret as $key => $val) {
2072                         if (!array_key_exists($key, $contact)) {
2073                                 unset($ret[$key]);
2074                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2075                                 $ret[$key] = $contact[$key];
2076                         } elseif ($ret[$key] != $contact[$key]) {
2077                                 $update = true;
2078                         }
2079                 }
2080
2081                 if ($ret['network'] != Protocol::FEED) {
2082                         self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2083                 }
2084
2085                 if (!$update) {
2086                         if ($force) {
2087                                 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2088                         }
2089                         return true;
2090                 }
2091
2092                 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2093                 $ret['updated'] = $updated;
2094
2095                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2096                 if (empty($pubkey) && !empty($new_pubkey)) {
2097                         $ret['pubkey'] = $new_pubkey;
2098                 }
2099
2100                 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2101                         $ret['uri-date'] = DateTimeFormat::utcNow();
2102                 }
2103
2104                 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2105                         $ret['name-date'] = $updated;
2106                 }
2107
2108                 if ($force && ($uid == 0)) {
2109                         $ret['last-update'] = $updated;
2110                         $ret['success_update'] = $updated;
2111                 }
2112
2113                 unset($ret['photo']);
2114
2115                 self::updateContact($id, $uid, $ret['url'], $ret);
2116
2117                 return true;
2118         }
2119
2120         public static function updateFromProbeByURL($url, $force = false)
2121         {
2122                 $id = self::getIdForURL($url);
2123
2124                 if (empty($id)) {
2125                         return $id;
2126                 }
2127
2128                 self::updateFromProbe($id, '', $force);
2129
2130                 return $id;
2131         }
2132
2133         /**
2134          * Detects if a given contact array belongs to a legacy DFRN connection
2135          *
2136          * @param array $contact
2137          * @return boolean
2138          */
2139         public static function isLegacyDFRNContact($contact)
2140         {
2141                 // Newer Friendica contacts are connected via AP, then these fields aren't set
2142                 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2143         }
2144
2145         /**
2146          * Detects the communication protocol for a given contact url.
2147          * This is used to detect Friendica contacts that we can communicate via AP.
2148          *
2149          * @param string $url contact url
2150          * @param string $network Network of that contact
2151          * @return string with protocol
2152          */
2153         public static function getProtocol($url, $network)
2154         {
2155                 if ($network != Protocol::DFRN) {
2156                         return $network;
2157                 }
2158
2159                 $apcontact = APContact::getByURL($url);
2160                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2161                         return Protocol::ACTIVITYPUB;
2162                 } else {
2163                         return $network;
2164                 }
2165         }
2166
2167         /**
2168          * Takes a $uid and a url/handle and adds a new contact
2169          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2170          * dfrn_request page.
2171          *
2172          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2173          *
2174          * Returns an array
2175          * $return['success'] boolean true if successful
2176          * $return['message'] error text if success is false.
2177          *
2178          * @brief Takes a $uid and a url/handle and adds a new contact
2179          * @param int    $uid
2180          * @param string $url
2181          * @param bool   $interactive
2182          * @param string $network
2183          * @return array
2184          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2185          * @throws \ImagickException
2186          */
2187         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2188         {
2189                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2190
2191                 $a = \get_app();
2192
2193                 // remove ajax junk, e.g. Twitter
2194                 $url = str_replace('/#!/', '/', $url);
2195
2196                 if (!Network::isUrlAllowed($url)) {
2197                         $result['message'] = L10n::t('Disallowed profile URL.');
2198                         return $result;
2199                 }
2200
2201                 if (Network::isUrlBlocked($url)) {
2202                         $result['message'] = L10n::t('Blocked domain');
2203                         return $result;
2204                 }
2205
2206                 if (!$url) {
2207                         $result['message'] = L10n::t('Connect URL missing.');
2208                         return $result;
2209                 }
2210
2211                 $arr = ['url' => $url, 'contact' => []];
2212
2213                 Hook::callAll('follow', $arr);
2214
2215                 if (empty($arr)) {
2216                         $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2217                         return $result;
2218                 }
2219
2220                 if (!empty($arr['contact']['name'])) {
2221                         $ret = $arr['contact'];
2222                 } else {
2223                         $ret = Probe::uri($url, $network, $uid, false);
2224                 }
2225
2226                 if (($network != '') && ($ret['network'] != $network)) {
2227                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2228                         return $result;
2229                 }
2230
2231                 // check if we already have a contact
2232                 // the poll url is more reliable than the profile url, as we may have
2233                 // indirect links or webfinger links
2234
2235                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2236                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2237                 if (!DBA::isResult($contact)) {
2238                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2239                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2240                 }
2241
2242                 $protocol = self::getProtocol($url, $ret['network']);
2243
2244                 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2245                         if ($interactive) {
2246                                 if (strlen($a->getURLPath())) {
2247                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2248                                 } else {
2249                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2250                                 }
2251
2252                                 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2253
2254                                 // NOTREACHED
2255                         }
2256                 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2257                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2258                         $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2259                         return $result;
2260                 }
2261
2262                 // This extra param just confuses things, remove it
2263                 if ($protocol === Protocol::DIASPORA) {
2264                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2265                 }
2266
2267                 // do we have enough information?
2268                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2269                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2270                         if (empty($ret['poll'])) {
2271                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2272                         }
2273                         if (empty($ret['name'])) {
2274                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2275                         }
2276                         if (empty($ret['url'])) {
2277                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2278                         }
2279                         if (strpos($url, '@') !== false) {
2280                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2281                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2282                         }
2283                         return $result;
2284                 }
2285
2286                 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2287                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2288                         $ret['notify'] = '';
2289                 }
2290
2291                 if (!$ret['notify']) {
2292                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2293                 }
2294
2295                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2296
2297                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2298
2299                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2300
2301                 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2302
2303                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2304                         $writeable = 1;
2305                 }
2306
2307                 if (DBA::isResult($contact)) {
2308                         // update contact
2309                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2310
2311                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2312                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2313                 } else {
2314                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2315
2316                         // create contact record
2317                         DBA::insert('contact', [
2318                                 'uid'     => $uid,
2319                                 'created' => DateTimeFormat::utcNow(),
2320                                 'url'     => $ret['url'],
2321                                 'nurl'    => Strings::normaliseLink($ret['url']),
2322                                 'addr'    => $ret['addr'],
2323                                 'alias'   => $ret['alias'],
2324                                 'batch'   => $ret['batch'],
2325                                 'notify'  => $ret['notify'],
2326                                 'poll'    => $ret['poll'],
2327                                 'poco'    => $ret['poco'],
2328                                 'name'    => $ret['name'],
2329                                 'nick'    => $ret['nick'],
2330                                 'network' => $ret['network'],
2331                                 'baseurl' => $ret['baseurl'],
2332                                 'protocol' => $protocol,
2333                                 'pubkey'  => $ret['pubkey'],
2334                                 'rel'     => $new_relation,
2335                                 'priority'=> $ret['priority'],
2336                                 'writable'=> $writeable,
2337                                 'hidden'  => $hidden,
2338                                 'blocked' => 0,
2339                                 'readonly'=> 0,
2340                                 'pending' => $pending,
2341                                 'subhub'  => $subhub
2342                         ]);
2343                 }
2344
2345                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2346                 if (!DBA::isResult($contact)) {
2347                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2348                         return $result;
2349                 }
2350
2351                 $contact_id = $contact['id'];
2352                 $result['cid'] = $contact_id;
2353
2354                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2355
2356                 // Update the avatar
2357                 self::updateAvatar($ret['photo'], $uid, $contact_id);
2358
2359                 // pull feed and consume it, which should subscribe to the hub.
2360
2361                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2362
2363                 $owner = User::getOwnerDataById($uid);
2364
2365                 if (DBA::isResult($owner)) {
2366                         if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2367                                 // create a follow slap
2368                                 $item = [];
2369                                 $item['verb'] = ACTIVITY_FOLLOW;
2370                                 $item['follow'] = $contact["url"];
2371                                 $item['body'] = '';
2372                                 $item['title'] = '';
2373                                 $item['guid'] = '';
2374                                 $item['tag'] = '';
2375                                 $item['attach'] = '';
2376
2377                                 $slap = OStatus::salmon($item, $owner);
2378
2379                                 if (!empty($contact['notify'])) {
2380                                         Salmon::slapper($owner, $contact['notify'], $slap);
2381                                 }
2382                         } elseif ($protocol == Protocol::DIASPORA) {
2383                                 $ret = Diaspora::sendShare($a->user, $contact);
2384                                 Logger::log('share returns: ' . $ret);
2385                         } elseif ($protocol == Protocol::ACTIVITYPUB) {
2386                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2387                                 if (empty($activity_id)) {
2388                                         // This really should never happen
2389                                         return false;
2390                                 }
2391
2392                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2393                                 Logger::log('Follow returns: ' . $ret);
2394                         }
2395                 }
2396
2397                 $result['success'] = true;
2398                 return $result;
2399         }
2400
2401         /**
2402          * @brief Updated contact's SSL policy
2403          *
2404          * @param array  $contact    Contact array
2405          * @param string $new_policy New policy, valid: self,full
2406          *
2407          * @return array Contact array with updated values
2408          * @throws \Exception
2409          */
2410         public static function updateSslPolicy(array $contact, $new_policy)
2411         {
2412                 $ssl_changed = false;
2413                 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2414                         $ssl_changed = true;
2415                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
2416                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
2417                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
2418                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
2419                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
2420                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
2421                 }
2422
2423                 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2424                         $ssl_changed = true;
2425                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
2426                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
2427                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
2428                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
2429                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
2430                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
2431                 }
2432
2433                 if ($ssl_changed) {
2434                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2435                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
2436                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2437                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2438                 }
2439
2440                 return $contact;
2441         }
2442
2443         /**
2444          * @param array  $importer Owner (local user) data
2445          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2446          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2447          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2448          * @param string $note     Introduction additional message
2449          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2450          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2451          * @throws \ImagickException
2452          */
2453         public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2454         {
2455                 // Should always be set
2456                 if (empty($datarray['author-id'])) {
2457                         return false;
2458                 }
2459
2460                 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2461                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2462                 if (!DBA::isResult($pub_contact)) {
2463                         // Should never happen
2464                         return false;
2465                 }
2466
2467                 // Contact is blocked at node-level
2468                 if (self::isBlocked($datarray['author-id'])) {
2469                         return false;
2470                 }
2471
2472                 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2473                 $name = $pub_contact['name'];
2474                 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2475                 $nick = $pub_contact['nick'];
2476                 $network = $pub_contact['network'];
2477
2478                 // Ensure that we don't create a new contact when there already is one
2479                 $cid = self::getIdForURL($url, $importer['uid']);
2480                 if (!empty($cid)) {
2481                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2482                 }
2483
2484                 if (!empty($contact)) {
2485                         if (!empty($contact['pending'])) {
2486                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2487                                 return null;
2488                         }
2489
2490                         // Contact is blocked at user-level
2491                         if (!empty($contact['id']) && !empty($importer['id']) &&
2492                                 self::isBlockedByUser($contact['id'], $importer['id'])) {
2493                                 return false;
2494                         }
2495
2496                         // Make sure that the existing contact isn't archived
2497                         self::unmarkForArchival($contact);
2498
2499                         if (($contact['rel'] == self::SHARING)
2500                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2501                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2502                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2503                         }
2504
2505                         return true;
2506                 } else {
2507                         // send email notification to owner?
2508                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2509                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2510                                 return null;
2511                         }
2512
2513                         // create contact record
2514                         DBA::insert('contact', [
2515                                 'uid'      => $importer['uid'],
2516                                 'created'  => DateTimeFormat::utcNow(),
2517                                 'url'      => $url,
2518                                 'nurl'     => Strings::normaliseLink($url),
2519                                 'name'     => $name,
2520                                 'nick'     => $nick,
2521                                 'photo'    => $photo,
2522                                 'network'  => $network,
2523                                 'rel'      => self::FOLLOWER,
2524                                 'blocked'  => 0,
2525                                 'readonly' => 0,
2526                                 'pending'  => 1,
2527                                 'writable' => 1,
2528                         ]);
2529
2530                         $contact_record = [
2531                                 'id' => DBA::lastInsertId(),
2532                                 'network' => $network,
2533                                 'name' => $name,
2534                                 'url' => $url,
2535                                 'photo' => $photo
2536                         ];
2537
2538                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2539
2540                         /// @TODO Encapsulate this into a function/method
2541                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2542                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2543                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2544                                 // create notification
2545                                 $hash = Strings::getRandomHex();
2546
2547                                 if (is_array($contact_record)) {
2548                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2549                                                                 'blocked' => false, 'knowyou' => false, 'note' => $note,
2550                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2551                                 }
2552
2553                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2554
2555                                 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2556                                         in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2557
2558                                         notification([
2559                                                 'type'         => NOTIFY_INTRO,
2560                                                 'notify_flags' => $user['notify-flags'],
2561                                                 'language'     => $user['language'],
2562                                                 'to_name'      => $user['username'],
2563                                                 'to_email'     => $user['email'],
2564                                                 'uid'          => $user['uid'],
2565                                                 'link'         => System::baseUrl() . '/notifications/intro',
2566                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2567                                                 'source_link'  => $contact_record['url'],
2568                                                 'source_photo' => $contact_record['photo'],
2569                                                 'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2570                                                 'otype'        => 'intro'
2571                                         ]);
2572                                 }
2573                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2574                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2575                                 DBA::update('contact', ['pending' => false], $condition);
2576
2577                                 return true;
2578                         }
2579                 }
2580
2581                 return null;
2582         }
2583
2584         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2585         {
2586                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2587                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2588                 } else {
2589                         Contact::remove($contact['id']);
2590                 }
2591         }
2592
2593         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2594         {
2595                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2596                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2597                 } else {
2598                         Contact::remove($contact['id']);
2599                 }
2600         }
2601
2602         /**
2603          * @brief Create a birthday event.
2604          *
2605          * Update the year and the birthday.
2606          */
2607         public static function updateBirthdays()
2608         {
2609                 $condition = [
2610                         '`bd` != ""
2611                         AND `bd` > "0001-01-01"
2612                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2613                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2614                         AND NOT `contact`.`pending`
2615                         AND NOT `contact`.`hidden`
2616                         AND NOT `contact`.`blocked`
2617                         AND NOT `contact`.`archive`
2618                         AND NOT `contact`.`deleted`',
2619                         Contact::SHARING,
2620                         Contact::FRIEND
2621                 ];
2622
2623                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2624
2625                 while ($contact = DBA::fetch($contacts)) {
2626                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2627
2628                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2629
2630                         if (Event::createBirthday($contact, $nextbd)) {
2631                                 // update bdyear
2632                                 DBA::update(
2633                                         'contact',
2634                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2635                                         ['id' => $contact['id']]
2636                                 );
2637                         }
2638                 }
2639         }
2640
2641         /**
2642          * Remove the unavailable contact ids from the provided list
2643          *
2644          * @param array $contact_ids Contact id list
2645          * @throws \Exception
2646          */
2647         public static function pruneUnavailable(array &$contact_ids)
2648         {
2649                 if (empty($contact_ids)) {
2650                         return;
2651                 }
2652
2653                 $str = DBA::escape(implode(',', $contact_ids));
2654
2655                 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2656
2657                 $return = [];
2658                 while($contact = DBA::fetch($stmt)) {
2659                         $return[] = $contact['id'];
2660                 }
2661
2662                 DBA::close($stmt);
2663
2664                 $contact_ids = $return;
2665         }
2666
2667         /**
2668          * @brief Returns a magic link to authenticate remote visitors
2669          *
2670          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2671          *
2672          * @param string $contact_url The address of the target contact profile
2673          * @param string $url         An url that we will be redirected to after the authentication
2674          *
2675          * @return string with "redir" link
2676          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2677          * @throws \ImagickException
2678          */
2679         public static function magicLink($contact_url, $url = '')
2680         {
2681                 if (!local_user() && !remote_user()) {
2682                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2683                 }
2684
2685                 $data = self::getProbeDataFromDatabase($contact_url);
2686                 if (empty($data)) {
2687                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2688                 }
2689
2690                 // Prevents endless loop in case only a non-public contact exists for the contact URL
2691                 unset($data['uid']);
2692
2693                 return self::magicLinkByContact($data, $contact_url);
2694         }
2695
2696         /**
2697          * @brief Returns a magic link to authenticate remote visitors
2698          *
2699          * @param integer $cid The contact id of the target contact profile
2700          * @param string  $url An url that we will be redirected to after the authentication
2701          *
2702          * @return string with "redir" link
2703          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2704          * @throws \ImagickException
2705          */
2706         public static function magicLinkbyId($cid, $url = '')
2707         {
2708                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2709
2710                 return self::magicLinkByContact($contact, $url);
2711         }
2712
2713         /**
2714          * @brief Returns a magic link to authenticate remote visitors
2715          *
2716          * @param array  $contact The contact array with "uid", "network" and "url"
2717          * @param string $url     An url that we will be redirected to after the authentication
2718          *
2719          * @return string with "redir" link
2720          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2721          * @throws \ImagickException
2722          */
2723         public static function magicLinkByContact($contact, $url = '')
2724         {
2725                 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2726                         return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2727                 }
2728
2729                 // Only redirections to the same host do make sense
2730                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2731                         return $url;
2732                 }
2733
2734                 if (!empty($contact['uid'])) {
2735                         return self::magicLink($contact['url'], $url);
2736                 }
2737
2738                 if (empty($contact['id'])) {
2739                         return $url ?: $contact['url'];
2740                 }
2741
2742                 $redirect = 'redir/' . $contact['id'];
2743
2744                 if ($url != '') {
2745                         $redirect .= '?url=' . $url;
2746                 }
2747
2748                 return $redirect;
2749         }
2750
2751         /**
2752          * Remove a contact from all groups
2753          *
2754          * @param integer $contact_id
2755          *
2756          * @return boolean Success
2757          */
2758         public static function removeFromGroups($contact_id)
2759         {
2760                 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2761         }
2762
2763         /**
2764          * Is the contact a forum?
2765          *
2766          * @param integer $contactid ID of the contact
2767          *
2768          * @return boolean "true" if it is a forum
2769          */
2770         public static function isForum($contactid)
2771         {
2772                 $fields = ['forum', 'prv'];
2773                 $condition = ['id' => $contactid];
2774                 $contact = DBA::selectFirst('contact', $fields, $condition);
2775                 if (!DBA::isResult($contact)) {
2776                         return false;
2777                 }
2778
2779                 // Is it a forum?
2780                 return ($contact['forum'] || $contact['prv']);
2781         }
2782
2783         /**
2784          * Can the remote contact receive private messages?
2785          *
2786          * @param array $contact
2787          * @return bool
2788          */
2789         public static function canReceivePrivateMessages(array $contact)
2790         {
2791                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2792                 $self = $contact['self'] ?? false;
2793
2794                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2795         }
2796 }