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