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 = '~';
42 public static function getByUserId($uid, $includesDeleted = false)
44 $conditions = ['uid' => $uid, 'cid' => null];
46 if (!$includesDeleted) {
47 $conditions['deleted'] = false;
50 return DBA::selectToArray('group', [], $conditions);
54 * @param int $group_id
58 public static function exists($group_id, $uid = null)
60 $condition = ['id' => $group_id, 'deleted' => false];
68 return DBA::exists('group', $condition);
72 * Create a new contact group
74 * Note: If we found a deleted group with the same name, we restore it
81 public static function create($uid, $name)
84 if (!empty($uid) && !empty($name)) {
85 $gid = self::getIdByName($uid, $name); // check for dupes
87 // This could be a problem.
88 // Let's assume we've just created a group which we once deleted
89 // all the old members are gone, but the group remains so we don't break any security
90 // access lists. What we're doing here is reviving the dead group, but old content which
91 // was restricted to this group may now be seen by the new group members.
92 $group = DBA::selectFirst('group', ['deleted'], ['id' => $gid]);
93 if (DBA::isResult($group) && $group['deleted']) {
94 DBA::update('group', ['deleted' => 0], ['id' => $gid]);
95 notice(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.'));
100 $return = DBA::insert('group', ['uid' => $uid, 'name' => $name]);
102 $return = DBA::lastInsertId();
109 * Update group information.
111 * @param int $id Group ID
112 * @param string $name Group name
114 * @return bool Was the update successful?
117 public static function update($id, $name)
119 return DBA::update('group', ['name' => $name], ['id' => $id]);
123 * Get a list of group ids a contact belongs to
129 public static function getIdsByContactId($cid)
133 $stmt = DBA::select('group_member', ['gid'], ['contact-id' => $cid]);
134 while ($group = DBA::fetch($stmt)) {
135 $return[] = $group['gid'];
140 $contact = Contact::getById($cid, ['rel']);
141 if ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND) {
142 $return[] = self::FOLLOWERS;
145 if ($contact['rel'] == Contact::FRIEND) {
146 $return[] = self::MUTUALS;
153 * count unread group items
155 * Count unread items of each groups of the local user
159 * 'name' => group name
160 * 'count' => counted unseen group items
163 public static function countUnseen()
165 $stmt = DBA::p("SELECT `group`.`id`, `group`.`name`,
166 (SELECT COUNT(*) FROM `post-user`
172 WHERE `group_member`.`gid` = `group`.`id`)
175 WHERE `group`.`uid` = ?;",
180 return DBA::toArray($stmt);
184 * Get the group id for a user/name couple
186 * Returns false if no group has been found.
189 * @param string $name
190 * @return int|boolean
193 public static function getIdByName($uid, $name)
195 if (!$uid || !strlen($name)) {
199 $group = DBA::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]);
200 if (DBA::isResult($group)) {
208 * Mark a group as deleted
214 public static function remove($gid)
220 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
221 if (!DBA::isResult($group)) {
225 // remove group from default posting lists
226 $user = DBA::selectFirst('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $group['uid']]);
227 if (DBA::isResult($user)) {
230 if ($user['def_gid'] == $gid) {
231 $user['def_gid'] = 0;
234 if (strpos($user['allow_gid'], '<' . $gid . '>') !== false) {
235 $user['allow_gid'] = str_replace('<' . $gid . '>', '', $user['allow_gid']);
238 if (strpos($user['deny_gid'], '<' . $gid . '>') !== false) {
239 $user['deny_gid'] = str_replace('<' . $gid . '>', '', $user['deny_gid']);
244 DBA::update('user', $user, ['uid' => $group['uid']]);
248 // remove all members
249 DBA::delete('group_member', ['gid' => $gid]);
252 $return = DBA::update('group', ['deleted' => 1], ['id' => $gid]);
258 * Adds a contact to a group
265 public static function addMember(int $gid, int $cid): bool
267 if (!$gid || !$cid) {
271 // @TODO Backward compatibility with user contacts, remove by version 2022.03
272 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
274 throw new HTTPException\NotFoundException('Group not found.');
277 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
278 if (empty($cdata['user'])) {
279 throw new HTTPException\NotFoundException('Invalid contact.');
282 return DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cdata['user']], Database::INSERT_IGNORE);
286 * Removes a contact from a group
293 public static function removeMember(int $gid, int $cid): bool
295 if (!$gid || !$cid) {
299 // @TODO Backward compatibility with user contacts, remove by version 2022.03
300 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
302 throw new HTTPException\NotFoundException('Group not found.');
305 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
306 if (empty($cdata['user'])) {
307 throw new HTTPException\NotFoundException('Invalid contact.');
310 return DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $cid]);
314 * Adds contacts to a group
317 * @param array $contacts
320 public static function addMembers(int $gid, array $contacts)
322 if (!$gid || !$contacts) {
326 // @TODO Backward compatibility with user contacts, remove by version 2022.03
327 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
329 throw new HTTPException\NotFoundException('Group not found.');
332 foreach ($contacts as $cid) {
333 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
334 if (empty($cdata['user'])) {
335 throw new HTTPException\NotFoundException('Invalid contact.');
338 DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cdata['user']], Database::INSERT_IGNORE);
343 * Removes contacts from a group
346 * @param array $contacts
349 public static function removeMembers(int $gid, array $contacts)
351 if (!$gid || !$contacts) {
355 // @TODO Backward compatibility with user contacts, remove by version 2022.03
356 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
358 throw new HTTPException\NotFoundException('Group not found.');
363 foreach ($contacts as $cid) {
364 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
365 if (empty($cdata['user'])) {
366 throw new HTTPException\NotFoundException('Invalid contact.');
369 $contactIds[] = $cdata['user'];
372 DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $contactIds]);
376 * Returns the combined list of contact ids from a group id list
379 * @param array $group_ids
380 * @param boolean $check_dead
384 public static function expand($uid, array $group_ids, $check_dead = false)
386 if (!is_array($group_ids) || !count($group_ids)) {
392 $networks = Protocol::SUPPORT_PRIVATE;
394 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $uid]);
395 if (DBA::isResult($mailacct)) {
396 $pubmail = $mailacct['pubmail'];
400 $networks = array_diff($networks, [Protocol::MAIL]);
403 $key = array_search(self::FOLLOWERS, $group_ids);
404 if ($key !== false) {
405 $followers = Contact::selectToArray(['id'], [
407 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
408 'network' => $networks,
409 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
415 foreach ($followers as $follower) {
416 $return[] = $follower['id'];
419 unset($group_ids[$key]);
422 $key = array_search(self::MUTUALS, $group_ids);
423 if ($key !== false) {
424 $mutuals = Contact::selectToArray(['id'], [
426 'rel' => [Contact::FRIEND],
427 'network' => $networks,
428 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
434 foreach ($mutuals as $mutual) {
435 $return[] = $mutual['id'];
438 unset($group_ids[$key]);
441 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
442 while ($group_member = DBA::fetch($stmt)) {
443 $return[] = $group_member['contact-id'];
448 $return = Contact::pruneUnavailable($return);
455 * Returns a templated group selection list
458 * @param int $gid An optional pre-selected group
459 * @param string $label An optional label of the list
463 public static function displayGroupSelection($uid, $gid = 0, $label = '')
473 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => $uid, 'cid' => null], ['order' => ['name']]);
474 while ($group = DBA::fetch($stmt)) {
475 $display_groups[] = [
476 'name' => $group['name'],
477 'id' => $group['id'],
478 'selected' => $gid == $group['id'] ? 'true' : ''
483 Logger::info('Got groups', $display_groups);
486 $label = DI::l10n()->t('Default privacy group for new contacts');
489 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
491 '$groups' => $display_groups
497 * Create group sidebar widget
499 * @param string $every
500 * @param string $each
501 * @param string $editmode
502 * 'standard' => include link 'Edit groups'
503 * 'extended' => include link 'Create new group'
504 * 'full' => include link 'Create new group' and provide for each group a link to edit this group
505 * @param string $group_id
510 public static function sidebarWidget($every = 'contact', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
518 'text' => DI::l10n()->t('Everybody'),
520 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
527 $member_of = self::getIdsByContactId($cid);
530 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => local_user(), 'cid' => null], ['order' => ['name']]);
531 while ($group = DBA::fetch($stmt)) {
532 $selected = (($group_id == $group['id']) ? ' group-selected' : '');
534 if ($editmode == 'full') {
536 'href' => 'group/' . $group['id'],
537 'title' => DI::l10n()->t('edit'),
543 if ($each == 'group') {
544 $count = DBA::count('group_member', ['gid' => $group['id']]);
545 $group_name = sprintf('%s (%d)', $group['name'], $count);
547 $group_name = $group['name'];
550 $display_groups[] = [
551 'id' => $group['id'],
553 'text' => $group_name,
554 'href' => $each . '/' . $group['id'],
555 'edit' => $groupedit,
556 'selected' => $selected,
557 'ismember' => in_array($group['id'], $member_of),
562 // Don't show the groups on the network page when there is only one
563 if ((count($display_groups) <= 2) && ($each == 'network')) {
567 $tpl = Renderer::getMarkupTemplate('group_side.tpl');
568 $o = Renderer::replaceMacros($tpl, [
569 '$add' => DI::l10n()->t('add'),
570 '$title' => DI::l10n()->t('Groups'),
571 '$groups' => $display_groups,
572 'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
573 'grouppage' => 'group/',
574 '$edittext' => DI::l10n()->t('Edit group'),
575 '$ungrouped' => $every === 'contact' ? DI::l10n()->t('Contacts not in any group') : '',
576 '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
577 '$createtext' => DI::l10n()->t('Create a new group'),
578 '$creategroup' => DI::l10n()->t('Group Name: '),
579 '$editgroupstext' => DI::l10n()->t('Edit groups'),
580 '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
587 * Fetch the group id for the given contact id
589 * @param integer $id Contact ID
590 * @return integer Group IO
592 public static function getIdForForum(int $id)
594 Logger::info('Get id for forum id', ['id' => $id]);
595 $contact = Contact::getById($id, ['uid', 'name', 'contact-type', 'manually-approve']);
596 if (empty($contact) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY) || !$contact['manually-approve']) {
600 $group = DBA::selectFirst('group', ['id'], ['uid' => $contact['uid'], 'cid' => $id]);
603 'uid' => $contact['uid'],
604 'name' => $contact['name'],
607 DBA::insert('group', $fields);
608 $gid = DBA::lastInsertId();
617 * Fetch the followers of a given contact id and store them as group members
619 * @param integer $id Contact ID
621 public static function updateMembersForForum(int $id)
623 Logger::info('Update forum members', ['id' => $id]);
625 $contact = Contact::getById($id, ['uid', 'url']);
626 if (empty($contact)) {
630 $apcontact = APContact::getByURL($contact['url']);
631 if (empty($apcontact['followers'])) {
635 $gid = self::getIdForForum($id);
640 $group_members = DBA::selectToArray('group_member', ['contact-id'], ['gid' => $gid]);
641 if (!empty($group_members)) {
642 $current = array_unique(array_column($group_members, 'contact-id'));
647 foreach (ActivityPub::fetchItems($apcontact['followers'], $contact['uid']) as $follower) {
648 $id = Contact::getIdForURL($follower);
649 if (!in_array($id, $current)) {
650 DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $id]);
652 $key = array_search($id, $current);
653 unset($current[$key]);
657 DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $current]);
658 Logger::info('Updated forum members', ['id' => $id, 'count' => DBA::count('group_member', ['gid' => $gid])]);