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