SuggestWizardDefaultReceiver.php 15.7 KB
Newer Older
1
<?php
2
namespace TYPO3\CMS\Backend\Form\Wizard;
3

4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
8
9
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
10
 *
11
12
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
15
 * The TYPO3 project - inspiring people to share!
 */
Nicole Cordes's avatar
Nicole Cordes committed
16
17

use TYPO3\CMS\Backend\Utility\BackendUtility;
18
use TYPO3\CMS\Core\Database\Connection;
19
20
21
22
23
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Database\Query\QueryHelper;
use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
24
25
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
26
use TYPO3\CMS\Core\Localization\LanguageService;
27
use TYPO3\CMS\Core\Type\Bitmask\Permission;
Nicole Cordes's avatar
Nicole Cordes committed
28
29
use TYPO3\CMS\Core\Utility\GeneralUtility;

30
31
32
33
34
35
/**
 * Default implementation of a handler class for an ajax record selector.
 *
 * Normally other implementations should be inherited from this one.
 * queryTable() should not be overwritten under normal circumstances.
 */
36
37
38
39
40
41
42
43
class SuggestWizardDefaultReceiver
{
    /**
     * The name of the table to query
     *
     * @var string
     */
    protected $table = '';
44

45
46
47
48
49
50
51
    /**
     * The name of the foreign table to query (records from this table will be used for displaying instead of the ones
     * from $table)
     *
     * @var string
     */
    protected $mmForeignTable = '';
52

53
54
55
56
57
    /**
     * Configuration for this selector from TSconfig
     *
     * @var array
     */
58
    protected $config = [];
59

60
61
62
63
64
    /**
     * The list of pages that are allowed to perform the search for records on
     *
     * @var array Array of PIDs
     */
65
    protected $allowedPages = [];
66

67
68
69
70
71
72
    /**
     * The maximum number of items to select.
     *
     * @var int
     */
    protected $maxItems = 10;
73

74
75
76
    /**
     * @var array
     */
77
    protected $params = [];
78

79
80
81
82
83
    /**
     * @var IconFactory
     */
    protected $iconFactory;

84
85
86
87
88
    /**
     * @var QueryBuilder
     */
    protected $queryBuilder;

89
90
91
92
    /**
     * The constructor of this class
     *
     * @param string $table The table to query
93
     * @param array $config The configuration (TCA overlaid with TSconfig) to use for this selector
94
95
96
     */
    public function __construct($table, $config)
    {
97
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
98
99
100
101
102
103
104
        $this->queryBuilder = $this->getQueryBuilderForTable($table);
        $this->queryBuilder->getRestrictions()
            ->removeAll()
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
            // if table is versionized, only get the records from the Live Workspace
            // the overlay itself of WS-records is done below
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class, 0));
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
        $this->table = $table;
        $this->config = $config;
        // get a list of all the pages that should be looked on
        if (isset($config['pidList'])) {
            $allowedPages = ($pageIds = GeneralUtility::trimExplode(',', $config['pidList']));
            $depth = (int)$config['pidDepth'];
            foreach ($pageIds as $pageId) {
                if ($pageId > 0) {
                    \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($allowedPages, $this->getAllSubpagesOfPage($pageId, $depth));
                }
            }
            $this->allowedPages = array_unique($allowedPages);
        }
        if (isset($config['maxItemsInResultList'])) {
            $this->maxItems = $config['maxItemsInResultList'];
        }
121
        if ($this->table === 'pages') {
122
            $this->queryBuilder->andWhere(
123
                QueryHelper::stripLogicalOperatorPrefix($GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW))
124
            );
125
126
        }
        if (isset($config['addWhere'])) {
127
128
129
            $this->queryBuilder->andWhere(
                QueryHelper::stripLogicalOperatorPrefix($config['addWhere'])
            );
130
131
        }
    }
132

