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];
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 * Returns the combined list of contact ids from a group id list
317 * @param array $group_ids
318 * @param boolean $check_dead
322 public static function expand($uid, array $group_ids, $check_dead = false)
324 if (!is_array($group_ids) || !count($group_ids)) {
330 $networks = Protocol::SUPPORT_PRIVATE;
332 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $uid]);
333 if (DBA::isResult($mailacct)) {
334 $pubmail = $mailacct['pubmail'];
338 $networks = array_diff($networks, [Protocol::MAIL]);
341 $key = array_search(self::FOLLOWERS, $group_ids);
342 if ($key !== false) {
343 $followers = Contact::selectToArray(['id'], [
345 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
346 'network' => $networks,
347 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
353 foreach ($followers as $follower) {
354 $return[] = $follower['id'];
357 unset($group_ids[$key]);
360 $key = array_search(self::MUTUALS, $group_ids);
361 if ($key !== false) {
362 $mutuals = Contact::selectToArray(['id'], [
364 'rel' => [Contact::FRIEND],
365 'network' => $networks,
366 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
372 foreach ($mutuals as $mutual) {
373 $return[] = $mutual['id'];
376 unset($group_ids[$key]);
379 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
380 while ($group_member = DBA::fetch($stmt)) {
381 $return[] = $group_member['contact-id'];
386 $return = Contact::pruneUnavailable($return);
393 * Returns a templated group selection list
396 * @param int $gid An optional pre-selected group
397 * @param string $label An optional label of the list
401 public static function displayGroupSelection($uid, $gid = 0, $label = '')
411 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid], ['order' => ['name']]);
412 while ($group = DBA::fetch($stmt)) {
413 $display_groups[] = [
414 'name' => $group['name'],
415 'id' => $group['id'],
416 'selected' => $gid == $group['id'] ? 'true' : ''
421 Logger::info('Got groups', $display_groups);
424 $label = DI::l10n()->t('Default privacy group for new contacts');
427 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
429 '$groups' => $display_groups
435 * Create group sidebar widget
437 * @param string $every
438 * @param string $each
439 * @param string $editmode
440 * 'standard' => include link 'Edit groups'
441 * 'extended' => include link 'Create new group'
442 * 'full' => include link 'Create new group' and provide for each group a link to edit this group
443 * @param string $group_id
448 public static function sidebarWidget($every = 'contact', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
456 'text' => DI::l10n()->t('Everybody'),
458 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
465 $member_of = self::getIdsByContactId($cid);
468 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => local_user()], ['order' => ['name']]);
469 while ($group = DBA::fetch($stmt)) {
470 $selected = (($group_id == $group['id']) ? ' group-selected' : '');
472 if ($editmode == 'full') {
474 'href' => 'group/' . $group['id'],
475 'title' => DI::l10n()->t('edit'),
481 if ($each == 'group') {
482 $count = DBA::count('group_member', ['gid' => $group['id']]);
483 $group_name = sprintf('%s (%d)', $group['name'], $count);
485 $group_name = $group['name'];
488 $display_groups[] = [
489 'id' => $group['id'],
491 'text' => $group_name,
492 'href' => $each . '/' . $group['id'],
493 'edit' => $groupedit,
494 'selected' => $selected,
495 'ismember' => in_array($group['id'], $member_of),
500 // Don't show the groups on the network page when there is only one
501 if ((count($display_groups) <= 2) && ($each == 'network')) {
505 $tpl = Renderer::getMarkupTemplate('group_side.tpl');
506 $o = Renderer::replaceMacros($tpl, [
507 '$add' => DI::l10n()->t('add'),
508 '$title' => DI::l10n()->t('Groups'),
509 '$groups' => $display_groups,
510 'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
511 'grouppage' => 'group/',
512 '$edittext' => DI::l10n()->t('Edit group'),
513 '$ungrouped' => $every === 'contact' ? DI::l10n()->t('Contacts not in any group') : '',
514 '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
515 '$createtext' => DI::l10n()->t('Create a new group'),
516 '$creategroup' => DI::l10n()->t('Group Name: '),
517 '$editgroupstext' => DI::l10n()->t('Edit groups'),
518 '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
525 * Fetch the followers of a given contact id and store them as group members
527 * @param integer $id Contact ID
529 public static function getMembersForForum(int $id) {
530 $contact = Contact::getById($id, ['uid', 'url', 'name']);
531 if (empty($contact)) {
535 $apcontact = APContact::getByURL($contact['url']);
536 if (empty($apcontact['followers'])) {
540 $group = DBA::selectFirst('group', ['id'], ['uid' => $contact['uid'], 'cid' => $id]);
543 'uid' => $contact['uid'],
544 'name' => $contact['name'],
547 DBA::insert('group', $fields);
548 $gid = DBA::lastInsertId();
553 $group_members = DBA::selectToArray('group_member', ['contact-id'], ['gid' => $gid]);
554 if (!empty($group_members)) {
555 $current = array_unique(array_column($group_members, 'contact-id'));
560 foreach (ActivityPub::fetchItems($apcontact['followers']) as $follower) {
561 $id = Contact::getIdForURL($follower);
562 if (!in_array($id, $current)) {
563 DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $id]);
565 $key = array_search($id, $current);
566 unset($current[$key]);
570 DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $current]);