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