15c8354001150adfca32e9db3661a91bdc8a48f1
[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 * Constructor
363 */
364 public function __construct() {
365 $GLOBALS['SOBE'] = $this;
366 $GLOBALS['LANG']->includeLLFile('EXT:lang/locallang_alt_doc.xml');
367 }
368
369 /**
370 * First initialization.
371 *
372 * @return void
373 */
374 public function preInit() {
375 if (GeneralUtility::_GP('justLocalized')) {
376 $this->localizationRedirect(GeneralUtility::_GP('justLocalized'));
377 }
378 // Setting GPvars:
379 $this->editconf = GeneralUtility::_GP('edit');
380 $this->defVals = GeneralUtility::_GP('defVals');
381 $this->overrideVals = GeneralUtility::_GP('overrideVals');
382 $this->columnsOnly = GeneralUtility::_GP('columnsOnly');
383 $this->returnUrl = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'));
384 $this->closeDoc = GeneralUtility::_GP('closeDoc');
385 $this->doSave = GeneralUtility::_GP('doSave');
386 $this->returnEditConf = GeneralUtility::_GP('returnEditConf');
387 $this->localizationMode = GeneralUtility::_GP('localizationMode');
388 $this->workspace = GeneralUtility::_GP('workspace');
389 $this->uc = GeneralUtility::_GP('uc');
390 // Setting override values as default if defVals does not exist.
391 if (!is_array($this->defVals) && is_array($this->overrideVals)) {
392 $this->defVals = $this->overrideVals;
393 }
394 // Setting return URL
395 $this->retUrl = $this->returnUrl ?: 'dummy.php';
396 // Fix $this->editconf if versioning applies to any of the records
397 $this->fixWSversioningInEditConf();
398 // Make R_URL (request url) based on input GETvars:
399 $this->R_URL_parts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
400 $this->R_URL_getvars = GeneralUtility::_GET();
401 $this->R_URL_getvars['edit'] = $this->editconf;
402 // MAKE url for storing
403 $this->compileStoreDat();
404 // Initialize more variables.
405 $this->dontStoreDocumentRef = 0;
406 $this->storeTitle = '';
407 // Get session data for the module:
408 $this->docDat = $GLOBALS['BE_USER']->getModuleData('alt_doc.php', 'ses');
409 $this->docHandler = $this->docDat[0];
410 // If a request for closing the document has been sent, act accordingly:
411 if ($this->closeDoc > 0) {
412 $this->closeDocument($this->closeDoc);
413 }
414 // If NO vars are sent to the script, try to read first document:
415 // Added !is_array($this->editconf) because editConf must not be set either.
416 // Anyways I can't figure out when this situation here will apply...
417 if (is_array($this->R_URL_getvars) && count($this->R_URL_getvars) < 2 && !is_array($this->editconf)) {
418 $this->setDocument($this->docDat[1]);
419 }
420
421 // Sets a temporary workspace, this request is based on
422 if ($this->workspace !== NULL) {
423 $this->getBackendUser()->setTemporaryWorkspace($this->workspace);
424 }
425 }
426
427 /**
428 * Detects, if a save command has been triggered.
429 *
430 * @return boolean TRUE, then save the document (data submitted)
431 */
432 public function doProcessData() {
433 $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']);
434 return $out;
435 }
436
437 /**
438 * Do processing of data, submitting it to TCEmain.
439 *
440 * @return void
441 */
442 public function processData() {
443 // GPvars specifically for processing:
444 $control = GeneralUtility::_GP('control');
445 $this->data = GeneralUtility::_GP('data');
446 $this->cmd = GeneralUtility::_GP('cmd');
447 $this->mirror = GeneralUtility::_GP('mirror');
448 $this->cacheCmd = GeneralUtility::_GP('cacheCmd');
449 $this->redirect = GeneralUtility::_GP('redirect');
450 $this->returnNewPageId = GeneralUtility::_GP('returnNewPageId');
451 $this->vC = GeneralUtility::_GP('vC');
452 // See tce_db.php for relevate options here:
453 // Only options related to $this->data submission are included here.
454 /** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
455 $tce = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
456 $tce->stripslashes_values = 0;
457
458 if (!empty($control)) {
459 $tce->setControl($control);
460 }
461 if (isset($_POST['_translation_savedok_x'])) {
462 $tce->updateModeL10NdiffData = 'FORCE_FFUPD';
463 }
464 if (isset($_POST['_translation_savedokclear_x'])) {
465 $tce->updateModeL10NdiffData = 'FORCE_FFUPD';
466 $tce->updateModeL10NdiffDataClear = TRUE;
467 }
468 // Setting default values specific for the user:
469 $TCAdefaultOverride = $GLOBALS['BE_USER']->getTSConfigProp('TCAdefaults');
470 if (is_array($TCAdefaultOverride)) {
471 $tce->setDefaultsFromUserTS($TCAdefaultOverride);
472 }
473 // Setting internal vars:
474 if ($GLOBALS['BE_USER']->uc['neverHideAtCopy']) {
475 $tce->neverHideAtCopy = 1;
476 }
477 $tce->debug = 0;
478 $tce->disableRTE = !$GLOBALS['BE_USER']->isRTE();
479 // Loading TCEmain with data:
480 $tce->start($this->data, $this->cmd);
481 if (is_array($this->mirror)) {
482 $tce->setMirror($this->mirror);
483 }
484 // If pages are being edited, we set an instruction about updating the page tree after this operation.
485 if (isset($this->data['pages']) || $GLOBALS['BE_USER']->workspace != 0 && count($this->data)) {
486 BackendUtility::setUpdateSignal('updatePageTree');
487 }
488 // Checking referer / executing
489 $refInfo = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
490 $httpHost = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
491 if ($httpHost != $refInfo['host'] && $this->vC != $GLOBALS['BE_USER']->veriCode() && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer']) {
492 $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));
493 debug('Error: Referer host did not match with server host.');
494 } else {
495 // Perform the saving operation with TCEmain:
496 $tce->process_uploads($_FILES);
497 $tce->process_datamap();
498 $tce->process_cmdmap();
499 // If there was saved any new items, load them:
500 if (count($tce->substNEWwithIDs_table)) {
501 // save the expanded/collapsed states for new inline records, if any
502 \TYPO3\CMS\Backend\Form\Element\InlineElement::updateInlineView($this->uc, $tce);
503 $newEditConf = array();
504 foreach ($this->editconf as $tableName => $tableCmds) {
505 $keys = array_keys($tce->substNEWwithIDs_table, $tableName);
506 if (count($keys) > 0) {
507 foreach ($keys as $key) {
508 $editId = $tce->substNEWwithIDs[$key];
509 // Check if the $editId isn't a child record of an IRRE action
510 if (!(is_array($tce->newRelatedIDs[$tableName]) && in_array($editId, $tce->newRelatedIDs[$tableName]))) {
511 // Translate new id to the workspace version:
512 if ($versionRec = BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $tableName, $editId, 'uid')) {
513 $editId = $versionRec['uid'];
514 }
515 $newEditConf[$tableName][$editId] = 'edit';
516 }
517 // Traverse all new records and forge the content of ->editconf so we can continue to EDIT these records!
518 if ($tableName == 'pages' && $this->retUrl != 'dummy.php' && $this->returnNewPageId) {
519 $this->retUrl .= '&id=' . $tce->substNEWwithIDs[$key];
520 }
521 }
522 } else {
523 $newEditConf[$tableName] = $tableCmds;
524 }
525 }
526 // Resetting editconf if newEditConf has values:
527 if (count($newEditConf)) {
528 $this->editconf = $newEditConf;
529 }
530 // Finally, set the editconf array in the "getvars" so they will be passed along in URLs as needed.
531 $this->R_URL_getvars['edit'] = $this->editconf;
532 // Unsetting default values since we don't need them anymore.
533 unset($this->R_URL_getvars['defVals']);
534 // Re-compile the store* values since editconf changed...
535 $this->compileStoreDat();
536 }
537 // See if any records was auto-created as new versions?
538 if (count($tce->autoVersionIdMap)) {
539 $this->fixWSversioningInEditConf($tce->autoVersionIdMap);
540 }
541 // If a document is saved and a new one is created right after.
542 if (isset($_POST['_savedoknew_x']) && is_array($this->editconf)) {
543 // Finding the current table:
544 reset($this->editconf);
545 $nTable = key($this->editconf);
546 // Finding the first id, getting the records pid+uid
547 reset($this->editconf[$nTable]);
548 $nUid = key($this->editconf[$nTable]);
549 $nRec = BackendUtility::getRecord($nTable, $nUid, 'pid,uid');
550 // Setting a blank editconf array for a new record:
551 $this->editconf = array();
552 if ($this->getNewIconMode($nTable) == 'top') {
553 $this->editconf[$nTable][$nRec['pid']] = 'new';
554 } else {
555 $this->editconf[$nTable][-$nRec['uid']] = 'new';
556 }
557 // Finally, set the editconf array in the "getvars" so they will be passed along in URLs as needed.
558 $this->R_URL_getvars['edit'] = $this->editconf;
559 // Re-compile the store* values since editconf changed...
560 $this->compileStoreDat();
561 }
562 $tce->printLogErrorMessages(isset($_POST['_saveandclosedok_x']) || isset($_POST['_translation_savedok_x']) ? $this->retUrl : $this->R_URL_parts['path'] . '?' . GeneralUtility::implodeArrayForUrl('', $this->R_URL_getvars));
563 }
564 // || count($tce->substNEWwithIDs)... If any new items has been save, the document is CLOSED
565 // because if not, we just get that element re-listed as new. And we don't want that!
566 if (isset($_POST['_saveandclosedok_x']) || isset($_POST['_translation_savedok_x']) || $this->closeDoc < 0) {
567 $this->closeDocument(abs($this->closeDoc));
568 }
569 }
570
571 /**
572 * Initialize the normal module operation
573 *
574 * @return void
575 */
576 public function init() {
577 // Setting more GPvars:
578 $this->popViewId = GeneralUtility::_GP('popViewId');
579 $this->popViewId_addParams = GeneralUtility::_GP('popViewId_addParams');
580 $this->viewUrl = GeneralUtility::_GP('viewUrl');
581 $this->editRegularContentFromId = GeneralUtility::_GP('editRegularContentFromId');
582 $this->recTitle = GeneralUtility::_GP('recTitle');
583 $this->disHelp = GeneralUtility::_GP('disHelp');
584 $this->noView = GeneralUtility::_GP('noView');
585 $this->perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
586 // Set other internal variables:
587 $this->R_URL_getvars['returnUrl'] = $this->retUrl;
588 $this->R_URI = $this->R_URL_parts['path'] . '?' . GeneralUtility::implodeArrayForUrl('', $this->R_URL_getvars);
589 // MENU-ITEMS:
590 // If array, then it's a selector box menu
591 // If empty string it's just a variable, that'll be saved.
592 // Values NOT in this array will not be saved in the settings-array for the module.
593 $this->MOD_MENU = array(
594 'showPalettes' => ''
595 );
596 // Setting virtual document name
597 $this->MCONF['name'] = 'xMOD_alt_doc.php';
598 // CLEANSE SETTINGS
599 $this->MOD_SETTINGS = BackendUtility::getModuleData($this->MOD_MENU, GeneralUtility::_GP('SET'), $this->MCONF['name']);
600 // Create an instance of the document template object
601 $this->doc = $GLOBALS['TBE_TEMPLATE'];
602 $this->doc->backPath = $GLOBALS['BACK_PATH'];
603 $this->doc->setModuleTemplate('EXT:backend/Resources/Private/Templates/alt_doc.html');
604 $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);">';
605 $this->doc->getPageRenderer()->loadPrototype();
606 $this->doc->JScode = $this->doc->wrapScriptTags('
607 function jumpToUrl(URL,formEl) { //
608 if (!TBE_EDITOR.isFormChanged()) {
609 window.location.href = URL;
610 } else if (formEl && formEl.type=="checkbox") {
611 formEl.checked = formEl.checked ? 0 : 1;
612 }
613 }
614 // Object: TS:
615 // passwordDummy and decimalSign are used by tbe_editor.js and have to be declared here as
616 // TS object overwrites the object declared in tbe_editor.js
617 function typoSetup() { //
618 this.uniqueID = "";
619 this.passwordDummy = "********";
620 this.PATH_typo3 = " ";
621 this.decimalSign = ".";
622 }
623 var TS = new typoSetup();
624
625 // Info view:
626 function launchView(table,uid,bP) { //
627 var backPath= bP ? bP : "";
628 var thePreviewWindow="";
629 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");
630 if (thePreviewWindow && thePreviewWindow.focus) {
631 thePreviewWindow.focus();
632 }
633 }
634 function deleteRecord(table,id,url) { //
635 if (
636 ' . ($GLOBALS['BE_USER']->jsConfirmation(4) ? 'confirm(' . GeneralUtility::quoteJSvalue($GLOBALS['LANG']->getLL('deleteWarning')) . ')' : '1==1') . '
637 ) {
638 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";
639 }
640 return false;
641 }
642 ' . (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) . ' } ' : ''));
643 // Setting up the context sensitive menu:
644 $this->doc->getContextMenuCode();
645 $this->doc->bodyTagAdditions = 'onload="window.scrollTo(0,' . MathUtility::forceIntegerInRange(GeneralUtility::_GP('_scrollPosition'), 0, 10000) . ');"';
646 }
647
648 /**
649 * Main module operation
650 *
651 * @return void
652 */
653 public function main() {
654 // Begin edit:
655 if (is_array($this->editconf)) {
656 // Initialize TCEforms (rendering the forms)
657 $this->tceforms = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Form\\FormEngine');
658 $this->tceforms->initDefaultBEMode();
659 $this->tceforms->doSaveFieldName = 'doSave';
660 $this->tceforms->localizationMode = GeneralUtility::inList('text,media', $this->localizationMode) ? $this->localizationMode : '';
661 // text,media is keywords defined in TYPO3 Core API..., see "l10n_cat"
662 $this->tceforms->returnUrl = $this->R_URI;
663 $this->tceforms->palettesCollapsed = !$this->MOD_SETTINGS['showPalettes'];
664 $this->tceforms->disableRTE = !$GLOBALS['BE_USER']->isRTE();
665 $this->tceforms->enableClickMenu = TRUE;
666 $this->tceforms->enableTabMenu = TRUE;
667 // Clipboard is initialized:
668 // Start clipboard
669 $this->tceforms->clipObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Clipboard\\Clipboard');
670 // Initialize - reads the clipboard content from the user session
671 $this->tceforms->clipObj->initializeClipboard();
672 // Setting external variables:
673 $this->tceforms->edit_showFieldHelp = $GLOBALS['BE_USER']->uc['edit_showFieldHelp'];
674 if ($this->editRegularContentFromId) {
675 $this->editRegularContentFromId();
676 }
677 // Creating the editing form, wrap it with buttons, document selector etc.
678 $editForm = $this->makeEditForm();
679 if ($editForm) {
680 $this->firstEl = reset($this->elementsData);
681 // Checking if the currently open document is stored in the list of "open documents" - if not, then add it:
682 if (($this->docDat[1] !== $this->storeUrlMd5 || !isset($this->docHandler[$this->storeUrlMd5])) && !$this->dontStoreDocumentRef) {
683 $this->docHandler[$this->storeUrlMd5] = array($this->storeTitle, $this->storeArray, $this->storeUrl, $this->firstEl);
684 $GLOBALS['BE_USER']->pushModuleData('alt_doc.php', array($this->docHandler, $this->storeUrlMd5));
685 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
686 }
687 // Module configuration
688 $this->modTSconfig = $this->viewId ? BackendUtility::getModTSconfig($this->viewId, 'mod.xMOD_alt_doc') : array();
689 $body = $this->tceforms->printNeededJSFunctions_top();
690 $body .= $this->compileForm($editForm);
691 $body .= $this->tceforms->printNeededJSFunctions();
692 $body .= $this->functionMenus();
693 $body .= $this->tceformMessages();
694 }
695 }
696 // Access check...
697 // The page will show only if there is a valid page and if this page may be viewed by the user
698 $this->pageinfo = BackendUtility::readPageAccess($this->viewId, $this->perms_clause);
699 // Setting up the buttons and markers for docheader
700 $docHeaderButtons = $this->getButtons();
701 $markers = array(
702 'LANGSELECTOR' => $this->langSelector(),
703 'EXTRAHEADER' => $this->extraFormHeaders(),
704 'CSH' => $docHeaderButtons['csh'],
705 'CONTENT' => $body
706 );
707 // Build the <body> for the module
708 $this->content = $this->doc->startPage('TYPO3 Edit Document');
709 $this->content .= $this->doc->moduleBody($this->pageinfo, $docHeaderButtons, $markers);
710 $this->content .= $this->doc->endPage();
711 $this->content = $this->doc->insertStylesAndJS($this->content);
712 }
713
714 /**
715 * Outputting the accumulated content to screen
716 *
717 * @return void
718 */
719 public function printContent() {
720 echo $this->content;
721 }
722
723 /***************************
724 *
725 * Sub-content functions, rendering specific parts of the module content.
726 *
727 ***************************/
728 /**
729 * Creates the editing form with TCEforms, based on the input from GPvars.
730 *
731 * @return string HTML form elements wrapped in tables
732 * @todo Define visibility
733 */
734 public function makeEditForm() {
735 // Initialize variables:
736 $this->elementsData = array();
737 $this->errorC = 0;
738 $this->newC = 0;
739 $thePrevUid = '';
740 $editForm = '';
741 $trData = NULL;
742 // Traverse the GPvar edit array
743 // Tables:
744 foreach ($this->editconf as $table => $conf) {
745 if (is_array($conf) && $GLOBALS['TCA'][$table] && $GLOBALS['BE_USER']->check('tables_modify', $table)) {
746 // Traverse the keys/comments of each table (keys can be a commalist of uids)
747 foreach ($conf as $cKey => $cmd) {
748 if ($cmd == 'edit' || $cmd == 'new') {
749 // Get the ids:
750 $ids = GeneralUtility::trimExplode(',', $cKey, TRUE);
751 // Traverse the ids:
752 foreach ($ids as $theUid) {
753 // Checking if the user has permissions? (Only working as a precaution,
754 // because the final permission check is always down in TCE. But it's
755 // good to notify the user on beforehand...)
756 // First, resetting flags.
757 $hasAccess = 1;
758 $deniedAccessReason = '';
759 $deleteAccess = 0;
760 $this->viewId = 0;
761 // If the command is to create a NEW record...:
762 if ($cmd == 'new') {
763 // NOTICE: the id values in this case points to the page uid onto which the
764 // record should be create OR (if the id is negativ) to a record from the
765 // same table AFTER which to create the record.
766 if ((int)$theUid) {
767 // Find parent page on which the new record reside
768 // Less than zero - find parent page
769 if ($theUid < 0) {
770 $calcPRec = BackendUtility::getRecord($table, abs($theUid));
771 $calcPRec = BackendUtility::getRecord('pages', $calcPRec['pid']);
772 } else {
773 // always a page
774 $calcPRec = BackendUtility::getRecord('pages', abs($theUid));
775 }
776 // Now, calculate whether the user has access to creating new records on this position:
777 if (is_array($calcPRec)) {
778 // Permissions for the parent page
779 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
780 if ($table == 'pages') {
781 // If pages:
782 $hasAccess = $CALC_PERMS & 8 ? 1 : 0;
783 $this->viewId = 0;
784 } else {
785 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
786 $this->viewId = $calcPRec['uid'];
787 }
788 }
789 }
790 // Don't save this document title in the document selector if the document is new.
791 $this->dontStoreDocumentRef = 1;
792 } else {
793 // Edit:
794 $calcPRec = BackendUtility::getRecord($table, $theUid);
795 BackendUtility::fixVersioningPid($table, $calcPRec);
796 if (is_array($calcPRec)) {
797 if ($table == 'pages') { // If pages:
798 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
799 $hasAccess = $CALC_PERMS & 2 ? 1 : 0;
800 $deleteAccess = $CALC_PERMS & 4 ? 1 : 0;
801 $this->viewId = $calcPRec['uid'];
802 } else {
803 // Fetching pid-record first
804 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(BackendUtility::getRecord('pages', $calcPRec['pid']));
805 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
806 $deleteAccess = $CALC_PERMS & 16 ? 1 : 0;
807 $this->viewId = $calcPRec['pid'];
808 // Adding "&L=xx" if the record being edited has a languageField with a value larger than zero!
809 if ($GLOBALS['TCA'][$table]['ctrl']['languageField'] && $calcPRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
810 $this->viewId_addParams = '&L=' . $calcPRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
811 }
812 }
813 // Check internals regarding access:
814 $isRootLevelRestrictionIgnored = BackendUtility::isRootLevelRestrictionIgnored($table);
815 if ($hasAccess || (string) $calcPRec['pid'] === '0' && $isRootLevelRestrictionIgnored) {
816 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
817 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
818 }
819 } else {
820 $hasAccess = 0;
821 }
822 }
823 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/alt_doc.php']['makeEditForm_accessCheck'])) {
824 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/alt_doc.php']['makeEditForm_accessCheck'] as $_funcRef) {
825 $_params = array(
826 'table' => $table,
827 'uid' => $theUid,
828 'cmd' => $cmd,
829 'hasAccess' => $hasAccess
830 );
831 $hasAccess = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
832 }
833 }
834 // AT THIS POINT we have checked the access status of the editing/creation of
835 // records and we can now proceed with creating the form elements:
836 if ($hasAccess) {
837 $prevPageID = is_object($trData) ? $trData->prevPageID : '';
838 $trData = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Form\\DataPreprocessor');
839 $trData->addRawData = TRUE;
840 $trData->defVals = $this->defVals;
841 $trData->lockRecords = 1;
842 $trData->disableRTE = !$GLOBALS['BE_USER']->isRTE();
843 $trData->prevPageID = $prevPageID;
844 // 'new'
845 $trData->fetchRecord($table, $theUid, $cmd == 'new' ? 'new' : '');
846 $rec = reset($trData->regTableItems_data);
847 $rec['uid'] = $cmd == 'new' ? uniqid('NEW') : $theUid;
848 if ($cmd == 'new') {
849 $rec['pid'] = $theUid == 'prev' ? $thePrevUid : $theUid;
850 }
851 $this->elementsData[] = array(
852 'table' => $table,
853 'uid' => $rec['uid'],
854 'pid' => $rec['pid'],
855 'cmd' => $cmd,
856 'deleteAccess' => $deleteAccess
857 );
858 // Now, render the form:
859 if (is_array($rec)) {
860 // Setting visual path / title of form:
861 $this->generalPathOfForm = $this->tceforms->getRecordPath($table, $rec);
862 if (!$this->storeTitle) {
863 $this->storeTitle = $this->recTitle ? htmlspecialchars($this->recTitle) : BackendUtility::getRecordTitle($table, $rec, TRUE);
864 }
865 // Setting variables in TCEforms object:
866 $this->tceforms->hiddenFieldList = '';
867 $this->tceforms->globalShowHelp = $this->disHelp ? 0 : 1;
868 if (is_array($this->overrideVals) && is_array($this->overrideVals[$table])) {
869 $this->tceforms->hiddenFieldListArr = array_keys($this->overrideVals[$table]);
870 }
871 // Register default language labels, if any:
872 $this->tceforms->registerDefaultLanguageData($table, $rec);
873 // Create form for the record (either specific list of fields or the whole record):
874 $panel = '';
875 if ($this->columnsOnly) {
876 if (is_array($this->columnsOnly)) {
877 $panel .= $this->tceforms->getListedFields($table, $rec, $this->columnsOnly[$table]);
878 } else {
879 $panel .= $this->tceforms->getListedFields($table, $rec, $this->columnsOnly);
880 }
881 } else {
882 $panel .= $this->tceforms->getMainFields($table, $rec);
883 }
884 $panel = $this->tceforms->wrapTotal($panel, $rec, $table);
885 // Setting the pid value for new records:
886 if ($cmd == 'new') {
887 $panel .= '<input type="hidden" name="data[' . $table . '][' . $rec['uid'] . '][pid]" value="' . $rec['pid'] . '" />';
888 $this->newC++;
889 }
890 // Display "is-locked" message:
891 if ($lockInfo = BackendUtility::isRecordLocked($table, $rec['uid'])) {
892 $flashMessage = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', htmlspecialchars($lockInfo['msg']), '', \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING);
893 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
894 $flashMessageService = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessageService');
895 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
896 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
897 $defaultFlashMessageQueue->enqueue($flashMessage);
898 }
899 // Combine it all:
900 $editForm .= $panel;
901 }
902 $thePrevUid = $rec['uid'];
903 } else {
904 $this->errorC++;
905 $editForm .= $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.noEditPermission', TRUE) . '<br /><br />' . ($deniedAccessReason ? 'Reason: ' . htmlspecialchars($deniedAccessReason) . '<br /><br />' : '');
906 }
907 }
908 }
909 }
910 }
911 }
912 return $editForm;
913 }
914
915 /**
916 * Create the panel of buttons for submitting the form or otherwise perform operations.
917 *
918 * @return array All available buttons as an assoc. array
919 */
920 protected function getButtons() {
921 $buttons = array(
922 'save' => '',
923 'save_view' => '',
924 'save_new' => '',
925 'save_close' => '',
926 'close' => '',
927 'delete' => '',
928 'undo' => '',
929 'history' => '',
930 'columns_only' => '',
931 'csh' => '',
932 'translation_save' => '',
933 'translation_saveclear' => ''
934 );
935 // Render SAVE type buttons:
936 // The action of each button is decided by its name attribute. (See doProcessData())
937 if (!$this->errorC && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly']) {
938 // SAVE button:
939 $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) . '" />'));
940 // SAVE / VIEW button:
941 if ($this->viewId && !$this->noView && ExtensionManagementUtility::isLoaded('cms') && $this->getNewIconMode($this->firstEl['table'], 'saveDocView')) {
942 $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) . '" />'));
943 }
944 // SAVE / NEW button:
945 if (count($this->elementsData) == 1 && $this->getNewIconMode($this->firstEl['table'])) {
946 $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) . '" />'));
947 }
948 // SAVE / CLOSE
949 $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) . '" />'));
950 // FINISH TRANSLATION / SAVE / CLOSE
951 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation']) {
952 $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) . '" />';
953 $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) . '" />';
954 }
955 }
956 // CLOSE button:
957 $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>';
958 // DELETE + UNDO buttons:
959 if (!$this->errorC && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly'] && count($this->elementsData) == 1) {
960 if ($this->firstEl['cmd'] != 'new' && MathUtility::canBeInterpretedAsInteger($this->firstEl['uid'])) {
961 // Delete:
962 if ($this->firstEl['deleteAccess'] && !$GLOBALS['TCA'][$this->firstEl['table']]['ctrl']['readOnly'] && !$this->getNewIconMode($this->firstEl['table'], 'disableDelete')) {
963 $aOnClick = 'return deleteRecord(\'' . $this->firstEl['table'] . '\',\'' . $this->firstEl['uid'] . '\', unescape(\'' . rawurlencode($this->retUrl) . '\'));';
964 $buttons['delete'] = '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '" title="' . $GLOBALS['LANG']->getLL('deleteItem', TRUE) . '">' . IconUtility::getSpriteIcon('actions-edit-delete') . '</a>';
965 }
966 // Undo:
967 $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');
968 if ($undoButtonR = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($undoRes)) {
969 $aOnClick = 'window.location.href=\'show_rechis.php?element=' . rawurlencode(($this->firstEl['table'] . ':' . $this->firstEl['uid'])) . '&revert=ALL_FIELDS&sumUp=-1&returnUrl=' . rawurlencode($this->R_URI) . '\'; return false;';
970 $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>';
971 }
972 if ($this->getNewIconMode($this->firstEl['table'], 'showHistory')) {
973 $aOnClick = 'window.location.href=\'show_rechis.php?element=' . rawurlencode(($this->firstEl['table'] . ':' . $this->firstEl['uid'])) . '&returnUrl=' . rawurlencode($this->R_URI) . '\'; return false;';
974 $buttons['history'] = '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '">' . IconUtility::getSpriteIcon('actions-document-history-open') . '</a>';
975 }
976 // If only SOME fields are shown in the form, this will link the user to the FULL form:
977 if ($this->columnsOnly) {
978 $buttons['columns_only'] = '<a href="' . htmlspecialchars(($this->R_URI . '&columnsOnly=')) . '" title="' . $GLOBALS['LANG']->getLL('editWholeRecord', TRUE) . '">' . IconUtility::getSpriteIcon('actions-document-open') . '</a>';
979 }
980 }
981 }
982 // add the CSH icon
983 $buttons['csh'] = BackendUtility::cshItem('xMOD_csh_corebe', 'TCEforms', $GLOBALS['BACK_PATH'], '', TRUE);
984 $buttons['shortcut'] = $this->shortCutLink();
985 $buttons['open_in_new_window'] = $this->openInNewWindowLink();
986 return $buttons;
987 }
988
989 /**
990 * Returns the language switch/selector for editing,
991 * show only when a single record is edited
992 * - multiple records are too confusing
993 *
994 * @return string The HTML
995 * @todo Define visibility
996 */
997 public function langSelector() {
998 $langSelector = '';
999 if (count($this->elementsData) == 1) {
1000 $langSelector = $this->languageSwitch($this->firstEl['table'], $this->firstEl['uid'], $this->firstEl['pid']);
1001 }
1002 return $langSelector;
1003 }
1004
1005 /**
1006 * Compiles the extra form headers if the tceforms
1007 *
1008 * @return string The HTML
1009 * @todo Define visibility
1010 */
1011 public function extraFormHeaders() {
1012 $extraTemplate = '';
1013 if (is_array($this->tceforms->extraFormHeaders)) {
1014 $extraTemplate = HtmlParser::getSubpart($this->doc->moduleTemplate, '###DOCHEADER_EXTRAHEADER###');
1015 $extraTemplate = HtmlParser::substituteMarker($extraTemplate, '###EXTRAHEADER###', implode(LF, $this->tceforms->extraFormHeaders));
1016 }
1017 return $extraTemplate;
1018 }
1019
1020 /**
1021 * Put together the various elements (buttons, selectors, form) into a table
1022 *
1023 * @param string $editForm HTML form.
1024 * @return string Composite HTML
1025 * @todo Define visibility
1026 */
1027 public function compileForm($editForm) {
1028 $formContent = '
1029 <!-- EDITING FORM -->
1030 ' . $editForm . '
1031
1032 <input type="hidden" name="returnUrl" value="' . htmlspecialchars($this->retUrl) . '" />
1033 <input type="hidden" name="viewUrl" value="' . htmlspecialchars($this->viewUrl) . '" />';
1034 if ($this->returnNewPageId) {
1035 $formContent .= '<input type="hidden" name="returnNewPageId" value="1" />';
1036 }
1037 $formContent .= '<input type="hidden" name="popViewId" value="' . htmlspecialchars($this->viewId) . '" />';
1038 if ($this->viewId_addParams) {
1039 $formContent .= '<input type="hidden" name="popViewId_addParams" value="' . htmlspecialchars($this->viewId_addParams) . '" />';
1040 }
1041 $formContent .= '
1042 <input type="hidden" name="closeDoc" value="0" />
1043 <input type="hidden" name="doSave" value="0" />
1044 <input type="hidden" name="_serialNumber" value="' . md5(microtime()) . '" />
1045 <input type="hidden" name="_scrollPosition" value="" />' . FormEngine::getHiddenTokenField('editRecord');
1046 return $formContent;
1047 }
1048
1049 /**
1050 * Create the checkbox buttons in the bottom of the pages.
1051 *
1052 * @return string HTML for function menus.
1053 * @todo Define visibility
1054 */
1055 public function functionMenus() {
1056 if ($GLOBALS['BE_USER']->getTSConfigVal('options.enableShowPalettes')) {
1057 // Show palettes:
1058 return '
1059 <!-- Function menu (checkbox for showing all palettes): -->
1060 <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>';
1061 } else {
1062 return '';
1063 }
1064 }
1065
1066 /**
1067 * Create shortcut icon
1068 *
1069 * @return string
1070 * @todo Define visibility
1071 */
1072 public function shortCutLink() {
1073 if ($this->returnUrl == 'close.html' || !$GLOBALS['BE_USER']->mayMakeShortcut()) {
1074 return '';
1075 }
1076 return $this->doc->makeShortcutIcon('returnUrl,edit,defVals,overrideVals,columnsOnly,returnNewPageId,editRegularContentFromId,disHelp,noView', implode(',', array_keys($this->MOD_MENU)), $this->MCONF['name'], 1);
1077 }
1078
1079 /**
1080 * Creates open-in-window link
1081 *
1082 * @return string
1083 * @todo Define visibility
1084 */
1085 public function openInNewWindowLink() {
1086 if ($this->returnUrl == 'close.html') {
1087 return '';
1088 }
1089 $aOnClick = 'vHWin=window.open(\'' . 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;';
1090 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>';
1091 }
1092
1093 /**
1094 * Reads comment messages from TCEforms and prints them in a HTML comment in the bottom of the page.
1095 *
1096 * @return void
1097 * @todo Define visibility
1098 */
1099 public function tceformMessages() {
1100 if (count($this->tceforms->commentMessages)) {
1101 $tceformMessages = '
1102 <!-- TCEFORM messages
1103 ' . htmlspecialchars(implode(LF, $this->tceforms->commentMessages)) . '
1104 -->
1105 ';
1106 }
1107 return $tceformMessages;
1108 }
1109
1110 /***************************
1111 *
1112 * Localization stuff
1113 *
1114 ***************************/
1115 /**
1116 * Make selector box for creating new translation for a record or switching to edit the record in an existing language.
1117 * Displays only languages which are available for the current page.
1118 *
1119 * @param string $table Table name
1120 * @param integer $uid Uid for which to create a new language
1121 * @param integer $pid Pid of the record
1122 * @return string <select> HTML element (if there were items for the box anyways...)
1123 * @todo Define visibility
1124 */
1125 public function languageSwitch($table, $uid, $pid = NULL) {
1126 $content = '';
1127 $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1128 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1129 // Table editable and activated for languages?
1130 if ($GLOBALS['BE_USER']->check('tables_modify', $table) && $languageField && $transOrigPointerField && !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) {
1131 if (is_null($pid)) {
1132 $row = BackendUtility::getRecord($table, $uid, 'pid');
1133 $pid = $row['pid'];
1134 }
1135 // Get all avalibale languages for the page
1136 $langRows = $this->getLanguages($pid);
1137 // Page available in other languages than default language?
1138 if (is_array($langRows) && count($langRows) > 1) {
1139 $rowsByLang = array();
1140 $fetchFields = 'uid,' . $languageField . ',' . $transOrigPointerField;
1141 // Get record in current language
1142 $rowCurrent = BackendUtility::getLiveVersionOfRecord($table, $uid, $fetchFields);
1143 if (!is_array($rowCurrent)) {
1144 $rowCurrent = BackendUtility::getRecord($table, $uid, $fetchFields);
1145 }
1146 $currentLanguage = $rowCurrent[$languageField];
1147 // Disabled for records with [all] language!
1148 if ($currentLanguage > -1) {
1149 // Get record in default language if needed
1150 if ($currentLanguage && $rowCurrent[$transOrigPointerField]) {
1151 $rowsByLang[0] = BackendUtility::getLiveVersionOfRecord($table, $rowCurrent[$transOrigPointerField], $fetchFields);
1152 if (!is_array($rowsByLang[0])) {
1153 $rowsByLang[0] = BackendUtility::getRecord($table, $rowCurrent[$transOrigPointerField], $fetchFields);
1154 }
1155 } else {
1156 $rowsByLang[$rowCurrent[$languageField]] = $rowCurrent;
1157 }
1158 if ($rowCurrent[$transOrigPointerField] || $currentLanguage === '0') {
1159 // Get record in other languages to see what's already available
1160 $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));
1161 foreach ($translations as $row) {
1162 $rowsByLang[$row[$languageField]] = $row;
1163 }
1164 }
1165 $langSelItems = array();
1166 foreach ($langRows as $lang) {
1167 if ($GLOBALS['BE_USER']->checkLanguageAccess($lang['uid'])) {
1168 $newTranslation = isset($rowsByLang[$lang['uid']]) ? '' : ' [' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.new', TRUE) . ']';
1169 // Create url for creating a localized record
1170 if ($newTranslation) {
1171 $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'));
1172 } else {
1173 $href = $this->backPath . 'alt_doc.php?';
1174 $href .= '&edit[' . $table . '][' . $rowsByLang[$lang['uid']]['uid'] . ']=edit';
1175 $href .= '&returnUrl=' . rawurlencode($this->retUrl) . BackendUtility::getUrlToken('editRecord');
1176 }
1177 $langSelItems[$lang['uid']] = '
1178 <option value="' . htmlspecialchars($href) . '"' . ($currentLanguage == $lang['uid'] ? ' selected="selected"' : '') . '>' . htmlspecialchars(($lang['title'] . $newTranslation)) . '</option>';
1179 }
1180 }
1181 // If any languages are left, make selector:
1182 if (count($langSelItems) > 1) {
1183 $onChange = 'if(this.options[this.selectedIndex].value){window.location.href=(this.options[this.selectedIndex].value);}';
1184 $content = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_general.xlf:LGL.language', TRUE) . ' <select name="_langSelector" onchange="' . htmlspecialchars($onChange) . '">
1185 ' . implode('', $langSelItems) . '
1186 </select>';
1187 }
1188 }
1189 }
1190 }
1191 return $content;
1192 }
1193
1194 /**
1195 * Redirects to alt_doc with new parameters to edit a just created localized record
1196 *
1197 * @param string $justLocalized String passed by GET &justLocalized=
1198 * @return void
1199 * @todo Define visibility
1200 */
1201 public function localizationRedirect($justLocalized) {
1202 list($table, $orig_uid, $language) = explode(':', $justLocalized);
1203 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
1204 $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));
1205 if (is_array($localizedRecord)) {
1206 // Create parameters and finally run the classic page module for creating a new page translation
1207 $params = '&edit[' . $table . '][' . $localizedRecord['uid'] . ']=edit';
1208 $returnUrl = '&returnUrl=' . rawurlencode(GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl')));
1209 $location = $GLOBALS['BACK_PATH'] . 'alt_doc.php?' . $params . $returnUrl . BackendUtility::getUrlToken('editRecord');
1210 HttpUtility::redirect($location);
1211 }
1212 }
1213 }
1214
1215 /**
1216 * Returns sys_language records available for record translations on given page.
1217 *
1218 * @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)
1219 * @return array Language records including faked record for default language
1220 * @todo Define visibility
1221 */
1222 public function getLanguages($id) {
1223 $modSharedTSconfig = BackendUtility::getModTSconfig($id, 'mod.SHARED');
1224 // Fallback non sprite-configuration
1225 if (preg_match('/\\.gif$/', $modSharedTSconfig['properties']['defaultLanguageFlag'])) {
1226 $modSharedTSconfig['properties']['defaultLanguageFlag'] = str_replace('.gif', '', $modSharedTSconfig['properties']['defaultLanguageFlag']);
1227 }
1228 $languages = array(
1229 0 => array(
1230 'uid' => 0,
1231 'pid' => 0,
1232 'hidden' => 0,
1233 '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'),
1234 'flag' => $modSharedTSconfig['properties']['defaultLanguageFlag']
1235 )
1236 );
1237 $exQ = $GLOBALS['BE_USER']->isAdmin() ? '' : ' AND sys_language.hidden=0';
1238 if ($id) {
1239 $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');
1240 } else {
1241 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('sys_language.*', 'sys_language', 'sys_language.hidden=0', '', 'sys_language.title');
1242 }
1243 if ($rows) {
1244 foreach ($rows as $row) {
1245 $languages[$row['uid']] = $row;
1246 }
1247 }
1248 return $languages;
1249 }
1250
1251 /***************************
1252 *
1253 * Other functions
1254 *
1255 ***************************/
1256 /**
1257 * Fix $this->editconf if versioning applies to any of the records
1258 *
1259 * @param array $mapArray Mapping between old and new ids if auto-versioning has been performed.
1260 * @return void
1261 * @todo Define visibility
1262 */
1263 public function fixWSversioningInEditConf($mapArray = FALSE) {
1264 // Traverse the editConf array
1265 if (is_array($this->editconf)) {
1266 // Tables:
1267 foreach ($this->editconf as $table => $conf) {
1268 if (is_array($conf) && $GLOBALS['TCA'][$table]) {
1269 // Traverse the keys/comments of each table (keys can be a commalist of uids)
1270 $newConf = array();
1271 foreach ($conf as $cKey => $cmd) {
1272 if ($cmd == 'edit') {
1273 // Traverse the ids:
1274 $ids = GeneralUtility::trimExplode(',', $cKey, TRUE);
1275 foreach ($ids as $idKey => $theUid) {
1276 if (is_array($mapArray)) {
1277 if ($mapArray[$table][$theUid]) {
1278 $ids[$idKey] = $mapArray[$table][$theUid];
1279 }
1280 } else {
1281 // Default, look for versions in workspace for record:
1282 $calcPRec = $this->getRecordForEdit($table, $theUid);
1283 if (is_array($calcPRec)) {
1284 // Setting UID again if it had changed, eg. due to workspace versioning.
1285 $ids[$idKey] = $calcPRec['uid'];
1286 }
1287 }
1288 }
1289 // Add the possibly manipulated IDs to the new-build newConf array:
1290 $newConf[implode(',', $ids)] = $cmd;
1291 } else {
1292 $newConf[$cKey] = $cmd;
1293 }
1294 }
1295 // Store the new conf array:
1296 $this->editconf[$table] = $newConf;
1297 }
1298 }
1299 }
1300 }
1301
1302 /**
1303 * Get record for editing.
1304 *
1305 * @param string $table Table name
1306 * @param integer $theUid Record UID
1307 * @return array Returns record to edit, FALSE if none
1308 * @todo Define visibility
1309 */
1310 public function getRecordForEdit($table, $theUid) {
1311 // Fetch requested record:
1312 $reqRecord = BackendUtility::getRecord($table, $theUid, 'uid,pid');
1313 if (is_array($reqRecord)) {
1314 // If workspace is OFFLINE:
1315 if ($GLOBALS['BE_USER']->workspace != 0) {
1316 // Check for versioning support of the table:
1317 if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1318 // If the record is already a version of "something" pass it by.
1319 if ($reqRecord['pid'] == -1) {
1320 // (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)
1321 return $reqRecord;
1322 } else {
1323 // The input record was online and an offline version must be found or made:
1324 // Look for version of this workspace:
1325 $versionRec = BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $reqRecord['uid'], 'uid,pid,t3ver_oid');
1326 return is_array($versionRec) ? $versionRec : $reqRecord;
1327 }
1328 } else {
1329 // This means that editing cannot occur on this record because it was not supporting versioning which is required inside an offline workspace.
1330 return FALSE;
1331 }
1332 } else {
1333 // In ONLINE workspace, just return the originally requested record:
1334 return $reqRecord;
1335 }
1336 } else {
1337 // Return FALSE because the table/uid was not found anyway.
1338 return FALSE;
1339 }
1340 }
1341
1342 /**
1343 * 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
1344 *
1345 * @return void
1346 * @todo Define visibility
1347 */
1348 public function editRegularContentFromId() {
1349 if (ExtensionManagementUtility::isLoaded('cms')) {
1350 $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');
1351 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1352 $ecUids = array();
1353 while ($ecRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1354 $ecUids[] = $ecRec['uid'];
1355 }
1356 $this->editconf['tt_content'][implode(',', $ecUids)] = 'edit';
1357 }
1358 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1359 }
1360 }
1361
1362 /**
1363 * Populates the variables $this->storeArray, $this->storeUrl, $this->storeUrlMd5
1364 *
1365 * @return void
1366 * @see makeDocSel()
1367 * @todo Define visibility
1368 */
1369 public function compileStoreDat() {
1370 $this->storeArray = GeneralUtility::compileSelectedGetVarsFromArray('edit,defVals,overrideVals,columnsOnly,disHelp,noView,editRegularContentFromId,workspace', $this->R_URL_getvars);
1371 $this->storeUrl = GeneralUtility::implodeArrayForUrl('', $this->storeArray);
1372 $this->storeUrlMd5 = md5($this->storeUrl);
1373 }
1374
1375 /**
1376 * Function used to look for configuration of buttons in the form: Fx. disabling buttons or showing them at various positions.
1377 *
1378 * @param string $table The table for which the configuration may be specific
1379 * @param string $key The option for look for. Default is checking if the saveDocNew button should be displayed.
1380 * @return string Return value fetched from USER TSconfig
1381 * @todo Define visibility
1382 */
1383 public function getNewIconMode($table, $key = 'saveDocNew') {
1384 $TSconfig = $GLOBALS['BE_USER']->getTSConfig('options.' . $key);
1385 $output = trim(isset($TSconfig['properties'][$table]) ? $TSconfig['properties'][$table] : $TSconfig['value']);
1386 return $output;
1387 }
1388
1389 /**
1390 * Handling the closing of a document
1391 *
1392 * @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
1393 * @return void
1394 * @todo Define visibility
1395 */
1396 public function closeDocument($code = 0) {
1397 // If current document is found in docHandler,
1398 // then unset it, possibly unset it ALL and finally, write it to the session data
1399 if (isset($this->docHandler[$this->storeUrlMd5])) {
1400 // add the closing document to the recent documents
1401 $recentDocs = $GLOBALS['BE_USER']->getModuleData('opendocs::recent');
1402 if (!is_array($recentDocs)) {
1403 $recentDocs = array();
1404 }
1405 $closedDoc = $this->docHandler[$this->storeUrlMd5];
1406 $recentDocs = array_merge(array($this->storeUrlMd5 => $closedDoc), $recentDocs);
1407 if (count($recentDocs) > 8) {
1408 $recentDocs = array_slice($recentDocs, 0, 8);
1409 }
1410 // remove it from the list of the open documents
1411 unset($this->docHandler[$this->storeUrlMd5]);
1412 if ($code == '3') {
1413 $recentDocs = array_merge($this->docHandler, $recentDocs);
1414 $this->docHandler = array();
1415 }
1416 $GLOBALS['BE_USER']->pushModuleData('opendocs::recent', $recentDocs);
1417 $GLOBALS['BE_USER']->pushModuleData('alt_doc.php', array($this->docHandler, $this->docDat[1]));
1418 BackendUtility::setUpdateSignal('OpendocsController::updateNumber', count($this->docHandler));
1419 }
1420 // 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...)
1421 if ($this->returnEditConf && $this->retUrl != 'dummy.php') {
1422 $this->retUrl .= '&returnEditConf=' . rawurlencode(json_encode($this->editconf));
1423 }
1424 // If code is NOT set OR set to 1, then make a header location redirect to $this->retUrl
1425 if (!$code || $code == 1) {
1426 HttpUtility::redirect($this->retUrl);
1427 } else {
1428 $this->setDocument('', $this->retUrl);
1429 }
1430 }
1431
1432 /**
1433 * Redirects to the document pointed to by $currentDocFromHandlerMD5 OR $retUrl (depending on some internal calculations).
1434 * Most likely you will get a header-location redirect from this function.
1435 *
1436 * @param string $currentDocFromHandlerMD5 Pointer to the document in the docHandler array
1437 * @param string $retUrl Alternative/Default retUrl
1438 * @return void
1439 * @todo Define visibility
1440 */
1441 public function setDocument($currentDocFromHandlerMD5 = '', $retUrl = 'alt_doc_nodoc.php') {
1442 if (!ExtensionManagementUtility::isLoaded('cms') && $retUrl === 'alt_doc_nodoc.php') {
1443 return;
1444 }
1445 if (!$this->modTSconfig['properties']['disableDocSelector'] && is_array($this->docHandler) && count($this->docHandler)) {
1446 if (isset($this->docHandler[$currentDocFromHandlerMD5])) {
1447 $setupArr = $this->docHandler[$currentDocFromHandlerMD5];
1448 } else {
1449 $setupArr = reset($this->docHandler);
1450 }
1451 if ($setupArr[2]) {
1452 $sParts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
1453 $retUrl = $sParts['path'] . '?' . $setupArr[2] . '&returnUrl=' . rawurlencode($retUrl);
1454 }
1455 }
1456 HttpUtility::redirect($retUrl);
1457 }
1458
1459 /**
1460 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1461 */
1462 protected function getBackendUser() {
1463 return $GLOBALS['BE_USER'];
1464 }
1465
1466 }