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