[TASK] Clean up TSFE constructor initialization
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Clipboard / Clipboard.php
1 <?php
2 namespace TYPO3\CMS\Backend\Clipboard;
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\Routing\UriBuilder;
18 use TYPO3\CMS\Backend\Utility\BackendUtility;
19 use TYPO3\CMS\Core\Database\ConnectionPool;
20 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
21 use TYPO3\CMS\Core\Imaging\Icon;
22 use TYPO3\CMS\Core\Imaging\IconFactory;
23 use TYPO3\CMS\Core\Resource\ResourceFactory;
24 use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
25 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
26 use TYPO3\CMS\Core\Utility\GeneralUtility;
27 use TYPO3\CMS\Core\Utility\MathUtility;
28 use TYPO3\CMS\Core\Utility\PathUtility;
29 use TYPO3\CMS\Fluid\View\StandaloneView;
30
31 /**
32 * TYPO3 clipboard for records and files
33 *
34 * @internal This class is a specific Backend implementation and is not considered part of the Public TYPO3 API.
35 */
36 class Clipboard
37 {
38 /**
39 * @var int
40 */
41 public $numberTabs = 3;
42
43 /**
44 * Clipboard data kept here
45 *
46 * Keys:
47 * 'normal'
48 * 'tab_[x]' where x is >=1 and denotes the pad-number
49 * 'mode' : 'copy' means copy-mode, default = moving ('cut')
50 * 'el' : Array of elements:
51 * DB: keys = '[tablename]|[uid]' eg. 'tt_content:123'
52 * DB: values = 1 (basically insignificant)
53 * FILE: keys = '_FILE|[shortmd5 of path]' eg. '_FILE|9ebc7e5c74'
54 * FILE: values = The full filepath, eg. '/www/htdocs/typo3/32/dummy/fileadmin/sem1_3_examples/alternative_index.php'
55 * or 'C:/www/htdocs/typo3/32/dummy/fileadmin/sem1_3_examples/alternative_index.php'
56 *
57 * 'current' pointer to current tab (among the above...)
58 *
59 * The virtual tablename '_FILE' will always indicate files/folders. When checking for elements from eg. 'all tables'
60 * (by using an empty string) '_FILE' entries are excluded (so in effect only DB elements are counted)
61 *
62 * @var array
63 */
64 public $clipData = [];
65
66 /**
67 * @var int
68 */
69 public $changed = 0;
70
71 /**
72 * @var string
73 */
74 public $current = '';
75
76 /**
77 * @var int
78 */
79 public $lockToNormal = 0;
80
81 /**
82 * If set, clipboard is displaying files.
83 *
84 * @var bool
85 */
86 public $fileMode = false;
87
88 /**
89 * @var IconFactory
90 */
91 protected $iconFactory;
92
93 /**
94 * @var StandaloneView
95 */
96 protected $view;
97
98 /**
99 * Construct
100 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\InvalidExtensionNameException
101 * @throws \InvalidArgumentException
102 */
103 public function __construct()
104 {
105 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
106 $this->view = $this->getStandaloneView();
107 }
108
109 /*****************************************
110 *
111 * Initialize
112 *
113 ****************************************/
114 /**
115 * Initialize the clipboard from the be_user session
116 */
117 public function initializeClipboard()
118 {
119 $userTsConfig = $this->getBackendUser()->getTSConfig();
120 // Get data
121 $clipData = $this->getBackendUser()->getModuleData('clipboard', $userTsConfig['options.']['saveClipboard'] ? '' : 'ses');
122 $this->numberTabs = MathUtility::forceIntegerInRange((int)($userTsConfig['options.']['clipboardNumberPads'] ?? 3), 0, 20);
123 // Resets/reinstates the clipboard pads
124 $this->clipData['normal'] = is_array($clipData['normal']) ? $clipData['normal'] : [];
125 for ($a = 1; $a <= $this->numberTabs; $a++) {
126 $this->clipData['tab_' . $a] = is_array($clipData['tab_' . $a]) ? $clipData['tab_' . $a] : [];
127 }
128 // Setting the current pad pointer ($this->current))
129 $this->clipData['current'] = ($this->current = isset($this->clipData[$clipData['current']]) ? $clipData['current'] : 'normal');
130 }
131
132 /**
133 * Call this method after initialization if you want to lock the clipboard to operate on the normal pad only.
134 * Trying to switch pad through ->setCmd will not work.
135 * This is used by the clickmenu since it only allows operation on single elements at a time (that is the "normal" pad)
136 */
137 public function lockToNormal()
138 {
139 $this->lockToNormal = 1;
140 $this->current = 'normal';
141 }
142
143 /**
144 * The array $cmd may hold various keys which notes some action to take.
145 * Normally perform only one action at a time.
146 * In scripts like db_list.php / filelist/mod1/index.php the GET-var CB is used to control the clipboard.
147 *
148 * Selecting / Deselecting elements
149 * Array $cmd['el'] has keys = element-ident, value = element value (see description of clipData array in header)
150 * Selecting elements for 'copy' should be done by simultaneously setting setCopyMode.
151 *
152 * @param array $cmd Array of actions, see function description
153 */
154 public function setCmd($cmd)
155 {
156 if (is_array($cmd['el'])) {
157 foreach ($cmd['el'] as $k => $v) {
158 if ($this->current === 'normal') {
159 unset($this->clipData['normal']);
160 }
161 if ($v) {
162 $this->clipData[$this->current]['el'][$k] = $v;
163 } else {
164 $this->removeElement($k);
165 }
166 $this->changed = 1;
167 }
168 }
169 // Change clipboard pad (if not locked to normal)
170 if ($cmd['setP']) {
171 $this->setCurrentPad($cmd['setP']);
172 }
173 // Remove element (value = item ident: DB; '[tablename]|[uid]' FILE: '_FILE|[shortmd5 hash of path]'
174 if ($cmd['remove']) {
175 $this->removeElement($cmd['remove']);
176 $this->changed = 1;
177 }
178 // Remove all on current pad (value = pad-ident)
179 if ($cmd['removeAll']) {
180 $this->clipData[$cmd['removeAll']] = [];
181 $this->changed = 1;
182 }
183 // Set copy mode of the tab
184 if (isset($cmd['setCopyMode'])) {
185 $this->clipData[$this->current]['mode'] = $this->isElements() ? ($cmd['setCopyMode'] ? 'copy' : '') : '';
186 $this->changed = 1;
187 }
188 }
189
190 /**
191 * Setting the current pad on clipboard
192 *
193 * @param string $padIdent Key in the array $this->clipData
194 */
195 public function setCurrentPad($padIdent)
196 {
197 // Change clipboard pad (if not locked to normal)
198 if (!$this->lockToNormal && $this->current != $padIdent) {
199 if (isset($this->clipData[$padIdent])) {
200 $this->clipData['current'] = ($this->current = $padIdent);
201 }
202 if ($this->current !== 'normal' || !$this->isElements()) {
203 $this->clipData[$this->current]['mode'] = '';
204 }
205 // Setting mode to default (move) if no items on it or if not 'normal'
206 $this->changed = 1;
207 }
208 }
209
210 /**
211 * Call this after initialization and setCmd in order to save the clipboard to the user session.
212 * The function will check if the internal flag ->changed has been set and if so, save the clipboard. Else not.
213 */
214 public function endClipboard()
215 {
216 if ($this->changed) {
217 $this->saveClipboard();
218 }
219 $this->changed = 0;
220 }
221
222 /**
223 * Cleans up an incoming element array $CBarr (Array selecting/deselecting elements)
224 *
225 * @param array $CBarr Element array from outside ("key" => "selected/deselected")
226 * @param string $table The 'table which is allowed'. Must be set.
227 * @param bool|int $removeDeselected Can be set in order to remove entries which are marked for deselection.
228 * @return array Processed input $CBarr
229 */
230 public function cleanUpCBC($CBarr, $table, $removeDeselected = 0)
231 {
232 if (is_array($CBarr)) {
233 foreach ($CBarr as $k => $v) {
234 $p = explode('|', $k);
235 if ((string)$p[0] != (string)$table || $removeDeselected && !$v) {
236 unset($CBarr[$k]);
237 }
238 }
239 }
240 return $CBarr;
241 }
242
243 /*****************************************
244 *
245 * Clipboard HTML renderings
246 *
247 ****************************************/
248 /**
249 * Prints the clipboard
250 *
251 * @return string HTML output
252 * @throws \BadFunctionCallException
253 */
254 public function printClipboard()
255 {
256 $languageService = $this->getLanguageService();
257 $elementCount = count($this->elFromTable($this->fileMode ? '_FILE' : ''));
258 // Copymode Selector menu
259 $copymodeUrl = GeneralUtility::linkThisScript();
260
261 $this->view->assign('actionCopyModeUrl', htmlspecialchars(GeneralUtility::quoteJSvalue($copymodeUrl . '&CB[setCopyMode]=')));
262 $this->view->assign('actionCopyModeUrl1', htmlspecialchars(GeneralUtility::quoteJSvalue($copymodeUrl . '&CB[setCopyMode]=1')));
263 $this->view->assign('currentMode', $this->currentMode());
264 $this->view->assign('elementCount', $elementCount);
265
266 if ($elementCount) {
267 $removeAllUrl = GeneralUtility::linkThisScript(['CB' => ['removeAll' => $this->current]]);
268 $this->view->assign('removeAllUrl', $removeAllUrl);
269
270 // Selector menu + clear button
271 $optionArray = [];
272 // Import / Export link:
273 if (ExtensionManagementUtility::isLoaded('impexp')) {
274 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
275 $url = $uriBuilder->buildUriFromRoute('tx_impexp_export', $this->exportClipElementParameters());
276 $optionArray[] = [
277 'label' => $this->clLabel('export', 'rm'),
278 'uri' => (string)$url
279 ];
280 }
281 // Edit:
282 if (!$this->fileMode) {
283 $optionArray[] = [
284 'label' => $this->clLabel('edit', 'rm'),
285 'uri' => '#',
286 'additionalAttributes' => [
287 'onclick' => htmlspecialchars('window.location.href=' . GeneralUtility::quoteJSvalue($this->editUrl() . '&returnUrl=') . '+encodeURIComponent(window.location.href);'),
288 ]
289 ];
290 }
291
292 // Delete referenced elements:
293 $confirmationCheck = false;
294 if ($this->getBackendUser()->jsConfirmation(JsConfirmation::DELETE)) {
295 $confirmationCheck = true;
296 }
297
298 $confirmationMessage = sprintf(
299 $languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:mess.deleteClip'),
300 $elementCount
301 );
302 $title = $languageService
303 ->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.clipboard.delete_elements');
304 $returnUrl = $this->deleteUrl(true, $this->fileMode);
305 $btnOkText = $languageService
306 ->sL('LLL:EXT:backend/Resources/Private/Language/locallang_alt_doc.xlf:buttons.confirm.delete_elements.yes');
307 $btnCancelText = $languageService
308 ->sL('LLL:EXT:backend/Resources/Private/Language/locallang_alt_doc.xlf:buttons.confirm.delete_elements.no');
309 $optionArray[] = [
310 'label' => htmlspecialchars($title),
311 'uri' => $returnUrl,
312 'additionalAttributes' => [
313 'class' => $confirmationCheck ? 't3js-modal-trigger' : '',
314 ],
315 'data' => [
316 'severity' => 'warning',
317 'button-close-text' => htmlspecialchars($btnCancelText),
318 'button-ok-text' => htmlspecialchars($btnOkText),
319 'content' => htmlspecialchars($confirmationMessage),
320 'title' => htmlspecialchars($title)
321 ]
322 ];
323
324 // Clear clipboard
325 $optionArray[] = [
326 'label' => $languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.clipboard.clear_clipboard'),
327 'uri' => $removeAllUrl . '#clip_head'
328 ];
329 $this->view->assign('optionArray', $optionArray);
330 }
331
332 // Print header and content for the NORMAL tab:
333 $this->view->assign('current', $this->current);
334 $tabArray = [];
335 $tabArray['normal'] = [
336 'id' => 'normal',
337 'number' => 0,
338 'url' => GeneralUtility::linkThisScript(['CB' => ['setP' => 'normal']]),
339 'description' => 'normal-description',
340 'label' => 'labels.normal',
341 'padding' => $this->padTitle('normal')
342 ];
343 if ($this->current === 'normal') {
344 $tabArray['normal']['content'] = $this->getContentFromTab('normal');
345 }
346 // Print header and content for the NUMERIC tabs:
347 for ($a = 1; $a <= $this->numberTabs; $a++) {
348 $tabArray['tab_' . $a] = [
349 'id' => 'tab_' . $a,
350 'number' => $a,
351 'url' => GeneralUtility::linkThisScript(['CB' => ['setP' => 'tab_' . $a]]),
352 'description' => 'cliptabs-description',
353 'label' => 'labels.cliptabs-name',
354 'padding' => $this->padTitle('tab_' . $a)
355 ];
356 if ($this->current === 'tab_' . $a) {
357 $tabArray['tab_' . $a]['content'] = $this->getContentFromTab('tab_' . $a);
358 }
359 }
360 $this->view->assign('clipboardHeader', BackendUtility::wrapInHelp('xMOD_csh_corebe', 'list_clipboard', $this->clLabel('clipboard', 'buttons')));
361 $this->view->assign('tabArray', $tabArray);
362 return $this->view->render();
363 }
364
365 /**
366 * Print the content on a pad. Called from ->printClipboard()
367 *
368 * @internal
369 * @param string $pad Pad reference
370 * @return array Array with table rows for the clipboard.
371 */
372 public function getContentFromTab($pad)
373 {
374 $lines = [];
375 if (is_array($this->clipData[$pad]['el'] ?? false)) {
376 foreach ($this->clipData[$pad]['el'] as $k => $v) {
377 if ($v) {
378 list($table, $uid) = explode('|', $k);
379 // Rendering files/directories on the clipboard
380 if ($table === '_FILE') {
381 $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($v);
382 if ($fileObject) {
383 $thumb = [];
384 $folder = $fileObject instanceof \TYPO3\CMS\Core\Resource\Folder;
385 $size = $folder ? '' : '(' . GeneralUtility::formatSize($fileObject->getSize()) . 'bytes)';
386 if (
387 !$folder
388 && GeneralUtility::inList(
389 $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'],
390 $fileObject->getExtension()
391 )
392 ) {
393 $thumb = [
394 'image' => $fileObject->process(\TYPO3\CMS\Core\Resource\ProcessedFile::CONTEXT_IMAGEPREVIEW, [])->getPublicUrl(true),
395 'title' => htmlspecialchars($fileObject->getName())
396 ];
397 }
398 $lines[] = [
399 'icon' => '<span title="' . htmlspecialchars($fileObject->getName() . ' ' . $size) . '">' . $this->iconFactory->getIconForResource(
400 $fileObject,
401 Icon::SIZE_SMALL
402 )->render() . '</span>',
403 'title' => $this->linkItemText(htmlspecialchars(GeneralUtility::fixed_lgd_cs(
404 $fileObject->getName(),
405 $this->getBackendUser()->uc['titleLen']
406 )), $fileObject->getName()),
407 'thumb' => $thumb,
408 'infoLink' => htmlspecialchars('top.TYPO3.InfoWindow.showItem(' . GeneralUtility::quoteJSvalue($table) . ', ' . GeneralUtility::quoteJSvalue($v) . '); return false;'),
409 'removeLink' => $this->removeUrl('_FILE', GeneralUtility::shortMD5($v))
410 ];
411 } else {
412 // If the file did not exist (or is illegal) then it is removed from the clipboard immediately:
413 unset($this->clipData[$pad]['el'][$k]);
414 $this->changed = 1;
415 }
416 } else {
417 // Rendering records:
418 $rec = BackendUtility::getRecordWSOL($table, $uid);
419 if (is_array($rec)) {
420 $lines[] = [
421 'icon' => $this->linkItemText($this->iconFactory->getIconForRecord(
422 $table,
423 $rec,
424 Icon::SIZE_SMALL
425 )->render(), $rec, $table),
426 'title' => $this->linkItemText(htmlspecialchars(GeneralUtility::fixed_lgd_cs(BackendUtility::getRecordTitle(
427 $table,
428 $rec
429 ), $this->getBackendUser()->uc['titleLen'])), $rec, $table),
430 'infoLink' => htmlspecialchars('top.TYPO3.InfoWindow.showItem(' . GeneralUtility::quoteJSvalue($table) . ', \'' . (int)$uid . '\'); return false;'),
431 'removeLink' => $this->removeUrl($table, $uid)
432 ];
433
434 $localizationData = $this->getLocalizations($table, $rec);
435 if (!empty($localizationData)) {
436 $lines = array_merge($lines, $localizationData);
437 }
438 } else {
439 unset($this->clipData[$pad]['el'][$k]);
440 $this->changed = 1;
441 }
442 }
443 }
444 }
445 }
446 $this->endClipboard();
447 return $lines;
448 }
449
450 /**
451 * Returns true if the clipboard contains elements
452 *
453 * @return bool
454 */
455 public function hasElements()
456 {
457 foreach ($this->clipData as $data) {
458 if (isset($data['el']) && is_array($data['el']) && !empty($data['el'])) {
459 return true;
460 }
461 }
462
463 return false;
464 }
465
466 /**
467 * Gets all localizations of the current record.
468 *
469 * @param string $table The table
470 * @param array $parentRec The current record
471 * @return array HTML table rows
472 */
473 public function getLocalizations($table, $parentRec)
474 {
475 $lines = [];
476 $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
477 if (BackendUtility::isTableLocalizable($table)) {
478 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
479 $queryBuilder->getRestrictions()
480 ->removeAll()
481 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
482
483 $queryBuilder
484 ->select('*')
485 ->from($table)
486 ->where(
487 $queryBuilder->expr()->eq(
488 $tcaCtrl['transOrigPointerField'],
489 $queryBuilder->createNamedParameter($parentRec['uid'], \PDO::PARAM_INT)
490 ),
491 $queryBuilder->expr()->neq(
492 $tcaCtrl['languageField'],
493 $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
494 ),
495 $queryBuilder->expr()->gt(
496 'pid',
497 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
498 )
499 );
500
501 if (isset($tcaCtrl['versioningWS']) && $tcaCtrl['versioningWS']) {
502 $queryBuilder
503 ->andWhere(
504 $queryBuilder->expr()->eq(
505 't3ver_wsid',
506 $queryBuilder->createNamedParameter($parentRec['t3ver_wsid'], \PDO::PARAM_INT)
507 )
508 );
509 }
510 $rows = $queryBuilder->execute()->fetchAll();
511 if (is_array($rows)) {
512 foreach ($rows as $rec) {
513 $lines[] = [
514 'icon' => $this->iconFactory->getIconForRecord($table, $rec, Icon::SIZE_SMALL)->render(),
515 'title' => htmlspecialchars(GeneralUtility::fixed_lgd_cs(BackendUtility::getRecordTitle($table, $rec), $this->getBackendUser()->uc['titleLen']))
516 ];
517 }
518 }
519 }
520 return $lines;
521 }
522
523 /**
524 * Warps title with number of elements if any.
525 *
526 * @param string $pad Pad reference
527 * @return string padding
528 */
529 public function padTitle($pad)
530 {
531 $el = count($this->elFromTable($this->fileMode ? '_FILE' : '', $pad));
532 if ($el) {
533 return ' (' . ($pad === 'normal' ? ($this->clipData['normal']['mode'] === 'copy' ? $this->clLabel('copy', 'cm') : $this->clLabel('cut', 'cm')) : htmlspecialchars($el)) . ')';
534 }
535 return '';
536 }
537
538 /**
539 * Wraps the title of the items listed in link-tags. The items will link to the page/folder where they originate from
540 *
541 * @param string $str Title of element - must be htmlspecialchar'ed on beforehand.
542 * @param mixed $rec If array, a record is expected. If string, its a path
543 * @param string $table Table name
544 * @return string
545 */
546 public function linkItemText($str, $rec, $table = '')
547 {
548 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
549 if (is_array($rec) && $table) {
550 if ($this->fileMode) {
551 $str = '<span class="text-muted">' . $str . '</span>';
552 } else {
553 $str = '<a href="' . htmlspecialchars((string)$uriBuilder->buildUriFromRoute('web_list', ['id' => $rec['pid']])) . '">' . $str . '</a>';
554 }
555 } elseif (file_exists($rec)) {
556 if (!$this->fileMode) {
557 $str = '<span class="text-muted">' . $str . '</span>';
558 } elseif (ExtensionManagementUtility::isLoaded('filelist')) {
559 $str = '<a href="' . htmlspecialchars((string)$uriBuilder->buildUriFromRoute('file_list', ['id' => PathUtility::dirname($rec)])) . '">' . $str . '</a>';
560 }
561 }
562 return $str;
563 }
564
565 /**
566 * Returns the select-url for database elements
567 *
568 * @param string $table Table name
569 * @param int $uid Uid of record
570 * @param bool|int $copy If set, copymode will be enabled
571 * @param bool|int $deselect If set, the link will deselect, otherwise select.
572 * @param array $baseArray The base array of GET vars to be sent in addition. Notice that current GET vars WILL automatically be included.
573 * @return string URL linking to the current script but with the CB array set to select the element with table/uid
574 */
575 public function selUrlDB($table, $uid, $copy = 0, $deselect = 0, $baseArray = [])
576 {
577 $CB = ['el' => [rawurlencode($table . '|' . $uid) => $deselect ? 0 : 1]];
578 if ($copy) {
579 $CB['setCopyMode'] = 1;
580 }
581 $baseArray['CB'] = $CB;
582 return GeneralUtility::linkThisScript($baseArray);
583 }
584
585 /**
586 * Returns the select-url for files
587 *
588 * @param string $path Filepath
589 * @param bool|int $copy If set, copymode will be enabled
590 * @param bool|int $deselect If set, the link will deselect, otherwise select.
591 * @param array $baseArray The base array of GET vars to be sent in addition. Notice that current GET vars WILL automatically be included.
592 * @return string URL linking to the current script but with the CB array set to select the path
593 */
594 public function selUrlFile($path, $copy = 0, $deselect = 0, $baseArray = [])
595 {
596 $CB = ['el' => [rawurlencode('_FILE|' . GeneralUtility::shortMD5($path)) => $deselect ? '' : $path]];
597 if ($copy) {
598 $CB['setCopyMode'] = 1;
599 }
600 $baseArray['CB'] = $CB;
601 return GeneralUtility::linkThisScript($baseArray);
602 }
603
604 /**
605 * pasteUrl of the element (database and file)
606 * For the meaning of $table and $uid, please read from ->makePasteCmdArray!!!
607 * The URL will point to tce_file or tce_db depending in $table
608 *
609 * @param string $table Tablename (_FILE for files)
610 * @param mixed $uid "destination": can be positive or negative indicating how the paste is done (paste into / paste after)
611 * @param bool $setRedirect If set, then the redirect URL will point back to the current script, but with CB reset.
612 * @param array|null $update Additional key/value pairs which should get set in the moved/copied record (via DataHandler)
613 * @return string
614 */
615 public function pasteUrl($table, $uid, $setRedirect = true, array $update = null)
616 {
617 $urlParameters = [
618 'CB[paste]' => $table . '|' . $uid,
619 'CB[pad]' => $this->current
620 ];
621 if ($setRedirect) {
622 $urlParameters['redirect'] = GeneralUtility::linkThisScript(['CB' => '']);
623 }
624 if (is_array($update)) {
625 $urlParameters['CB[update]'] = $update;
626 }
627 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
628 return (string)$uriBuilder->buildUriFromRoute($table === '_FILE' ? 'tce_file' : 'tce_db', $urlParameters);
629 }
630
631 /**
632 * deleteUrl for current pad
633 *
634 * @param bool $setRedirect If set, then the redirect URL will point back to the current script, but with CB reset.
635 * @param bool $file If set, then the URL will link to the tce_file.php script in the typo3/ dir.
636 * @return string
637 */
638 public function deleteUrl($setRedirect = true, $file = false)
639 {
640 $urlParameters = [
641 'CB[delete]' => 1,
642 'CB[pad]' => $this->current
643 ];
644 if ($setRedirect) {
645 $urlParameters['redirect'] = GeneralUtility::linkThisScript(['CB' => '']);
646 }
647 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
648 return (string)$uriBuilder->buildUriFromRoute($file ? 'tce_file' : 'tce_db', $urlParameters);
649 }
650
651 /**
652 * editUrl of all current elements
653 * ONLY database
654 * Links to FormEngine
655 *
656 * @return string The URL to FormEngine with parameters.
657 */
658 public function editUrl()
659 {
660 $parameters = [];
661 // All records
662 $elements = $this->elFromTable('');
663 foreach ($elements as $tP => $value) {
664 list($table, $uid) = explode('|', $tP);
665 $parameters['edit[' . $table . '][' . $uid . ']'] = 'edit';
666 }
667 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
668 return (string)$uriBuilder->buildUriFromRoute('record_edit', $parameters);
669 }
670
671 /**
672 * Returns the remove-url (file and db)
673 * for file $table='_FILE' and $uid = shortmd5 hash of path
674 *
675 * @param string $table Tablename
676 * @param string $uid Uid integer/shortmd5 hash
677 * @return string URL
678 */
679 public function removeUrl($table, $uid)
680 {
681 return GeneralUtility::linkThisScript(['CB' => ['remove' => $table . '|' . $uid]]);
682 }
683
684 /**
685 * Returns confirm JavaScript message
686 *
687 * @param string $table Table name
688 * @param mixed $rec For records its an array, for files its a string (path)
689 * @param string $type Type-code
690 * @param array $clElements Array of selected elements
691 * @param string $columnLabel Name of the content column
692 * @return string the text for a confirm message
693 */
694 public function confirmMsgText($table, $rec, $type, $clElements, $columnLabel = '')
695 {
696 if ($this->getBackendUser()->jsConfirmation(JsConfirmation::COPY_MOVE_PASTE)) {
697 $labelKey = 'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:mess.' . ($this->currentMode() === 'copy' ? 'copy' : 'move') . ($this->current === 'normal' ? '' : 'cb') . '_' . $type;
698 $msg = $this->getLanguageService()->sL($labelKey . ($columnLabel ? '_colPos' : ''));
699 if ($table === '_FILE') {
700 $thisRecTitle = PathUtility::basename($rec);
701 if ($this->current === 'normal') {
702 $selItem = reset($clElements);
703 $selRecTitle = PathUtility::basename($selItem);
704 } else {
705 $selRecTitle = count($clElements);
706 }
707 } else {
708 $thisRecTitle = $table === 'pages' && !is_array($rec) ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] : BackendUtility::getRecordTitle($table, $rec);
709 if ($this->current === 'normal') {
710 $selItem = $this->getSelectedRecord();
711 $selRecTitle = $selItem['_RECORD_TITLE'];
712 } else {
713 $selRecTitle = count($clElements);
714 }
715 }
716 // @TODO
717 // This can get removed as soon as the "_colPos" label is translated
718 // into all available locallang languages.
719 if (!$msg && $columnLabel) {
720 $thisRecTitle .= ' | ' . $columnLabel;
721 $msg = $this->getLanguageService()->sL($labelKey);
722 }
723
724 // Message
725 $conf = sprintf(
726 $msg,
727 GeneralUtility::fixed_lgd_cs($selRecTitle, 30),
728 GeneralUtility::fixed_lgd_cs($thisRecTitle, 30),
729 GeneralUtility::fixed_lgd_cs($columnLabel, 30)
730 );
731 } else {
732 $conf = '';
733 }
734 return $conf;
735 }
736
737 /**
738 * Clipboard label - getting from "EXT:core/Resources/Private/Language/locallang_core.xlf:"
739 *
740 * @param string $key Label Key
741 * @param string $Akey Alternative key to "labels
742 * @return string
743 */
744 public function clLabel($key, $Akey = 'labels')
745 {
746 return htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:' . $Akey . '.' . $key));
747 }
748
749 /**
750 * Creates GET parameters for linking to the export module.
751 *
752 * @return array GET parameters for current clipboard content to be exported
753 */
754 protected function exportClipElementParameters()
755 {
756 // Init
757 $pad = $this->current;
758 $params = [];
759 // Traverse items:
760 if (is_array($this->clipData[$pad]['el'] ?? false)) {
761 foreach ($this->clipData[$pad]['el'] as $k => $v) {
762 if ($v) {
763 list($table, $uid) = explode('|', $k);
764 // Rendering files/directories on the clipboard
765 if ($table === '_FILE') {
766 if (file_exists($v) && GeneralUtility::isAllowedAbsPath($v)) {
767 $params['tx_impexp'][is_dir($v) ? 'dir' : 'file'][] = $v;
768 }
769 } else {
770 // Rendering records:
771 $rec = BackendUtility::getRecord($table, $uid);
772 if (is_array($rec)) {
773 $params['tx_impexp']['record'][] = $table . ':' . $uid;
774 }
775 }
776 }
777 }
778 }
779 return $params;
780 }
781
782 /*****************************************
783 *
784 * Helper functions
785 *
786 ****************************************/
787 /**
788 * Removes element on clipboard
789 *
790 * @param string $el Key of element in ->clipData array
791 */
792 public function removeElement($el)
793 {
794 unset($this->clipData[$this->current]['el'][$el]);
795 $this->changed = 1;
796 }
797
798 /**
799 * Saves the clipboard, no questions asked.
800 * Use ->endClipboard normally (as it checks if changes has been done so saving is necessary)
801 *
802 * @internal
803 */
804 public function saveClipboard()
805 {
806 $this->getBackendUser()->pushModuleData('clipboard', $this->clipData);
807 }
808
809 /**
810 * Returns the current mode, 'copy' or 'cut'
811 *
812 * @return string "copy" or "cut
813 */
814 public function currentMode()
815 {
816 return ($this->clipData[$this->current]['mode'] ?? '') === 'copy' ? 'copy' : 'cut';
817 }
818
819 /**
820 * This traverses the elements on the current clipboard pane
821 * and unsets elements which does not exist anymore or are disabled.
822 */
823 public function cleanCurrent()
824 {
825 if (is_array($this->clipData[$this->current]['el'] ?? false)) {
826 foreach ($this->clipData[$this->current]['el'] as $k => $v) {
827 list($table, $uid) = explode('|', $k);
828 if ($table !== '_FILE') {
829 if (!$v || !is_array(BackendUtility::getRecord($table, $uid, 'uid'))) {
830 unset($this->clipData[$this->current]['el'][$k]);
831 $this->changed = 1;
832 }
833 } else {
834 if (!$v) {
835 unset($this->clipData[$this->current]['el'][$k]);
836 $this->changed = 1;
837 } else {
838 try {
839 ResourceFactory::getInstance()->retrieveFileOrFolderObject($v);
840 } catch (\TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException $e) {
841 // The file has been deleted in the meantime, so just remove it silently
842 unset($this->clipData[$this->current]['el'][$k]);
843 }
844 }
845 }
846 }
847 }
848 }
849
850 /**
851 * Counts the number of elements from the table $matchTable. If $matchTable is blank, all tables (except '_FILE' of course) is counted.
852 *
853 * @param string $matchTable Table to match/count for.
854 * @param string $pad Can optionally be used to set another pad than the current.
855 * @return array Array with keys from the CB.
856 */
857 public function elFromTable($matchTable = '', $pad = '')
858 {
859 $pad = $pad ? $pad : $this->current;
860 $list = [];
861 if (is_array($this->clipData[$pad]['el'] ?? false)) {
862 foreach ($this->clipData[$pad]['el'] as $k => $v) {
863 if ($v) {
864 list($table, $uid) = explode('|', $k);
865 if ($table !== '_FILE') {
866 if ((!$matchTable || (string)$table == (string)$matchTable) && $GLOBALS['TCA'][$table]) {
867 $list[$k] = $pad === 'normal' ? $v : $uid;
868 }
869 } else {
870 if ((string)$table == (string)$matchTable) {
871 $list[$k] = $v;
872 }
873 }
874 }
875 }
876 }
877 return $list;
878 }
879
880 /**
881 * Verifies if the item $table/$uid is on the current pad.
882 * If the pad is "normal", the mode value is returned if the element existed. Thus you'll know if the item was copy or cut moded...
883 *
884 * @param string $table Table name, (_FILE for files...)
885 * @param int $uid Element uid (path for files)
886 * @return string
887 */
888 public function isSelected($table, $uid)
889 {
890 $k = $table . '|' . $uid;
891 return !empty($this->clipData[$this->current]['el'][$k]) ? ($this->current === 'normal' ? $this->currentMode() : 1) : '';
892 }
893
894 /**
895 * Returns item record $table,$uid if selected on current clipboard
896 * If table and uid is blank, the first element is returned.
897 * Makes sense only for DB records - not files!
898 *
899 * @param string $table Table name
900 * @param int|string $uid Element uid
901 * @return array Element record with extra field _RECORD_TITLE set to the title of the record
902 */
903 public function getSelectedRecord($table = '', $uid = '')
904 {
905 if (!$table && !$uid) {
906 $elArr = $this->elFromTable('');
907 reset($elArr);
908 list($table, $uid) = explode('|', key($elArr));
909 }
910 if ($this->isSelected($table, $uid)) {
911 $selRec = BackendUtility::getRecordWSOL($table, $uid);
912 $selRec['_RECORD_TITLE'] = BackendUtility::getRecordTitle($table, $selRec);
913 return $selRec;
914 }
915 return [];
916 }
917
918 /**
919 * Reports if the current pad has elements (does not check file/DB type OR if file/DBrecord exists or not. Only counting array)
920 *
921 * @return bool TRUE if elements exist.
922 */
923 public function isElements()
924 {
925 return is_array($this->clipData[$this->current]['el']) && !empty($this->clipData[$this->current]['el']);
926 }
927
928 /**
929 * Applies the proper paste configuration in the $cmd array send to SimpleDataHandlerController (tce_db route)
930 * $ref is the target, see description below.
931 * The current pad is pasted
932 *
933 * $ref: [tablename]:[paste-uid].
934 * Tablename is the name of the table from which elements *on the current clipboard* is pasted with the 'pid' paste-uid.
935 * No tablename means that all items on the clipboard (non-files) are pasted. This requires paste-uid to be positive though.
936 * so 'tt_content:-3' means 'paste tt_content elements on the clipboard to AFTER tt_content:3 record
937 * 'tt_content:30' means 'paste tt_content elements on the clipboard into page with id 30
938 * ':30' means 'paste ALL database elements on the clipboard into page with id 30
939 * ':-30' not valid.
940 *
941 * @param string $ref [tablename]:[paste-uid], see description
942 * @param array $CMD Command-array
943 * @param array|null $update If additional values should get set in the copied/moved record this will be an array containing key=>value pairs
944 * @return array Modified Command-array
945 */
946 public function makePasteCmdArray($ref, $CMD, array $update = null)
947 {
948 list($pTable, $pUid) = explode('|', $ref);
949 $pUid = (int)$pUid;
950 // pUid must be set and if pTable is not set (that means paste ALL elements)
951 // the uid MUST be positive/zero (pointing to page id)
952 if ($pTable || $pUid >= 0) {
953 $elements = $this->elFromTable($pTable);
954 // So the order is preserved.
955 $elements = array_reverse($elements);
956 $mode = $this->currentMode() === 'copy' ? 'copy' : 'move';
957 // Traverse elements and make CMD array
958 foreach ($elements as $tP => $value) {
959 list($table, $uid) = explode('|', $tP);
960 if (!is_array($CMD[$table])) {
961 $CMD[$table] = [];
962 }
963 if (is_array($update)) {
964 $CMD[$table][$uid][$mode] = [
965 'action' => 'paste',
966 'target' => $pUid,
967 'update' => $update,
968 ];
969 } else {
970 $CMD[$table][$uid][$mode] = $pUid;
971 }
972 if ($mode === 'move') {
973 $this->removeElement($tP);
974 }
975 }
976 $this->endClipboard();
977 }
978 return $CMD;
979 }
980
981 /**
982 * Delete record entries in CMD array
983 *
984 * @param array $CMD Command-array
985 * @return array Modified Command-array
986 */
987 public function makeDeleteCmdArray($CMD)
988 {
989 // all records
990 $elements = $this->elFromTable('');
991 foreach ($elements as $tP => $value) {
992 list($table, $uid) = explode('|', $tP);
993 if (!is_array($CMD[$table])) {
994 $CMD[$table] = [];
995 }
996 $CMD[$table][$uid]['delete'] = 1;
997 $this->removeElement($tP);
998 }
999 $this->endClipboard();
1000 return $CMD;
1001 }
1002
1003 /*****************************************
1004 *
1005 * FOR USE IN tce_file.php:
1006 *
1007 ****************************************/
1008 /**
1009 * Applies the proper paste configuration in the $file array send to tce_file.php.
1010 * The current pad is pasted
1011 *
1012 * @param string $ref Reference to element (splitted by "|")
1013 * @param array $FILE Command-array
1014 * @return array Modified Command-array
1015 */
1016 public function makePasteCmdArray_file($ref, $FILE)
1017 {
1018 list($pTable, $pUid) = explode('|', $ref);
1019 $elements = $this->elFromTable('_FILE');
1020 $mode = $this->currentMode() === 'copy' ? 'copy' : 'move';
1021 // Traverse elements and make CMD array
1022 foreach ($elements as $tP => $path) {
1023 $FILE[$mode][] = ['data' => $path, 'target' => $pUid];
1024 if ($mode === 'move') {
1025 $this->removeElement($tP);
1026 }
1027 }
1028 $this->endClipboard();
1029 return $FILE;
1030 }
1031
1032 /**
1033 * Delete files in CMD array
1034 *
1035 * @param array $FILE Command-array
1036 * @return array Modified Command-array
1037 */
1038 public function makeDeleteCmdArray_file($FILE)
1039 {
1040 $elements = $this->elFromTable('_FILE');
1041 // Traverse elements and make CMD array
1042 foreach ($elements as $tP => $path) {
1043 $FILE['delete'][] = ['data' => $path];
1044 $this->removeElement($tP);
1045 }
1046 $this->endClipboard();
1047 return $FILE;
1048 }
1049
1050 /**
1051 * Returns LanguageService
1052 *
1053 * @return \TYPO3\CMS\Core\Localization\LanguageService
1054 */
1055 protected function getLanguageService()
1056 {
1057 return $GLOBALS['LANG'];
1058 }
1059
1060 /**
1061 * Returns the current BE user.
1062 *
1063 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1064 */
1065 protected function getBackendUser()
1066 {
1067 return $GLOBALS['BE_USER'];
1068 }
1069
1070 /**
1071 * returns a new standalone view, shorthand function
1072 *
1073 * @return StandaloneView
1074 * @throws \InvalidArgumentException
1075 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\InvalidExtensionNameException
1076 */
1077 protected function getStandaloneView()
1078 {
1079 /** @var StandaloneView $view */
1080 $view = GeneralUtility::makeInstance(StandaloneView::class);
1081 $view->setLayoutRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Layouts')]);
1082 $view->setPartialRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Partials')]);
1083 $view->setTemplateRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates')]);
1084
1085 $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates/Clipboard/Main.html'));
1086
1087 $view->getRequest()->setControllerExtensionName('Backend');
1088 return $view;
1089 }
1090 }