]> git.mxchange.org Git - friendica.git/blob - src/Module/Group.php
930e885c587d7a384610189137691ab011aa1590
[friendica.git] / src / Module / 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\Module;
23
24 use Friendica\BaseModule;
25 use Friendica\Core\Renderer;
26 use Friendica\Core\Session;
27 use Friendica\Core\System;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Model;
31
32 class Group extends BaseModule
33 {
34         protected function post(array $request = [])
35         {
36                 if (DI::mode()->isAjax()) {
37                         $this->ajaxPost();
38                 }
39
40                 if (!Session::getLocalUser()) {
41                         DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
42                         DI::baseUrl()->redirect();
43                 }
44
45                 // @TODO: Replace with parameter from router
46                 if ((DI::args()->getArgc() == 2) && (DI::args()->getArgv()[1] === 'new')) {
47                         BaseModule::checkFormSecurityTokenRedirectOnError('/group/new', 'group_edit');
48
49                         $name = trim($request['groupname']);
50                         $r = Model\Group::create(Session::getLocalUser(), $name);
51                         if ($r) {
52                                 $r = Model\Group::getIdByName(Session::getLocalUser(), $name);
53                                 if ($r) {
54                                         DI::baseUrl()->redirect('group/' . $r);
55                                 }
56                         } else {
57                                 DI::sysmsg()->addNotice(DI::l10n()->t('Could not create group.'));
58                         }
59                         DI::baseUrl()->redirect('group');
60                 }
61
62                 // @TODO: Replace with parameter from router
63                 if ((DI::args()->getArgc() == 2) && intval(DI::args()->getArgv()[1])) {
64                         BaseModule::checkFormSecurityTokenRedirectOnError('/group', 'group_edit');
65
66                         $group = DBA::selectFirst('group', ['id', 'name'], ['id' => DI::args()->getArgv()[1], 'uid' => Session::getLocalUser()]);
67                         if (!DBA::isResult($group)) {
68                                 DI::sysmsg()->addNotice(DI::l10n()->t('Group not found.'));
69                                 DI::baseUrl()->redirect('contact');
70                         }
71                         $groupname = trim($_POST['groupname']);
72                         if (strlen($groupname) && ($groupname != $group['name'])) {
73                                 if (!Model\Group::update($group['id'], $groupname)) {
74                                         DI::sysmsg()->addNotice(DI::l10n()->t('Group name was not changed.'));
75                                 }
76                         }
77                 }
78         }
79
80         public function ajaxPost()
81         {
82                 try {
83                         if (!Session::getLocalUser()) {
84                                 throw new \Exception(DI::l10n()->t('Permission denied.'), 403);
85                         }
86
87                         if (isset($this->parameters['command'])) {
88                                 $group_id = $this->parameters['group'];
89                                 $contact_id = $this->parameters['contact'];
90
91                                 if (!Model\Group::exists($group_id, Session::getLocalUser())) {
92                                         throw new \Exception(DI::l10n()->t('Unknown group.'), 404);
93                                 }
94
95                                 // @TODO Backward compatibility with user contacts, remove by version 2022.03
96                                 $cdata = Model\Contact::getPublicAndUserContactID($contact_id, Session::getLocalUser());
97                                 if (empty($cdata['public'])) {
98                                         throw new \Exception(DI::l10n()->t('Contact not found.'), 404);
99                                 }
100
101                                 if (empty($cdata['user'])) {
102                                         throw new \Exception(DI::l10n()->t('Invalid contact.'), 404);
103                                 }
104
105                                 $contact = Model\Contact::getById($cdata['user'], ['deleted']);
106                                 if (!DBA::isResult($contact)) {
107                                         throw new \Exception(DI::l10n()->t('Contact not found.'), 404);
108                                 }
109
110                                 if ($contact['deleted']) {
111                                         throw new \Exception(DI::l10n()->t('Contact is deleted.'), 410);
112                                 }
113
114                                 switch($this->parameters['command']) {
115                                         case 'add':
116                                                 if (!Model\Group::addMember($group_id, $cdata['user'])) {
117                                                         throw new \Exception(DI::l10n()->t('Unable to add the contact to the group.'), 500);
118                                                 }
119
120                                                 $message = DI::l10n()->t('Contact successfully added to group.');
121                                                 break;
122                                         case 'remove':
123                                                 if (!Model\Group::removeMember($group_id, $cdata['user'])) {
124                                                         throw new \Exception(DI::l10n()->t('Unable to remove the contact from the group.'), 500);
125                                                 }
126
127                                                 $message = DI::l10n()->t('Contact successfully removed from group.');
128                                                 break;
129                                 }
130                         } else {
131                                 throw new \Exception(DI::l10n()->t('Bad request.'), 400);
132                         }
133
134                         DI::sysmsg()->addInfo($message);
135                         System::jsonExit(['status' => 'OK', 'message' => $message]);
136                 } catch (\Exception $e) {
137                         DI::sysmsg()->addNotice($e->getMessage());
138                         System::jsonError($e->getCode(), ['status' => 'error', 'message' => $e->getMessage()]);
139                 }
140         }
141
142         protected function content(array $request = []): string
143         {
144                 $change = false;
145
146                 if (!Session::getLocalUser()) {
147                         throw new \Friendica\Network\HTTPException\ForbiddenException();
148                 }
149
150                 $a = DI::app();
151
152                 DI::page()['aside'] = Model\Group::sidebarWidget('contact', 'group', 'extended', ((DI::args()->getArgc() > 1) ? DI::args()->getArgv()[1] : 'everyone'));
153
154                 // With no group number provided we jump to the unassigned contacts as a starting point
155                 // @TODO: Replace with parameter from router
156                 if (DI::args()->getArgc() == 1) {
157                         DI::baseUrl()->redirect('group/none');
158                 }
159
160                 // Switch to text mode interface if we have more than 'n' contacts or group members
161                 $switchtotext = DI::pConfig()->get(Session::getLocalUser(), 'system', 'groupedit_image_limit');
162                 if (is_null($switchtotext)) {
163                         $switchtotext = DI::config()->get('system', 'groupedit_image_limit', 200);
164                 }
165
166                 $tpl = Renderer::getMarkupTemplate('group_edit.tpl');
167
168
169                 $context = [
170                         '$submit' => DI::l10n()->t('Save Group'),
171                         '$submit_filter' => DI::l10n()->t('Filter'),
172                 ];
173
174                 // @TODO: Replace with parameter from router
175                 if ((DI::args()->getArgc() == 2) && (DI::args()->getArgv()[1] === 'new')) {
176                         return Renderer::replaceMacros($tpl, $context + [
177                                 '$title' => DI::l10n()->t('Create a group of contacts/friends.'),
178                                 '$gname' => ['groupname', DI::l10n()->t('Group Name: '), '', ''],
179                                 '$gid' => 'new',
180                                 '$form_security_token' => BaseModule::getFormSecurityToken("group_edit"),
181                         ]);
182                 }
183
184                 $nogroup = false;
185
186                 // @TODO: Replace with parameter from router
187                 if ((DI::args()->getArgc() == 2) && (DI::args()->getArgv()[1] === 'none') ||
188                         (DI::args()->getArgc() == 1) && (DI::args()->getArgv()[0] === 'nogroup')) {
189                         $id = -1;
190                         $nogroup = true;
191                         $group = [
192                                 'id' => $id,
193                                 'name' => DI::l10n()->t('Contacts not in any group'),
194                         ];
195
196                         $members = [];
197                         $preselected = [];
198
199                         $context = $context + [
200                                 '$title' => $group['name'],
201                                 '$gname' => ['groupname', DI::l10n()->t('Group Name: '), $group['name'], ''],
202                                 '$gid' => $id,
203                                 '$editable' => 0,
204                         ];
205                 }
206
207                 // @TODO: Replace with parameter from router
208                 if ((DI::args()->getArgc() == 3) && (DI::args()->getArgv()[1] === 'drop')) {
209                         BaseModule::checkFormSecurityTokenRedirectOnError('/group', 'group_drop', 't');
210
211                         // @TODO: Replace with parameter from router
212                         if (intval(DI::args()->getArgv()[2])) {
213                                 if (!Model\Group::exists(DI::args()->getArgv()[2], Session::getLocalUser())) {
214                                         DI::sysmsg()->addNotice(DI::l10n()->t('Group not found.'));
215                                         DI::baseUrl()->redirect('contact');
216                                 }
217
218                                 if (!Model\Group::remove(DI::args()->getArgv()[2])) {
219                                         DI::sysmsg()->addNotice(DI::l10n()->t('Unable to remove group.'));
220                                 }
221                         }
222                         DI::baseUrl()->redirect('group');
223                 }
224
225                 // @TODO: Replace with parameter from router
226                 if ((DI::args()->getArgc() > 2) && intval(DI::args()->getArgv()[1]) && intval(DI::args()->getArgv()[2])) {
227                         BaseModule::checkFormSecurityTokenForbiddenOnError('group_member_change', 't');
228
229                         if (DBA::exists('contact', ['id' => DI::args()->getArgv()[2], 'uid' => Session::getLocalUser(), 'self' => false, 'pending' => false, 'blocked' => false])) {
230                                 $change = intval(DI::args()->getArgv()[2]);
231                         }
232                 }
233
234                 // @TODO: Replace with parameter from router
235                 if ((DI::args()->getArgc() > 1) && intval(DI::args()->getArgv()[1])) {
236                         $group = DBA::selectFirst('group', ['id', 'name'], ['id' => DI::args()->getArgv()[1], 'uid' => Session::getLocalUser(), 'deleted' => false]);
237                         if (!DBA::isResult($group)) {
238                                 DI::sysmsg()->addNotice(DI::l10n()->t('Group not found.'));
239                                 DI::baseUrl()->redirect('contact');
240                         }
241
242                         $members = Model\Contact\Group::getById($group['id']);
243                         $preselected = [];
244
245                         if (count($members)) {
246                                 foreach ($members as $member) {
247                                         $preselected[] = $member['id'];
248                                 }
249                         }
250
251                         if ($change) {
252                                 if (in_array($change, $preselected)) {
253                                         Model\Group::removeMember($group['id'], $change);
254                                 } else {
255                                         Model\Group::addMember($group['id'], $change);
256                                 }
257
258                                 $members = Model\Contact\Group::getById($group['id']);
259                                 $preselected = [];
260                                 if (count($members)) {
261                                         foreach ($members as $member) {
262                                                 $preselected[] = $member['id'];
263                                         }
264                                 }
265                         }
266
267                         $drop_tpl = Renderer::getMarkupTemplate('group_drop.tpl');
268                         $drop_txt = Renderer::replaceMacros($drop_tpl, [
269                                 '$id' => $group['id'],
270                                 '$delete' => DI::l10n()->t('Delete Group'),
271                                 '$form_security_token' => BaseModule::getFormSecurityToken("group_drop"),
272                         ]);
273
274                         $context = $context + [
275                                 '$title' => $group['name'],
276                                 '$gname' => ['groupname', DI::l10n()->t('Group Name: '), $group['name'], ''],
277                                 '$gid' => $group['id'],
278                                 '$drop' => $drop_txt,
279                                 '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
280                                 '$edit_name' => DI::l10n()->t('Edit Group Name'),
281                                 '$editable' => 1,
282                         ];
283                 }
284
285                 if (!isset($group)) {
286                         throw new \Friendica\Network\HTTPException\BadRequestException();
287                 }
288
289                 $groupeditor = [
290                         'label_members' => DI::l10n()->t('Members'),
291                         'members' => [],
292                         'label_contacts' => DI::l10n()->t('All Contacts'),
293                         'group_is_empty' => DI::l10n()->t('Group is empty'),
294                         'contacts' => [],
295                 ];
296
297                 $sec_token = addslashes(BaseModule::getFormSecurityToken('group_member_change'));
298
299                 // Format the data of the group members
300                 foreach ($members as $member) {
301                         if ($member['url']) {
302                                 $entry = Contact::getContactTemplateVars($member);
303                                 $entry['label'] = 'members';
304                                 $entry['photo_menu'] = '';
305                                 $entry['change_member'] = [
306                                         'title'     => DI::l10n()->t("Remove contact from group"),
307                                         'gid'       => $group['id'],
308                                         'cid'       => $member['id'],
309                                         'sec_token' => $sec_token
310                                 ];
311
312                                 $groupeditor['members'][] = $entry;
313                         } else {
314                                 Model\Group::removeMember($group['id'], $member['id']);
315                         }
316                 }
317
318                 if ($nogroup) {
319                         $contacts = Model\Contact\Group::listUngrouped(Session::getLocalUser());
320                 } else {
321                         $contacts_stmt = DBA::select('contact', [],
322                                 ['rel' => [Model\Contact::FOLLOWER, Model\Contact::FRIEND, Model\Contact::SHARING],
323                                 'uid' => Session::getLocalUser(), 'pending' => false, 'blocked' => false, 'failed' => false, 'self' => false],
324                                 ['order' => ['name']]
325                         );
326                         $contacts = DBA::toArray($contacts_stmt);
327                         $context['$desc'] = DI::l10n()->t('Click on a contact to add or remove.');
328                 }
329
330                 if (DBA::isResult($contacts)) {
331                         // Format the data of the contacts who aren't in the contact group
332                         foreach ($contacts as $member) {
333                                 if (!in_array($member['id'], $preselected)) {
334                                         $entry = Contact::getContactTemplateVars($member);
335                                         $entry['label'] = 'contacts';
336                                         if (!$nogroup)
337                                                 $entry['photo_menu'] = [];
338
339                                         if (!$nogroup) {
340                                                 $entry['change_member'] = [
341                                                         'title'     => DI::l10n()->t("Add contact to group"),
342                                                         'gid'       => $group['id'],
343                                                         'cid'       => $member['id'],
344                                                         'sec_token' => $sec_token
345                                                 ];
346                                         }
347
348                                         $groupeditor['contacts'][] = $entry;
349                                 }
350                         }
351                 }
352
353                 $context['$groupeditor'] = $groupeditor;
354
355                 // If there are to many contacts we could provide an alternative view mode
356                 $total = count($groupeditor['members']) + count($groupeditor['contacts']);
357                 $context['$shortmode'] = (($switchtotext && ($total > $switchtotext)) ? true : false);
358
359                 if ($change) {
360                         $tpl = Renderer::getMarkupTemplate('groupeditor.tpl');
361                         echo Renderer::replaceMacros($tpl, $context);
362                         System::exit();
363                 }
364
365                 return Renderer::replaceMacros($tpl, $context);
366         }
367 }