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