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