[TASK] Add more fixers for php-cs-fixer
[Packages/TYPO3.CMS.git] / typo3 / sysext / sys_action / Classes / ActionTask.php
index f275e93..fa51437 100644 (file)
@@ -14,13 +14,19 @@ namespace TYPO3\CMS\SysAction;
  * The TYPO3 project - inspiring people to share!
  */
 
+use Doctrine\DBAL\DBALException;
 use TYPO3\CMS\Backend\Utility\BackendUtility;
+use TYPO3\CMS\Core\Database\ConnectionPool;
+use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
+use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
+use TYPO3\CMS\Core\Database\Query\Restriction\RootLevelRestriction;
 use TYPO3\CMS\Core\Imaging\Icon;
 use TYPO3\CMS\Core\Imaging\IconFactory;
 use TYPO3\CMS\Core\Messaging\FlashMessage;
 use TYPO3\CMS\Core\Messaging\FlashMessageService;
 use TYPO3\CMS\Core\Page\PageRenderer;
 use TYPO3\CMS\Core\Utility\GeneralUtility;
+use TYPO3\CMS\Core\Utility\HttpUtility;
 
 /**
  * This class provides a task for the taskcenter
@@ -37,7 +43,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
      *
      * @var array
      */
-    protected $hookObjects = array();
+    protected $hookObjects = [];
 
     /**
      * URL to task module
@@ -159,42 +165,90 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
      */
     protected function getActions()
     {
-        $actionList = array();
-        // admins can see any record
-        if ($this->getBackendUser()->isAdmin()) {
-            $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'sys_action', '', '', 'sys_action.sorting');
-        } else {
-            // Editors can only see the actions which are assigned to a usergroup they belong to
-            $additionalWhere = 'be_groups.uid IN (' . ($this->getBackendUser()->groupList ?: 0) . ')';
-            $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');
+        $backendUser = $this->getBackendUser();
+        $actionList = [];
+
+        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_action');
+        $queryBuilder->select('sys_action.*')
+            ->from('sys_action');
+
+        if (!empty($GLOBALS['TCA']['sys_action']['ctrl']['sortby'])) {
+            $queryBuilder->orderBy('sys_action.' . $GLOBALS['TCA']['sys_action']['ctrl']['sortby']);
         }
-        while ($actionRow = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
+
+        $queryBuilder->getRestrictions()
+            ->removeAll()
+            ->add(GeneralUtility::makeInstance(RootLevelRestriction::class, ['sys_action']));
+
+        // Editors can only see the actions which are assigned to a usergroup they belong to
+        if (!$backendUser->isAdmin()) {
+            $groupList = $backendUser->groupList ?: '0';
+
+            $queryBuilder->getRestrictions()
+                ->add(GeneralUtility::makeInstance(HiddenRestriction::class));
+
+            $queryBuilder
+                ->join(
+                    'sys_action',
+                    'sys_action_asgr_mm',
+                    'sys_action_asgr_mm',
+                    $queryBuilder->expr()->eq(
+                        'sys_action_asgr_mm.uid_local',
+                        $queryBuilder->quoteIdentifier('sys_action.uid')
+                    )
+                )
+                ->join(
+                    'sys_action_asgr_mm',
+                    'be_groups',
+                    'be_groups',
+                    $queryBuilder->expr()->eq(
+                        'sys_action_asgr_mm.uid_foreign',
+                        $queryBuilder->quoteIdentifier('be_groups.uid')
+                    )
+                )
+                ->where($queryBuilder->expr()->in('be_groups.uid', GeneralUtility::intExplode(',', $groupList, true)))
+                ->groupBy('sys_action.uid');
+        }
+
+        $queryResult = $queryBuilder->execute();
+        while ($actionRow = $queryResult->fetch()) {
             $editActionLink = '';
+
             // Admins are allowed to edit sys_action records
             if ($this->getBackendUser()->isAdmin()) {
+                $uidEditArgument = 'edit[sys_action][' . (int)$actionRow['uid'] . ']';
+
                 $link = BackendUtility::getModuleUrl(
                     'record_edit',
-                    array(
-                        'edit[sys_action][' . $actionRow['uid'] . ']' => 'edit',
+                    [
+                        $uidEditArgument => 'edit',
                         'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')
-                    ),
-                    false,
-                    true
+                    ]
                 );
+
                 $title = 'title="' . $this->getLanguageService()->getLL('edit-sys_action') . '"';
                 $icon = $this->iconFactory->getIcon('actions-document-open', Icon::SIZE_SMALL)->render();
                 $editActionLink = '<a class="btn btn-default btn-sm" href="' . $link . '"' . $title . '>';
                 $editActionLink .= $icon . ' ' . $this->getLanguageService()->getLL('edit-sys_action') . '</a>';
             }
-            $actionList[] = array(
+
+            $actionList[] = [
                 'uid' => 'actiontask' . $actionRow['uid'],
                 'title' => $actionRow['title'],
                 'description' => $actionRow['description'],
-                'descriptionHtml' => ($actionRow['description'] ? '<p>' . nl2br(htmlspecialchars($actionRow['description'])) . '</p>' : '') . $editActionLink,
-                'link' => $this->moduleUrl . '&SET[function]=sys_action.TYPO3\\CMS\\SysAction\\ActionTask&show=' . $actionRow['uid']
-            );
+                'descriptionHtml' => (
+                    $actionRow['description']
+                        ? '<p>' . nl2br(htmlspecialchars($actionRow['description'])) . '</p>'
+                        : ''
+                    ) . $editActionLink,
+                'link' => $this->moduleUrl
+                    . '&SET[function]=sys_action.'
+                    . self::class
+                    . '&show='
+                    . (int)$actionRow['uid']
+            ];
         }
-        $this->getDatabaseConnection()->sql_free_result($res);
+
         return $actionList;
     }
 
