0522f4d80a0244ee761186b9b9db8fb9d5cace83
[Packages/TYPO3.CMS.git] / typo3 / sysext / sys_action / Classes / ActionTask.php
1 <?php
2 namespace TYPO3\CMS\SysAction;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Imaging\Icon;
19 use TYPO3\CMS\Core\Imaging\IconFactory;
20 use TYPO3\CMS\Core\Page\PageRenderer;
21 use TYPO3\CMS\Core\Utility\GeneralUtility;
22
23 /**
24 * This class provides a task for the taskcenter
25 */
26 class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
27 {
28 /**
29 * @var \TYPO3\CMS\Taskcenter\Controller\TaskModuleController
30 */
31 protected $taskObject;
32
33 /**
34 * All hook objects get registered here for later use
35 *
36 * @var array
37 */
38 protected $hookObjects = array();
39
40 /**
41 * URL to task module
42 *
43 * @var string
44 */
45 protected $moduleUrl;
46
47 /**
48 * @var IconFactory
49 */
50 protected $iconFactory;
51
52 /**
53 * Constructor
54 */
55 public function __construct(\TYPO3\CMS\Taskcenter\Controller\TaskModuleController $taskObject)
56 {
57 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
58 $this->moduleUrl = BackendUtility::getModuleUrl('user_task');
59 $this->taskObject = $taskObject;
60 $this->getLanguageService()->includeLLFile('EXT:sys_action/Resources/Private/Language/locallang.xlf');
61 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['sys_action']['tx_sysaction_task'])) {
62 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['sys_action']['tx_sysaction_task'] as $classRef) {
63 $this->hookObjects[] = GeneralUtility::getUserObj($classRef);
64 }
65 }
66 }
67
68 /**
69 * This method renders the task
70 *
71 * @return string The task as HTML
72 */
73 public function getTask()
74 {
75 $content = '';
76 $show = (int)GeneralUtility::_GP('show');
77 foreach ($this->hookObjects as $hookObject) {
78 if (method_exists($hookObject, 'getTask')) {
79 $show = $hookObject->getTask($show, $this);
80 }
81 }
82 // If no task selected, render the menu
83 if ($show == 0) {
84 $content .= $this->taskObject->description($this->getLanguageService()->getLL('sys_action'), $this->getLanguageService()->getLL('description'));
85 $content .= $this->renderActionList();
86 } else {
87 $record = BackendUtility::getRecord('sys_action', $show);
88 // If the action is not found
89 if (empty($record)) {
90 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $this->getLanguageService()->getLL('action_error-not-found', true), $this->getLanguageService()->getLL('action_error'), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
91 $content .= $flashMessage->render();
92 } else {
93 // Render the task
94 $content .= $this->taskObject->description($record['title'], $record['description']);
95 // Output depends on the type
96 switch ($record['type']) {
97 case 1:
98 $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
99 $pageRenderer->loadRequireJsModule('TYPO3/CMS/SysAction/ActionTask');
100 $content .= $this->viewNewBackendUser($record);
101 break;
102 case 2:
103 $content .= $this->viewSqlQuery($record);
104 break;
105 case 3:
106 $content .= $this->viewRecordList($record);
107 break;
108 case 4:
109 $content .= $this->viewEditRecord($record);
110 break;
111 case 5:
112 $content .= $this->viewNewRecord($record);
113 break;
114 default:
115 $flashMessage = GeneralUtility::makeInstance(
116 \TYPO3\CMS\Core\Messaging\FlashMessage::class,
117 $this->getLanguageService()->getLL('action_noType', true),
118 $this->getLanguageService()->getLL('action_error'),
119 \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
120 );
121 $content .= '<br />' . $flashMessage->render();
122 }
123 }
124 }
125 return $content;
126 }
127
128 /**
129 * General overview over the task in the taskcenter menu
130 *
131 * @return string Overview as HTML
132 */
133 public function getOverview()
134 {
135 $content = '<p>' . $this->getLanguageService()->getLL('description') . '</p>';
136 // Get the actions
137 $actionList = $this->getActions();
138 if (!empty($actionList)) {
139 $items = '';
140 // Render a single action menu item
141 foreach ($actionList as $action) {
142 $active = GeneralUtility::_GP('show') === $action['uid'] ? ' class="active" ' : '';
143 $items .= '<li' . $active . '>
144 <a href="' . $action['link'] . '" title="' . htmlspecialchars($action['description']) . '">' . htmlspecialchars($action['title']) . '</a>
145 </li>';
146 }
147 $content .= '<ul>' . $items . '</ul>';
148 }
149 return $content;
150 }
151
152 /**
153 * Get all actions of an user. Admins can see any action, all others only those
154 * which are allowed in sys_action record itself.
155 *
156 * @return array Array holding every needed information of a sys_action
157 */
158 protected function getActions()
159 {
160 $actionList = array();
161 // admins can see any record
162 if ($this->getBackendUser()->isAdmin()) {
163 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'sys_action', '', '', 'sys_action.sorting');
164 } else {
165 // Editors can only see the actions which are assigned to a usergroup they belong to
166 $additionalWhere = 'be_groups.uid IN (' . ($this->getBackendUser()->groupList ?: 0) . ')';
167 $res = $this->getDatabaseConnection()->exec_SELECT_mm_query('sys_action.*', 'sys_action', 'sys_action_asgr_mm', 'be_groups', ' AND sys_action.hidden=0 AND ' . $additionalWhere, 'sys_action.uid', 'sys_action.sorting');
168 }
169 while ($actionRow = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
170 $editActionLink = '';
171 // Admins are allowed to edit sys_action records
172 if ($this->getBackendUser()->isAdmin()) {
173 $link = BackendUtility::getModuleUrl(
174 'record_edit',
175 array(
176 'edit[sys_action][' . $actionRow['uid'] . ']' => 'edit',
177 'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')
178 ),
179 false,
180 true
181 );
182 $title = 'title="' . $this->getLanguageService()->getLL('edit-sys_action') . '"';
183 $icon = $this->iconFactory->getIcon('actions-document-info', Icon::SIZE_SMALL)->render();
184 $editActionLink = '<a class="edit" href="' . $link . '"' . $title . '>';
185 $editActionLink .= $icon . $this->getLanguageService()->getLL('edit-sys_action') . '</a>';
186 }
187 $actionList[] = array(
188 'uid' => $actionRow['uid'],
189 'title' => $actionRow['title'],
190 'description' => $actionRow['description'],
191 'descriptionHtml' => nl2br(htmlspecialchars($actionRow['description'])) . $editActionLink,
192 'link' => $this->moduleUrl . '&SET[function]=sys_action.TYPO3\\CMS\\SysAction\\ActionTask&show=' . $actionRow['uid']
193 );
194 }
195 $this->getDatabaseConnection()->sql_free_result($res);
196 return $actionList;
197 }
198
199 /**
200 * Render the menu of sys_actions
201 *
202 * @return string List of sys_actions as HTML
203 */
204 protected function renderActionList()
205 {
206 $content = '';
207 // Get the sys_action records
208 $actionList = $this->getActions();
209 // If any actions are found for the current users
210 if (!empty($actionList)) {
211 $content .= $this->taskObject->renderListMenu($actionList);
212 } else {
213 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $this->getLanguageService()->getLL('action_not-found-description', true), $this->getLanguageService()->getLL('action_not-found'), \TYPO3\CMS\Core\Messaging\FlashMessage::INFO);
214 $content .= $flashMessage->render();
215 }
216 // Admin users can create a new action
217 if ($this->getBackendUser()->isAdmin()) {
218 $link = BackendUtility::getModuleUrl(
219 'record_edit',
220 array(
221 'edit[sys_action][0]' => 'new',
222 'returnUrl' => $this->moduleUrl
223 ),
224 false,
225 true
226 );
227 $content .= '<p>' .
228 '<a href="' . $link . '" title="' . $this->getLanguageService()->getLL('new-sys_action') . '">' .
229 $this->iconFactory->getIcon('actions-document-new', Icon::SIZE_SMALL)->render() .
230 $this->getLanguageService()->getLL('new-sys_action') .
231 '</a></p>';
232 }
233 return $content;
234 }
235
236 /**
237 * Action to create a new BE user
238 *
239 * @param array $record sys_action record
240 * @return string form to create a new user
241 */
242 protected function viewNewBackendUser($record)
243 {
244 $content = '';
245 $beRec = BackendUtility::getRecord('be_users', (int)$record['t1_copy_of_user']);
246 // A record is need which is used as copy for the new user
247 if (!is_array($beRec)) {
248 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $this->getLanguageService()->getLL('action_notReady', true), $this->getLanguageService()->getLL('action_error'), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
249 $content .= $flashMessage->render();
250 return $content;
251 }
252 $vars = GeneralUtility::_POST('data');
253 $key = 'NEW';
254 if ($vars['sent'] == 1) {
255 $errors = array();
256 // Basic error checks
257 if (!empty($vars['email']) && !GeneralUtility::validEmail($vars['email'])) {
258 $errors[] = $this->getLanguageService()->getLL('error-wrong-email');
259 }
260 if (empty($vars['username'])) {
261 $errors[] = $this->getLanguageService()->getLL('error-username-empty');
262 }
263 if ($vars['key'] === 'NEW' && empty($vars['password'])) {
264 $errors[] = $this->getLanguageService()->getLL('error-password-empty');
265 }
266 if ($vars['key'] !== 'NEW' && !$this->isCreatedByUser($vars['key'], $record)) {
267 $errors[] = $this->getLanguageService()->getLL('error-wrong-user');
268 }
269 foreach ($this->hookObjects as $hookObject) {
270 if (method_exists($hookObject, 'viewNewBackendUser_Error')) {
271 $errors = $hookObject->viewNewBackendUser_Error($vars, $errors, $this);
272 }
273 }
274 // Show errors if there are any
275 if (!empty($errors)) {
276 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, implode('<br />', $errors), $this->getLanguageService()->getLL('action_error'), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
277 $content .= $flashMessage->render() . '<br />';
278 } else {
279 // Save user
280 $key = $this->saveNewBackendUser($record, $vars);
281 // Success message
282 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $vars['key'] === 'NEW' ? $this->getLanguageService()->getLL('success-user-created') : $this->getLanguageService()->getLL('success-user-updated'), $this->getLanguageService()->getLL('success'), \TYPO3\CMS\Core\Messaging\FlashMessage::OK);
283 $content .= $flashMessage->render() . '<br />';
284 }
285 }
286 // Load BE user to edit
287 if ((int)GeneralUtility::_GP('be_users_uid') > 0) {
288 $tmpUserId = (int)GeneralUtility::_GP('be_users_uid');
289 // Check if the selected user is created by the current user
290 $rawRecord = $this->isCreatedByUser($tmpUserId, $record);
291 if ($rawRecord) {
292 // Delete user
293 if (GeneralUtility::_GP('delete') == 1) {
294 $this->deleteUser($tmpUserId, $record['uid']);
295 }
296 $key = $tmpUserId;
297 $vars = $rawRecord;
298 }
299 }
300 $content .= '<form action="" method="post" enctype="multipart/form-data">
301 <fieldset class="fields">
302 <legend>' . $this->getLanguageService()->getLL('action_t1_legend_generalFields') . '</legend>
303 <div class="row">
304 <label for="field_disable">' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_general.xlf:LGL.disable') . '</label>
305 <input type="checkbox" id="field_disable" name="data[disable]" value="1" class="checkbox" ' . ($vars['disable'] == 1 ? ' checked="checked" ' : '') . ' />
306 </div>
307 <div class="row">
308 <label for="field_realname">' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_general.xlf:LGL.name') . '</label>
309 <input type="text" id="field_realname" name="data[realName]" value="' . htmlspecialchars($vars['realName']) . '" />
310 </div>
311 <div class="row">
312 <label for="field_username">' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_tca.xlf:be_users.username') . '</label>
313 <input type="text" id="field_username" name="data[username]" value="' . htmlspecialchars($vars['username']) . '" />
314 </div>
315 <div class="row">
316 <label for="field_password">' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_tca.xlf:be_users.password') . '</label>
317 <input type="password" id="field_password" name="data[password]" value="" />
318 </div>
319 <div class="row">
320 <label for="field_email">' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_general.xlf:LGL.email') . '</label>
321 <input type="text" id="field_email" name="data[email]" value="' . htmlspecialchars($vars['email']) . '" />
322 </div>
323 </fieldset>
324 <fieldset class="fields">
325 <legend>' . $this->getLanguageService()->getLL('action_t1_legend_configuration') . '</legend>
326
327 <div class="row">
328 <label for="field_usergroup">' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_tca.xlf:be_users.usergroup') . '</label>
329 <select id="field_usergroup" name="data[usergroup][]" multiple="multiple">
330 ' . $this->getUsergroups($record, $vars) . '
331 </select>
332 </div>
333 <div class="row">
334 <input type="hidden" name="data[key]" value="' . $key . '" />
335 <input type="hidden" name="data[sent]" value="1" />
336 <input class="btn btn-default" type="submit" value="' . ($key === 'NEW' ? $this->getLanguageService()->getLL('action_Create') : $this->getLanguageService()->getLL('action_Update')) . '" />
337 </div>
338 </fieldset>
339 </form>';
340 $content .= $this->getCreatedUsers($record, $key);
341 return $content;
342 }
343
344 /**
345 * Delete a BE user and redirect to the action by its id
346 *
347 * @param int $userId Id of the BE user
348 * @param int $actionId Id of the action
349 * @return void
350 */
351 protected function deleteUser($userId, $actionId)
352 {
353 $this->getDatabaseConnection()->exec_UPDATEquery('be_users', 'uid=' . $userId, array(
354 'deleted' => 1,
355 'tstamp' => $GLOBALS['ACCESS_TIME']
356 ));
357 // redirect to the original task
358 $redirectUrl = $this->moduleUrl . '&show=' . $actionId;
359 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($redirectUrl);
360 }
361
362 /**
363 * Check if a BE user is created by the current user
364 *
365 * @param int $id Id of the BE user
366 * @param array $action sys_action record.
367 * @return mixed The record of the BE user if found, otherwise FALSE
368 */
369 protected function isCreatedByUser($id, $action)
370 {
371 $record = BackendUtility::getRecord('be_users', $id, '*', ' AND cruser_id=' . $this->getBackendUser()->user['uid'] . ' AND createdByAction=' . $action['uid']);
372 if (is_array($record)) {
373 return $record;
374 } else {
375 return false;
376 }
377 }
378
379 /**
380 * Render all users who are created by the current BE user including a link to edit the record
381 *
382 * @param array $action sys_action record.
383 * @param int $selectedUser Id of a selected user
384 * @return string html list of users
385 */
386 protected function getCreatedUsers($action, $selectedUser)
387 {
388 $content = '';
389 $userList = array();
390 // List of users
391 $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'be_users', 'cruser_id=' . $this->getBackendUser()->user['uid'] . ' AND createdByAction=' . (int)$action['uid'] . BackendUtility::deleteClause('be_users'), '', 'username');
392 // Render the user records
393 while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
394 $icon = '<span title="' . htmlspecialchars('uid=' . $row['uid']) . '">' . $this->iconFactory->getIconForRecord('be_users', $row, Icon::SIZE_SMALL)->render() . '</span>';
395 $line = $icon . $this->action_linkUserName($row['username'], $row['realName'], $action['uid'], $row['uid']);
396 // Selected user
397 if ($row['uid'] == $selectedUser) {
398 $line = '<strong>' . $line . '</strong>';
399 }
400 $userList[] = $line;
401 }
402 $this->getDatabaseConnection()->sql_free_result($res);
403 // If any records found
404 if (!empty($userList)) {
405 $content .= '<br /><h3>' . $this->getLanguageService()->getLL('action_t1_listOfUsers', true) . '</h3><div>' . implode('<br />', $userList) . '</div>';
406 }
407 return $content;
408 }
409
410 /**
411 * Create a link to edit a user
412 *
413 * @param string $username Username
414 * @param string $realName Real name of the user
415 * @param int $sysActionUid Id of the sys_action record
416 * @param int $userId Id of the user
417 * @return string html link
418 */
419 protected function action_linkUserName($username, $realName, $sysActionUid, $userId)
420 {
421 if (!empty($realName)) {
422 $username .= ' (' . $realName . ')';
423 }
424 // Link to update the user record
425 $href = $this->moduleUrl . '&SET[function]=sys_action.TYPO3\\CMS\\SysAction\\ActionTask&show=' . (int)$sysActionUid . '&be_users_uid=' . (int)$userId;
426 $link = '<a href="' . htmlspecialchars($href) . '">' . htmlspecialchars($username) . '</a>';
427 // Link to delete the user record
428 $link .= '
429 <a href="' . htmlspecialchars(($href . '&delete=1')) . '" class="t3js-confirm-trigger" data-title="' . $this->getLanguageService()->getLL('lDelete_warning_title', true) . '" data-message="' . $this->getLanguageService()->getLL('lDelete_warning', true) . '">'
430 . $this->iconFactory->getIcon('actions-edit-delete', Icon::SIZE_SMALL)->render() .
431 '</a>';
432 return $link;
433 }
434
435 /**
436 * Save/Update a BE user
437 *
438 * @param array $record Current action record
439 * @param array $vars POST vars
440 * @return int Id of the new/updated user
441 */
442 protected function saveNewBackendUser($record, $vars)
443 {
444 // Check if the db mount is a page the current user is allowed to.);
445 $vars['db_mountpoints'] = $this->fixDbMount($vars['db_mountpoints']);
446 // Check if the usergroup is allowed
447 $vars['usergroup'] = $this->fixUserGroup($vars['usergroup'], $record);
448 $key = $vars['key'];
449 $vars['password'] = trim($vars['password']);
450 // Check if md5 is used as password encryption
451 if ($vars['password'] !== '' && strpos($GLOBALS['TCA']['be_users']['columns']['password']['config']['eval'], 'md5') !== false) {
452 $vars['password'] = md5($vars['password']);
453 }
454 $data = '';
455 $newUserId = 0;
456 if ($key === 'NEW') {
457 $beRec = BackendUtility::getRecord('be_users', (int)$record['t1_copy_of_user']);
458 if (is_array($beRec)) {
459 $data = array();
460 $data['be_users'][$key] = $beRec;
461 $data['be_users'][$key]['username'] = $this->fixUsername($vars['username'], $record['t1_userprefix']);
462 $data['be_users'][$key]['password'] = $vars['password'];
463 $data['be_users'][$key]['realName'] = $vars['realName'];
464 $data['be_users'][$key]['email'] = $vars['email'];
465 $data['be_users'][$key]['disable'] = (int)$vars['disable'];
466 $data['be_users'][$key]['admin'] = 0;
467 $data['be_users'][$key]['usergroup'] = $vars['usergroup'];
468 $data['be_users'][$key]['db_mountpoints'] = $vars['db_mountpoints'];
469 $data['be_users'][$key]['createdByAction'] = $record['uid'];
470 }
471 } else {
472 // Check ownership
473 $beRec = BackendUtility::getRecord('be_users', (int)$key);
474 if (is_array($beRec) && $beRec['cruser_id'] == $this->getBackendUser()->user['uid']) {
475 $data = array();
476 $data['be_users'][$key]['username'] = $this->fixUsername($vars['username'], $record['t1_userprefix']);
477 if ($vars['password'] !== '') {
478 $data['be_users'][$key]['password'] = $vars['password'];
479 }
480 $data['be_users'][$key]['realName'] = $vars['realName'];
481 $data['be_users'][$key]['email'] = $vars['email'];
482 $data['be_users'][$key]['disable'] = (int)$vars['disable'];
483 $data['be_users'][$key]['admin'] = 0;
484 $data['be_users'][$key]['usergroup'] = $vars['usergroup'];
485 $data['be_users'][$key]['db_mountpoints'] = $vars['db_mountpoints'];
486 $newUserId = $key;
487 }
488 }
489 // Save/update user by using TCEmain
490 if (is_array($data)) {
491 $tce = GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
492 $tce->start($data, array(), $this->getBackendUser());
493 $tce->admin = 1;
494 $tce->process_datamap();
495 $newUserId = (int)$tce->substNEWwithIDs['NEW'];
496 if ($newUserId) {
497 // Create
498 $this->action_createDir($newUserId);
499 } else {
500 // Update
501 $newUserId = (int)$key;
502 }
503 unset($tce);
504 }
505 return $newUserId;
506 }
507
508 /**
509 * Create the username based on the given username and the prefix
510 *
511 * @param string $username Username
512 * @param string $prefix Prefix
513 * @return string Combined username
514 */
515 protected function fixUsername($username, $prefix)
516 {
517 $prefix = trim($prefix);
518 if (substr($username, 0, strlen($prefix)) === $prefix) {
519 $username = substr($username, strlen($prefix));
520 }
521 return $prefix . $username;
522 }
523
524 /**
525 * Clean the to be applied usergroups from not allowed ones
526 *
527 * @param array $appliedUsergroups Array of to be applied user groups
528 * @param array $actionRecord The action record
529 * @return array Cleaned array
530 */
531 protected function fixUserGroup($appliedUsergroups, $actionRecord)
532 {
533 if (is_array($appliedUsergroups)) {
534 $cleanGroupList = array();
535 // Create an array from the allowed usergroups using the uid as key
536 $allowedUsergroups = array_flip(explode(',', $actionRecord['t1_allowed_groups']));
537 // Walk through the array and check every uid if it is under the allowed ines
538 foreach ($appliedUsergroups as $group) {
539 if (isset($allowedUsergroups[$group])) {
540 $cleanGroupList[] = $group;
541 }
542 }
543 $appliedUsergroups = $cleanGroupList;
544 }
545 return $appliedUsergroups;
546 }
547
548 /**
549 * Clean the to be applied DB-Mounts from not allowed ones
550 *
551 * @param string $appliedDbMounts List of pages like pages_123,pages456
552 * @return string Cleaned list
553 */
554 protected function fixDbMount($appliedDbMounts)
555 {
556 // Admins can see any page, no need to check there
557 if (!empty($appliedDbMounts) && !$this->getBackendUser()->isAdmin()) {
558 $cleanDbMountList = array();
559 $dbMounts = GeneralUtility::trimExplode(',', $appliedDbMounts, true);
560 // Walk through every wanted DB-Mount and check if it allowed for the current user
561 foreach ($dbMounts as $dbMount) {
562 $uid = (int)substr($dbMount, strrpos($dbMount, '_') + 1);
563 $page = BackendUtility::getRecord('pages', $uid);
564 // Check rootline and access rights
565 if ($this->checkRootline($uid) && $this->getBackendUser()->calcPerms($page)) {
566 $cleanDbMountList[] = 'pages_' . $uid;
567 }
568 }
569 // Build the clean list
570 $appliedDbMounts = implode(',', $cleanDbMountList);
571 }
572 return $appliedDbMounts;
573 }
574
575 /**
576 * Check if a page is inside the rootline the current user can see
577 *
578 * @param int $pageId Id of the the page to be checked
579 * @return bool Access to the page
580 */
581 protected function checkRootline($pageId)
582 {
583 $access = false;
584 $dbMounts = array_flip(explode(',', trim($this->getBackendUser()->dataLists['webmount_list'], ',')));
585 $rootline = BackendUtility::BEgetRootLine($pageId);
586 foreach ($rootline as $page) {
587 if (isset($dbMounts[$page['uid']]) && !$access) {
588 $access = true;
589 }
590 }
591 return $access;
592 }
593
594 /**
595 * Create a user directory if defined
596 *
597 * @param int $uid Id of the user record
598 * @return void
599 */
600 protected function action_createDir($uid)
601 {
602 $path = $this->action_getUserMainDir();
603 if ($path) {
604 GeneralUtility::mkdir($path . $uid);
605 GeneralUtility::mkdir($path . $uid . '/_temp_/');
606 }
607 }
608
609 /**
610 * Get the path to the user home directory which is set in the localconf.php
611 *
612 * @return string Path
613 */
614 protected function action_getUserMainDir()
615 {
616 $path = $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'];
617 // If path is set and a valid directory
618 if ($path && @is_dir($path) && $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && GeneralUtility::isFirstPartOfStr($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']) && substr($path, -1) == '/') {
619 return $path;
620 }
621 }
622
623 /**
624 * Get all allowed usergroups which can be applied to a user record
625 *
626 * @param array $record sys_action record
627 * @param array $vars Selected be_user record
628 * @return string Rendered user groups
629 */
630 protected function getUsergroups($record, $vars)
631 {
632 $content = '';
633 // Do nothing if no groups are allowed
634 if (empty($record['t1_allowed_groups'])) {
635 return $content;
636 }
637 $content .= '<option value=""></option>';
638 $grList = GeneralUtility::trimExplode(',', $record['t1_allowed_groups'], true);
639 foreach ($grList as $group) {
640 $checkGroup = BackendUtility::getRecord('be_groups', $group);
641 if (is_array($checkGroup)) {
642 $selected = GeneralUtility::inList($vars['usergroup'], $checkGroup['uid']) ? ' selected="selected" ' : '';
643 $content .= '<option ' . $selected . 'value="' . $checkGroup['uid'] . '">' . htmlspecialchars($checkGroup['title']) . '</option>';
644 }
645 }
646 return $content;
647 }
648
649 /**
650 * Action to create a new record
651 *
652 * @param array $record sys_action record
653 * @return void Redirect to form to create a record
654 */
655 protected function viewNewRecord($record)
656 {
657 $link = BackendUtility::getModuleUrl(
658 'record_edit',
659 array(
660 'edit[' . $record['t3_tables'] . '][' . (int)$record['t3_listPid'] . ']' => 'new',
661 'returnUrl' => $this->moduleUrl
662 ),
663 false,
664 true
665 );
666 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($link);
667 }
668
669 /**
670 * Action to edit records
671 *
672 * @param array $record sys_action record
673 * @return string list of records
674 */
675 protected function viewEditRecord($record)
676 {
677 $content = '';
678 $actionList = array();
679 $dbAnalysis = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
680 $dbAnalysis->setFetchAllFields(true);
681 $dbAnalysis->start($record['t4_recordsToEdit'], '*');
682 $dbAnalysis->getFromDB();
683 // collect the records
684 foreach ($dbAnalysis->itemArray as $el) {
685 $path = BackendUtility::getRecordPath($el['id'], $this->taskObject->perms_clause, $this->getBackendUser()->uc['titleLen']);
686 $record = BackendUtility::getRecord($el['table'], $dbAnalysis->results[$el['table']][$el['id']]);
687 $title = BackendUtility::getRecordTitle($el['table'], $dbAnalysis->results[$el['table']][$el['id']]);
688 $description = $this->getLanguageService()->sL($GLOBALS['TCA'][$el['table']]['ctrl']['title'], true);
689 // @todo: which information could be needful
690 if (isset($record['crdate'])) {
691 $description .= ' - ' . BackendUtility::dateTimeAge($record['crdate']);
692 }
693 $link = BackendUtility::getModuleUrl(
694 'record_edit',
695 array(
696 'edit[' . $el['table'] . '][' . $el['id'] . ']' => 'edit',
697 'returnUrl' => $this->moduleUrl
698 ),
699 false,
700 true
701 );
702 $actionList[$el['id']] = array(
703 'title' => $title,
704 'description' => BackendUtility::getRecordTitle($el['table'], $dbAnalysis->results[$el['table']][$el['id']]),
705 'descriptionHtml' => $description,
706 'link' => $link,
707 'icon' => '<span title="' . htmlspecialchars($path) . '">' . $this->iconFactory->getIconForRecord($el['table'], $dbAnalysis->results[$el['table']][$el['id']], Icon::SIZE_SMALL)->render() . '</span>'
708 );
709 }
710 // Render the record list
711 $content .= $this->taskObject->renderListMenu($actionList);
712 return $content;
713 }
714
715 /**
716 * Action to view the result of a SQL query
717 *
718 * @param array $record sys_action record
719 * @return string Result of the query
720 */
721 protected function viewSqlQuery($record)
722 {
723 $content = '';
724 if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('lowlevel')) {
725 $sql_query = unserialize($record['t2_data']);
726 if (!is_array($sql_query) || is_array($sql_query) && strtoupper(substr(trim($sql_query['qSelect']), 0, 6)) === 'SELECT') {
727 $actionContent = '';
728 $fullsearch = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\QueryView::class);
729 $fullsearch->formW = 40;
730 $fullsearch->noDownloadB = 1;
731 $type = $sql_query['qC']['search_query_makeQuery'];
732 if ($sql_query['qC']['labels_noprefix'] === 'on') {
733 $GLOBALS['SOBE']->MOD_SETTINGS['labels_noprefix'] = 'on';
734 }
735 $sqlQuery = $sql_query['qSelect'];
736 $queryIsEmpty = false;
737 if ($sqlQuery) {
738 $res = $this->getDatabaseConnection()->sql_query($sqlQuery);
739 if (!$this->getDatabaseConnection()->sql_error()) {
740 $fullsearch->formW = 48;
741 // Additional configuration
742 $GLOBALS['SOBE']->MOD_SETTINGS['search_result_labels'] = 1;
743 $GLOBALS['SOBE']->MOD_SETTINGS['queryFields'] = $sql_query['qC']['queryFields'];
744 $cP = $fullsearch->getQueryResultCode($type, $res, $sql_query['qC']['queryTable']);
745 $actionContent = $cP['content'];
746 // If the result is rendered as csv or xml, show a download link
747 if ($type === 'csv' || $type === 'xml') {
748 $actionContent .= '<br /><br /><a href="' . GeneralUtility::getIndpEnv('REQUEST_URI') . '&download_file=1"><strong>' . $this->getLanguageService()->getLL('action_download_file') . '</strong></a>';
749 }
750 } else {
751 $actionContent .= $this->getDatabaseConnection()->sql_error();
752 }
753 } else {
754 // Query is empty (not built)
755 $queryIsEmpty = true;
756 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $this->getLanguageService()->getLL('action_emptyQuery', true), $this->getLanguageService()->getLL('action_error'), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
757 $content .= '<br />' . $flashMessage->render();
758 }
759 // Admin users are allowed to see and edit the query
760 if ($this->getBackendUser()->isAdmin()) {
761 if (!$queryIsEmpty) {
762 $actionContent .= '<hr /> ' . $fullsearch->tableWrap($sql_query['qSelect']);
763 }
764 $actionContent .= '<br /><a title="' . $this->getLanguageService()->getLL('action_editQuery') . '" href="'
765 . htmlspecialchars(BackendUtility::getModuleUrl('system_dbint')
766 . '&id=' . '&SET[function]=search' . '&SET[search]=query'
767 . '&storeControl[STORE]=-' . $record['uid'] . '&storeControl[LOAD]=1')
768 . '">'
769 . $this->iconFactory->getIcon('actions-document-info', Icon::SIZE_SMALL)->render()
770 . $this->getLanguageService()->getLL(($queryIsEmpty ? 'action_createQuery'
771 : 'action_editQuery')) . '</a><br /><br />';
772 }
773 $content .= '<h2>' . $this->getLanguageService()->getLL('action_t2_result', true) . '</h2><div>' . $actionContent . '</div>';
774 } else {
775 // Query is not configured
776 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $this->getLanguageService()->getLL('action_notReady', true), $this->getLanguageService()->getLL('action_error'), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
777 $content .= '<br />' . $flashMessage->render();
778 }
779 } else {
780 // Required sysext lowlevel is not installed
781 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $this->getLanguageService()->getLL('action_lowlevelMissing', true), $this->getLanguageService()->getLL('action_error'), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
782 $content .= '<br />' . $flashMessage->render();
783 }
784 return $content;
785 }
786
787 /**
788 * Action to create a list of records of a specific table and pid
789 *
790 * @param array $record sys_action record
791 * @return string list of records
792 */
793 protected function viewRecordList($record)
794 {
795 $content = '';
796 $this->id = (int)$record['t3_listPid'];
797 $this->table = $record['t3_tables'];
798 if ($this->id == 0) {
799 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $this->getLanguageService()->getLL('action_notReady', true), $this->getLanguageService()->getLL('action_error'), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
800 $content .= '<br />' . $flashMessage->render();
801 return $content;
802 }
803 // Loading current page record and checking access:
804 $this->pageinfo = BackendUtility::readPageAccess($this->id, $this->taskObject->perms_clause);
805 $access = is_array($this->pageinfo) ? 1 : 0;
806 // If there is access to the page, then render the list contents and set up the document template object:
807 if ($access) {
808 // Initialize the dblist object:
809 $dblist = GeneralUtility::makeInstance(\TYPO3\CMS\SysAction\ActionList::class);
810 $dblist->script = GeneralUtility::getIndpEnv('REQUEST_URI');
811 $dblist->calcPerms = $this->getBackendUser()->calcPerms($this->pageinfo);
812 $dblist->thumbs = $this->getBackendUser()->uc['thumbnailsByDefault'];
813 $dblist->returnUrl = $this->taskObject->returnUrl;
814 $dblist->allFields = 1;
815 $dblist->localizationView = 1;
816 $dblist->showClipboard = 0;
817 $dblist->disableSingleTableView = 1;
818 $dblist->pageRow = $this->pageinfo;
819 $dblist->counter++;
820 $dblist->MOD_MENU = array('bigControlPanel' => '', 'clipBoard' => '', 'localization' => '');
821 $dblist->modTSconfig = $this->taskObject->modTSconfig;
822 $dblist->dontShowClipControlPanels = (!$this->taskObject->MOD_SETTINGS['bigControlPanel'] && $dblist->clipObj->current == 'normal' && !$this->modTSconfig['properties']['showClipControlPanelsDespiteOfCMlayers']);
823 // Initialize the listing object, dblist, for rendering the list:
824 $this->pointer = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange(GeneralUtility::_GP('pointer'), 0, 100000);
825 $dblist->start($this->id, $this->table, $this->pointer, $this->taskObject->search_field, $this->taskObject->search_levels, $this->taskObject->showLimit);
826 $dblist->setDispFields();
827 // Render the list of tables:
828 $dblist->generateList();
829 // Add JavaScript functions to the page:
830 $this->taskObject->getModuleTemplate()->addJavaScriptCode(
831 'ActionTaskInlineJavascript',
832 '
833
834 function jumpExt(URL,anchor) {
835 var anc = anchor?anchor:"";
836 window.location.href = URL+(T3_THIS_LOCATION?"&returnUrl="+T3_THIS_LOCATION:"")+anc;
837 return false;
838 }
839 function jumpSelf(URL) {
840 window.location.href = URL+(T3_RETURN_URL?"&returnUrl="+T3_RETURN_URL:"");
841 return false;
842 }
843
844 function setHighlight(id) {
845 top.fsMod.recentIds["web"]=id;
846 top.fsMod.navFrameHighlightedID["web"]="pages"+id+"_"+top.fsMod.currentBank; // For highlighting
847
848 if (top.content && top.content.nav_frame && top.content.nav_frame.refresh_nav) {
849 top.content.nav_frame.refresh_nav();
850 }
851 }
852
853 ' . $dblist->CBfunctions() . '
854 function editRecords(table,idList,addParams,CBflag) {
855 window.location.href="' . BackendUtility::getModuleUrl('record_edit', array('returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'))) . '&edit["+table+"]["+idList+"]=edit"+addParams;
856 }
857 function editList(table,idList) {
858 var list="";
859
860 // Checking how many is checked, how many is not
861 var pointer=0;
862 var pos = idList.indexOf(",");
863 while (pos!=-1) {
864 if (cbValue(table+"|"+idList.substr(pointer,pos-pointer))) {
865 list+=idList.substr(pointer,pos-pointer)+",";
866 }
867 pointer=pos+1;
868 pos = idList.indexOf(",",pointer);
869 }
870 if (cbValue(table+"|"+idList.substr(pointer))) {
871 list+=idList.substr(pointer)+",";
872 }
873
874 return list ? list : idList;
875 }
876 T3_THIS_LOCATION = ' . GeneralUtility::quoteJSvalue(rawurlencode(GeneralUtility::getIndpEnv('REQUEST_URI'))) . ';
877
878 if (top.fsMod) top.fsMod.recentIds["web"] = ' . (int)$this->id . ';
879 '
880 );
881 // Setting up the context sensitive menu:
882 $this->taskObject->getModuleTemplate()->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ClickMenu');
883 // Begin to compile the whole page
884 $content .= '<form action="' . htmlspecialchars($dblist->listURL()) . '" method="post" name="dblistForm">' . $dblist->HTMLcode . '<input type="hidden" name="cmd_table" /><input type="hidden" name="cmd" />
885 </form>';
886 // If a listing was produced, create the page footer with search form etc:
887 // Making field select box (when extended view for a single table is enabled):
888 if ($dblist->HTMLcode && $dblist->table) {
889 $content .= $dblist->fieldSelectBox($dblist->table);
890 }
891 } else {
892 // Not enough rights to access the list view or the page
893 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $this->getLanguageService()->getLL('action_error-access', true), $this->getLanguageService()->getLL('action_error'), \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR);
894 $content .= $flashMessage->render();
895 }
896 return $content;
897 }
898
899 /**
900 * Returns LanguageService
901 *
902 * @return \TYPO3\CMS\Lang\LanguageService
903 */
904 protected function getLanguageService()
905 {
906 return $GLOBALS['LANG'];
907 }
908
909 /**
910 * Returns the current BE user.
911 *
912 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
913 */
914 protected function getBackendUser()
915 {
916 return $GLOBALS['BE_USER'];
917 }
918
919 /**
920 * Returns the database connection
921 *
922 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
923 */
924 protected function getDatabaseConnection()
925 {
926 return $GLOBALS['TYPO3_DB'];
927 }
928 }