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