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