]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Update more PHPDoc, including in include/
[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          * @throws \Exception
1058          */
1059         public static function getUngroupedList($uid)
1060         {
1061                 return q("SELECT *
1062                            FROM `contact`
1063                            WHERE `uid` = %d
1064                            AND NOT `self`
1065                            AND NOT `deleted`
1066                            AND NOT `blocked`
1067                            AND NOT `pending`
1068                            AND `id` NOT IN (
1069                                 SELECT DISTINCT(`contact-id`)
1070                                 FROM `group_member`
1071                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1072                                 WHERE `group`.`uid` = %d
1073                            )", intval($uid), intval($uid));
1074         }
1075
1076         /**
1077          * @brief Fetch the contact id for a given URL and user
1078          *
1079          * First lookup in the contact table to find a record matching either `url`, `nurl`,
1080          * `addr` or `alias`.
1081          *
1082          * If there's no record and we aren't looking for a public contact, we quit.
1083          * If there's one, we check that it isn't time to update the picture else we
1084          * directly return the found contact id.
1085          *
1086          * Second, we probe the provided $url whether it's http://server.tld/profile or
1087          * nick@server.tld. We quit if we can't get any info back.
1088          *
1089          * Third, we create the contact record if it doesn't exist
1090          *
1091          * Fourth, we update the existing record with the new data (avatar, alias, nick)
1092          * if there's any updates
1093          *
1094          * @param string  $url       Contact URL
1095          * @param integer $uid       The user id for the contact (0 = public contact)
1096          * @param boolean $no_update Don't update the contact
1097          * @param array   $default   Default value for creating the contact when every else fails
1098          * @param boolean $in_loop   Internally used variable to prevent an endless loop
1099          *
1100          * @return integer Contact ID
1101          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1102          * @throws \ImagickException
1103          */
1104         public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1105         {
1106                 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1107
1108                 $contact_id = 0;
1109
1110                 if ($url == '') {
1111                         return 0;
1112                 }
1113
1114                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1115                 // We first try the nurl (http://server.tld/nick), most common case
1116                 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1117
1118                 // Then the addr (nick@server.tld)
1119                 if (!DBA::isResult($contact)) {
1120                         $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1121                 }
1122
1123                 // Then the alias (which could be anything)
1124                 if (!DBA::isResult($contact)) {
1125                         // The link could be provided as http although we stored it as https
1126                         $ssl_url = str_replace('http://', 'https://', $url);
1127                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1128                         $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1129                 }
1130
1131                 if (DBA::isResult($contact)) {
1132                         $contact_id = $contact["id"];
1133
1134                         // Update the contact every 7 days
1135                         $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1136
1137                         // We force the update if the avatar is empty
1138                         if (empty($contact['avatar'])) {
1139                                 $update_contact = true;
1140                         }
1141                         if (!$update_contact || $no_update) {
1142                                 return $contact_id;
1143                         }
1144                 } elseif ($uid != 0) {
1145                         // Non-existing user-specific contact, exiting
1146                         return 0;
1147                 }
1148
1149                 // When we don't want to update, we look if some of our users already know this contact
1150                 if ($no_update) {
1151                         $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1152                                 'photo', 'keywords', 'location', 'about', 'network',
1153                                 'priority', 'batch', 'request', 'confirm', 'poco'];
1154                         $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1155
1156                         if (DBA::isResult($data)) {
1157                                 // For security reasons we don't fetch key data from our users
1158                                 $data["pubkey"] = '';
1159                         }
1160                 } else {
1161                         $data = [];
1162                 }
1163
1164                 if (empty($data)) {
1165                         $data = Probe::uri($url, "", $uid);
1166
1167                         // Ensure that there is a gserver entry
1168                         if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1169                                 PortableContact::checkServer($data['baseurl']);
1170                         }
1171                 }
1172
1173                 // Last try in gcontact for unsupported networks
1174                 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1175                         if ($uid != 0) {
1176                                 return 0;
1177                         }
1178
1179                         // Get data from the gcontact table
1180                         $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1181                         $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1182                         if (!DBA::isResult($contact)) {
1183                                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1184                         }
1185
1186                         if (!DBA::isResult($contact)) {
1187                                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1188                                         'photo', 'keywords', 'location', 'about', 'network',
1189                                         'priority', 'batch', 'request', 'confirm', 'poco'];
1190                                 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1191                         }
1192
1193                         if (!DBA::isResult($contact)) {
1194                                 // The link could be provided as http although we stored it as https
1195                                 $ssl_url = str_replace('http://', 'https://', $url);
1196                                 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1197                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1198                         }
1199
1200                         if (!DBA::isResult($contact)) {
1201                                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1202                                         'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1203                                 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1204                                 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1205                         }
1206
1207                         if (!empty($default)) {
1208                                 $contact = $default;
1209                         }
1210
1211                         if (!DBA::isResult($contact)) {
1212                                 return 0;
1213                         } else {
1214                                 $data = array_merge($data, $contact);
1215                         }
1216                 }
1217
1218                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1219                         $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1220                 }
1221
1222                 $url = $data["url"];
1223                 if (!$contact_id) {
1224                         $fields = [
1225                                 'uid'       => $uid,
1226                                 'created'   => DateTimeFormat::utcNow(),
1227                                 'url'       => $data["url"],
1228                                 'nurl'      => Strings::normaliseLink($data["url"]),
1229                                 'addr'      => $data["addr"],
1230                                 'alias'     => $data["alias"],
1231                                 'notify'    => $data["notify"],
1232                                 'poll'      => $data["poll"],
1233                                 'name'      => $data["name"],
1234                                 'nick'      => $data["nick"],
1235                                 'photo'     => $data["photo"],
1236                                 'keywords'  => $data["keywords"],
1237                                 'location'  => $data["location"],
1238                                 'about'     => $data["about"],
1239                                 'network'   => $data["network"],
1240                                 'pubkey'    => $data["pubkey"],
1241                                 'rel'       => self::SHARING,
1242                                 'priority'  => $data["priority"],
1243                                 'batch'     => $data["batch"],
1244                                 'request'   => $data["request"],
1245                                 'confirm'   => $data["confirm"],
1246                                 'poco'      => $data["poco"],
1247                                 'name-date' => DateTimeFormat::utcNow(),
1248                                 'uri-date'  => DateTimeFormat::utcNow(),
1249                                 'avatar-date' => DateTimeFormat::utcNow(),
1250                                 'writable'  => 1,
1251                                 'blocked'   => 0,
1252                                 'readonly'  => 0,
1253                                 'pending'   => 0];
1254
1255                         $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1256
1257                         DBA::update('contact', $fields, $condition, true);
1258
1259                         $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1260                         $contacts = DBA::toArray($s);
1261                         if (!DBA::isResult($contacts)) {
1262                                 return 0;
1263                         }
1264
1265                         $contact_id = $contacts[0]["id"];
1266
1267                         // Update the newly created contact from data in the gcontact table
1268                         $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1269                         if (DBA::isResult($gcontact)) {
1270                                 // Only use the information when the probing hadn't fetched these values
1271                                 if ($data['keywords'] != '') {
1272                                         unset($gcontact['keywords']);
1273                                 }
1274                                 if ($data['location'] != '') {
1275                                         unset($gcontact['location']);
1276                                 }
1277                                 if ($data['about'] != '') {
1278                                         unset($gcontact['about']);
1279                                 }
1280                                 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1281                         }
1282
1283                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1284                                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1285                                         Strings::normaliseLink($data["url"]), 0, $contact_id];
1286                                 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1287                                 DBA::delete('contact', $condition);
1288                         }
1289                 }
1290
1291                 self::updateAvatar($data["photo"], $uid, $contact_id);
1292
1293                 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1294                 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1295
1296                 // This condition should always be true
1297                 if (!DBA::isResult($contact)) {
1298                         return $contact_id;
1299                 }
1300
1301                 $updated = ['addr' => $data['addr'],
1302                         'alias' => $data['alias'],
1303                         'url' => $data['url'],
1304                         'nurl' => Strings::normaliseLink($data['url']),
1305                         'name' => $data['name'],
1306                         'nick' => $data['nick']];
1307
1308                 if ($data['keywords'] != '') {
1309                         $updated['keywords'] = $data['keywords'];
1310                 }
1311                 if ($data['location'] != '') {
1312                         $updated['location'] = $data['location'];
1313                 }
1314
1315                 // Update the technical stuff as well - if filled
1316                 if ($data['notify'] != '') {
1317                         $updated['notify'] = $data['notify'];
1318                 }
1319                 if ($data['poll'] != '') {
1320                         $updated['poll'] = $data['poll'];
1321                 }
1322                 if ($data['batch'] != '') {
1323                         $updated['batch'] = $data['batch'];
1324                 }
1325                 if ($data['request'] != '') {
1326                         $updated['request'] = $data['request'];
1327                 }
1328                 if ($data['confirm'] != '') {
1329                         $updated['confirm'] = $data['confirm'];
1330                 }
1331                 if ($data['poco'] != '') {
1332                         $updated['poco'] = $data['poco'];
1333                 }
1334
1335                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1336                 if (empty($contact['pubkey'])) {
1337                         $updated['pubkey'] = $data['pubkey'];
1338                 }
1339
1340                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1341                         $updated['uri-date'] = DateTimeFormat::utcNow();
1342                 }
1343                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1344                         $updated['name-date'] = DateTimeFormat::utcNow();
1345                 }
1346
1347                 $updated['avatar-date'] = DateTimeFormat::utcNow();
1348
1349                 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1350
1351                 return $contact_id;
1352         }
1353
1354         /**
1355          * @brief Checks if the contact is blocked
1356          *
1357          * @param int $cid contact id
1358          *
1359          * @return boolean Is the contact blocked?
1360          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1361          */
1362         public static function isBlocked($cid)
1363         {
1364                 if ($cid == 0) {
1365                         return false;
1366                 }
1367
1368                 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1369                 if (!DBA::isResult($blocked)) {
1370                         return false;
1371                 }
1372
1373                 if (Network::isUrlBlocked($blocked['url'])) {
1374                         return true;
1375                 }
1376
1377                 return (bool) $blocked['blocked'];
1378         }
1379
1380         /**
1381          * @brief Checks if the contact is hidden
1382          *
1383          * @param int $cid contact id
1384          *
1385          * @return boolean Is the contact hidden?
1386          * @throws \Exception
1387          */
1388         public static function isHidden($cid)
1389         {
1390                 if ($cid == 0) {
1391                         return false;
1392                 }
1393
1394                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1395                 if (!DBA::isResult($hidden)) {
1396                         return false;
1397                 }
1398                 return (bool) $hidden['hidden'];
1399         }
1400
1401         /**
1402          * @brief Returns posts from a given contact url
1403          *
1404          * @param string $contact_url Contact URL
1405          *
1406          * @param bool   $thread_mode
1407          * @param int    $update
1408          * @return string posts in HTML
1409          * @throws \Exception
1410          */
1411         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1412         {
1413                 $a = self::getApp();
1414
1415                 $cid = Self::getIdForURL($contact_url);
1416
1417                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1418                 if (!DBA::isResult($contact)) {
1419                         return '';
1420                 }
1421
1422                 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1423                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1424                 } else {
1425                         $sql = "`item`.`uid` = ?";
1426                 }
1427
1428                 $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1429
1430                 if ($thread_mode) {
1431                         $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1432                                 $cid, GRAVITY_PARENT, local_user()];
1433                 } else {
1434                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1435                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1436                 }
1437
1438                 $pager = new Pager($a->query_string);
1439
1440                 $params = ['order' => ['created' => true],
1441                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1442
1443                 if ($thread_mode) {
1444                         $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1445
1446                         $items = Item::inArray($r);
1447
1448                         $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1449                 } else {
1450                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1451
1452                         $items = Item::inArray($r);
1453
1454                         $o = conversation($a, $items, $pager, 'contact-posts', false);
1455                 }
1456
1457                 if (!$update) {
1458                         $o .= $pager->renderMinimal(count($items));
1459                 }
1460
1461                 return $o;
1462         }
1463
1464         /**
1465          * @brief Returns the account type name
1466          *
1467          * The function can be called with either the user or the contact array
1468          *
1469          * @param array $contact contact or user array
1470          * @return string
1471          */
1472         public static function getAccountType(array $contact)
1473         {
1474                 // There are several fields that indicate that the contact or user is a forum
1475                 // "page-flags" is a field in the user table,
1476                 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1477                 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1478                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1479                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1480                         || (isset($contact['forum']) && intval($contact['forum']))
1481                         || (isset($contact['prv']) && intval($contact['prv']))
1482                         || (isset($contact['community']) && intval($contact['community']))
1483                 ) {
1484                         $type = self::ACCOUNT_TYPE_COMMUNITY;
1485                 } else {
1486                         $type = self::ACCOUNT_TYPE_PERSON;
1487                 }
1488
1489                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1490                 if (isset($contact["contact-type"])) {
1491                         $type = $contact["contact-type"];
1492                 }
1493
1494                 if (isset($contact["account-type"])) {
1495                         $type = $contact["account-type"];
1496                 }
1497
1498                 switch ($type) {
1499                         case self::ACCOUNT_TYPE_ORGANISATION:
1500                                 $account_type = L10n::t("Organisation");
1501                                 break;
1502
1503                         case self::ACCOUNT_TYPE_NEWS:
1504                                 $account_type = L10n::t('News');
1505                                 break;
1506
1507                         case self::ACCOUNT_TYPE_COMMUNITY:
1508                                 $account_type = L10n::t("Forum");
1509                                 break;
1510
1511                         default:
1512                                 $account_type = "";
1513                                 break;
1514                 }
1515
1516                 return $account_type;
1517         }
1518
1519         /**
1520          * @brief Blocks a contact
1521          *
1522          * @param int $uid
1523          * @return bool
1524          * @throws \Exception
1525          */
1526         public static function block($uid)
1527         {
1528                 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1529
1530                 return $return;
1531         }
1532
1533         /**
1534          * @brief Unblocks a contact
1535          *
1536          * @param int $uid
1537          * @return bool
1538          * @throws \Exception
1539          */
1540         public static function unblock($uid)
1541         {
1542                 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1543
1544                 return $return;
1545         }
1546
1547         /**
1548          * @brief Updates the avatar links in a contact only if needed
1549          *
1550          * @param string $avatar Link to avatar picture
1551          * @param int    $uid    User id of contact owner
1552          * @param int    $cid    Contact id
1553          * @param bool   $force  force picture update
1554          *
1555          * @return array Returns array of the different avatar sizes
1556          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1557          * @throws \ImagickException
1558          */
1559         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1560         {
1561                 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1562                 if (!DBA::isResult($contact)) {
1563                         return false;
1564                 } else {
1565                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1566                 }
1567
1568                 if (($contact["avatar"] != $avatar) || $force) {
1569                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1570
1571                         if ($photos) {
1572                                 DBA::update(
1573                                         'contact',
1574                                         ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1575                                         ['id' => $cid]
1576                                 );
1577
1578                                 // Update the public contact (contact id = 0)
1579                                 if ($uid != 0) {
1580                                         $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1581                                         if (DBA::isResult($pcontact)) {
1582                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1583                                         }
1584                                 }
1585
1586                                 return $photos;
1587                         }
1588                 }
1589
1590                 return $data;
1591         }
1592
1593         /**
1594          * @param integer $id      contact id
1595          * @param string  $network Optional network we are probing for
1596          * @return boolean
1597          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1598          * @throws \ImagickException
1599          */
1600         public static function updateFromProbe($id, $network = '')
1601         {
1602                 /*
1603                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1604                   This will reliably kill your communication with Friendica contacts.
1605                  */
1606
1607                 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1608                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1609                 if (!DBA::isResult($contact)) {
1610                         return false;
1611                 }
1612
1613                 $ret = Probe::uri($contact["url"], $network);
1614
1615                 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1616                 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, $network])) {
1617                         return false;
1618                 }
1619
1620                 $update = false;
1621
1622                 // make sure to not overwrite existing values with blank entries
1623                 foreach ($ret as $key => $val) {
1624                         if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1625                                 $ret[$key] = $contact[$key];
1626                         }
1627
1628                         if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1629                                 $update = true;
1630                         }
1631                 }
1632
1633                 if (!$update) {
1634                         return true;
1635                 }
1636
1637                 DBA::update(
1638                         'contact', [
1639                                 'url'     => $ret['url'],
1640                                 'nurl'    => Strings::normaliseLink($ret['url']),
1641                                 'network' => $ret['network'],
1642                                 'addr'    => $ret['addr'],
1643                                 'alias'   => $ret['alias'],
1644                                 'batch'   => $ret['batch'],
1645                                 'notify'  => $ret['notify'],
1646                                 'poll'    => $ret['poll'],
1647                                 'poco'    => $ret['poco']
1648                         ],
1649                         ['id' => $id]
1650                 );
1651
1652                 // Update the corresponding gcontact entry
1653                 PortableContact::lastUpdated($ret["url"]);
1654
1655                 return true;
1656         }
1657
1658         /**
1659          * Takes a $uid and a url/handle and adds a new contact
1660          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1661          * dfrn_request page.
1662          *
1663          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1664          *
1665          * Returns an array
1666          * $return['success'] boolean true if successful
1667          * $return['message'] error text if success is false.
1668          *
1669          * @brief Takes a $uid and a url/handle and adds a new contact
1670          * @param int    $uid
1671          * @param string $url
1672          * @param bool   $interactive
1673          * @param string $network
1674          * @return array
1675          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1676          * @throws \ImagickException
1677          */
1678         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1679         {
1680                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1681
1682                 $a = \get_app();
1683
1684                 // remove ajax junk, e.g. Twitter
1685                 $url = str_replace('/#!/', '/', $url);
1686
1687                 if (!Network::isUrlAllowed($url)) {
1688                         $result['message'] = L10n::t('Disallowed profile URL.');
1689                         return $result;
1690                 }
1691
1692                 if (Network::isUrlBlocked($url)) {
1693                         $result['message'] = L10n::t('Blocked domain');
1694                         return $result;
1695                 }
1696
1697                 if (!$url) {
1698                         $result['message'] = L10n::t('Connect URL missing.');
1699                         return $result;
1700                 }
1701
1702                 $arr = ['url' => $url, 'contact' => []];
1703
1704                 Hook::callAll('follow', $arr);
1705
1706                 if (empty($arr)) {
1707                         $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1708                         return $result;
1709                 }
1710
1711                 if (!empty($arr['contact']['name'])) {
1712                         $ret = $arr['contact'];
1713                 } else {
1714                         $ret = Probe::uri($url, $network, $uid, false);
1715                 }
1716
1717                 if (($network != '') && ($ret['network'] != $network)) {
1718                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1719                         return $result;
1720                 }
1721
1722                 // check if we already have a contact
1723                 // the poll url is more reliable than the profile url, as we may have
1724                 // indirect links or webfinger links
1725
1726                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1727                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1728                 if (!DBA::isResult($contact)) {
1729                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1730                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1731                 }
1732
1733                 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1734                         if ($interactive) {
1735                                 if (strlen($a->getURLPath())) {
1736                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1737                                 } else {
1738                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1739                                 }
1740
1741                                 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1742
1743                                 // NOTREACHED
1744                         }
1745                 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1746                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1747                         $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1748                         return $result;
1749                 }
1750
1751                 // This extra param just confuses things, remove it
1752                 if ($ret['network'] === Protocol::DIASPORA) {
1753                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1754                 }
1755
1756                 // do we have enough information?
1757                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1758                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1759                         if (empty($ret['poll'])) {
1760                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1761                         }
1762                         if (empty($ret['name'])) {
1763                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1764                         }
1765                         if (empty($ret['url'])) {
1766                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1767                         }
1768                         if (strpos($url, '@') !== false) {
1769                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1770                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1771                         }
1772                         return $result;
1773                 }
1774
1775                 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1776                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1777                         $ret['notify'] = '';
1778                 }
1779
1780                 if (!$ret['notify']) {
1781                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1782                 }
1783
1784                 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1785
1786                 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1787
1788                 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1789
1790                 $pending = in_array($ret['network'], [Protocol::ACTIVITYPUB]);
1791
1792                 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1793                         $writeable = 1;
1794                 }
1795
1796                 if (DBA::isResult($contact)) {
1797                         // update contact
1798                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1799
1800                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1801                         DBA::update('contact', $fields, ['id' => $contact['id']]);
1802                 } else {
1803                         $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1804
1805                         // create contact record
1806                         DBA::insert('contact', [
1807                                 'uid'     => $uid,
1808                                 'created' => DateTimeFormat::utcNow(),
1809                                 'url'     => $ret['url'],
1810                                 'nurl'    => Strings::normaliseLink($ret['url']),
1811                                 'addr'    => $ret['addr'],
1812                                 'alias'   => $ret['alias'],
1813                                 'batch'   => $ret['batch'],
1814                                 'notify'  => $ret['notify'],
1815                                 'poll'    => $ret['poll'],
1816                                 'poco'    => $ret['poco'],
1817                                 'name'    => $ret['name'],
1818                                 'nick'    => $ret['nick'],
1819                                 'network' => $ret['network'],
1820                                 'pubkey'  => $ret['pubkey'],
1821                                 'rel'     => $new_relation,
1822                                 'priority'=> $ret['priority'],
1823                                 'writable'=> $writeable,
1824                                 'hidden'  => $hidden,
1825                                 'blocked' => 0,
1826                                 'readonly'=> 0,
1827                                 'pending' => $pending,
1828                                 'subhub'  => $subhub
1829                         ]);
1830                 }
1831
1832                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1833                 if (!DBA::isResult($contact)) {
1834                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1835                         return $result;
1836                 }
1837
1838                 $contact_id = $contact['id'];
1839                 $result['cid'] = $contact_id;
1840
1841                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1842
1843                 // Update the avatar
1844                 self::updateAvatar($ret['photo'], $uid, $contact_id);
1845
1846                 // pull feed and consume it, which should subscribe to the hub.
1847
1848                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1849
1850                 $owner = User::getOwnerDataById($uid);
1851
1852                 if (DBA::isResult($owner)) {
1853                         if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1854                                 // create a follow slap
1855                                 $item = [];
1856                                 $item['verb'] = ACTIVITY_FOLLOW;
1857                                 $item['follow'] = $contact["url"];
1858                                 $item['body'] = '';
1859                                 $item['title'] = '';
1860                                 $item['guid'] = '';
1861                                 $item['tag'] = '';
1862                                 $item['attach'] = '';
1863
1864                                 $slap = OStatus::salmon($item, $owner);
1865
1866                                 if (!empty($contact['notify'])) {
1867                                         Salmon::slapper($owner, $contact['notify'], $slap);
1868                                 }
1869                         } elseif ($contact['network'] == Protocol::DIASPORA) {
1870                                 $ret = Diaspora::sendShare($a->user, $contact);
1871                                 Logger::log('share returns: ' . $ret);
1872                         } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1873                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
1874                                 if (empty($activity_id)) {
1875                                         // This really should never happen
1876                                         return false;
1877                                 }
1878
1879                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
1880                                 Logger::log('Follow returns: ' . $ret);
1881                         }
1882                 }
1883
1884                 $result['success'] = true;
1885                 return $result;
1886         }
1887
1888         /**
1889          * @brief Updated contact's SSL policy
1890          *
1891          * @param array  $contact    Contact array
1892          * @param string $new_policy New policy, valid: self,full
1893          *
1894          * @return array Contact array with updated values
1895          * @throws \Exception
1896          */
1897         public static function updateSslPolicy(array $contact, $new_policy)
1898         {
1899                 $ssl_changed = false;
1900                 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1901                         $ssl_changed = true;
1902                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
1903                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
1904                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
1905                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
1906                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
1907                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
1908                 }
1909
1910                 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1911                         $ssl_changed = true;
1912                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
1913                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
1914                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
1915                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
1916                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
1917                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
1918                 }
1919
1920                 if ($ssl_changed) {
1921                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1922                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
1923                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1924                         DBA::update('contact', $fields, ['id' => $contact['id']]);
1925                 }
1926
1927                 return $contact;
1928         }
1929
1930         public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1931                 // Should always be set
1932                 if (empty($datarray['author-id'])) {
1933                         return;
1934                 }
1935
1936                 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1937                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1938                 if (!DBA::isResult($pub_contact)) {
1939                         // Should never happen
1940                         return;
1941                 }
1942
1943                 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1944                 $name = $pub_contact['name'];
1945                 $photo = $pub_contact['photo'];
1946                 $nick = $pub_contact['nick'];
1947                 $network = $pub_contact['network'];
1948
1949                 if (is_array($contact)) {
1950                         if (($contact['rel'] == self::SHARING)
1951                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1952                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1953                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1954                         }
1955
1956                         if ($contact['network'] == Protocol::ACTIVITYPUB) {
1957                                 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1958                         }
1959
1960                         // send email notification to owner?
1961                 } else {
1962                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
1963                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1964                                 return;
1965                         }
1966                         // create contact record
1967                         q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1968                                 `blocked`, `readonly`, `pending`, `writable`)
1969                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1970                                 intval($importer['uid']),
1971                                 DBA::escape(DateTimeFormat::utcNow()),
1972                                 DBA::escape($url),
1973                                 DBA::escape(Strings::normaliseLink($url)),
1974                                 DBA::escape($name),
1975                                 DBA::escape($nick),
1976                                 DBA::escape($photo),
1977                                 DBA::escape($network),
1978                                 intval(self::FOLLOWER)
1979                         );
1980
1981                         $contact_record = [
1982                                 'id' => DBA::lastInsertId(),
1983                                 'network' => $network,
1984                                 'name' => $name,
1985                                 'url' => $url,
1986                                 'photo' => $photo
1987                         ];
1988
1989                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1990
1991                         /// @TODO Encapsulate this into a function/method
1992                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1993                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1994                         if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1995                                 // create notification
1996                                 $hash = Strings::getRandomHex();
1997
1998                                 if (is_array($contact_record)) {
1999                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2000                                                                 'blocked' => false, 'knowyou' => false,
2001                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2002                                 }
2003
2004                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2005
2006                                 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2007                                         in_array($user['page-flags'], [self::PAGE_NORMAL])) {
2008
2009                                         notification([
2010                                                 'type'         => NOTIFY_INTRO,
2011                                                 'notify_flags' => $user['notify-flags'],
2012                                                 'language'     => $user['language'],
2013                                                 'to_name'      => $user['username'],
2014                                                 'to_email'     => $user['email'],
2015                                                 'uid'          => $user['uid'],
2016                                                 'link'         => System::baseUrl() . '/notifications/intro',
2017                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2018                                                 'source_link'  => $contact_record['url'],
2019                                                 'source_photo' => $contact_record['photo'],
2020                                                 'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2021                                                 'otype'        => 'intro'
2022                                         ]);
2023
2024                                 }
2025                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
2026                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2027                                 DBA::update('contact', ['pending' => false], $condition);
2028
2029                                 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
2030
2031                                 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2032                                         ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2033                                 }
2034                         }
2035                 }
2036         }
2037
2038         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2039         {
2040                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2041                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2042                 } else {
2043                         Contact::remove($contact['id']);
2044                 }
2045         }
2046
2047         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2048         {
2049                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2050                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2051                 } else {
2052                         Contact::remove($contact['id']);
2053                 }
2054         }
2055
2056         /**
2057          * @brief Create a birthday event.
2058          *
2059          * Update the year and the birthday.
2060          */
2061         public static function updateBirthdays()
2062         {
2063                 $condition = [
2064                         '`bd` != ""
2065                         AND `bd` > "0001-01-01"
2066                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2067                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2068                         AND NOT `contact`.`pending`
2069                         AND NOT `contact`.`hidden`
2070                         AND NOT `contact`.`blocked`
2071                         AND NOT `contact`.`archive`
2072                         AND NOT `contact`.`deleted`',
2073                         Contact::SHARING,
2074                         Contact::FRIEND
2075                 ];
2076
2077                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2078
2079                 while ($contact = DBA::fetch($contacts)) {
2080                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2081
2082                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2083
2084                         if (Event::createBirthday($contact, $nextbd)) {
2085                                 // update bdyear
2086                                 DBA::update(
2087                                         'contact',
2088                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2089                                         ['id' => $contact['id']]
2090                                 );
2091                         }
2092                 }
2093         }
2094
2095         /**
2096          * Remove the unavailable contact ids from the provided list
2097          *
2098          * @param array $contact_ids Contact id list
2099          * @throws \Exception
2100          */
2101         public static function pruneUnavailable(array &$contact_ids)
2102         {
2103                 if (empty($contact_ids)) {
2104                         return;
2105                 }
2106
2107                 $str = DBA::escape(implode(',', $contact_ids));
2108
2109                 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2110
2111                 $return = [];
2112                 while($contact = DBA::fetch($stmt)) {
2113                         $return[] = $contact['id'];
2114                 }
2115
2116                 DBA::close($stmt);
2117
2118                 $contact_ids = $return;
2119         }
2120
2121         /**
2122          * @brief Returns a magic link to authenticate remote visitors
2123          *
2124          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2125          *
2126          * @param string $contact_url The address of the target contact profile
2127          * @param string $url         An url that we will be redirected to after the authentication
2128          *
2129          * @return string with "redir" link
2130          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2131          * @throws \ImagickException
2132          */
2133         public static function magicLink($contact_url, $url = '')
2134         {
2135                 if (!local_user() && !remote_user()) {
2136                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2137                 }
2138
2139                 $cid = self::getIdForURL($contact_url, 0, true);
2140                 if (empty($cid)) {
2141                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2142                 }
2143
2144                 return self::magicLinkbyId($cid, $url);
2145         }
2146
2147         /**
2148          * @brief Returns a magic link to authenticate remote visitors
2149          *
2150          * @param integer $cid The contact id of the target contact profile
2151          * @param string  $url An url that we will be redirected to after the authentication
2152          *
2153          * @return string with "redir" link
2154          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2155          * @throws \ImagickException
2156          */
2157         public static function magicLinkbyId($cid, $url = '')
2158         {
2159                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2160
2161                 return self::magicLinkbyContact($contact, $url);
2162         }
2163
2164         /**
2165          * @brief Returns a magic link to authenticate remote visitors
2166          *
2167          * @param array  $contact The contact array with "uid", "network" and "url"
2168          * @param string $url     An url that we will be redirected to after the authentication
2169          *
2170          * @return string with "redir" link
2171          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2172          * @throws \ImagickException
2173          */
2174         public static function magicLinkbyContact($contact, $url = '')
2175         {
2176                 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2177                         return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2178                 }
2179
2180                 // Only redirections to the same host do make sense
2181                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2182                         return $url;
2183                 }
2184
2185                 if ($contact['uid'] != 0) {
2186                         return self::magicLink($contact['url'], $url);
2187                 }
2188
2189                 $redirect = 'redir/' . $contact['id'];
2190
2191                 if ($url != '') {
2192                         $redirect .= '?url=' . $url;
2193                 }
2194
2195                 return $redirect;
2196         }
2197 }