]> git.mxchange.org Git - friendica.git/blob - src/Model/Group.php
Merge pull request #10969 from MrPetovan/task/remove-private-contacts
[friendica.git] / src / Model / Group.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\Renderer;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30
31 /**
32  * functions for interacting with the group database table
33  */
34 class Group
35 {
36         const FOLLOWERS = '~';
37         const MUTUALS = '&';
38
39         public static function getByUserId($uid, $includesDeleted = false)
40         {
41                 $conditions = ['uid' => $uid];
42
43                 if (!$includesDeleted) {
44                         $conditions['deleted'] = false;
45                 }
46
47                 return DBA::selectToArray('group', [], $conditions);
48         }
49
50         /**
51          * @param int $group_id
52          * @return bool
53          * @throws \Exception
54          */
55         public static function exists($group_id, $uid = null)
56         {
57                 $condition = ['id' => $group_id, 'deleted' => false];
58
59                 if (isset($uid)) {
60                         $condition = [
61                                 'uid' => $uid
62                         ];
63                 }
64
65                 return DBA::exists('group', $condition);
66         }
67
68         /**
69          * Create a new contact group
70          *
71          * Note: If we found a deleted group with the same name, we restore it
72          *
73          * @param int    $uid
74          * @param string $name
75          * @return boolean
76          * @throws \Exception
77          */
78         public static function create($uid, $name)
79         {
80                 $return = false;
81                 if (!empty($uid) && !empty($name)) {
82                         $gid = self::getIdByName($uid, $name); // check for dupes
83                         if ($gid !== false) {
84                                 // This could be a problem.
85                                 // Let's assume we've just created a group which we once deleted
86                                 // all the old members are gone, but the group remains so we don't break any security
87                                 // access lists. What we're doing here is reviving the dead group, but old content which
88                                 // was restricted to this group may now be seen by the new group members.
89                                 $group = DBA::selectFirst('group', ['deleted'], ['id' => $gid]);
90                                 if (DBA::isResult($group) && $group['deleted']) {
91                                         DBA::update('group', ['deleted' => 0], ['id' => $gid]);
92                                         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.'));
93                                 }
94                                 return true;
95                         }
96
97                         $return = DBA::insert('group', ['uid' => $uid, 'name' => $name]);
98                         if ($return) {
99                                 $return = DBA::lastInsertId();
100                         }
101                 }
102                 return $return;
103         }
104
105         /**
106          * Update group information.
107          *
108          * @param int    $id   Group ID
109          * @param string $name Group name
110          *
111          * @return bool Was the update successful?
112          * @throws \Exception
113          */
114         public static function update($id, $name)
115         {
116                 return DBA::update('group', ['name' => $name], ['id' => $id]);
117         }
118
119         /**
120          * Get a list of group ids a contact belongs to
121          *
122          * @param int $cid
123          * @return array
124          * @throws \Exception
125          */
126         public static function getIdsByContactId($cid)
127         {
128                 $return = [];
129
130                 $stmt = DBA::select('group_member', ['gid'], ['contact-id' => $cid]);
131                 while ($group = DBA::fetch($stmt)) {
132                         $return[] = $group['gid'];
133                 }
134                 DBA::close($stmt);
135
136                 // Meta-groups
137                 $contact = Contact::getById($cid, ['rel']);
138                 if ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND) {
139                         $return[] = self::FOLLOWERS;
140                 }
141
142                 if ($contact['rel'] == Contact::FRIEND) {
143                         $return[] = self::MUTUALS;
144                 }
145
146                 return $return;
147         }
148
149         /**
150          * count unread group items
151          *
152          * Count unread items of each groups of the local user
153          *
154          * @return array
155          *    'id' => group id
156          *    'name' => group name
157          *    'count' => counted unseen group items
158          * @throws \Exception
159          */
160         public static function countUnseen()
161         {
162                 $stmt = DBA::p("SELECT `group`.`id`, `group`.`name`,
163                                 (SELECT COUNT(*) FROM `post-user`
164                                         WHERE `uid` = ?
165                                         AND `unseen`
166                                         AND `contact-id` IN
167                                                 (SELECT `contact-id`
168                                                 FROM `group_member`
169                                                 WHERE `group_member`.`gid` = `group`.`id`)
170                                         ) AS `count`
171                                 FROM `group`
172                                 WHERE `group`.`uid` = ?;",
173                         local_user(),
174                         local_user()
175                 );
176
177                 return DBA::toArray($stmt);
178         }
179
180         /**
181          * Get the group id for a user/name couple
182          *
183          * Returns false if no group has been found.
184          *
185          * @param int    $uid
186          * @param string $name
187          * @return int|boolean
188          * @throws \Exception
189          */
190         public static function getIdByName($uid, $name)
191         {
192                 if (!$uid || !strlen($name)) {
193                         return false;
194                 }
195
196                 $group = DBA::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]);
197                 if (DBA::isResult($group)) {
198                         return $group['id'];
199                 }
200
201                 return false;
202         }
203
204         /**
205          * Mark a group as deleted
206          *
207          * @param int $gid
208          * @return boolean
209          * @throws \Exception
210          */
211         public static function remove($gid)
212         {
213                 if (!$gid) {
214                         return false;
215                 }
216
217                 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
218                 if (!DBA::isResult($group)) {
219                         return false;
220                 }
221
222                 // remove group from default posting lists
223                 $user = DBA::selectFirst('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $group['uid']]);
224                 if (DBA::isResult($user)) {
225                         $change = false;
226
227                         if ($user['def_gid'] == $gid) {
228                                 $user['def_gid'] = 0;
229                                 $change = true;
230                         }
231                         if (strpos($user['allow_gid'], '<' . $gid . '>') !== false) {
232                                 $user['allow_gid'] = str_replace('<' . $gid . '>', '', $user['allow_gid']);
233                                 $change = true;
234                         }
235                         if (strpos($user['deny_gid'], '<' . $gid . '>') !== false) {
236                                 $user['deny_gid'] = str_replace('<' . $gid . '>', '', $user['deny_gid']);
237                                 $change = true;
238                         }
239
240                         if ($change) {
241                                 DBA::update('user', $user, ['uid' => $group['uid']]);
242                         }
243                 }
244
245                 // remove all members
246                 DBA::delete('group_member', ['gid' => $gid]);
247
248                 // remove group
249                 $return = DBA::update('group', ['deleted' => 1], ['id' => $gid]);
250
251                 return $return;
252         }
253
254         /**
255          * Adds a contact to a group
256          *
257          * @param int $gid
258          * @param int $cid
259          * @return boolean
260          * @throws \Exception
261          */
262         public static function addMember($gid, $cid)
263         {
264                 if (!$gid || !$cid) {
265                         return false;
266                 }
267
268                 $row_exists = DBA::exists('group_member', ['gid' => $gid, 'contact-id' => $cid]);
269                 if ($row_exists) {
270                         // Row already existing, nothing to do
271                         $return = true;
272                 } else {
273                         $return = DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cid]);
274                 }
275
276                 return $return;
277         }
278
279         /**
280          * Removes a contact from a group
281          *
282          * @param int $gid
283          * @param int $cid
284          * @return boolean
285          * @throws \Exception
286          */
287         public static function removeMember($gid, $cid)
288         {
289                 if (!$gid || !$cid) {
290                         return false;
291                 }
292
293                 $return = DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $cid]);
294
295                 return $return;
296         }
297
298         /**
299          * Returns the combined list of contact ids from a group id list
300          *
301          * @param int     $uid
302          * @param array   $group_ids
303          * @param boolean $check_dead
304          * @return array
305          * @throws \Exception
306          */
307         public static function expand($uid, array $group_ids, $check_dead = false)
308         {
309                 if (!is_array($group_ids) || !count($group_ids)) {
310                         return [];
311                 }
312
313                 $return = [];
314                 $pubmail = false;
315                 $networks = Protocol::SUPPORT_PRIVATE;
316
317                 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $uid]);
318                 if (DBA::isResult($mailacct)) {
319                         $pubmail = $mailacct['pubmail'];
320                 }
321
322                 if (!$pubmail) {
323                         $networks = array_diff($networks, [Protocol::MAIL]);
324                 }
325
326                 $key = array_search(self::FOLLOWERS, $group_ids);
327                 if ($key !== false) {
328                         $followers = Contact::selectToArray(['id'], [
329                                 'uid' => $uid,
330                                 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
331                                 'network' => $networks,
332                                 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
333                                 'archive' => false,
334                                 'pending' => false,
335                                 'blocked' => false,
336                         ]);
337
338                         foreach ($followers as $follower) {
339                                 $return[] = $follower['id'];
340                         }
341
342                         unset($group_ids[$key]);
343                 }
344
345                 $key = array_search(self::MUTUALS, $group_ids);
346                 if ($key !== false) {
347                         $mutuals = Contact::selectToArray(['id'], [
348                                 'uid' => $uid,
349                                 'rel' => [Contact::FRIEND],
350                                 'network' => $networks,
351                                 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
352                                 'archive' => false,
353                                 'pending' => false,
354                                 'blocked' => false,
355                         ]);
356
357                         foreach ($mutuals as $mutual) {
358                                 $return[] = $mutual['id'];
359                         }
360
361                         unset($group_ids[$key]);
362                 }
363
364                 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
365                 while ($group_member = DBA::fetch($stmt)) {
366                         $return[] = $group_member['contact-id'];
367                 }
368                 DBA::close($stmt);
369
370                 if ($check_dead) {
371                         $return = Contact::pruneUnavailable($return);
372                 }
373
374                 return $return;
375         }
376
377         /**
378          * Returns a templated group selection list
379          *
380          * @param int    $uid
381          * @param int    $gid   An optional pre-selected group
382          * @param string $label An optional label of the list
383          * @return string
384          * @throws \Exception
385          */
386         public static function displayGroupSelection($uid, $gid = 0, $label = '')
387         {
388                 $display_groups = [
389                         [
390                                 'name' => '',
391                                 'id' => '0',
392                                 'selected' => ''
393                         ]
394                 ];
395
396                 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid], ['order' => ['name']]);
397                 while ($group = DBA::fetch($stmt)) {
398                         $display_groups[] = [
399                                 'name' => $group['name'],
400                                 'id' => $group['id'],
401                                 'selected' => $gid == $group['id'] ? 'true' : ''
402                         ];
403                 }
404                 DBA::close($stmt);
405
406                 Logger::info('Got groups', $display_groups);
407
408                 if ($label == '') {
409                         $label = DI::l10n()->t('Default privacy group for new contacts');
410                 }
411
412                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
413                         '$label' => $label,
414                         '$groups' => $display_groups
415                 ]);
416                 return $o;
417         }
418
419         /**
420          * Create group sidebar widget
421          *
422          * @param string $every
423          * @param string $each
424          * @param string $editmode
425          *    'standard' => include link 'Edit groups'
426          *    'extended' => include link 'Create new group'
427          *    'full' => include link 'Create new group' and provide for each group a link to edit this group
428          * @param string $group_id
429          * @param int    $cid
430          * @return string
431          * @throws \Exception
432          */
433         public static function sidebarWidget($every = 'contact', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
434         {
435                 if (!local_user()) {
436                         return '';
437                 }
438
439                 $display_groups = [
440                         [
441                                 'text' => DI::l10n()->t('Everybody'),
442                                 'id' => 0,
443                                 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
444                                 'href' => $every,
445                         ]
446                 ];
447
448                 $member_of = [];
449                 if ($cid) {
450                         $member_of = self::getIdsByContactId($cid);
451                 }
452
453                 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => local_user()], ['order' => ['name']]);
454                 while ($group = DBA::fetch($stmt)) {
455                         $selected = (($group_id == $group['id']) ? ' group-selected' : '');
456
457                         if ($editmode == 'full') {
458                                 $groupedit = [
459                                         'href' => 'group/' . $group['id'],
460                                         'title' => DI::l10n()->t('edit'),
461                                 ];
462                         } else {
463                                 $groupedit = null;
464                         }
465
466                         if ($each == 'group') {
467                                 $count = DBA::count('group_member', ['gid' => $group['id']]);
468                                 $group_name = sprintf('%s (%d)', $group['name'], $count);
469                         } else {
470                                 $group_name = $group['name'];
471                         }
472
473                         $display_groups[] = [
474                                 'id'   => $group['id'],
475                                 'cid'  => $cid,
476                                 'text' => $group_name,
477                                 'href' => $each . '/' . $group['id'],
478                                 'edit' => $groupedit,
479                                 'selected' => $selected,
480                                 'ismember' => in_array($group['id'], $member_of),
481                         ];
482                 }
483                 DBA::close($stmt);
484
485                 // Don't show the groups on the network page when there is only one
486                 if ((count($display_groups) <= 2) && ($each == 'network')) {
487                         return '';
488                 }
489
490                 $tpl = Renderer::getMarkupTemplate('group_side.tpl');
491                 $o = Renderer::replaceMacros($tpl, [
492                         '$add' => DI::l10n()->t('add'),
493                         '$title' => DI::l10n()->t('Groups'),
494                         '$groups' => $display_groups,
495                         'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
496                         'grouppage' => 'group/',
497                         '$edittext' => DI::l10n()->t('Edit group'),
498                         '$ungrouped' => $every === 'contact' ? DI::l10n()->t('Contacts not in any group') : '',
499                         '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
500                         '$createtext' => DI::l10n()->t('Create a new group'),
501                         '$creategroup' => DI::l10n()->t('Group Name: '),
502                         '$editgroupstext' => DI::l10n()->t('Edit groups'),
503                         '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
504                 ]);
505
506                 return $o;
507         }
508 }