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;
34 * functions for interacting with the group database table
38 const FOLLOWERS = '~';
41 public static function getByUserId($uid, $includesDeleted = false)
43 $conditions = ['uid' => $uid];
45 if (!$includesDeleted) {
46 $conditions['deleted'] = false;
49 return DBA::selectToArray('group', [], $conditions);
53 * @param int $group_id
57 public static function exists($group_id, $uid = null)
59 $condition = ['id' => $group_id, 'deleted' => false];
67 return DBA::exists('group', $condition);
71 * Create a new contact group
73 * Note: If we found a deleted group with the same name, we restore it
80 public static function create($uid, $name)
83 if (!empty($uid) && !empty($name)) {
84 $gid = self::getIdByName($uid, $name); // check for dupes
86 // This could be a problem.
87 // Let's assume we've just created a group which we once deleted
88 // all the old members are gone, but the group remains so we don't break any security
89 // access lists. What we're doing here is reviving the dead group, but old content which
90 // was restricted to this group may now be seen by the new group members.
91 $group = DBA::selectFirst('group', ['deleted'], ['id' => $gid]);
92 if (DBA::isResult($group) && $group['deleted']) {
93 DBA::update('group', ['deleted' => 0], ['id' => $gid]);
94 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.'));
99 $return = DBA::insert('group', ['uid' => $uid, 'name' => $name]);
101 $return = DBA::lastInsertId();
108 * Update group information.
110 * @param int $id Group ID
111 * @param string $name Group name
113 * @return bool Was the update successful?
116 public static function update($id, $name)
118 return DBA::update('group', ['name' => $name], ['id' => $id]);
122 * Get a list of group ids a contact belongs to
128 public static function getIdsByContactId($cid)
132 $stmt = DBA::select('group_member', ['gid'], ['contact-id' => $cid]);
133 while ($group = DBA::fetch($stmt)) {
134 $return[] = $group['gid'];
139 $contact = Contact::getById($cid, ['rel']);
140 if ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND) {
141 $return[] = self::FOLLOWERS;
144 if ($contact['rel'] == Contact::FRIEND) {
145 $return[] = self::MUTUALS;
152 * count unread group items
154 * Count unread items of each groups of the local user
158 * 'name' => group name
159 * 'count' => counted unseen group items
162 public static function countUnseen()
164 $stmt = DBA::p("SELECT `group`.`id`, `group`.`name`,
165 (SELECT COUNT(*) FROM `post-user`
171 WHERE `group_member`.`gid` = `group`.`id`)
174 WHERE `group`.`uid` = ?;",
179 return DBA::toArray($stmt);
183 * Get the group id for a user/name couple
185 * Returns false if no group has been found.
188 * @param string $name
189 * @return int|boolean
192 public static function getIdByName($uid, $name)
194 if (!$uid || !strlen($name)) {
198 $group = DBA::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]);
199 if (DBA::isResult($group)) {
207 * Mark a group as deleted
213 public static function remove($gid)
219 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
220 if (!DBA::isResult($group)) {
224 // remove group from default posting lists
225 $user = DBA::selectFirst('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $group['uid']]);
226 if (DBA::isResult($user)) {
229 if ($user['def_gid'] == $gid) {
230 $user['def_gid'] = 0;
233 if (strpos($user['allow_gid'], '<' . $gid . '>') !== false) {
234 $user['allow_gid'] = str_replace('<' . $gid . '>', '', $user['allow_gid']);
237 if (strpos($user['deny_gid'], '<' . $gid . '>') !== false) {
238 $user['deny_gid'] = str_replace('<' . $gid . '>', '', $user['deny_gid']);
243 DBA::update('user', $user, ['uid' => $group['uid']]);
247 // remove all members
248 DBA::delete('group_member', ['gid' => $gid]);
251 $return = DBA::update('group', ['deleted' => 1], ['id' => $gid]);
257 * Adds a contact to a group
264 public static function addMember(int $gid, int $cid): bool
266 if (!$gid || !$cid) {
270 // @TODO Backward compatibility with user contacts, remove by version 2022.03
271 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
273 throw new HTTPException\NotFoundException('Group not found.');
276 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
277 if (empty($cdata['user'])) {
278 throw new HTTPException\NotFoundException('Invalid contact.');
281 return DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cdata['user']], Database::INSERT_IGNORE);
285 * Removes a contact from a group
292 public static function removeMember(int $gid, int $cid): bool
294 if (!$gid || !$cid) {
298 // @TODO Backward compatibility with user contacts, remove by version 2022.03
299 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
301 throw new HTTPException\NotFoundException('Group not found.');
304 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
305 if (empty($cdata['user'])) {
306 throw new HTTPException\NotFoundException('Invalid contact.');
309 return DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $cid]);
313 * Returns the combined list of contact ids from a group id list
316 * @param array $group_ids
317 * @param boolean $check_dead
321 public static function expand($uid, array $group_ids, $check_dead = false)
323 if (!is_array($group_ids) || !count($group_ids)) {
329 $networks = Protocol::SUPPORT_PRIVATE;
331 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $uid]);
332 if (DBA::isResult($mailacct)) {
333 $pubmail = $mailacct['pubmail'];
337 $networks = array_diff($networks, [Protocol::MAIL]);
340 $key = array_search(self::FOLLOWERS, $group_ids);
341 if ($key !== false) {
342 $followers = Contact::selectToArray(['id'], [
344 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
345 'network' => $networks,
346 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
352 foreach ($followers as $follower) {
353 $return[] = $follower['id'];
356 unset($group_ids[$key]);
359 $key = array_search(self::MUTUALS, $group_ids);
360 if ($key !== false) {
361 $mutuals = Contact::selectToArray(['id'], [
363 'rel' => [Contact::FRIEND],
364 'network' => $networks,
365 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
371 foreach ($mutuals as $mutual) {
372 $return[] = $mutual['id'];
375 unset($group_ids[$key]);
378 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
379 while ($group_member = DBA::fetch($stmt)) {
380 $return[] = $group_member['contact-id'];
385 $return = Contact::pruneUnavailable($return);
392 * Returns a templated group selection list
395 * @param int $gid An optional pre-selected group
396 * @param string $label An optional label of the list
400 public static function displayGroupSelection($uid, $gid = 0, $label = '')
410 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid], ['order' => ['name']]);
411 while ($group = DBA::fetch($stmt)) {
412 $display_groups[] = [
413 'name' => $group['name'],
414 'id' => $group['id'],
415 'selected' => $gid == $group['id'] ? 'true' : ''
420 Logger::info('Got groups', $display_groups);
423 $label = DI::l10n()->t('Default privacy group for new contacts');
426 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
428 '$groups' => $display_groups
434 * Create group sidebar widget
436 * @param string $every
437 * @param string $each
438 * @param string $editmode
439 * 'standard' => include link 'Edit groups'
440 * 'extended' => include link 'Create new group'
441 * 'full' => include link 'Create new group' and provide for each group a link to edit this group
442 * @param string $group_id
447 public static function sidebarWidget($every = 'contact', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
455 'text' => DI::l10n()->t('Everybody'),
457 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
464 $member_of = self::getIdsByContactId($cid);
467 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => local_user()], ['order' => ['name']]);
468 while ($group = DBA::fetch($stmt)) {
469 $selected = (($group_id == $group['id']) ? ' group-selected' : '');
471 if ($editmode == 'full') {
473 'href' => 'group/' . $group['id'],
474 'title' => DI::l10n()->t('edit'),
480 if ($each == 'group') {
481 $count = DBA::count('group_member', ['gid' => $group['id']]);
482 $group_name = sprintf('%s (%d)', $group['name'], $count);
484 $group_name = $group['name'];
487 $display_groups[] = [
488 'id' => $group['id'],
490 'text' => $group_name,
491 'href' => $each . '/' . $group['id'],
492 'edit' => $groupedit,
493 'selected' => $selected,
494 'ismember' => in_array($group['id'], $member_of),
499 // Don't show the groups on the network page when there is only one
500 if ((count($display_groups) <= 2) && ($each == 'network')) {
504 $tpl = Renderer::getMarkupTemplate('group_side.tpl');
505 $o = Renderer::replaceMacros($tpl, [
506 '$add' => DI::l10n()->t('add'),
507 '$title' => DI::l10n()->t('Groups'),
508 '$groups' => $display_groups,
509 'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
510 'grouppage' => 'group/',
511 '$edittext' => DI::l10n()->t('Edit group'),
512 '$ungrouped' => $every === 'contact' ? DI::l10n()->t('Contacts not in any group') : '',
513 '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
514 '$createtext' => DI::l10n()->t('Create a new group'),
515 '$creategroup' => DI::l10n()->t('Group Name: '),
516 '$editgroupstext' => DI::l10n()->t('Edit groups'),
517 '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),