]> git.mxchange.org Git - friendica.git/blob - src/Model/Group.php
Merge remote-tracking branch 'upstream/develop' into logging
[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          * Mark a group as deleted based on its name
256          *
257          * @param int    $uid
258          * @param string $name
259          * @return bool
260          * @throws \Exception
261          * @deprecated Use Group::remove instead
262          *
263          */
264         public static function removeByName($uid, $name)
265         {
266                 $return = false;
267                 if (!empty($uid) && !empty($name)) {
268                         $gid = self::getIdByName($uid, $name);
269
270                         $return = self::remove($gid);
271                 }
272
273                 return $return;
274         }
275
276         /**
277          * Adds a contact to a group
278          *
279          * @param int $gid
280          * @param int $cid
281          * @return boolean
282          * @throws \Exception
283          */
284         public static function addMember($gid, $cid)
285         {
286                 if (!$gid || !$cid) {
287                         return false;
288                 }
289
290                 $row_exists = DBA::exists('group_member', ['gid' => $gid, 'contact-id' => $cid]);
291                 if ($row_exists) {
292                         // Row already existing, nothing to do
293                         $return = true;
294                 } else {
295                         $return = DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cid]);
296                 }
297
298                 return $return;
299         }
300
301         /**
302          * Removes a contact from a group
303          *
304          * @param int $gid
305          * @param int $cid
306          * @return boolean
307          * @throws \Exception
308          */
309         public static function removeMember($gid, $cid)
310         {
311                 if (!$gid || !$cid) {
312                         return false;
313                 }
314
315                 $return = DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $cid]);
316
317                 return $return;
318         }
319
320         /**
321          * Removes a contact from a group based on its name
322          *
323          * @param int    $uid
324          * @param string $name
325          * @param int    $cid
326          * @return boolean
327          * @throws \Exception
328          * @deprecated Use Group::removeMember instead
329          *
330          */
331         public static function removeMemberByName($uid, $name, $cid)
332         {
333                 $gid = self::getIdByName($uid, $name);
334
335                 $return = self::removeMember($gid, $cid);
336
337                 return $return;
338         }
339
340         /**
341          * Returns the combined list of contact ids from a group id list
342          *
343          * @param int     $uid
344          * @param array   $group_ids
345          * @param boolean $check_dead
346          * @return array
347          * @throws \Exception
348          */
349         public static function expand($uid, array $group_ids, $check_dead = false)
350         {
351                 if (!is_array($group_ids) || !count($group_ids)) {
352                         return [];
353                 }
354
355                 $return = [];
356                 $pubmail = false;
357                 $networks = Protocol::SUPPORT_PRIVATE;
358
359                 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $uid]);
360                 if (DBA::isResult($mailacct)) {
361                         $pubmail = $mailacct['pubmail'];
362                 }
363
364                 if (!$pubmail) {
365                         $networks = array_diff($networks, [Protocol::MAIL]);
366                 }
367
368                 $key = array_search(self::FOLLOWERS, $group_ids);
369                 if ($key !== false) {
370                         $followers = Contact::selectToArray(['id'], [
371                                 'uid' => $uid,
372                                 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
373                                 'network' => $networks,
374                                 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
375                                 'archive' => false,
376                                 'pending' => false,
377                                 'blocked' => false,
378                         ]);
379
380                         foreach ($followers as $follower) {
381                                 $return[] = $follower['id'];
382                         }
383
384                         unset($group_ids[$key]);
385                 }
386
387                 $key = array_search(self::MUTUALS, $group_ids);
388                 if ($key !== false) {
389                         $mutuals = Contact::selectToArray(['id'], [
390                                 'uid' => $uid,
391                                 'rel' => [Contact::FRIEND],
392                                 'network' => $networks,
393                                 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
394                                 'archive' => false,
395                                 'pending' => false,
396                                 'blocked' => false,
397                         ]);
398
399                         foreach ($mutuals as $mutual) {
400                                 $return[] = $mutual['id'];
401                         }
402
403                         unset($group_ids[$key]);
404                 }
405
406                 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
407                 while ($group_member = DBA::fetch($stmt)) {
408                         $return[] = $group_member['contact-id'];
409                 }
410                 DBA::close($stmt);
411
412                 if ($check_dead) {
413                         $return = Contact::pruneUnavailable($return);
414                 }
415
416                 return $return;
417         }
418
419         /**
420          * Returns a templated group selection list
421          *
422          * @param int    $uid
423          * @param int    $gid   An optional pre-selected group
424          * @param string $label An optional label of the list
425          * @return string
426          * @throws \Exception
427          */
428         public static function displayGroupSelection($uid, $gid = 0, $label = '')
429         {
430                 $display_groups = [
431                         [
432                                 'name' => '',
433                                 'id' => '0',
434                                 'selected' => ''
435                         ]
436                 ];
437
438                 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid], ['order' => ['name']]);
439                 while ($group = DBA::fetch($stmt)) {
440                         $display_groups[] = [
441                                 'name' => $group['name'],
442                                 'id' => $group['id'],
443                                 'selected' => $gid == $group['id'] ? 'true' : ''
444                         ];
445                 }
446                 DBA::close($stmt);
447
448                 Logger::info('Got groups', $display_groups);
449
450                 if ($label == '') {
451                         $label = DI::l10n()->t('Default privacy group for new contacts');
452                 }
453
454                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
455                         '$label' => $label,
456                         '$groups' => $display_groups
457                 ]);
458                 return $o;
459         }
460
461         /**
462          * Create group sidebar widget
463          *
464          * @param string $every
465          * @param string $each
466          * @param string $editmode
467          *    'standard' => include link 'Edit groups'
468          *    'extended' => include link 'Create new group'
469          *    'full' => include link 'Create new group' and provide for each group a link to edit this group
470          * @param string $group_id
471          * @param int    $cid
472          * @return string
473          * @throws \Exception
474          */
475         public static function sidebarWidget($every = 'contact', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
476         {
477                 if (!local_user()) {
478                         return '';
479                 }
480
481                 $display_groups = [
482                         [
483                                 'text' => DI::l10n()->t('Everybody'),
484                                 'id' => 0,
485                                 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
486                                 'href' => $every,
487                         ]
488                 ];
489
490                 $member_of = [];
491                 if ($cid) {
492                         $member_of = self::getIdsByContactId($cid);
493                 }
494
495                 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => local_user()], ['order' => ['name']]);
496                 while ($group = DBA::fetch($stmt)) {
497                         $selected = (($group_id == $group['id']) ? ' group-selected' : '');
498
499                         if ($editmode == 'full') {
500                                 $groupedit = [
501                                         'href' => 'group/' . $group['id'],
502                                         'title' => DI::l10n()->t('edit'),
503                                 ];
504                         } else {
505                                 $groupedit = null;
506                         }
507
508                         if ($each == 'group') {
509                                 $count = DBA::count('group_member', ['gid' => $group['id']]);
510                                 $group_name = sprintf('%s (%d)', $group['name'], $count);
511                         } else {
512                                 $group_name = $group['name'];
513                         }
514
515                         $display_groups[] = [
516                                 'id'   => $group['id'],
517                                 'cid'  => $cid,
518                                 'text' => $group_name,
519                                 'href' => $each . '/' . $group['id'],
520                                 'edit' => $groupedit,
521                                 'selected' => $selected,
522                                 'ismember' => in_array($group['id'], $member_of),
523                         ];
524                 }
525                 DBA::close($stmt);
526
527                 // Don't show the groups on the network page when there is only one
528                 if ((count($display_groups) <= 2) && ($each == 'network')) {
529                         return '';
530                 }
531
532                 $tpl = Renderer::getMarkupTemplate('group_side.tpl');
533                 $o = Renderer::replaceMacros($tpl, [
534                         '$add' => DI::l10n()->t('add'),
535                         '$title' => DI::l10n()->t('Groups'),
536                         '$groups' => $display_groups,
537                         'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
538                         'grouppage' => 'group/',
539                         '$edittext' => DI::l10n()->t('Edit group'),
540                         '$ungrouped' => $every === 'contact' ? DI::l10n()->t('Contacts not in any group') : '',
541                         '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
542                         '$createtext' => DI::l10n()->t('Create a new group'),
543                         '$creategroup' => DI::l10n()->t('Group Name: '),
544                         '$editgroupstext' => DI::l10n()->t('Edit groups'),
545                         '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
546                 ]);
547
548                 return $o;
549         }
550 }