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