[BUGFIX] Convert eID null return values to a NullResponse
[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\Fluid\View\StandaloneView;
29
30 /**
31 * TYPO3 clipboard for records and files
32 */
33 class Clipboard
34 {
35 /**
36 * @var int
37 */
38 public $numberTabs = 3;
39
40 /**
41 * Clipboard data kept here
42 *
43 * Keys:
44 * 'normal'
45 * 'tab_[x]' where x is >=1 and denotes the pad-number
46 * 'mode' : 'copy' means copy-mode, default = moving ('cut')
47 * 'el' : Array of elements:
48 * DB: keys = '[tablename]|[uid]' eg. 'tt_content:123'
49 * DB: values = 1 (basically insignificant)
50 * FILE: keys = '_FILE|[shortmd5 of path]' eg. '_FILE|9ebc7e5c74'
51 * FILE: values = The full filepath, eg. '/www/htdocs/typo3/32/dummy/fileadmin/sem1_3_examples/alternative_index.php'
52 * or 'C:/www/htdocs/typo3/32/dummy/fileadmin/sem1_3_examples/alternative_index.php'
53 *
54 * 'current' pointer to current tab (among the above...)
55 *
56 * The virtual tablename '_FILE' will always indicate files/folders. When checking for elements from eg. 'all tables'
57 * (by using an empty string) '_FILE' entries are excluded (so in effect only DB elements are counted)
58 *
59 * @var array
60 */
61 public $clipData = [];
62
63 /**
64 * @var int
65 */
66 public $changed = 0;
67
68 /**
69 * @var string
70 */
71 public $current = '';
72
73 /**
74 * @var int
75 */
76 public $lockToNormal = 0;
77
78 /**
79 * If set, clipboard is displaying files.
80 *
81 * @var bool
82 */
83 public $fileMode = false;
84
85 /**
86 * @var IconFactory
87 */
88 protected $iconFactory;
89
90 /**
91 * @var StandaloneView
92 */
93 protected $view;
94
95 /**
96 * Construct
97 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\InvalidExtensionNameException
98 * @throws \InvalidArgumentException
99 */
100 public function __construct()
101 {
102 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
103 $this->view = $this->getStandaloneView();
104 }
105
106 /*****************************************
107 *
108 * Initialize
109 *
110 ****************************************/
111 /**
112 * Initialize the clipboard from the be_user session
113 */
114 public function initializeClipboard()
115 {
116 // Get data
117 $clipData = $this->getBackendUser()->getModuleData('clipboard', $this->getBackendUser()->getTSConfigVal('options.saveClipboard') ? '' : 'ses');
118 // NumberTabs
119 $clNP = $this->getBackendUser()->getTSConfigVal('options.clipboardNumberPads');
120 if (MathUtility::canBeInterpretedAsInteger($clNP) && $clNP >= 0) {
121 $this->numberTabs = MathUtility::forceIntegerInRange($clNP, 0, 20);
122 }
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('xMOD_tximpexp', $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=') . '+top.rawurlencode(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:lang/Resources/Private/Language/locallang_core.xlf:mess.deleteClip'),
300 $elementCount
301 );
302 $title = $languageService
303 ->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.clipboard.delete_elements');
304 $returnUrl = $this->deleteUrl(true, $this->fileMode);
305 $btnOkText = $languageService
306 ->sL('LLL:EXT:lang/Resources/Private/Language/locallang_alt_doc.xlf:buttons.confirm.delete_elements.yes');
307 $btnCancelText = $languageService
308 ->sL('LLL:EXT:lang/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:lang/Resources/Private/Language/locallang_core.xlf:labels.clipboard.clear_clipboard', true),
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 * @access private
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, []),
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 );
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 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
545 if (is_array($rec) && $table) {
546 if ($this->fileMode) {
547 $str = '<span class="text-muted">' . $str . '</span>';
548 } else {
549 $str = '<a href="' . htmlspecialchars((string)$uriBuilder->buildUriFromRoute('web_list', ['id' => $rec['pid']])) . '">' . $str . '</a>';
550 }
551 } elseif (file_exists($rec)) {
552 if (!$this->fileMode) {
553 $str = '<span class="text-muted">' . $str . '</span>';
554 } elseif (ExtensionManagementUtility::isLoaded('filelist')) {
555 $str = '<a href="' . htmlspecialchars((string)$uriBuilder->buildUriFromRoute('file_list', ['id' => dirname($rec)])) . '">' . $str . '</a>';
556 }
557 }
558 return $str;
559 }
560
561 /**
562 * Returns the select-url for database elements
563 *
564 * @param string $table Table name
565 * @param int $uid Uid of record
566 * @param bool|int $copy If set, copymode will be enabled
567 * @param bool|int $deselect If set, the link will deselect, otherwise select.
568 * @param array $baseArray The base array of GET vars to be sent in addition. Notice that current GET vars WILL automatically be included.
569 * @return string URL linking to the current script but with the CB array set to select the element with table/uid
570 */
571 public function selUrlDB($table, $uid, $copy = 0, $deselect = 0, $baseArray = [])
572 {
573 $CB = ['el' => [rawurlencode($table . '|' . $uid) => $deselect ? 0 : 1]];
574 if ($copy) {
575 $CB['setCopyMode'] = 1;
576 }
577 $baseArray['CB'] = $CB;
578 return GeneralUtility::linkThisScript($baseArray);
579 }
580
581 /**
582 * Returns the select-url for files
583 *
584 * @param string $path Filepath
585 * @param bool|int $copy If set, copymode will be enabled
586 * @param bool|int $deselect If set, the link will deselect, otherwise select.
587 * @param array $baseArray The base array of GET vars to be sent in addition. Notice that current GET vars WILL automatically be included.
588 * @return string URL linking to the current script but with the CB array set to select the path
589 */
590 public function selUrlFile($path, $copy = 0, $deselect = 0, $baseArray = [])
591 {
592 $CB = ['el' => [rawurlencode('_FILE|' . GeneralUtility::shortMD5($path)) => $deselect ? '' : $path]];
593 if ($copy) {
594 $CB['setCopyMode'] = 1;
595 }
596 $baseArray['CB'] = $CB;
597 return GeneralUtility::linkThisScript($baseArray);
598 }
599
600 /**
601 * pasteUrl of the element (database and file)
602 * For the meaning of $table and $uid, please read from ->makePasteCmdArray!!!
603 * The URL will point to tce_file or tce_db depending in $table
604 *
605 * @param string $table Tablename (_FILE for files)
606 * @param mixed $uid "destination": can be positive or negative indicating how the paste is done (paste into / paste after)
607 * @param bool $setRedirect If set, then the redirect URL will point back to the current script, but with CB reset.
608 * @param array|null $update Additional key/value pairs which should get set in the moved/copied record (via DataHandler)
609 * @return string
610 */
611 public function pasteUrl($table, $uid, $setRedirect = true, array $update = null)
612 {
613 $urlParameters = [
614 'CB[paste]' => $table . '|' . $uid,
615 'CB[pad]' => $this->current
616 ];
617 if ($setRedirect) {
618 $urlParameters['redirect'] = GeneralUtility::linkThisScript(['CB' => '']);
619 }
620 if (is_array($update)) {
621 $urlParameters['CB[update]'] = $update;
622 }
623 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
624 return (string)$uriBuilder->buildUriFromRoute($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 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
644 return (string)$uriBuilder->buildUriFromRoute($file ? 'tce_file' : 'tce_db', $urlParameters);
645 }
646
647 /**
648 * editUrl of all current elements
649 * ONLY database
650 * Links to FormEngine
651 *
652 * @return string The URL to FormEngine with parameters.
653 */
654 public function editUrl()
655 {
656 $parameters = [];
657 // All records
658 $elements = $this->elFromTable('');
659 foreach ($elements as $tP => $value) {
660 list($table, $uid) = explode('|', $tP);
661 $parameters['edit[' . $table . '][' . $uid . ']'] = 'edit';
662 }
663 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
664 return (string)$uriBuilder->buildUriFromRoute('record_edit', $parameters);
665 }
666
667 /**
668 * Returns the remove-url (file and db)
669 * for file $table='_FILE' and $uid = shortmd5 hash of path
670 *
671 * @param string $table Tablename
672 * @param string $uid Uid integer/shortmd5 hash
673 * @return string URL
674 */
675 public function removeUrl($table, $uid)
676 {
677 return GeneralUtility::linkThisScript(['CB' => ['remove' => $table . '|' . $uid]]);
678 }
679
680 /**
681 * Returns confirm JavaScript message
682 *
683 * @param string $table Table name
684 * @param mixed $rec For records its an array, for files its a string (path)
685 * @param string $type Type-code
686 * @param array $clElements Array of selected elements
687 * @param string $columnLabel Name of the content column
688 * @return string the text for a confirm message
689 */
690 public function confirmMsgText($table, $rec, $type, $clElements, $columnLabel = '')
691 {
692 if ($this->getBackendUser()->jsConfirmation(JsConfirmation::COPY_MOVE_PASTE)) {
693 $labelKey = 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:mess.' . ($this->currentMode() === 'copy' ? 'copy' : 'move') . ($this->current === 'normal' ? '' : 'cb') . '_' . $type;
694 $msg = $this->getLanguageService()->sL($labelKey . ($columnLabel ? '_colPos' : ''));
695 if ($table === '_FILE') {
696 $thisRecTitle = basename($rec);
697 if ($this->current === 'normal') {
698 $selItem = reset($clElements);
699 $selRecTitle = basename($selItem);
700 } else {
701 $selRecTitle = count($clElements);
702 }
703 } else {
704 $thisRecTitle = $table === 'pages' && !is_array($rec) ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] : BackendUtility::getRecordTitle($table, $rec);
705 if ($this->current === 'normal') {
706 $selItem = $this->getSelectedRecord();
707 $selRecTitle = $selItem['_RECORD_TITLE'];
708 } else {
709 $selRecTitle = count($clElements);
710 }
711 }
712 // @TODO
713 // This can get removed as soon as the "_colPos" label is translated
714 // into all available locallang languages.
715 if (!$msg && $columnLabel) {
716 $thisRecTitle .= ' | ' . $columnLabel;
717 $msg = $this->getLanguageService()->sL($labelKey);
718 }
719
720 // Message
721 $conf = sprintf(
722 $msg,
723 GeneralUtility::fixed_lgd_cs($selRecTitle, 30),
724 GeneralUtility::fixed_lgd_cs($thisRecTitle, 30),
725 GeneralUtility::fixed_lgd_cs($columnLabel, 30)
726 );
727 } else {
728 $conf = '';
729 }
730 return $conf;
731 }
732
733 /**
734 * Clipboard label - getting from "EXT:lang/Resources/Private/Language/locallang_core.xlf:"
735 *
736 * @param string $key Label Key
737 * @param string $Akey Alternative key to "labels
738 * @return string
739 */
740 public function clLabel($key, $Akey = 'labels')
741 {
742 return htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:' . $Akey . '.' . $key));
743 }
744
745 /**
746 * Creates GET parameters for linking to the export module.
747 *
748 * @return array GET parameters for current clipboard content to be exported
749 */
750 protected function exportClipElementParameters()
751 {
752 // Init
753 $pad = $this->current;
754 $params = [];
755 $params['tx_impexp']['action'] = 'export';
756 // Traverse items:
757 if (is_array($this->clipData[$pad]['el'] ?? false)) {
758 foreach ($this->clipData[$pad]['el'] as $k => $v) {
759 if ($v) {
760 list($table, $uid) = explode('|', $k);
761 // Rendering files/directories on the clipboard
762 if ($table === '_FILE') {
763 if (file_exists($v) && GeneralUtility::isAllowedAbsPath($v)) {
764 $params['tx_impexp'][is_dir($v) ? 'dir' : 'file'][] = $v;
765 }
766 } else {
767 // Rendering records:
768 $rec = BackendUtility::getRecord($table, $uid);
769 if (is_array($rec)) {
770 $params['tx_impexp']['record'][] = $table . ':' . $uid;
771 }
772 }
773 }
774 }
775 }
776 return $params;
777 }
778
779 /*****************************************
780 *
781 * Helper functions
782 *
783 ****************************************/
784 /**
785 * Removes element on clipboard
786 *
787 * @param string $el Key of element in ->clipData array
788 */
789 public function removeElement($el)
790 {
791 unset($this->clipData[$this->current]['el'][$el]);
792 $this->changed = 1;
793 }
794
795 /**
796 * Saves the clipboard, no questions asked.
797 * Use ->endClipboard normally (as it checks if changes has been done so saving is necessary)
798 *
799 * @access private
800 */
801 public function saveClipboard()
802 {
803 $this->getBackendUser()->pushModuleData('clipboard', $this->clipData);
804 }
805
806 /**
807 * Returns the current mode, 'copy' or 'cut'
808 *
809 * @return string "copy" or "cut
810 */
811 public function currentMode()
812 {
813 return ($this->clipData[$this->current]['mode'] ?? '') === 'copy' ? 'copy' : 'cut';
814 }
815
816 /**
817 * This traverses the elements on the current clipboard pane
818 * and unsets elements which does not exist anymore or are disabled.
819 */
820 public function cleanCurrent()
821 {
822 if (is_array($this->clipData[$this->current]['el'] ?? false)) {
823 foreach ($this->clipData[$this->current]['el'] as $k => $v) {
824 list($table, $uid) = explode('|', $k);
825 if ($table !== '_FILE') {
826 if (!$v || !is_array(BackendUtility::getRecord($table, $uid, 'uid'))) {
827 unset($this->clipData[$this->current]['el'][$k]);
828 $this->changed = 1;
829 }
830 } else {
831 if (!$v) {
832 unset($this->clipData[$this->current]['el'][$k]);
833 $this->changed = 1;
834 } else {
835 try {
836 ResourceFactory::getInstance()->retrieveFileOrFolderObject($v);
837 } catch (\TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException $e) {
838 // The file has been deleted in the meantime, so just remove it silently
839 unset($this->clipData[$this->current]['el'][$k]);
840 }
841 }
842 }
843 }
844 }
845 }
846
847 /**
848 * Counts the number of elements from the table $matchTable. If $matchTable is blank, all tables (except '_FILE' of course) is counted.
849 *
850 * @param string $matchTable Table to match/count for.
851 * @param string $pad Can optionally be used to set another pad than the current.
852 * @return array Array with keys from the CB.
853 */
854 public function elFromTable($matchTable = '', $pad = '')
855 {
856 $pad = $pad ? $pad : $this->current;
857 $list = [];
858 if (is_array($this->clipData[$pad]['el'] ?? false)) {
859 foreach ($this->clipData[$pad]['el'] as $k => $v) {
860 if ($v) {
861 list($table, $uid) = explode('|', $k);
862 if ($table !== '_FILE') {
863 if ((!$matchTable || (string)$table == (string)$matchTable) && $GLOBALS['TCA'][$table]) {
864 $list[$k] = $pad === 'normal' ? $v : $uid;
865 }
866 } else {
867 if ((string)$table == (string)$matchTable) {
868 $list[$k] = $v;
869 }
870 }
871 }
872 }
873 }
874 return $list;
875 }
876
877 /**
878 * Verifies if the item $table/$uid is on the current pad.
879 * 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...
880 *
881 * @param string $table Table name, (_FILE for files...)
882 * @param int $uid Element uid (path for files)
883 * @return string
884 */
885 public function isSelected($table, $uid)
886 {
887 $k = $table . '|' . $uid;
888 return !empty($this->clipData[$this->current]['el'][$k]) ? ($this->current === 'normal' ? $this->currentMode() : 1) : '';
889 }
890
891 /**
892 * Returns item record $table,$uid if selected on current clipboard
893 * If table and uid is blank, the first element is returned.
894 * Makes sense only for DB records - not files!
895 *
896 * @param string $table Table name
897 * @param int|string $uid Element uid
898 * @return array Element record with extra field _RECORD_TITLE set to the title of the record
899 */
900 public function getSelectedRecord($table = '', $uid = '')
901 {
902 if (!$table && !$uid) {
903 $elArr = $this->elFromTable('');
904 reset($elArr);
905 list($table, $uid) = explode('|', key($elArr));
906 }
907 if ($this->isSelected($table, $uid)) {
908 $selRec = BackendUtility::getRecordWSOL($table, $uid);
909 $selRec['_RECORD_TITLE'] = BackendUtility::getRecordTitle($table, $selRec);
910 return $selRec;
911 }
912 return [];
913 }
914
915 /**
916 * Reports if the current pad has elements (does not check file/DB type OR if file/DBrecord exists or not. Only counting array)
917 *
918 * @return bool TRUE if elements exist.
919 */
920 public function isElements()
921 {
922 return is_array($this->clipData[$this->current]['el']) && !empty($this->clipData[$this->current]['el']);
923 }
924
925 /*****************************************
926 *
927 * FOR USE IN tce_db.php:
928 *
929 ****************************************/
930 /**
931 * Applies the proper paste configuration in the $cmd array send to tce_db.php.
932 * $ref is the target, see description below.
933 * The current pad is pasted
934 *
935 * $ref: [tablename]:[paste-uid].
936 * Tablename is the name of the table from which elements *on the current clipboard* is pasted with the 'pid' paste-uid.
937 * No tablename means that all items on the clipboard (non-files) are pasted. This requires paste-uid to be positive though.
938 * so 'tt_content:-3' means 'paste tt_content elements on the clipboard to AFTER tt_content:3 record
939 * 'tt_content:30' means 'paste tt_content elements on the clipboard into page with id 30
940 * ':30' means 'paste ALL database elements on the clipboard into page with id 30
941 * ':-30' not valid.
942 *
943 * @param string $ref [tablename]:[paste-uid], see description
944 * @param array $CMD Command-array
945 * @param array|null $update If additional values should get set in the copied/moved record this will be an array containing key=>value pairs
946 * @return array Modified Command-array
947 */
948 public function makePasteCmdArray($ref, $CMD, array $update = null)
949 {
950 list($pTable, $pUid) = explode('|', $ref);
951 $pUid = (int)$pUid;
952 // pUid must be set and if pTable is not set (that means paste ALL elements)
953 // the uid MUST be positive/zero (pointing to page id)
954 if ($pTable || $pUid >= 0) {
955 $elements = $this->elFromTable($pTable);
956 // So the order is preserved.
957 $elements = array_reverse($elements);
958 $mode = $this->currentMode() === 'copy' ? 'copy' : 'move';
959 // Traverse elements and make CMD array
960 foreach ($elements as $tP => $value) {
961 list($table, $uid) = explode('|', $tP);
962 if (!is_array($CMD[$table])) {
963 $CMD[$table] = [];
964 }
965 if (is_array($update)) {
966 $CMD[$table][$uid][$mode] = [
967 'action' => 'paste',
968 'target' => $pUid,
969 'update' => $update,
970 ];
971 } else {
972 $CMD[$table][$uid][$mode] = $pUid;
973 }
974 if ($mode === 'move') {
975 $this->removeElement($tP);
976 }
977 }
978 $this->endClipboard();
979 }
980 return $CMD;
981 }
982
983 /**
984 * Delete record entries in CMD array
985 *
986 * @param array $CMD Command-array
987 * @return array Modified Command-array
988 */
989 public function makeDeleteCmdArray($CMD)
990 {
991 // all records
992 $elements = $this->elFromTable('');
993 foreach ($elements as $tP => $value) {
994 list($table, $uid) = explode('|', $tP);
995 if (!is_array($CMD[$table])) {
996 $CMD[$table] = [];
997 }
998 $CMD[$table][$uid]['delete'] = 1;
999 $this->removeElement($tP);
1000 }
1001 $this->endClipboard();
1002 return $CMD;
1003 }
1004
1005 /*****************************************
1006 *
1007 * FOR USE IN tce_file.php:
1008 *
1009 ****************************************/
1010 /**
1011 * Applies the proper paste configuration in the $file array send to tce_file.php.
1012 * The current pad is pasted
1013 *
1014 * @param string $ref Reference to element (splitted by "|")
1015 * @param array $FILE Command-array
1016 * @return array Modified Command-array
1017 */
1018 public function makePasteCmdArray_file($ref, $FILE)
1019 {
1020 list($pTable, $pUid) = explode('|', $ref);
1021 $elements = $this->elFromTable('_FILE');
1022 $mode = $this->currentMode() === 'copy' ? 'copy' : 'move';
1023 // Traverse elements and make CMD array
1024 foreach ($elements as $tP => $path) {
1025 $FILE[$mode][] = ['data' => $path, 'target' => $pUid];
1026 if ($mode === 'move') {
1027 $this->removeElement($tP);
1028 }
1029 }
1030 $this->endClipboard();
1031 return $FILE;
1032 }
1033
1034 /**
1035 * Delete files in CMD array
1036 *
1037 * @param array $FILE Command-array
1038 * @return array Modified Command-array
1039 */
1040 public function makeDeleteCmdArray_file($FILE)
1041 {
1042 $elements = $this->elFromTable('_FILE');
1043 // Traverse elements and make CMD array
1044 foreach ($elements as $tP => $path) {
1045 $FILE['delete'][] = ['data' => $path];
1046 $this->removeElement($tP);
1047 }
1048 $this->endClipboard();
1049 return $FILE;
1050 }
1051
1052 /**
1053 * Returns LanguageService
1054 *
1055 * @return \TYPO3\CMS\Core\Localization\LanguageService
1056 */
1057 protected function getLanguageService()
1058 {
1059 return $GLOBALS['LANG'];
1060 }
1061
1062 /**
1063 * Returns the current BE user.
1064 *
1065 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1066 */
1067 protected function getBackendUser()
1068 {
1069 return $GLOBALS['BE_USER'];
1070 }
1071
1072 /**
1073 * returns a new standalone view, shorthand function
1074 *
1075 * @return StandaloneView
1076 * @throws \InvalidArgumentException
1077 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\InvalidExtensionNameException
1078 */
1079 protected function getStandaloneView()
1080 {
1081 /** @var StandaloneView $view */
1082 $view = GeneralUtility::makeInstance(StandaloneView::class);
1083 $view->setLayoutRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Layouts')]);
1084 $view->setPartialRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Partials')]);
1085 $view->setTemplateRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates')]);
1086
1087 $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates/Clipboard/Main.html'));
1088
1089 $view->getRequest()->setControllerExtensionName('Backend');
1090 return $view;
1091 }
1092 }