]> git.mxchange.org Git - friendica.git/blob - src/Module/Settings/Delegation.php
Merge pull request #13724 from Raroun/Fix-for-Issue-#13637---Photo-caption-prevents...
[friendica.git] / src / Module / Settings / Delegation.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\Settings;
23
24 use Friendica\App;
25 use Friendica\BaseModule;
26 use Friendica\Core\L10n;
27 use Friendica\Core\Renderer;
28 use Friendica\Core\Session\Capability\IHandleUserSessions;
29 use Friendica\Database\Database;
30 use Friendica\Model\User;
31 use Friendica\Module\BaseSettings;
32 use Friendica\Module\Response;
33 use Friendica\Navigation\SystemMessages;
34 use Friendica\Network\HTTPException;
35 use Friendica\Util\Profiler;
36 use Friendica\Util\Strings;
37 use Psr\Log\LoggerInterface;
38
39 /**
40  * Account delegation settings module
41  */
42 class Delegation extends BaseSettings
43 {
44         /** @var SystemMessages */
45         private $systemMessages;
46         /** @var Database */
47         private $db;
48
49         public function __construct(Database $db, SystemMessages $systemMessages, IHandleUserSessions $session, App\Page $page, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
50         {
51                 parent::__construct($session, $page, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
52
53                 $this->systemMessages = $systemMessages;
54                 $this->db             = $db;
55         }
56
57         protected function post(array $request = [])
58         {
59                 if (!$this->session->isAuthenticated()) {
60                         return;
61                 }
62
63                 BaseModule::checkFormSecurityTokenRedirectOnError('settings/delegation', 'delegate');
64
65                 $parent_uid      = $request['parent_user'] ?? null;
66                 $parent_password = $request['parent_password'] ?? '';
67
68                 if ($parent_uid) {
69                         try {
70                                 // An integer value will trigger the direct user query on uid in User::getAuthenticationInfo
71                                 $parent_uid = (int)$parent_uid;
72                                 User::getIdFromPasswordAuthentication($parent_uid, $parent_password);
73                                 $this->systemMessages->addInfo($this->t('Delegation successfully granted.'));
74                         } catch (\Exception $ex) {
75                                 $this->systemMessages->addNotice($this->t('Parent user not found, unavailable or password doesn\'t match.'));
76                                 return;
77                         }
78                 } else {
79                         $this->systemMessages->addInfo($this->t('Delegation successfully revoked.'));
80                 }
81
82                 $this->db->update('user', ['parent-uid' => $parent_uid], ['uid' => $this->session->getLocalUserId()]);
83         }
84
85         protected function content(array $request = []): string
86         {
87                 parent::content();
88
89                 if (!$this->session->isAuthenticated()) {
90                         throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
91                 }
92
93                 $action  = $this->parameters['action'] ?? '';
94                 $user_id = $this->parameters['user_id'] ?? 0;
95
96                 if ($action === 'add' && $user_id) {
97                         if ($this->session->getSubManagedUserId()) {
98                                 $this->systemMessages->addNotice($this->t('Delegated administrators can view but not change delegation permissions.'));
99                                 $this->baseUrl->redirect('settings/delegation');
100                         }
101
102                         $user = User::getById($user_id, ['nickname']);
103                         if ($this->db->isResult($user)) {
104                                 $condition = [
105                                         'uid'  => $this->session->getLocalUserId(),
106                                         'nurl' => Strings::normaliseLink($this->baseUrl . '/profile/' . $user['nickname'])
107                                 ];
108                                 if ($this->db->exists('contact', $condition)) {
109                                         $this->db->insert('manage', ['uid' => $user_id, 'mid' => $this->session->getLocalUserId()]);
110                                 }
111                         } else {
112                                 $this->systemMessages->addNotice($this->t('Delegate user not found.'));
113                         }
114
115                         $this->baseUrl->redirect('settings/delegation');
116                 }
117
118                 if ($action === 'remove' && $user_id) {
119                         if ($this->session->getSubManagedUserId()) {
120                                 $this->systemMessages->addNotice($this->t('Delegated administrators can view but not change delegation permissions.'));
121                                 $this->baseUrl->redirect('settings/delegation');
122                         }
123
124                         $this->db->delete('manage', ['uid' => $user_id, 'mid' => $this->session->getLocalUserId()]);
125                         $this->baseUrl->redirect('settings/delegation');
126                 }
127
128                 // find everybody that currently has delegated management to this account/page
129                 $delegates = $this->db->selectToArray('user', [], ['`uid` IN (SELECT `uid` FROM `manage` WHERE `mid` = ?)', $this->session->getLocalUserId()]);
130
131                 $uids = [];
132                 foreach ($delegates as $user) {
133                         $uids[] = $user['uid'];
134                 }
135
136                 // find every contact who might be a candidate for delegation
137                 $potentials = [];
138                 $nicknames  = [];
139
140                 $condition = ['baseurl' => $this->baseUrl, 'self' => false, 'uid' => $this->session->getLocalUserId(), 'blocked' => false];
141                 $contacts  = $this->db->select('contact', ['nick'], $condition);
142                 while ($contact = $this->db->fetch($contacts)) {
143                         $nicknames[] = $contact['nick'];
144                 }
145                 $this->db->close($contacts);
146
147                 // get user records for all potential page delegates who are not already delegates or managers
148                 $potentialDelegateUsers = $this->db->selectToArray(
149                         'user',
150                         ['uid', 'username', 'nickname'],
151                         [
152                                 'nickname'        => $nicknames,
153                                 'account_removed' => false,
154                                 'account_expired' => false,
155                                 'blocked'         => false,
156                         ]
157                 );
158                 foreach ($potentialDelegateUsers as $user) {
159                         if (!in_array($user['uid'], $uids)) {
160                                 $potentials[] = $user;
161                         }
162                 }
163
164                 $parent_user     = null;
165                 $parent_password = null;
166                 $user            = User::getById($this->session->getLocalUserId(), ['parent-uid', 'email']);
167                 if ($this->db->isResult($user) && !$this->db->exists('user', ['parent-uid' => $this->session->getLocalUserId()])) {
168                         $parent_uid = $user['parent-uid'];
169                         $parents    = [0 => $this->t('No parent user')];
170
171                         $fields       = ['uid', 'username', 'nickname'];
172                         $condition    = ['email' => $user['email'], 'verified' => true, 'blocked' => false, 'parent-uid' => null];
173                         $parent_users = $this->db->selectToArray('user', $fields, $condition);
174                         foreach ($parent_users as $parent) {
175                                 if ($parent['uid'] != $this->session->getLocalUserId()) {
176                                         $parents[$parent['uid']] = sprintf('%s (%s)', $parent['username'], $parent['nickname']);
177                                 }
178                         }
179
180                         $parent_user     = ['parent_user', $this->t('Parent User'), $parent_uid, '', $parents];
181                         $parent_password = ['parent_password', $this->t('Parent Password:'), '', $this->t('Please enter the password of the parent account to legitimize your request.')];
182                 }
183
184                 $is_child_user = !empty($user['parent-uid']);
185
186                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('settings/delegation.tpl'), [
187                         '$l10n' => [
188                                 'account_header'   => $this->t('Additional Accounts'),
189                                 'account_desc'     => $this->t('Register additional accounts that are automatically connected to your existing account so you can manage them from this account.'),
190                                 'add_account'      => $this->t('Register an additional account'),
191                                 'parent_header'    => $this->t('Parent User'),
192                                 'parent_desc'      => $this->t('Parent users have total control about this account, including the account settings. Please double check whom you give this access.'),
193                                 'submit'           => $this->t('Save Settings'),
194                                 'header'           => $this->t('Manage Accounts'),
195                                 'delegates_header' => $this->t('Delegates'),
196                                 'desc'             => $this->t('Delegates are able to manage all aspects of this account/page except for basic account settings. Please do not delegate your personal account to anybody that you do not trust completely.'),
197                                 'head_delegates'   => $this->t('Existing Page Delegates'),
198                                 'head_potentials'  => $this->t('Potential Delegates'),
199                                 'none'             => $this->t('No entries.'),
200                         ],
201
202                         '$form_security_token' => BaseModule::getFormSecurityToken('delegate'),
203                         '$parent_user'         => $parent_user,
204                         '$parent_password'     => $parent_password,
205                         '$is_child_user'       => $is_child_user,
206                         '$delegates'           => $delegates,
207                         '$potentials'          => $potentials,
208                 ]);
209         }
210 }