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