Issue 13787: Filter in circles editor by contact relation
[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                 $relation = $request['rel'] ?? '';
146
147                 if (!DI::userSession()->getLocalUserId()) {
148                         throw new \Friendica\Network\HTTPException\ForbiddenException();
149                 }
150
151                 DI::page()['aside'] = Model\Circle::sidebarWidget('contact', 'circle', 'extended', ((DI::args()->getArgc() > 1) ? DI::args()->getArgv()[1] : 'everyone'));
152                 DI::page()['aside'] .= Widget::contactRels($this->server['REQUEST_URI'], $relation);
153
154                 // With no circle 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('circle/none');
158                 }
159
160                 // Switch to text mode interface if we have more than 'n' contacts or circle members
161                 $switchtotext = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'circle_edit_image_limit') ??
162                         DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'groupedit_image_limit');
163                 if (is_null($switchtotext)) {
164                         $switchtotext = DI::config()->get('system', 'groupedit_image_limit') ??
165                                 DI::config()->get('system', 'circle_edit_image_limit');
166                 }
167
168                 $tpl = Renderer::getMarkupTemplate('circle_edit.tpl');
169
170
171                 $context = [
172                         '$submit' => DI::l10n()->t('Save Circle'),
173                         '$submit_filter' => DI::l10n()->t('Filter'),
174                 ];
175
176                 // @TODO: Replace with parameter from router
177                 if ((DI::args()->getArgc() == 2) && (DI::args()->getArgv()[1] === 'new')) {
178                         return Renderer::replaceMacros($tpl, $context + [
179                                 '$title' => DI::l10n()->t('Create a circle of contacts/friends.'),
180                                 '$gname' => ['circle_name', DI::l10n()->t('Circle Name: '), '', ''],
181                                 '$gid' => 'new',
182                                 '$form_security_token' => BaseModule::getFormSecurityToken('circle_edit'),
183                         ]);
184                 }
185
186                 $nocircle = false;
187
188                 // @TODO: Replace with parameter from router
189                 if ((DI::args()->getArgc() == 2) && (DI::args()->getArgv()[1] === 'none') ||
190                         (DI::args()->getArgc() == 1) && (DI::args()->getArgv()[0] === 'nocircle')) {
191                         $id = -1;
192                         $nocircle = true;
193                         $circle = [
194                                 'id' => $id,
195                                 'name' => DI::l10n()->t('Contacts not in any circle'),
196                         ];
197
198                         $members = [];
199                         $preselected = [];
200
201                         $context = $context + [
202                                 '$title' => $circle['name'],
203                                 '$gname' => ['circle_name', DI::l10n()->t('Circle Name: '), $circle['name'], ''],
204                                 '$gid' => $id,
205                                 '$editable' => 0,
206                         ];
207                 }
208
209                 // @TODO: Replace with parameter from router
210                 if ((DI::args()->getArgc() == 3) && (DI::args()->getArgv()[1] === 'drop')) {
211                         BaseModule::checkFormSecurityTokenRedirectOnError('/circle', 'circle_drop', 't');
212
213                         // @TODO: Replace with parameter from router
214                         if (intval(DI::args()->getArgv()[2])) {
215                                 if (!Model\Circle::exists(DI::args()->getArgv()[2], DI::userSession()->getLocalUserId())) {
216                                         DI::sysmsg()->addNotice(DI::l10n()->t('Circle not found.'));
217                                         DI::baseUrl()->redirect('contact');
218                                 }
219
220                                 if (!Model\Circle::remove(DI::args()->getArgv()[2])) {
221                                         DI::sysmsg()->addNotice(DI::l10n()->t('Unable to remove circle.'));
222                                 }
223                         }
224                         DI::baseUrl()->redirect('circle');
225                 }
226
227                 // @TODO: Replace with parameter from router
228                 if ((DI::args()->getArgc() > 2) && intval(DI::args()->getArgv()[1]) && intval(DI::args()->getArgv()[2])) {
229                         BaseModule::checkFormSecurityTokenForbiddenOnError('circle_member_change', 't');
230
231                         if (DBA::exists('contact', ['id' => DI::args()->getArgv()[2], 'uid' => DI::userSession()->getLocalUserId(), 'self' => false, 'pending' => false, 'blocked' => false])) {
232                                 $change = intval(DI::args()->getArgv()[2]);
233                         }
234                 }
235
236                 // @TODO: Replace with parameter from router
237                 if ((DI::args()->getArgc() > 1) && intval(DI::args()->getArgv()[1])) {
238                         $circle = DBA::selectFirst('group', ['id', 'name'], ['id' => DI::args()->getArgv()[1], 'uid' => DI::userSession()->getLocalUserId(), 'deleted' => false]);
239                         if (!DBA::isResult($circle)) {
240                                 DI::sysmsg()->addNotice(DI::l10n()->t('Circle not found.'));
241                                 DI::baseUrl()->redirect('contact');
242                         }
243
244                         $members = Model\Contact\Circle::getById($circle['id']);
245                         $preselected = [];
246
247                         if (count($members)) {
248                                 foreach ($members as $member) {
249                                         $preselected[] = $member['id'];
250                                 }
251                         }
252
253                         if ($change) {
254                                 if (in_array($change, $preselected)) {
255                                         Model\Circle::removeMember($circle['id'], $change);
256                                 } else {
257                                         Model\Circle::addMember($circle['id'], $change);
258                                 }
259
260                                 $members = Model\Contact\Circle::getById($circle['id']);
261                                 $preselected = [];
262                                 if (count($members)) {
263                                         foreach ($members as $member) {
264                                                 $preselected[] = $member['id'];
265                                         }
266                                 }
267                         }
268
269                         $drop_tpl = Renderer::getMarkupTemplate('circle_drop.tpl');
270                         $drop_txt = Renderer::replaceMacros($drop_tpl, [
271                                 '$id' => $circle['id'],
272                                 '$delete' => DI::l10n()->t('Delete Circle'),
273                                 '$form_security_token' => BaseModule::getFormSecurityToken('circle_drop'),
274                         ]);
275
276                         $context = $context + [
277                                 '$title' => $circle['name'],
278                                 '$gname' => ['circle_name', DI::l10n()->t('Circle Name: '), $circle['name'], ''],
279                                 '$gid' => $circle['id'],
280                                 '$drop' => $drop_txt,
281                                 '$form_security_token' => BaseModule::getFormSecurityToken('circle_edit'),
282                                 '$edit_name' => DI::l10n()->t('Edit Circle Name'),
283                                 '$editable' => 1,
284                         ];
285                 }
286
287                 if (!isset($circle)) {
288                         throw new \Friendica\Network\HTTPException\BadRequestException();
289                 }
290
291                 $circle_editor = [
292                         'label_members' => DI::l10n()->t('Members'),
293                         'members' => [],
294                         'label_contacts' => DI::l10n()->t('All Contacts'),
295                         'circle_is_empty' => DI::l10n()->t('Circle is empty'),
296                         'contacts' => [],
297                 ];
298
299                 $sec_token = addslashes(BaseModule::getFormSecurityToken('circle_member_change'));
300
301                 // Format the data of the circle members
302                 foreach ($members as $member) {
303                         if (!self::matchRelation($relation, $member['rel'])) {
304                                 continue;
305                         }
306                         if ($member['url']) {
307                                 $entry = Contact::getContactTemplateVars($member);
308                                 $entry['label'] = 'members';
309                                 $entry['photo_menu'] = '';
310                                 $entry['change_member'] = [
311                                         'title'     => DI::l10n()->t('Remove contact from circle'),
312                                         'gid'       => $circle['id'],
313                                         'cid'       => $member['id'],
314                                         'sec_token' => $sec_token
315                                 ];
316
317                                 $circle_editor['members'][] = $entry;
318                         } else {
319                                 Model\Circle::removeMember($circle['id'], $member['id']);
320                         }
321                 }
322
323                 if ($nocircle) {
324                         $contacts = Model\Contact\Circle::listUncircled(DI::userSession()->getLocalUserId());
325                 } else {
326                         $networks = Widget::unavailableNetworks();
327                         $query = "`uid` = ? AND NOT `self` AND NOT `deleted` AND NOT `blocked` AND NOT `pending` AND NOT `failed`
328                                 AND `rel` IN (?, ?, ?)
329                                 AND NOT `network` IN (" . substr(str_repeat('?, ', count($networks)), 0, -2) . ")";
330                         $condition = array_merge([$query], [DI::userSession()->getLocalUserId(), Model\Contact::FOLLOWER, Model\Contact::FRIEND, Model\Contact::SHARING], $networks);
331
332                         $contacts_stmt = DBA::select('contact', [], $condition, ['order' => ['name']]);
333                         $contacts = DBA::toArray($contacts_stmt);
334                         $context['$desc'] = DI::l10n()->t('Click on a contact to add or remove.');
335                 }
336
337                 if (DBA::isResult($contacts)) {
338                         // Format the data of the contacts who aren't in the contact circle
339                         foreach ($contacts as $member) {
340                                 if (!self::matchRelation($relation, $member['rel'])) {
341                                         continue;
342                                 }
343                                 if (!in_array($member['id'], $preselected)) {
344                                         $entry = Contact::getContactTemplateVars($member);
345                                         $entry['label'] = 'contacts';
346                                         if (!$nocircle)
347                                                 $entry['photo_menu'] = [];
348
349                                         if (!$nocircle) {
350                                                 $entry['change_member'] = [
351                                                         'title'     => DI::l10n()->t('Add contact to circle'),
352                                                         'gid'       => $circle['id'],
353                                                         'cid'       => $member['id'],
354                                                         'sec_token' => $sec_token
355                                                 ];
356                                         }
357
358                                         $circle_editor['contacts'][] = $entry;
359                                 }
360                         }
361                 }
362
363                 $context['$circle_editor'] = $circle_editor;
364
365                 // If there are to many contacts we could provide an alternative view mode
366                 $total = count($circle_editor['members']) + count($circle_editor['contacts']);
367                 $context['$shortmode'] = (($switchtotext && ($total > $switchtotext)) ? true : false);
368
369                 if ($change) {
370                         $tpl = Renderer::getMarkupTemplate('circle_editor.tpl');
371                         echo Renderer::replaceMacros($tpl, $context);
372                         System::exit();
373                 }
374
375                 return Renderer::replaceMacros($tpl, $context);
376         }
377
378         private static function matchRelation(string $relation, int $rel)
379         {
380                 switch ($relation) {
381                         case 'followers':
382                                 return($rel == Model\Contact::FOLLOWER);
383                         case 'following':
384                                 return($rel == Model\Contact::SHARING);
385                         case 'mutuals':
386                                 return($rel == Model\Contact::FRIEND);
387                         case 'nothing':
388                                 return($rel == Model\Contact::NOTHING);
389                 }
390                 return true;
391         }
392 }