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