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