@@ -222,13 +276,12 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
         if ($this->getBackendUser()->isAdmin()) {
             $link = BackendUtility::getModuleUrl(
                 'record_edit',
-                array(
+                [
                     'edit[sys_action][0]' => 'new',
                     'returnUrl' => $this->moduleUrl
-                ),
-                false,
-                true
+                ]
             );
+
             $content .= '<p>' .
                 '<a class="btn btn-default" href="' . $link . '" title="' . $this->getLanguageService()->getLL('new-sys_action') . '">' .
                 $this->iconFactory->getIcon('actions-document-new', Icon::SIZE_SMALL)->render() . ' ' .
@@ -261,7 +314,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
         $vars = GeneralUtility::_POST('data');
         $key = 'NEW';
         if ($vars['sent'] == 1) {
-            $errors = array();
+            $errors = [];
             // Basic error checks
             if (!empty($vars['email']) && !GeneralUtility::validEmail($vars['email'])) {
                 $errors[] = $this->getLanguageService()->getLL('error-wrong-email');
@@ -367,13 +420,14 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
      */
     protected function deleteUser($userId, $actionId)
     {
-        $this->getDatabaseConnection()->exec_UPDATEquery('be_users', 'uid=' . $userId, array(
-            'deleted' => 1,
-            'tstamp' => $GLOBALS['ACCESS_TIME']
-        ));
+        GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('be_users')->update(
+            'be_users',
+            ['deleted' => 1, 'tstamp' => (int)$GLOBALS['ACCESS_TIME']],
+            ['uid' => (int)$userId]
+        );
+
         // redirect to the original task
-        $redirectUrl = $this->moduleUrl . '&show=' . $actionId;
-        \TYPO3\CMS\Core\Utility\HttpUtility::redirect($redirectUrl);
+        HttpUtility::redirect($this->moduleUrl . '&show=' . (int)$actionId);
     }
 
     /**
@@ -403,11 +457,27 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
     protected function getCreatedUsers($action, $selectedUser)
     {
         $content = '';
-        $userList = array();
-        // List of users
-        $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'be_users', 'cruser_id=' . $this->getBackendUser()->user['uid'] . ' AND createdByAction=' . (int)$action['uid'] . BackendUtility::deleteClause('be_users'), '', 'username');
+        $userList = [];
+
+        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
+            ->getQueryBuilderForTable('be_users');
+
+        $queryBuilder->getRestrictions()
+            ->removeAll()
+            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
+
+        $res = $queryBuilder
+            ->select('*')
+            ->from('be_users')
+            ->where(
+                $queryBuilder->expr()->eq('cruser_id', (int)$this->getBackendUser()->user['uid']),
+                $queryBuilder->expr()->eq('createdByAction', (int)$action['uid'])
+            )
+            ->orderBy('username')
+            ->execute();
+
         // Render the user records
-        while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
+        while ($row = $res->fetch()) {
             $icon = '<span title="' . htmlspecialchars('uid=' . $row['uid']) . '">' . $this->iconFactory->getIconForRecord('be_users', $row, Icon::SIZE_SMALL)->render() . '</span>';
             $line = $icon . $this->action_linkUserName($row['username'], $row['realName'], $action['uid'], $row['uid']);
             // Selected user
@@ -416,7 +486,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
             }
             $userList[] = '<li class="list-group-item">' . $line . '</li>';
         }
-        $this->getDatabaseConnection()->sql_free_result($res);
+
         // If any records found
         if (!empty($userList)) {
             $content .= '<div class="panel panel-default">';
@@ -478,7 +548,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
         if ($key === 'NEW') {
             $beRec = BackendUtility::getRecord('be_users', (int)$record['t1_copy_of_user']);
             if (is_array($beRec)) {
-                $data = array();
+                $data = [];
                 $data['be_users'][$key] = $beRec;
                 $data['be_users'][$key]['username'] = $this->fixUsername($vars['username'], $record['t1_userprefix']);
                 $data['be_users'][$key]['password'] = $vars['password'];
@@ -494,7 +564,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
             // Check ownership
             $beRec = BackendUtility::getRecord('be_users', (int)$key);
             if (is_array($beRec) && $beRec['cruser_id'] == $this->getBackendUser()->user['uid']) {
-                $data = array();
+                $data = [];
                 $data['be_users'][$key]['username'] = $this->fixUsername($vars['username'], $record['t1_userprefix']);
                 if ($vars['password'] !== '') {
                     $data['be_users'][$key]['password'] = $vars['password'];
@@ -511,7 +581,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
         // Save/update user by using TCEmain
         if (is_array($data)) {
             $tce = GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
-            $tce->start($data, array(), $this->getBackendUser());
+            $tce->start($data, [], $this->getBackendUser());
             $tce->admin = 1;
             $tce->process_datamap();
             $newUserId = (int)$tce->substNEWwithIDs['NEW'];
@@ -553,7 +623,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
     protected function fixUserGroup($appliedUsergroups, $actionRecord)
     {
         if (is_array($appliedUsergroups)) {
-            $cleanGroupList = array();
+            $cleanGroupList = [];
             // Create an array from the allowed usergroups using the uid as key
             $allowedUsergroups = array_flip(explode(',', $actionRecord['t1_allowed_groups']));
             // Walk through the array and check every uid if it is under the allowed ines
@@ -577,7 +647,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
     {
         // Admins can see any page, no need to check there
         if (!empty($appliedDbMounts) && !$this->getBackendUser()->isAdmin()) {
-            $cleanDbMountList = array();
+            $cleanDbMountList = [];
             $dbMounts = GeneralUtility::trimExplode(',', $appliedDbMounts, true);
             // Walk through every wanted DB-Mount and check if it allowed for the current user
             foreach ($dbMounts as $dbMount) {
@@ -678,14 +748,12 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
     {
         $link = BackendUtility::getModuleUrl(
             'record_edit',
-            array(
+            [
                 'edit[' . $record['t3_tables'] . '][' . (int)$record['t3_listPid'] . ']' => 'new',
                 'returnUrl' => $this->moduleUrl
-            ),
-            false,
-            true
+            ]
         );
-        \TYPO3\CMS\Core\Utility\HttpUtility::redirect($link);
+        HttpUtility::redirect($link);
     }
 
     /**
@@ -697,7 +765,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
     protected function viewEditRecord($record)
     {
         $content = '';
-        $actionList = array();
+        $actionList = [];
         $dbAnalysis = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
         $dbAnalysis->setFetchAllFields(true);
         $dbAnalysis->start($record['t4_recordsToEdit'], '*');
@@ -707,28 +775,26 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
             $path = BackendUtility::getRecordPath($el['id'], $this->taskObject->perms_clause, $this->getBackendUser()->uc['titleLen']);
             $record = BackendUtility::getRecord($el['table'], $dbAnalysis->results[$el['table']][$el['id']]);
             $title = BackendUtility::getRecordTitle($el['table'], $dbAnalysis->results[$el['table']][$el['id']]);
-            $description = $this->getLanguageService()->sL($GLOBALS['TCA'][$el['table']]['ctrl']['title'], true);
+            $description = htmlspecialchars($this->getLanguageService()->sL($GLOBALS['TCA'][$el['table']]['ctrl']['title']));
             // @todo: which information could be needful
             if (isset($record['crdate'])) {
                 $description .= ' - ' . BackendUtility::dateTimeAge($record['crdate']);
             }
             $link = BackendUtility::getModuleUrl(
                 'record_edit',
-                array(
+                [
                     'edit[' . $el['table'] . '][' . $el['id'] . ']' => 'edit',
                     'returnUrl' => $this->moduleUrl
-                ),
-                false,
-                true
+                ]
             );
-            $actionList[$el['id']] = array(
+            $actionList[$el['id']] = [
                 'uid' => 'record-' . $el['table'] . '-' . $el['id'],
                 'title' => $title,
                 'description' => BackendUtility::getRecordTitle($el['table'], $dbAnalysis->results[$el['table']][$el['id']]),
                 'descriptionHtml' => $description,
                 'link' => $link,
                 'icon' => '<span title="' . htmlspecialchars($path) . '">' . $this->iconFactory->getIconForRecord($el['table'], $dbAnalysis->results[$el['table']][$el['id']], Icon::SIZE_SMALL)->render() . '</span>'
-            );
+            ];
         }
         // Render the record list
         $content .= $this->taskObject->renderListMenu($actionList);
@@ -758,20 +824,22 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
                 $sqlQuery = $sql_query['qSelect'];
                 $queryIsEmpty = false;
                 if ($sqlQuery) {
-                    $res = $this->getDatabaseConnection()->sql_query($sqlQuery);
-                    if (!$this->getDatabaseConnection()->sql_error()) {
+                    try {
+                        $dataRows = GeneralUtility::makeInstance(ConnectionPool::class)
+                            ->getConnectionForTable($sql_query['qC']['queryTable'])
+                            ->executeQuery($sqlQuery)->fetchAll();
                         $fullsearch->formW = 48;
                         // Additional configuration
                         $GLOBALS['SOBE']->MOD_SETTINGS['search_result_labels'] = 1;
                         $GLOBALS['SOBE']->MOD_SETTINGS['queryFields'] = $sql_query['qC']['queryFields'];
-                        $cP = $fullsearch->getQueryResultCode($type, $res, $sql_query['qC']['queryTable']);
+                        $cP = $fullsearch->getQueryResultCode($type, $dataRows, $sql_query['qC']['queryTable']);
                         $actionContent = $cP['content'];
                         // If the result is rendered as csv or xml, show a download link
                         if ($type === 'csv' || $type === 'xml') {
                             $actionContent .= '<a href="' . GeneralUtility::getIndpEnv('REQUEST_URI') . '&download_file=1"><strong>' . $this->getLanguageService()->getLL('action_download_file') . '</strong></a>';
                         }
-                    } else {
-                        $actionContent .= $this->getDatabaseConnection()->sql_error();
+                    } catch (DBALException $e) {
+                        $actionContent .= $e->getMessage();
                     }
                 } else {
                     // Query is empty (not built)
@@ -786,7 +854,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
                 // Admin users are allowed to see and edit the query
                 if ($this->getBackendUser()->isAdmin()) {
                     if (!$queryIsEmpty) {
-                        $actionContent .= '<div class="panel panel-default"><div class="panel-body">' . $fullsearch->tableWrap($sql_query['qSelect']) . '</div></div>';
+                        $actionContent .= '<div class="panel panel-default"><div class="panel-body"><pre>' . $sql_query['qSelect'] . '</pre></div></div>';
                     }
                     $actionContent .= '<a title="' . $this->getLanguageService()->getLL('action_editQuery') . '" class="btn btn-default" href="'
                         . htmlspecialchars(BackendUtility::getModuleUrl('system_dbint')
@@ -856,7 +924,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
             $dblist->disableSingleTableView = 1;
             $dblist->pageRow = $this->pageinfo;
             $dblist->counter++;
-            $dblist->MOD_MENU = array('bigControlPanel' => '', 'clipBoard' => '', 'localization' => '');
+            $dblist->MOD_MENU = ['bigControlPanel' => '', 'clipBoard' => '', 'localization' => ''];
             $dblist->modTSconfig = $this->taskObject->modTSconfig;
             $dblist->dontShowClipControlPanels = (!$this->taskObject->MOD_SETTINGS['bigControlPanel'] && $dblist->clipObj->current == 'normal' && !$this->modTSconfig['properties']['showClipControlPanelsDespiteOfCMlayers']);
             // Initialize the listing object, dblist, for rendering the list:
@@ -891,7 +959,7 @@ class ActionTask implements \TYPO3\CMS\Taskcenter\TaskInterface
 
                                ' . $dblist->CBfunctions() . '
                                function editRecords(table,idList,addParams,CBflag) {
-                                       window.location.href="' . BackendUtility::getModuleUrl('record_edit', array('returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'))) . '&edit["+table+"]["+idList+"]=edit"+addParams;
+                                       window.location.href="' . BackendUtility::getModuleUrl('record_edit', ['returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')]) . '&edit["+table+"]["+idList+"]=edit"+addParams;
                                }
                                function editList(table,idList) {
                                        var list="";