3 * @copyright Copyright (C) 2010-2022, 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 group record by user id and maybe includes deleted groups as well
45 * @param int $uid User id to fetch group(s) for
46 * @param bool $includesDeleted Whether deleted groups 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 group id is found in database
63 * @param int $group_id Groupd it
64 * @param int $uid Optional user id
68 public static function exists(int $group_id, int $uid = null): bool
70 $condition = ['id' => $group_id, 'deleted' => false];
78 return DBA::exists('group', $condition);
82 * Create a new contact group
84 * Note: If we found a deleted group with the same name, we restore it
86 * @param int $uid User id to create group for
87 * @param string $name Name of group
88 * @return int|boolean Id of newly created group 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 group which we once deleted
99 // all the old members are gone, but the group remains so we don't break any security
100 // access lists. What we're doing here is reviving the dead group, but old content which
101 // was restricted to this group may now be seen by the new group members.
102 $group = DBA::selectFirst('group', ['deleted'], ['id' => $gid]);
103 if (DBA::isResult($group) && $group['deleted']) {
104 DBA::update('group', ['deleted' => 0], ['id' => $gid]);
105 DI::sysmsg()->addNotice(DI::l10n()->t('A deleted group with this name was revived. Existing item permissions <strong>may</strong> apply to this group and any future members. If this is not what you intended, please create another group with a different name.'));
110 $return = DBA::insert('group', ['uid' => $uid, 'name' => $name]);
112 $return = DBA::lastInsertId();
119 * Update group information.
121 * @param int $id Group ID
122 * @param string $name Group 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 group ids a contact belongs to
135 * @param int $cid Contact id
136 * @return array Group 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 ($group = DBA::fetch($stmt)) {
150 $groupIds[] = $group['gid'];
155 if ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND) {
156 $groupIds[] = self::FOLLOWERS;
159 if ($contact['rel'] == Contact::FRIEND) {
160 $groupIds[] = self::MUTUALS;
167 * count unread group items
169 * Count unread items of each groups of the local user
173 * 'name' => group name
174 * 'count' => counted unseen group items
177 public static function countUnseen()
179 $stmt = DBA::p("SELECT `group`.`id`, `group`.`name`,
180 (SELECT COUNT(*) FROM `post-user`
186 WHERE `group_member`.`gid` = `group`.`id`)
189 WHERE `group`.`uid` = ?;",
190 DI::userSession()->getLocalUserId(),
191 DI::userSession()->getLocalUserId()
194 return DBA::toArray($stmt);
198 * Get the group id for a user/name couple
200 * Returns false if no group has been found.
202 * @param int $uid User id
203 * @param string $name Group name
204 * @return int|boolean Groups' id number or false on error
207 public static function getIdByName(int $uid, string $name)
209 if (!$uid || !strlen($name)) {
213 $group = DBA::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]);
214 if (DBA::isResult($group)) {
222 * Mark a group as deleted
228 public static function remove(int $gid): bool
234 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
235 if (!DBA::isResult($group)) {
239 // remove group from default posting lists
240 $user = DBA::selectFirst('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $group['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' => $group['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 group
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 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
288 throw new HTTPException\NotFoundException('Group not found.');
291 $cdata = Contact::getPublicAndUserContactID($cid, $group['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 group
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 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
316 throw new HTTPException\NotFoundException('Group not found.');
319 $cdata = Contact::getPublicAndUserContactID($cid, $group['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 group
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 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
344 throw new HTTPException\NotFoundException('Group not found.');
347 foreach ($contacts as $cid) {
348 $cdata = Contact::getPublicAndUserContactID($cid, $group['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 group
360 * @param int $gid Group 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 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
374 throw new HTTPException\NotFoundException('Group not found.');
379 foreach ($contacts as $cid) {
380 $cdata = Contact::getPublicAndUserContactID($cid, $group['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 group id list
395 * @param int $uid User id
396 * @param array $group_ids Groups ids
397 * @param boolean $check_dead Whether check "dead" records (?)
401 public static function expand(int $uid, array $group_ids, bool $check_dead = false): array
403 if (!is_array($group_ids) || !count($group_ids)) {
409 $networks = Protocol::SUPPORT_PRIVATE;
411 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $uid]);
412 if (DBA::isResult($mailacct)) {
413 $pubmail = $mailacct['pubmail'];
417 $networks = array_diff($networks, [Protocol::MAIL]);
420 $key = array_search(self::FOLLOWERS, $group_ids);
421 if ($key !== false) {
422 $followers = Contact::selectToArray(['id'], [
424 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
425 'network' => $networks,
426 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
432 foreach ($followers as $follower) {
433 $return[] = $follower['id'];
436 unset($group_ids[$key]);
439 $key = array_search(self::MUTUALS, $group_ids);
440 if ($key !== false) {
441 $mutuals = Contact::selectToArray(['id'], [
443 'rel' => [Contact::FRIEND],
444 'network' => $networks,
445 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
451 foreach ($mutuals as $mutual) {
452 $return[] = $mutual['id'];
455 unset($group_ids[$key]);
458 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
459 while ($group_member = DBA::fetch($stmt)) {
460 $return[] = $group_member['contact-id'];
465 $return = Contact::pruneUnavailable($return);
472 * Returns a templated group selection list
474 * @param int $uid User id
475 * @param int $gid An optional pre-selected group
476 * @param string $label An optional label of the list
480 public static function displayGroupSelection(int $uid, int $gid = 0, string $label = ''): string
490 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => $uid, 'cid' => null], ['order' => ['name']]);
491 while ($group = DBA::fetch($stmt)) {
492 $display_groups[] = [
493 'name' => $group['name'],
494 'id' => $group['id'],
495 'selected' => $gid == $group['id'] ? 'true' : ''
500 Logger::info('Got groups', $display_groups);
503 $label = DI::l10n()->t('Default privacy group for new contacts');
506 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
508 '$groups' => $display_groups
514 * Create group sidebar widget
516 * @param string $every
517 * @param string $each
518 * @param string $editmode
519 * 'standard' => include link 'Edit groups'
520 * 'extended' => include link 'Create new group'
521 * 'full' => include link 'Create new group' and provide for each group a link to edit this group
522 * @param string|int $group_id Distinct group id or 'everyone'
523 * @param int $cid Contact id
524 * @return string Sidebar widget HTML code
527 public static function sidebarWidget(string $every = 'contact', string $each = 'group', string $editmode = 'standard', $group_id = '', int $cid = 0)
529 if (!DI::userSession()->getLocalUserId()) {
535 'text' => DI::l10n()->t('Everybody'),
537 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
544 $member_of = self::getIdsByContactId($cid);
547 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => DI::userSession()->getLocalUserId(), 'cid' => null], ['order' => ['name']]);
548 while ($group = DBA::fetch($stmt)) {
549 $selected = (($group_id == $group['id']) ? ' group-selected' : '');
551 if ($editmode == 'full') {
553 'href' => 'group/' . $group['id'],
554 'title' => DI::l10n()->t('edit'),
560 if ($each == 'group') {
561 $count = DBA::count('group_member', ['gid' => $group['id']]);
562 $group_name = sprintf('%s (%d)', $group['name'], $count);
564 $group_name = $group['name'];
567 $display_groups[] = [
568 'id' => $group['id'],
570 'text' => $group_name,
571 'href' => $each . '/' . $group['id'],
572 'edit' => $groupedit,
573 'selected' => $selected,
574 'ismember' => in_array($group['id'], $member_of),
579 // Don't show the groups on the network page when there is only one
580 if ((count($display_groups) <= 2) && ($each == 'network')) {
584 $tpl = Renderer::getMarkupTemplate('group_side.tpl');
585 $o = Renderer::replaceMacros($tpl, [
586 '$add' => DI::l10n()->t('add'),
587 '$title' => DI::l10n()->t('Groups'),
588 '$groups' => $display_groups,
589 'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
590 'grouppage' => 'group/',
591 '$edittext' => DI::l10n()->t('Edit group'),
592 '$ungrouped' => $every === 'contact' ? DI::l10n()->t('Contacts not in any group') : '',
593 '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
594 '$createtext' => DI::l10n()->t('Create a new group'),
595 '$creategroup' => DI::l10n()->t('Group Name: '),
596 '$editgroupstext' => DI::l10n()->t('Edit groups'),
597 '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
604 * Fetch the group id for the given contact id
606 * @param integer $id Contact ID
607 * @return integer Group IO
609 public static function getIdForForum(int $id): int
611 Logger::info('Get id for forum id', ['id' => $id]);
612 $contact = Contact::getById($id, ['uid', 'name', 'contact-type', 'manually-approve']);
613 if (empty($contact) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY) || !$contact['manually-approve']) {
617 $group = DBA::selectFirst('group', ['id'], ['uid' => $contact['uid'], 'cid' => $id]);
620 'uid' => $contact['uid'],
621 'name' => $contact['name'],
624 DBA::insert('group', $fields);
625 $gid = DBA::lastInsertId();
634 * Fetch the followers of a given contact id and store them as group members
636 * @param integer $id Contact ID
639 public static function updateMembersForForum(int $id)
641 Logger::info('Update forum members', ['id' => $id]);
643 $contact = Contact::getById($id, ['uid', 'url']);
644 if (empty($contact)) {
648 $apcontact = APContact::getByURL($contact['url']);
649 if (empty($apcontact['followers'])) {
653 $gid = self::getIdForForum($id);
658 $group_members = DBA::selectToArray('group_member', ['contact-id'], ['gid' => $gid]);
659 if (!empty($group_members)) {
660 $current = array_unique(array_column($group_members, 'contact-id'));
665 foreach (ActivityPub::fetchItems($apcontact['followers'], $contact['uid']) as $follower) {
666 $id = Contact::getIdForURL($follower);
667 if (!in_array($id, $current)) {
668 DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $id]);
670 $key = array_search($id, $current);
671 unset($current[$key]);
675 DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $current]);
676 Logger::info('Updated forum members', ['id' => $id, 'count' => DBA::count('group_member', ['gid' => $gid])]);