]> git.mxchange.org Git - friendica.git/blob - src/Model/Group.php
Use central function to fetch the global directory
[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          * Adds contacts to a group
315          *
316          * @param int $gid
317          * @param array $contacts
318          * @throws \Exception
319          */
320         public static function addMembers(int $gid, array $contacts)
321         {
322                 if (!$gid || !$contacts) {
323                         return false;
324                 }
325
326                 // @TODO Backward compatibility with user contacts, remove by version 2022.03
327                 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
328                 if (empty($group)) {
329                         throw new HTTPException\NotFoundException('Group not found.');
330                 }
331
332                 foreach ($contacts as $cid) {
333                         $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
334                         if (empty($cdata['user'])) {
335                                 throw new HTTPException\NotFoundException('Invalid contact.');
336                         }
337
338                         DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cdata['user']], Database::INSERT_IGNORE);
339                 }
340         }
341
342         /**
343          * Removes contacts from a group
344          *
345          * @param int $gid
346          * @param array $contacts
347          * @throws \Exception
348          */
349         public static function removeMembers(int $gid, array $contacts)
350         {
351                 if (!$gid || !$contacts) {
352                         return false;
353                 }
354
355                 // @TODO Backward compatibility with user contacts, remove by version 2022.03
356                 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
357                 if (empty($group)) {
358                         throw new HTTPException\NotFoundException('Group not found.');
359                 }
360
361                 $contactIds = [];
362
363                 foreach ($contacts as $cid) {
364                         $cdata = Contact::getPublicAndUserContactID($cid, $group['uid']);
365                         if (empty($cdata['user'])) {
366                                 throw new HTTPException\NotFoundException('Invalid contact.');
367                         }
368
369                         $contactIds[] = $cdata['user'];
370                 }
371
372                 DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $contactIds]);
373         }
374
375         /**
376          * Returns the combined list of contact ids from a group id list
377          *
378          * @param int     $uid
379          * @param array   $group_ids
380          * @param boolean $check_dead
381          * @return array
382          * @throws \Exception
383          */
384         public static function expand($uid, array $group_ids, $check_dead = false)
385         {
386                 if (!is_array($group_ids) || !count($group_ids)) {
387                         return [];
388                 }
389
390                 $return = [];
391                 $pubmail = false;
392                 $networks = Protocol::SUPPORT_PRIVATE;
393
394                 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $uid]);
395                 if (DBA::isResult($mailacct)) {
396                         $pubmail = $mailacct['pubmail'];
397                 }
398
399                 if (!$pubmail) {
400                         $networks = array_diff($networks, [Protocol::MAIL]);
401                 }
402
403                 $key = array_search(self::FOLLOWERS, $group_ids);
404                 if ($key !== false) {
405                         $followers = Contact::selectToArray(['id'], [
406                                 'uid' => $uid,
407                                 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
408                                 'network' => $networks,
409                                 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
410                                 'archive' => false,
411                                 'pending' => false,
412                                 'blocked' => false,
413                         ]);
414
415                         foreach ($followers as $follower) {
416                                 $return[] = $follower['id'];
417                         }
418
419                         unset($group_ids[$key]);
420                 }
421
422                 $key = array_search(self::MUTUALS, $group_ids);
423                 if ($key !== false) {
424                         $mutuals = Contact::selectToArray(['id'], [
425                                 'uid' => $uid,
426                                 'rel' => [Contact::FRIEND],
427                                 'network' => $networks,
428                                 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON],
429                                 'archive' => false,
430                                 'pending' => false,
431                                 'blocked' => false,
432                         ]);
433
434                         foreach ($mutuals as $mutual) {
435                                 $return[] = $mutual['id'];
436                         }
437
438                         unset($group_ids[$key]);
439                 }
440
441                 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
442                 while ($group_member = DBA::fetch($stmt)) {
443                         $return[] = $group_member['contact-id'];
444                 }
445                 DBA::close($stmt);
446
447                 if ($check_dead) {
448                         $return = Contact::pruneUnavailable($return);
449                 }
450
451                 return $return;
452         }
453
454         /**
455          * Returns a templated group selection list
456          *
457          * @param int    $uid
458          * @param int    $gid   An optional pre-selected group
459          * @param string $label An optional label of the list
460          * @return string
461          * @throws \Exception
462          */
463         public static function displayGroupSelection($uid, $gid = 0, $label = '')
464         {
465                 $display_groups = [
466                         [
467                                 'name' => '',
468                                 'id' => '0',
469                                 'selected' => ''
470                         ]
471                 ];
472
473                 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => $uid, 'cid' => null], ['order' => ['name']]);
474                 while ($group = DBA::fetch($stmt)) {
475                         $display_groups[] = [
476                                 'name' => $group['name'],
477                                 'id' => $group['id'],
478                                 'selected' => $gid == $group['id'] ? 'true' : ''
479                         ];
480                 }
481                 DBA::close($stmt);
482
483                 Logger::info('Got groups', $display_groups);
484
485                 if ($label == '') {
486                         $label = DI::l10n()->t('Default privacy group for new contacts');
487                 }
488
489                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
490                         '$label' => $label,
491                         '$groups' => $display_groups
492                 ]);
493                 return $o;
494         }
495
496         /**
497          * Create group sidebar widget
498          *
499          * @param string $every
500          * @param string $each
501          * @param string $editmode
502          *    'standard' => include link 'Edit groups'
503          *    'extended' => include link 'Create new group'
504          *    'full' => include link 'Create new group' and provide for each group a link to edit this group
505          * @param string $group_id
506          * @param int    $cid
507          * @return string
508          * @throws \Exception
509          */
510         public static function sidebarWidget($every = 'contact', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
511         {
512                 if (!local_user()) {
513                         return '';
514                 }
515
516                 $display_groups = [
517                         [
518                                 'text' => DI::l10n()->t('Everybody'),
519                                 'id' => 0,
520                                 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
521                                 'href' => $every,
522                         ]
523                 ];
524
525                 $member_of = [];
526                 if ($cid) {
527                         $member_of = self::getIdsByContactId($cid);
528                 }
529
530                 $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => local_user(), 'cid' => null], ['order' => ['name']]);
531                 while ($group = DBA::fetch($stmt)) {
532                         $selected = (($group_id == $group['id']) ? ' group-selected' : '');
533
534                         if ($editmode == 'full') {
535                                 $groupedit = [
536                                         'href' => 'group/' . $group['id'],
537                                         'title' => DI::l10n()->t('edit'),
538                                 ];
539                         } else {
540                                 $groupedit = null;
541                         }
542
543                         if ($each == 'group') {
544                                 $count = DBA::count('group_member', ['gid' => $group['id']]);
545                                 $group_name = sprintf('%s (%d)', $group['name'], $count);
546                         } else {
547                                 $group_name = $group['name'];
548                         }
549
550                         $display_groups[] = [
551                                 'id'   => $group['id'],
552                                 'cid'  => $cid,
553                                 'text' => $group_name,
554                                 'href' => $each . '/' . $group['id'],
555                                 'edit' => $groupedit,
556                                 'selected' => $selected,
557                                 'ismember' => in_array($group['id'], $member_of),
558                         ];
559                 }
560                 DBA::close($stmt);
561
562                 // Don't show the groups on the network page when there is only one
563                 if ((count($display_groups) <= 2) && ($each == 'network')) {
564                         return '';
565                 }
566
567                 $tpl = Renderer::getMarkupTemplate('group_side.tpl');
568                 $o = Renderer::replaceMacros($tpl, [
569                         '$add' => DI::l10n()->t('add'),
570                         '$title' => DI::l10n()->t('Groups'),
571                         '$groups' => $display_groups,
572                         'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
573                         'grouppage' => 'group/',
574                         '$edittext' => DI::l10n()->t('Edit group'),
575                         '$ungrouped' => $every === 'contact' ? DI::l10n()->t('Contacts not in any group') : '',
576                         '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
577                         '$createtext' => DI::l10n()->t('Create a new group'),
578                         '$creategroup' => DI::l10n()->t('Group Name: '),
579                         '$editgroupstext' => DI::l10n()->t('Edit groups'),
580                         '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
581                 ]);
582
583                 return $o;
584         }
585
586         /**
587          * Fetch the group id for the given contact id
588          *
589          * @param integer $id Contact ID
590          * @return integer Group IO
591          */
592         public static function getIdForForum(int $id)
593         {
594                 Logger::info('Get id for forum id', ['id' => $id]);
595                 $contact = Contact::getById($id, ['uid', 'name', 'contact-type', 'manually-approve']);
596                 if (empty($contact) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY) || !$contact['manually-approve']) {
597                         return 0;
598                 }
599
600                 $group = DBA::selectFirst('group', ['id'], ['uid' => $contact['uid'], 'cid' => $id]);
601                 if (empty($group)) {
602                         $fields = [
603                                 'uid'  => $contact['uid'],
604                                 'name' => $contact['name'],
605                                 'cid'  => $id,
606                         ];
607                         DBA::insert('group', $fields);
608                         $gid = DBA::lastInsertId();
609                 } else {
610                         $gid = $group['id'];
611                 }
612
613                 return $gid;
614         }
615
616         /**
617          * Fetch the followers of a given contact id and store them as group members
618          *
619          * @param integer $id Contact ID
620          */
621         public static function updateMembersForForum(int $id)
622         {
623                 Logger::info('Update forum members', ['id' => $id]);
624
625                 $contact = Contact::getById($id, ['uid', 'url']);
626                 if (empty($contact)) {
627                         return;
628                 }
629
630                 $apcontact = APContact::getByURL($contact['url']);
631                 if (empty($apcontact['followers'])) {
632                         return;
633                 }
634
635                 $gid = self::getIdForForum($id);
636                 if (empty($gid)) {
637                         return;
638                 }
639
640                 $group_members = DBA::selectToArray('group_member', ['contact-id'], ['gid' => $gid]);
641                 if (!empty($group_members)) {
642                         $current = array_unique(array_column($group_members, 'contact-id'));
643                 } else {
644                         $current = [];
645                 }
646
647                 foreach (ActivityPub::fetchItems($apcontact['followers'], $contact['uid']) as $follower) {
648                         $id = Contact::getIdForURL($follower);
649                         if (!in_array($id, $current)) {
650                                 DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $id]);
651                         } else {
652                                 $key = array_search($id, $current);
653                                 unset($current[$key]);
654                         }
655                 }
656
657                 DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $current]);
658                 Logger::info('Updated forum members', ['id' => $id, 'count' => DBA::count('group_member', ['gid' => $gid])]);
659         }
660 }