c21b509bc0f00895203a0f0b5bc909fe81262bc9
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / EditDocumentController.php
1 <?php
2 namespace TYPO3\CMS\Backend\Controller;
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\Form\FormEngine;
18 use TYPO3\CMS\Backend\Utility\BackendUtility;
19 use TYPO3\CMS\Backend\Utility\IconUtility;
20 use TYPO3\CMS\Core\Html\HtmlParser;
21 use TYPO3\CMS\Core\Utility\GeneralUtility;
22 use TYPO3\CMS\Core\Utility\HttpUtility;
23 use TYPO3\CMS\Core\Utility\MathUtility;
24
25 /**
26 * Script Class: Drawing the editing form for editing records in TYPO3.
27 * Notice: It does NOT use tce_db.php to submit data to, rather it handles submissions itself
28 *
29 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
30 */
31 class EditDocumentController {
32
33 /**
34 * GPvar "edit": Is an array looking approx like [tablename][list-of-ids]=command, eg.
35 * "&edit[pages][123]=edit". See \TYPO3\CMS\Backend\Utility\BackendUtility::editOnClick(). Value can be seen modified
36 * internally (converting NEW keyword to id, workspace/versioning etc).
37 *
38 * @var array
39 */
40 public $editconf;
41
42 /**
43 * Commalist of fieldnames to edit. The point is IF you specify this list, only those
44 * fields will be rendered in the form. Otherwise all (available) fields in the record
45 * is shown according to the types configuration in $GLOBALS['TCA']
46 *
47 * @var bool
48 */
49 public $columnsOnly;
50
51 /**
52 * Default values for fields (array with tablenames, fields etc. as keys).
53 * Can be seen modified internally.
54 *
55 * @var array
56 */
57 public $defVals;
58
59 /**
60 * Array of values to force being set (as hidden fields). Will be set as $this->defVals
61 * IF defVals does not exist.
62 *
63 * @var array
64 */
65 public $overrideVals;
66
67 /**
68 * If set, this value will be set in $this->retUrl (which is used quite many places
69 * as the return URL). If not set, "dummy.php" will be set in $this->retUrl
70 *
71 * @var string
72 */
73 public $returnUrl;
74
75 /**
76 * Close-document command. Not really sure of all options...
77 *
78 * @var int
79 */
80 public $closeDoc;
81
82 /**
83 * Quite simply, if this variable is set, then the processing of incoming data will be performed
84 * as if a save-button is pressed. Used in the forms as a hidden field which can be set through
85 * JavaScript if the form is somehow submitted by JavaScript).
86 *
87 * @var bool
88 */
89 public $doSave;
90
91 /**
92 * The data array from which the data comes...
93 *
94 * @var array
95 */
96 public $data;
97
98 /**
99 * @var array
100 */
101 public $mirror;
102
103 /**
104 * Clear-cache cmd.
105 *
106 * @var string
107 */
108 public $cacheCmd;
109
110 /**
111 * Redirect (not used???)
112 *
113 * @var string
114 */
115 public $redirect;
116
117 /**
118 * Boolean: If set, then the GET var "&id=" will be added to the
119 * retUrl string so that the NEW id of something is returned to the script calling the form.
120 *
121 * @var bool
122 */
123 public $returnNewPageId;
124
125 /**
126 * @var string
127 */
128 public $vC;
129
130 /**
131 * update BE_USER->uc
132 *
133 * @var array
134 */
135 public $uc;
136
137 /**
138 * ID for displaying the page in the frontend (used for SAVE/VIEW operations)
139 *
140 * @var int
141 */
142 public $popViewId;
143
144 /**
145 * Additional GET vars for the link, eg. "&L=xxx"
146 *
147 * @var string
148 */
149 public $popViewId_addParams;
150
151 /**
152 * Alternative URL for viewing the frontend pages.
153 *
154 * @var string
155 */
156 public $viewUrl;
157
158 /**
159 * If this is pointing to a page id it will automatically load all content elements
160 * (NORMAL column/default language) from that page into the form!
161 *
162 * @var int
163 */
164 public $editRegularContentFromId;
165
166 /**
167 * Alternative title for the document handler.
168 *
169 * @var string
170 */
171 public $recTitle;
172
173 /**
174 * Disable help... ?
175 *
176 * @var bool
177 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
178 */
179 public $disHelp;
180
181 /**
182 * If set, then no SAVE/VIEW button is printed
183 *
184 * @var bool
185 */
186 public $noView;
187
188 /**
189 * If set, the $this->editconf array is returned to the calling script
190 * (used by wizard_add.php for instance)
191 *
192 * @var bool
193 */
194 public $returnEditConf;
195
196 /**
197 * localization mode for TCEforms (eg. "text")
198 *
199 * @var string
200 */
201 public $localizationMode;
202
203 /**
204 * Workspace used for the editing action.
205 *
206 * @var NULL|integer
207 */
208 protected $workspace;
209
210 /**
211 * document template object
212 *
213 * @var \TYPO3\CMS\Backend\Template\DocumentTemplate
214 */
215 public $doc;
216
217 /**
218 * a static HTML template, usually in templates/alt_doc.html
219 *
220 * @var string
221 */
222 public $template;
223
224 /**
225 * Content accumulation
226 *
227 * @var string
228 */
229 public $content;
230
231 /**
232 * Return URL script, processed. This contains the script (if any) that we should
233 * RETURN TO from the alt_doc.php script IF we press the close button. Thus this
234 * variable is normally passed along from the calling script so we can properly return if needed.
235 *
236 * @var string
237 */
238 public $retUrl;
239
240 /**
241 * Contains the parts of the REQUEST_URI (current url). By parts we mean the result of resolving
242 * REQUEST_URI (current url) by the parse_url() function. The result is an array where eg. "path"
243 * is the script path and "query" is the parameters...
244 *
245 * @var array
246 */
247 public $R_URL_parts;
248
249 /**
250 * Contains the current GET vars array; More specifically this array is the foundation for creating
251 * the R_URI internal var (which becomes the "url of this script" to which we submit the forms etc.)
252 *
253 * @var array
254 */
255 public $R_URL_getvars;
256
257 /**
258 * Set to the URL of this script including variables which is needed to re-display the form. See main()
259 *
260 * @var string
261 */
262 public $R_URI;
263
264 /**
265 * Is loaded with the "title" of the currently "open document" - this is used in the
266 * Document Selector box. (see makeDocSel())
267 *
268 * @var string
269 */
270 public $storeTitle;
271
272 /**
273 * Contains an array with key/value pairs of GET parameters needed to reach the
274 * current document displayed - used in the Document Selector box. (see compileStoreDat())
275 *
276 * @var array
277 */
278 public $storeArray;
279
280 /**
281 * Contains storeArray, but imploded into a GET parameter string (see compileStoreDat())
282 *
283 * @var string
284 */
285 public $storeUrl;
286
287 /**
288 * Hashed value of storeURL (see compileStoreDat())
289 *
290 * @var string
291 */
292 public $storeUrlMd5;
293
294 /**
295 * Module session data
296 *
297 * @var array
298 */
299 public $docDat;
300
301 /**
302 * An array of the "open documents" - keys are md5 hashes (see $storeUrlMd5) identifying
303 * the various documents on the GET parameter list needed to open it. The values are
304 * arrays with 0,1,2 keys with information about the document (see compileStoreDat()).
305 * The docHandler variable is stored in the $docDat session data, key "0".
306 *
307 * @var array
308 */
309 public $docHandler;
310
311 /**
312 * Array of the elements to create edit forms for.
313 *
314 * @var array
315 */
316 public $elementsData;
317
318 /**
319 * Pointer to the first element in $elementsData
320 *
321 * @var array
322 */
323 public $firstEl;
324
325 /**
326 * Counter, used to count the number of errors (when users do not have edit permissions)
327 *
328 * @var int
329 */
330 public $errorC;
331
332 /**
333 * Counter, used to count the number of new record forms displayed
334 *
335 * @var int
336 */
337 public $newC;
338
339 /**
340 * Is set to the pid value of the last shown record - thus indicating which page to
341 * show when clicking the SAVE/VIEW button
342 *
343 * @var int
344 */
345 public $viewId;
346
347 /**
348 * Is set to additional parameters (like "&L=xxx") if the record supports it.
349 *
350 * @var string
351 */
352 public $viewId_addParams;
353
354 /**
355 * Module TSconfig, loaded from main() based on the page id value of viewId
356 *
357 * @var array
358 */
359 public $modTSconfig;
360
361 /**
362 * instance of TCEforms class
363 *
364 * @var \TYPO3\CMS\Backend\Form\FormEngine
365 */
366 public $tceforms;
367
368 /**
369 * Contains the root-line path of the currently edited record(s) - for display.
370 *
371 * @var string
372 */
373 public $generalPathOfForm;
374
375 /**
376 * Used internally to disable the storage of the document reference (eg. new records)
377 *
378 * @var bool
379 */
380 public $dontStoreDocumentRef;
381
382 /**
383 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
384 */
385 protected $signalSlotDispatcher;
386
387 /**
388 * Constructor
389 */
390 public function __construct() {
391 $GLOBALS['SOBE'] = $this;
392 $GLOBALS['LANG']->includeLLFile('EXT:lang/locallang_alt_doc.xml');
393 }
394
395 /**
396 * Get the SignalSlot dispatcher
397 *
398 * @return \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
399 */
400 protected function getSignalSlotDispatcher() {
401 if (!isset($this->signalSlotDispatcher)) {
402 $this->signalSlotDispatcher = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class);
403 }
404 return $this->signalSlotDispatcher;
405 }
406
407 /**
408 * Emits a signal after a function was executed
409 *
410 * @param string $signalName
411 */
412 protected function emitFunctionAfterSignal($signalName) {
413 $this->getSignalSlotDispatcher()->dispatch(__CLASS__, $signalName . 'After', array($this));
414 }
415
416 /**
417 * First initialization.
418 *
419 * @return void
420 */
421 public function preInit() {
422 if (GeneralUtility::_GP('justLocalized')) {
423 $this->localizationRedirect(GeneralUtility::_GP('justLocalized'));
424 }
425 // Setting GPvars:
426 $this->editconf = GeneralUtility::_GP('edit');
427 $this->defVals = GeneralUtility::_GP('defVals');
428 $this->overrideVals = GeneralUtility::_GP('overrideVals');
429 $this->columnsOnly = GeneralUtility::_GP('columnsOnly');
430 $this->returnUrl = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'));
431 $this->closeDoc = GeneralUtility::_GP('closeDoc');
432 $this->doSave = GeneralUtility::_GP('doSave');
433 $this->returnEditConf = GeneralUtility::_GP('returnEditConf');
434 $this->localizationMode = GeneralUtility::_GP('localizationMode');
435 $this->workspace = GeneralUtility::_GP('workspace');
436 $this->uc = GeneralUtility::_GP('uc');
437 // Setting override values as default if defVals does not exist.
438 if (!is_array($this->defVals) && is_array($this->overrideVals)) {
439 $this->defVals = $this->overrideVals;
440 }
441 // Setting return URL
442 $this->retUrl = $this->returnUrl ?: 'dummy.php';
443 // Fix $this->editconf if versioning applies to any of the records
444 $this->fixWSversioningInEditConf();
445 // Make R_URL (request url) based on input GETvars:
446 $this->R_URL_parts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
447 $this->R_URL_getvars = GeneralUtility::_GET();
448 $this->R_URL_getvars['edit'] = $this->editconf;
449 // MAKE url for storing
450 $this->compileStoreDat();
451 // Initialize more variables.
452 $this->dontStoreDocumentRef = 0;
453 $this->storeTitle = '';
454 // Get session data for the module:
455 $this->docDat = $GLOBALS['BE_USER']->getModuleData('alt_doc.php', 'ses');
456 $this->docHandler = $this->docDat[0];
457 // If a request for closing the document has been sent, act accordingly:
458 if ($this->closeDoc > 0) {
459 $this->closeDocument($this->closeDoc);
460 }
461 // If NO vars are sent to the script, try to read first document:
462 // Added !is_array($this->editconf) because editConf must not be set either.
463 // Anyways I can't figure out when this situation here will apply...
464 if (is_array($this->R_URL_getvars) && count($this->R_URL_getvars) < 2 && !is_array($this->editconf)) {
465 $this->setDocument($this->docDat[1]);
466 }
467
468 // Sets a temporary workspace, this request is based on
469 if ($this->workspace !== NULL) {
470 $this->getBackendUser()->setTemporaryWorkspace($this->workspace);
471 }
472
473 $this->emitFunctionAfterSignal(__FUNCTION__);
474 }
475
476 /**
477 * Detects, if a save command has been triggered.
478 *
479 * @return bool TRUE, then save the document (data submitted)
480 */
481 public function doProcessData() {
482 $out = $this->doSave || isset($_POST['_savedok_x']) || isset($_POST['_saveandclosedok_x']) || isset($_POST['_savedokview_x']) || isset($_POST['_savedoknew_x']) || isset($_POST['_translation_savedok_x']) || isset($_POST['_translation_savedokclear_x']);
483 return $out;
484 }
485
486 /**
487 * Do processing of data, submitting it to TCEmain.
488 *
489 * @return void
490 */
491 public function processData() {
492 // GPvars specifically for processing:
493 $control = GeneralUtility::_GP('control');
494 $this->data = GeneralUtility::_GP('data');
495 $this->cmd = GeneralUtility::_GP('cmd');
496 $this->mirror = GeneralUtility::_GP('mirror');
497 $this->cacheCmd = GeneralUtility::_GP('cacheCmd');
498 $this->redirect = GeneralUtility::_GP('redirect');
499 $this->returnNewPageId = GeneralUtility::_GP('returnNewPageId');
500 $this->vC = GeneralUtility::_GP('vC');
501 // See tce_db.php for relevate options here:
502 // Only options related to $this->data submission are included here.
503 /** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
504 $tce = GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
505 $tce->stripslashes_values = 0;
506
507 if (!empty($control)) {
508 $tce->setControl($control);
509 }
510 if (isset($_POST['_translation_savedok_x'])) {
511 $tce->updateModeL10NdiffData = 'FORCE_FFUPD';
512 }
513 if (isset($_POST['_translation_savedokclear_x'])) {
514 $tce->updateModeL10NdiffData = 'FORCE_FFUPD';
515 $tce->updateModeL10NdiffDataClear = TRUE;
516 }
517 // Setting default values specific for the user:
518 $TCAdefaultOverride = $GLOBALS['BE_USER']->getTSConfigProp('TCAdefaults');
519 if (is_array($TCAdefaultOverride)) {
520 $tce->setDefaultsFromUserTS($TCAdefaultOverride);
521 }
522 // Setting internal vars:
523 if ($GLOBALS['BE_USER']->uc['neverHideAtCopy']) {
524 $tce->neverHideAtCopy = 1;
525 }
526 $tce->debug = 0;
527 // Loading TCEmain with data:
528 $tce->start($this->data, $this->cmd);
529 if (is_array($this->mirror)) {
530 $tce->setMirror($this->mirror);
531 }
532 // Checking referer / executing
533 $refInfo = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
534 $httpHost = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
535 if ($httpHost != $refInfo['host'] && $this->vC != $GLOBALS['BE_USER']->veriCode() && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer']) {
536 $tce->log('', 0, 0, 0, 1, 'Referer host \'%s\' and server host \'%s\' did not match and veriCode was not valid either!', 1, array($refInfo['host'], $httpHost));
537 debug('Error: Referer host did not match with server host.');
538 } else {
539 // Perform the saving operation with TCEmain:
540 $tce->process_uploads($_FILES);
541 $tce->process_datamap();
542 $tce->process_cmdmap();
543 // If pages are being edited, we set an instruction about updating the page tree after this operation.
544 if ($tce->pagetreeNeedsRefresh && (isset($this->data['pages']) || $GLOBALS['BE_USER']->workspace != 0 && count($this->data))) {
545 BackendUtility::setUpdateSignal('updatePageTree');
546 }
547 // If there was saved any new items, load them:
548 if (count($tce->substNEWwithIDs_table)) {
549 // save the expanded/collapsed states for new inline records, if any
550 \TYPO3\CMS\Backend\Form\Element\InlineElement::updateInlineView($this->uc, $tce);
551 $newEditConf = array();
552 foreach ($this->editconf as $tableName => $tableCmds) {
553 $keys = array_keys($tce->substNEWwithIDs_table, $tableName);
554 if (count($keys) > 0) {
555 foreach ($keys as $key) {
556 $editId = $tce->substNEWwithIDs[$key];
557 // Check if the $editId isn't a child record of an IRRE action
558 if (!(is_array($tce->newRelatedIDs[$tableName]) && in_array($editId, $tce->newRelatedIDs[$tableName]))) {
559 // Translate new id to the workspace version:
560 if ($versionRec = BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $tableName, $editId, 'uid')) {
561 $editId = $versionRec['uid'];
562 }
563 $newEditConf[$tableName][$editId] = 'edit';
564 }
565 // Traverse all new records and forge the content of ->editconf so we can continue to EDIT these records!
566 if ($tableName == 'pages' && $this->retUrl != 'dummy.php' && $this->returnNewPageId) {
567 $this->retUrl .= '&id=' . $tce->substNEWwithIDs[$key];
568 }
569 }
570 } else {
571 $newEditConf[$tableName] = $tableCmds;
572 }
573 }
574 // Resetting editconf if newEditConf has values:
575 if (count($newEditConf)) {
576 $this->editconf = $newEditConf;
577 }
578 // Finally, set the editconf array in the "getvars" so they will be passed along in URLs as needed.
579 $this->R_URL_getvars['edit'] = $this->editconf;
580 // Unsetting default values since we don't need them anymore.
581 unset($this->R_URL_getvars['defVals']);
582 // Re-compile the store* values since editconf changed...
583 $this->compileStoreDat();
584 }
585 // See if any records was auto-created as new versions?
586 if (count($tce->autoVersionIdMap)) {
587 $this->fixWSversioningInEditConf($tce->autoVersionIdMap);
588 }
589 // If a document is saved and a new one is created right after.
590 if (isset($_POST['_savedoknew_x']) && is_array($this->editconf)) {
591 // Finding the current table:
592 reset($this->editconf);
593 $nTable = key($this->editconf);
594 // Finding the first id, getting the records pid+uid
595 reset($this->editconf[$nTable]);
596 $nUid = key($this->editconf[$nTable]);
597 $nRec = BackendUtility::getRecord($nTable, $nUid, 'pid,uid');
598 // Setting a blank editconf array for a new record:
599 $this->editconf = array();
600 if ($this->getNewIconMode($nTable) == 'top') {
601 $this->editconf[$nTable][$nRec['pid']] = 'new';
602 } else {
603 $this->editconf[$nTable][-$nRec['uid']] = 'new';
604 }
605 // Finally, set the editconf array in the "getvars" so they will be passed along in URLs as needed.
606 $this->R_URL_getvars['edit'] = $this->editconf;
607 // Re-compile the store* values since editconf changed...
608 $this->compileStoreDat();
609 }
610 $tce->printLogErrorMessages(isset($_POST['_saveandclosedok_x']) || isset($_POST['_translation_savedok_x']) ? $this->retUrl : $this->R_URL_parts['path'] . '?' . GeneralUtility::implodeArrayForUrl('', $this->R_URL_getvars));
611 }
612 // || count($tce->substNEWwithIDs)... If any new items has been save, the document is CLOSED
613 // because if not, we just get that element re-listed as new. And we don't want that!
614 if (isset($_POST['_saveandclosedok_x']) || isset($_POST['_translation_savedok_x']) || $this->closeDoc < 0) {
615 $this->closeDocument(abs($this->closeDoc));
616 }
617 }
618
619 /**
620 * Initialize the normal module operation
621 *
622 * @return void
623 */
624 public function init() {
625 // Setting more GPvars:
626 $this->popViewId = GeneralUtility::_GP('popViewId');
627 $this->popViewId_addParams = GeneralUtility::_GP('popViewId_addParams');
628 $this->viewUrl = GeneralUtility::_GP('viewUrl');
629 $this->editRegularContentFromId = GeneralUtility::_GP('editRegularContentFromId');
630 $this->recTitle = GeneralUtility::_GP('recTitle');
631 $this->noView = GeneralUtility::_GP('noView');
632 $this->perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
633 // Set other internal variables:
634 $this->R_URL_getvars['returnUrl'] = $this->retUrl;
635 $this->R_URI = $this->R_URL_parts['path'] . '?' . GeneralUtility::implodeArrayForUrl('', $this->R_URL_getvars);
636 // MENU-ITEMS:
637 // If array, then it's a selector box menu
638 // If empty string it's just a variable, that'll be saved.
639 // Values NOT in this array will not be saved in the settings-array for the module.
640 $this->MOD_MENU = array(
641 'showPalettes' => ''
642 );
643 // Setting virtual document name
644 $this->MCONF['name'] = 'xMOD_alt_doc.php';
645 // CLEANSE SETTINGS
646 $this->MOD_SETTINGS = BackendUtility::getModuleData($this->MOD_MENU, GeneralUtility::_GP('SET'), $this->MCONF['name']);
647 // Create an instance of the document template object
648 $this->doc = $GLOBALS['TBE_TEMPLATE'];
649 $this->doc->backPath = $GLOBALS['BACK_PATH'];
650 $this->doc->setModuleTemplate('EXT:backend/Resources/Private/Templates/alt_doc.html');
651 $this->doc->form = '<form action="' . htmlspecialchars($this->R_URI) . '" method="post" enctype="' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['form_enctype'] . '" name="editform" onsubmit="document.editform._scrollPosition.value=(document.documentElement.scrollTop || document.body.scrollTop); return TBE_EDITOR.checkSubmit(1);">';
652 $this->doc->getPageRenderer()->loadPrototype();
653 // override the default jumpToUrl
654 $this->doc->JScodeArray['jumpToUrl'] = '
655 function jumpToUrl(URL,formEl) {
656 if (!TBE_EDITOR.isFormChanged()) {
657 window.location.href = URL;
658 } else if (formEl && formEl.type=="checkbox") {
659 formEl.checked = formEl.checked ? 0 : 1;
660 }
661 }
662 ';
663 $this->doc->JScode = $this->doc->wrapScriptTags('
664 // Object: TS:
665 // passwordDummy and decimalSign are used by tbe_editor.js and have to be declared here as
666 // TS object overwrites the object declared in tbe_editor.js
667 function typoSetup() { //
668 this.uniqueID = "";
669 this.passwordDummy = "********";
670 this.PATH_typo3 = " ";
671 this.decimalSign = ".";
672 }
673 var TS = new typoSetup();
674
675 // Info view:
676 function launchView(table,uid,bP) { //
677 var backPath= bP ? bP : "";
678 var thePreviewWindow="";
679 thePreviewWindow = window.open(backPath+"show_item.php?table="+encodeURIComponent(table)+"&uid="+encodeURIComponent(uid),"ShowItem"+TS.uniqueID,"height=300,width=410,status=0,menubar=0,resizable=0,location=0,directories=0,scrollbars=1,toolbar=0");
680 if (thePreviewWindow && thePreviewWindow.focus) {
681 thePreviewWindow.focus();
682 }
683 }
684 function deleteRecord(table,id,url) { //
685 if (
686 ' . ($GLOBALS['BE_USER']->jsConfirmation(4) ? 'confirm(' . GeneralUtility::quoteJSvalue($GLOBALS['LANG']->getLL('deleteWarning')) . ')' : '1==1') . '
687 ) {
688 window.location.href = ' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('tce_db') . '&cmd[') . '+table+"]["+id+"][delete]=1' . BackendUtility::getUrlToken('tceAction') . '&redirect="+escape(url)+"&vC=' . $GLOBALS['BE_USER']->veriCode() . '&prErr=1&uPT=1";
689 }
690 return false;
691 }
692 ' . (isset($_POST['_savedokview_x']) && $this->popViewId ? 'if (window.opener) { ' . BackendUtility::viewOnClick($this->popViewId, '', BackendUtility::BEgetRootLine($this->popViewId), '', $this->viewUrl, $this->popViewId_addParams, FALSE) . ' } else { ' . BackendUtility::viewOnClick($this->popViewId, '', BackendUtility::BEgetRootLine($this->popViewId), '', $this->viewUrl, $this->popViewId_addParams) . ' } ' : ''));
693 // Setting up the context sensitive menu:
694 $this->doc->getContextMenuCode();
695 $this->doc->bodyTagAdditions = 'onload="window.scrollTo(0,' . MathUtility::forceIntegerInRange(GeneralUtility::_GP('_scrollPosition'), 0, 10000) . ');"';
696
697 $this->emitFunctionAfterSignal(__FUNCTION__);
698 }
699
700 /**
701 * Main module operation
702 *
703 * @return void
704 */
705 public function main() {
706 // Begin edit:
707 if (is_array($this->editconf)) {
708 // Initialize TCEforms (rendering the forms)
709 $this->tceforms = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Form\FormEngine::class);
710 $this->tceforms->initDefaultBEMode();
711 $this->tceforms->doSaveFieldName = 'doSave';
712 $this->tceforms->localizationMode = GeneralUtility::inList('text,media', $this->localizationMode) ? $this->localizationMode : '';
713 // text,media is keywords defined in TYPO3 Core API..., see "l10n_cat"
714 $this->tceforms->returnUrl = $this->R_URI;
715 $this->tceforms->palettesCollapsed = !$this->MOD_SETTINGS['showPalettes'];
716 if ($this->editRegularContentFromId) {
717 $this->editRegularContentFromId();
718 }
719 // Creating the editing form, wrap it with buttons, document selector etc.
720 $editForm = $this->makeEditForm();
721 if ($editForm) {
722 $this->firstEl = reset($this->elementsData);
723 // Checking if the currently open document is stored in the list of "open documents" - if not, then add it:
724 if (($this->docDat[1] !== $this->storeUrlMd5 || !isset($this->docHandler[$this->storeUrlMd5])) && !$this->dontStoreDocumentRef) {
725 $this->docHandler[$this->storeUrlMd5] = array($this->storeTitle, $this->storeArray, $this->storeUrl, $this->firstEl);
726 $GLOBALS['BE_USER']->pushModuleData('alt_doc.php', array($this->docHandler, $this->storeUrlMd5));
727 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
728 }
729 // Module configuration
730 $this->modTSconfig = $this->viewId ? BackendUtility::getModTSconfig($this->viewId, 'mod.xMOD_alt_doc') : array();
731 $body = $this->tceforms->printNeededJSFunctions_top();
732 $body .= $this->compileForm($editForm);
733 $body .= $this->tceforms->printNeededJSFunctions();
734 $body .= $this->functionMenus();
735 }
736 }
737 // Access check...
738 // The page will show only if there is a valid page and if this page may be viewed by the user
739 $this->pageinfo = BackendUtility::readPageAccess($this->viewId, $this->perms_clause);
740 // Setting up the buttons and markers for docheader
741 $docHeaderButtons = $this->getButtons();
742 $markers = array(
743 'LANGSELECTOR' => $this->langSelector(),
744 'EXTRAHEADER' => $this->extraFormHeaders(),
745 'CSH' => $docHeaderButtons['csh'],
746 'CONTENT' => $body
747 );
748 // Build the <body> for the module
749 $this->content = $this->doc->startPage('TYPO3 Edit Document');
750 $this->content .= $this->doc->moduleBody($this->pageinfo, $docHeaderButtons, $markers);
751 $this->content .= $this->doc->endPage();
752 $this->content = $this->doc->insertStylesAndJS($this->content);
753 }
754
755 /**
756 * Outputting the accumulated content to screen
757 *
758 * @return void
759 */
760 public function printContent() {
761 echo $this->content;
762 }
763
764 /***************************
765 *
766 * Sub-content functions, rendering specific parts of the module content.
767 *
768 ***************************/
769 /**
770 * Creates the editing form with TCEforms, based on the input from GPvars.
771 *
772 * @return string HTML form elements wrapped in tables
773 */
774 public function makeEditForm() {
775 // Initialize variables:
776 $this->elementsData = array();
777 $this->errorC = 0;
778 $this->newC = 0;
779 $thePrevUid = '';
780 $editForm = '';
781 $trData = NULL;
782 // Traverse the GPvar edit array
783 // Tables:
784 foreach ($this->editconf as $table => $conf) {
785 if (is_array($conf) && $GLOBALS['TCA'][$table] && $GLOBALS['BE_USER']->check('tables_modify', $table)) {
786 // Traverse the keys/comments of each table (keys can be a commalist of uids)
787 foreach ($conf as $cKey => $cmd) {
788 if ($cmd == 'edit' || $cmd == 'new') {
789 // Get the ids:
790 $ids = GeneralUtility::trimExplode(',', $cKey, TRUE);
791 // Traverse the ids:
792 foreach ($ids as $theUid) {
793 // Checking if the user has permissions? (Only working as a precaution,
794 // because the final permission check is always down in TCE. But it's
795 // good to notify the user on beforehand...)
796 // First, resetting flags.
797 $hasAccess = 1;
798 $deniedAccessReason = '';
799 $deleteAccess = 0;
800 $this->viewId = 0;
801 // If the command is to create a NEW record...:
802 if ($cmd == 'new') {
803 // NOTICE: the id values in this case points to the page uid onto which the
804 // record should be create OR (if the id is negativ) to a record from the
805 // same table AFTER which to create the record.
806 if ((int)$theUid) {
807 // Find parent page on which the new record reside
808 // Less than zero - find parent page
809 if ($theUid < 0) {
810 $calcPRec = BackendUtility::getRecord($table, abs($theUid));
811 $calcPRec = BackendUtility::getRecord('pages', $calcPRec['pid']);
812 } else {
813 // always a page
814 $calcPRec = BackendUtility::getRecord('pages', abs($theUid));
815 }
816 // Now, calculate whether the user has access to creating new records on this position:
817 if (is_array($calcPRec)) {
818 // Permissions for the parent page
819 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
820 if ($table == 'pages') {
821 // If pages:
822 $hasAccess = $CALC_PERMS & 8 ? 1 : 0;
823 $this->viewId = 0;
824 } else {
825 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
826 $this->viewId = $calcPRec['uid'];
827 }
828 }
829 }
830 // Don't save this document title in the document selector if the document is new.
831 $this->dontStoreDocumentRef = 1;
832 } else {
833 // Edit:
834 $calcPRec = BackendUtility::getRecord($table, $theUid);
835 BackendUtility::fixVersioningPid($table, $calcPRec);
836 if (is_array($calcPRec)) {
837 if ($table == 'pages') { // If pages:
838 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
839 $hasAccess = $CALC_PERMS & 2 ? 1 : 0;
840 $deleteAccess = $CALC_PERMS & 4 ? 1 : 0;
841 $this->viewId = $calcPRec['uid'];
842 } else {
843 // Fetching pid-record first
844 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(BackendUtility::getRecord('pages', $calcPRec['pid']));
845 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
846 $deleteAccess = $CALC_PERMS & 16 ? 1 : 0;
847 $this->viewId = $calcPRec['pid'];
848 // Adding "&L=xx" if the record being edited has a languageField with a value larger than zero!
849 if ($GLOBALS['TCA'][$table]['ctrl']['languageField'] && $calcPRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
850 $this->viewId_addParams = '&L=' . $calcPRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
851 }
852 }
853 // Check internals regarding access:
854 $isRootLevelRestrictionIgnored = BackendUtility::isRootLevelRestrictionIgnored($table);
855 if ($hasAccess || (string)$calcPRec['pid'] === '0' && $isRootLevelRestrictionIgnored) {
856 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
857 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
858 }
859 } else {
860 $hasAccess = 0;
861 }
862 }
863 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/alt_doc.php']['makeEditForm_accessCheck'])) {
864 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/alt_doc.php']['makeEditForm_accessCheck'] as $_funcRef) {
865 $_params = array(
866 'table' => $table,
867 'uid' => $theUid,
868 'cmd' => $cmd,
869 'hasAccess' => $hasAccess
870 );
871 $hasAccess = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
872 }
873 }
874 // AT THIS POINT we have checked the access status of the editing/creation of
875 // records and we can now proceed with creating the form elements:
876 if ($hasAccess) {
877 $prevPageID = is_object($trData) ? $trData->prevPageID : '';
878 $trData = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Form\DataPreprocessor::class);
879 $trData->addRawData = TRUE;
880 $trData->defVals = $this->defVals;
881 $trData->lockRecords = 1;
882 $trData->prevPageID = $prevPageID;
883 // 'new'
884 $trData->fetchRecord($table, $theUid, $cmd == 'new' ? 'new' : '');
885 $rec = reset($trData->regTableItems_data);
886 $rec['uid'] = $cmd == 'new' ? uniqid('NEW', TRUE) : $theUid;
887 if ($cmd == 'new') {
888 $rec['pid'] = $theUid == 'prev' ? $thePrevUid : $theUid;
889 }
890 $this->elementsData[] = array(
891 'table' => $table,
892 'uid' => $rec['uid'],
893 'pid' => $rec['pid'],
894 'cmd' => $cmd,
895 'deleteAccess' => $deleteAccess
896 );
897 // Now, render the form:
898 if (is_array($rec)) {
899 // Setting visual path / title of form:
900 $this->generalPathOfForm = $this->tceforms->getRecordPath($table, $rec);
901 if (!$this->storeTitle) {
902 $this->storeTitle = $this->recTitle ? htmlspecialchars($this->recTitle) : BackendUtility::getRecordTitle($table, $rec, TRUE);
903 }
904 // Setting variables in TCEforms object:
905 $this->tceforms->hiddenFieldList = '';
906 if (is_array($this->overrideVals) && is_array($this->overrideVals[$table])) {
907 $this->tceforms->hiddenFieldListArr = array_keys($this->overrideVals[$table]);
908 }
909 // Register default language labels, if any:
910 $this->tceforms->registerDefaultLanguageData($table, $rec);
911 // Create form for the record (either specific list of fields or the whole record):
912 $panel = '';
913 if ($this->columnsOnly) {
914 if (is_array($this->columnsOnly)) {
915 $panel .= $this->tceforms->getListedFields($table, $rec, $this->columnsOnly[$table]);
916 } else {
917 $panel .= $this->tceforms->getListedFields($table, $rec, $this->columnsOnly);
918 }
919 } else {
920 $panel .= $this->tceforms->getMainFields($table, $rec);
921 }
922 $panel = $this->tceforms->wrapTotal($panel, $rec, $table);
923 // Setting the pid value for new records:
924 if ($cmd == 'new') {
925 $panel .= '<input type="hidden" name="data[' . $table . '][' . $rec['uid'] . '][pid]" value="' . $rec['pid'] . '" />';
926 $this->newC++;
927 }
928 // Display "is-locked" message:
929 if ($lockInfo = BackendUtility::isRecordLocked($table, $rec['uid'])) {
930 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, htmlspecialchars($lockInfo['msg']), '', \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING);
931 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
932 $flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
933 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
934 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
935 $defaultFlashMessageQueue->enqueue($flashMessage);
936 }
937 // Combine it all:
938 $editForm .= $panel;
939 }
940 $thePrevUid = $rec['uid'];
941 } else {
942 $this->errorC++;
943 $editForm .= $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.noEditPermission', TRUE) . '<br /><br />' . ($deniedAccessReason ? 'Reason: ' . htmlspecialchars($deniedAccessReason) . '<br /><br />' : '');
944 }
945 }
946 }
947 }
948 }
949 }
950 return $editForm;
951 }
952
953 /**
954 * Create the panel of buttons for submitting the form or otherwise perform operations.
955 *
956 * @return array All available buttons as an assoc. array
957 */
958 protected function getButtons() {
959 $buttons = array(
960 'save' => '',
961 'save_view' => '',
962 'save_new' => '',
963 'save_close' => '',
964 'close' => '',
965 'delete' => '',
966 'undo' => '',
967 'history' => '',
968 'columns_only' => '',
969 'csh' => '',
970 'translation_save' => '',
971 'translation_saveclear' => ''
972 );
973 // Render SAVE type buttons:
974 // The action of each button is decided by its name attribute. (See doProcessData())
975 if (!$this->errorC && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly']) {
976 // SAVE button:
977 $buttons['save'] = IconUtility::getSpriteIcon('actions-document-save', array('html' => '<input type="image" name="_savedok" class="c-inputButton" src="clear.gif" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:rm.saveDoc', TRUE) . '" />'));
978 // SAVE / VIEW button:
979 if ($this->viewId && !$this->noView && $this->getNewIconMode($this->firstEl['table'], 'saveDocView')) {
980 $buttons['save_view'] = IconUtility::getSpriteIcon('actions-document-save-view', array('html' => '<input onclick="window.open(\'\', \'newTYPO3frontendWindow\');" type="image" class="c-inputButton" name="_savedokview" src="clear.gif" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:rm.saveDocShow', TRUE) . '" />'));
981 }
982 // SAVE / NEW button:
983 if (count($this->elementsData) == 1 && $this->getNewIconMode($this->firstEl['table'])) {
984 $buttons['save_new'] = IconUtility::getSpriteIcon('actions-document-save-new', array('html' => '<input type="image" class="c-inputButton" name="_savedoknew" src="clear.gif" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:rm.saveNewDoc', TRUE) . '" />'));
985 }
986 // SAVE / CLOSE
987 $buttons['save_close'] = IconUtility::getSpriteIcon('actions-document-save-close', array('html' => '<input type="image" class="c-inputButton" name="_saveandclosedok" src="clear.gif" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:rm.saveCloseDoc', TRUE) . '" />'));
988 // FINISH TRANSLATION / SAVE / CLOSE
989 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation']) {
990 $buttons['translation_save'] = '<input type="image" class="c-inputButton" name="_translation_savedok" src="' . IconUtility::skinImg($this->doc->backPath, 'sysext/t3skin/images/icons/actions/document-save-translation.png', '', 1) . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:rm.translationSaveDoc', TRUE) . '" /> ';
991 $buttons['translation_saveclear'] = '<input type="image" class="c-inputButton" name="_translation_savedokclear" src="' . IconUtility::skinImg($this->doc->backPath, 'sysext/t3skin/images/icons/actions/document-save-cleartranslationcache.png', '', 1) . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:rm.translationSaveDocClear', TRUE) . '" />';
992 }
993 }
994 // CLOSE button:
995 $buttons['close'] = '<a href="#" onclick="document.editform.closeDoc.value=1; document.editform.submit(); return false;" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:rm.closeDoc', TRUE) . '">' . IconUtility::getSpriteIcon('actions-document-close') . '</a>';
996 // DELETE + UNDO buttons:
997 if (!$this->errorC && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly'] && count($this->elementsData) == 1) {
998 if ($this->firstEl['cmd'] != 'new' && MathUtility::canBeInterpretedAsInteger($this->firstEl['uid'])) {
999 // Delete:
1000 if ($this->firstEl['deleteAccess'] && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly'] && !$this->getNewIconMode($this->firstEl['table'], 'disableDelete')) {
1001 $aOnClick = 'return deleteRecord(\'' . $this->firstEl['table'] . '\',\'' . $this->firstEl['uid'] . '\', unescape(\'' . rawurlencode($this->retUrl) . '\'));';
1002 $buttons['delete'] = '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '" title="' . $GLOBALS['LANG']->getLL('deleteItem', TRUE) . '">' . IconUtility::getSpriteIcon('actions-edit-delete') . '</a>';
1003 }
1004 // Undo:
1005 $undoRes = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tstamp', 'sys_history', 'tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->firstEl['table'], 'sys_history') . ' AND recuid=' . (int)$this->firstEl['uid'], '', 'tstamp DESC', '1');
1006 if ($undoButtonR = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($undoRes)) {
1007 $aOnClick = 'window.location.href=' .
1008 GeneralUtility::quoteJSvalue(
1009 BackendUtility::getModuleUrl(
1010 'record_history',
1011 array(
1012 'element' => $this->firstEl['table'] . ':' . $this->firstEl['uid'],
1013 'revert' => 'ALL_FIELDS',
1014 'sumUp' => -1,
1015 'returnUrl' => $this->R_URI,
1016 )
1017 )
1018 ) . '; return false;';
1019 $buttons['undo'] = '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '"' . ' title="' . htmlspecialchars(sprintf($GLOBALS['LANG']->getLL('undoLastChange'), BackendUtility::calcAge(($GLOBALS['EXEC_TIME'] - $undoButtonR['tstamp']), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.minutesHoursDaysYears')))) . '">' . IconUtility::getSpriteIcon('actions-edit-undo') . '</a>';
1020 }
1021 if ($this->getNewIconMode($this->firstEl['table'], 'showHistory')) {
1022 $aOnClick = 'window.location.href=' .
1023 GeneralUtility::quoteJSvalue(
1024 BackendUtility::getModuleUrl(
1025 'record_history',
1026 array(
1027 'element' => $this->firstEl['table'] . ':' . $this->firstEl['uid'],
1028 'returnUrl' => $this->R_URI,
1029 )
1030 )
1031 ) . '; return false;';
1032 $buttons['history'] = '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '">' . IconUtility::getSpriteIcon('actions-document-history-open') . '</a>';
1033 }
1034 // If only SOME fields are shown in the form, this will link the user to the FULL form:
1035 if ($this->columnsOnly) {
1036 $buttons['columns_only'] = '<a href="' . htmlspecialchars(($this->R_URI . '&columnsOnly=')) . '" title="' . $GLOBALS['LANG']->getLL('editWholeRecord', TRUE) . '">' . IconUtility::getSpriteIcon('actions-document-open') . '</a>';
1037 }
1038 }
1039 }
1040 // add the CSH icon
1041 $buttons['csh'] = BackendUtility::cshItem('xMOD_csh_corebe', 'TCEforms');
1042 $buttons['shortcut'] = $this->shortCutLink();
1043 $buttons['open_in_new_window'] = $this->openInNewWindowLink();
1044 return $buttons;
1045 }
1046
1047 /**
1048 * Returns the language switch/selector for editing,
1049 * show only when a single record is edited
1050 * - multiple records are too confusing
1051 *
1052 * @return string The HTML
1053 */
1054 public function langSelector() {
1055 $langSelector = '';
1056 if (count($this->elementsData) == 1) {
1057 $langSelector = $this->languageSwitch($this->firstEl['table'], $this->firstEl['uid'], $this->firstEl['pid']);
1058 }
1059 return $langSelector;
1060 }
1061
1062 /**
1063 * Compiles the extra form headers if the tceforms
1064 *
1065 * @return string The HTML
1066 */
1067 public function extraFormHeaders() {
1068 $extraTemplate = '';
1069 if (is_array($this->tceforms->extraFormHeaders)) {
1070 $extraTemplate = HtmlParser::getSubpart($this->doc->moduleTemplate, '###DOCHEADER_EXTRAHEADER###');
1071 $extraTemplate = HtmlParser::substituteMarker($extraTemplate, '###EXTRAHEADER###', implode(LF, $this->tceforms->extraFormHeaders));
1072 }
1073 return $extraTemplate;
1074 }
1075
1076 /**
1077 * Put together the various elements (buttons, selectors, form) into a table
1078 *
1079 * @param string $editForm HTML form.
1080 * @return string Composite HTML
1081 */
1082 public function compileForm($editForm) {
1083 $formContent = '
1084 <!-- EDITING FORM -->
1085 ' . $editForm . '
1086
1087 <input type="hidden" name="returnUrl" value="' . htmlspecialchars($this->retUrl) . '" />
1088 <input type="hidden" name="viewUrl" value="' . htmlspecialchars($this->viewUrl) . '" />';
1089 if ($this->returnNewPageId) {
1090 $formContent .= '<input type="hidden" name="returnNewPageId" value="1" />';
1091 }
1092 $formContent .= '<input type="hidden" name="popViewId" value="' . htmlspecialchars($this->viewId) . '" />';
1093 if ($this->viewId_addParams) {
1094 $formContent .= '<input type="hidden" name="popViewId_addParams" value="' . htmlspecialchars($this->viewId_addParams) . '" />';
1095 }
1096 $formContent .= '
1097 <input type="hidden" name="closeDoc" value="0" />
1098 <input type="hidden" name="doSave" value="0" />
1099 <input type="hidden" name="_serialNumber" value="' . md5(microtime()) . '" />
1100 <input type="hidden" name="_scrollPosition" value="" />' . FormEngine::getHiddenTokenField('editRecord');
1101 return $formContent;
1102 }
1103
1104 /**
1105 * Create the checkbox buttons in the bottom of the pages.
1106 *
1107 * @return string HTML for function menus.
1108 */
1109 public function functionMenus() {
1110 if ($GLOBALS['BE_USER']->getTSConfigVal('options.enableShowPalettes')) {
1111 // Show palettes:
1112
1113 return '<div class="checkbox">' .
1114 '<label for="checkShowPalettes">' .
1115 BackendUtility::getFuncCheck('', 'SET[showPalettes]', $this->MOD_SETTINGS['showPalettes'], 'alt_doc.php', (GeneralUtility::implodeArrayForUrl('', array_merge($this->R_URL_getvars, array('SET' => ''))) . BackendUtility::getUrlToken('editRecord')), 'id="checkShowPalettes"') .
1116 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.showPalettes', TRUE) .
1117 '</label>'.
1118 '</div>';
1119 } else {
1120 return '';
1121 }
1122 }
1123
1124 /**
1125 * Create shortcut icon
1126 *
1127 * @return string
1128 */
1129 public function shortCutLink() {
1130 if ($this->returnUrl == 'close.html' || !$GLOBALS['BE_USER']->mayMakeShortcut()) {
1131 return '';
1132 }
1133 return $this->doc->makeShortcutIcon('returnUrl,edit,defVals,overrideVals,columnsOnly,returnNewPageId,editRegularContentFromId,noView', implode(',', array_keys($this->MOD_MENU)), $this->MCONF['name'], 1);
1134 }
1135
1136 /**
1137 * Creates open-in-window link
1138 *
1139 * @return string
1140 */
1141 public function openInNewWindowLink() {
1142 if ($this->returnUrl == 'close.html') {
1143 return '';
1144 }
1145 $aOnClick = 'vHWin=window.open(' . GeneralUtility::quoteJSvalue(GeneralUtility::linkThisScript(array('returnUrl' => 'close.html'))) . ',\'' . md5($this->R_URI) . '\',\'width=670,height=500,status=0,menubar=0,scrollbars=1,resizable=1\');vHWin.focus();return false;';
1146 return '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.openInNewWindow', TRUE) . '">' . IconUtility::getSpriteIcon('actions-window-open') . '</a>';
1147 }
1148
1149 /**
1150 * Reads comment messages from TCEforms and prints them in a HTML comment in the bottom of the page.
1151 *
1152 * @return string
1153 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1154 */
1155 public function tceformMessages() {
1156 GeneralUtility::logDeprecatedFunction();
1157 return '';
1158 }
1159
1160 /***************************
1161 *
1162 * Localization stuff
1163 *
1164 ***************************/
1165 /**
1166 * Make selector box for creating new translation for a record or switching to edit the record in an existing language.
1167 * Displays only languages which are available for the current page.
1168 *
1169 * @param string $table Table name
1170 * @param int $uid Uid for which to create a new language
1171 * @param int $pid Pid of the record
1172 * @return string <select> HTML element (if there were items for the box anyways...)
1173 */
1174 public function languageSwitch($table, $uid, $pid = NULL) {
1175 $content = '';
1176 $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1177 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1178 // Table editable and activated for languages?
1179 if ($GLOBALS['BE_USER']->check('tables_modify', $table) && $languageField && $transOrigPointerField && !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) {
1180 if (is_null($pid)) {
1181 $row = BackendUtility::getRecord($table, $uid, 'pid');
1182 $pid = $row['pid'];
1183 }
1184 // Get all avalibale languages for the page
1185 $langRows = $this->getLanguages($pid);
1186 // Page available in other languages than default language?
1187 if (is_array($langRows) && count($langRows) > 1) {
1188 $rowsByLang = array();
1189 $fetchFields = 'uid,' . $languageField . ',' . $transOrigPointerField;
1190 // Get record in current language
1191 $rowCurrent = BackendUtility::getLiveVersionOfRecord($table, $uid, $fetchFields);
1192 if (!is_array($rowCurrent)) {
1193 $rowCurrent = BackendUtility::getRecord($table, $uid, $fetchFields);
1194 }
1195 $currentLanguage = $rowCurrent[$languageField];
1196 // Disabled for records with [all] language!
1197 if ($currentLanguage > -1) {
1198 // Get record in default language if needed
1199 if ($currentLanguage && $rowCurrent[$transOrigPointerField]) {
1200 $rowsByLang[0] = BackendUtility::getLiveVersionOfRecord($table, $rowCurrent[$transOrigPointerField], $fetchFields);
1201 if (!is_array($rowsByLang[0])) {
1202 $rowsByLang[0] = BackendUtility::getRecord($table, $rowCurrent[$transOrigPointerField], $fetchFields);
1203 }
1204 } else {
1205 $rowsByLang[$rowCurrent[$languageField]] = $rowCurrent;
1206 }
1207 if ($rowCurrent[$transOrigPointerField] || $currentLanguage === '0') {
1208 // Get record in other languages to see what's already available
1209 $translations = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows($fetchFields, $table, 'pid=' . (int)$pid . ' AND ' . $languageField . '>0' . ' AND ' . $transOrigPointerField . '=' . (int)$rowsByLang[0]['uid'] . BackendUtility::deleteClause($table) . BackendUtility::versioningPlaceholderClause($table));
1210 foreach ($translations as $row) {
1211 $rowsByLang[$row[$languageField]] = $row;
1212 }
1213 }
1214 $langSelItems = array();
1215 foreach ($langRows as $lang) {
1216 if ($GLOBALS['BE_USER']->checkLanguageAccess($lang['uid'])) {
1217 $newTranslation = isset($rowsByLang[$lang['uid']]) ? '' : ' [' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.new', TRUE) . ']';
1218 // Create url for creating a localized record
1219 if ($newTranslation) {
1220 $href = $this->doc->issueCommand('&cmd[' . $table . '][' . $rowsByLang[0]['uid'] . '][localize]=' . $lang['uid'], $this->backPath . 'alt_doc.php?justLocalized=' . rawurlencode(($table . ':' . $rowsByLang[0]['uid'] . ':' . $lang['uid'])) . '&returnUrl=' . rawurlencode($this->retUrl) . BackendUtility::getUrlToken('editRecord'));
1221 } else {
1222 $href = $this->backPath . 'alt_doc.php?';
1223 $href .= '&edit[' . $table . '][' . $rowsByLang[$lang['uid']]['uid'] . ']=edit';
1224 $href .= '&returnUrl=' . rawurlencode($this->retUrl) . BackendUtility::getUrlToken('editRecord');
1225 }
1226 $langSelItems[$lang['uid']] = '
1227 <option value="' . htmlspecialchars($href) . '"' . ($currentLanguage == $lang['uid'] ? ' selected="selected"' : '') . '>' . htmlspecialchars(($lang['title'] . $newTranslation)) . '</option>';
1228 }
1229 }
1230 // If any languages are left, make selector:
1231 if (count($langSelItems) > 1) {
1232 $onChange = 'if(this.options[this.selectedIndex].value){window.location.href=(this.options[this.selectedIndex].value);}';
1233 $content = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_general.xlf:LGL.language', TRUE) . ' <select name="_langSelector" onchange="' . htmlspecialchars($onChange) . '">
1234 ' . implode('', $langSelItems) . '
1235 </select>';
1236 }
1237 }
1238 }
1239 }
1240 return $content;
1241 }
1242
1243 /**
1244 * Redirects to alt_doc with new parameters to edit a just created localized record
1245 *
1246 * @param string $justLocalized String passed by GET &justLocalized=
1247 * @return void
1248 */
1249 public function localizationRedirect($justLocalized) {
1250 list($table, $orig_uid, $language) = explode(':', $justLocalized);
1251 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
1252 $localizedRecord = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('uid', $table, $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '=' . (int)$language . ' AND ' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] . '=' . (int)$orig_uid . BackendUtility::deleteClause($table) . BackendUtility::versioningPlaceholderClause($table));
1253 if (is_array($localizedRecord)) {
1254 // Create parameters and finally run the classic page module for creating a new page translation
1255 $params = '&edit[' . $table . '][' . $localizedRecord['uid'] . ']=edit';
1256 $returnUrl = '&returnUrl=' . rawurlencode(GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl')));
1257 $location = $GLOBALS['BACK_PATH'] . 'alt_doc.php?' . $params . $returnUrl . BackendUtility::getUrlToken('editRecord');
1258 HttpUtility::redirect($location);
1259 }
1260 }
1261 }
1262
1263 /**
1264 * Returns sys_language records available for record translations on given page.
1265 *
1266 * @param int $id Page id: If zero, the query will select all sys_language records from root level which are NOT hidden. If set to another value, the query will select all sys_language records that has a pages_language_overlay record on that page (and is not hidden, unless you are admin user)
1267 * @return array Language records including faked record for default language
1268 */
1269 public function getLanguages($id) {
1270 $modSharedTSconfig = BackendUtility::getModTSconfig($id, 'mod.SHARED');
1271 // Fallback non sprite-configuration
1272 if (preg_match('/\\.gif$/', $modSharedTSconfig['properties']['defaultLanguageFlag'])) {
1273 $modSharedTSconfig['properties']['defaultLanguageFlag'] = str_replace('.gif', '', $modSharedTSconfig['properties']['defaultLanguageFlag']);
1274 }
1275 $languages = array(
1276 0 => array(
1277 'uid' => 0,
1278 'pid' => 0,
1279 'hidden' => 0,
1280 'title' => $modSharedTSconfig['properties']['defaultLanguageLabel'] !== ''
1281 ? $modSharedTSconfig['properties']['defaultLanguageLabel'] . ' (' . $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_mod_web_list.xlf:defaultLanguage') . ')'
1282 : $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_mod_web_list.xlf:defaultLanguage'),
1283 'flag' => $modSharedTSconfig['properties']['defaultLanguageFlag']
1284 )
1285 );
1286 $exQ = $GLOBALS['BE_USER']->isAdmin() ? '' : ' AND sys_language.hidden=0';
1287 if ($id) {
1288 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('sys_language.*', 'pages_language_overlay,sys_language', 'pages_language_overlay.sys_language_uid=sys_language.uid AND pages_language_overlay.pid=' . (int)$id . BackendUtility::deleteClause('pages_language_overlay') . $exQ, 'pages_language_overlay.sys_language_uid,sys_language.uid,sys_language.pid,sys_language.tstamp,sys_language.hidden,sys_language.title,sys_language.language_isocode,sys_language.static_lang_isocode,sys_language.flag', 'sys_language.title');
1289 } else {
1290 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('sys_language.*', 'sys_language', 'sys_language.hidden=0', '', 'sys_language.title');
1291 }
1292 if ($rows) {
1293 foreach ($rows as $row) {
1294 $languages[$row['uid']] = $row;
1295 }
1296 }
1297 return $languages;
1298 }
1299
1300 /***************************
1301 *
1302 * Other functions
1303 *
1304 ***************************/
1305 /**
1306 * Fix $this->editconf if versioning applies to any of the records
1307 *
1308 * @param array $mapArray Mapping between old and new ids if auto-versioning has been performed.
1309 * @return void
1310 */
1311 public function fixWSversioningInEditConf($mapArray = FALSE) {
1312 // Traverse the editConf array
1313 if (is_array($this->editconf)) {
1314 // Tables:
1315 foreach ($this->editconf as $table => $conf) {
1316 if (is_array($conf) && $GLOBALS['TCA'][$table]) {
1317 // Traverse the keys/comments of each table (keys can be a commalist of uids)
1318 $newConf = array();
1319 foreach ($conf as $cKey => $cmd) {
1320 if ($cmd == 'edit') {
1321 // Traverse the ids:
1322 $ids = GeneralUtility::trimExplode(',', $cKey, TRUE);
1323 foreach ($ids as $idKey => $theUid) {
1324 if (is_array($mapArray)) {
1325 if ($mapArray[$table][$theUid]) {
1326 $ids[$idKey] = $mapArray[$table][$theUid];
1327 }
1328 } else {
1329 // Default, look for versions in workspace for record:
1330 $calcPRec = $this->getRecordForEdit($table, $theUid);
1331 if (is_array($calcPRec)) {
1332 // Setting UID again if it had changed, eg. due to workspace versioning.
1333 $ids[$idKey] = $calcPRec['uid'];
1334 }
1335 }
1336 }
1337 // Add the possibly manipulated IDs to the new-build newConf array:
1338 $newConf[implode(',', $ids)] = $cmd;
1339 } else {
1340 $newConf[$cKey] = $cmd;
1341 }
1342 }
1343 // Store the new conf array:
1344 $this->editconf[$table] = $newConf;
1345 }
1346 }
1347 }
1348 }
1349
1350 /**
1351 * Get record for editing.
1352 *
1353 * @param string $table Table name
1354 * @param int $theUid Record UID
1355 * @return array Returns record to edit, FALSE if none
1356 */
1357 public function getRecordForEdit($table, $theUid) {
1358 // Fetch requested record:
1359 $reqRecord = BackendUtility::getRecord($table, $theUid, 'uid,pid');
1360 if (is_array($reqRecord)) {
1361 // If workspace is OFFLINE:
1362 if ($GLOBALS['BE_USER']->workspace != 0) {
1363 // Check for versioning support of the table:
1364 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1365 // If the record is already a version of "something" pass it by.
1366 if ($reqRecord['pid'] == -1) {
1367 // (If it turns out not to be a version of the current workspace there will be trouble, but that is handled inside TCEmain then and in the interface it would clearly be an error of links if the user accesses such a scenario)
1368 return $reqRecord;
1369 } else {
1370 // The input record was online and an offline version must be found or made:
1371 // Look for version of this workspace:
1372 $versionRec = BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $reqRecord['uid'], 'uid,pid,t3ver_oid');
1373 return is_array($versionRec) ? $versionRec : $reqRecord;
1374 }
1375 } else {
1376 // This means that editing cannot occur on this record because it was not supporting versioning which is required inside an offline workspace.
1377 return FALSE;
1378 }
1379 } else {
1380 // In ONLINE workspace, just return the originally requested record:
1381 return $reqRecord;
1382 }
1383 } else {
1384 // Return FALSE because the table/uid was not found anyway.
1385 return FALSE;
1386 }
1387 }
1388
1389 /**
1390 * Function, which populates the internal editconf array with editing commands for all tt_content elements from the normal column in normal language from the page pointed to by $this->editRegularContentFromId
1391 *
1392 * @return void
1393 */
1394 public function editRegularContentFromId() {
1395 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'tt_content', 'pid=' . (int)$this->editRegularContentFromId . BackendUtility::deleteClause('tt_content') . BackendUtility::versioningPlaceholderClause('tt_content') . ' AND colPos=0 AND sys_language_uid=0', '', 'sorting');
1396 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1397 $ecUids = array();
1398 while ($ecRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1399 $ecUids[] = $ecRec['uid'];
1400 }
1401 $this->editconf['tt_content'][implode(',', $ecUids)] = 'edit';
1402 }
1403 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1404 }
1405
1406 /**
1407 * Populates the variables $this->storeArray, $this->storeUrl, $this->storeUrlMd5
1408 *
1409 * @return void
1410 * @see makeDocSel()
1411 */
1412 public function compileStoreDat() {
1413 $this->storeArray = GeneralUtility::compileSelectedGetVarsFromArray('edit,defVals,overrideVals,columnsOnly,noView,editRegularContentFromId,workspace', $this->R_URL_getvars);
1414 $this->storeUrl = GeneralUtility::implodeArrayForUrl('', $this->storeArray);
1415 $this->storeUrlMd5 = md5($this->storeUrl);
1416 }
1417
1418 /**
1419 * Function used to look for configuration of buttons in the form: Fx. disabling buttons or showing them at various positions.
1420 *
1421 * @param string $table The table for which the configuration may be specific
1422 * @param string $key The option for look for. Default is checking if the saveDocNew button should be displayed.
1423 * @return string Return value fetched from USER TSconfig
1424 */
1425 public function getNewIconMode($table, $key = 'saveDocNew') {
1426 $TSconfig = $GLOBALS['BE_USER']->getTSConfig('options.' . $key);
1427 $output = trim(isset($TSconfig['properties'][$table]) ? $TSconfig['properties'][$table] : $TSconfig['value']);
1428 return $output;
1429 }
1430
1431 /**
1432 * Handling the closing of a document
1433 *
1434 * @param int $code Close code: 0/1 will redirect to $this->retUrl, 3 will clear the docHandler (thus closing all documents) and otehr values will call setDocument with ->retUrl
1435 * @return void
1436 */
1437 public function closeDocument($code = 0) {
1438 // If current document is found in docHandler,
1439 // then unset it, possibly unset it ALL and finally, write it to the session data
1440 if (isset($this->docHandler[$this->storeUrlMd5])) {
1441 // add the closing document to the recent documents
1442 $recentDocs = $GLOBALS['BE_USER']->getModuleData('opendocs::recent');
1443 if (!is_array($recentDocs)) {
1444 $recentDocs = array();
1445 }
1446 $closedDoc = $this->docHandler[$this->storeUrlMd5];
1447 $recentDocs = array_merge(array($this->storeUrlMd5 => $closedDoc), $recentDocs);
1448 if (count($recentDocs) > 8) {
1449 $recentDocs = array_slice($recentDocs, 0, 8);
1450 }
1451 // remove it from the list of the open documents
1452 unset($this->docHandler[$this->storeUrlMd5]);
1453 if ($code == '3') {
1454 $recentDocs = array_merge($this->docHandler, $recentDocs);
1455 $this->docHandler = array();
1456 }
1457 $GLOBALS['BE_USER']->pushModuleData('opendocs::recent', $recentDocs);
1458 $GLOBALS['BE_USER']->pushModuleData('alt_doc.php', array($this->docHandler, $this->docDat[1]));
1459 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
1460 }
1461 // If ->returnEditConf is set, then add the current content of editconf to the ->retUrl variable: (used by other scripts, like wizard_add, to know which records was created or so...)
1462 if ($this->returnEditConf && $this->retUrl != 'dummy.php') {
1463 $this->retUrl .= '&returnEditConf=' . rawurlencode(json_encode($this->editconf));
1464 }
1465 // If code is NOT set OR set to 1, then make a header location redirect to $this->retUrl
1466 if (!$code || $code == 1) {
1467 HttpUtility::redirect($this->retUrl);
1468 } else {
1469 $this->setDocument('', $this->retUrl);
1470 }
1471 }
1472
1473 /**
1474 * Redirects to the document pointed to by $currentDocFromHandlerMD5 OR $retUrl (depending on some internal calculations).
1475 * Most likely you will get a header-location redirect from this function.
1476 *
1477 * @param string $currentDocFromHandlerMD5 Pointer to the document in the docHandler array
1478 * @param string $retUrl Alternative/Default retUrl
1479 * @return void
1480 */
1481 public function setDocument($currentDocFromHandlerMD5 = '', $retUrl = 'dummy.php') {
1482 if ($retUrl === 'dummy.php') {
1483 return;
1484 }
1485 if (!$this->modTSconfig['properties']['disableDocSelector'] && is_array($this->docHandler) && count($this->docHandler)) {
1486 if (isset($this->docHandler[$currentDocFromHandlerMD5])) {
1487 $setupArr = $this->docHandler[$currentDocFromHandlerMD5];
1488 } else {
1489 $setupArr = reset($this->docHandler);
1490 }
1491 if ($setupArr[2]) {
1492 $sParts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
1493 $retUrl = $sParts['path'] . '?' . $setupArr[2] . '&returnUrl=' . rawurlencode($retUrl);
1494 }
1495 }
1496 HttpUtility::redirect($retUrl);
1497 }
1498
1499 /**
1500 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1501 */
1502 protected function getBackendUser() {
1503 return $GLOBALS['BE_USER'];
1504 }
1505
1506 }