133
134
135
136
137
138
139
140
141
142
143
144
145
146
    /**
     * Queries a table for records and completely processes them
     *
     * Returns a two-dimensional array of almost finished records; the only need to be put into a <li>-structure
     *
     * If you subclass this class, you will most likely only want to overwrite the functions called from here, but not
     * this function itself
     *
     * @param array $params
     * @param int $recursionCounter The parent object
     * @return array Array of rows or FALSE if nothing found
     */
    public function queryTable(&$params, $recursionCounter = 0)
    {
147
        $rows = [];
148
149
150
151
        $this->params = &$params;
        $start = $recursionCounter * 50;
        $this->prepareSelectStatement();
        $this->prepareOrderByStatement();
152
153
154
155
156
157
        $result = $this->queryBuilder->select('*')
            ->from($this->table)
            ->setFirstResult($start)
            ->setMaxResults(50)
            ->execute();
        $allRowsCount = $result->rowCount();
158
        if ($allRowsCount) {
159
            while ($row = $result->fetch()) {
160
161
162
163
164
165
166
167
168
169
                // check if we already have collected the maximum number of records
                if (count($rows) > $this->maxItems) {
                    break;
                }
                $this->manipulateRecord($row);
                $this->makeWorkspaceOverlay($row);
                // check if the user has access to the record
                if (!$this->checkRecordAccess($row, $row['uid'])) {
                    continue;
                }
170
                $spriteIcon = $this->iconFactory->getIconForRecord($this->table, $row, Icon::SIZE_SMALL)->render();
171
172
                $uid = $row['t3ver_oid'] > 0 ? $row['t3ver_oid'] : $row['uid'];
                $path = $this->getRecordPath($row, $uid);
173
                if (mb_strlen($path, 'utf-8') > 30) {
174
175
                    $croppedPath = '<abbr title="' . htmlspecialchars($path) . '">' .
                        htmlspecialchars(
176
                            mb_substr($path, 0, 10, 'utf-8')
177
                                . '...'
178
                                . mb_substr($path, -20, null, 'utf-8')
179
180
181
182
183
184
                        ) .
                        '</abbr>';
                } else {
                    $croppedPath = htmlspecialchars($path);
                }
                $label = $this->getLabel($row);
185
                $entry = [
186
                    'text' => '<span class="suggest-label">' . $label . '</span><span class="suggest-uid">[' . $uid . ']</span><br />
187
								<span class="suggest-path">' . $croppedPath . '</span>',
188
189
190
191
192
193
194
                    'table' => $this->mmForeignTable ? $this->mmForeignTable : $this->table,
                    'label' => $label,
                    'path' => $path,
                    'uid' => $uid,
                    'style' => '',
                    'class' => isset($this->config['cssClass']) ? $this->config['cssClass'] : '',
                    'sprite' => $spriteIcon
195
                ];
196
197
                $rows[$this->table . '_' . $uid] = $this->renderRecord($row, $entry);
            }
198

199
200
201
202
203
204
205
206
            // if there are less records than we need, call this function again to get more records
            if (count($rows) < $this->maxItems && $allRowsCount >= 50 && $recursionCounter < $this->maxItems) {
                $tmp = self::queryTable($params, ++$recursionCounter);
                $rows = array_merge($tmp, $rows);
            }
        }
        return $rows;
    }
207

