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