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\BaseURL;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
31 * @brief functions for interacting with a contact
33 class Contact extends BaseObject
36 * @deprecated since version 2019.03
37 * @see User::PAGE_FLAGS_NORMAL
39 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
41 * @deprecated since version 2019.03
42 * @see User::PAGE_FLAGS_SOAPBOX
44 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
46 * @deprecated since version 2019.03
47 * @see User::PAGE_FLAGS_COMMUNITY
49 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
51 * @deprecated since version 2019.03
52 * @see User::PAGE_FLAGS_FREELOVE
54 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
56 * @deprecated since version 2019.03
57 * @see User::PAGE_FLAGS_BLOG
59 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
61 * @deprecated since version 2019.03
62 * @see User::PAGE_FLAGS_PRVGROUP
64 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
72 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
74 * TYPE_PERSON - the account belongs to a person
75 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
77 * TYPE_ORGANISATION - the account belongs to an organisation
78 * Associated page type: PAGE_SOAPBOX
80 * TYPE_NEWS - the account is a news reflector
81 * Associated page type: PAGE_SOAPBOX
83 * TYPE_COMMUNITY - the account is community forum
84 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
86 * TYPE_RELAY - the account is a relay
87 * This will only be assigned to contacts, not to user accounts
90 const TYPE_UNKNOWN = -1;
91 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
92 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
93 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
94 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
95 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
115 * @return array|boolean Contact record if it exists, false otherwise
118 public static function getById($id)
120 return DBA::selectFirst('contact', [], ['id' => $id]);
124 * @brief Tests if the given contact is a follower
126 * @param int $cid Either public contact id or user's contact id
127 * @param int $uid User ID
129 * @return boolean is the contact id a follower?
130 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
131 * @throws \ImagickException
133 public static function isFollower($cid, $uid)
135 if (self::isBlockedByUser($cid, $uid)) {
139 $cdata = self::getPublicAndUserContacID($cid, $uid);
140 if (empty($cdata['user'])) {
144 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
145 return DBA::exists('contact', $condition);
149 * @brief Get the basepath for a given contact link
150 * @todo Add functionality to store this value in the contact table
152 * @param string $url The contact link
154 * @return string basepath
155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
156 * @throws \ImagickException
158 public static function getBasepath($url)
160 $data = Probe::uri($url);
161 if (!empty($data['baseurl'])) {
162 return $data['baseurl'];
165 // When we can't probe the server, we use some ugly function that does some pattern matching
166 return PortableContact::detectServer($url);
170 * Returns the public contact id of the given user id
172 * @param integer $uid User ID
174 * @return integer|boolean Public contact id for given user id
177 public static function getPublicIdByUserId($uid)
179 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
180 if (!DBA::isResult($self)) {
183 return self::getIdForURL($self['url'], 0, true);
187 * @brief Returns the contact id for the user and the public contact id for a given contact id
189 * @param int $cid Either public contact id or user's contact id
190 * @param int $uid User ID
192 * @return array with public and user's contact id
193 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
194 * @throws \ImagickException
196 public static function getPublicAndUserContacID($cid, $uid)
198 if (empty($uid) || empty($cid)) {
202 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
203 if (!DBA::isResult($contact)) {
207 // We quit when the user id don't match the user id of the provided contact
208 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
212 if ($contact['uid'] != 0) {
213 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
217 $ucid = $contact['id'];
219 $pcid = $contact['id'];
220 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
223 return ['public' => $pcid, 'user' => $ucid];
227 * @brief Block contact id for user id
229 * @param int $cid Either public contact id or user's contact id
230 * @param int $uid User ID
231 * @param boolean $blocked Is the contact blocked or unblocked?
234 public static function setBlockedForUser($cid, $uid, $blocked)
236 $cdata = self::getPublicAndUserContacID($cid, $uid);
241 if ($cdata['user'] != 0) {
242 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
245 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
248 // Blocked contact can't be in any group
249 self::removeFromGroups($cid);
254 * @brief Returns "block" state for contact id and user id
256 * @param int $cid Either public contact id or user's contact id
257 * @param int $uid User ID
259 * @return boolean is the contact id blocked for the given user?
262 public static function isBlockedByUser($cid, $uid)
264 $cdata = self::getPublicAndUserContacID($cid, $uid);
269 $public_blocked = false;
271 if (!empty($cdata['public'])) {
272 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
273 if (DBA::isResult($public_contact)) {
274 $public_blocked = $public_contact['blocked'];
278 $user_blocked = $public_blocked;
280 if (!empty($cdata['user'])) {
281 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
282 if (DBA::isResult($user_contact)) {
283 $user_blocked = $user_contact['blocked'];
287 if ($user_blocked != $public_blocked) {
288 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
291 return $user_blocked;
295 * @brief Ignore contact id for user id
297 * @param int $cid Either public contact id or user's contact id
298 * @param int $uid User ID
299 * @param boolean $ignored Is the contact ignored or unignored?
302 public static function setIgnoredForUser($cid, $uid, $ignored)
304 $cdata = self::getPublicAndUserContacID($cid, $uid);
309 if ($cdata['user'] != 0) {
310 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
313 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
317 * @brief Returns "ignore" state for contact id and user id
319 * @param int $cid Either public contact id or user's contact id
320 * @param int $uid User ID
322 * @return boolean is the contact id ignored for the given user?
325 public static function isIgnoredByUser($cid, $uid)
327 $cdata = self::getPublicAndUserContacID($cid, $uid);
332 $public_ignored = false;
334 if (!empty($cdata['public'])) {
335 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
336 if (DBA::isResult($public_contact)) {
337 $public_ignored = $public_contact['ignored'];
341 $user_ignored = $public_ignored;
343 if (!empty($cdata['user'])) {
344 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
345 if (DBA::isResult($user_contact)) {
346 $user_ignored = $user_contact['readonly'];
350 if ($user_ignored != $public_ignored) {
351 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
354 return $user_ignored;
358 * @brief Set "collapsed" for contact id and user id
360 * @param int $cid Either public contact id or user's contact id
361 * @param int $uid User ID
362 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
365 public static function setCollapsedForUser($cid, $uid, $collapsed)
367 $cdata = self::getPublicAndUserContacID($cid, $uid);
372 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
376 * @brief Returns "collapsed" state for contact id and user id
378 * @param int $cid Either public contact id or user's contact id
379 * @param int $uid User ID
381 * @return boolean is the contact id blocked for the given user?
382 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
383 * @throws \ImagickException
385 public static function isCollapsedByUser($cid, $uid)
387 $cdata = self::getPublicAndUserContacID($cid, $uid);
394 if (!empty($cdata['public'])) {
395 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
396 if (DBA::isResult($public_contact)) {
397 $collapsed = $public_contact['collapsed'];
405 * @brief Returns a list of contacts belonging in a group
411 public static function getByGroupId($gid)
416 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
418 INNER JOIN `group_member`
419 ON `contact`.`id` = `group_member`.`contact-id`
421 AND `contact`.`uid` = ?
422 AND NOT `contact`.`self`
423 AND NOT `contact`.`deleted`
424 AND NOT `contact`.`blocked`
425 AND NOT `contact`.`pending`
426 ORDER BY `contact`.`name` ASC',
431 if (DBA::isResult($stmt)) {
432 $return = DBA::toArray($stmt);
440 * @brief Returns the count of OStatus contacts in a group
446 public static function getOStatusCountByGroupId($gid)
450 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
452 INNER JOIN `group_member`
453 ON `contact`.`id` = `group_member`.`contact-id`
455 AND `contact`.`uid` = ?
456 AND `contact`.`network` = ?
457 AND `contact`.`notify` != ""',
462 $return = $contacts['count'];
469 * Creates the self-contact for the provided user id
472 * @return bool Operation success
473 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
475 public static function createSelfFromUserId($uid)
477 // Only create the entry if it doesn't exist yet
478 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
482 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
483 if (!DBA::isResult($user)) {
487 $return = DBA::insert('contact', [
488 'uid' => $user['uid'],
489 'created' => DateTimeFormat::utcNow(),
491 'name' => $user['username'],
492 'nick' => $user['nickname'],
493 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
494 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
495 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
498 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
499 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
500 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
501 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
502 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
503 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
504 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
505 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
506 'name-date' => DateTimeFormat::utcNow(),
507 'uri-date' => DateTimeFormat::utcNow(),
508 'avatar-date' => DateTimeFormat::utcNow(),
516 * Updates the self-contact for the provided user id
519 * @param boolean $update_avatar Force the avatar update
520 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
522 public static function updateSelfFromUserID($uid, $update_avatar = false)
524 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
525 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
526 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
527 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
528 if (!DBA::isResult($self)) {
532 $fields = ['nickname', 'page-flags', 'account-type'];
533 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
534 if (!DBA::isResult($user)) {
538 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
539 'country-name', 'gender', 'pub_keywords', 'xmpp'];
540 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
541 if (!DBA::isResult($profile)) {
545 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
546 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
547 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
548 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
549 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
551 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
552 if (DBA::isResult($avatar)) {
553 if ($update_avatar) {
554 $fields['avatar-date'] = DateTimeFormat::utcNow();
557 // Creating the path to the avatar, beginning with the file suffix
558 $types = Image::supportedTypes();
559 if (isset($types[$avatar['type']])) {
560 $file_suffix = $types[$avatar['type']];
562 $file_suffix = 'jpg';
565 // We are adding a timestamp value so that other systems won't use cached content
566 $timestamp = strtotime($fields['avatar-date']);
568 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
569 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
571 $fields['photo'] = $prefix . '4' . $suffix;
572 $fields['thumb'] = $prefix . '5' . $suffix;
573 $fields['micro'] = $prefix . '6' . $suffix;
575 // We hadn't found a photo entry, so we use the default avatar
576 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
577 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
578 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
581 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
582 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
584 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
585 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
586 $fields['nurl'] = Strings::normaliseLink($fields['url']);
587 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
588 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
589 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
590 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
591 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
592 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
596 foreach ($fields as $field => $content) {
597 if ($self[$field] != $content) {
603 if ($fields['name'] != $self['name']) {
604 $fields['name-date'] = DateTimeFormat::utcNow();
606 $fields['updated'] = DateTimeFormat::utcNow();
607 DBA::update('contact', $fields, ['id' => $self['id']]);
609 // Update the public contact as well
610 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
612 // Update the profile
613 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
614 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
615 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
620 * @brief Marks a contact for removal
622 * @param int $id contact id
624 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
626 public static function remove($id)
628 // We want just to make sure that we don't delete our "self" contact
629 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
630 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
634 // Archive the contact
635 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
637 // Delete it in the background
638 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
642 * @brief Sends an unfriend message. Does not remove the contact
644 * @param array $user User unfriending
645 * @param array $contact Contact unfriended
646 * @param boolean $dissolve Remove the contact on the remote side
648 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
649 * @throws \ImagickException
651 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
653 if (empty($contact['network'])) {
657 $protocol = $contact['network'];
658 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
659 $protocol = Protocol::ACTIVITYPUB;
662 if (($protocol == Protocol::DFRN) && $dissolve) {
663 DFRN::deliver($user, $contact, 'placeholder', true);
664 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
665 // create an unfollow slap
667 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
668 $item['follow'] = $contact["url"];
673 $item['attach'] = '';
674 $slap = OStatus::salmon($item, $user);
676 if (!empty($contact['notify'])) {
677 Salmon::slapper($user, $contact['notify'], $slap);
679 } elseif ($protocol == Protocol::DIASPORA) {
680 Diaspora::sendUnshare($user, $contact);
681 } elseif ($protocol == Protocol::ACTIVITYPUB) {
682 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
685 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
691 * @brief Marks a contact for archival after a communication issue delay
693 * Contact has refused to recognise us as a friend. We will start a countdown.
694 * If they still don't recognise us in 32 days, the relationship is over,
695 * and we won't waste any more time trying to communicate with them.
696 * This provides for the possibility that their database is temporarily messed
697 * up or some other transient event and that there's a possibility we could recover from it.
699 * @param array $contact contact to mark for archival
701 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
703 public static function markForArchival(array $contact)
705 if (!isset($contact['url']) && !empty($contact['id'])) {
706 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
707 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
708 if (!DBA::isResult($contact)) {
711 } elseif (!isset($contact['url'])) {
712 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
715 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
717 // Contact already archived or "self" contact? => nothing to do
718 if ($contact['archive'] || $contact['self']) {
722 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
723 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
724 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
727 * We really should send a notification to the owner after 2-3 weeks
728 * so they won't be surprised when the contact vanishes and can take
729 * remedial action if this was a serious mistake or glitch
732 /// @todo Check for contact vitality via probing
733 $archival_days = Config::get('system', 'archival_days', 32);
735 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
736 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
737 /* Relationship is really truly dead. archive them rather than
738 * delete, though if the owner tries to unarchive them we'll start
739 * the whole process over again.
741 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
742 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
748 * @brief Cancels the archival countdown
750 * @see Contact::markForArchival()
752 * @param array $contact contact to be unmarked for archival
756 public static function unmarkForArchival(array $contact)
758 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
759 $exists = DBA::exists('contact', $condition);
761 // We don't need to update, we never marked this contact for archival
766 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
768 if (!isset($contact['url']) && !empty($contact['id'])) {
769 $fields = ['id', 'url', 'batch'];
770 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
771 if (!DBA::isResult($contact)) {
776 // It's a miracle. Our dead contact has inexplicably come back to life.
777 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
778 DBA::update('contact', $fields, ['id' => $contact['id']]);
779 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
781 if (!empty($contact['batch'])) {
782 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
783 DBA::update('contact', $fields, $condition);
788 * @brief Get contact data for a given profile link
790 * The function looks at several places (contact table and gcontact table) for the contact
791 * It caches its result for the same script execution to prevent duplicate calls
793 * @param string $url The profile link
794 * @param int $uid User id
795 * @param array $default If not data was found take this data as default value
797 * @return array Contact data
798 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
800 public static function getDetailsByURL($url, $uid = -1, array $default = [])
812 if (isset($cache[$url][$uid])) {
813 return $cache[$url][$uid];
816 $ssl_url = str_replace('http://', 'https://', $url);
818 // Fetch contact data from the contact table for the given user
819 $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`,
820 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
821 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
822 $r = DBA::toArray($s);
824 // Fetch contact data from the contact table for the given user, checking with the alias
825 if (!DBA::isResult($r)) {
826 $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`,
827 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
828 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
829 $r = DBA::toArray($s);
832 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
833 if (!DBA::isResult($r)) {
834 $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`,
835 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
836 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
837 $r = DBA::toArray($s);
840 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
841 if (!DBA::isResult($r)) {
842 $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`,
843 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
844 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
845 $r = DBA::toArray($s);
848 // Fetch the data from the gcontact table
849 if (!DBA::isResult($r)) {
850 $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`,
851 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
852 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
853 $r = DBA::toArray($s);
856 if (DBA::isResult($r)) {
857 // If there is more than one entry we filter out the connector networks
859 foreach ($r as $id => $result) {
860 if ($result["network"] == Protocol::STATUSNET) {
866 $profile = array_shift($r);
868 // "bd" always contains the upcoming birthday of a contact.
869 // "birthday" might contain the birthday including the year of birth.
870 if ($profile["birthday"] > DBA::NULL_DATE) {
871 $bd_timestamp = strtotime($profile["birthday"]);
872 $month = date("m", $bd_timestamp);
873 $day = date("d", $bd_timestamp);
875 $current_timestamp = time();
876 $current_year = date("Y", $current_timestamp);
877 $current_month = date("m", $current_timestamp);
878 $current_day = date("d", $current_timestamp);
880 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
881 $current = $current_year . "-" . $current_month . "-" . $current_day;
883 if ($profile["bd"] < $current) {
884 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
887 $profile["bd"] = DBA::NULL_DATE;
893 if (empty($profile["photo"]) && isset($default["photo"])) {
894 $profile["photo"] = $default["photo"];
897 if (empty($profile["name"]) && isset($default["name"])) {
898 $profile["name"] = $default["name"];
901 if (empty($profile["network"]) && isset($default["network"])) {
902 $profile["network"] = $default["network"];
905 if (empty($profile["thumb"]) && isset($profile["photo"])) {
906 $profile["thumb"] = $profile["photo"];
909 if (empty($profile["micro"]) && isset($profile["thumb"])) {
910 $profile["micro"] = $profile["thumb"];
913 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
914 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
916 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
919 // Show contact details of Diaspora contacts only if connected
920 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
921 $profile["location"] = "";
922 $profile["about"] = "";
923 $profile["gender"] = "";
924 $profile["birthday"] = DBA::NULL_DATE;
927 $cache[$url][$uid] = $profile;
933 * @brief Get contact data for a given address
935 * The function looks at several places (contact table and gcontact table) for the contact
937 * @param string $addr The profile link
938 * @param int $uid User id
940 * @return array Contact data
941 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
942 * @throws \ImagickException
944 public static function getDetailsByAddr($addr, $uid = -1)
954 // Fetch contact data from the contact table for the given user
955 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
956 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
957 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
961 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
962 if (!DBA::isResult($r)) {
963 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
964 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
965 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
970 // Fetch the data from the gcontact table
971 if (!DBA::isResult($r)) {
972 $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`,
973 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
974 FROM `gcontact` WHERE `addr` = '%s'",
979 if (!DBA::isResult($r)) {
980 $data = Probe::uri($addr);
982 $profile = self::getDetailsByURL($data['url'], $uid);
991 * @brief Returns the data array for the photo menu of a given contact
993 * @param array $contact contact
994 * @param int $uid optional, default 0
996 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
997 * @throws \ImagickException
999 public static function photoMenu(array $contact, $uid = 0)
1004 $contact_drop_link = '';
1008 $uid = local_user();
1011 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1013 $profile_link = self::magicLink($contact['url']);
1014 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1019 // Look for our own contact if the uid doesn't match and isn't public
1020 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1021 if (DBA::isResult($contact_own)) {
1022 return self::photoMenu($contact_own, $uid);
1027 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1029 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1031 $profile_link = $contact['url'];
1034 if ($profile_link === 'mailbox') {
1039 $status_link = $profile_link . '?tab=status';
1040 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1041 $profile_link = $profile_link . '?tab=profile';
1044 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
1045 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1048 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1049 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1052 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1054 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1056 if (!$contact['self']) {
1057 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1062 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1064 if (empty($contact['uid'])) {
1065 $connlnk = 'follow/?url=' . $contact['url'];
1067 'profile' => [L10n::t('View Profile'), $profile_link, true],
1068 'network' => [L10n::t('Network Posts'), $posts_link, false],
1069 'edit' => [L10n::t('View Contact'), $contact_url, false],
1070 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1074 'status' => [L10n::t('View Status'), $status_link, true],
1075 'profile' => [L10n::t('View Profile'), $profile_link, true],
1076 'photos' => [L10n::t('View Photos'), $photos_link, true],
1077 'network' => [L10n::t('Network Posts'), $posts_link, false],
1078 'edit' => [L10n::t('View Contact'), $contact_url, false],
1079 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1080 'pm' => [L10n::t('Send PM'), $pm_url, false],
1081 'poke' => [L10n::t('Poke'), $poke_link, false],
1085 $args = ['contact' => $contact, 'menu' => &$menu];
1087 Hook::callAll('contact_photo_menu', $args);
1089 $menucondensed = [];
1091 foreach ($menu as $menuname => $menuitem) {
1092 if ($menuitem[1] != '') {
1093 $menucondensed[$menuname] = $menuitem;
1097 return $menucondensed;
1101 * @brief Returns ungrouped contact count or list for user
1103 * Returns either the total number of ungrouped contacts for the given user
1104 * id or a paginated list of ungrouped contacts.
1106 * @param int $uid uid
1108 * @throws \Exception
1110 public static function getUngroupedList($uid)
1120 SELECT DISTINCT(`contact-id`)
1122 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1123 WHERE `group`.`uid` = %d
1124 )", intval($uid), intval($uid));
1128 * Have a look at all contact tables for a given profile url.
1129 * This function works as a replacement for probing the contact.
1131 * @param string $url Contact URL
1132 * @param integer $cid Contact ID
1134 * @return array Contact array in the "probe" structure
1136 private static function getProbeDataFromDatabase($url, $cid)
1138 // The link could be provided as http although we stored it as https
1139 $ssl_url = str_replace('http://', 'https://', $url);
1141 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1142 'photo', 'keywords', 'location', 'about', 'network',
1143 'priority', 'batch', 'request', 'confirm', 'poco'];
1146 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1147 if (DBA::isResult($data)) {
1152 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1154 if (!DBA::isResult($data)) {
1155 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1156 $data = DBA::selectFirst('contact', $fields, $condition);
1159 if (DBA::isResult($data)) {
1160 // For security reasons we don't fetch key data from our users
1161 $data["pubkey"] = '';
1165 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1166 'photo', 'keywords', 'location', 'about', 'network'];
1167 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1169 if (!DBA::isResult($data)) {
1170 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1171 $data = DBA::selectFirst('contact', $fields, $condition);
1174 if (DBA::isResult($data)) {
1175 $data["pubkey"] = '';
1177 $data["priority"] = 0;
1178 $data["batch"] = '';
1179 $data["request"] = '';
1180 $data["confirm"] = '';
1185 $data = ActivityPub::probeProfile($url, false);
1186 if (!empty($data)) {
1190 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1191 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1192 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1194 if (!DBA::isResult($data)) {
1195 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1196 $data = DBA::selectFirst('contact', $fields, $condition);
1199 if (DBA::isResult($data)) {
1200 $data["pubkey"] = '';
1201 $data["keywords"] = '';
1202 $data["location"] = '';
1203 $data["about"] = '';
1212 * @brief Fetch the contact id for a given URL and user
1214 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1215 * `addr` or `alias`.
1217 * If there's no record and we aren't looking for a public contact, we quit.
1218 * If there's one, we check that it isn't time to update the picture else we
1219 * directly return the found contact id.
1221 * Second, we probe the provided $url whether it's http://server.tld/profile or
1222 * nick@server.tld. We quit if we can't get any info back.
1224 * Third, we create the contact record if it doesn't exist
1226 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1227 * if there's any updates
1229 * @param string $url Contact URL
1230 * @param integer $uid The user id for the contact (0 = public contact)
1231 * @param boolean $no_update Don't update the contact
1232 * @param array $default Default value for creating the contact when every else fails
1233 * @param boolean $in_loop Internally used variable to prevent an endless loop
1235 * @return integer Contact ID
1236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1237 * @throws \ImagickException
1239 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1241 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1249 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1250 // We first try the nurl (http://server.tld/nick), most common case
1251 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1253 // Then the addr (nick@server.tld)
1254 if (!DBA::isResult($contact)) {
1255 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1258 // Then the alias (which could be anything)
1259 if (!DBA::isResult($contact)) {
1260 // The link could be provided as http although we stored it as https
1261 $ssl_url = str_replace('http://', 'https://', $url);
1262 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1263 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], $condition);
1266 if (DBA::isResult($contact)) {
1267 $contact_id = $contact["id"];
1269 // Update the contact every 7 days
1270 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1272 // We force the update if the avatar is empty
1273 if (empty($contact['avatar'])) {
1274 $update_contact = true;
1277 // Update the contact in the background if needed but it is called by the frontend
1278 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1279 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1282 if (!$update_contact || $no_update) {
1285 } elseif ($uid != 0) {
1286 // Non-existing user-specific contact, exiting
1290 // When we don't want to update, we look if we know this contact in any way
1291 if ($no_update && empty($default)) {
1292 $data = self::getProbeDataFromDatabase($url, $contact_id);
1293 $background_update = true;
1296 $background_update = false;
1300 $data = Probe::uri($url, "", $uid);
1302 // Ensure that there is a gserver entry
1303 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1304 PortableContact::checkServer($data['baseurl']);
1308 // Last try in gcontact for unsupported networks
1309 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1314 $contact = array_merge(self::getProbeDataFromDatabase($url, $contact_id), $default);
1315 if (empty($contact)) {
1319 $data = array_merge($data, $contact);
1326 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1327 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1333 'created' => DateTimeFormat::utcNow(),
1334 'url' => $data['url'],
1335 'nurl' => Strings::normaliseLink($data['url']),
1336 'addr' => defaults($data, 'addr', ''),
1337 'alias' => defaults($data, 'alias', ''),
1338 'notify' => defaults($data, 'notify', ''),
1339 'poll' => defaults($data, 'poll', ''),
1340 'name' => defaults($data, 'name', ''),
1341 'nick' => defaults($data, 'nick', ''),
1342 'photo' => defaults($data, 'photo', ''),
1343 'keywords' => defaults($data, 'keywords', ''),
1344 'location' => defaults($data, 'location', ''),
1345 'about' => defaults($data, 'about', ''),
1346 'network' => $data['network'],
1347 'pubkey' => defaults($data, 'pubkey', ''),
1348 'rel' => self::SHARING,
1349 'priority' => defaults($data, 'priority', 0),
1350 'batch' => defaults($data, 'batch', ''),
1351 'request' => defaults($data, 'request', ''),
1352 'confirm' => defaults($data, 'confirm', ''),
1353 'poco' => defaults($data, 'poco', ''),
1354 'name-date' => DateTimeFormat::utcNow(),
1355 'uri-date' => DateTimeFormat::utcNow(),
1356 'avatar-date' => DateTimeFormat::utcNow(),
1362 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1364 DBA::update('contact', $fields, $condition, true);
1366 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1367 $contacts = DBA::toArray($s);
1368 if (!DBA::isResult($contacts)) {
1372 $contact_id = $contacts[0]["id"];
1374 // Update in the background when we fetched the data solely from the database
1375 if ($background_update) {
1376 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1379 // Update the newly created contact from data in the gcontact table
1380 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1381 if (DBA::isResult($gcontact)) {
1382 // Only use the information when the probing hadn't fetched these values
1383 if (!empty($data['keywords'])) {
1384 unset($gcontact['keywords']);
1386 if (!empty($data['location'])) {
1387 unset($gcontact['location']);
1389 if (!empty($data['about'])) {
1390 unset($gcontact['about']);
1392 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1395 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1396 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1397 Strings::normaliseLink($data["url"]), 0, $contact_id];
1398 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1399 DBA::delete('contact', $condition);
1403 if (!empty($data['photo'])) {
1404 self::updateAvatar($data['photo'], $uid, $contact_id);
1407 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1408 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1410 // This condition should always be true
1411 if (!DBA::isResult($contact)) {
1415 $updated = ['addr' => $data['addr'],
1416 'alias' => defaults($data, 'alias', ''),
1417 'url' => $data['url'],
1418 'nurl' => Strings::normaliseLink($data['url']),
1419 'name' => $data['name'],
1420 'nick' => $data['nick']];
1422 if (!empty($data['keywords'])) {
1423 $updated['keywords'] = $data['keywords'];
1425 if (!empty($data['location'])) {
1426 $updated['location'] = $data['location'];
1429 // Update the technical stuff as well - if filled
1430 if (!empty($data['notify'])) {
1431 $updated['notify'] = $data['notify'];
1433 if (!empty($data['poll'])) {
1434 $updated['poll'] = $data['poll'];
1436 if (!empty($data['batch'])) {
1437 $updated['batch'] = $data['batch'];
1439 if (!empty($data['request'])) {
1440 $updated['request'] = $data['request'];
1442 if (!empty($data['confirm'])) {
1443 $updated['confirm'] = $data['confirm'];
1445 if (!empty($data['poco'])) {
1446 $updated['poco'] = $data['poco'];
1449 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1450 if (empty($contact['pubkey'])) {
1451 $updated['pubkey'] = $data['pubkey'];
1454 if (($data['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1455 $updated['uri-date'] = DateTimeFormat::utcNow();
1457 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1458 $updated['name-date'] = DateTimeFormat::utcNow();
1461 $updated['updated'] = DateTimeFormat::utcNow();
1463 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1469 * @brief Checks if the contact is blocked
1471 * @param int $cid contact id
1473 * @return boolean Is the contact blocked?
1474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1476 public static function isBlocked($cid)
1482 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1483 if (!DBA::isResult($blocked)) {
1487 if (Network::isUrlBlocked($blocked['url'])) {
1491 return (bool) $blocked['blocked'];
1495 * @brief Checks if the contact is hidden
1497 * @param int $cid contact id
1499 * @return boolean Is the contact hidden?
1500 * @throws \Exception
1502 public static function isHidden($cid)
1508 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1509 if (!DBA::isResult($hidden)) {
1512 return (bool) $hidden['hidden'];
1516 * @brief Returns posts from a given contact url
1518 * @param string $contact_url Contact URL
1520 * @param bool $thread_mode
1521 * @param int $update
1522 * @return string posts in HTML
1523 * @throws \Exception
1525 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1527 $a = self::getApp();
1529 $cid = self::getIdForURL($contact_url);
1531 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1532 if (!DBA::isResult($contact)) {
1536 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1537 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1539 $sql = "`item`.`uid` = ?";
1542 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1545 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1546 $cid, GRAVITY_PARENT, local_user()];
1548 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1549 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1552 $pager = new Pager($a->query_string);
1554 $params = ['order' => ['created' => true],
1555 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1558 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1560 $items = Item::inArray($r);
1562 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1564 $r = Item::selectForUser(local_user(), [], $condition, $params);
1566 $items = Item::inArray($r);
1568 $o = conversation($a, $items, $pager, 'contact-posts', false);
1572 $o .= $pager->renderMinimal(count($items));
1579 * @brief Returns the account type name
1581 * The function can be called with either the user or the contact array
1583 * @param array $contact contact or user array
1586 public static function getAccountType(array $contact)
1588 // There are several fields that indicate that the contact or user is a forum
1589 // "page-flags" is a field in the user table,
1590 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1591 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1592 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1593 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1594 || (isset($contact['forum']) && intval($contact['forum']))
1595 || (isset($contact['prv']) && intval($contact['prv']))
1596 || (isset($contact['community']) && intval($contact['community']))
1598 $type = self::TYPE_COMMUNITY;
1600 $type = self::TYPE_PERSON;
1603 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1604 if (isset($contact["contact-type"])) {
1605 $type = $contact["contact-type"];
1608 if (isset($contact["account-type"])) {
1609 $type = $contact["account-type"];
1613 case self::TYPE_ORGANISATION:
1614 $account_type = L10n::t("Organisation");
1617 case self::TYPE_NEWS:
1618 $account_type = L10n::t('News');
1621 case self::TYPE_COMMUNITY:
1622 $account_type = L10n::t("Forum");
1630 return $account_type;
1634 * @brief Blocks a contact
1638 * @throws \Exception
1640 public static function block($uid)
1642 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1648 * @brief Unblocks a contact
1652 * @throws \Exception
1654 public static function unblock($uid)
1656 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1662 * @brief Updates the avatar links in a contact only if needed
1664 * @param string $avatar Link to avatar picture
1665 * @param int $uid User id of contact owner
1666 * @param int $cid Contact id
1667 * @param bool $force force picture update
1669 * @return array Returns array of the different avatar sizes
1670 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1671 * @throws \ImagickException
1673 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1675 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1676 if (!DBA::isResult($contact)) {
1679 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1682 if (($contact["avatar"] != $avatar) || $force) {
1683 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1688 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1692 // Update the public contact (contact id = 0)
1694 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1695 if (DBA::isResult($pcontact)) {
1696 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1708 * @param integer $id contact id
1709 * @param string $network Optional network we are probing for
1710 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1712 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1713 * @throws \ImagickException
1715 public static function updateFromProbe($id, $network = '', $force = false)
1718 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1719 This will reliably kill your communication with Friendica contacts.
1722 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1723 'poll', 'request', 'confirm', 'poco', 'network', 'alias'];
1724 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1725 if (!DBA::isResult($contact)) {
1729 $uid = $contact['uid'];
1730 unset($contact['uid']);
1732 $contact['photo'] = $contact['avatar'];
1733 unset($contact['avatar']);
1735 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1737 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1738 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1742 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT)) {
1748 // make sure to not overwrite existing values with blank entries
1749 foreach ($ret as $key => $val) {
1750 if (!isset($contact[$key])) {
1752 } elseif (($contact[$key] != '') && ($val == '')) {
1753 $ret[$key] = $contact[$key];
1754 } elseif ($ret[$key] != $contact[$key]) {
1763 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1764 $ret['updated'] = DateTimeFormat::utcNow();
1766 self::updateAvatar($ret['photo'], $uid, $id, true);
1768 unset($ret['photo']);
1769 DBA::update('contact', $ret, ['id' => $id]);
1771 // Update the corresponding gcontact entry
1772 PortableContact::lastUpdated($ret["url"]);
1778 * Detects if a given contact array belongs to a legacy DFRN connection
1780 * @param array $contact
1783 public static function isLegacyDFRNContact($contact)
1785 // Newer Friendica contacts are connected via AP, then these fields aren't set
1786 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1790 * Detects the communication protocol for a given contact url.
1791 * This is used to detect Friendica contacts that we can communicate via AP.
1793 * @param string $url contact url
1794 * @param string $network Network of that contact
1795 * @return string with protocol
1797 public static function getProtocol($url, $network)
1799 if ($network != Protocol::DFRN) {
1803 $apcontact = APContact::getByURL($url);
1804 if (!empty($apcontact) && !empty($apcontact['generator'])) {
1805 return Protocol::ACTIVITYPUB;
1812 * Takes a $uid and a url/handle and adds a new contact
1813 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1814 * dfrn_request page.
1816 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1819 * $return['success'] boolean true if successful
1820 * $return['message'] error text if success is false.
1822 * @brief Takes a $uid and a url/handle and adds a new contact
1824 * @param string $url
1825 * @param bool $interactive
1826 * @param string $network
1828 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1829 * @throws \ImagickException
1831 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1833 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1837 // remove ajax junk, e.g. Twitter
1838 $url = str_replace('/#!/', '/', $url);
1840 if (!Network::isUrlAllowed($url)) {
1841 $result['message'] = L10n::t('Disallowed profile URL.');
1845 if (Network::isUrlBlocked($url)) {
1846 $result['message'] = L10n::t('Blocked domain');
1851 $result['message'] = L10n::t('Connect URL missing.');
1855 $arr = ['url' => $url, 'contact' => []];
1857 Hook::callAll('follow', $arr);
1860 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1864 if (!empty($arr['contact']['name'])) {
1865 $ret = $arr['contact'];
1867 $ret = Probe::uri($url, $network, $uid, false);
1870 if (($network != '') && ($ret['network'] != $network)) {
1871 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1875 // check if we already have a contact
1876 // the poll url is more reliable than the profile url, as we may have
1877 // indirect links or webfinger links
1879 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1880 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1881 if (!DBA::isResult($contact)) {
1882 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1883 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1886 $protocol = self::getProtocol($url, $ret['network']);
1888 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
1890 if (strlen($a->getURLPath())) {
1891 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1893 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1896 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1900 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1901 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1902 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1906 // This extra param just confuses things, remove it
1907 if ($protocol === Protocol::DIASPORA) {
1908 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1911 // do we have enough information?
1912 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1913 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1914 if (empty($ret['poll'])) {
1915 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1917 if (empty($ret['name'])) {
1918 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1920 if (empty($ret['url'])) {
1921 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1923 if (strpos($url, '@') !== false) {
1924 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1925 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1930 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1931 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1932 $ret['notify'] = '';
1935 if (!$ret['notify']) {
1936 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1939 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1941 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
1943 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
1945 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
1947 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1951 if (DBA::isResult($contact)) {
1953 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1955 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1956 DBA::update('contact', $fields, ['id' => $contact['id']]);
1958 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1960 // create contact record
1961 DBA::insert('contact', [
1963 'created' => DateTimeFormat::utcNow(),
1964 'url' => $ret['url'],
1965 'nurl' => Strings::normaliseLink($ret['url']),
1966 'addr' => $ret['addr'],
1967 'alias' => $ret['alias'],
1968 'batch' => $ret['batch'],
1969 'notify' => $ret['notify'],
1970 'poll' => $ret['poll'],
1971 'poco' => $ret['poco'],
1972 'name' => $ret['name'],
1973 'nick' => $ret['nick'],
1974 'network' => $ret['network'],
1975 'protocol' => $protocol,
1976 'pubkey' => $ret['pubkey'],
1977 'rel' => $new_relation,
1978 'priority'=> $ret['priority'],
1979 'writable'=> $writeable,
1980 'hidden' => $hidden,
1983 'pending' => $pending,
1988 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1989 if (!DBA::isResult($contact)) {
1990 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1994 $contact_id = $contact['id'];
1995 $result['cid'] = $contact_id;
1997 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1999 // Update the avatar
2000 self::updateAvatar($ret['photo'], $uid, $contact_id);
2002 // pull feed and consume it, which should subscribe to the hub.
2004 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2006 $owner = User::getOwnerDataById($uid);
2008 if (DBA::isResult($owner)) {
2009 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2010 // create a follow slap
2012 $item['verb'] = ACTIVITY_FOLLOW;
2013 $item['follow'] = $contact["url"];
2015 $item['title'] = '';
2018 $item['attach'] = '';
2020 $slap = OStatus::salmon($item, $owner);
2022 if (!empty($contact['notify'])) {
2023 Salmon::slapper($owner, $contact['notify'], $slap);
2025 } elseif ($protocol == Protocol::DIASPORA) {
2026 $ret = Diaspora::sendShare($a->user, $contact);
2027 Logger::log('share returns: ' . $ret);
2028 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2029 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2030 if (empty($activity_id)) {
2031 // This really should never happen
2035 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2036 Logger::log('Follow returns: ' . $ret);
2040 $result['success'] = true;
2045 * @brief Updated contact's SSL policy
2047 * @param array $contact Contact array
2048 * @param string $new_policy New policy, valid: self,full
2050 * @return array Contact array with updated values
2051 * @throws \Exception
2053 public static function updateSslPolicy(array $contact, $new_policy)
2055 $ssl_changed = false;
2056 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2057 $ssl_changed = true;
2058 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2059 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2060 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2061 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2062 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2063 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2066 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2067 $ssl_changed = true;
2068 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2069 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2070 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2071 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2072 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2073 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2077 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2078 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2079 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2080 DBA::update('contact', $fields, ['id' => $contact['id']]);
2086 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false, $note = '') {
2087 // Should always be set
2088 if (empty($datarray['author-id'])) {
2092 $fields = ['url', 'name', 'nick', 'photo', 'network'];
2093 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2094 if (!DBA::isResult($pub_contact)) {
2095 // Should never happen
2099 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2100 $name = $pub_contact['name'];
2101 $photo = $pub_contact['photo'];
2102 $nick = $pub_contact['nick'];
2103 $network = $pub_contact['network'];
2105 if (is_array($contact)) {
2106 // Make sure that the existing contact isn't archived
2107 self::unmarkForArchival($contact);
2109 $protocol = self::getProtocol($url, $contact['network']);
2111 if (($contact['rel'] == self::SHARING)
2112 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2113 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2114 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2117 if ($protocol == Protocol::ACTIVITYPUB) {
2118 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2121 // send email notification to owner?
2123 $protocol = self::getProtocol($url, $network);
2125 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2126 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2129 // create contact record
2130 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2131 `blocked`, `readonly`, `pending`, `writable`)
2132 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
2133 intval($importer['uid']),
2134 DBA::escape(DateTimeFormat::utcNow()),
2136 DBA::escape(Strings::normaliseLink($url)),
2139 DBA::escape($photo),
2140 DBA::escape($network),
2141 intval(self::FOLLOWER)
2145 'id' => DBA::lastInsertId(),
2146 'network' => $network,
2152 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2154 /// @TODO Encapsulate this into a function/method
2155 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2156 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2157 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2158 // create notification
2159 $hash = Strings::getRandomHex();
2161 if (is_array($contact_record)) {
2162 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2163 'blocked' => false, 'knowyou' => false, 'note' => $note,
2164 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2167 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2169 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2170 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2173 'type' => NOTIFY_INTRO,
2174 'notify_flags' => $user['notify-flags'],
2175 'language' => $user['language'],
2176 'to_name' => $user['username'],
2177 'to_email' => $user['email'],
2178 'uid' => $user['uid'],
2179 'link' => System::baseUrl() . '/notifications/intro',
2180 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2181 'source_link' => $contact_record['url'],
2182 'source_photo' => $contact_record['photo'],
2183 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2188 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2189 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2190 DBA::update('contact', ['pending' => false], $condition);
2192 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
2193 $protocol = self::getProtocol($contact['url'], $contact['network']);
2195 if ($protocol == Protocol::ACTIVITYPUB) {
2196 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2202 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2204 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2205 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2207 Contact::remove($contact['id']);
2211 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2213 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2214 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2216 Contact::remove($contact['id']);
2221 * @brief Create a birthday event.
2223 * Update the year and the birthday.
2225 public static function updateBirthdays()
2229 AND `bd` > "0001-01-01"
2230 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2231 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2232 AND NOT `contact`.`pending`
2233 AND NOT `contact`.`hidden`
2234 AND NOT `contact`.`blocked`
2235 AND NOT `contact`.`archive`
2236 AND NOT `contact`.`deleted`',
2241 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2243 while ($contact = DBA::fetch($contacts)) {
2244 Logger::log('update_contact_birthday: ' . $contact['bd']);
2246 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2248 if (Event::createBirthday($contact, $nextbd)) {
2252 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2253 ['id' => $contact['id']]
2260 * Remove the unavailable contact ids from the provided list
2262 * @param array $contact_ids Contact id list
2263 * @throws \Exception
2265 public static function pruneUnavailable(array &$contact_ids)
2267 if (empty($contact_ids)) {
2271 $str = DBA::escape(implode(',', $contact_ids));
2273 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2276 while($contact = DBA::fetch($stmt)) {
2277 $return[] = $contact['id'];
2282 $contact_ids = $return;
2286 * @brief Returns a magic link to authenticate remote visitors
2288 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2290 * @param string $contact_url The address of the target contact profile
2291 * @param string $url An url that we will be redirected to after the authentication
2293 * @return string with "redir" link
2294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2295 * @throws \ImagickException
2297 public static function magicLink($contact_url, $url = '')
2299 if (!local_user() && !remote_user()) {
2300 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2303 $cid = self::getIdForURL($contact_url, 0, true);
2305 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2308 return self::magicLinkbyId($cid, $url);
2312 * @brief Returns a magic link to authenticate remote visitors
2314 * @param integer $cid The contact id of the target contact profile
2315 * @param string $url An url that we will be redirected to after the authentication
2317 * @return string with "redir" link
2318 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2319 * @throws \ImagickException
2321 public static function magicLinkbyId($cid, $url = '')
2323 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2325 return self::magicLinkByContact($contact, $url);
2329 * @brief Returns a magic link to authenticate remote visitors
2331 * @param array $contact The contact array with "uid", "network" and "url"
2332 * @param string $url An url that we will be redirected to after the authentication
2334 * @return string with "redir" link
2335 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2336 * @throws \ImagickException
2338 public static function magicLinkByContact($contact, $url = '')
2340 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2341 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2344 // Only redirections to the same host do make sense
2345 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2349 if ($contact['uid'] != 0) {
2350 return self::magicLink($contact['url'], $url);
2353 $redirect = 'redir/' . $contact['id'];
2356 $redirect .= '?url=' . $url;
2363 * Remove a contact from all groups
2365 * @param integer $contact_id
2367 * @return boolean Success
2369 public static function removeFromGroups($contact_id)
2371 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2375 * Is the contact a forum?
2377 * @param integer $contactid ID of the contact
2379 * @return boolean "true" if it is a forum
2381 public static function isForum($contactid)
2383 $fields = ['forum', 'prv'];
2384 $condition = ['id' => $contactid];
2385 $contact = DBA::selectFirst('contact', $fields, $condition);
2386 if (!DBA::isResult($contact)) {
2391 return ($contact['forum'] || $contact['prv']);