208
209
210
211
212
213
    /**
     * Prepare the statement for selecting the records which will be returned to the selector. May also return some
     * other records (e.g. from a mm-table) which will be used later on to select the real records
     */
    protected function prepareSelectStatement()
    {
214
        $expressionBuilder = $this->queryBuilder->expr();
215
216
217
218
        $searchWholePhrase = !isset($this->config['searchWholePhrase']) || $this->config['searchWholePhrase'];
        $searchString = $this->params['value'];
        $searchUid = (int)$searchString;
        if ($searchString !== '') {
219
            $likeCondition = ($searchWholePhrase ? '%' : '') . $searchString . '%';
220
221
222
223
            // Search in all fields given by label or label_alt
            $selectFieldsList = $GLOBALS['TCA'][$this->table]['ctrl']['label'] . ',' . $GLOBALS['TCA'][$this->table]['ctrl']['label_alt'] . ',' . $this->config['additionalSearchFields'];
            $selectFields = GeneralUtility::trimExplode(',', $selectFieldsList, true);
            $selectFields = array_unique($selectFields);
224
            $selectParts = $expressionBuilder->orX();
225
            foreach ($selectFields as $field) {
226
                $selectParts->add($expressionBuilder->like($field, $this->queryBuilder->createPositionalParameter($likeCondition)));
227
            }
228
229

            $searchClause = $expressionBuilder->orX($selectParts);
230
            if ($searchUid > 0 && $searchUid == $searchString) {
231
                $searchClause->add($expressionBuilder->eq('uid', $searchUid));
232
            }
233
234

            $this->queryBuilder->andWhere($expressionBuilder->orX($searchClause));
235
236
        }
        if (!empty($this->allowedPages)) {
237
            $pidList = array_map('intval', $this->allowedPages);
238
            if (!empty($pidList)) {
239
240
241
                $this->queryBuilder->andWhere(
                    $expressionBuilder->in('pid', $pidList)
                );
242
243
244
245
            }
        }
        // add an additional search condition comment
        if (isset($this->config['searchCondition']) && $this->config['searchCondition'] !== '') {
246
            $this->queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($this->config['searchCondition']));
247
248
        }
    }
249

250
251
252
253
254
255
256
257
258
    /**
     * Selects all subpages of one page, optionally only up to a certain level
     *
     * @param int $uid The uid of the page
     * @param int $depth The depth to select up to. Defaults to 99
     * @return array of page IDs
     */
    protected function getAllSubpagesOfPage($uid, $depth = 99)
    {
259
        $pageIds = [$uid];
260
        $level = 0;
261
        $pages = [$uid];
262
263
264
        $queryBuilder = $this->getQueryBuilderForTable('pages');
        $queryBuilder->select('uid')
            ->from('pages');
265
266
267
        // fetch all
        while ($depth - $level > 0 && !empty($pageIds)) {
            ++$level;
268
269
270
271
272
273
274
            $rows = $queryBuilder
                ->where(
                    $queryBuilder->expr()->in(
                        'pid',
                        $queryBuilder->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
                    )
                )
275
276
277
278
279
                ->execute()
                ->fetchAll();

            $rows = array_column(($rows ?: []), 'uid', 'uid');
            if (!count($rows)) {
280
281
282
283
284
285
286
287
                $pageIds = array_keys($rows);
                $pages = array_merge($pages, $pageIds);
            } else {
                break;
            }
        }
        return $pages;
    }
288

289
290
291
292
293
294
    /**
     * Prepares the clause by which the result elements are sorted. See description of ORDER BY in
     * SQL standard for reference.
     */
    protected function prepareOrderByStatement()
    {
295
296
297
298
299
300
301
        if (empty($this->config['orderBy'])) {
            $this->queryBuilder->addOrderBy($GLOBALS['TCA'][$this->table]['ctrl']['label']);
        } else {
            foreach (QueryHelper::parseOrderBy($this->config['orderBy']) as $orderPair) {
                list($fieldName, $order) = $orderPair;
                $this->queryBuilder->addOrderBy($fieldName, $order);
            }
302
303
        }
    }
304

305
306
307
308
309
310
311
312
    /**
     * Manipulate a record before using it to render the selector; may be used to replace a MM-relation etc.
     *
     * @param array $row
     */
    protected function manipulateRecord(&$row)
    {
    }
313

