3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\BaseObject;
8 use Friendica\Content\Pager;
9 use Friendica\Core\Config;
10 use Friendica\Core\Hook;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBA;
17 use Friendica\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Protocol\ActivityPub;
20 use Friendica\Protocol\DFRN;
21 use Friendica\Protocol\Diaspora;
22 use Friendica\Protocol\OStatus;
23 use Friendica\Protocol\PortableContact;
24 use Friendica\Protocol\Salmon;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
30 * @brief functions for interacting with a contact
32 class Contact extends BaseObject
37 * PAGE_NORMAL is a typical personal profile account
38 * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
39 * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
40 * write access to wall and comments (no email and not included in page owner's ACL lists)
41 * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
45 const PAGE_NORMAL = 0;
46 const PAGE_SOAPBOX = 1;
47 const PAGE_COMMUNITY = 2;
48 const PAGE_FREELOVE = 3;
50 const PAGE_PRVGROUP = 5;
58 * ACCOUNT_TYPE_PERSON - the account belongs to a person
59 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
61 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
62 * Associated page type: PAGE_SOAPBOX
64 * ACCOUNT_TYPE_NEWS - the account is a news reflector
65 * Associated page type: PAGE_SOAPBOX
67 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
68 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
70 * ACCOUNT_TYPE_RELAY - the account is a relay
71 * This will only be assigned to contacts, not to user accounts
74 const ACCOUNT_TYPE_PERSON = 0;
75 const ACCOUNT_TYPE_ORGANISATION = 1;
76 const ACCOUNT_TYPE_NEWS = 2;
77 const ACCOUNT_TYPE_COMMUNITY = 3;
78 const ACCOUNT_TYPE_RELAY = 4;
97 * @brief Tests if the given contact is a follower
99 * @param int $cid Either public contact id or user's contact id
100 * @param int $uid User ID
102 * @return boolean is the contact id a follower?
103 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
104 * @throws \ImagickException
106 public static function isFollower($cid, $uid)
108 if (self::isBlockedByUser($cid, $uid)) {
112 $cdata = self::getPublicAndUserContacID($cid, $uid);
113 if (empty($cdata['user'])) {
117 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
118 return DBA::exists('contact', $condition);
122 * @brief Get the basepath for a given contact link
123 * @todo Add functionality to store this value in the contact table
125 * @param string $url The contact link
127 * @return string basepath
128 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129 * @throws \ImagickException
131 public static function getBasepath($url)
133 $data = Probe::uri($url);
134 if (!empty($data['baseurl'])) {
135 return $data['baseurl'];
138 // When we can't probe the server, we use some ugly function that does some pattern matching
139 return PortableContact::detectServer($url);
143 * @brief Returns the contact id for the user and the public contact id for a given contact id
145 * @param int $cid Either public contact id or user's contact id
146 * @param int $uid User ID
148 * @return array with public and user's contact id
149 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
150 * @throws \ImagickException
152 public static function getPublicAndUserContacID($cid, $uid)
154 if (empty($uid) || empty($cid)) {
158 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
159 if (!DBA::isResult($contact)) {
163 // We quit when the user id don't match the user id of the provided contact
164 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
168 if ($contact['uid'] != 0) {
169 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
173 $ucid = $contact['id'];
175 $pcid = $contact['id'];
176 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
179 return ['public' => $pcid, 'user' => $ucid];
183 * @brief Block contact id for user id
185 * @param int $cid Either public contact id or user's contact id
186 * @param int $uid User ID
187 * @param boolean $blocked Is the contact blocked or unblocked?
190 public static function setBlockedForUser($cid, $uid, $blocked)
192 $cdata = self::getPublicAndUserContacID($cid, $uid);
197 if ($cdata['user'] != 0) {
198 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
201 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
205 * @brief Returns "block" state for contact id and user id
207 * @param int $cid Either public contact id or user's contact id
208 * @param int $uid User ID
210 * @return boolean is the contact id blocked for the given user?
213 public static function isBlockedByUser($cid, $uid)
215 $cdata = self::getPublicAndUserContacID($cid, $uid);
220 $public_blocked = false;
222 if (!empty($cdata['public'])) {
223 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
224 if (DBA::isResult($public_contact)) {
225 $public_blocked = $public_contact['blocked'];
229 $user_blocked = $public_blocked;
231 if (!empty($cdata['user'])) {
232 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
233 if (DBA::isResult($user_contact)) {
234 $user_blocked = $user_contact['blocked'];
238 if ($user_blocked != $public_blocked) {
239 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
242 return $user_blocked;
246 * @brief Ignore contact id for user id
248 * @param int $cid Either public contact id or user's contact id
249 * @param int $uid User ID
250 * @param boolean $ignored Is the contact ignored or unignored?
253 public static function setIgnoredForUser($cid, $uid, $ignored)
255 $cdata = self::getPublicAndUserContacID($cid, $uid);
260 if ($cdata['user'] != 0) {
261 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
264 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
268 * @brief Returns "ignore" state for contact id and user id
270 * @param int $cid Either public contact id or user's contact id
271 * @param int $uid User ID
273 * @return boolean is the contact id ignored for the given user?
276 public static function isIgnoredByUser($cid, $uid)
278 $cdata = self::getPublicAndUserContacID($cid, $uid);
283 $public_ignored = false;
285 if (!empty($cdata['public'])) {
286 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
287 if (DBA::isResult($public_contact)) {
288 $public_ignored = $public_contact['ignored'];
292 $user_ignored = $public_ignored;
294 if (!empty($cdata['user'])) {
295 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
296 if (DBA::isResult($user_contact)) {
297 $user_ignored = $user_contact['readonly'];
301 if ($user_ignored != $public_ignored) {
302 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
305 return $user_ignored;
309 * @brief Set "collapsed" for contact id and user id
311 * @param int $cid Either public contact id or user's contact id
312 * @param int $uid User ID
313 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
316 public static function setCollapsedForUser($cid, $uid, $collapsed)
318 $cdata = self::getPublicAndUserContacID($cid, $uid);
323 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
327 * @brief Returns "collapsed" state for contact id and user id
329 * @param int $cid Either public contact id or user's contact id
330 * @param int $uid User ID
332 * @return boolean is the contact id blocked for the given user?
333 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
334 * @throws \ImagickException
336 public static function isCollapsedByUser($cid, $uid)
338 $cdata = self::getPublicAndUserContacID($cid, $uid);
345 if (!empty($cdata['public'])) {
346 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
347 if (DBA::isResult($public_contact)) {
348 $collapsed = $public_contact['collapsed'];
356 * @brief Returns a list of contacts belonging in a group
362 public static function getByGroupId($gid)
367 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
369 INNER JOIN `group_member`
370 ON `contact`.`id` = `group_member`.`contact-id`
372 AND `contact`.`uid` = ?
373 AND NOT `contact`.`self`
374 AND NOT `contact`.`deleted`
375 AND NOT `contact`.`blocked`
376 AND NOT `contact`.`pending`
377 ORDER BY `contact`.`name` ASC',
382 if (DBA::isResult($stmt)) {
383 $return = DBA::toArray($stmt);
391 * @brief Returns the count of OStatus contacts in a group
397 public static function getOStatusCountByGroupId($gid)
401 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
403 INNER JOIN `group_member`
404 ON `contact`.`id` = `group_member`.`contact-id`
406 AND `contact`.`uid` = ?
407 AND `contact`.`network` = ?
408 AND `contact`.`notify` != ""',
413 $return = $contacts['count'];
420 * Creates the self-contact for the provided user id
423 * @return bool Operation success
424 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
426 public static function createSelfFromUserId($uid)
428 // Only create the entry if it doesn't exist yet
429 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
433 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
434 if (!DBA::isResult($user)) {
438 $return = DBA::insert('contact', [
439 'uid' => $user['uid'],
440 'created' => DateTimeFormat::utcNow(),
442 'name' => $user['username'],
443 'nick' => $user['nickname'],
444 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
445 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
446 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
449 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
450 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
451 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
452 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
453 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
454 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
455 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
456 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
457 'name-date' => DateTimeFormat::utcNow(),
458 'uri-date' => DateTimeFormat::utcNow(),
459 'avatar-date' => DateTimeFormat::utcNow(),
467 * Updates the self-contact for the provided user id
470 * @param boolean $update_avatar Force the avatar update
471 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
473 public static function updateSelfFromUserID($uid, $update_avatar = false)
475 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
476 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
477 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
478 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
479 if (!DBA::isResult($self)) {
483 $fields = ['nickname', 'page-flags', 'account-type'];
484 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
485 if (!DBA::isResult($user)) {
489 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
490 'country-name', 'gender', 'pub_keywords', 'xmpp'];
491 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
492 if (!DBA::isResult($profile)) {
496 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
497 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
498 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
499 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
500 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
502 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
503 if (DBA::isResult($avatar)) {
504 if ($update_avatar) {
505 $fields['avatar-date'] = DateTimeFormat::utcNow();
508 // Creating the path to the avatar, beginning with the file suffix
509 $types = Image::supportedTypes();
510 if (isset($types[$avatar['type']])) {
511 $file_suffix = $types[$avatar['type']];
513 $file_suffix = 'jpg';
516 // We are adding a timestamp value so that other systems won't use cached content
517 $timestamp = strtotime($fields['avatar-date']);
519 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
520 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
522 $fields['photo'] = $prefix . '4' . $suffix;
523 $fields['thumb'] = $prefix . '5' . $suffix;
524 $fields['micro'] = $prefix . '6' . $suffix;
526 // We hadn't found a photo entry, so we use the default avatar
527 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
528 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
529 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
532 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
533 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
535 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
536 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
537 $fields['nurl'] = Strings::normaliseLink($fields['url']);
538 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
539 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
540 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
541 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
542 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
543 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
547 foreach ($fields as $field => $content) {
548 if ($self[$field] != $content) {
554 $fields['name-date'] = DateTimeFormat::utcNow();
555 DBA::update('contact', $fields, ['id' => $self['id']]);
557 // Update the public contact as well
558 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
560 // Update the profile
561 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
562 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
563 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
568 * @brief Marks a contact for removal
570 * @param int $id contact id
572 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
574 public static function remove($id)
576 // We want just to make sure that we don't delete our "self" contact
577 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
578 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
582 // Archive the contact
583 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
585 // Delete it in the background
586 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
590 * @brief Sends an unfriend message. Does not remove the contact
592 * @param array $user User unfriending
593 * @param array $contact Contact unfriended
594 * @param boolean $dissolve Remove the contact on the remote side
596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
597 * @throws \ImagickException
599 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
601 if (empty($contact['network'])) {
604 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
605 DFRN::deliver($user, $contact, 'placeholder', true);
606 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
607 // create an unfollow slap
609 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
610 $item['follow'] = $contact["url"];
615 $item['attach'] = '';
616 $slap = OStatus::salmon($item, $user);
618 if (!empty($contact['notify'])) {
619 Salmon::slapper($user, $contact['notify'], $slap);
621 } elseif ($contact['network'] == Protocol::DIASPORA) {
622 Diaspora::sendUnshare($user, $contact);
623 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
624 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
627 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
633 * @brief Marks a contact for archival after a communication issue delay
635 * Contact has refused to recognise us as a friend. We will start a countdown.
636 * If they still don't recognise us in 32 days, the relationship is over,
637 * and we won't waste any more time trying to communicate with them.
638 * This provides for the possibility that their database is temporarily messed
639 * up or some other transient event and that there's a possibility we could recover from it.
641 * @param array $contact contact to mark for archival
643 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
645 public static function markForArchival(array $contact)
647 if (!isset($contact['url']) && !empty($contact['id'])) {
648 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
649 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
650 if (!DBA::isResult($contact)) {
653 } elseif (!isset($contact['url'])) {
654 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
657 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
659 // Contact already archived or "self" contact? => nothing to do
660 if ($contact['archive'] || $contact['self']) {
664 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
665 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
666 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
669 * We really should send a notification to the owner after 2-3 weeks
670 * so they won't be surprised when the contact vanishes and can take
671 * remedial action if this was a serious mistake or glitch
674 /// @todo Check for contact vitality via probing
675 $archival_days = Config::get('system', 'archival_days', 32);
677 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
678 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
679 /* Relationship is really truly dead. archive them rather than
680 * delete, though if the owner tries to unarchive them we'll start
681 * the whole process over again.
683 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
684 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
690 * @brief Cancels the archival countdown
692 * @see Contact::markForArchival()
694 * @param array $contact contact to be unmarked for archival
698 public static function unmarkForArchival(array $contact)
700 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
701 $exists = DBA::exists('contact', $condition);
703 // We don't need to update, we never marked this contact for archival
708 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
710 if (!isset($contact['url']) && !empty($contact['id'])) {
711 $fields = ['id', 'url', 'batch'];
712 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
713 if (!DBA::isResult($contact)) {
718 // It's a miracle. Our dead contact has inexplicably come back to life.
719 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
720 DBA::update('contact', $fields, ['id' => $contact['id']]);
721 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
723 if (!empty($contact['batch'])) {
724 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
725 DBA::update('contact', $fields, $condition);
730 * @brief Get contact data for a given profile link
732 * The function looks at several places (contact table and gcontact table) for the contact
733 * It caches its result for the same script execution to prevent duplicate calls
735 * @param string $url The profile link
736 * @param int $uid User id
737 * @param array $default If not data was found take this data as default value
739 * @return array Contact data
740 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
742 public static function getDetailsByURL($url, $uid = -1, array $default = [])
754 if (isset($cache[$url][$uid])) {
755 return $cache[$url][$uid];
758 $ssl_url = str_replace('http://', 'https://', $url);
760 // Fetch contact data from the contact table for the given user
761 $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`,
762 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
763 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
764 $r = DBA::toArray($s);
766 // Fetch contact data from the contact table for the given user, checking with the alias
767 if (!DBA::isResult($r)) {
768 $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`,
769 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
770 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
771 $r = DBA::toArray($s);
774 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
775 if (!DBA::isResult($r)) {
776 $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`,
777 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
778 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
779 $r = DBA::toArray($s);
782 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
783 if (!DBA::isResult($r)) {
784 $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`,
785 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
786 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
787 $r = DBA::toArray($s);
790 // Fetch the data from the gcontact table
791 if (!DBA::isResult($r)) {
792 $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`,
793 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
794 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
795 $r = DBA::toArray($s);
798 if (DBA::isResult($r)) {
799 // If there is more than one entry we filter out the connector networks
801 foreach ($r as $id => $result) {
802 if ($result["network"] == Protocol::STATUSNET) {
808 $profile = array_shift($r);
810 // "bd" always contains the upcoming birthday of a contact.
811 // "birthday" might contain the birthday including the year of birth.
812 if ($profile["birthday"] > DBA::NULL_DATE) {
813 $bd_timestamp = strtotime($profile["birthday"]);
814 $month = date("m", $bd_timestamp);
815 $day = date("d", $bd_timestamp);
817 $current_timestamp = time();
818 $current_year = date("Y", $current_timestamp);
819 $current_month = date("m", $current_timestamp);
820 $current_day = date("d", $current_timestamp);
822 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
823 $current = $current_year . "-" . $current_month . "-" . $current_day;
825 if ($profile["bd"] < $current) {
826 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
829 $profile["bd"] = DBA::NULL_DATE;
835 if (empty($profile["photo"]) && isset($default["photo"])) {
836 $profile["photo"] = $default["photo"];
839 if (empty($profile["name"]) && isset($default["name"])) {
840 $profile["name"] = $default["name"];
843 if (empty($profile["network"]) && isset($default["network"])) {
844 $profile["network"] = $default["network"];
847 if (empty($profile["thumb"]) && isset($profile["photo"])) {
848 $profile["thumb"] = $profile["photo"];
851 if (empty($profile["micro"]) && isset($profile["thumb"])) {
852 $profile["micro"] = $profile["thumb"];
855 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
856 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
858 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
861 // Show contact details of Diaspora contacts only if connected
862 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
863 $profile["location"] = "";
864 $profile["about"] = "";
865 $profile["gender"] = "";
866 $profile["birthday"] = DBA::NULL_DATE;
869 $cache[$url][$uid] = $profile;
875 * @brief Get contact data for a given address
877 * The function looks at several places (contact table and gcontact table) for the contact
879 * @param string $addr The profile link
880 * @param int $uid User id
882 * @return array Contact data
883 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
884 * @throws \ImagickException
886 public static function getDetailsByAddr($addr, $uid = -1)
898 // Fetch contact data from the contact table for the given user
899 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
900 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
901 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
905 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
906 if (!DBA::isResult($r)) {
907 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
908 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
909 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
914 // Fetch the data from the gcontact table
915 if (!DBA::isResult($r)) {
916 $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`,
917 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
918 FROM `gcontact` WHERE `addr` = '%s'",
923 if (!DBA::isResult($r)) {
924 $data = Probe::uri($addr);
926 $profile = self::getDetailsByURL($data['url'], $uid);
935 * @brief Returns the data array for the photo menu of a given contact
937 * @param array $contact contact
938 * @param int $uid optional, default 0
940 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
941 * @throws \ImagickException
943 public static function photoMenu(array $contact, $uid = 0)
945 // @todo Unused, to be removed
953 $contact_drop_link = '';
960 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
962 $profile_link = self::magicLink($contact['url']);
963 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
968 // Look for our own contact if the uid doesn't match and isn't public
969 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
970 if (DBA::isResult($contact_own)) {
971 return self::photoMenu($contact_own, $uid);
976 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
978 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
980 $profile_link = $contact['url'];
983 if ($profile_link === 'mailbox') {
988 $status_link = $profile_link . '?url=status';
989 $photos_link = $profile_link . '?url=photos';
990 $profile_link = $profile_link . '?url=profile';
993 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
994 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
997 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
998 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1001 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1003 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1005 if (!$contact['self']) {
1006 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1011 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1013 if (empty($contact['uid'])) {
1014 $connlnk = 'follow/?url=' . $contact['url'];
1016 'profile' => [L10n::t('View Profile'), $profile_link, true],
1017 'network' => [L10n::t('Network Posts'), $posts_link, false],
1018 'edit' => [L10n::t('View Contact'), $contact_url, false],
1019 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1023 'status' => [L10n::t('View Status'), $status_link, true],
1024 'profile' => [L10n::t('View Profile'), $profile_link, true],
1025 'photos' => [L10n::t('View Photos'), $photos_link, true],
1026 'network' => [L10n::t('Network Posts'), $posts_link, false],
1027 'edit' => [L10n::t('View Contact'), $contact_url, false],
1028 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1029 'pm' => [L10n::t('Send PM'), $pm_url, false],
1030 'poke' => [L10n::t('Poke'), $poke_link, false],
1034 $args = ['contact' => $contact, 'menu' => &$menu];
1036 Hook::callAll('contact_photo_menu', $args);
1038 $menucondensed = [];
1040 foreach ($menu as $menuname => $menuitem) {
1041 if ($menuitem[1] != '') {
1042 $menucondensed[$menuname] = $menuitem;
1046 return $menucondensed;
1050 * @brief Returns ungrouped contact count or list for user
1052 * Returns either the total number of ungrouped contacts for the given user
1053 * id or a paginated list of ungrouped contacts.
1055 * @param int $uid uid
1058 public static function getUngroupedList($uid)
1068 SELECT DISTINCT(`contact-id`)
1070 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1071 WHERE `group`.`uid` = %d
1072 )", intval($uid), intval($uid));
1076 * @brief Fetch the contact id for a given URL and user
1078 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1079 * `addr` or `alias`.
1081 * If there's no record and we aren't looking for a public contact, we quit.
1082 * If there's one, we check that it isn't time to update the picture else we
1083 * directly return the found contact id.
1085 * Second, we probe the provided $url whether it's http://server.tld/profile or
1086 * nick@server.tld. We quit if we can't get any info back.
1088 * Third, we create the contact record if it doesn't exist
1090 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1091 * if there's any updates
1093 * @param string $url Contact URL
1094 * @param integer $uid The user id for the contact (0 = public contact)
1095 * @param boolean $no_update Don't update the contact
1096 * @param array $default Default value for creating the contact when every else fails
1097 * @param boolean $in_loop Internally used variable to prevent an endless loop
1099 * @return integer Contact ID
1100 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1101 * @throws \ImagickException
1103 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1105 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1113 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1114 // We first try the nurl (http://server.tld/nick), most common case
1115 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1117 // Then the addr (nick@server.tld)
1118 if (!DBA::isResult($contact)) {
1119 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1122 // Then the alias (which could be anything)
1123 if (!DBA::isResult($contact)) {
1124 // The link could be provided as http although we stored it as https
1125 $ssl_url = str_replace('http://', 'https://', $url);
1126 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1127 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1130 if (DBA::isResult($contact)) {
1131 $contact_id = $contact["id"];
1133 // Update the contact every 7 days
1134 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1136 // We force the update if the avatar is empty
1137 if (empty($contact['avatar'])) {
1138 $update_contact = true;
1140 if (!$update_contact || $no_update) {
1143 } elseif ($uid != 0) {
1144 // Non-existing user-specific contact, exiting
1148 // When we don't want to update, we look if some of our users already know this contact
1150 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1151 'photo', 'keywords', 'location', 'about', 'network',
1152 'priority', 'batch', 'request', 'confirm', 'poco'];
1153 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1155 if (DBA::isResult($data)) {
1156 // For security reasons we don't fetch key data from our users
1157 $data["pubkey"] = '';
1164 $data = Probe::uri($url, "", $uid);
1166 // Ensure that there is a gserver entry
1167 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1168 PortableContact::checkServer($data['baseurl']);
1172 // Last try in gcontact for unsupported networks
1173 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1178 // Get data from the gcontact table
1179 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1180 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1181 if (!DBA::isResult($contact)) {
1182 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1185 if (!DBA::isResult($contact)) {
1186 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1187 'photo', 'keywords', 'location', 'about', 'network',
1188 'priority', 'batch', 'request', 'confirm', 'poco'];
1189 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1192 if (!DBA::isResult($contact)) {
1193 // The link could be provided as http although we stored it as https
1194 $ssl_url = str_replace('http://', 'https://', $url);
1195 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1196 $contact = DBA::selectFirst('contact', $fields, $condition);
1199 if (!DBA::isResult($contact)) {
1200 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1201 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1202 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1203 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1206 if (!empty($default)) {
1207 $contact = $default;
1210 if (!DBA::isResult($contact)) {
1213 $data = array_merge($data, $contact);
1217 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1218 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1221 $url = $data["url"];
1225 'created' => DateTimeFormat::utcNow(),
1226 'url' => $data["url"],
1227 'nurl' => Strings::normaliseLink($data["url"]),
1228 'addr' => $data["addr"],
1229 'alias' => $data["alias"],
1230 'notify' => $data["notify"],
1231 'poll' => $data["poll"],
1232 'name' => $data["name"],
1233 'nick' => $data["nick"],
1234 'photo' => $data["photo"],
1235 'keywords' => $data["keywords"],
1236 'location' => $data["location"],
1237 'about' => $data["about"],
1238 'network' => $data["network"],
1239 'pubkey' => $data["pubkey"],
1240 'rel' => self::SHARING,
1241 'priority' => $data["priority"],
1242 'batch' => $data["batch"],
1243 'request' => $data["request"],
1244 'confirm' => $data["confirm"],
1245 'poco' => $data["poco"],
1246 'name-date' => DateTimeFormat::utcNow(),
1247 'uri-date' => DateTimeFormat::utcNow(),
1248 'avatar-date' => DateTimeFormat::utcNow(),
1254 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1256 DBA::update('contact', $fields, $condition, true);
1258 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1259 $contacts = DBA::toArray($s);
1260 if (!DBA::isResult($contacts)) {
1264 $contact_id = $contacts[0]["id"];
1266 // Update the newly created contact from data in the gcontact table
1267 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1268 if (DBA::isResult($gcontact)) {
1269 // Only use the information when the probing hadn't fetched these values
1270 if ($data['keywords'] != '') {
1271 unset($gcontact['keywords']);
1273 if ($data['location'] != '') {
1274 unset($gcontact['location']);
1276 if ($data['about'] != '') {
1277 unset($gcontact['about']);
1279 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1282 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1283 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1284 Strings::normaliseLink($data["url"]), 0, $contact_id];
1285 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1286 DBA::delete('contact', $condition);
1290 self::updateAvatar($data["photo"], $uid, $contact_id);
1292 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1293 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1295 // This condition should always be true
1296 if (!DBA::isResult($contact)) {
1300 $updated = ['addr' => $data['addr'],
1301 'alias' => $data['alias'],
1302 'url' => $data['url'],
1303 'nurl' => Strings::normaliseLink($data['url']),
1304 'name' => $data['name'],
1305 'nick' => $data['nick']];
1307 if ($data['keywords'] != '') {
1308 $updated['keywords'] = $data['keywords'];
1310 if ($data['location'] != '') {
1311 $updated['location'] = $data['location'];
1314 // Update the technical stuff as well - if filled
1315 if ($data['notify'] != '') {
1316 $updated['notify'] = $data['notify'];
1318 if ($data['poll'] != '') {
1319 $updated['poll'] = $data['poll'];
1321 if ($data['batch'] != '') {
1322 $updated['batch'] = $data['batch'];
1324 if ($data['request'] != '') {
1325 $updated['request'] = $data['request'];
1327 if ($data['confirm'] != '') {
1328 $updated['confirm'] = $data['confirm'];
1330 if ($data['poco'] != '') {
1331 $updated['poco'] = $data['poco'];
1334 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1335 if (empty($contact['pubkey'])) {
1336 $updated['pubkey'] = $data['pubkey'];
1339 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1340 $updated['uri-date'] = DateTimeFormat::utcNow();
1342 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1343 $updated['name-date'] = DateTimeFormat::utcNow();
1346 $updated['avatar-date'] = DateTimeFormat::utcNow();
1348 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1354 * @brief Checks if the contact is blocked
1356 * @param int $cid contact id
1358 * @return boolean Is the contact blocked?
1359 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1361 public static function isBlocked($cid)
1367 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1368 if (!DBA::isResult($blocked)) {
1372 if (Network::isUrlBlocked($blocked['url'])) {
1376 return (bool) $blocked['blocked'];
1380 * @brief Checks if the contact is hidden
1382 * @param int $cid contact id
1384 * @return boolean Is the contact hidden?
1385 * @throws \Exception
1387 public static function isHidden($cid)
1393 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1394 if (!DBA::isResult($hidden)) {
1397 return (bool) $hidden['hidden'];
1401 * @brief Returns posts from a given contact url
1403 * @param string $contact_url Contact URL
1405 * @param bool $thread_mode
1406 * @param int $update
1407 * @return string posts in HTML
1408 * @throws \Exception
1410 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1412 $a = self::getApp();
1414 $cid = Self::getIdForURL($contact_url);
1416 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1417 if (!DBA::isResult($contact)) {
1421 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1422 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1424 $sql = "`item`.`uid` = ?";
1427 $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1430 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1431 $cid, GRAVITY_PARENT, local_user()];
1433 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1434 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1437 $pager = new Pager($a->query_string);
1439 $params = ['order' => ['created' => true],
1440 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1443 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1445 $items = Item::inArray($r);
1447 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1449 $r = Item::selectForUser(local_user(), [], $condition, $params);
1451 $items = Item::inArray($r);
1453 $o = conversation($a, $items, $pager, 'contact-posts', false);
1457 $o .= $pager->renderMinimal(count($items));
1464 * @brief Returns the account type name
1466 * The function can be called with either the user or the contact array
1468 * @param array $contact contact or user array
1471 public static function getAccountType(array $contact)
1473 // There are several fields that indicate that the contact or user is a forum
1474 // "page-flags" is a field in the user table,
1475 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1476 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1477 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1478 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1479 || (isset($contact['forum']) && intval($contact['forum']))
1480 || (isset($contact['prv']) && intval($contact['prv']))
1481 || (isset($contact['community']) && intval($contact['community']))
1483 $type = self::ACCOUNT_TYPE_COMMUNITY;
1485 $type = self::ACCOUNT_TYPE_PERSON;
1488 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1489 if (isset($contact["contact-type"])) {
1490 $type = $contact["contact-type"];
1493 if (isset($contact["account-type"])) {
1494 $type = $contact["account-type"];
1498 case self::ACCOUNT_TYPE_ORGANISATION:
1499 $account_type = L10n::t("Organisation");
1502 case self::ACCOUNT_TYPE_NEWS:
1503 $account_type = L10n::t('News');
1506 case self::ACCOUNT_TYPE_COMMUNITY:
1507 $account_type = L10n::t("Forum");
1515 return $account_type;
1519 * @brief Blocks a contact
1523 * @throws \Exception
1525 public static function block($uid)
1527 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1533 * @brief Unblocks a contact
1537 * @throws \Exception
1539 public static function unblock($uid)
1541 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1547 * @brief Updates the avatar links in a contact only if needed
1549 * @param string $avatar Link to avatar picture
1550 * @param int $uid User id of contact owner
1551 * @param int $cid Contact id
1552 * @param bool $force force picture update
1554 * @return array Returns array of the different avatar sizes
1555 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1556 * @throws \ImagickException
1558 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1560 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1561 if (!DBA::isResult($contact)) {
1564 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1567 if (($contact["avatar"] != $avatar) || $force) {
1568 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1573 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1577 // Update the public contact (contact id = 0)
1579 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1580 if (DBA::isResult($pcontact)) {
1581 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1593 * @param integer $id contact id
1594 * @param string $network Optional network we are probing for
1596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1597 * @throws \ImagickException
1599 public static function updateFromProbe($id, $network = '')
1602 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1603 This will reliably kill your communication with Friendica contacts.
1606 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1607 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1608 if (!DBA::isResult($contact)) {
1612 $ret = Probe::uri($contact["url"], $network);
1614 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1615 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, $network])) {
1621 // make sure to not overwrite existing values with blank entries
1622 foreach ($ret as $key => $val) {
1623 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1624 $ret[$key] = $contact[$key];
1627 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1638 'url' => $ret['url'],
1639 'nurl' => Strings::normaliseLink($ret['url']),
1640 'network' => $ret['network'],
1641 'addr' => $ret['addr'],
1642 'alias' => $ret['alias'],
1643 'batch' => $ret['batch'],
1644 'notify' => $ret['notify'],
1645 'poll' => $ret['poll'],
1646 'poco' => $ret['poco']
1651 // Update the corresponding gcontact entry
1652 PortableContact::lastUpdated($ret["url"]);
1658 * Takes a $uid and a url/handle and adds a new contact
1659 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1660 * dfrn_request page.
1662 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1665 * $return['success'] boolean true if successful
1666 * $return['message'] error text if success is false.
1668 * @brief Takes a $uid and a url/handle and adds a new contact
1670 * @param string $url
1671 * @param bool $interactive
1672 * @param string $network
1674 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1675 * @throws \ImagickException
1677 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1679 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1683 // remove ajax junk, e.g. Twitter
1684 $url = str_replace('/#!/', '/', $url);
1686 if (!Network::isUrlAllowed($url)) {
1687 $result['message'] = L10n::t('Disallowed profile URL.');
1691 if (Network::isUrlBlocked($url)) {
1692 $result['message'] = L10n::t('Blocked domain');
1697 $result['message'] = L10n::t('Connect URL missing.');
1701 $arr = ['url' => $url, 'contact' => []];
1703 Hook::callAll('follow', $arr);
1706 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1710 if (!empty($arr['contact']['name'])) {
1711 $ret = $arr['contact'];
1713 $ret = Probe::uri($url, $network, $uid, false);
1716 if (($network != '') && ($ret['network'] != $network)) {
1717 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1721 // check if we already have a contact
1722 // the poll url is more reliable than the profile url, as we may have
1723 // indirect links or webfinger links
1725 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1726 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1727 if (!DBA::isResult($contact)) {
1728 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1729 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1732 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1734 if (strlen($a->getURLPath())) {
1735 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1737 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1740 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1744 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1745 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1746 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1750 // This extra param just confuses things, remove it
1751 if ($ret['network'] === Protocol::DIASPORA) {
1752 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1755 // do we have enough information?
1756 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1757 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1758 if (empty($ret['poll'])) {
1759 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1761 if (empty($ret['name'])) {
1762 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1764 if (empty($ret['url'])) {
1765 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1767 if (strpos($url, '@') !== false) {
1768 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1769 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1774 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1775 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1776 $ret['notify'] = '';
1779 if (!$ret['notify']) {
1780 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1783 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1785 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1787 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1789 $pending = in_array($ret['network'], [Protocol::ACTIVITYPUB]);
1791 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1795 if (DBA::isResult($contact)) {
1797 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1799 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1800 DBA::update('contact', $fields, ['id' => $contact['id']]);
1802 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1804 // create contact record
1805 DBA::insert('contact', [
1807 'created' => DateTimeFormat::utcNow(),
1808 'url' => $ret['url'],
1809 'nurl' => Strings::normaliseLink($ret['url']),
1810 'addr' => $ret['addr'],
1811 'alias' => $ret['alias'],
1812 'batch' => $ret['batch'],
1813 'notify' => $ret['notify'],
1814 'poll' => $ret['poll'],
1815 'poco' => $ret['poco'],
1816 'name' => $ret['name'],
1817 'nick' => $ret['nick'],
1818 'network' => $ret['network'],
1819 'pubkey' => $ret['pubkey'],
1820 'rel' => $new_relation,
1821 'priority'=> $ret['priority'],
1822 'writable'=> $writeable,
1823 'hidden' => $hidden,
1826 'pending' => $pending,
1831 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1832 if (!DBA::isResult($contact)) {
1833 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1837 $contact_id = $contact['id'];
1838 $result['cid'] = $contact_id;
1840 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1842 // Update the avatar
1843 self::updateAvatar($ret['photo'], $uid, $contact_id);
1845 // pull feed and consume it, which should subscribe to the hub.
1847 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1849 $owner = User::getOwnerDataById($uid);
1851 if (DBA::isResult($owner)) {
1852 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1853 // create a follow slap
1855 $item['verb'] = ACTIVITY_FOLLOW;
1856 $item['follow'] = $contact["url"];
1858 $item['title'] = '';
1861 $item['attach'] = '';
1863 $slap = OStatus::salmon($item, $owner);
1865 if (!empty($contact['notify'])) {
1866 Salmon::slapper($owner, $contact['notify'], $slap);
1868 } elseif ($contact['network'] == Protocol::DIASPORA) {
1869 $ret = Diaspora::sendShare($a->user, $contact);
1870 Logger::log('share returns: ' . $ret);
1871 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1872 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
1873 if (empty($activity_id)) {
1874 // This really should never happen
1878 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
1879 Logger::log('Follow returns: ' . $ret);
1883 $result['success'] = true;
1888 * @brief Updated contact's SSL policy
1890 * @param array $contact Contact array
1891 * @param string $new_policy New policy, valid: self,full
1893 * @return array Contact array with updated values
1894 * @throws \Exception
1896 public static function updateSslPolicy(array $contact, $new_policy)
1898 $ssl_changed = false;
1899 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1900 $ssl_changed = true;
1901 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1902 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1903 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1904 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1905 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1906 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1909 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1910 $ssl_changed = true;
1911 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1912 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1913 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1914 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1915 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1916 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1920 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1921 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1922 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1923 DBA::update('contact', $fields, ['id' => $contact['id']]);
1929 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1930 // Should always be set
1931 if (empty($datarray['author-id'])) {
1935 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1936 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1937 if (!DBA::isResult($pub_contact)) {
1938 // Should never happen
1942 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1943 $name = $pub_contact['name'];
1944 $photo = $pub_contact['photo'];
1945 $nick = $pub_contact['nick'];
1946 $network = $pub_contact['network'];
1948 if (is_array($contact)) {
1949 if (($contact['rel'] == self::SHARING)
1950 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1951 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1952 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1955 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1956 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1959 // send email notification to owner?
1961 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
1962 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1965 // create contact record
1966 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1967 `blocked`, `readonly`, `pending`, `writable`)
1968 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1969 intval($importer['uid']),
1970 DBA::escape(DateTimeFormat::utcNow()),
1972 DBA::escape(Strings::normaliseLink($url)),
1975 DBA::escape($photo),
1976 DBA::escape($network),
1977 intval(self::FOLLOWER)
1981 'id' => DBA::lastInsertId(),
1982 'network' => $network,
1988 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1990 /// @TODO Encapsulate this into a function/method
1991 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1992 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1993 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1994 // create notification
1995 $hash = Strings::getRandomHex();
1997 if (is_array($contact_record)) {
1998 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1999 'blocked' => false, 'knowyou' => false,
2000 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2003 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2005 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2006 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
2009 'type' => NOTIFY_INTRO,
2010 'notify_flags' => $user['notify-flags'],
2011 'language' => $user['language'],
2012 'to_name' => $user['username'],
2013 'to_email' => $user['email'],
2014 'uid' => $user['uid'],
2015 'link' => System::baseUrl() . '/notifications/intro',
2016 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2017 'source_link' => $contact_record['url'],
2018 'source_photo' => $contact_record['photo'],
2019 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2024 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
2025 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2026 DBA::update('contact', ['pending' => false], $condition);
2028 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
2030 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2031 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2037 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2039 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2040 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2042 Contact::remove($contact['id']);
2046 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2048 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2049 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2051 Contact::remove($contact['id']);
2056 * @brief Create a birthday event.
2058 * Update the year and the birthday.
2060 public static function updateBirthdays()
2064 AND `bd` > "0001-01-01"
2065 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2066 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2067 AND NOT `contact`.`pending`
2068 AND NOT `contact`.`hidden`
2069 AND NOT `contact`.`blocked`
2070 AND NOT `contact`.`archive`
2071 AND NOT `contact`.`deleted`',
2076 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2078 while ($contact = DBA::fetch($contacts)) {
2079 Logger::log('update_contact_birthday: ' . $contact['bd']);
2081 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2083 if (Event::createBirthday($contact, $nextbd)) {
2087 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2088 ['id' => $contact['id']]
2095 * Remove the unavailable contact ids from the provided list
2097 * @param array $contact_ids Contact id list
2098 * @throws \Exception
2100 public static function pruneUnavailable(array &$contact_ids)
2102 if (empty($contact_ids)) {
2106 $str = DBA::escape(implode(',', $contact_ids));
2108 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2111 while($contact = DBA::fetch($stmt)) {
2112 $return[] = $contact['id'];
2117 $contact_ids = $return;
2121 * @brief Returns a magic link to authenticate remote visitors
2123 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2125 * @param string $contact_url The address of the target contact profile
2126 * @param string $url An url that we will be redirected to after the authentication
2128 * @return string with "redir" link
2129 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2130 * @throws \ImagickException
2132 public static function magicLink($contact_url, $url = '')
2134 if (!local_user() && !remote_user()) {
2135 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2138 $cid = self::getIdForURL($contact_url, 0, true);
2140 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2143 return self::magicLinkbyId($cid, $url);
2147 * @brief Returns a magic link to authenticate remote visitors
2149 * @param integer $cid The contact id of the target contact profile
2150 * @param string $url An url that we will be redirected to after the authentication
2152 * @return string with "redir" link
2153 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2154 * @throws \ImagickException
2156 public static function magicLinkbyId($cid, $url = '')
2158 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2160 return self::magicLinkbyContact($contact, $url);
2164 * @brief Returns a magic link to authenticate remote visitors
2166 * @param array $contact The contact array with "uid", "network" and "url"
2167 * @param string $url An url that we will be redirected to after the authentication
2169 * @return string with "redir" link
2170 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2171 * @throws \ImagickException
2173 public static function magicLinkbyContact($contact, $url = '')
2175 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2176 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2179 // Only redirections to the same host do make sense
2180 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2184 if ($contact['uid'] != 0) {
2185 return self::magicLink($contact['url'], $url);
2188 $redirect = 'redir/' . $contact['id'];
2191 $redirect .= '?url=' . $url;