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