314
315
316
317
318
319
320
321
322
323
324
    /**
     * Selects whether the logged in Backend User is allowed to read a specific record
     *
     * @param array $row
     * @param int $uid
     * @return bool
     */
    protected function checkRecordAccess($row, $uid)
    {
        $retValue = true;
        $table = $this->mmForeignTable ?: $this->table;
325
        if ($table === 'pages') {
326
            if (!BackendUtility::readPageAccess($uid, $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW))) {
327
328
329
330
331
                $retValue = false;
            }
        } elseif (isset($GLOBALS['TCA'][$table]['ctrl']['is_static']) && (bool)$GLOBALS['TCA'][$table]['ctrl']['is_static']) {
            $retValue = true;
        } else {
332
            if (!is_array(BackendUtility::readPageAccess($row['pid'], $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW)))) {
333
334
335
336
337
                $retValue = false;
            }
        }
        return $retValue;
    }
338

339
340
341
    /**
     * Overlay the given record with its workspace-version, if any
     *
342
     * @param array $row The record to get the workspace version for
343
344
345
346
347
348
349
350
     */
    protected function makeWorkspaceOverlay(&$row)
    {
        // Check for workspace-versions
        if ($GLOBALS['BE_USER']->workspace != 0 && $GLOBALS['TCA'][$this->table]['ctrl']['versioningWS'] == true) {
            BackendUtility::workspaceOL($this->mmForeignTable ? $this->mmForeignTable : $this->table, $row);
        }
    }
351

352
353
354
355
356
357
358
359
360
361
362
363
364
    /**
     * Returns the path for a record. Is the whole path for all records except pages - for these the last part is cut
     * off, because it contains the pagetitle itself, which would be double information
     *
     * The path is returned uncut, cutting has to be done by calling function.
     *
     * @param array $row The row
     * @param array $record The record
     * @return string The record-path
     */
    protected function getRecordPath(&$row, $uid)
    {
        $titleLimit = max($this->config['maxPathTitleLength'], 0);
365
        if (($this->mmForeignTable ? $this->mmForeignTable : $this->table) === 'pages') {
366
367
368
369
370
371
372
373
374
            $path = BackendUtility::getRecordPath($uid, '', $titleLimit);
            // For pages we only want the first (n-1) parts of the path,
            // because the n-th part is the page itself
            $path = substr($path, 0, strrpos($path, '/', -2)) . '/';
        } else {
            $path = BackendUtility::getRecordPath($row['pid'], '', $titleLimit);
        }
        return $path;
    }
375

376
377
378
379
380
381
382
383
384
385
    /**
     * Returns a label for a given record; usually only a wrapper for \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordTitle
     *
     * @param array $row The record to get the label for
     * @return string The label
     */
    protected function getLabel($row)
    {
        return BackendUtility::getRecordTitle($this->mmForeignTable ? $this->mmForeignTable : $this->table, $row, true);
    }
386

387
388
389
390
391
392
393
394
395
396
397
398
399
    /**
     * Calls a user function for rendering the page.
     *
     * This user function should manipulate $entry, especially $entry['text'].
     *
     * @param array $row The row
     * @param array $entry The entry to render
     * @return array The rendered entry (will be put into a <li> later on
     */
    protected function renderRecord($row, $entry)
    {
        // Call renderlet if available (normal pages etc. usually don't have one)
        if ($this->config['renderFunc'] != '') {
400
            $params = [
401
402
403
404
                'table' => $this->table,
                'uid' => $row['uid'],
                'row' => $row,
                'entry' => &$entry
405
            ];
406
            GeneralUtility::callUserFunction($this->config['renderFunc'], $params, $this);
407
408
409
        }
        return $entry;
    }
410

411
412
413
414
415
416
417
    /**
     * @return LanguageService
     */
    protected function getLanguageService()
    {
        return $GLOBALS['LANG'];
    }
418
419
420
421
422
423
424
425
426

    /**
     * @param string $table
     * @return QueryBuilder
     */
    protected function getQueryBuilderForTable($table)
    {
        return GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
    }
427
}