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
35 * @deprecated since version 2019.03
36 * @see User::PAGE_FLAGS_NORMAL
38 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
40 * @deprecated since version 2019.03
41 * @see User::PAGE_FLAGS_SOAPBOX
43 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
45 * @deprecated since version 2019.03
46 * @see User::PAGE_FLAGS_COMMUNITY
48 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
50 * @deprecated since version 2019.03
51 * @see User::PAGE_FLAGS_FREELOVE
53 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
55 * @deprecated since version 2019.03
56 * @see User::PAGE_FLAGS_BLOG
58 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
60 * @deprecated since version 2019.03
61 * @see User::PAGE_FLAGS_PRVGROUP
63 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
71 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
73 * TYPE_PERSON - the account belongs to a person
74 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
76 * TYPE_ORGANISATION - the account belongs to an organisation
77 * Associated page type: PAGE_SOAPBOX
79 * TYPE_NEWS - the account is a news reflector
80 * Associated page type: PAGE_SOAPBOX
82 * TYPE_COMMUNITY - the account is community forum
83 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
85 * TYPE_RELAY - the account is a relay
86 * This will only be assigned to contacts, not to user accounts
89 const TYPE_UNKNOWN = -1;
90 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
91 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
92 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
93 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
94 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
114 * @return array|boolean Contact record if it exists, false otherwise
117 public static function getById($id)
119 return DBA::selectFirst('contact', [], ['id' => $id]);
123 * @brief Tests if the given contact is a follower
125 * @param int $cid Either public contact id or user's contact id
126 * @param int $uid User ID
128 * @return boolean is the contact id a follower?
129 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
130 * @throws \ImagickException
132 public static function isFollower($cid, $uid)
134 if (self::isBlockedByUser($cid, $uid)) {
138 $cdata = self::getPublicAndUserContacID($cid, $uid);
139 if (empty($cdata['user'])) {
143 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
144 return DBA::exists('contact', $condition);
148 * @brief Get the basepath for a given contact link
149 * @todo Add functionality to store this value in the contact table
151 * @param string $url The contact link
153 * @return string basepath
154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
155 * @throws \ImagickException
157 public static function getBasepath($url)
159 $data = Probe::uri($url);
160 if (!empty($data['baseurl'])) {
161 return $data['baseurl'];
164 // When we can't probe the server, we use some ugly function that does some pattern matching
165 return PortableContact::detectServer($url);
169 * Returns the public contact id of the given user id
171 * @param integer $uid User ID
173 * @return integer|boolean Public contact id for given user id
176 public static function getPublicIdByUserId($uid)
178 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
179 if (!DBA::isResult($self)) {
182 return self::getIdForURL($self['url'], 0, true);
186 * @brief Returns the contact id for the user and the public contact id for a given contact id
188 * @param int $cid Either public contact id or user's contact id
189 * @param int $uid User ID
191 * @return array with public and user's contact id
192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
193 * @throws \ImagickException
195 public static function getPublicAndUserContacID($cid, $uid)
197 if (empty($uid) || empty($cid)) {
201 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
202 if (!DBA::isResult($contact)) {
206 // We quit when the user id don't match the user id of the provided contact
207 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
211 if ($contact['uid'] != 0) {
212 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
216 $ucid = $contact['id'];
218 $pcid = $contact['id'];
219 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
222 return ['public' => $pcid, 'user' => $ucid];
226 * @brief Block contact id for user id
228 * @param int $cid Either public contact id or user's contact id
229 * @param int $uid User ID
230 * @param boolean $blocked Is the contact blocked or unblocked?
233 public static function setBlockedForUser($cid, $uid, $blocked)
235 $cdata = self::getPublicAndUserContacID($cid, $uid);
240 if ($cdata['user'] != 0) {
241 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
244 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
247 // Blocked contact can't be in any group
248 self::removeFromGroups($cid);
253 * @brief Returns "block" state for contact id and user id
255 * @param int $cid Either public contact id or user's contact id
256 * @param int $uid User ID
258 * @return boolean is the contact id blocked for the given user?
261 public static function isBlockedByUser($cid, $uid)
263 $cdata = self::getPublicAndUserContacID($cid, $uid);
268 $public_blocked = false;
270 if (!empty($cdata['public'])) {
271 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
272 if (DBA::isResult($public_contact)) {
273 $public_blocked = $public_contact['blocked'];
277 $user_blocked = $public_blocked;
279 if (!empty($cdata['user'])) {
280 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
281 if (DBA::isResult($user_contact)) {
282 $user_blocked = $user_contact['blocked'];
286 if ($user_blocked != $public_blocked) {
287 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
290 return $user_blocked;
294 * @brief Ignore contact id for user id
296 * @param int $cid Either public contact id or user's contact id
297 * @param int $uid User ID
298 * @param boolean $ignored Is the contact ignored or unignored?
301 public static function setIgnoredForUser($cid, $uid, $ignored)
303 $cdata = self::getPublicAndUserContacID($cid, $uid);
308 if ($cdata['user'] != 0) {
309 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
312 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
316 * @brief Returns "ignore" state for contact id and user id
318 * @param int $cid Either public contact id or user's contact id
319 * @param int $uid User ID
321 * @return boolean is the contact id ignored for the given user?
324 public static function isIgnoredByUser($cid, $uid)
326 $cdata = self::getPublicAndUserContacID($cid, $uid);
331 $public_ignored = false;
333 if (!empty($cdata['public'])) {
334 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
335 if (DBA::isResult($public_contact)) {
336 $public_ignored = $public_contact['ignored'];
340 $user_ignored = $public_ignored;
342 if (!empty($cdata['user'])) {
343 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
344 if (DBA::isResult($user_contact)) {
345 $user_ignored = $user_contact['readonly'];
349 if ($user_ignored != $public_ignored) {
350 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
353 return $user_ignored;
357 * @brief Set "collapsed" for contact id and user id
359 * @param int $cid Either public contact id or user's contact id
360 * @param int $uid User ID
361 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
364 public static function setCollapsedForUser($cid, $uid, $collapsed)
366 $cdata = self::getPublicAndUserContacID($cid, $uid);
371 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
375 * @brief Returns "collapsed" state for contact id and user id
377 * @param int $cid Either public contact id or user's contact id
378 * @param int $uid User ID
380 * @return boolean is the contact id blocked for the given user?
381 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
382 * @throws \ImagickException
384 public static function isCollapsedByUser($cid, $uid)
386 $cdata = self::getPublicAndUserContacID($cid, $uid);
393 if (!empty($cdata['public'])) {
394 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
395 if (DBA::isResult($public_contact)) {
396 $collapsed = $public_contact['collapsed'];
404 * @brief Returns a list of contacts belonging in a group
410 public static function getByGroupId($gid)
415 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
417 INNER JOIN `group_member`
418 ON `contact`.`id` = `group_member`.`contact-id`
420 AND `contact`.`uid` = ?
421 AND NOT `contact`.`self`
422 AND NOT `contact`.`deleted`
423 AND NOT `contact`.`blocked`
424 AND NOT `contact`.`pending`
425 ORDER BY `contact`.`name` ASC',
430 if (DBA::isResult($stmt)) {
431 $return = DBA::toArray($stmt);
439 * @brief Returns the count of OStatus contacts in a group
445 public static function getOStatusCountByGroupId($gid)
449 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
451 INNER JOIN `group_member`
452 ON `contact`.`id` = `group_member`.`contact-id`
454 AND `contact`.`uid` = ?
455 AND `contact`.`network` = ?
456 AND `contact`.`notify` != ""',
461 $return = $contacts['count'];
468 * Creates the self-contact for the provided user id
471 * @return bool Operation success
472 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
474 public static function createSelfFromUserId($uid)
476 // Only create the entry if it doesn't exist yet
477 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
481 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
482 if (!DBA::isResult($user)) {
486 $return = DBA::insert('contact', [
487 'uid' => $user['uid'],
488 'created' => DateTimeFormat::utcNow(),
490 'name' => $user['username'],
491 'nick' => $user['nickname'],
492 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
493 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
494 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
497 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
498 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
499 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
500 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
501 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
502 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
503 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
504 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
505 'name-date' => DateTimeFormat::utcNow(),
506 'uri-date' => DateTimeFormat::utcNow(),
507 'avatar-date' => DateTimeFormat::utcNow(),
515 * Updates the self-contact for the provided user id
518 * @param boolean $update_avatar Force the avatar update
519 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
521 public static function updateSelfFromUserID($uid, $update_avatar = false)
523 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
524 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
525 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
526 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
527 if (!DBA::isResult($self)) {
531 $fields = ['nickname', 'page-flags', 'account-type'];
532 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
533 if (!DBA::isResult($user)) {
537 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
538 'country-name', 'gender', 'pub_keywords', 'xmpp'];
539 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
540 if (!DBA::isResult($profile)) {
544 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
545 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
546 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
547 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
548 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
550 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
551 if (DBA::isResult($avatar)) {
552 if ($update_avatar) {
553 $fields['avatar-date'] = DateTimeFormat::utcNow();
556 // Creating the path to the avatar, beginning with the file suffix
557 $types = Image::supportedTypes();
558 if (isset($types[$avatar['type']])) {
559 $file_suffix = $types[$avatar['type']];
561 $file_suffix = 'jpg';
564 // We are adding a timestamp value so that other systems won't use cached content
565 $timestamp = strtotime($fields['avatar-date']);
567 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
568 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
570 $fields['photo'] = $prefix . '4' . $suffix;
571 $fields['thumb'] = $prefix . '5' . $suffix;
572 $fields['micro'] = $prefix . '6' . $suffix;
574 // We hadn't found a photo entry, so we use the default avatar
575 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
576 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
577 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
580 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
581 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
583 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
584 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
585 $fields['nurl'] = Strings::normaliseLink($fields['url']);
586 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
587 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
588 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
589 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
590 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
591 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
595 foreach ($fields as $field => $content) {
596 if ($self[$field] != $content) {
602 if ($fields['name'] != $self['name']) {
603 $fields['name-date'] = DateTimeFormat::utcNow();
605 $fields['updated'] = DateTimeFormat::utcNow();
606 DBA::update('contact', $fields, ['id' => $self['id']]);
608 // Update the public contact as well
609 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
611 // Update the profile
612 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
613 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
614 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
619 * @brief Marks a contact for removal
621 * @param int $id contact id
623 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
625 public static function remove($id)
627 // We want just to make sure that we don't delete our "self" contact
628 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
629 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
633 // Archive the contact
634 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
636 // Delete it in the background
637 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
641 * @brief Sends an unfriend message. Does not remove the contact
643 * @param array $user User unfriending
644 * @param array $contact Contact unfriended
645 * @param boolean $dissolve Remove the contact on the remote side
647 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
648 * @throws \ImagickException
650 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
652 if (empty($contact['network'])) {
655 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
656 DFRN::deliver($user, $contact, 'placeholder', true);
657 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
658 // create an unfollow slap
660 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
661 $item['follow'] = $contact["url"];
666 $item['attach'] = '';
667 $slap = OStatus::salmon($item, $user);
669 if (!empty($contact['notify'])) {
670 Salmon::slapper($user, $contact['notify'], $slap);
672 } elseif ($contact['network'] == Protocol::DIASPORA) {
673 Diaspora::sendUnshare($user, $contact);
674 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
675 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
678 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
684 * @brief Marks a contact for archival after a communication issue delay
686 * Contact has refused to recognise us as a friend. We will start a countdown.
687 * If they still don't recognise us in 32 days, the relationship is over,
688 * and we won't waste any more time trying to communicate with them.
689 * This provides for the possibility that their database is temporarily messed
690 * up or some other transient event and that there's a possibility we could recover from it.
692 * @param array $contact contact to mark for archival
694 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
696 public static function markForArchival(array $contact)
698 if (!isset($contact['url']) && !empty($contact['id'])) {
699 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
700 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
701 if (!DBA::isResult($contact)) {
704 } elseif (!isset($contact['url'])) {
705 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
708 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
710 // Contact already archived or "self" contact? => nothing to do
711 if ($contact['archive'] || $contact['self']) {
715 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
716 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
717 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
720 * We really should send a notification to the owner after 2-3 weeks
721 * so they won't be surprised when the contact vanishes and can take
722 * remedial action if this was a serious mistake or glitch
725 /// @todo Check for contact vitality via probing
726 $archival_days = Config::get('system', 'archival_days', 32);
728 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
729 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
730 /* Relationship is really truly dead. archive them rather than
731 * delete, though if the owner tries to unarchive them we'll start
732 * the whole process over again.
734 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
735 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
741 * @brief Cancels the archival countdown
743 * @see Contact::markForArchival()
745 * @param array $contact contact to be unmarked for archival
749 public static function unmarkForArchival(array $contact)
751 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
752 $exists = DBA::exists('contact', $condition);
754 // We don't need to update, we never marked this contact for archival
759 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
761 if (!isset($contact['url']) && !empty($contact['id'])) {
762 $fields = ['id', 'url', 'batch'];
763 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
764 if (!DBA::isResult($contact)) {
769 // It's a miracle. Our dead contact has inexplicably come back to life.
770 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
771 DBA::update('contact', $fields, ['id' => $contact['id']]);
772 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
774 if (!empty($contact['batch'])) {
775 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
776 DBA::update('contact', $fields, $condition);
781 * @brief Get contact data for a given profile link
783 * The function looks at several places (contact table and gcontact table) for the contact
784 * It caches its result for the same script execution to prevent duplicate calls
786 * @param string $url The profile link
787 * @param int $uid User id
788 * @param array $default If not data was found take this data as default value
790 * @return array Contact data
791 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
793 public static function getDetailsByURL($url, $uid = -1, array $default = [])
805 if (isset($cache[$url][$uid])) {
806 return $cache[$url][$uid];
809 $ssl_url = str_replace('http://', 'https://', $url);
811 // Fetch contact data from the contact table for the given user
812 $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`,
813 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
814 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
815 $r = DBA::toArray($s);
817 // Fetch contact data from the contact table for the given user, checking with the alias
818 if (!DBA::isResult($r)) {
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 `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
822 $r = DBA::toArray($s);
825 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
826 if (!DBA::isResult($r)) {
827 $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`,
828 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
829 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
830 $r = DBA::toArray($s);
833 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
834 if (!DBA::isResult($r)) {
835 $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`,
836 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
837 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
838 $r = DBA::toArray($s);
841 // Fetch the data from the gcontact table
842 if (!DBA::isResult($r)) {
843 $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`,
844 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
845 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
846 $r = DBA::toArray($s);
849 if (DBA::isResult($r)) {
850 // If there is more than one entry we filter out the connector networks
852 foreach ($r as $id => $result) {
853 if ($result["network"] == Protocol::STATUSNET) {
859 $profile = array_shift($r);
861 // "bd" always contains the upcoming birthday of a contact.
862 // "birthday" might contain the birthday including the year of birth.
863 if ($profile["birthday"] > DBA::NULL_DATE) {
864 $bd_timestamp = strtotime($profile["birthday"]);
865 $month = date("m", $bd_timestamp);
866 $day = date("d", $bd_timestamp);
868 $current_timestamp = time();
869 $current_year = date("Y", $current_timestamp);
870 $current_month = date("m", $current_timestamp);
871 $current_day = date("d", $current_timestamp);
873 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
874 $current = $current_year . "-" . $current_month . "-" . $current_day;
876 if ($profile["bd"] < $current) {
877 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
880 $profile["bd"] = DBA::NULL_DATE;
886 if (empty($profile["photo"]) && isset($default["photo"])) {
887 $profile["photo"] = $default["photo"];
890 if (empty($profile["name"]) && isset($default["name"])) {
891 $profile["name"] = $default["name"];
894 if (empty($profile["network"]) && isset($default["network"])) {
895 $profile["network"] = $default["network"];
898 if (empty($profile["thumb"]) && isset($profile["photo"])) {
899 $profile["thumb"] = $profile["photo"];
902 if (empty($profile["micro"]) && isset($profile["thumb"])) {
903 $profile["micro"] = $profile["thumb"];
906 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
907 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
909 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
912 // Show contact details of Diaspora contacts only if connected
913 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
914 $profile["location"] = "";
915 $profile["about"] = "";
916 $profile["gender"] = "";
917 $profile["birthday"] = DBA::NULL_DATE;
920 $cache[$url][$uid] = $profile;
926 * @brief Get contact data for a given address
928 * The function looks at several places (contact table and gcontact table) for the contact
930 * @param string $addr The profile link
931 * @param int $uid User id
933 * @return array Contact data
934 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
935 * @throws \ImagickException
937 public static function getDetailsByAddr($addr, $uid = -1)
947 // Fetch contact data from the contact table for the given user
948 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
949 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
950 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
954 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
955 if (!DBA::isResult($r)) {
956 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
957 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
958 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
963 // Fetch the data from the gcontact table
964 if (!DBA::isResult($r)) {
965 $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`,
966 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
967 FROM `gcontact` WHERE `addr` = '%s'",
972 if (!DBA::isResult($r)) {
973 $data = Probe::uri($addr);
975 $profile = self::getDetailsByURL($data['url'], $uid);
984 * @brief Returns the data array for the photo menu of a given contact
986 * @param array $contact contact
987 * @param int $uid optional, default 0
989 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
990 * @throws \ImagickException
992 public static function photoMenu(array $contact, $uid = 0)
997 $contact_drop_link = '';
1001 $uid = local_user();
1004 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1006 $profile_link = self::magicLink($contact['url']);
1007 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1012 // Look for our own contact if the uid doesn't match and isn't public
1013 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1014 if (DBA::isResult($contact_own)) {
1015 return self::photoMenu($contact_own, $uid);
1020 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1022 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1024 $profile_link = $contact['url'];
1027 if ($profile_link === 'mailbox') {
1032 $status_link = $profile_link . '?tab=status';
1033 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1034 $profile_link = $profile_link . '?tab=profile';
1037 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
1038 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1041 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1042 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1045 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1047 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1049 if (!$contact['self']) {
1050 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1055 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1057 if (empty($contact['uid'])) {
1058 $connlnk = 'follow/?url=' . $contact['url'];
1060 'profile' => [L10n::t('View Profile'), $profile_link, true],
1061 'network' => [L10n::t('Network Posts'), $posts_link, false],
1062 'edit' => [L10n::t('View Contact'), $contact_url, false],
1063 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1067 'status' => [L10n::t('View Status'), $status_link, true],
1068 'profile' => [L10n::t('View Profile'), $profile_link, true],
1069 'photos' => [L10n::t('View Photos'), $photos_link, true],
1070 'network' => [L10n::t('Network Posts'), $posts_link, false],
1071 'edit' => [L10n::t('View Contact'), $contact_url, false],
1072 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1073 'pm' => [L10n::t('Send PM'), $pm_url, false],
1074 'poke' => [L10n::t('Poke'), $poke_link, false],
1078 $args = ['contact' => $contact, 'menu' => &$menu];
1080 Hook::callAll('contact_photo_menu', $args);
1082 $menucondensed = [];
1084 foreach ($menu as $menuname => $menuitem) {
1085 if ($menuitem[1] != '') {
1086 $menucondensed[$menuname] = $menuitem;
1090 return $menucondensed;
1094 * @brief Returns ungrouped contact count or list for user
1096 * Returns either the total number of ungrouped contacts for the given user
1097 * id or a paginated list of ungrouped contacts.
1099 * @param int $uid uid
1101 * @throws \Exception
1103 public static function getUngroupedList($uid)
1113 SELECT DISTINCT(`contact-id`)
1115 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1116 WHERE `group`.`uid` = %d
1117 )", intval($uid), intval($uid));
1121 * Have a look at all contact tables for a given profile url.
1122 * This function works as a replacement for probing the contact.
1124 * @param string $url Contact URL
1125 * @param integer $cid Contact ID
1127 * @return array Contact array in the "probe" structure
1129 private static function getProbeDataFromDatabase($url, $cid)
1131 // The link could be provided as http although we stored it as https
1132 $ssl_url = str_replace('http://', 'https://', $url);
1134 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1135 'photo', 'keywords', 'location', 'about', 'network',
1136 'priority', 'batch', 'request', 'confirm', 'poco'];
1139 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1140 if (DBA::isResult($data)) {
1145 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1147 if (!DBA::isResult($data)) {
1148 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1149 $data = DBA::selectFirst('contact', $fields, $condition);
1152 if (DBA::isResult($data)) {
1153 // For security reasons we don't fetch key data from our users
1154 $data["pubkey"] = '';
1158 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1159 'photo', 'keywords', 'location', 'about', 'network'];
1160 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1162 if (!DBA::isResult($data)) {
1163 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1164 $data = DBA::selectFirst('contact', $fields, $condition);
1167 if (DBA::isResult($data)) {
1168 $data["pubkey"] = '';
1170 $data["priority"] = 0;
1171 $data["batch"] = '';
1172 $data["request"] = '';
1173 $data["confirm"] = '';
1178 $data = ActivityPub::probeProfile($url, false);
1179 if (!empty($data)) {
1183 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1184 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1185 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1187 if (!DBA::isResult($data)) {
1188 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1189 $data = DBA::selectFirst('contact', $fields, $condition);
1192 if (DBA::isResult($data)) {
1193 $data["pubkey"] = '';
1194 $data["keywords"] = '';
1195 $data["location"] = '';
1196 $data["about"] = '';
1205 * @brief Fetch the contact id for a given URL and user
1207 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1208 * `addr` or `alias`.
1210 * If there's no record and we aren't looking for a public contact, we quit.
1211 * If there's one, we check that it isn't time to update the picture else we
1212 * directly return the found contact id.
1214 * Second, we probe the provided $url whether it's http://server.tld/profile or
1215 * nick@server.tld. We quit if we can't get any info back.
1217 * Third, we create the contact record if it doesn't exist
1219 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1220 * if there's any updates
1222 * @param string $url Contact URL
1223 * @param integer $uid The user id for the contact (0 = public contact)
1224 * @param boolean $no_update Don't update the contact
1225 * @param array $default Default value for creating the contact when every else fails
1226 * @param boolean $in_loop Internally used variable to prevent an endless loop
1228 * @return integer Contact ID
1229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1230 * @throws \ImagickException
1232 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1234 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1242 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1243 // We first try the nurl (http://server.tld/nick), most common case
1244 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1246 // Then the addr (nick@server.tld)
1247 if (!DBA::isResult($contact)) {
1248 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1251 // Then the alias (which could be anything)
1252 if (!DBA::isResult($contact)) {
1253 // The link could be provided as http although we stored it as https
1254 $ssl_url = str_replace('http://', 'https://', $url);
1255 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1256 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated'], $condition);
1259 if (DBA::isResult($contact)) {
1260 $contact_id = $contact["id"];
1262 // Update the contact every 7 days
1263 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1265 // We force the update if the avatar is empty
1266 if (empty($contact['avatar'])) {
1267 $update_contact = true;
1270 // Update the contact in the background if needed but it is called by the frontend
1271 if ($update_contact && $no_update) {
1272 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1275 if (!$update_contact || $no_update) {
1278 } elseif ($uid != 0) {
1279 // Non-existing user-specific contact, exiting
1283 // When we don't want to update, we look if we know this contact in any way
1284 if ($no_update && empty($default)) {
1285 $data = self::getProbeDataFromDatabase($url, $contact_id);
1286 $background_update = true;
1289 $background_update = false;
1293 $data = Probe::uri($url, "", $uid);
1295 // Ensure that there is a gserver entry
1296 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1297 PortableContact::checkServer($data['baseurl']);
1301 // Last try in gcontact for unsupported networks
1302 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1307 $contact = array_merge(self::getProbeDataFromDatabase($url, $contact_id), $default);
1308 if (empty($contact)) {
1312 $data = array_merge($data, $contact);
1319 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1320 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1326 'created' => DateTimeFormat::utcNow(),
1327 'url' => $data["url"],
1328 'nurl' => Strings::normaliseLink($data["url"]),
1329 'addr' => $data["addr"],
1330 'alias' => $data["alias"],
1331 'notify' => $data["notify"],
1332 'poll' => $data["poll"],
1333 'name' => $data["name"],
1334 'nick' => $data["nick"],
1335 'photo' => $data["photo"],
1336 'keywords' => $data["keywords"],
1337 'location' => $data["location"],
1338 'about' => $data["about"],
1339 'network' => $data["network"],
1340 'pubkey' => $data["pubkey"],
1341 'rel' => self::SHARING,
1342 'priority' => $data["priority"],
1343 'batch' => $data["batch"],
1344 'request' => $data["request"],
1345 'confirm' => $data["confirm"],
1346 'poco' => $data["poco"],
1347 'name-date' => DateTimeFormat::utcNow(),
1348 'uri-date' => DateTimeFormat::utcNow(),
1349 'avatar-date' => DateTimeFormat::utcNow(),
1355 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1357 DBA::update('contact', $fields, $condition, true);
1359 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1360 $contacts = DBA::toArray($s);
1361 if (!DBA::isResult($contacts)) {
1365 $contact_id = $contacts[0]["id"];
1367 // Update in the background when we fetched the data solely from the database
1368 if ($background_update) {
1369 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1372 // Update the newly created contact from data in the gcontact table
1373 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1374 if (DBA::isResult($gcontact)) {
1375 // Only use the information when the probing hadn't fetched these values
1376 if ($data['keywords'] != '') {
1377 unset($gcontact['keywords']);
1379 if ($data['location'] != '') {
1380 unset($gcontact['location']);
1382 if ($data['about'] != '') {
1383 unset($gcontact['about']);
1385 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1388 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1389 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1390 Strings::normaliseLink($data["url"]), 0, $contact_id];
1391 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1392 DBA::delete('contact', $condition);
1396 self::updateAvatar($data["photo"], $uid, $contact_id);
1398 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1399 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1401 // This condition should always be true
1402 if (!DBA::isResult($contact)) {
1406 $updated = ['addr' => $data['addr'],
1407 'alias' => $data['alias'],
1408 'url' => $data['url'],
1409 'nurl' => Strings::normaliseLink($data['url']),
1410 'name' => $data['name'],
1411 'nick' => $data['nick']];
1413 if ($data['keywords'] != '') {
1414 $updated['keywords'] = $data['keywords'];
1416 if ($data['location'] != '') {
1417 $updated['location'] = $data['location'];
1420 // Update the technical stuff as well - if filled
1421 if ($data['notify'] != '') {
1422 $updated['notify'] = $data['notify'];
1424 if ($data['poll'] != '') {
1425 $updated['poll'] = $data['poll'];
1427 if ($data['batch'] != '') {
1428 $updated['batch'] = $data['batch'];
1430 if ($data['request'] != '') {
1431 $updated['request'] = $data['request'];
1433 if ($data['confirm'] != '') {
1434 $updated['confirm'] = $data['confirm'];
1436 if ($data['poco'] != '') {
1437 $updated['poco'] = $data['poco'];
1440 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1441 if (empty($contact['pubkey'])) {
1442 $updated['pubkey'] = $data['pubkey'];
1445 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1446 $updated['uri-date'] = DateTimeFormat::utcNow();
1448 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1449 $updated['name-date'] = DateTimeFormat::utcNow();
1452 $updated['updated'] = DateTimeFormat::utcNow();
1454 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1460 * @brief Checks if the contact is blocked
1462 * @param int $cid contact id
1464 * @return boolean Is the contact blocked?
1465 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1467 public static function isBlocked($cid)
1473 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1474 if (!DBA::isResult($blocked)) {
1478 if (Network::isUrlBlocked($blocked['url'])) {
1482 return (bool) $blocked['blocked'];
1486 * @brief Checks if the contact is hidden
1488 * @param int $cid contact id
1490 * @return boolean Is the contact hidden?
1491 * @throws \Exception
1493 public static function isHidden($cid)
1499 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1500 if (!DBA::isResult($hidden)) {
1503 return (bool) $hidden['hidden'];
1507 * @brief Returns posts from a given contact url
1509 * @param string $contact_url Contact URL
1511 * @param bool $thread_mode
1512 * @param int $update
1513 * @return string posts in HTML
1514 * @throws \Exception
1516 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1518 $a = self::getApp();
1520 $cid = self::getIdForURL($contact_url);
1522 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1523 if (!DBA::isResult($contact)) {
1527 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1528 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1530 $sql = "`item`.`uid` = ?";
1533 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1536 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1537 $cid, GRAVITY_PARENT, local_user()];
1539 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1540 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1543 $pager = new Pager($a->query_string);
1545 $params = ['order' => ['created' => true],
1546 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1549 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1551 $items = Item::inArray($r);
1553 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1555 $r = Item::selectForUser(local_user(), [], $condition, $params);
1557 $items = Item::inArray($r);
1559 $o = conversation($a, $items, $pager, 'contact-posts', false);
1563 $o .= $pager->renderMinimal(count($items));
1570 * @brief Returns the account type name
1572 * The function can be called with either the user or the contact array
1574 * @param array $contact contact or user array
1577 public static function getAccountType(array $contact)
1579 // There are several fields that indicate that the contact or user is a forum
1580 // "page-flags" is a field in the user table,
1581 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1582 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1583 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1584 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1585 || (isset($contact['forum']) && intval($contact['forum']))
1586 || (isset($contact['prv']) && intval($contact['prv']))
1587 || (isset($contact['community']) && intval($contact['community']))
1589 $type = self::TYPE_COMMUNITY;
1591 $type = self::TYPE_PERSON;
1594 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1595 if (isset($contact["contact-type"])) {
1596 $type = $contact["contact-type"];
1599 if (isset($contact["account-type"])) {
1600 $type = $contact["account-type"];
1604 case self::TYPE_ORGANISATION:
1605 $account_type = L10n::t("Organisation");
1608 case self::TYPE_NEWS:
1609 $account_type = L10n::t('News');
1612 case self::TYPE_COMMUNITY:
1613 $account_type = L10n::t("Forum");
1621 return $account_type;
1625 * @brief Blocks a contact
1629 * @throws \Exception
1631 public static function block($uid)
1633 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1639 * @brief Unblocks a contact
1643 * @throws \Exception
1645 public static function unblock($uid)
1647 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1653 * @brief Updates the avatar links in a contact only if needed
1655 * @param string $avatar Link to avatar picture
1656 * @param int $uid User id of contact owner
1657 * @param int $cid Contact id
1658 * @param bool $force force picture update
1660 * @return array Returns array of the different avatar sizes
1661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1662 * @throws \ImagickException
1664 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1666 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1667 if (!DBA::isResult($contact)) {
1670 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1673 if (($contact["avatar"] != $avatar) || $force) {
1674 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1679 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1683 // Update the public contact (contact id = 0)
1685 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1686 if (DBA::isResult($pcontact)) {
1687 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1699 * @param integer $id contact id
1700 * @param string $network Optional network we are probing for
1701 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1703 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1704 * @throws \ImagickException
1706 public static function updateFromProbe($id, $network = '', $force = false)
1709 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1710 This will reliably kill your communication with Friendica contacts.
1713 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1714 'poll', 'request', 'confirm', 'poco', 'network', 'alias'];
1715 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1716 if (!DBA::isResult($contact)) {
1720 $uid = $contact['uid'];
1721 unset($contact['uid']);
1723 $contact['photo'] = $contact['avatar'];
1724 unset($contact['avatar']);
1726 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1728 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1729 if ((in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM])) && ($ret['network'] != $contact['network'])) {
1735 // make sure to not overwrite existing values with blank entries
1736 foreach ($ret as $key => $val) {
1737 if (!isset($contact[$key])) {
1739 } elseif (($contact[$key] != '') && ($val == '')) {
1740 $ret[$key] = $contact[$key];
1741 } elseif ($ret[$key] != $contact[$key]) {
1750 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1751 $ret['updated'] = DateTimeFormat::utcNow();
1753 self::updateAvatar($ret['photo'], $uid, $id, true);
1755 unset($ret['photo']);
1756 DBA::update('contact', $ret, ['id' => $id]);
1758 // Update the corresponding gcontact entry
1759 PortableContact::lastUpdated($ret["url"]);
1765 * Takes a $uid and a url/handle and adds a new contact
1766 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1767 * dfrn_request page.
1769 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1772 * $return['success'] boolean true if successful
1773 * $return['message'] error text if success is false.
1775 * @brief Takes a $uid and a url/handle and adds a new contact
1777 * @param string $url
1778 * @param bool $interactive
1779 * @param string $network
1781 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1782 * @throws \ImagickException
1784 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1786 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1790 // remove ajax junk, e.g. Twitter
1791 $url = str_replace('/#!/', '/', $url);
1793 if (!Network::isUrlAllowed($url)) {
1794 $result['message'] = L10n::t('Disallowed profile URL.');
1798 if (Network::isUrlBlocked($url)) {
1799 $result['message'] = L10n::t('Blocked domain');
1804 $result['message'] = L10n::t('Connect URL missing.');
1808 $arr = ['url' => $url, 'contact' => []];
1810 Hook::callAll('follow', $arr);
1813 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1817 if (!empty($arr['contact']['name'])) {
1818 $ret = $arr['contact'];
1820 $ret = Probe::uri($url, $network, $uid, false);
1823 if (($network != '') && ($ret['network'] != $network)) {
1824 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1828 // check if we already have a contact
1829 // the poll url is more reliable than the profile url, as we may have
1830 // indirect links or webfinger links
1832 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1833 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1834 if (!DBA::isResult($contact)) {
1835 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1836 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1839 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1841 if (strlen($a->getURLPath())) {
1842 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1844 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1847 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1851 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1852 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1853 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1857 // This extra param just confuses things, remove it
1858 if ($ret['network'] === Protocol::DIASPORA) {
1859 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1862 // do we have enough information?
1863 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1864 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1865 if (empty($ret['poll'])) {
1866 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1868 if (empty($ret['name'])) {
1869 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1871 if (empty($ret['url'])) {
1872 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1874 if (strpos($url, '@') !== false) {
1875 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1876 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1881 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1882 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1883 $ret['notify'] = '';
1886 if (!$ret['notify']) {
1887 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1890 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1892 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1894 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1896 $pending = in_array($ret['network'], [Protocol::ACTIVITYPUB]);
1898 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1902 if (DBA::isResult($contact)) {
1904 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1906 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1907 DBA::update('contact', $fields, ['id' => $contact['id']]);
1909 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1911 // create contact record
1912 DBA::insert('contact', [
1914 'created' => DateTimeFormat::utcNow(),
1915 'url' => $ret['url'],
1916 'nurl' => Strings::normaliseLink($ret['url']),
1917 'addr' => $ret['addr'],
1918 'alias' => $ret['alias'],
1919 'batch' => $ret['batch'],
1920 'notify' => $ret['notify'],
1921 'poll' => $ret['poll'],
1922 'poco' => $ret['poco'],
1923 'name' => $ret['name'],
1924 'nick' => $ret['nick'],
1925 'network' => $ret['network'],
1926 'pubkey' => $ret['pubkey'],
1927 'rel' => $new_relation,
1928 'priority'=> $ret['priority'],
1929 'writable'=> $writeable,
1930 'hidden' => $hidden,
1933 'pending' => $pending,
1938 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1939 if (!DBA::isResult($contact)) {
1940 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1944 $contact_id = $contact['id'];
1945 $result['cid'] = $contact_id;
1947 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1949 // Update the avatar
1950 self::updateAvatar($ret['photo'], $uid, $contact_id);
1952 // pull feed and consume it, which should subscribe to the hub.
1954 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1956 $owner = User::getOwnerDataById($uid);
1958 if (DBA::isResult($owner)) {
1959 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1960 // create a follow slap
1962 $item['verb'] = ACTIVITY_FOLLOW;
1963 $item['follow'] = $contact["url"];
1965 $item['title'] = '';
1968 $item['attach'] = '';
1970 $slap = OStatus::salmon($item, $owner);
1972 if (!empty($contact['notify'])) {
1973 Salmon::slapper($owner, $contact['notify'], $slap);
1975 } elseif ($contact['network'] == Protocol::DIASPORA) {
1976 $ret = Diaspora::sendShare($a->user, $contact);
1977 Logger::log('share returns: ' . $ret);
1978 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1979 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
1980 if (empty($activity_id)) {
1981 // This really should never happen
1985 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
1986 Logger::log('Follow returns: ' . $ret);
1990 $result['success'] = true;
1995 * @brief Updated contact's SSL policy
1997 * @param array $contact Contact array
1998 * @param string $new_policy New policy, valid: self,full
2000 * @return array Contact array with updated values
2001 * @throws \Exception
2003 public static function updateSslPolicy(array $contact, $new_policy)
2005 $ssl_changed = false;
2006 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2007 $ssl_changed = true;
2008 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2009 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2010 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2011 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2012 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2013 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2016 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2017 $ssl_changed = true;
2018 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2019 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2020 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2021 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2022 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2023 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2027 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2028 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2029 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2030 DBA::update('contact', $fields, ['id' => $contact['id']]);
2036 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
2037 // Should always be set
2038 if (empty($datarray['author-id'])) {
2042 $fields = ['url', 'name', 'nick', 'photo', 'network'];
2043 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2044 if (!DBA::isResult($pub_contact)) {
2045 // Should never happen
2049 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2050 $name = $pub_contact['name'];
2051 $photo = $pub_contact['photo'];
2052 $nick = $pub_contact['nick'];
2053 $network = $pub_contact['network'];
2055 if (is_array($contact)) {
2056 if (($contact['rel'] == self::SHARING)
2057 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2058 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
2059 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2062 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2063 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2066 // send email notification to owner?
2068 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2069 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2072 // create contact record
2073 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2074 `blocked`, `readonly`, `pending`, `writable`)
2075 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
2076 intval($importer['uid']),
2077 DBA::escape(DateTimeFormat::utcNow()),
2079 DBA::escape(Strings::normaliseLink($url)),
2082 DBA::escape($photo),
2083 DBA::escape($network),
2084 intval(self::FOLLOWER)
2088 'id' => DBA::lastInsertId(),
2089 'network' => $network,
2095 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2097 /// @TODO Encapsulate this into a function/method
2098 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2099 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2100 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2101 // create notification
2102 $hash = Strings::getRandomHex();
2104 if (is_array($contact_record)) {
2105 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2106 'blocked' => false, 'knowyou' => false,
2107 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2110 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2112 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2113 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2116 'type' => NOTIFY_INTRO,
2117 'notify_flags' => $user['notify-flags'],
2118 'language' => $user['language'],
2119 'to_name' => $user['username'],
2120 'to_email' => $user['email'],
2121 'uid' => $user['uid'],
2122 'link' => System::baseUrl() . '/notifications/intro',
2123 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2124 'source_link' => $contact_record['url'],
2125 'source_photo' => $contact_record['photo'],
2126 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2131 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2132 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2133 DBA::update('contact', ['pending' => false], $condition);
2135 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
2137 if ($contact['network'] == Protocol::ACTIVITYPUB) {
2138 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2144 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2146 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2147 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2149 Contact::remove($contact['id']);
2153 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2155 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2156 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2158 Contact::remove($contact['id']);
2163 * @brief Create a birthday event.
2165 * Update the year and the birthday.
2167 public static function updateBirthdays()
2171 AND `bd` > "0001-01-01"
2172 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2173 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2174 AND NOT `contact`.`pending`
2175 AND NOT `contact`.`hidden`
2176 AND NOT `contact`.`blocked`
2177 AND NOT `contact`.`archive`
2178 AND NOT `contact`.`deleted`',
2183 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2185 while ($contact = DBA::fetch($contacts)) {
2186 Logger::log('update_contact_birthday: ' . $contact['bd']);
2188 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2190 if (Event::createBirthday($contact, $nextbd)) {
2194 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2195 ['id' => $contact['id']]
2202 * Remove the unavailable contact ids from the provided list
2204 * @param array $contact_ids Contact id list
2205 * @throws \Exception
2207 public static function pruneUnavailable(array &$contact_ids)
2209 if (empty($contact_ids)) {
2213 $str = DBA::escape(implode(',', $contact_ids));
2215 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2218 while($contact = DBA::fetch($stmt)) {
2219 $return[] = $contact['id'];
2224 $contact_ids = $return;
2228 * @brief Returns a magic link to authenticate remote visitors
2230 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2232 * @param string $contact_url The address of the target contact profile
2233 * @param string $url An url that we will be redirected to after the authentication
2235 * @return string with "redir" link
2236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2237 * @throws \ImagickException
2239 public static function magicLink($contact_url, $url = '')
2241 if (!local_user() && !remote_user()) {
2242 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2245 $cid = self::getIdForURL($contact_url, 0, true);
2247 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2250 return self::magicLinkbyId($cid, $url);
2254 * @brief Returns a magic link to authenticate remote visitors
2256 * @param integer $cid The contact id of the target contact profile
2257 * @param string $url An url that we will be redirected to after the authentication
2259 * @return string with "redir" link
2260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2261 * @throws \ImagickException
2263 public static function magicLinkbyId($cid, $url = '')
2265 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2267 return self::magicLinkByContact($contact, $url);
2271 * @brief Returns a magic link to authenticate remote visitors
2273 * @param array $contact The contact array with "uid", "network" and "url"
2274 * @param string $url An url that we will be redirected to after the authentication
2276 * @return string with "redir" link
2277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2278 * @throws \ImagickException
2280 public static function magicLinkByContact($contact, $url = '')
2282 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2283 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2286 // Only redirections to the same host do make sense
2287 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2291 if ($contact['uid'] != 0) {
2292 return self::magicLink($contact['url'], $url);
2295 $redirect = 'redir/' . $contact['id'];
2298 $redirect .= '?url=' . $url;
2305 * Remove a contact from all groups
2307 * @param integer $contact_id
2309 * @return boolean Success
2311 public static function removeFromGroups($contact_id)
2313 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2317 * Is the contact a forum?
2319 * @param integer $contactid ID of the contact
2321 * @return boolean "true" if it is a forum
2323 public static function isForum($contactid)
2325 $fields = ['forum', 'prv'];
2326 $condition = ['id' => $contactid];
2327 $contact = DBA::selectFirst('contact', $fields, $condition);
2328 if (!DBA::isResult($contact)) {
2333 return ($contact['forum'] || $contact['prv']);