]> git.mxchange.org Git - friendica.git/blob - src/Model/Group.php
User lower case
[friendica.git] / src / Model / Group.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\Database;
29 use Friendica\Database\DBA;
30 use Friendica\DI;
31 use Friendica\Network\HTTPException;
32 use Friendica\Protocol\ActivityPub;
33
34 /**
35  * functions for interacting with the group database table
36  */
37 class Group
38 {
39         const FOLLOWERS = '~';
40         const MUTUALS = '&';
41
42         public static function getByUserId($uid, $includesDeleted = false)
43         {
44                 $conditions = ['uid' => $uid, 'cid' => null];
45
46                 if (!$includesDeleted) {
47                         $conditions['deleted'] = false;
48                 }
49
50                 return DBA::selectToArray('group', [], $conditions);
51         }
52
53         /**
54          * @param int $group_id
55          * @return bool
56          * @throws \Exception
57          */
58         public static function exists($group_id, $uid = null)
59         {
60                 $condition = ['id' => $group_id, 'deleted' => false];
61
62                 if (isset($uid)) {
63                         $condition = [
64                                 'uid' => $uid
65                         ];
66                 }
67
68                 return DBA::exists('group', $condition);
69         }
70
71         /**
72          * Create a new contact group
73          *
74          * Note: If we found a deleted group with the same name, we restore it
75          *
76          * @param int    $uid
77          * @param string $name
78          * @return boolean
79          * @throws \Exception
80          */
81         public static function create($uid, $name)
82         {
83                 $return = false;
84                 if (!empty($uid) && !empty($name)) {
85                         $gid = self::getIdByName($uid, $name); // check for dupes
86                         if ($gid !== false) {
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.'));
96                                 }
97                                 return true;
98                         }
99
100                         $return = DBA::insert('group', ['uid' => $uid, 'name' => $name]);
101                         if ($return) {
102                                 $return = DBA::lastInsertId();
103                         }
104                 }
105                 return $return;
106         }
107
108         /**
109          * Update group information.
110          *
111          * @param int    $id   Group ID
112          * @param string $name Group name
113          *
114          * @return bool Was the update successful?
115          * @throws \Exception
116          */
117         public static function update($id, $name)
118         {
119                 return DBA::update('group', ['name' => $name], ['id' => $id]);
120         }
121
122         /**
123          * Get a list of group ids a contact belongs to
124          *
125          * @param int $cid
126          * @return array
127          * @throws \Exception
128          */
129         public static function getIdsByContactId($cid)
130         {
131                 $return = [];
132
133                 $stmt = DBA::select('group_member', ['gid'], ['contact-id' => $cid]);
134                 while ($group = DBA::fetch($stmt)) {
135                         $return[] = $group['gid'];
136                 }
137                 DBA::close($stmt);
138
139                 // Meta-groups
140                 $contact = Contact::getById($cid, ['rel']);
141                 if ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND) {
142                         $return[] = self::FOLLOWERS;
143                 }
144
145                 if ($contact['rel'] == Contact::FRIEND) {
146                         $return[] = self::MUTUALS;
147                 }
148
149                 return $return;
150         }
151
152         /**
153          * count unread group items
154          *
155          * Count unread items of each groups of the local user
156          *
157          * @return array
158          *    'id' => group id
159          *    'name' => group name
160          *    'count' => counted unseen group items
161          * @throws \Exception
162          */
163         public static function countUnseen()
164         {
165                 $stmt = DBA::p("SELECT `group`.`id`, `group`.`name`,
166                                 (SELECT COUNT(*) FROM `post-user`
167                                         WHERE `uid` = ?
168                                         AND `unseen`
169                                         AND `contact-id` IN
170                                                 (SELECT `contact-id`
171                                                 FROM `group_member`
172                                                 WHERE `group_member`.`gid` = `group`.`id`)
173                                         ) AS `count`
174                                 FROM `group`
175                                 WHERE `group`.`uid` = ?;",
176                         local_user(),
177                         local_user()
178                 );
179
180                 return DBA::toArray($stmt);
181         }
182
183         /**
184          * Get the group id for a user/name couple
185          *
186          * Returns false if no group has been found.
187          *
188          * @param int    $uid
189          * @param string $name
190          * @return int|boolean
191          * @throws \Exception
192          */
193         public static function getIdByName($uid, $name)
194         {
195                 if (!$uid || !strlen($name)) {
196                         return false;
197                 }
198
199                 $group = DBA::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]);
200                 if (DBA::isResult($group)) {
201                         return $group['id'];
202                 }
203
204                 return false;
205         }
206
207         /**
208          * Mark a group as deleted
209          *
210          * @param int $gid
211          * @return boolean
212          * @throws \Exception
213          */
214         public static function remove($gid)
215         {
216                 if (!$gid) {
217                         return false;
218                 }
219
220                 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
221                 if (!DBA::isResult($group)) {
222                         return false;
223                 }
224
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)) {
228                         $change = false;
229
230                         if ($user['def_gid'] == $gid) {
231                                 $user['def_gid'] = 0;
232                                 $change = true;
233                         }
234                         if (strpos($user['allow_gid'], '<' . $gid . '>') !== false) {
235                                 $user['allow_gid'] = str_replace('<' . $gid . '>', '', $user['allow_gid']);
236                                 $change = true;
237                         }
238                         if (strpos($user['deny_gid'], '<' . $gid . '>') !== false) {
239                                 $user['deny_gid'] = str_replace('<' . $gid . '>', '', $user['deny_gid']);
240                                 $change = true;
241                         }
242
243                         if ($change) {
244                                 DBA::update('user', $user, ['uid' => $group['uid']]);
245                         }
246                 }
247
248                 // remove all members
249                 DBA::delete('group_member', ['gid' => $gid]);
250
251                 // remove group
252                 $return = DBA::update('group', ['deleted' => 1], ['id' => $gid]);
253
254                 return $return;
255         }
256
257         /**
258          * Adds a contact to a group
259          *
260          * @param int $gid
261          * @param int $cid
262          * @return boolean
263          * @throws \Exception
264          */
265         public static function addMember(int $gid, int $cid): bool
266         {
267                 if (!$gid || !$cid) {
268                         return false;
269                 }
270
271                 // @TODO Backward compatibility with user contacts, remove by version 2022.03
272                 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
273                 if (empty($group)) {
274                         throw new HTTPException\NotFoundException('Group not found.');
275                 }
276
277                 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
278                 if (empty($cdata['user'])) {
279                         throw new HTTPException\NotFoundException('Invalid contact.');
280                 }
281
282                 return DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cdata['user']], Database::INSERT_IGNORE);
283         }
284
285         /**
286          * Removes a contact from a group
287          *
288          * @param int $gid
289          * @param int $cid
290          * @return boolean
291          * @throws \Exception
292          */
293         public static function removeMember(int $gid, int $cid): bool
294         {
295                 if (!$gid || !$cid) {
296                         return false;
297                 }
298
299                 // @TODO Backward compatibility with user contacts, remove by version 2022.03
300                 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
301                 if (empty($group)) {
302                         throw new HTTPException\NotFoundException('Group not found.');
303                 }
304
305                 $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
306                 if (empty($cdata['user'])) {
307                         throw new HTTPException\NotFoundException('Invalid contact.');
308                 }
309
310                 return DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $cid]);
311         }
312
313         /**
314          * Returns the combined list of contact ids from a group id list
315          *
316          * @param int     $uid
317          * @param array   $group_ids
318          * @param boolean $check_dead
319          * @return array
320          * @throws \Exception
321          */
322         public static function expand($uid, array $group_ids, $check_dead = false)
323         {
324                 if (!is_array($group_ids) || !count($group_ids)) {
325                         return [];
326                 }
327
328                 $return = [];
329                 $pubmail = false;
330                 $networks = Protocol::SUPPORT_PRIVATE;
331
332                 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $uid]);
333                 if (DBA::isResult($mailacct)) {
334                         $pubmail = $mailacct['pubmail'];
335                 }
336
337                 if (!$pubmail) {
338                         $networks = array_diff($networks, [Protocol::MAIL]);
339                 }
340
341                 $key = array_search(self::FOLLOWERS, $group_ids);
342                 if ($key !== false) {
343                         $followers = Contact::selectToArray(['id'], [
344                                 'uid' => $uid,
345                                 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
346                                 'network' => $networks,
347                                 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
348                                 'archive' => false,
349                                 'pending' => false,
350                                 'blocked' => false,
351                         ]);
352
353                         foreach ($followers as $follower) {
354                                 $return[] = $follower['id'];
355                         }
356
357                         unset($group_ids[$key]);
358                 }
359
360                 $key = array_search(self::MUTUALS, $group_ids);
361                 if ($key !== false) {
362                         $mutuals = Contact::selectToArray(['id'], [
363                                 'uid' => $uid,
364                                 'rel' => [Contact::FRIEND],
365                                 'network' => $networks,
366                                 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
367                                 'archive' => false,
368                                 'pending' => false,
369                                 'blocked' => false,
370                         ]);
371
372                         foreach ($mutuals as $mutual) {
373                                 $return[] = $mutual['id'];
374                         }
375
376                         unset($group_ids[$key]);
377                 }
378
379                 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
380                 while ($group_member = DBA::fetch($stmt)) {
381                         $return[] = $group_member['contact-id'];
382                 }
383                 DBA::close($stmt);
384
385                 if ($check_dead) {
386                         $return = Contact::pruneUnavailable($return);
387                 }
388
389                 return $return;
390         }
391
392         /**
393          * Returns a templated group selection list
394          *
395          * @param int    $uid
396          * @param int    $gid   An optional pre-selected group
397          * @param string $label An optional label of the list
398          * @return string
399          * @throws \Exception
400          */
401         public static function displayGroupSelection($uid, $gid = 0, $label = '')
402         {
403                 $display_groups = [
404                         [
405                                 'name' => '',
406                                 'id' => '0',
407                                 'selected' => ''
408                         ]
409                 ];
410
411                 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => $uid, 'cid' => null], ['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' : ''
417                         ];
418                 }
419                 DBA::close($stmt);
420
421                 Logger::info('Got groups', $display_groups);
422
423                 if ($label == '') {
424                         $label = DI::l10n()->t('Default privacy group for new contacts');
425                 }
426
427                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
428                         '$label' => $label,
429                         '$groups' => $display_groups
430                 ]);
431                 return $o;
432         }
433
434         /**
435          * Create group sidebar widget
436          *
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
444          * @param int    $cid
445          * @return string
446          * @throws \Exception
447          */
448         public static function sidebarWidget($every = 'contact', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
449         {
450                 if (!local_user()) {
451                         return '';
452                 }
453
454                 $display_groups = [
455                         [
456                                 'text' => DI::l10n()->t('Everybody'),
457                                 'id' => 0,
458                                 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
459                                 'href' => $every,
460                         ]
461                 ];
462
463                 $member_of = [];
464                 if ($cid) {
465                         $member_of = self::getIdsByContactId($cid);
466                 }
467
468                 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => local_user(), 'cid' => null], ['order' => ['name']]);
469                 while ($group = DBA::fetch($stmt)) {
470                         $selected = (($group_id == $group['id']) ? ' group-selected' : '');
471
472                         if ($editmode == 'full') {
473                                 $groupedit = [
474                                         'href' => 'group/' . $group['id'],
475                                         'title' => DI::l10n()->t('edit'),
476                                 ];
477                         } else {
478                                 $groupedit = null;
479                         }
480
481                         if ($each == 'group') {
482                                 $count = DBA::count('group_member', ['gid' => $group['id']]);
483                                 $group_name = sprintf('%s (%d)', $group['name'], $count);
484                         } else {
485                                 $group_name = $group['name'];
486                         }
487
488                         $display_groups[] = [
489                                 'id'   => $group['id'],
490                                 'cid'  => $cid,
491                                 'text' => $group_name,
492                                 'href' => $each . '/' . $group['id'],
493                                 'edit' => $groupedit,
494                                 'selected' => $selected,
495                                 'ismember' => in_array($group['id'], $member_of),
496                         ];
497                 }
498                 DBA::close($stmt);
499
500                 // Don't show the groups on the network page when there is only one
501                 if ((count($display_groups) <= 2) && ($each == 'network')) {
502                         return '';
503                 }
504
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'),
519                 ]);
520
521                 return $o;
522         }
523
524         /**
525          * Fetch the group id for the given contact id
526          *
527          * @param integer $id Contact ID
528          * @return integer Group IO
529          */
530         public static function getIdForForum(int $id)
531         {
532                 Logger::info('Get id for forum id', ['id' => $id]);
533                 $contact = Contact::getById($id, ['uid', 'name', 'contact-type', 'manually-approve']);
534                 if (empty($contact) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY) || !$contact['manually-approve']) {
535                         return 0;
536                 }
537
538                 $group = DBA::selectFirst('group', ['id'], ['uid' => $contact['uid'], 'cid' => $id]);
539                 if (empty($group)) {
540                         $fields = [
541                                 'uid'  => $contact['uid'],
542                                 'name' => $contact['name'],
543                                 'cid'  => $id,
544                         ];
545                         DBA::insert('group', $fields);
546                         $gid = DBA::lastInsertId();
547                 } else {
548                         $gid = $group['id'];
549                 }
550
551                 return $gid;
552         }
553
554         /**
555          * Fetch the followers of a given contact id and store them as group members
556          *
557          * @param integer $id Contact ID
558          */
559         public static function updateMembersForForum(int $id)
560         {
561                 Logger::info('Update forum members', ['id' => $id]);
562
563                 $contact = Contact::getById($id, ['uid', 'url']);
564                 if (empty($contact)) {
565                         return;
566                 }
567
568                 $apcontact = APContact::getByURL($contact['url']);
569                 if (empty($apcontact['followers'])) {
570                         return;
571                 }
572
573                 $gid = self::getIdForForum($id);
574                 if (empty($gid)) {
575                         return;
576                 }
577
578                 $group_members = DBA::selectToArray('group_member', ['contact-id'], ['gid' => $gid]);
579                 if (!empty($group_members)) {
580                         $current = array_unique(array_column($group_members, 'contact-id'));
581                 } else {
582                         $current = [];
583                 }
584
585                 foreach (ActivityPub::fetchItems($apcontact['followers'], $contact['uid']) as $follower) {
586                         $id = Contact::getIdForURL($follower);
587                         if (!in_array($id, $current)) {
588                                 DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $id]);
589                         } else {
590                                 $key = array_search($id, $current);
591                                 unset($current[$key]);
592                         }
593                 }
594
595                 DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $current]);
596                 Logger::info('Updated forum members', ['id' => $id, 'count' => DBA::count('group_member', ['gid' => $gid])]);
597         }
598 }