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