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