3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\Renderer;
28 use Friendica\Database\Database;
29 use Friendica\Database\DBA;
31 use Friendica\Network\HTTPException;
32 use Friendica\Protocol\ActivityPub;
35 * functions for interacting with the group database table
39 const FOLLOWERS = '~';
43 * Fetches circle record by user id and maybe includes deleted circles as well
45 * @param int $uid User id to fetch circle(s) for
46 * @param bool $includesDeleted Whether deleted circles should be included
47 * @return array|bool Array on success, bool on error
49 public static function getByUserId(int $uid, bool $includesDeleted = false)
51 $conditions = ['uid' => $uid, 'cid' => null];
53 if (!$includesDeleted) {
54 $conditions['deleted'] = false;
57 return DBA::selectToArray('group', [], $conditions);
61 * Checks whether given circle id is found in database
63 * @param int $circle_id Circle id
64 * @param int $uid Optional user id
68 public static function exists(int $circle_id, int $uid = null): bool
70 $condition = ['id' => $circle_id, 'deleted' => false];
78 return DBA::exists('group', $condition);
82 * Create a new contact circle
84 * Note: If we found a deleted circle with the same name, we restore it
86 * @param int $uid User id to create circle for
87 * @param string $name Name of circle
88 * @return int|boolean Id of newly created circle or false on error
91 public static function create(int $uid, string $name)
94 if (!empty($uid) && !empty($name)) {
95 $gid = self::getIdByName($uid, $name); // check for dupes
97 // This could be a problem.
98 // Let's assume we've just created a circle which we once deleted
99 // all the old members are gone, but the circle remains, so we don't break any security
100 // access lists. What we're doing here is reviving the dead circle, but old content which
101 // was restricted to this circle may now be seen by the new circle members.
102 $circle = DBA::selectFirst('group', ['deleted'], ['id' => $gid]);
103 if (DBA::isResult($circle) && $circle['deleted']) {
104 DBA::update('group', ['deleted' => 0], ['id' => $gid]);
105 DI::sysmsg()->addNotice(DI::l10n()->t('A deleted circle with this name was revived. Existing item permissions <strong>may</strong> apply to this circle and any future members. If this is not what you intended, please create another circle with a different name.'));
110 $return = DBA::insert('group', ['uid' => $uid, 'name' => $name]);
112 $return = DBA::lastInsertId();
119 * Update circle information.
121 * @param int $id Circle ID
122 * @param string $name Circle name
124 * @return bool Was the update successful?
127 public static function update(int $id, string $name): bool
129 return DBA::update('group', ['name' => $name], ['id' => $id]);
133 * Get a list of circle ids a contact belongs to
135 * @param int $cid Contact id
136 * @return array Circle ids
139 public static function getIdsByContactId(int $cid): array
141 $contact = Contact::getById($cid, ['rel']);
148 $stmt = DBA::select('group_member', ['gid'], ['contact-id' => $cid]);
149 while ($circle = DBA::fetch($stmt)) {
150 $circleIds[] = $circle['gid'];
155 if ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND) {
156 $circleIds[] = self::FOLLOWERS;
159 if ($contact['rel'] == Contact::FRIEND) {
160 $circleIds[] = self::MUTUALS;
167 * count unread circle items
169 * Count unread items of each circle of the local user
173 * 'name' => circle name
174 * 'count' => counted unseen circle items
177 public static function countUnseen()
179 $stmt = DBA::p("SELECT `circle`.`id`, `circle`.`name`,
180 (SELECT COUNT(*) FROM `post-user`
185 FROM `group_member` AS `circle_member`
186 WHERE `circle_member`.`gid` = `circle`.`id`)
188 FROM `group` AS `circle`
189 WHERE `circle`.`uid` = ?;",
190 DI::userSession()->getLocalUserId(),
191 DI::userSession()->getLocalUserId()
194 return DBA::toArray($stmt);
198 * Get the circle id for a user/name couple
200 * Returns false if no circle has been found.
202 * @param int $uid User id
203 * @param string $name Circle name
204 * @return int|boolean Circle's id number or false on error
207 public static function getIdByName(int $uid, string $name)
209 if (!$uid || !strlen($name)) {
213 $circle = DBA::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]);
214 if (DBA::isResult($circle)) {
215 return $circle['id'];
222 * Mark a circle as deleted
228 public static function remove(int $gid): bool
234 $circle = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
235 if (!DBA::isResult($circle)) {
239 // remove circle from default posting lists
240 $user = DBA::selectFirst('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $circle['uid']]);
241 if (DBA::isResult($user)) {
244 if ($user['def_gid'] == $gid) {
245 $user['def_gid'] = 0;
248 if (strpos($user['allow_gid'], '<' . $gid . '>') !== false) {
249 $user['allow_gid'] = str_replace('<' . $gid . '>', '', $user['allow_gid']);
252 if (strpos($user['deny_gid'], '<' . $gid . '>') !== false) {
253 $user['deny_gid'] = str_replace('<' . $gid . '>', '', $user['deny_gid']);
258 DBA::update('user', $user, ['uid' => $circle['uid']]);
262 // remove all members
263 DBA::delete('group_member', ['gid' => $gid]);
266 $return = DBA::update('group', ['deleted' => 1], ['id' => $gid]);
272 * Adds a contact to a circle
279 public static function addMember(int $gid, int $cid): bool
281 if (!$gid || !$cid) {
285 // @TODO Backward compatibility with user contacts, remove by version 2022.03
286 $circle = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
287 if (empty($circle)) {
288 throw new HTTPException\NotFoundException('Circle not found.');
291 $cdata = Contact::getPublicAndUserContactID($cid, $circle['uid']);
292 if (empty($cdata['user'])) {
293 throw new HTTPException\NotFoundException('Invalid contact.');
296 return DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cdata['user']], Database::INSERT_IGNORE);
300 * Removes a contact from a circle
307 public static function removeMember(int $gid, int $cid): bool
309 if (!$gid || !$cid) {
313 // @TODO Backward compatibility with user contacts, remove by version 2022.03
314 $circle = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
315 if (empty($circle)) {
316 throw new HTTPException\NotFoundException('Circle not found.');
319 $cdata = Contact::getPublicAndUserContactID($cid, $circle['uid']);
320 if (empty($cdata['user'])) {
321 throw new HTTPException\NotFoundException('Invalid contact.');
324 return DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $cid]);
328 * Adds contacts to a circle
331 * @param array $contacts Array with contact ids
335 public static function addMembers(int $gid, array $contacts)
337 if (!$gid || !$contacts) {
341 // @TODO Backward compatibility with user contacts, remove by version 2022.03
342 $circle = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
343 if (empty($circle)) {
344 throw new HTTPException\NotFoundException('Circle not found.');
347 foreach ($contacts as $cid) {
348 $cdata = Contact::getPublicAndUserContactID($cid, $circle['uid']);
349 if (empty($cdata['user'])) {
350 throw new HTTPException\NotFoundException('Invalid contact.');
353 DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cdata['user']], Database::INSERT_IGNORE);
358 * Removes contacts from a circle
360 * @param int $gid Circle id
361 * @param array $contacts Contact ids
365 public static function removeMembers(int $gid, array $contacts)
367 if (!$gid || !$contacts) {
371 // @TODO Backward compatibility with user contacts, remove by version 2022.03
372 $circle = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
373 if (empty($circle)) {
374 throw new HTTPException\NotFoundException('Circle not found.');
379 foreach ($contacts as $cid) {
380 $cdata = Contact::getPublicAndUserContactID($cid, $circle['uid']);
381 if (empty($cdata['user'])) {
382 throw new HTTPException\NotFoundException('Invalid contact.');
385 $contactIds[] = $cdata['user'];
388 // Return status of deletion
389 return DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $contactIds]);
393 * Returns the combined list of contact ids from a circle id list
395 * @param int $uid User id
396 * @param array $circle_ids Circles ids
397 * @param boolean $check_dead Whether check "dead" records (?)
398 * @param boolean $expand_followers Expand the list of followers
402 public static function expand(int $uid, array $circle_ids, bool $check_dead = false, bool $expand_followers = true): array
404 if (!is_array($circle_ids) || !count($circle_ids)) {
410 $followers_collection = false;
411 $networks = Protocol::SUPPORT_PRIVATE;
413 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $uid]);
414 if (DBA::isResult($mailacct)) {
415 $pubmail = $mailacct['pubmail'];
419 $networks = array_diff($networks, [Protocol::MAIL]);
422 $key = array_search(self::FOLLOWERS, $circle_ids);
423 if ($key !== false) {
424 if ($expand_followers) {
425 $followers = Contact::selectToArray(['id'], [
427 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
428 'network' => $networks,
429 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
435 foreach ($followers as $follower) {
436 $return[] = $follower['id'];
439 $followers_collection = true;
441 unset($circle_ids[$key]);
444 $key = array_search(self::MUTUALS, $circle_ids);
445 if ($key !== false) {
446 $mutuals = Contact::selectToArray(['id'], [
448 'rel' => [Contact::FRIEND],
449 'network' => $networks,
450 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
456 foreach ($mutuals as $mutual) {
457 $return[] = $mutual['id'];
460 unset($circle_ids[$key]);
463 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $circle_ids]);
464 while ($circle_member = DBA::fetch($stmt)) {
465 $return[] = $circle_member['contact-id'];
470 $return = Contact::pruneUnavailable($return);
473 if ($followers_collection) {
481 * Returns a templated circle selection list
483 * @param int $uid User id
484 * @param int $gid An optional pre-selected circle
485 * @param string $label An optional label of the list
489 public static function getSelectorHTML(int $uid, int $gid = 0, string $label = ''): string
499 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => $uid, 'cid' => null], ['order' => ['name']]);
500 while ($circle = DBA::fetch($stmt)) {
501 $display_circles[] = [
502 'name' => $circle['name'],
503 'id' => $circle['id'],
504 'selected' => $gid == $circle['id'] ? 'true' : ''
509 Logger::info('Got circles', $display_circles);
512 $label = DI::l10n()->t('Default privacy circle for new contacts');
515 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('circle_selection.tpl'), [
517 '$circles' => $display_circles
523 * Create circle sidebar widget
525 * @param string $every
526 * @param string $each
527 * @param string $editmode
528 * 'standard' => include link 'Edit circles'
529 * 'extended' => include link 'Create new circle'
530 * 'full' => include link 'Create new circle' and provide for each circle a link to edit this circle
531 * @param string|int $circle_id Distinct circle id or 'everyone'
532 * @param int $cid Contact id
533 * @return string Sidebar widget HTML code
536 public static function sidebarWidget(string $every = 'contact', string $each = 'circle', string $editmode = 'standard', $circle_id = '', int $cid = 0)
538 if (!DI::userSession()->getLocalUserId()) {
544 'text' => DI::l10n()->t('Everybody'),
546 'selected' => (($circle_id === 'everyone') ? 'circle-selected' : ''),
553 $member_of = self::getIdsByContactId($cid);
556 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => DI::userSession()->getLocalUserId(), 'cid' => null], ['order' => ['name']]);
557 while ($circle = DBA::fetch($stmt)) {
558 $selected = (($circle_id == $circle['id']) ? ' circle-selected' : '');
560 if ($editmode == 'full') {
562 'href' => 'circle/' . $circle['id'],
563 'title' => DI::l10n()->t('edit'),
569 if ($each == 'circle') {
570 $count = DBA::count('group_member', ['gid' => $circle['id']]);
571 $circle_name = sprintf('%s (%d)', $circle['name'], $count);
573 $circle_name = $circle['name'];
576 $display_circles[] = [
577 'id' => $circle['id'],
579 'text' => $circle_name,
580 'href' => $each . '/' . $circle['id'],
581 'edit' => $circleedit,
582 'selected' => $selected,
583 'ismember' => in_array($circle['id'], $member_of),
588 // Don't show the circles on the network page when there is only one
589 if ((count($display_circles) <= 2) && ($each == 'network')) {
593 $tpl = Renderer::getMarkupTemplate('circle_side.tpl');
594 $o = Renderer::replaceMacros($tpl, [
595 '$add' => DI::l10n()->t('add'),
596 '$title' => DI::l10n()->t('Circles'),
597 '$circles' => $display_circles,
598 '$new_circle' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
599 '$circle_page' => 'circle/',
600 '$edittext' => DI::l10n()->t('Edit circle'),
601 '$uncircled' => $every === 'contact' ? DI::l10n()->t('Contacts not in any circle') : '',
602 '$uncircled_selected' => (($circle_id === 'none') ? 'circle-selected' : ''),
603 '$createtext' => DI::l10n()->t('Create a new circle'),
604 '$create_circle' => DI::l10n()->t('Circle Name: '),
605 '$edit_circles_text' => DI::l10n()->t('Edit circles'),
606 '$form_security_token' => BaseModule::getFormSecurityToken('circle_edit'),
613 * Fetch the circle id for the given contact id
615 * @param integer $id Contact ID
616 * @return integer Circle ID
618 public static function getIdForForum(int $id): int
620 Logger::info('Get id for forum id', ['id' => $id]);
621 $contact = Contact::getById($id, ['uid', 'name', 'contact-type', 'manually-approve']);
622 if (empty($contact) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY) || !$contact['manually-approve']) {
626 $circle = DBA::selectFirst('group', ['id'], ['uid' => $contact['uid'], 'cid' => $id]);
627 if (empty($circle)) {
629 'uid' => $contact['uid'],
630 'name' => $contact['name'],
633 DBA::insert('group', $fields);
634 $gid = DBA::lastInsertId();
636 $gid = $circle['id'];
643 * Fetch the followers of a given contact id and store them as circle members
645 * @param integer $id Contact ID
648 public static function updateMembersForForum(int $id)
650 Logger::info('Update forum members', ['id' => $id]);
652 $contact = Contact::getById($id, ['uid', 'url']);
653 if (empty($contact)) {
657 $apcontact = APContact::getByURL($contact['url']);
658 if (empty($apcontact['followers'])) {
662 $gid = self::getIdForForum($id);
667 $circle_members = DBA::selectToArray('group_member', ['contact-id'], ['gid' => $gid]);
668 if (!empty($circle_members)) {
669 $current = array_unique(array_column($circle_members, 'contact-id'));
674 foreach (ActivityPub::fetchItems($apcontact['followers'], $contact['uid']) as $follower) {
675 $id = Contact::getIdForURL($follower);
676 if (!in_array($id, $current)) {
677 DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $id]);
679 $key = array_search($id, $current);
680 unset($current[$key]);
684 DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $current]);
685 Logger::info('Updated forum members', ['id' => $id, 'count' => DBA::count('group_member', ['gid' => $gid])]);