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