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