[BUGFIX] Browse for records in edit document popup works again
[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 // define the window size of the element browser
664 $popupWindowWidth = 700;
665 $popupWindowHeight = 750;
666 $popupWindowSize = trim($GLOBALS['BE_USER']->getTSConfigVal('options.popupWindowSize'));
667 if (!empty($popupWindowSize)) {
668 list($popupWindowWidth, $popupWindowHeight) = GeneralUtility::intExplode('x', $popupWindowSize);
669 }
670 $t3Configuration = array(
671 'PopupWindow' => array(
672 'width' => $popupWindowWidth,
673 'height' => $popupWindowHeight
674 ),
675 );
676 $this->doc->JScode = $this->doc->wrapScriptTags('
677 TYPO3.configuration = ' . json_encode($t3Configuration) . ';
678 // Object: TS:
679 // passwordDummy and decimalSign are used by tbe_editor.js and have to be declared here as
680 // TS object overwrites the object declared in tbe_editor.js
681 function typoSetup() { //
682 this.uniqueID = "";
683 this.passwordDummy = "********";
684 this.PATH_typo3 = " ";
685 this.decimalSign = ".";
686 }
687 var TS = new typoSetup();
688
689 // Info view:
690 function launchView(table,uid,bP) { //
691 var backPath= bP ? bP : "";
692 var thePreviewWindow="";
693 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");
694 if (thePreviewWindow && thePreviewWindow.focus) {
695 thePreviewWindow.focus();
696 }
697 }
698 function deleteRecord(table,id,url) { //
699 if (
700 ' . ($GLOBALS['BE_USER']->jsConfirmation(4) ? 'confirm(' . GeneralUtility::quoteJSvalue($GLOBALS['LANG']->getLL('deleteWarning')) . ')' : '1==1') . '
701 ) {
702 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";
703 }
704 return false;
705 }
706 ' . (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) . ' } ' : ''));
707 // Setting up the context sensitive menu:
708 $this->doc->getContextMenuCode();
709 $this->doc->bodyTagAdditions = 'onload="window.scrollTo(0,' . MathUtility::forceIntegerInRange(GeneralUtility::_GP('_scrollPosition'), 0, 10000) . ');"';
710
711 $this->emitFunctionAfterSignal(__FUNCTION__);
712 }
713
714 /**
715 * Main module operation
716 *
717 * @return void
718 */
719 public function main() {
720 // Begin edit:
721 if (is_array($this->editconf)) {
722 // Initialize TCEforms (rendering the forms)
723 $this->tceforms = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Form\FormEngine::class);
724 $this->tceforms->initDefaultBEMode();
725 $this->tceforms->doSaveFieldName = 'doSave';
726 $this->tceforms->localizationMode = GeneralUtility::inList('text,media', $this->localizationMode) ? $this->localizationMode : '';
727 // text,media is keywords defined in TYPO3 Core API..., see "l10n_cat"
728 $this->tceforms->returnUrl = $this->R_URI;
729 $this->tceforms->palettesCollapsed = !$this->MOD_SETTINGS['showPalettes'];
730 if ($this->editRegularContentFromId) {
731 $this->editRegularContentFromId();
732 }
733 // Creating the editing form, wrap it with buttons, document selector etc.
734 $editForm = $this->makeEditForm();
735 if ($editForm) {
736 $this->firstEl = reset($this->elementsData);
737 // Checking if the currently open document is stored in the list of "open documents" - if not, then add it:
738 if (($this->docDat[1] !== $this->storeUrlMd5 || !isset($this->docHandler[$this->storeUrlMd5])) && !$this->dontStoreDocumentRef) {
739 $this->docHandler[$this->storeUrlMd5] = array($this->storeTitle, $this->storeArray, $this->storeUrl, $this->firstEl);
740 $GLOBALS['BE_USER']->pushModuleData('alt_doc.php', array($this->docHandler, $this->storeUrlMd5));
741 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
742 }
743 // Module configuration
744 $this->modTSconfig = $this->viewId ? BackendUtility::getModTSconfig($this->viewId, 'mod.xMOD_alt_doc') : array();
745 $body = $this->tceforms->printNeededJSFunctions_top();
746 $body .= $this->compileForm($editForm);
747 $body .= $this->tceforms->printNeededJSFunctions();
748 $body .= $this->functionMenus();
749 }
750 }
751 // Access check...
752 // The page will show only if there is a valid page and if this page may be viewed by the user
753 $this->pageinfo = BackendUtility::readPageAccess($this->viewId, $this->perms_clause);
754 // Setting up the buttons and markers for docheader
755 $docHeaderButtons = $this->getButtons();
756 $markers = array(
757 'LANGSELECTOR' => $this->langSelector(),
758 'EXTRAHEADER' => $this->extraFormHeaders(),
759 'CSH' => $docHeaderButtons['csh'],
760 'CONTENT' => $body
761 );
762 // Build the <body> for the module
763 $this->content = $this->doc->startPage('TYPO3 Edit Document');
764 $this->content .= $this->doc->moduleBody($this->pageinfo, $docHeaderButtons, $markers);
765 $this->content .= $this->doc->endPage();
766 $this->content = $this->doc->insertStylesAndJS($this->content);
767 }
768
769 /**
770 * Outputting the accumulated content to screen
771 *
772 * @return void
773 */
774 public function printContent() {
775 echo $this->content;
776 }
777
778 /***************************
779 *
780 * Sub-content functions, rendering specific parts of the module content.
781 *
782 ***************************/
783 /**
784 * Creates the editing form with TCEforms, based on the input from GPvars.
785 *
786 * @return string HTML form elements wrapped in tables
787 */
788 public function makeEditForm() {
789 // Initialize variables:
790 $this->elementsData = array();
791 $this->errorC = 0;
792 $this->newC = 0;
793 $thePrevUid = '';
794 $editForm = '';
795 $trData = NULL;
796 // Traverse the GPvar edit array
797 // Tables:
798 foreach ($this->editconf as $table => $conf) {
799 if (is_array($conf) && $GLOBALS['TCA'][$table] && $GLOBALS['BE_USER']->check('tables_modify', $table)) {
800 // Traverse the keys/comments of each table (keys can be a commalist of uids)
801 foreach ($conf as $cKey => $cmd) {
802 if ($cmd == 'edit' || $cmd == 'new') {
803 // Get the ids:
804 $ids = GeneralUtility::trimExplode(',', $cKey, TRUE);
805 // Traverse the ids:
806 foreach ($ids as $theUid) {
807 // Checking if the user has permissions? (Only working as a precaution,
808 // because the final permission check is always down in TCE. But it's
809 // good to notify the user on beforehand...)
810 // First, resetting flags.
811 $hasAccess = 1;
812 $deniedAccessReason = '';
813 $deleteAccess = 0;
814 $this->viewId = 0;
815 // If the command is to create a NEW record...:
816 if ($cmd == 'new') {
817 // NOTICE: the id values in this case points to the page uid onto which the
818 // record should be create OR (if the id is negativ) to a record from the
819 // same table AFTER which to create the record.
820 if ((int)$theUid) {
821 // Find parent page on which the new record reside
822 // Less than zero - find parent page
823 if ($theUid < 0) {
824 $calcPRec = BackendUtility::getRecord($table, abs($theUid));
825 $calcPRec = BackendUtility::getRecord('pages', $calcPRec['pid']);
826 } else {
827 // always a page
828 $calcPRec = BackendUtility::getRecord('pages', abs($theUid));
829 }
830 // Now, calculate whether the user has access to creating new records on this position:
831 if (is_array($calcPRec)) {
832 // Permissions for the parent page
833 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
834 if ($table == 'pages') {
835 // If pages:
836 $hasAccess = $CALC_PERMS & 8 ? 1 : 0;
837 $this->viewId = 0;
838 } else {
839 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
840 $this->viewId = $calcPRec['uid'];
841 }
842 }
843 }
844 // Don't save this document title in the document selector if the document is new.
845 $this->dontStoreDocumentRef = 1;
846 } else {
847 // Edit:
848 $calcPRec = BackendUtility::getRecord($table, $theUid);
849 BackendUtility::fixVersioningPid($table, $calcPRec);
850 if (is_array($calcPRec)) {
851 if ($table == 'pages') { // If pages:
852 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
853 $hasAccess = $CALC_PERMS & 2 ? 1 : 0;
854 $deleteAccess = $CALC_PERMS & 4 ? 1 : 0;
855 $this->viewId = $calcPRec['uid'];
856 } else {
857 // Fetching pid-record first
858 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(BackendUtility::getRecord('pages', $calcPRec['pid']));
859 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
860 $deleteAccess = $CALC_PERMS & 16 ? 1 : 0;
861 $this->viewId = $calcPRec['pid'];
862 // Adding "&L=xx" if the record being edited has a languageField with a value larger than zero!
863 if ($GLOBALS['TCA'][$table]['ctrl']['languageField'] && $calcPRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
864 $this->viewId_addParams = '&L=' . $calcPRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
865 }
866 }
867 // Check internals regarding access:
868 $isRootLevelRestrictionIgnored = BackendUtility::isRootLevelRestrictionIgnored($table);
869 if ($hasAccess || (string)$calcPRec['pid'] === '0' && $isRootLevelRestrictionIgnored) {
870 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
871 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
872 }
873 } else {
874 $hasAccess = 0;
875 }
876 }
877 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/alt_doc.php']['makeEditForm_accessCheck'])) {
878 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/alt_doc.php']['makeEditForm_accessCheck'] as $_funcRef) {
879 $_params = array(
880 'table' => $table,
881 'uid' => $theUid,
882 'cmd' => $cmd,
883 'hasAccess' => $hasAccess
884 );
885 $hasAccess = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
886 }
887 }
888 // AT THIS POINT we have checked the access status of the editing/creation of
889 // records and we can now proceed with creating the form elements:
890 if ($hasAccess) {
891 $prevPageID = is_object($trData) ? $trData->prevPageID : '';
892 $trData = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Form\DataPreprocessor::class);
893 $trData->addRawData = TRUE;
894 $trData->defVals = $this->defVals;
895 $trData->lockRecords = 1;
896 $trData->prevPageID = $prevPageID;
897 // 'new'
898 $trData->fetchRecord($table, $theUid, $cmd == 'new' ? 'new' : '');
899 $rec = reset($trData->regTableItems_data);
900 $rec['uid'] = $cmd == 'new' ? uniqid('NEW', TRUE) : $theUid;
901 if ($cmd == 'new') {
902 $rec['pid'] = $theUid == 'prev' ? $thePrevUid : $theUid;
903 }
904 $this->elementsData[] = array(
905 'table' => $table,
906 'uid' => $rec['uid'],
907 'pid' => $rec['pid'],
908 'cmd' => $cmd,
909 'deleteAccess' => $deleteAccess
910 );
911 // Now, render the form:
912 if (is_array($rec)) {
913 // Setting visual path / title of form:
914 $this->generalPathOfForm = $this->tceforms->getRecordPath($table, $rec);
915 if (!$this->storeTitle) {
916 $this->storeTitle = $this->recTitle ? htmlspecialchars($this->recTitle) : BackendUtility::getRecordTitle($table, $rec, TRUE);
917 }
918 // Setting variables in TCEforms object:
919 $this->tceforms->hiddenFieldList = '';
920 if (is_array($this->overrideVals) && is_array($this->overrideVals[$table])) {
921 $this->tceforms->hiddenFieldListArr = array_keys($this->overrideVals[$table]);
922 }
923 // Register default language labels, if any:
924 $this->tceforms->registerDefaultLanguageData($table, $rec);
925 // Create form for the record (either specific list of fields or the whole record):
926 $panel = '';
927 if ($this->columnsOnly) {
928 if (is_array($this->columnsOnly)) {
929 $panel .= $this->tceforms->getListedFields($table, $rec, $this->columnsOnly[$table]);
930 } else {
931 $panel .= $this->tceforms->getListedFields($table, $rec, $this->columnsOnly);
932 }
933 } else {
934 $panel .= $this->tceforms->getMainFields($table, $rec);
935 }
936 $panel = $this->tceforms->wrapTotal($panel, $rec, $table);
937 // Setting the pid value for new records:
938 if ($cmd == 'new') {
939 $panel .= '<input type="hidden" name="data[' . $table . '][' . $rec['uid'] . '][pid]" value="' . $rec['pid'] . '" />';
940 $this->newC++;
941 }
942 // Display "is-locked" message:
943 if ($lockInfo = BackendUtility::isRecordLocked($table, $rec['uid'])) {
944 $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, htmlspecialchars($lockInfo['msg']), '', \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING);
945 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
946 $flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
947 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
948 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
949 $defaultFlashMessageQueue->enqueue($flashMessage);
950 }
951 // Combine it all:
952 $editForm .= $panel;
953 }
954 $thePrevUid = $rec['uid'];
955 } else {
956 $this->errorC++;
957 $editForm .= $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.noEditPermission', TRUE) . '<br /><br />' . ($deniedAccessReason ? 'Reason: ' . htmlspecialchars($deniedAccessReason) . '<br /><br />' : '');
958 }
959 }
960 }
961 }
962 }
963 }
964 return $editForm;
965 }
966
967 /**
968 * Create the panel of buttons for submitting the form or otherwise perform operations.
969 *
970 * @return array All available buttons as an assoc. array
971 */
972 protected function getButtons() {
973 $buttons = array(
974 'save' => '',
975 'save_view' => '',
976 'save_new' => '',
977 'save_close' => '',
978 'close' => '',
979 'delete' => '',
980 'undo' => '',
981 'history' => '',
982 'columns_only' => '',
983 'csh' => '',
984 'translation_save' => '',
985 'translation_saveclear' => ''
986 );
987 // Render SAVE type buttons:
988 // The action of each button is decided by its name attribute. (See doProcessData())
989 if (!$this->errorC && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly']) {
990 // SAVE button:
991 $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) . '" />'));
992 // SAVE / VIEW button:
993 if ($this->viewId && !$this->noView && $this->getNewIconMode($this->firstEl['table'], 'saveDocView')) {
994 $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) . '" />'));
995 }
996 // SAVE / NEW button:
997 if (count($this->elementsData) == 1 && $this->getNewIconMode($this->firstEl['table'])) {
998 $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) . '" />'));
999 }
1000 // SAVE / CLOSE
1001 $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) . '" />'));
1002 // FINISH TRANSLATION / SAVE / CLOSE
1003 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation']) {
1004 $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) . '" /> ';
1005 $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) . '" />';
1006 }
1007 }
1008 // CLOSE button:
1009 $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>';
1010 // DELETE + UNDO buttons:
1011 if (!$this->errorC && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly'] && count($this->elementsData) == 1) {
1012 if ($this->firstEl['cmd'] != 'new' && MathUtility::canBeInterpretedAsInteger($this->firstEl['uid'])) {
1013 // Delete:
1014 if ($this->firstEl['deleteAccess'] && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly'] && !$this->getNewIconMode($this->firstEl['table'], 'disableDelete')) {
1015 $aOnClick = 'return deleteRecord(\'' . $this->firstEl['table'] . '\',\'' . $this->firstEl['uid'] . '\', unescape(\'' . rawurlencode($this->retUrl) . '\'));';
1016 $buttons['delete'] = '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '" title="' . $GLOBALS['LANG']->getLL('deleteItem', TRUE) . '">' . IconUtility::getSpriteIcon('actions-edit-delete') . '</a>';
1017 }
1018 // Undo:
1019 $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');
1020 if ($undoButtonR = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($undoRes)) {
1021 $aOnClick = 'window.location.href=' .
1022 GeneralUtility::quoteJSvalue(
1023 BackendUtility::getModuleUrl(
1024 'record_history',
1025 array(
1026 'element' => $this->firstEl['table'] . ':' . $this->firstEl['uid'],
1027 'revert' => 'ALL_FIELDS',
1028 'sumUp' => -1,
1029 'returnUrl' => $this->R_URI,
1030 )
1031 )
1032 ) . '; return false;';
1033 $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>';
1034 }
1035 if ($this->getNewIconMode($this->firstEl['table'], 'showHistory')) {
1036 $aOnClick = 'window.location.href=' .
1037 GeneralUtility::quoteJSvalue(
1038 BackendUtility::getModuleUrl(
1039 'record_history',
1040 array(
1041 'element' => $this->firstEl['table'] . ':' . $this->firstEl['uid'],
1042 'returnUrl' => $this->R_URI,
1043 )
1044 )
1045 ) . '; return false;';
1046 $buttons['history'] = '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '">' . IconUtility::getSpriteIcon('actions-document-history-open') . '</a>';
1047 }
1048 // If only SOME fields are shown in the form, this will link the user to the FULL form:
1049 if ($this->columnsOnly) {
1050 $buttons['columns_only'] = '<a href="' . htmlspecialchars(($this->R_URI . '&columnsOnly=')) . '" title="' . $GLOBALS['LANG']->getLL('editWholeRecord', TRUE) . '">' . IconUtility::getSpriteIcon('actions-document-open') . '</a>';
1051 }
1052 }
1053 }
1054 // add the CSH icon
1055 $buttons['csh'] = BackendUtility::cshItem('xMOD_csh_corebe', 'TCEforms');
1056 $buttons['shortcut'] = $this->shortCutLink();
1057 $buttons['open_in_new_window'] = $this->openInNewWindowLink();
1058 return $buttons;
1059 }
1060
1061 /**
1062 * Returns the language switch/selector for editing,
1063 * show only when a single record is edited
1064 * - multiple records are too confusing
1065 *
1066 * @return string The HTML
1067 */
1068 public function langSelector() {
1069 $langSelector = '';
1070 if (count($this->elementsData) == 1) {
1071 $langSelector = $this->languageSwitch($this->firstEl['table'], $this->firstEl['uid'], $this->firstEl['pid']);
1072 }
1073 return $langSelector;
1074 }
1075
1076 /**
1077 * Compiles the extra form headers if the tceforms
1078 *
1079 * @return string The HTML
1080 */
1081 public function extraFormHeaders() {
1082 $extraTemplate = '';
1083 if (is_array($this->tceforms->extraFormHeaders)) {
1084 $extraTemplate = HtmlParser::getSubpart($this->doc->moduleTemplate, '###DOCHEADER_EXTRAHEADER###');
1085 $extraTemplate = HtmlParser::substituteMarker($extraTemplate, '###EXTRAHEADER###', implode(LF, $this->tceforms->extraFormHeaders));
1086 }
1087 return $extraTemplate;
1088 }
1089
1090 /**
1091 * Put together the various elements (buttons, selectors, form) into a table
1092 *
1093 * @param string $editForm HTML form.
1094 * @return string Composite HTML
1095 */
1096 public function compileForm($editForm) {
1097 $formContent = '
1098 <!-- EDITING FORM -->
1099 ' . $editForm . '
1100
1101 <input type="hidden" name="returnUrl" value="' . htmlspecialchars($this->retUrl) . '" />
1102 <input type="hidden" name="viewUrl" value="' . htmlspecialchars($this->viewUrl) . '" />';
1103 if ($this->returnNewPageId) {
1104 $formContent .= '<input type="hidden" name="returnNewPageId" value="1" />';
1105 }
1106 $formContent .= '<input type="hidden" name="popViewId" value="' . htmlspecialchars($this->viewId) . '" />';
1107 if ($this->viewId_addParams) {
1108 $formContent .= '<input type="hidden" name="popViewId_addParams" value="' . htmlspecialchars($this->viewId_addParams) . '" />';
1109 }
1110 $formContent .= '
1111 <input type="hidden" name="closeDoc" value="0" />
1112 <input type="hidden" name="doSave" value="0" />
1113 <input type="hidden" name="_serialNumber" value="' . md5(microtime()) . '" />
1114 <input type="hidden" name="_scrollPosition" value="" />' . FormEngine::getHiddenTokenField('editRecord');
1115 return $formContent;
1116 }
1117
1118 /**
1119 * Create the checkbox buttons in the bottom of the pages.
1120 *
1121 * @return string HTML for function menus.
1122 */
1123 public function functionMenus() {
1124 if ($GLOBALS['BE_USER']->getTSConfigVal('options.enableShowPalettes')) {
1125 // Show palettes:
1126
1127 return '<div class="checkbox">' .
1128 '<label for="checkShowPalettes">' .
1129 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"') .
1130 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.showPalettes', TRUE) .
1131 '</label>'.
1132 '</div>';
1133 } else {
1134 return '';
1135 }
1136 }
1137
1138 /**
1139 * Create shortcut icon
1140 *
1141 * @return string
1142 */
1143 public function shortCutLink() {
1144 if ($this->returnUrl == 'close.html' || !$GLOBALS['BE_USER']->mayMakeShortcut()) {
1145 return '';
1146 }
1147 return $this->doc->makeShortcutIcon('returnUrl,edit,defVals,overrideVals,columnsOnly,returnNewPageId,editRegularContentFromId,noView', implode(',', array_keys($this->MOD_MENU)), $this->MCONF['name'], 1);
1148 }
1149
1150 /**
1151 * Creates open-in-window link
1152 *
1153 * @return string
1154 */
1155 public function openInNewWindowLink() {
1156 if ($this->returnUrl == 'close.html') {
1157 return '';
1158 }
1159 $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;';
1160 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>';
1161 }
1162
1163 /**
1164 * Reads comment messages from TCEforms and prints them in a HTML comment in the bottom of the page.
1165 *
1166 * @return string
1167 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1168 */
1169 public function tceformMessages() {
1170 GeneralUtility::logDeprecatedFunction();
1171 return '';
1172 }
1173
1174 /***************************
1175 *
1176 * Localization stuff
1177 *
1178 ***************************/
1179 /**
1180 * Make selector box for creating new translation for a record or switching to edit the record in an existing language.
1181 * Displays only languages which are available for the current page.
1182 *
1183 * @param string $table Table name
1184 * @param int $uid Uid for which to create a new language
1185 * @param int $pid Pid of the record
1186 * @return string <select> HTML element (if there were items for the box anyways...)
1187 */
1188 public function languageSwitch($table, $uid, $pid = NULL) {
1189 $content = '';
1190 $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1191 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1192 // Table editable and activated for languages?
1193 if ($GLOBALS['BE_USER']->check('tables_modify', $table) && $languageField && $transOrigPointerField && !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) {
1194 if (is_null($pid)) {
1195 $row = BackendUtility::getRecord($table, $uid, 'pid');
1196 $pid = $row['pid'];
1197 }
1198 // Get all avalibale languages for the page
1199 $langRows = $this->getLanguages($pid);
1200 // Page available in other languages than default language?
1201 if (is_array($langRows) && count($langRows) > 1) {
1202 $rowsByLang = array();
1203 $fetchFields = 'uid,' . $languageField . ',' . $transOrigPointerField;
1204 // Get record in current language
1205 $rowCurrent = BackendUtility::getLiveVersionOfRecord($table, $uid, $fetchFields);
1206 if (!is_array($rowCurrent)) {
1207 $rowCurrent = BackendUtility::getRecord($table, $uid, $fetchFields);
1208 }
1209 $currentLanguage = $rowCurrent[$languageField];
1210 // Disabled for records with [all] language!
1211 if ($currentLanguage > -1) {
1212 // Get record in default language if needed
1213 if ($currentLanguage && $rowCurrent[$transOrigPointerField]) {
1214 $rowsByLang[0] = BackendUtility::getLiveVersionOfRecord($table, $rowCurrent[$transOrigPointerField], $fetchFields);
1215 if (!is_array($rowsByLang[0])) {
1216 $rowsByLang[0] = BackendUtility::getRecord($table, $rowCurrent[$transOrigPointerField], $fetchFields);
1217 }
1218 } else {
1219 $rowsByLang[$rowCurrent[$languageField]] = $rowCurrent;
1220 }
1221 if ($rowCurrent[$transOrigPointerField] || $currentLanguage === '0') {
1222 // Get record in other languages to see what's already available
1223 $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));
1224 foreach ($translations as $row) {
1225 $rowsByLang[$row[$languageField]] = $row;
1226 }
1227 }
1228 $langSelItems = array();
1229 foreach ($langRows as $lang) {
1230 if ($GLOBALS['BE_USER']->checkLanguageAccess($lang['uid'])) {
1231 $newTranslation = isset($rowsByLang[$lang['uid']]) ? '' : ' [' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.new', TRUE) . ']';
1232 // Create url for creating a localized record
1233 if ($newTranslation) {
1234 $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'));
1235 } else {
1236 $href = $this->backPath . 'alt_doc.php?';
1237 $href .= '&edit[' . $table . '][' . $rowsByLang[$lang['uid']]['uid'] . ']=edit';
1238 $href .= '&returnUrl=' . rawurlencode($this->retUrl) . BackendUtility::getUrlToken('editRecord');
1239 }
1240 $langSelItems[$lang['uid']] = '
1241 <option value="' . htmlspecialchars($href) . '"' . ($currentLanguage == $lang['uid'] ? ' selected="selected"' : '') . '>' . htmlspecialchars(($lang['title'] . $newTranslation)) . '</option>';
1242 }
1243 }
1244 // If any languages are left, make selector:
1245 if (count($langSelItems) > 1) {
1246 $onChange = 'if(this.options[this.selectedIndex].value){window.location.href=(this.options[this.selectedIndex].value);}';
1247 $content = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_general.xlf:LGL.language', TRUE) . ' <select name="_langSelector" onchange="' . htmlspecialchars($onChange) . '">
1248 ' . implode('', $langSelItems) . '
1249 </select>';
1250 }
1251 }
1252 }
1253 }
1254 return $content;
1255 }
1256
1257 /**
1258 * Redirects to alt_doc with new parameters to edit a just created localized record
1259 *
1260 * @param string $justLocalized String passed by GET &justLocalized=
1261 * @return void
1262 */
1263 public function localizationRedirect($justLocalized) {
1264 list($table, $orig_uid, $language) = explode(':', $justLocalized);
1265 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
1266 $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));
1267 if (is_array($localizedRecord)) {
1268 // Create parameters and finally run the classic page module for creating a new page translation
1269 $params = '&edit[' . $table . '][' . $localizedRecord['uid'] . ']=edit';
1270 $returnUrl = '&returnUrl=' . rawurlencode(GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl')));
1271 $location = $GLOBALS['BACK_PATH'] . 'alt_doc.php?' . $params . $returnUrl . BackendUtility::getUrlToken('editRecord');
1272 HttpUtility::redirect($location);
1273 }
1274 }
1275 }
1276
1277 /**
1278 * Returns sys_language records available for record translations on given page.
1279 *
1280 * @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)
1281 * @return array Language records including faked record for default language
1282 */
1283 public function getLanguages($id) {
1284 $modSharedTSconfig = BackendUtility::getModTSconfig($id, 'mod.SHARED');
1285 // Fallback non sprite-configuration
1286 if (preg_match('/\\.gif$/', $modSharedTSconfig['properties']['defaultLanguageFlag'])) {
1287 $modSharedTSconfig['properties']['defaultLanguageFlag'] = str_replace('.gif', '', $modSharedTSconfig['properties']['defaultLanguageFlag']);
1288 }
1289 $languages = array(
1290 0 => array(
1291 'uid' => 0,
1292 'pid' => 0,
1293 'hidden' => 0,
1294 'title' => $modSharedTSconfig['properties']['defaultLanguageLabel'] !== ''
1295 ? $modSharedTSconfig['properties']['defaultLanguageLabel'] . ' (' . $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_mod_web_list.xlf:defaultLanguage') . ')'
1296 : $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_mod_web_list.xlf:defaultLanguage'),
1297 'flag' => $modSharedTSconfig['properties']['defaultLanguageFlag']
1298 )
1299 );
1300 $exQ = $GLOBALS['BE_USER']->isAdmin() ? '' : ' AND sys_language.hidden=0';
1301 if ($id) {
1302 $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');
1303 } else {
1304 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('sys_language.*', 'sys_language', 'sys_language.hidden=0', '', 'sys_language.title');
1305 }
1306 if ($rows) {
1307 foreach ($rows as $row) {
1308 $languages[$row['uid']] = $row;
1309 }
1310 }
1311 return $languages;
1312 }
1313
1314 /***************************
1315 *
1316 * Other functions
1317 *
1318 ***************************/
1319 /**
1320 * Fix $this->editconf if versioning applies to any of the records
1321 *
1322 * @param array $mapArray Mapping between old and new ids if auto-versioning has been performed.
1323 * @return void
1324 */
1325 public function fixWSversioningInEditConf($mapArray = FALSE) {
1326 // Traverse the editConf array
1327 if (is_array($this->editconf)) {
1328 // Tables:
1329 foreach ($this->editconf as $table => $conf) {
1330 if (is_array($conf) && $GLOBALS['TCA'][$table]) {
1331 // Traverse the keys/comments of each table (keys can be a commalist of uids)
1332 $newConf = array();
1333 foreach ($conf as $cKey => $cmd) {
1334 if ($cmd == 'edit') {
1335 // Traverse the ids:
1336 $ids = GeneralUtility::trimExplode(',', $cKey, TRUE);
1337 foreach ($ids as $idKey => $theUid) {
1338 if (is_array($mapArray)) {
1339 if ($mapArray[$table][$theUid]) {
1340 $ids[$idKey] = $mapArray[$table][$theUid];
1341 }
1342 } else {
1343 // Default, look for versions in workspace for record:
1344 $calcPRec = $this->getRecordForEdit($table, $theUid);
1345 if (is_array($calcPRec)) {
1346 // Setting UID again if it had changed, eg. due to workspace versioning.
1347 $ids[$idKey] = $calcPRec['uid'];
1348 }
1349 }
1350 }
1351 // Add the possibly manipulated IDs to the new-build newConf array:
1352 $newConf[implode(',', $ids)] = $cmd;
1353 } else {
1354 $newConf[$cKey] = $cmd;
1355 }
1356 }
1357 // Store the new conf array:
1358 $this->editconf[$table] = $newConf;
1359 }
1360 }
1361 }
1362 }
1363
1364 /**
1365 * Get record for editing.
1366 *
1367 * @param string $table Table name
1368 * @param int $theUid Record UID
1369 * @return array Returns record to edit, FALSE if none
1370 */
1371 public function getRecordForEdit($table, $theUid) {
1372 // Fetch requested record:
1373 $reqRecord = BackendUtility::getRecord($table, $theUid, 'uid,pid');
1374 if (is_array($reqRecord)) {
1375 // If workspace is OFFLINE:
1376 if ($GLOBALS['BE_USER']->workspace != 0) {
1377 // Check for versioning support of the table:
1378 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1379 // If the record is already a version of "something" pass it by.
1380 if ($reqRecord['pid'] == -1) {
1381 // (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)
1382 return $reqRecord;
1383 } else {
1384 // The input record was online and an offline version must be found or made:
1385 // Look for version of this workspace:
1386 $versionRec = BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $reqRecord['uid'], 'uid,pid,t3ver_oid');
1387 return is_array($versionRec) ? $versionRec : $reqRecord;
1388 }
1389 } else {
1390 // This means that editing cannot occur on this record because it was not supporting versioning which is required inside an offline workspace.
1391 return FALSE;
1392 }
1393 } else {
1394 // In ONLINE workspace, just return the originally requested record:
1395 return $reqRecord;
1396 }
1397 } else {
1398 // Return FALSE because the table/uid was not found anyway.
1399 return FALSE;
1400 }
1401 }
1402
1403 /**
1404 * 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
1405 *
1406 * @return void
1407 */
1408 public function editRegularContentFromId() {
1409 $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');
1410 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1411 $ecUids = array();
1412 while ($ecRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1413 $ecUids[] = $ecRec['uid'];
1414 }
1415 $this->editconf['tt_content'][implode(',', $ecUids)] = 'edit';
1416 }
1417 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1418 }
1419
1420 /**
1421 * Populates the variables $this->storeArray, $this->storeUrl, $this->storeUrlMd5
1422 *
1423 * @return void
1424 * @see makeDocSel()
1425 */
1426 public function compileStoreDat() {
1427 $this->storeArray = GeneralUtility::compileSelectedGetVarsFromArray('edit,defVals,overrideVals,columnsOnly,noView,editRegularContentFromId,workspace', $this->R_URL_getvars);
1428 $this->storeUrl = GeneralUtility::implodeArrayForUrl('', $this->storeArray);
1429 $this->storeUrlMd5 = md5($this->storeUrl);
1430 }
1431
1432 /**
1433 * Function used to look for configuration of buttons in the form: Fx. disabling buttons or showing them at various positions.
1434 *
1435 * @param string $table The table for which the configuration may be specific
1436 * @param string $key The option for look for. Default is checking if the saveDocNew button should be displayed.
1437 * @return string Return value fetched from USER TSconfig
1438 */
1439 public function getNewIconMode($table, $key = 'saveDocNew') {
1440 $TSconfig = $GLOBALS['BE_USER']->getTSConfig('options.' . $key);
1441 $output = trim(isset($TSconfig['properties'][$table]) ? $TSconfig['properties'][$table] : $TSconfig['value']);
1442 return $output;
1443 }
1444
1445 /**
1446 * Handling the closing of a document
1447 *
1448 * @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
1449 * @return void
1450 */
1451 public function closeDocument($code = 0) {
1452 // If current document is found in docHandler,
1453 // then unset it, possibly unset it ALL and finally, write it to the session data
1454 if (isset($this->docHandler[$this->storeUrlMd5])) {
1455 // add the closing document to the recent documents
1456 $recentDocs = $GLOBALS['BE_USER']->getModuleData('opendocs::recent');
1457 if (!is_array($recentDocs)) {
1458 $recentDocs = array();
1459 }
1460 $closedDoc = $this->docHandler[$this->storeUrlMd5];
1461 $recentDocs = array_merge(array($this->storeUrlMd5 => $closedDoc), $recentDocs);
1462 if (count($recentDocs) > 8) {
1463 $recentDocs = array_slice($recentDocs, 0, 8);
1464 }
1465 // remove it from the list of the open documents
1466 unset($this->docHandler[$this->storeUrlMd5]);
1467 if ($code == '3') {
1468 $recentDocs = array_merge($this->docHandler, $recentDocs);
1469 $this->docHandler = array();
1470 }
1471 $GLOBALS['BE_USER']->pushModuleData('opendocs::recent', $recentDocs);
1472 $GLOBALS['BE_USER']->pushModuleData('alt_doc.php', array($this->docHandler, $this->docDat[1]));
1473 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
1474 }
1475 // 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...)
1476 if ($this->returnEditConf && $this->retUrl != 'dummy.php') {
1477 $this->retUrl .= '&returnEditConf=' . rawurlencode(json_encode($this->editconf));
1478 }
1479 // If code is NOT set OR set to 1, then make a header location redirect to $this->retUrl
1480 if (!$code || $code == 1) {
1481 HttpUtility::redirect($this->retUrl);
1482 } else {
1483 $this->setDocument('', $this->retUrl);
1484 }
1485 }
1486
1487 /**
1488 * Redirects to the document pointed to by $currentDocFromHandlerMD5 OR $retUrl (depending on some internal calculations).
1489 * Most likely you will get a header-location redirect from this function.
1490 *
1491 * @param string $currentDocFromHandlerMD5 Pointer to the document in the docHandler array
1492 * @param string $retUrl Alternative/Default retUrl
1493 * @return void
1494 */
1495 public function setDocument($currentDocFromHandlerMD5 = '', $retUrl = 'dummy.php') {
1496 if ($retUrl === 'dummy.php') {
1497 return;
1498 }
1499 if (!$this->modTSconfig['properties']['disableDocSelector'] && is_array($this->docHandler) && count($this->docHandler)) {
1500 if (isset($this->docHandler[$currentDocFromHandlerMD5])) {
1501 $setupArr = $this->docHandler[$currentDocFromHandlerMD5];
1502 } else {
1503 $setupArr = reset($this->docHandler);
1504 }
1505 if ($setupArr[2]) {
1506 $sParts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
1507 $retUrl = $sParts['path'] . '?' . $setupArr[2] . '&returnUrl=' . rawurlencode($retUrl);
1508 }
1509 }
1510 HttpUtility::redirect($retUrl);
1511 }
1512
1513 /**
1514 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1515 */
1516 protected function getBackendUser() {
1517 return $GLOBALS['BE_USER'];
1518 }
1519
1520 }