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