98a29411d3cc91d06410454781c42d2ff4b728f8
[friendica.git/.git] / src / Module / Circle.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2024, 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\Content\Widget;
26 use Friendica\Core\Renderer;
27 use Friendica\Core\System;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Model;
31
32 class Circle extends BaseModule
33 {
34         protected function post(array $request = [])
35         {
36                 if (DI::mode()->isAjax()) {
37                         $this->ajaxPost();
38                 }
39
40                 if (!DI::userSession()->getLocalUserId()) {
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('/circle/new', 'circle_edit');
48
49                         $name = trim($request['circle_name']);
50                         $r = Model\Circle::create(DI::userSession()->getLocalUserId(), $name);
51                         if ($r) {
52                                 $r = Model\Circle::getIdByName(DI::userSession()->getLocalUserId(), $name);
53                                 if ($r) {
54                                         DI::baseUrl()->redirect('circle/' . $r);
55                                 }
56                         } else {
57                                 DI::sysmsg()->addNotice(DI::l10n()->t('Could not create circle.'));
58                         }
59                         DI::baseUrl()->redirect('circle');
60                 }
61
62                 // @TODO: Replace with parameter from router
63                 if ((DI::args()->getArgc() == 2) && intval(DI::args()->getArgv()[1])) {
64                         BaseModule::checkFormSecurityTokenRedirectOnError('/circle', 'circle_edit');
65
66                         $circle = DBA::selectFirst('group', ['id', 'name'], ['id' => DI::args()->getArgv()[1], 'uid' => DI::userSession()->getLocalUserId()]);
67                         if (!DBA::isResult($circle)) {
68                                 DI::sysmsg()->addNotice(DI::l10n()->t('Circle not found.'));
69                                 DI::baseUrl()->redirect('contact');
70                         }
71                         $circlename = trim($_POST['circle_name']);
72                         if (strlen($circlename) && ($circlename != $circle['name'])) {
73                                 if (!Model\Circle::update($circle['id'], $circlename)) {
74                                         DI::sysmsg()->addNotice(DI::l10n()->t('Circle name was not changed.'));
75                                 }
76                         }
77                 }
78         }
79
80         public function ajaxPost()
81         {
82                 try {
83                         if (!DI::userSession()->getLocalUserId()) {
84                                 throw new \Exception(DI::l10n()->t('Permission denied.'), 403);
85                         }
86
87                         if (isset($this->parameters['command'])) {
88                                 $circle_id = $this->parameters['circle'];
89                                 $contact_id = $this->parameters['contact'];
90
91                                 if (!Model\Circle::exists($circle_id, DI::userSession()->getLocalUserId())) {
92                                         throw new \Exception(DI::l10n()->t('Unknown circle.'), 404);
93                                 }
94
95                                 // @TODO Backward compatibility with user contacts, remove by version 2022.03
96                                 $cdata = Model\Contact::getPublicAndUserContactID($contact_id, DI::userSession()->getLocalUserId());
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\Circle::addMember($circle_id, $cdata['user'])) {
117                                                         throw new \Exception(DI::l10n()->t('Unable to add the contact to the circle.'), 500);
118                                                 }
119
120                                                 $message = DI::l10n()->t('Contact successfully added to circle.');
121                                                 break;
122                                         case 'remove':
123                                                 if (!Model\Circle::removeMember($circle_id, $cdata['user'])) {
124                                                         throw new \Exception(DI::l10n()->t('Unable to remove the contact from the circle.'), 500);
125                                                 }
126
127                                                 $message = DI::l10n()->t('Contact successfully removed from circle.');
128                                                 break;
129                                 }
130                         } else {
131                                 throw new \Exception(DI::l10n()->t('Bad request.'), 400);
132                         }
133
134                         DI::sysmsg()->addInfo($message);
135                         $this->jsonExit(['status' => 'OK', 'message' => $message]);
136                 } catch (\Exception $e) {
137                         DI::sysmsg()->addNotice($e->getMessage());
138                         $this->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 (!DI::userSession()->getLocalUserId()) {
147                         throw new \Friendica\Network\HTTPException\ForbiddenException();
148                 }
149
150                 DI::page()['aside'] = Model\Circle::sidebarWidget('contact', 'circle', 'extended', ((DI::args()->getArgc() > 1) ? DI::args()->getArgv()[1] : 'everyone'));
151
152                 // With no circle number provided we jump to the unassigned contacts as a starting point
153                 // @TODO: Replace with parameter from router
154                 if (DI::args()->getArgc() == 1) {
155                         DI::baseUrl()->redirect('circle/none');
156                 }
157
158                 // Switch to text mode interface if we have more than 'n' contacts or circle members
159                 $switchtotext = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'circle_edit_image_limit') ??
160                         DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'groupedit_image_limit');
161                 if (is_null($switchtotext)) {
162                         $switchtotext = DI::config()->get('system', 'groupedit_image_limit') ??
163                                 DI::config()->get('system', 'circle_edit_image_limit');
164                 }
165
166                 $tpl = Renderer::getMarkupTemplate('circle_edit.tpl');
167
168
169                 $context = [
170                         '$submit' => DI::l10n()->t('Save Circle'),
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 circle of contacts/friends.'),
178                                 '$gname' => ['circle_name', DI::l10n()->t('Circle Name: '), '', ''],
179                                 '$gid' => 'new',
180                                 '$form_security_token' => BaseModule::getFormSecurityToken('circle_edit'),
181                         ]);
182                 }
183
184                 $nocircle = 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] === 'nocircle')) {
189                         $id = -1;
190                         $nocircle = true;
191                         $circle = [
192                                 'id' => $id,
193                                 'name' => DI::l10n()->t('Contacts not in any circle'),
194                         ];
195
196                         $members = [];
197                         $preselected = [];
198
199                         $context = $context + [
200                                 '$title' => $circle['name'],
201                                 '$gname' => ['circle_name', DI::l10n()->t('Circle Name: '), $circle['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('/circle', 'circle_drop', 't');
210
211                         // @TODO: Replace with parameter from router
212                         if (intval(DI::args()->getArgv()[2])) {
213                                 if (!Model\Circle::exists(DI::args()->getArgv()[2], DI::userSession()->getLocalUserId())) {
214                                         DI::sysmsg()->addNotice(DI::l10n()->t('Circle not found.'));
215                                         DI::baseUrl()->redirect('contact');
216                                 }
217
218                                 if (!Model\Circle::remove(DI::args()->getArgv()[2])) {
219                                         DI::sysmsg()->addNotice(DI::l10n()->t('Unable to remove circle.'));
220                                 }
221                         }
222                         DI::baseUrl()->redirect('circle');
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('circle_member_change', 't');
228
229                         if (DBA::exists('contact', ['id' => DI::args()->getArgv()[2], 'uid' => DI::userSession()->getLocalUserId(), '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                         $circle = DBA::selectFirst('group', ['id', 'name'], ['id' => DI::args()->getArgv()[1], 'uid' => DI::userSession()->getLocalUserId(), 'deleted' => false]);
237                         if (!DBA::isResult($circle)) {
238                                 DI::sysmsg()->addNotice(DI::l10n()->t('Circle not found.'));
239                                 DI::baseUrl()->redirect('contact');
240                         }
241
242                         $members = Model\Contact\Circle::getById($circle['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\Circle::removeMember($circle['id'], $change);
254                                 } else {
255                                         Model\Circle::addMember($circle['id'], $change);
256                                 }
257
258                                 $members = Model\Contact\Circle::getById($circle['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('circle_drop.tpl');
268                         $drop_txt = Renderer::replaceMacros($drop_tpl, [
269                                 '$id' => $circle['id'],
270                                 '$delete' => DI::l10n()->t('Delete Circle'),
271                                 '$form_security_token' => BaseModule::getFormSecurityToken('circle_drop'),
272                         ]);
273
274                         $context = $context + [
275                                 '$title' => $circle['name'],
276                                 '$gname' => ['circle_name', DI::l10n()->t('Circle Name: '), $circle['name'], ''],
277                                 '$gid' => $circle['id'],
278                                 '$drop' => $drop_txt,
279                                 '$form_security_token' => BaseModule::getFormSecurityToken('circle_edit'),
280                                 '$edit_name' => DI::l10n()->t('Edit Circle Name'),
281                                 '$editable' => 1,
282                         ];
283                 }
284
285                 if (!isset($circle)) {
286                         throw new \Friendica\Network\HTTPException\BadRequestException();
287                 }
288
289                 $circle_editor = [
290                         'label_members' => DI::l10n()->t('Members'),
291                         'members' => [],
292                         'label_contacts' => DI::l10n()->t('All Contacts'),
293                         'circle_is_empty' => DI::l10n()->t('Circle is empty'),
294                         'contacts' => [],
295                 ];
296
297                 $sec_token = addslashes(BaseModule::getFormSecurityToken('circle_member_change'));
298
299                 // Format the data of the circle 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 circle'),
307                                         'gid'       => $circle['id'],
308                                         'cid'       => $member['id'],
309                                         'sec_token' => $sec_token
310                                 ];
311
312                                 $circle_editor['members'][] = $entry;
313                         } else {
314                                 Model\Circle::removeMember($circle['id'], $member['id']);
315                         }
316                 }
317
318                 if ($nocircle) {
319                         $contacts = Model\Contact\Circle::listUncircled(DI::userSession()->getLocalUserId());
320                 } else {
321                         $networks = Widget::unavailableNetworks();
322                         $query = "`uid` = ? AND NOT `self` AND NOT `deleted` AND NOT `blocked` AND NOT `pending` AND NOT `failed`
323                                 AND `rel` IN (?, ?, ?)
324                                 AND NOT `network` IN (" . substr(str_repeat('?, ', count($networks)), 0, -2) . ")";
325                         $condition = array_merge([$query], [DI::userSession()->getLocalUserId(), Model\Contact::FOLLOWER, Model\Contact::FRIEND, Model\Contact::SHARING], $networks);
326
327                         $contacts_stmt = DBA::select('contact', [], $condition, ['order' => ['name']]);
328                         $contacts = DBA::toArray($contacts_stmt);
329                         $context['$desc'] = DI::l10n()->t('Click on a contact to add or remove.');
330                 }
331
332                 if (DBA::isResult($contacts)) {
333                         // Format the data of the contacts who aren't in the contact circle
334                         foreach ($contacts as $member) {
335                                 if (!in_array($member['id'], $preselected)) {
336                                         $entry = Contact::getContactTemplateVars($member);
337                                         $entry['label'] = 'contacts';
338                                         if (!$nocircle)
339                                                 $entry['photo_menu'] = [];
340
341                                         if (!$nocircle) {
342                                                 $entry['change_member'] = [
343                                                         'title'     => DI::l10n()->t('Add contact to circle'),
344                                                         'gid'       => $circle['id'],
345                                                         'cid'       => $member['id'],
346                                                         'sec_token' => $sec_token
347                                                 ];
348                                         }
349
350                                         $circle_editor['contacts'][] = $entry;
351                                 }
352                         }
353                 }
354
355                 $context['$circle_editor'] = $circle_editor;
356
357                 // If there are to many contacts we could provide an alternative view mode
358                 $total = count($circle_editor['members']) + count($circle_editor['contacts']);
359                 $context['$shortmode'] = (($switchtotext && ($total > $switchtotext)) ? true : false);
360
361                 if ($change) {
362                         $tpl = Renderer::getMarkupTemplate('circle_editor.tpl');
363                         echo Renderer::replaceMacros($tpl, $context);
364                         System::exit();
365                 }
366
367                 return Renderer::replaceMacros($tpl, $context);
368         }
369 }