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\Core\Session;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
32 use Friendica\Network\HTTPException;
33 use Friendica\Protocol\ActivityPub;
36 * functions for interacting with the group database table
40 const FOLLOWERS = '~';
44 * Fetches group record by user id and maybe includes deleted groups as well
46 * @param int $uid User id to fetch group(s) for
47 * @param bool $includesDeleted Whether deleted groups should be included
48 * @return array|bool Array on success, bool on error
50 public static function getByUserId(int $uid, bool $includesDeleted = false)
52 $conditions = ['uid' => $uid, 'cid' => null];
54 if (!$includesDeleted) {
55 $conditions['deleted'] = false;
58 return DBA::selectToArray('group', [], $conditions);
62 * Checks whether given group id is found in database
64 * @param int $group_id Groupd it
65 * @param int $uid Optional user id
69 public static function exists(int $group_id, int $uid = null): bool
71 $condition = ['id' => $group_id, 'deleted' => false];
79 return DBA::exists('group', $condition);
83 * Create a new contact group
85 * Note: If we found a deleted group with the same name, we restore it
87 * @param int $uid User id to create group for
88 * @param string $name Name of group
89 * @return int|boolean Id of newly created group or false on error
92 public static function create(int $uid, string $name)
95 if (!empty($uid) && !empty($name)) {
96 $gid = self::getIdByName($uid, $name); // check for dupes
98 // This could be a problem.
99 // Let's assume we've just created a group which we once deleted
100 // all the old members are gone, but the group remains so we don't break any security
101 // access lists. What we're doing here is reviving the dead group, but old content which
102 // was restricted to this group may now be seen by the new group members.
103 $group = DBA::selectFirst('group', ['deleted'], ['id' => $gid]);
104 if (DBA::isResult($group) && $group['deleted']) {
105 DBA::update('group', ['deleted' => 0], ['id' => $gid]);
106 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.'));
111 $return = DBA::insert('group', ['uid' => $uid, 'name' => $name]);
113 $return = DBA::lastInsertId();
120 * Update group information.
122 * @param int $id Group ID
123 * @param string $name Group name
125 * @return bool Was the update successful?
128 public static function update(int $id, string $name): bool
130 return DBA::update('group', ['name' => $name], ['id' => $id]);
134 * Get a list of group ids a contact belongs to
136 * @param int $cid Contact id
137 * @return array Group ids
140 public static function getIdsByContactId(int $cid): array
142 $contact = Contact::getById($cid, ['rel']);
149 $stmt = DBA::select('group_member', ['gid'], ['contact-id' => $cid]);
150 while ($group = DBA::fetch($stmt)) {
151 $groupIds[] = $group['gid'];
156 if ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND) {
157 $groupIds[] = self::FOLLOWERS;
160 if ($contact['rel'] == Contact::FRIEND) {
161 $groupIds[] = self::MUTUALS;
168 * count unread group items
170 * Count unread items of each groups of the local user
174 * 'name' => group name
175 * 'count' => counted unseen group items
178 public static function countUnseen()
180 $stmt = DBA::p("SELECT `group`.`id`, `group`.`name`,
181 (SELECT COUNT(*) FROM `post-user`
187 WHERE `group_member`.`gid` = `group`.`id`)
190 WHERE `group`.`uid` = ?;",
191 Session::getLocalUser(),
192 Session::getLocalUser()
195 return DBA::toArray($stmt);
199 * Get the group id for a user/name couple
201 * Returns false if no group has been found.
203 * @param int $uid User id
204 * @param string $name Group name
205 * @return int|boolean Groups' id number or false on error
208 public static function getIdByName(int $uid, string $name)
210 if (!$uid || !strlen($name)) {
214 $group = DBA::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]);
215 if (DBA::isResult($group)) {
223 * Mark a group as deleted
229 public static function remove(int $gid): bool
235 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
236 if (!DBA::isResult($group)) {
240 // remove group from default posting lists
241 $user = DBA::selectFirst('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $group['uid']]);
242 if (DBA::isResult($user)) {
245 if ($user['def_gid'] == $gid) {
246 $user['def_gid'] = 0;
249 if (strpos($user['allow_gid'], '<' . $gid . '>') !== false) {
250 $user['allow_gid'] = str_replace('<' . $gid . '>', '', $user['allow_gid']);
253 if (strpos($user['deny_gid'], '<' . $gid . '>') !== false) {
254 $user['deny_gid'] = str_replace('<' . $gid . '>', '', $user['deny_gid']);
259 DBA::update('user', $user, ['uid' => $group['uid']]);
263 // remove all members
264 DBA::delete('group_member', ['gid' => $gid]);
267 $return = DBA::update('group', ['deleted' => 1], ['id' => $gid]);
273 * Adds a contact to a group
280 public static function addMember(int $gid, int $cid): bool
282 if (!$gid || !$cid) {
286 // @TODO Backward compatibility with user contacts, remove by version 2022.03
287 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
289 throw new HTTPException\NotFoundException('Group not found.');
292 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
293 if (empty($cdata['user'])) {
294 throw new HTTPException\NotFoundException('Invalid contact.');
297 return DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cdata['user']], Database::INSERT_IGNORE);
301 * Removes a contact from a group
308 public static function removeMember(int $gid, int $cid): bool
310 if (!$gid || !$cid) {
314 // @TODO Backward compatibility with user contacts, remove by version 2022.03
315 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
317 throw new HTTPException\NotFoundException('Group not found.');
320 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
321 if (empty($cdata['user'])) {
322 throw new HTTPException\NotFoundException('Invalid contact.');
325 return DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $cid]);
329 * Adds contacts to a group
332 * @param array $contacts Array with contact ids
336 public static function addMembers(int $gid, array $contacts)
338 if (!$gid || !$contacts) {
342 // @TODO Backward compatibility with user contacts, remove by version 2022.03
343 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
345 throw new HTTPException\NotFoundException('Group not found.');
348 foreach ($contacts as $cid) {
349 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
350 if (empty($cdata['user'])) {
351 throw new HTTPException\NotFoundException('Invalid contact.');
354 DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cdata['user']], Database::INSERT_IGNORE);
359 * Removes contacts from a group
361 * @param int $gid Group id
362 * @param array $contacts Contact ids
366 public static function removeMembers(int $gid, array $contacts)
368 if (!$gid || !$contacts) {
372 // @TODO Backward compatibility with user contacts, remove by version 2022.03
373 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
375 throw new HTTPException\NotFoundException('Group not found.');
380 foreach ($contacts as $cid) {
381 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
382 if (empty($cdata['user'])) {
383 throw new HTTPException\NotFoundException('Invalid contact.');
386 $contactIds[] = $cdata['user'];
389 // Return status of deletion
390 return DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $contactIds]);
394 * Returns the combined list of contact ids from a group id list
396 * @param int $uid User id
397 * @param array $group_ids Groups ids
398 * @param boolean $check_dead Whether check "dead" records (?)
402 public static function expand(int $uid, array $group_ids, bool $check_dead = false): array
404 if (!is_array($group_ids) || !count($group_ids)) {
410 $networks = Protocol::SUPPORT_PRIVATE;
412 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $uid]);
413 if (DBA::isResult($mailacct)) {
414 $pubmail = $mailacct['pubmail'];
418 $networks = array_diff($networks, [Protocol::MAIL]);
421 $key = array_search(self::FOLLOWERS, $group_ids);
422 if ($key !== false) {
423 $followers = Contact::selectToArray(['id'], [
425 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
426 'network' => $networks,
427 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
433 foreach ($followers as $follower) {
434 $return[] = $follower['id'];
437 unset($group_ids[$key]);
440 $key = array_search(self::MUTUALS, $group_ids);
441 if ($key !== false) {
442 $mutuals = Contact::selectToArray(['id'], [
444 'rel' => [Contact::FRIEND],
445 'network' => $networks,
446 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
452 foreach ($mutuals as $mutual) {
453 $return[] = $mutual['id'];
456 unset($group_ids[$key]);
459 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
460 while ($group_member = DBA::fetch($stmt)) {
461 $return[] = $group_member['contact-id'];
466 $return = Contact::pruneUnavailable($return);
473 * Returns a templated group selection list
475 * @param int $uid User id
476 * @param int $gid An optional pre-selected group
477 * @param string $label An optional label of the list
481 public static function displayGroupSelection(int $uid, int $gid = 0, string $label = ''): string
491 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => $uid, 'cid' => null], ['order' => ['name']]);
492 while ($group = DBA::fetch($stmt)) {
493 $display_groups[] = [
494 'name' => $group['name'],
495 'id' => $group['id'],
496 'selected' => $gid == $group['id'] ? 'true' : ''
501 Logger::info('Got groups', $display_groups);
504 $label = DI::l10n()->t('Default privacy group for new contacts');
507 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
509 '$groups' => $display_groups
515 * Create group sidebar widget
517 * @param string $every
518 * @param string $each
519 * @param string $editmode
520 * 'standard' => include link 'Edit groups'
521 * 'extended' => include link 'Create new group'
522 * 'full' => include link 'Create new group' and provide for each group a link to edit this group
523 * @param string|int $group_id Distinct group id or 'everyone'
524 * @param int $cid Contact id
525 * @return string Sidebar widget HTML code
528 public static function sidebarWidget(string $every = 'contact', string $each = 'group', string $editmode = 'standard', $group_id = '', int $cid = 0)
530 if (!Session::getLocalUser()) {
536 'text' => DI::l10n()->t('Everybody'),
538 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
545 $member_of = self::getIdsByContactId($cid);
548 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => Session::getLocalUser(), 'cid' => null], ['order' => ['name']]);
549 while ($group = DBA::fetch($stmt)) {
550 $selected = (($group_id == $group['id']) ? ' group-selected' : '');
552 if ($editmode == 'full') {
554 'href' => 'group/' . $group['id'],
555 'title' => DI::l10n()->t('edit'),
561 if ($each == 'group') {
562 $count = DBA::count('group_member', ['gid' => $group['id']]);
563 $group_name = sprintf('%s (%d)', $group['name'], $count);
565 $group_name = $group['name'];
568 $display_groups[] = [
569 'id' => $group['id'],
571 'text' => $group_name,
572 'href' => $each . '/' . $group['id'],
573 'edit' => $groupedit,
574 'selected' => $selected,
575 'ismember' => in_array($group['id'], $member_of),
580 // Don't show the groups on the network page when there is only one
581 if ((count($display_groups) <= 2) && ($each == 'network')) {
585 $tpl = Renderer::getMarkupTemplate('group_side.tpl');
586 $o = Renderer::replaceMacros($tpl, [
587 '$add' => DI::l10n()->t('add'),
588 '$title' => DI::l10n()->t('Groups'),
589 '$groups' => $display_groups,
590 'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
591 'grouppage' => 'group/',
592 '$edittext' => DI::l10n()->t('Edit group'),
593 '$ungrouped' => $every === 'contact' ? DI::l10n()->t('Contacts not in any group') : '',
594 '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
595 '$createtext' => DI::l10n()->t('Create a new group'),
596 '$creategroup' => DI::l10n()->t('Group Name: '),
597 '$editgroupstext' => DI::l10n()->t('Edit groups'),
598 '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
605 * Fetch the group id for the given contact id
607 * @param integer $id Contact ID
608 * @return integer Group IO
610 public static function getIdForForum(int $id): int
612 Logger::info('Get id for forum id', ['id' => $id]);
613 $contact = Contact::getById($id, ['uid', 'name', 'contact-type', 'manually-approve']);
614 if (empty($contact) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY) || !$contact['manually-approve']) {
618 $group = DBA::selectFirst('group', ['id'], ['uid' => $contact['uid'], 'cid' => $id]);
621 'uid' => $contact['uid'],
622 'name' => $contact['name'],
625 DBA::insert('group', $fields);
626 $gid = DBA::lastInsertId();
635 * Fetch the followers of a given contact id and store them as group members
637 * @param integer $id Contact ID
640 public static function updateMembersForForum(int $id)
642 Logger::info('Update forum members', ['id' => $id]);
644 $contact = Contact::getById($id, ['uid', 'url']);
645 if (empty($contact)) {
649 $apcontact = APContact::getByURL($contact['url']);
650 if (empty($apcontact['followers'])) {
654 $gid = self::getIdForForum($id);
659 $group_members = DBA::selectToArray('group_member', ['contact-id'], ['gid' => $gid]);
660 if (!empty($group_members)) {
661 $current = array_unique(array_column($group_members, 'contact-id'));
666 foreach (ActivityPub::fetchItems($apcontact['followers'], $contact['uid']) as $follower) {
667 $id = Contact::getIdForURL($follower);
668 if (!in_array($id, $current)) {
669 DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $id]);
671 $key = array_search($id, $current);
672 unset($current[$key]);
676 DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $current]);
677 Logger::info('Updated forum members', ['id' => $id, 'count' => DBA::count('group_member', ['gid' => $gid])]);