TYPO3 CMS  TYPO3_6-2
InlineElement.php
Go to the documentation of this file.
1 <?php
3 
27 
34 
35  const Structure_Separator = '-';
36 
37  const FlexForm_Separator = '---';
38 
39  const FlexForm_Substitute = ':';
40 
41  const Disposal_AttributeName = 'Disposal_AttributeName';
42 
43  const Disposal_AttributeId = 'Disposal_AttributeId';
44 
51  public $fObj;
52 
58  public $backPath;
59 
65  public $isAjaxCall = FALSE;
66 
72  public $inlineStructure = array();
73 
80 
86  public $inlineNames = array();
87 
93  public $inlineData = array();
94 
100  public $inlineView = array();
101 
107  public $inlineCount = 0;
108 
112  public $inlineStyles = array();
113 
119  public $prependNaming = 'data';
120 
127 
134 
135  // Array containing instances of hook classes called once for IRRE objects
136  protected $hookObjects = array();
137 
145  public function init(&$formEngine) {
146  $this->fObj = $formEngine;
147  $this->backPath = &$formEngine->backPath;
148  $this->prependFormFieldNames = &$this->fObj->prependFormFieldNames;
149  $this->prependCmdFieldNames = &$this->fObj->prependCmdFieldNames;
150  $this->inlineStyles['margin-right'] = '5';
151  $this->initHookObjects();
152  }
153 
161  protected function initHookObjects() {
162  $this->hookObjects = array();
163  if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'])) {
164  $tceformsInlineHook = &$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'];
165  if (is_array($tceformsInlineHook)) {
166  foreach ($tceformsInlineHook as $classData) {
167  $processObject = GeneralUtility::getUserObj($classData);
168  if (!$processObject instanceof \TYPO3\CMS\Backend\Form\Element\InlineElementHookInterface) {
169  throw new \UnexpectedValueException('$processObject must implement interface TYPO3\\CMS\\Backend\\Form\\Element\\InlineElementHookInterface', 1202072000);
170  }
171  $processObject->init($this);
172  $this->hookObjects[] = $processObject;
173  }
174  }
175  }
176  }
177 
188  public function getSingleField_typeInline($table, $field, $row, &$PA) {
189  // Check the TCA configuration - if FALSE is returned, something was wrong
190  if ($this->checkConfiguration($PA['fieldConf']['config']) === FALSE) {
191  return FALSE;
192  }
193  $item = '';
194  $localizationLinks = '';
195  // Count the number of processed inline elements
196  $this->inlineCount++;
197  // Init:
198  $config = $PA['fieldConf']['config'];
199  $foreign_table = $config['foreign_table'];
200  $language = 0;
202  $language = (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
203  }
204  $minitems = MathUtility::forceIntegerInRange($config['minitems'], 0);
205  $maxitems = MathUtility::forceIntegerInRange($config['maxitems'], 0);
206  if (!$maxitems) {
207  $maxitems = 100000;
208  }
209  // Register the required number of elements:
210  $this->fObj->requiredElements[$PA['itemFormElName']] = array($minitems, $maxitems, 'imgName' => $table . '_' . $row['uid'] . '_' . $field);
211  // Remember the page id (pid of record) where inline editing started first
212  // We need that pid for ajax calls, so that they would know where the action takes place on the page structure
213  if (!isset($this->inlineFirstPid)) {
214  // If this record is not new, try to fetch the inlineView states
215  // @TODO: Add checking/cleaning for unused tables, records, etc. to save space in uc-field
216  if (MathUtility::canBeInterpretedAsInteger($row['uid'])) {
217  $inlineView = unserialize($GLOBALS['BE_USER']->uc['inlineView']);
218  $this->inlineView = $inlineView[$table][$row['uid']];
219  }
220  // If the parent is a page, use the uid(!) of the (new?) page as pid for the child records:
221  if ($table == 'pages') {
222  $liveVersionId = BackendUtility::getLiveVersionIdOfRecord('pages', $row['uid']);
223  $this->inlineFirstPid = is_null($liveVersionId) ? $row['uid'] : $liveVersionId;
224  } elseif ($row['pid'] < 0) {
225  $prevRec = BackendUtility::getRecord($table, abs($row['pid']));
226  $this->inlineFirstPid = $prevRec['pid'];
227  } else {
228  $this->inlineFirstPid = $row['pid'];
229  }
230  }
231  // Add the current inline job to the structure stack
232  $this->pushStructure($table, $row['uid'], $field, $config, $PA);
233  // e.g. data[<table>][<uid>][<field>]
234  $nameForm = $this->inlineNames['form'];
235  // e.g. data-<pid>-<table1>-<uid1>-<field1>-<table2>-<uid2>-<field2>
236  $nameObject = $this->inlineNames['object'];
237  // Get the records related to this inline record
238  $relatedRecords = $this->getRelatedRecords($table, $field, $row, $PA, $config);
239  // Set the first and last record to the config array
240  $relatedRecordsUids = array_keys($relatedRecords['records']);
241  $config['inline']['first'] = reset($relatedRecordsUids);
242  $config['inline']['last'] = end($relatedRecordsUids);
243  // Tell the browser what we have (using JSON later):
244  $top = $this->getStructureLevel(0);
245  $this->inlineData['config'][$nameObject] = array(
246  'table' => $foreign_table,
247  'md5' => md5($nameObject)
248  );
249  $this->inlineData['config'][$nameObject . self::Structure_Separator . $foreign_table] = array(
250  'min' => $minitems,
251  'max' => $maxitems,
252  'sortable' => $config['appearance']['useSortable'],
253  'top' => array(
254  'table' => $top['table'],
255  'uid' => $top['uid']
256  ),
257  'context' => array(
258  'config' => $config,
259  'hmac' => GeneralUtility::hmac(serialize($config)),
260  ),
261  );
262  // Set a hint for nested IRRE and tab elements:
263  $this->inlineData['nested'][$nameObject] = $this->fObj->getDynNestedStack(FALSE, $this->isAjaxCall);
264  // If relations are required to be unique, get the uids that have already been used on the foreign side of the relation
265  if ($config['foreign_unique']) {
266  // If uniqueness *and* selector are set, they should point to the same field - so, get the configuration of one:
267  $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_unique']);
268  // Get the used unique ids:
269  $uniqueIds = $this->getUniqueIds($relatedRecords['records'], $config, $selConfig['type'] == 'groupdb');
270  $possibleRecords = $this->getPossibleRecords($table, $field, $row, $config, 'foreign_unique');
271  $uniqueMax = $config['appearance']['useCombination'] || $possibleRecords === FALSE ? -1 : count($possibleRecords);
272  $this->inlineData['unique'][$nameObject . self::Structure_Separator . $foreign_table] = array(
273  'max' => $uniqueMax,
274  'used' => $uniqueIds,
275  'type' => $selConfig['type'],
276  'table' => $config['foreign_table'],
277  'elTable' => $selConfig['table'],
278  // element/record table (one step down in hierarchy)
279  'field' => $config['foreign_unique'],
280  'selector' => $selConfig['selector'],
281  'possible' => $this->getPossibleRecordsFlat($possibleRecords)
282  );
283  }
284  // Render the localization links
285  if ($language > 0 && $row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0 && MathUtility::canBeInterpretedAsInteger($row['uid'])) {
286  // Add the "Localize all records" link before all child records:
287  if (isset($config['appearance']['showAllLocalizationLink']) && $config['appearance']['showAllLocalizationLink']) {
288  $localizationLinks .= ' ' . $this->getLevelInteractionLink('localize', $nameObject . self::Structure_Separator . $foreign_table, $config);
289  }
290  // Add the "Synchronize with default language" link before all child records:
291  if (isset($config['appearance']['showSynchronizationLink']) && $config['appearance']['showSynchronizationLink']) {
292  $localizationLinks .= ' ' . $this->getLevelInteractionLink('synchronize', $nameObject . self::Structure_Separator . $foreign_table, $config);
293  }
294  }
295  // If it's required to select from possible child records (reusable children), add a selector box
296  if ($config['foreign_selector'] && $config['appearance']['showPossibleRecordsSelector'] !== FALSE) {
297  // If not already set by the foreign_unique, set the possibleRecords here and the uniqueIds to an empty array
298  if (!$config['foreign_unique']) {
299  $possibleRecords = $this->getPossibleRecords($table, $field, $row, $config);
300  $uniqueIds = array();
301  }
302  $selectorBox = $this->renderPossibleRecordsSelector($possibleRecords, $config, $uniqueIds);
303  $item .= $selectorBox . $localizationLinks;
304  }
305  // Render the level links (create new record):
306  $levelLinks = $this->getLevelInteractionLink('newRecord', $nameObject . self::Structure_Separator . $foreign_table, $config);
307 
308  // Wrap all inline fields of a record with a <div> (like a container)
309  $item .= '<div id="' . $nameObject . '">';
310  // Define how to show the "Create new record" link - if there are more than maxitems, hide it
311  if ($relatedRecords['count'] >= $maxitems || $uniqueMax > 0 && $relatedRecords['count'] >= $uniqueMax) {
312  $config['inline']['inlineNewButtonStyle'] = 'display: none;';
313  }
314  // Add the level links before all child records:
315  if (in_array($config['appearance']['levelLinksPosition'], array('both', 'top'))) {
316  $item .= $levelLinks . $localizationLinks;
317  }
318  $item .= '<div id="' . $nameObject . '_records">';
319  $relationList = array();
320  if (count($relatedRecords['records'])) {
321  foreach ($relatedRecords['records'] as $rec) {
322  $item .= $this->renderForeignRecord($row['uid'], $rec, $config);
323  if (!isset($rec['__virtual']) || !$rec['__virtual']) {
324  $relationList[] = $rec['uid'];
325  }
326  }
327  }
328  $item .= '</div>';
329  // Add the level links after all child records:
330  if (in_array($config['appearance']['levelLinksPosition'], array('both', 'bottom'))) {
331  $item .= $levelLinks . $localizationLinks;
332  }
333  if (is_array($config['customControls'])) {
334  $item .= '<div id="' . $nameObject . '_customControls">';
335  foreach ($config['customControls'] as $customControlConfig) {
336  $parameters = array(
337  'table' => $table,
338  'field' => $field,
339  'row' => $row,
340  'nameObject' => $nameObject,
341  'nameForm' => $nameForm,
342  'config' => $config
343  );
344  $item .= GeneralUtility::callUserFunction($customControlConfig, $parameters, $this);
345  }
346  $item .= '</div>';
347  }
348  // Add Drag&Drop functions for sorting to FormEngine::$additionalJS_post
349  if (count($relationList) > 1 && $config['appearance']['useSortable']) {
350  $this->addJavaScriptSortable($nameObject . '_records');
351  }
352  // Publish the uids of the child records in the given order to the browser
353  $item .= '<input type="hidden" name="' . $nameForm . '" value="' . implode(',', $relationList) . '" class="inlineRecord" />';
354  // Close the wrap for all inline fields (container)
355  $item .= '</div>';
356  // On finishing this section, remove the last item from the structure stack
357  $this->popStructure();
358  // If this was the first call to the inline type, restore the values
359  if (!$this->getStructureDepth()) {
360  unset($this->inlineFirstPid);
361  }
362  return $item;
363  }
364 
365  /*
366  *
367  * Regular rendering of forms, fields, etc.
368  *
369  */
370 
380  public function renderForeignRecord($parentUid, $rec, $config = array()) {
381  $foreign_table = $config['foreign_table'];
382  $foreign_selector = $config['foreign_selector'];
383  // Register default localization content:
384  $parent = $this->getStructureLevel(-1);
385  if (isset($parent['localizationMode']) && $parent['localizationMode'] != FALSE) {
386  $this->fObj->registerDefaultLanguageData($foreign_table, $rec);
387  }
388  // Send a mapping information to the browser via JSON:
389  // e.g. data[<curTable>][<curId>][<curField>] => data-<pid>-<parentTable>-<parentId>-<parentField>-<curTable>-<curId>-<curField>
390  $this->inlineData['map'][$this->inlineNames['form']] = $this->inlineNames['object'];
391  // Set this variable if we handle a brand new unsaved record:
392  $isNewRecord = !MathUtility::canBeInterpretedAsInteger($rec['uid']);
393  // Set this variable if the record is virtual and only show with header and not editable fields:
394  $isVirtualRecord = isset($rec['__virtual']) && $rec['__virtual'];
395  // If there is a selector field, normalize it:
396  if ($foreign_selector) {
397  $rec[$foreign_selector] = $this->normalizeUid($rec[$foreign_selector]);
398  }
399  if (!$this->checkAccess(($isNewRecord ? 'new' : 'edit'), $foreign_table, $rec['uid'])) {
400  return FALSE;
401  }
402  // Get the current naming scheme for DOM name/id attributes:
403  $nameObject = $this->inlineNames['object'];
404  $appendFormFieldNames = '[' . $foreign_table . '][' . $rec['uid'] . ']';
405  $objectId = $nameObject . self::Structure_Separator . $foreign_table . self::Structure_Separator . $rec['uid'];
406  // Put the current level also to the dynNestedStack of FormEngine:
407  $this->fObj->pushToDynNestedStack('inline', $objectId);
408  $class = '';
409  if (!$isVirtualRecord) {
410  // Get configuration:
411  $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
412  $expandAll = isset($config['appearance']['collapseAll']) && !$config['appearance']['collapseAll'];
413  $ajaxLoad = isset($config['appearance']['ajaxLoad']) && !$config['appearance']['ajaxLoad'] ? FALSE : TRUE;
414  if ($isNewRecord) {
415  // Show this record expanded or collapsed
416  $isExpanded = $expandAll || (!$collapseAll ? 1 : 0);
417  } else {
418  $isExpanded = $config['renderFieldsOnly'] || !$collapseAll && $this->getExpandedCollapsedState($foreign_table, $rec['uid']) || $expandAll;
419  }
420  // Render full content ONLY IF this is a AJAX-request, a new record, the record is not collapsed or AJAX-loading is explicitly turned off
421  if ($isNewRecord || $isExpanded || !$ajaxLoad) {
422  $combination = $this->renderCombinationTable($rec, $appendFormFieldNames, $config);
423  $overruleTypesArray = isset($config['foreign_types']) ? $config['foreign_types'] : array();
424  $fields = $this->renderMainFields($foreign_table, $rec, $overruleTypesArray);
425  $fields = $this->wrapFormsSection($fields);
426  // Replace returnUrl in Wizard-Code, if this is an AJAX call
427  $ajaxArguments = GeneralUtility::_GP('ajax');
428  if (isset($ajaxArguments[2]) && trim($ajaxArguments[2]) != '') {
429  $fields = str_replace('P[returnUrl]=%2F' . rawurlencode(TYPO3_mainDir) . 'ajax.php', 'P[returnUrl]=' . rawurlencode($ajaxArguments[2]), $fields);
430  }
431  } else {
432  $combination = '';
433  // This string is the marker for the JS-function to check if the full content has already been loaded
434  $fields = '<!--notloaded-->';
435  }
436  if ($isNewRecord) {
437  // Get the top parent table
438  $top = $this->getStructureLevel(0);
439  $ucFieldName = 'uc[inlineView][' . $top['table'] . '][' . $top['uid'] . ']' . $appendFormFieldNames;
440  // Set additional fields for processing for saving
441  $fields .= '<input type="hidden" name="' . $this->prependFormFieldNames . $appendFormFieldNames . '[pid]" value="' . $rec['pid'] . '"/>';
442  $fields .= '<input type="hidden" name="' . $ucFieldName . '" value="' . $isExpanded . '" />';
443  } else {
444  // Set additional field for processing for saving
445  $fields .= '<input type="hidden" name="' . $this->prependCmdFieldNames . $appendFormFieldNames . '[delete]" value="1" disabled="disabled" />';
446  if (!$isExpanded
447  && !empty($GLOBALS['TCA'][$foreign_table]['ctrl']['enablecolumns']['disabled'])
448  && $ajaxLoad
449  ) {
450  $checked = !empty($rec['hidden']) ? ' checked="checked"' : '';
451  $fields .= '<input type="checkbox" name="' . $this->prependFormFieldNames . $appendFormFieldNames . '[hidden]_0" value="1"' . $checked . ' />';
452  $fields .= '<input type="input" name="' . $this->prependFormFieldNames . $appendFormFieldNames . '[hidden]" value="' . $rec['hidden'] . '" />';
453  }
454  }
455  // If this record should be shown collapsed
456  if (!$isExpanded) {
457  $class = 't3-form-field-container-inline-collapsed';
458  }
459  }
460  if ($config['renderFieldsOnly']) {
461  $out = $fields . $combination;
462  } else {
463  // Set the record container with data for output
464  if ($isVirtualRecord) {
465  $class .= ' t3-form-field-container-inline-placeHolder';
466  }
467  if (isset($rec['hidden']) && (int)$rec['hidden']) {
468  $class .= ' t3-form-field-container-inline-hidden';
469  }
470  $out = '<div class="t3-form-field-record-inline" id="' . $objectId . '_fields" data-expandSingle="' . ($config['appearance']['expandSingle'] ? 1 : 0) . '" data-returnURL="' . htmlspecialchars(GeneralUtility::getIndpEnv('REQUEST_URI')) . '">' . $fields . $combination . '</div>';
471  $header = IconUtility::getSpriteIcon('apps-irre-' . ($class != '' ? 'collapsed' : 'expanded'));
472  $header .= $this->renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
473  $out = '<div class="t3-form-field-header-inline" id="' . $objectId . '_header">' . $header . '</div>' . $out;
474  // Wrap the header, fields and combination part of a child record with a div container
475  $classMSIE = $this->fObj->clientInfo['BROWSER'] == 'msie' && $this->fObj->clientInfo['VERSION'] < 8 ? 'MSIE' : '';
476  $class .= ' inlineDiv' . $classMSIE . ($isNewRecord ? ' inlineIsNewRecord' : '');
477  $out = '<div id="' . $objectId . '_div" class="t3-form-field-container-inline ' . trim($class) . '">' . $out . '</div>';
478  }
479  // Remove the current level also from the dynNestedStack of FormEngine:
480  $this->fObj->popFromDynNestedStack();
481  return $out;
482  }
483 
492  protected function renderMainFields($table, array $row, array $overruleTypesArray = array()) {
493  // The current render depth of \TYPO3\CMS\Backend\Form\FormEngine
494  $depth = $this->fObj->renderDepth;
495  // If there is some information about already rendered palettes of our parent, store this info:
496  if (isset($this->fObj->palettesRendered[$depth][$table])) {
497  $palettesRendered = $this->fObj->palettesRendered[$depth][$table];
498  }
499  // Render the form:
500  $content = $this->fObj->getMainFields($table, $row, $depth, $overruleTypesArray);
501  // If there was some info about rendered palettes stored, write it back for our parent:
502  if (isset($palettesRendered)) {
503  $this->fObj->palettesRendered[$depth][$table] = $palettesRendered;
504  }
505  return $content;
506  }
507 
520  public function renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord = FALSE) {
521  // Init:
522  $objectId = $this->inlineNames['object'] . self::Structure_Separator . $foreign_table . self::Structure_Separator . $rec['uid'];
523  // We need the returnUrl of the main script when loading the fields via AJAX-call (to correct wizard code, so include it as 3rd parameter)
524  // Pre-Processing:
525  $isOnSymmetricSide = RelationHandler::isOnSymmetricSide($parentUid, $config, $rec);
526  $hasForeignLabel = !$isOnSymmetricSide && $config['foreign_label'] ? TRUE : FALSE;
527  $hasSymmetricLabel = $isOnSymmetricSide && $config['symmetric_label'] ? TRUE : FALSE;
528 
529  // Get the record title/label for a record:
530  // Try using a self-defined user function only for formatted labels
531  if (isset($GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc'])) {
532  $params = array(
533  'table' => $foreign_table,
534  'row' => $rec,
535  'title' => '',
536  'isOnSymmetricSide' => $isOnSymmetricSide,
537  'options' => isset($GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc_options'])
538  ? $GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc_options']
539  : array(),
540  'parent' => array(
541  'uid' => $parentUid,
542  'config' => $config
543  )
544  );
545  // callUserFunction requires a third parameter, but we don't want to give $this as reference!
546  $null = NULL;
547  GeneralUtility::callUserFunction($GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc'], $params, $null);
548  $recTitle = $params['title'];
549 
550  // Try using a normal self-defined user function
551  } elseif (isset($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc'])) {
552  $params = array(
553  'table' => $foreign_table,
554  'row' => $rec,
555  'title' => '',
556  'isOnSymmetricSide' => $isOnSymmetricSide,
557  'parent' => array(
558  'uid' => $parentUid,
559  'config' => $config
560  )
561  );
562  // callUserFunction requires a third parameter, but we don't want to give $this as reference!
563  $null = NULL;
564  GeneralUtility::callUserFunction($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc'], $params, $null);
565  $recTitle = $params['title'];
566  } elseif ($hasForeignLabel || $hasSymmetricLabel) {
567  $titleCol = $hasForeignLabel ? $config['foreign_label'] : $config['symmetric_label'];
568  $foreignConfig = $this->getPossibleRecordsSelectorConfig($config, $titleCol);
569  // Render title for everything else than group/db:
570  if ($foreignConfig['type'] != 'groupdb') {
571  $recTitle = BackendUtility::getProcessedValueExtra($foreign_table, $titleCol, $rec[$titleCol], 0, 0, FALSE);
572  } else {
573  // $recTitle could be something like: "tx_table_123|...",
574  $valueParts = GeneralUtility::trimExplode('|', $rec[$titleCol]);
575  $itemParts = GeneralUtility::revExplode('_', $valueParts[0], 2);
576  $recTemp = BackendUtility::getRecordWSOL($itemParts[0], $itemParts[1]);
577  $recTitle = BackendUtility::getRecordTitle($itemParts[0], $recTemp, FALSE);
578  }
579  $recTitle = BackendUtility::getRecordTitlePrep($recTitle);
580  if (trim($recTitle) === '') {
581  $recTitle = BackendUtility::getNoRecordTitle(TRUE);
582  }
583  } else {
584  $recTitle = BackendUtility::getRecordTitle($foreign_table, $rec, TRUE);
585  }
586 
587  $altText = BackendUtility::getRecordIconAltText($rec, $foreign_table);
588  $iconImg = IconUtility::getSpriteIconForRecord($foreign_table, $rec, array('title' => htmlspecialchars($altText), 'id' => $objectId . '_icon'));
589  $label = '<span id="' . $objectId . '_label">' . $recTitle . '</span>';
590  $ctrl = $this->renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
591  $thumbnail = FALSE;
592 
593  // Renders a thumbnail for the header
594  if (!empty($config['appearance']['headerThumbnail']['field'])) {
595  $fieldValue = $rec[$config['appearance']['headerThumbnail']['field']];
596  $firstElement = array_shift(GeneralUtility::trimExplode(',', $fieldValue));
597  $fileUid = array_pop(BackendUtility::splitTable_Uid($firstElement));
598 
599  if (!empty($fileUid)) {
600  $fileObject = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->getFileObject($fileUid);
601  if ($fileObject && $fileObject->isMissing()) {
602  $flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility::getFlashMessageForMissingFile($fileObject);
603  $thumbnail = $flashMessage->render();
604  } elseif($fileObject) {
605  $imageSetup = $config['appearance']['headerThumbnail'];
606  unset($imageSetup['field']);
607  $imageSetup = array_merge(array('width' => '45', 'height' => '45c'), $imageSetup);
608  $processedImage = $fileObject->process(\TYPO3\CMS\Core\Resource\ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, $imageSetup);
609  // Only use a thumbnail if the processing was successful.
610  if (!$processedImage->usesOriginalFile()) {
611  $imageUrl = $processedImage->getPublicUrl(TRUE);
612  $thumbnail = '<img class="t3-form-field-header-inline-thumbnail-image" src="' . $imageUrl . '" alt="' . htmlspecialchars($altText) . '" title="' . htmlspecialchars($altText) . '">';
613  }
614  }
615  }
616  }
617 
618  if (!empty($config['appearance']['headerThumbnail']['field']) && $thumbnail) {
619  $headerClasses = ' t3-form-field-header-inline-has-thumbnail';
620  $mediaContainer = '<div class="t3-form-field-header-inline-thumbnail" id="' . $objectId . '_thumbnailcontainer">' . $thumbnail . '</div>';
621  } else {
622  $headerClasses = ' t3-form-field-header-inline-has-icon';
623  $mediaContainer = '<div class="t3-form-field-header-inline-icon" id="' . $objectId . '_iconcontainer">' . $iconImg . '</div>';
624  }
625 
626  $header = '<div class="t3-form-field-header-inline-wrap' . $headerClasses . '">'
627  . '<div class="t3-form-field-header-inline-ctrl">' . $ctrl . '</div>'
628  . '<div class="t3-form-field-header-inline-body">'
629  . $mediaContainer
630  . '<div class="t3-form-field-header-inline-summary">' . $label . '</div>'
631  . '</div>'
632  . '</div>';
633 
634  return $header;
635  }
636 
650  public function renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config = array(), $isVirtualRecord = FALSE) {
651  // Initialize:
652  $cells = array();
653  $isNewItem = substr($rec['uid'], 0, 3) == 'NEW';
654  $isParentExisting = MathUtility::canBeInterpretedAsInteger($parentUid);
655  $tcaTableCtrl = &$GLOBALS['TCA'][$foreign_table]['ctrl'];
656  $tcaTableCols = &$GLOBALS['TCA'][$foreign_table]['columns'];
657  $isPagesTable = $foreign_table == 'pages' ? TRUE : FALSE;
658  $isSysFileReferenceTable = $foreign_table === 'sys_file_reference';
659  $isOnSymmetricSide = RelationHandler::isOnSymmetricSide($parentUid, $config, $rec);
660  $enableManualSorting = $tcaTableCtrl['sortby'] || $config['MM'] || !$isOnSymmetricSide && $config['foreign_sortby'] || $isOnSymmetricSide && $config['symmetric_sortby'] ? TRUE : FALSE;
661  $nameObject = $this->inlineNames['object'];
662  $nameObjectFt = $nameObject . self::Structure_Separator . $foreign_table;
663  $nameObjectFtId = $nameObjectFt . self::Structure_Separator . $rec['uid'];
664  $calcPerms = $GLOBALS['BE_USER']->calcPerms(BackendUtility::readPageAccess($rec['pid'], $GLOBALS['BE_USER']->getPagePermsClause(1)));
665  // If the listed table is 'pages' we have to request the permission settings for each page:
666  $localCalcPerms = FALSE;
667  if ($isPagesTable) {
668  $localCalcPerms = $GLOBALS['BE_USER']->calcPerms(BackendUtility::getRecord('pages', $rec['uid']));
669  }
670  // This expresses the edit permissions for this particular element:
671  $permsEdit = $isPagesTable && $localCalcPerms & 2 || !$isPagesTable && $calcPerms & 16;
672  // Controls: Defines which controls should be shown
673  $enabledControls = $config['appearance']['enabledControls'];
674  // Hook: Can disable/enable single controls for specific child records:
675  foreach ($this->hookObjects as $hookObj) {
676  $hookObj->renderForeignRecordHeaderControl_preProcess($parentUid, $foreign_table, $rec, $config, $isVirtualRecord, $enabledControls);
677  }
678  // Icon to visualize that a required field is nested in this inline level:
679  $cells['required'] = '<img name="' . $nameObjectFtId . '_req" src="clear.gif" width="10" height="10" hspace="4" vspace="3" alt="" />';
680  if (isset($rec['__create'])) {
681  $cells['localize.isLocalizable'] = IconUtility::getSpriteIcon('actions-edit-localize-status-low', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:localize.isLocalizable', TRUE)));
682  } elseif (isset($rec['__remove'])) {
683  $cells['localize.wasRemovedInOriginal'] = IconUtility::getSpriteIcon('actions-edit-localize-status-high', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:localize.wasRemovedInOriginal', TRUE)));
684  }
685  // "Info": (All records)
686  if ($enabledControls['info'] && !$isNewItem) {
687  if ($rec['table_local'] === 'sys_file') {
688  $uid = (int)substr($rec['uid_local'], 9);
689  $table = '_FILE';
690  } else {
691  $uid = $rec['uid'];
692  $table = $foreign_table;
693  }
694  $cells['info'] = '<a href="#" onclick="' . htmlspecialchars(('top.launchView(\'' . $table . '\', \'' . $uid . '\'); return false;')) . '">' . IconUtility::getSpriteIcon('status-dialog-information', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:showInfo', TRUE))) . '</a>';
695  }
696  // If the table is NOT a read-only table, then show these links:
697  if (!$tcaTableCtrl['readOnly'] && !$isVirtualRecord) {
698  // "New record after" link (ONLY if the records in the table are sorted by a "sortby"-row or if default values can depend on previous record):
699  if ($enabledControls['new'] && ($enableManualSorting || $tcaTableCtrl['useColumnsForDefaultValues'])) {
700  if (!$isPagesTable && $calcPerms & 16 || $isPagesTable && $calcPerms & 8) {
701  $onClick = 'return inline.createNewRecord(\'' . $nameObjectFt . '\',\'' . $rec['uid'] . '\')';
702  $class = ' class="inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'] . '"';
703  if ($config['inline']['inlineNewButtonStyle']) {
704  $style = ' style="' . $config['inline']['inlineNewButtonStyle'] . '"';
705  }
706  $cells['new'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '"' . $class . $style . '>' . IconUtility::getSpriteIcon(('actions-' . ($isPagesTable ? 'page' : 'document') . '-new'), array(
707  'title' => $GLOBALS['LANG']->sL(('LLL:EXT:lang/locallang_mod_web_list.xlf:new' . ($isPagesTable ? 'Page' : 'Record')), TRUE)
708  )) . '</a>';
709  }
710  }
711  // "Up/Down" links
712  if ($enabledControls['sort'] && $permsEdit && $enableManualSorting) {
713  $onClick = 'return inline.changeSorting(\'' . $nameObjectFtId . '\', \'1\')';
714  // Up
715  $style = $config['inline']['first'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
716  $cells['sort.up'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '" class="sortingUp" ' . $style . '>' . IconUtility::getSpriteIcon('actions-move-up', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:moveUp', TRUE))) . '</a>';
717  $onClick = 'return inline.changeSorting(\'' . $nameObjectFtId . '\', \'-1\')';
718  // Down
719  $style = $config['inline']['last'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
720  $cells['sort.down'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '" class="sortingDown" ' . $style . '>' . IconUtility::getSpriteIcon('actions-move-down', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:moveDown', TRUE))) . '</a>';
721  }
722  // "Delete" link:
723  if ($enabledControls['delete'] && ($isPagesTable && $localCalcPerms & 4
724  || !$isPagesTable && $calcPerms & 16
725  || $isSysFileReferenceTable && $calcPerms & 2)) {
726 
727  $onClick = 'inline.deleteRecord(\'' . $nameObjectFtId . '\');';
728  $cells['delete'] = '<a href="#" onclick="' . htmlspecialchars(('if (confirm(' . GeneralUtility::quoteJSvalue($GLOBALS['LANG']->getLL('deleteWarning')) . ')) { ' . $onClick . ' } return false;')) . '">' . IconUtility::getSpriteIcon('actions-edit-delete', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:delete', TRUE))) . '</a>';
729  }
730 
731  // "Hide/Unhide" links:
732  $hiddenField = $tcaTableCtrl['enablecolumns']['disabled'];
733  if ($enabledControls['hide'] && $permsEdit && $hiddenField && $tcaTableCols[$hiddenField] && (!$tcaTableCols[$hiddenField]['exclude'] || $GLOBALS['BE_USER']->check('non_exclude_fields', $foreign_table . ':' . $hiddenField))) {
734  $onClick = 'return inline.enableDisableRecord(\'' . $nameObjectFtId . '\')';
735  if ($rec[$hiddenField]) {
736  $cells['hide.unhide'] = '<a href="#" class="hiddenHandle" onclick="' . htmlspecialchars($onClick) . '">' . IconUtility::getSpriteIcon('actions-edit-unhide', array(
737  'title' => $GLOBALS['LANG']->sL(('LLL:EXT:lang/locallang_mod_web_list.xlf:unHide' . ($isPagesTable ? 'Page' : '')), TRUE),
738  'id' => ($nameObjectFtId . '_disabled')
739  )) . '</a>';
740  } else {
741  $cells['hide.hide'] = '<a href="#" class="hiddenHandle" onclick="' . htmlspecialchars($onClick) . '">' . IconUtility::getSpriteIcon('actions-edit-hide', array(
742  'title' => $GLOBALS['LANG']->sL(('LLL:EXT:lang/locallang_mod_web_list.xlf:hide' . ($isPagesTable ? 'Page' : '')), TRUE),
743  'id' => ($nameObjectFtId . '_disabled')
744  )) . '</a>';
745  }
746  }
747  // Drag&Drop Sorting: Sortable handler for script.aculo.us
748  if ($enabledControls['dragdrop'] && $permsEdit && $enableManualSorting && $config['appearance']['useSortable']) {
749  $cells['dragdrop'] = IconUtility::getSpriteIcon('actions-move-move', array('data-id' => $rec['uid'], 'class' => 'sortableHandle', 'title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.move', TRUE)));
750  }
751  } elseif ($isVirtualRecord && $isParentExisting) {
752  if ($enabledControls['localize'] && isset($rec['__create'])) {
753  $onClick = 'inline.synchronizeLocalizeRecords(\'' . $nameObjectFt . '\', ' . $rec['uid'] . ');';
754  $cells['localize'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . IconUtility::getSpriteIcon('actions-document-localize', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:localize', TRUE))) . '</a>';
755  }
756  }
757  // If the record is edit-locked by another user, we will show a little warning sign:
758  if ($lockInfo = BackendUtility::isRecordLocked($foreign_table, $rec['uid'])) {
759  $cells['locked'] = '<a href="#" onclick="alert(' . GeneralUtility::quoteJSvalue($lockInfo['msg']) . ');return false;">' . IconUtility::getSpriteIcon('status-warning-in-use', array('title' => $lockInfo['msg'])) . '</a>';
760  }
761  // Hook: Post-processing of single controls for specific child records:
762  foreach ($this->hookObjects as $hookObj) {
763  $hookObj->renderForeignRecordHeaderControl_postProcess($parentUid, $foreign_table, $rec, $config, $isVirtualRecord, $cells);
764  }
765  return '<!-- CONTROL PANEL: ' . $foreign_table . ':' . $rec['uid'] . ' -->' . implode('', $cells);
766  }
767 
779  public function renderCombinationTable(&$rec, $appendFormFieldNames, $config = array()) {
780  $foreign_table = $config['foreign_table'];
781  $foreign_selector = $config['foreign_selector'];
782  if ($foreign_selector && $config['appearance']['useCombination']) {
783  $comboConfig = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector]['config'];
784  // If record does already exist, load it:
785  if ($rec[$foreign_selector] && MathUtility::canBeInterpretedAsInteger($rec[$foreign_selector])) {
786  $comboRecord = $this->getRecord($this->inlineFirstPid, $comboConfig['foreign_table'], $rec[$foreign_selector]);
787  $isNewRecord = FALSE;
788  } else {
789  $comboRecord = $this->getNewRecord($this->inlineFirstPid, $comboConfig['foreign_table']);
790  $isNewRecord = TRUE;
791  }
792  $flashMessage = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:warning.inline_use_combination'), '', FlashMessage::WARNING);
793  $out = $flashMessage->render();
794  // Get the FormEngine interpretation of the TCA of the child table
795  $out .= $this->renderMainFields($comboConfig['foreign_table'], $comboRecord);
796  $out = $this->wrapFormsSection($out, array(), array());
797  // If this is a new record, add a pid value to store this record and the pointer value for the intermediate table
798  if ($isNewRecord) {
799  $comboFormFieldName = $this->prependFormFieldNames . '[' . $comboConfig['foreign_table'] . '][' . $comboRecord['uid'] . '][pid]';
800  $out .= '<input type="hidden" name="' . $comboFormFieldName . '" value="' . $comboRecord['pid'] . '" />';
801  }
802  // If the foreign_selector field is also responsible for uniqueness, tell the browser the uid of the "other" side of the relation
803  if ($isNewRecord || $config['foreign_unique'] == $foreign_selector) {
804  $parentFormFieldName = $this->prependFormFieldNames . $appendFormFieldNames . '[' . $foreign_selector . ']';
805  $out .= '<input type="hidden" name="' . $parentFormFieldName . '" value="' . $comboRecord['uid'] . '" />';
806  }
807  }
808  return $out;
809  }
810 
821  public function renderPossibleRecordsSelector($selItems, $conf, $uniqueIds = array()) {
822  $foreign_selector = $conf['foreign_selector'];
823  $selConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_selector);
824  if ($selConfig['type'] == 'select') {
825  $item = $this->renderPossibleRecordsSelectorTypeSelect($selItems, $conf, $selConfig['PA'], $uniqueIds);
826  } elseif ($selConfig['type'] == 'groupdb') {
827  $item = $this->renderPossibleRecordsSelectorTypeGroupDB($conf, $selConfig['PA']);
828  }
829  return $item;
830  }
831 
843  public function renderPossibleRecordsSelectorTypeSelect($selItems, $conf, &$PA, $uniqueIds = array()) {
844  $foreign_table = $conf['foreign_table'];
845  $foreign_selector = $conf['foreign_selector'];
846  $PA = array();
847  $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector];
848  $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ?: $PA['fieldConf']['config']['type'];
849  // Using "form_type" locally in this script
850  $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table, array(), $foreign_selector);
851  $config = $PA['fieldConf']['config'];
852  //TODO: $disabled is not present - should be read from config?
853  $disabled = FALSE;
854  if (!$disabled) {
855  // Create option tags:
856  $opt = array();
857  $styleAttrValue = '';
858  foreach ($selItems as $p) {
859  if ($config['iconsInOptionTags']) {
860  $styleAttrValue = $this->fObj->optionTagStyle($p[2]);
861  }
862  if (!in_array($p[1], $uniqueIds)) {
863  $opt[] = '<option value="' . htmlspecialchars($p[1]) . '"' . ' style="' . (in_array($p[1], $uniqueIds) ? '' : '') . ($styleAttrValue ? ' style="' . htmlspecialchars($styleAttrValue) : '') . '">' . htmlspecialchars($p[0]) . '</option>';
864  }
865  }
866  // Put together the selector box:
867  $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="' . htmlspecialchars($config['itemListStyle']) . '"' : ' style="' . $this->fObj->defaultMultipleSelectorStyle . '"';
868  $size = (int)$conf['size'];
869  $size = $conf['autoSizeMax'] ? MathUtility::forceIntegerInRange(count($selItems) + 1, MathUtility::forceIntegerInRange($size, 1), $conf['autoSizeMax']) : $size;
870  $onChange = 'return inline.importNewRecord(\'' . $this->inlineNames['object'] . self::Structure_Separator . $conf['foreign_table'] . '\')';
871  $item = '
872  <select id="' . $this->inlineNames['object'] . self::Structure_Separator . $conf['foreign_table'] . '_selector"' . $this->fObj->insertDefStyle('select') . ($size ? ' size="' . $size . '"' : '') . ' onchange="' . htmlspecialchars($onChange) . '"' . $PA['onFocus'] . $selector_itemListStyle . ($conf['foreign_unique'] ? ' isunique="isunique"' : '') . '>
873  ' . implode('
874  ', $opt) . '
875  </select>';
876  // Add a "Create new relation" link for adding new relations
877  // This is necessary, if the size of the selector is "1" or if
878  // there is only one record item in the select-box, that is selected by default
879  // The selector-box creates a new relation on using a onChange event (see some line above)
880  if (!empty($conf['appearance']['createNewRelationLinkTitle'])) {
881  $createNewRelationText = $GLOBALS['LANG']->sL($conf['appearance']['createNewRelationLinkTitle'], TRUE);
882  } else {
883  $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:cm.createNewRelation', TRUE);
884  }
885  $item .= ' <a href="#" class="t3-button" onclick="' . htmlspecialchars($onChange) . '" align="abstop">' . IconUtility::getSpriteIcon('actions-document-new', array('title' => $createNewRelationText)) . $createNewRelationText . '</a>';
886  $item = '<div class="t3-form-field-group">' . $item . '</div>';
887  }
888  return $item;
889  }
890 
900  public function renderPossibleRecordsSelectorTypeGroupDB($conf, &$PA) {
901  $config = $PA['fieldConf']['config'];
902  ArrayUtility::mergeRecursiveWithOverrule($config, $conf);
903  $foreign_table = $config['foreign_table'];
904  $allowed = $config['allowed'];
905  $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $foreign_table;
906  $mode = 'db';
907  $showUpload = FALSE;
908  if (!empty($config['appearance']['createNewRelationLinkTitle'])) {
909  $createNewRelationText = $GLOBALS['LANG']->sL($config['appearance']['createNewRelationLinkTitle'], TRUE);
910  } else {
911  $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:cm.createNewRelation', TRUE);
912  }
913  if (is_array($config['appearance'])) {
914  if (isset($config['appearance']['elementBrowserType'])) {
915  $mode = $config['appearance']['elementBrowserType'];
916  }
917  if ($mode === 'file') {
918  $showUpload = TRUE;
919  }
920  if (isset($config['appearance']['fileUploadAllowed'])) {
921  $showUpload = (bool)$config['appearance']['fileUploadAllowed'];
922  }
923  if (isset($config['appearance']['elementBrowserAllowed'])) {
924  $allowed = $config['appearance']['elementBrowserAllowed'];
925  }
926  }
927  $browserParams = '|||' . $allowed . '|' . $objectPrefix . '|inline.checkUniqueElement||inline.importElement';
928  $onClick = 'setFormValueOpenBrowser(\'' . $mode . '\', \'' . $browserParams . '\'); return false;';
929 
930  $item = '<a href="#" class="t3-button" onclick="' . htmlspecialchars($onClick) . '">';
931  $item .= IconUtility::getSpriteIcon('actions-insert-record', array('title' => $createNewRelationText));
932  $item .= $createNewRelationText . '</a>';
933 
934  if ($showUpload && $this->fObj->edit_docModuleUpload) {
935  $folder = $GLOBALS['BE_USER']->getDefaultUploadFolder();
936  if ($folder instanceof \TYPO3\CMS\Core\Resource\Folder) {
937  $maxFileSize = GeneralUtility::getMaxUploadFileSize() * 1024;
938  $item .= ' <a href="#" class="t3-button t3-drag-uploader"
939  style="display:none"
940  data-dropzone-target="#' . htmlspecialchars($this->inlineNames['object']) . '"
941  data-insert-dropzone-before="1"
942  data-file-irre-object="' . htmlspecialchars($objectPrefix) . '"
943  data-file-allowed="' . htmlspecialchars($allowed) . '"
944  data-target-folder="' . htmlspecialchars($folder->getCombinedIdentifier()) . '"
945  data-max-file-size="' . htmlspecialchars($maxFileSize) . '"
946  ><span class="t3-icon t3-icon-actions t3-icon-actions-edit t3-icon-edit-upload">&nbsp;</span>';
947  $item .= $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:file_upload.select-and-submit', TRUE);
948  $item .= '</a>';
949 
950  $this->loadDragUploadJs();
951  }
952  }
953 
954  return $item;
955  }
956 
960  protected function loadDragUploadJs() {
961 
963  $pageRenderer = $GLOBALS['SOBE']->doc->getPageRenderer();
964  $pageRenderer->loadRequireJsModule('TYPO3/CMS/Filelist/FileListLocalisation');
965  $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/DragUploader');
966  $pageRenderer->addInlineLanguagelabelFile(
967  \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('lang') . 'locallang_core.xlf',
968  'file_upload'
969  );
970  }
971 
981  protected function getLevelInteractionLink($type, $objectPrefix, $conf = array()) {
982  $nameObject = $this->inlineNames['object'];
983  $attributes = array();
984  switch ($type) {
985  case 'newRecord':
986  $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:cm.createnew', TRUE);
987  $icon = 'actions-document-new';
988  $className = 'typo3-newRecordLink';
989  $attributes['class'] = 't3-button inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'];
990  $attributes['onclick'] = 'return inline.createNewRecord(\'' . $objectPrefix . '\')';
991  if (!empty($conf['inline']['inlineNewButtonStyle'])) {
992  $attributes['style'] = $conf['inline']['inlineNewButtonStyle'];
993  }
994  if (!empty($conf['appearance']['newRecordLinkAddTitle'])) {
995  $title = sprintf(
996  $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:cm.createnew.link', TRUE),
997  $GLOBALS['LANG']->sL($GLOBALS['TCA'][$conf['foreign_table']]['ctrl']['title'], TRUE)
998  );
999  } elseif (isset($conf['appearance']['newRecordLinkTitle']) && $conf['appearance']['newRecordLinkTitle'] !== '') {
1000  $title = $GLOBALS['LANG']->sL($conf['appearance']['newRecordLinkTitle'], TRUE);
1001  }
1002  break;
1003  case 'localize':
1004  $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:localizeAllRecords', 1);
1005  $icon = 'actions-document-localize';
1006  $className = 'typo3-localizationLink';
1007  $attributes['class'] = 't3-button';
1008  $attributes['onclick'] = 'return inline.synchronizeLocalizeRecords(\'' . $objectPrefix . '\', \'localize\')';
1009  break;
1010  case 'synchronize':
1011  $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:synchronizeWithOriginalLanguage', TRUE);
1012  $icon = 'actions-document-synchronize';
1013  $className = 'typo3-synchronizationLink';
1014  $attributes['class'] = 't3-button inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'];
1015  $attributes['onclick'] = 'return inline.synchronizeLocalizeRecords(\'' . $objectPrefix . '\', \'synchronize\')';
1016  break;
1017  default:
1018  $title = '';
1019  $icon = '';
1020  $className = '';
1021  }
1022  // Create the link:
1023  $icon = $icon ? IconUtility::getSpriteIcon($icon, array('title' => htmlspecialchars($title))) : '';
1024  $link = $this->wrapWithAnchor($icon . $title, '#', $attributes);
1025  return '<div' . ($className ? ' class="' . $className . '"' : '') . '>' . $link . '</div>';
1026  }
1027 
1035  public function addJavaScriptSortable($objectId) {
1036  $this->fObj->additionalJS_post[] = '
1037  inline.createDragAndDropSorting("' . $objectId . '");
1038  ';
1039  }
1040 
1041  /*******************************************************
1042  *
1043  * Handling of AJAX calls
1044  *
1045  *******************************************************/
1054  public function processAjaxRequest($_, $ajaxObj) {
1055  $ajaxArguments = GeneralUtility::_GP('ajax');
1056  $ajaxIdParts = explode('::', $GLOBALS['ajaxID'], 2);
1057  if (isset($ajaxArguments) && is_array($ajaxArguments) && count($ajaxArguments)) {
1058  $ajaxMethod = $ajaxIdParts[1];
1059  switch ($ajaxMethod) {
1060  case 'createNewRecord':
1061 
1062  case 'synchronizeLocalizeRecords':
1063 
1064  case 'getRecordDetails':
1065  $this->isAjaxCall = TRUE;
1066  // Construct runtime environment for Inline Relational Record Editing:
1067  $this->processAjaxRequestConstruct($ajaxArguments);
1068  // Parse the DOM identifier (string), add the levels to the structure stack (array) and load the TCA config:
1069  $this->parseStructureString($ajaxArguments[0], TRUE);
1070  $this->injectAjaxConfiguration($ajaxArguments);
1071  // Render content:
1072  $ajaxObj->setContentFormat('jsonbody');
1073  $ajaxObj->setContent(call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments));
1074  break;
1075  case 'setExpandedCollapsedState':
1076  $ajaxObj->setContentFormat('jsonbody');
1077  call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments);
1078  break;
1079  }
1080  }
1081  }
1082 
1090  protected function injectAjaxConfiguration(array $ajaxArguments) {
1091  $level = $this->calculateStructureLevel(-1);
1092 
1093  if (empty($ajaxArguments['context']) || $level === FALSE) {
1094  return;
1095  }
1096 
1097  $current = &$this->inlineStructure['stable'][$level];
1098  $context = json_decode($ajaxArguments['context'], TRUE);
1099 
1100  if (GeneralUtility::hmac(serialize($context['config'])) !== $context['hmac']) {
1101  return;
1102  }
1103 
1104  $current['config'] = $context['config'];
1105  $current['localizationMode'] = BackendUtility::getInlineLocalizationMode(
1106  $current['table'],
1107  $current['config']
1108  );
1109  }
1110 
1121  protected function processAjaxRequestConstruct(&$ajaxArguments) {
1122  $GLOBALS['LANG']->includeLLFile('EXT:lang/locallang_alt_doc.xlf');
1123  // Create a new anonymous object:
1124  $GLOBALS['SOBE'] = new \stdClass();
1125  $GLOBALS['SOBE']->MOD_MENU = array(
1126  'showPalettes' => '',
1127  'showDescriptions' => '',
1128  'disableRTE' => ''
1129  );
1130  // Setting virtual document name
1131  $GLOBALS['SOBE']->MCONF['name'] = 'xMOD_alt_doc.php';
1132  // CLEANSE SETTINGS
1133  $GLOBALS['SOBE']->MOD_SETTINGS = BackendUtility::getModuleData($GLOBALS['SOBE']->MOD_MENU, GeneralUtility::_GP('SET'), $GLOBALS['SOBE']->MCONF['name']);
1134  // Create an instance of the document template object
1135  $GLOBALS['SOBE']->doc = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Template\\DocumentTemplate');
1136  $GLOBALS['SOBE']->doc->backPath = $GLOBALS['BACK_PATH'];
1137  // Initialize FormEngine (rendering the forms)
1138  $GLOBALS['SOBE']->tceforms = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Form\\FormEngine');
1139  $GLOBALS['SOBE']->tceforms->inline = $this;
1140  $GLOBALS['SOBE']->tceforms->RTEcounter = (int)array_shift($ajaxArguments);
1141  $GLOBALS['SOBE']->tceforms->initDefaultBEMode();
1142  $GLOBALS['SOBE']->tceforms->palettesCollapsed = !$GLOBALS['SOBE']->MOD_SETTINGS['showPalettes'];
1143  $GLOBALS['SOBE']->tceforms->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1144  $GLOBALS['SOBE']->tceforms->enableClickMenu = TRUE;
1145  $GLOBALS['SOBE']->tceforms->enableTabMenu = TRUE;
1146  // Clipboard is initialized:
1147  // Start clipboard
1148  $GLOBALS['SOBE']->tceforms->clipObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Clipboard\\Clipboard');
1149  // Initialize - reads the clipboard content from the user session
1150  $GLOBALS['SOBE']->tceforms->clipObj->initializeClipboard();
1151  }
1152 
1160  protected function getCommonScriptCalls(&$jsonArray, $config) {
1161  // Add data that would have been added at the top of a regular FormEngine call:
1162  if ($headTags = $this->getHeadTags()) {
1163  $jsonArray['headData'] = $headTags;
1164  }
1165  // Add the JavaScript data that would have been added at the bottom of a regular FormEngine call:
1166  $jsonArray['scriptCall'][] = $this->fObj->JSbottom($this->fObj->formName, TRUE);
1167  // If script.aculo.us Sortable is used, update the Observer to know the record:
1168  if ($config['appearance']['useSortable']) {
1169  $jsonArray['scriptCall'][] = 'inline.createDragAndDropSorting(\'' . $this->inlineNames['object'] . '_records\');';
1170  }
1171  // if FormEngine has some JavaScript code to be executed, just do it
1172  if ($this->fObj->extJSCODE) {
1173  $jsonArray['scriptCall'][] = $this->fObj->extJSCODE;
1174  }
1175  // activate "enable tabs" for textareas
1176  $jsonArray['scriptCall'][] = 'changeTextareaElements();';
1177  }
1178 
1185  protected function getErrorMessageForAJAX($message) {
1186  $jsonArray = array(
1187  'data' => $message,
1188  'scriptCall' => array(
1189  'alert("' . $message . '");'
1190  )
1191  );
1192  return $jsonArray;
1193  }
1194 
1204  public function createNewRecord($domObjectId, $foreignUid = 0) {
1205  // The current table - for this table we should add/import records
1206  $current = $this->inlineStructure['unstable'];
1207  // The parent table - this table embeds the current table
1208  $parent = $this->getStructureLevel(-1);
1209  $config = $parent['config'];
1210  // Get TCA 'config' of the parent table
1211  if (!$this->checkConfiguration($config)) {
1212  return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1213  }
1214  $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
1215  $expandSingle = isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle'];
1216  // Put the current level also to the dynNestedStack of FormEngine:
1217  $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1218  // Dynamically create a new record using \TYPO3\CMS\Backend\Form\DataPreprocessor
1219  if (!$foreignUid || !MathUtility::canBeInterpretedAsInteger($foreignUid) || $config['foreign_selector']) {
1220  $record = $this->getNewRecord($this->inlineFirstPid, $current['table']);
1221  // Set default values for new created records
1222  if (isset($config['foreign_record_defaults']) && is_array($config['foreign_record_defaults'])) {
1223  $foreignTableConfig = $GLOBALS['TCA'][$current['table']];
1224  // the following system relevant fields can't be set by foreign_record_defaults
1225  $notSettableFields = array(
1226  'uid', 'pid', 't3ver_oid', 't3ver_id', 't3ver_label', 't3ver_wsid', 't3ver_state', 't3ver_stage',
1227  't3ver_count', 't3ver_tstamp', 't3ver_move_id'
1228  );
1229  $configurationKeysForNotSettableFields = array(
1230  'crdate', 'cruser_id', 'delete', 'origUid', 'transOrigDiffSourceField', 'transOrigPointerField',
1231  'tstamp'
1232  );
1233  foreach ($configurationKeysForNotSettableFields as $configurationKey) {
1234  if (isset($foreignTableConfig['ctrl'][$configurationKey])) {
1235  $notSettableFields[] = $foreignTableConfig['ctrl'][$configurationKey];
1236  }
1237  }
1238  foreach ($config['foreign_record_defaults'] as $fieldName => $defaultValue) {
1239  if (isset($foreignTableConfig['columns'][$fieldName]) && !in_array($fieldName, $notSettableFields)) {
1240  $record[$fieldName] = $defaultValue;
1241  }
1242  }
1243  }
1244  // Set language of new child record to the language of the parent record:
1245  if ($parent['localizationMode'] === 'select') {
1246  $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1247  $parentLanguageField = $GLOBALS['TCA'][$parent['table']]['ctrl']['languageField'];
1248  $childLanguageField = $GLOBALS['TCA'][$current['table']]['ctrl']['languageField'];
1249  if ($parentRecord[$parentLanguageField] > 0) {
1250  $record[$childLanguageField] = $parentRecord[$parentLanguageField];
1251  }
1252  }
1253  } else {
1254  $record = $this->getRecord($this->inlineFirstPid, $current['table'], $foreignUid);
1255  }
1256  // Now there is a foreign_selector, so there is a new record on the intermediate table, but
1257  // this intermediate table holds a field, which is responsible for the foreign_selector, so
1258  // we have to set this field to the uid we get - or if none, to a new uid
1259  if ($config['foreign_selector'] && $foreignUid) {
1260  $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_selector']);
1261  // For a selector of type group/db, prepend the tablename (<tablename>_<uid>):
1262  $record[$config['foreign_selector']] = $selConfig['type'] != 'groupdb' ? '' : $selConfig['table'] . '_';
1263  $record[$config['foreign_selector']] .= $foreignUid;
1264  }
1265  // The HTML-object-id's prefix of the dynamically created record
1266  $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1267  $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1268  // Render the foreign record that should passed back to browser
1269  $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1270  if ($item === FALSE) {
1271  return $this->getErrorMessageForAJAX('Access denied');
1272  }
1273  if (!$current['uid']) {
1274  $jsonArray = array(
1275  'data' => $item,
1276  'scriptCall' => array(
1277  'inline.domAddNewRecord(\'bottom\',\'' . $this->inlineNames['object'] . '_records\',\'' . $objectPrefix . '\',json.data);',
1278  'inline.memorizeAddRecord(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\',null,\'' . $foreignUid . '\');'
1279  )
1280  );
1281  } else {
1282  $jsonArray = array(
1283  'data' => $item,
1284  'scriptCall' => array(
1285  'inline.domAddNewRecord(\'after\',\'' . $domObjectId . '_div' . '\',\'' . $objectPrefix . '\',json.data);',
1286  'inline.memorizeAddRecord(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\',\'' . $current['uid'] . '\',\'' . $foreignUid . '\');'
1287  )
1288  );
1289  }
1290  $this->getCommonScriptCalls($jsonArray, $config);
1291  // Collapse all other records if requested:
1292  if (!$collapseAll && $expandSingle) {
1293  $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\', \'' . $objectPrefix . '\', \'' . $record['uid'] . '\');';
1294  }
1295  // Tell the browser to scroll to the newly created record
1296  $jsonArray['scriptCall'][] = 'Element.scrollTo(\'' . $objectId . '_div\');';
1297  // Fade out and fade in the new record in the browser view to catch the user's eye
1298  $jsonArray['scriptCall'][] = 'inline.fadeOutFadeIn(\'' . $objectId . '_div\');';
1299  // Remove the current level also from the dynNestedStack of FormEngine:
1300  $this->fObj->popFromDynNestedStack();
1301  // Return the JSON array:
1302  return $jsonArray;
1303  }
1304 
1312  protected function synchronizeLocalizeRecords($_, $type) {
1313  $jsonArray = FALSE;
1314  if (GeneralUtility::inList('localize,synchronize', $type) || MathUtility::canBeInterpretedAsInteger($type)) {
1315  // The parent level:
1316  $parent = $this->getStructureLevel(-1);
1317  $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1318  $cmd = array();
1319  $cmd[$parent['table']][$parent['uid']]['inlineLocalizeSynchronize'] = $parent['field'] . ',' . $type;
1321  $tce = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
1322  $tce->stripslashes_values = FALSE;
1323  $tce->start(array(), $cmd);
1324  $tce->process_cmdmap();
1325  $newItemList = $tce->registerDBList[$parent['table']][$parent['uid']][$parent['field']];
1326  unset($tce);
1327  $jsonArray = $this->getExecuteChangesJsonArray($parentRecord[$parent['field']], $newItemList);
1328  $this->getCommonScriptCalls($jsonArray, $parent['config']);
1329  }
1330  return $jsonArray;
1331  }
1332 
1342  public function getRecordDetails($domObjectId) {
1343  // The current table - for this table we should add/import records
1344  $current = $this->inlineStructure['unstable'];
1345  // The parent table - this table embeds the current table
1346  $parent = $this->getStructureLevel(-1);
1347  // Get TCA 'config' of the parent table
1348  if (!$this->checkConfiguration($parent['config'])) {
1349  return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1350  }
1351  $config = $parent['config'];
1352  // Set flag in config so that only the fields are rendered
1353  $config['renderFieldsOnly'] = TRUE;
1354  $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
1355  $expandSingle = isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle'];
1356  // Put the current level also to the dynNestedStack of FormEngine:
1357  $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1358  $record = $this->getRecord($this->inlineFirstPid, $current['table'], $current['uid']);
1359  // The HTML-object-id's prefix of the dynamically created record
1360  $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1361  $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1362  $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1363  if ($item === FALSE) {
1364  return $this->getErrorMessageForAJAX('Access denied');
1365  }
1366  $jsonArray = array(
1367  'data' => $item,
1368  'scriptCall' => array(
1369  'inline.domAddRecordDetails(\'' . $domObjectId . '\',\'' . $objectPrefix . '\',' . ($expandSingle ? '1' : '0') . ',json.data);'
1370  )
1371  );
1372  if ($config['foreign_unique']) {
1373  $jsonArray['scriptCall'][] = 'inline.removeUsed(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1374  }
1375  $this->getCommonScriptCalls($jsonArray, $config);
1376  // Collapse all other records if requested:
1377  if (!$collapseAll && $expandSingle) {
1378  $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\',\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1379  }
1380  // Remove the current level also from the dynNestedStack of FormEngine:
1381  $this->fObj->popFromDynNestedStack();
1382  // Return the JSON array:
1383  return $jsonArray;
1384  }
1385 
1393  protected function getExecuteChangesJsonArray($oldItemList, $newItemList) {
1394  $data = '';
1395  $parent = $this->getStructureLevel(-1);
1396  $current = $this->inlineStructure['unstable'];
1397  $jsonArray = array('scriptCall' => array());
1398  $jsonArrayScriptCall = &$jsonArray['scriptCall'];
1399  $nameObject = $this->inlineNames['object'];
1400  $nameObjectForeignTable = $nameObject . self::Structure_Separator . $current['table'];
1401  // Get the name of the field pointing to the original record:
1402  $transOrigPointerField = $GLOBALS['TCA'][$current['table']]['ctrl']['transOrigPointerField'];
1403  // Get the name of the field used as foreign selector (if any):
1404  $foreignSelector = isset($parent['config']['foreign_selector']) && $parent['config']['foreign_selector'] ? $parent['config']['foreign_selector'] : FALSE;
1405  // Convert lists to array with uids of child records:
1406  $oldItems = $this->getRelatedRecordsUidArray($oldItemList);
1407  $newItems = $this->getRelatedRecordsUidArray($newItemList);
1408  // Determine the items that were localized or localized:
1409  $removedItems = array_diff($oldItems, $newItems);
1410  $localizedItems = array_diff($newItems, $oldItems);
1411  // Set the items that should be removed in the forms view:
1412  foreach ($removedItems as $item) {
1413  $jsonArrayScriptCall[] = 'inline.deleteRecord(\'' . $nameObjectForeignTable . self::Structure_Separator . $item . '\', {forceDirectRemoval: true});';
1414  }
1415  // Set the items that should be added in the forms view:
1416  foreach ($localizedItems as $item) {
1417  $row = $this->getRecord($this->inlineFirstPid, $current['table'], $item);
1418  $selectedValue = $foreignSelector ? '\'' . $row[$foreignSelector] . '\'' : 'null';
1419  $data .= $this->renderForeignRecord($parent['uid'], $row, $parent['config']);
1420  $jsonArrayScriptCall[] = 'inline.memorizeAddRecord(\'' . $nameObjectForeignTable . '\', \'' . $item . '\', null, ' . $selectedValue . ');';
1421  // Remove possible virtual records in the form which showed that a child records could be localized:
1422  if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]) {
1423  $jsonArrayScriptCall[] = 'inline.fadeAndRemove(\'' . $nameObjectForeignTable . self::Structure_Separator . $row[$transOrigPointerField] . '_div' . '\');';
1424  }
1425  }
1426  if ($data) {
1427  $jsonArray['data'] = $data;
1428  array_unshift($jsonArrayScriptCall, 'inline.domAddNewRecord(\'bottom\', \'' . $nameObject . '_records\', \'' . $nameObjectForeignTable . '\', json.data);');
1429  }
1430  return $jsonArray;
1431  }
1432 
1442  public function setExpandedCollapsedState($domObjectId, $expand, $collapse) {
1443  // Parse the DOM identifier (string), add the levels to the structure stack (array), but don't load TCA config
1444  $this->parseStructureString($domObjectId, FALSE);
1445  // The current table - for this table we should add/import records
1446  $current = $this->inlineStructure['unstable'];
1447  // The top parent table - this table embeds the current table
1448  $top = $this->getStructureLevel(0);
1449  // Only do some action if the top record and the current record were saved before
1450  if (MathUtility::canBeInterpretedAsInteger($top['uid'])) {
1451  $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
1452  $inlineViewCurrent = &$inlineView[$top['table']][$top['uid']];
1453  $expandUids = GeneralUtility::trimExplode(',', $expand);
1454  $collapseUids = GeneralUtility::trimExplode(',', $collapse);
1455  // Set records to be expanded
1456  foreach ($expandUids as $uid) {
1457  $inlineViewCurrent[$current['table']][] = $uid;
1458  }
1459  // Set records to be collapsed
1460  foreach ($collapseUids as $uid) {
1461  $inlineViewCurrent[$current['table']] = $this->removeFromArray($uid, $inlineViewCurrent[$current['table']]);
1462  }
1463  // Save states back to database
1464  if (is_array($inlineViewCurrent[$current['table']])) {
1465  $inlineViewCurrent[$current['table']] = array_unique($inlineViewCurrent[$current['table']]);
1466  $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
1467  $GLOBALS['BE_USER']->writeUC();
1468  }
1469  }
1470  }
1471 
1472  /*
1473  *
1474  * Get data from database and handle relations
1475  *
1476  */
1477 
1490  public function getRelatedRecords($table, $field, $row, &$PA, $config) {
1491  $language = 0;
1492  $pid = $row['pid'];
1493  $elements = $PA['itemFormElValue'];
1494  $foreignTable = $config['foreign_table'];
1495  $localizationMode = BackendUtility::getInlineLocalizationMode($table, $config);
1496  if ($localizationMode != FALSE) {
1497  $language = (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
1498  $transOrigPointer = (int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
1499  $transOrigTable = BackendUtility::getOriginalTranslationTable($table);
1500 
1501  if ($language > 0 && $transOrigPointer) {
1502  // Localization in mode 'keep', isn't a real localization, but keeps the children of the original parent record:
1503  if ($localizationMode == 'keep') {
1504  $transOrigRec = $this->getRecord(0, $transOrigTable, $transOrigPointer);
1505  $elements = $transOrigRec[$field];
1506  $pid = $transOrigRec['pid'];
1507  } elseif ($localizationMode == 'select') {
1508  $transOrigRec = $this->getRecord(0, $transOrigTable, $transOrigPointer);
1509  $pid = $transOrigRec['pid'];
1510  $fieldValue = $transOrigRec[$field];
1511 
1512  // Checks if it is a flexform field
1513  if ($GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'flex') {
1514  $flexFormParts = $this->extractFlexFormParts($PA['itemFormElName']);
1515  $flexData = GeneralUtility::xml2array($fieldValue);
1517  $flexFormTools = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Configuration\\FlexForm\\FlexFormTools');
1518  $flexFormFieldValue = $flexFormTools->getArrayValueByPath($flexFormParts, $flexData);
1519 
1520  if ($flexFormFieldValue !== NULL) {
1521  $fieldValue = $flexFormFieldValue;
1522  }
1523  }
1524 
1525  $recordsOriginal = $this->getRelatedRecordsArray($pid, $foreignTable, $fieldValue);
1526  }
1527  }
1528  }
1529  $records = $this->getRelatedRecordsArray($pid, $foreignTable, $elements);
1530  $relatedRecords = array('records' => $records, 'count' => count($records));
1531  // Merge original language with current localization and show differences:
1532  if (!empty($recordsOriginal)) {
1533  $options = array(
1534  'showPossible' => isset($config['appearance']['showPossibleLocalizationRecords']) && $config['appearance']['showPossibleLocalizationRecords'],
1535  'showRemoved' => isset($config['appearance']['showRemovedLocalizationRecords']) && $config['appearance']['showRemovedLocalizationRecords']
1536  );
1537  // Either show records that possibly can localized or removed
1538  if ($options['showPossible'] || $options['showRemoved']) {
1539  $relatedRecords['records'] = $this->getLocalizationDifferences($foreignTable, $options, $recordsOriginal, $records);
1540  // Otherwise simulate localizeChildrenAtParentLocalization behaviour when creating a new record
1541  // (which has language and translation pointer values set)
1542  } elseif (!empty($config['behaviour']['localizeChildrenAtParentLocalization']) && !MathUtility::canBeInterpretedAsInteger($row['uid'])) {
1543  if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'])) {
1544  $foreignLanguageField = $GLOBALS['TCA'][$foreignTable]['ctrl']['languageField'];
1545  }
1546  if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'])) {
1547  $foreignTranslationPointerField = $GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'];
1548  }
1549  // Duplicate child records of default language in form
1550  foreach ($recordsOriginal as $record) {
1551  if (!empty($foreignLanguageField)) {
1552  $record[$foreignLanguageField] = $language;
1553  }
1554  if (!empty($foreignTranslationPointerField)) {
1555  $record[$foreignTranslationPointerField] = $record['uid'];
1556  }
1557  $newId = uniqid('NEW', TRUE);
1558  $record['uid'] = $newId;
1559  $record['pid'] = $this->inlineFirstPid;
1560  $relatedRecords['records'][$newId] = $record;
1561  }
1562  }
1563  }
1564  return $relatedRecords;
1565  }
1566 
1575  protected function getRelatedRecordsArray($pid, $table, $itemList) {
1576  $records = array();
1577  $itemArray = $this->getRelatedRecordsUidArray($itemList);
1578  // Perform modification of the selected items array:
1579  foreach ($itemArray as $uid) {
1580  // Get the records for this uid using \TYPO3\CMS\Backend\Form\DataPreprocessor
1581  if ($record = $this->getRecord($pid, $table, $uid)) {
1582  $records[$uid] = $record;
1583  }
1584  }
1585  return $records;
1586  }
1587 
1596  protected function getRelatedRecordsUidArray($itemList) {
1597  $itemArray = GeneralUtility::trimExplode(',', $itemList, TRUE);
1598  // Perform modification of the selected items array:
1599  foreach ($itemArray as $key => &$value) {
1600  $parts = explode('|', $value, 2);
1601  $value = $parts[0];
1602  }
1603  unset($value);
1604  return $itemArray;
1605  }
1606 
1618  protected function getLocalizationDifferences($table, array $options, array $recordsOriginal, array $recordsLocalization) {
1619  $records = array();
1620  $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1621  // Compare original to localized version of the records:
1622  foreach ($recordsLocalization as $uid => $row) {
1623  // If the record points to a original translation which doesn't exist anymore, it could be removed:
1624  if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField] > 0) {
1625  $transOrigPointer = $row[$transOrigPointerField];
1626  if (isset($recordsOriginal[$transOrigPointer])) {
1627  unset($recordsOriginal[$transOrigPointer]);
1628  } elseif ($options['showRemoved']) {
1629  $row['__remove'] = TRUE;
1630  }
1631  }
1632  $records[$uid] = $row;
1633  }
1634  // Process the remaining records in the original unlocalized parent:
1635  if ($options['showPossible']) {
1636  foreach ($recordsOriginal as $uid => $row) {
1637  $row['__create'] = TRUE;
1638  $row['__virtual'] = TRUE;
1639  $records[$uid] = $row;
1640  }
1641  }
1642  return $records;
1643  }
1644 
1657  public function getPossibleRecords($table, $field, $row, $conf, $checkForConfField = 'foreign_selector') {
1658  // ctrl configuration from TCA:
1659  $tcaTableCtrl = $GLOBALS['TCA'][$table]['ctrl'];
1660  // Field configuration from TCA:
1661  $foreign_check = $conf[$checkForConfField];
1662  $foreignConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_check);
1663  $PA = $foreignConfig['PA'];
1664  $config = $PA['fieldConf']['config'];
1665  if ($foreignConfig['type'] == 'select') {
1666  // Getting the selector box items from the system
1667  $selItems = $this->fObj->addSelectOptionsToItemArray($this->fObj->initItemArray($PA['fieldConf']), $PA['fieldConf'], $this->fObj->setTSconfig($table, $row), $field);
1668 
1669  // Possibly filter some items:
1671  $selItems,
1672  $PA['fieldTSConfig']['keepItems'],
1673  function ($value) {
1674  return $value[1];
1675  }
1676  );
1677 
1678  // Possibly add some items:
1679  $selItems = $this->fObj->addItems($selItems, $PA['fieldTSConfig']['addItems.']);
1680  if (isset($config['itemsProcFunc']) && $config['itemsProcFunc']) {
1681  $selItems = $this->fObj->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
1682  }
1683  // Possibly remove some items:
1684  $removeItems = GeneralUtility::trimExplode(',', $PA['fieldTSConfig']['removeItems'], TRUE);
1685  foreach ($selItems as $tk => $p) {
1686  // Checking languages and authMode:
1687  $languageDeny = $tcaTableCtrl['languageField'] && (string)$tcaTableCtrl['languageField'] === $field && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
1688  $authModeDeny = $config['form_type'] == 'select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table, $field, $p[1], $config['authMode']);
1689  if (in_array($p[1], $removeItems) || $languageDeny || $authModeDeny) {
1690  unset($selItems[$tk]);
1691  } elseif (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
1692  $selItems[$tk][0] = htmlspecialchars($this->fObj->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]));
1693  }
1694  // Removing doktypes with no access:
1695  if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1696  if (!($GLOBALS['BE_USER']->isAdmin() || GeneralUtility::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'], $p[1]))) {
1697  unset($selItems[$tk]);
1698  }
1699  }
1700  }
1701  } else {
1702  $selItems = FALSE;
1703  }
1704  return $selItems;
1705  }
1706 
1716  public function getUniqueIds($records, $conf = array(), $splitValue = FALSE) {
1717  $uniqueIds = array();
1718  if (isset($conf['foreign_unique']) && $conf['foreign_unique'] && count($records)) {
1719  foreach ($records as $rec) {
1720  // Skip virtual records (e.g. shown in localization mode):
1721  if (!isset($rec['__virtual']) || !$rec['__virtual']) {
1722  $value = $rec[$conf['foreign_unique']];
1723  // Split the value and extract the table and uid:
1724  if ($splitValue) {
1725  $valueParts = GeneralUtility::trimExplode('|', $value);
1726  $itemParts = explode('_', $valueParts[0]);
1727  $value = array(
1728  'uid' => array_pop($itemParts),
1729  'table' => implode('_', $itemParts)
1730  );
1731  }
1732  $uniqueIds[$rec['uid']] = $value;
1733  }
1734  }
1735  }
1736  return $uniqueIds;
1737  }
1738 
1747  protected function getNewRecordPid($table, $parentPid = NULL) {
1748  $newRecordPid = $this->inlineFirstPid;
1749  $pageTS = BackendUtility::getPagesTSconfig($parentPid);
1750  if (isset($pageTS['TCAdefaults.'][$table . '.']['pid']) && MathUtility::canBeInterpretedAsInteger($pageTS['TCAdefaults.'][$table . '.']['pid'])) {
1751  $newRecordPid = $pageTS['TCAdefaults.'][$table . '.']['pid'];
1752  } elseif (isset($parentPid) && MathUtility::canBeInterpretedAsInteger($parentPid)) {
1753  $newRecordPid = $parentPid;
1754  }
1755  return $newRecordPid;
1756  }
1757 
1770  public function getRecord($_, $table, $uid, $cmd = '') {
1771  // Fetch workspace version of a record (if any):
1772  if ($cmd !== 'new' && $GLOBALS['BE_USER']->workspace !== 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
1773  $workspaceVersion = BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $uid, 'uid,t3ver_state');
1774  if ($workspaceVersion !== FALSE) {
1775  $versionState = VersionState::cast($workspaceVersion['t3ver_state']);
1776  if ($versionState->equals(VersionState::DELETE_PLACEHOLDER)) {
1777  return FALSE;
1778  }
1779  $uid = $workspaceVersion['uid'];
1780  }
1781  }
1783  $trData = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Form\\DataPreprocessor');
1784  $trData->addRawData = TRUE;
1785  $trData->lockRecords = 1;
1786  $trData->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1787  // If a new record should be created
1788  $trData->fetchRecord($table, $uid, $cmd === 'new' ? 'new' : '');
1789  $rec = reset($trData->regTableItems_data);
1790  return $rec;
1791  }
1792 
1801  public function getNewRecord($pid, $table) {
1802  $rec = $this->getRecord($pid, $table, $pid, 'new');
1803  $rec['uid'] = uniqid('NEW', TRUE);
1804  $rec['pid'] = $this->getNewRecordPid($table, $pid);
1805  return $rec;
1806  }
1807 
1808  /*******************************************************
1809  *
1810  * Structure stack for handling inline objects/levels
1811  *
1812  *******************************************************/
1825  public function pushStructure($table, $uid, $field = '', $config = array(), array $parameters = array()) {
1826  $structure = array(
1827  'table' => $table,
1828  'uid' => $uid,
1829  'field' => $field,
1830  'config' => $config,
1831  'localizationMode' => BackendUtility::getInlineLocalizationMode($table, $config),
1832  );
1833 
1834  // Extract FlexForm parts (if any) from element name,
1835  // e.g. array('vDEF', 'lDEF', 'FlexField', 'vDEF')
1836  if (!empty($parameters['itemFormElName'])) {
1837  $flexFormParts = $this->extractFlexFormParts($parameters['itemFormElName']);
1838 
1839  if ($flexFormParts !== NULL) {
1840  $structure['flexform'] = $flexFormParts;
1841  }
1842  }
1843 
1844  $this->inlineStructure['stable'][] = $structure;
1845  $this->updateStructureNames();
1846  }
1847 
1854  public function popStructure() {
1855  $popItem = NULL;
1856 
1857  if (count($this->inlineStructure['stable'])) {
1858  $popItem = array_pop($this->inlineStructure['stable']);
1859  $this->updateStructureNames();
1860  }
1861  return $popItem;
1862  }
1863 
1873  public function updateStructureNames() {
1874  $current = $this->getStructureLevel(-1);
1875  // If there are still more inline levels available
1876  if ($current !== FALSE) {
1877  $this->inlineNames = array(
1878  'form' => $this->prependFormFieldNames . $this->getStructureItemName($current, self::Disposal_AttributeName),
1879  'object' => $this->prependNaming . self::Structure_Separator . $this->inlineFirstPid . self::Structure_Separator . $this->getStructurePath()
1880  );
1881  } else {
1882  $this->inlineNames = array();
1883  }
1884  }
1885 
1894  public function getStructureItemName($levelData, $disposal = self::Disposal_AttributeId) {
1895  $name = NULL;
1896 
1897  if (is_array($levelData)) {
1898  $parts = array($levelData['table'], $levelData['uid']);
1899 
1900  if (!empty($levelData['field'])) {
1901  $parts[] = $levelData['field'];
1902  }
1903 
1904  // Use in name attributes:
1905  if ($disposal === self::Disposal_AttributeName) {
1906  if (!empty($levelData['field']) && !empty($levelData['flexform']) && $this->getStructureLevel(-1) === $levelData) {
1907  $parts[] = implode('][', $levelData['flexform']);
1908  }
1909  $name = '[' . implode('][', $parts) . ']';
1910  // Use in object id attributes:
1911  } else {
1912  $name = implode(self::Structure_Separator, $parts);
1913 
1914  if (!empty($levelData['field']) && !empty($levelData['flexform'])) {
1915  array_unshift($levelData['flexform'], $name);
1916  $name = implode(self::FlexForm_Separator, $levelData['flexform']);
1917  }
1918  }
1919  }
1920 
1921  return $name;
1922  }
1923 
1933  public function getStructureLevel($level) {
1934  $level = $this->calculateStructureLevel($level);
1935 
1936  if ($level !== FALSE) {
1937  return $this->inlineStructure['stable'][$level];
1938  } else {
1939  return FALSE;
1940  }
1941  }
1942 
1949  protected function calculateStructureLevel($level) {
1950  $result = FALSE;
1951 
1952  $inlineStructureCount = count($this->inlineStructure['stable']);
1953  if ($level < 0) {
1954  $level = $inlineStructureCount + $level;
1955  }
1956  if ($level >= 0 && $level < $inlineStructureCount) {
1957  $result = $level;
1958  }
1959 
1960  return $result;
1961  }
1962 
1971  public function getStructurePath($structureDepth = -1) {
1972  $structureLevels = array();
1973  $structureCount = count($this->inlineStructure['stable']);
1974  if ($structureDepth < 0 || $structureDepth > $structureCount) {
1975  $structureDepth = $structureCount;
1976  }
1977  for ($i = 1; $i <= $structureDepth; $i++) {
1978  array_unshift($structureLevels, $this->getStructureItemName($this->getStructureLevel(-$i), self::Disposal_AttributeId));
1979  }
1980  return implode(self::Structure_Separator, $structureLevels);
1981  }
1982 
1996  public function parseStructureString($domObjectId, $loadConfig = TRUE) {
1997  $unstable = array();
1998  $vector = array('table', 'uid', 'field');
1999 
2000  // Substitute FlexForm addition and make parsing a bit easier
2001  $domObjectId = str_replace(self::FlexForm_Separator, self::FlexForm_Substitute, $domObjectId);
2002  // The starting pattern of an object identifier (e.g. "data-<firstPidValue>-<anything>)
2003  $pattern = '/^' . $this->prependNaming . self::Structure_Separator . '(.+?)' . self::Structure_Separator . '(.+)$/';
2004 
2005  if (preg_match($pattern, $domObjectId, $match)) {
2006  $this->inlineFirstPid = $match[1];
2007  $parts = explode(self::Structure_Separator, $match[2]);
2008  $partsCnt = count($parts);
2009  for ($i = 0; $i < $partsCnt; $i++) {
2010  if ($i > 0 && $i % 3 == 0) {
2011  // Load the TCA configuration of the table field and store it in the stack
2012  if ($loadConfig) {
2013  $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
2014  // Fetch TSconfig:
2015  $TSconfig = $this->fObj->setTSconfig($unstable['table'], array('uid' => $unstable['uid'], 'pid' => $this->inlineFirstPid), $unstable['field']);
2016  // Override TCA field config by TSconfig:
2017  if (!$TSconfig['disabled']) {
2018  $unstable['config'] = $this->fObj->overrideFieldConf($unstable['config'], $TSconfig);
2019  }
2020  $unstable['localizationMode'] = BackendUtility::getInlineLocalizationMode($unstable['table'], $unstable['config']);
2021  }
2022 
2023  // Extract FlexForm from field part (if any)
2024  if (strpos($unstable['field'], self::FlexForm_Substitute) !== FALSE) {
2025  $fieldParts = GeneralUtility::trimExplode(self::FlexForm_Substitute, $unstable['field']);
2026  $unstable['field'] = array_shift($fieldParts);
2027  // FlexForm parts start with data:
2028  if (count($fieldParts) > 0 && $fieldParts[0] === 'data') {
2029  $unstable['flexform'] = $fieldParts;
2030  }
2031  }
2032 
2033  $this->inlineStructure['stable'][] = $unstable;
2034  $unstable = array();
2035  }
2036  $unstable[$vector[$i % 3]] = $parts[$i];
2037  }
2038  $this->updateStructureNames();
2039  if (count($unstable)) {
2040  $this->inlineStructure['unstable'] = $unstable;
2041  }
2042  }
2043  }
2044 
2045  /*
2046  *
2047  * Helper functions
2048  *
2049  */
2050 
2057  public function checkConfiguration(&$config) {
2058  $foreign_table = $config['foreign_table'];
2059  // An inline field must have a foreign_table, if not, stop all further inline actions for this field:
2060  if (!$foreign_table || !is_array($GLOBALS['TCA'][$foreign_table])) {
2061  return FALSE;
2062  }
2063  // Init appearance if not set:
2064  if (!isset($config['appearance']) || !is_array($config['appearance'])) {
2065  $config['appearance'] = array();
2066  }
2067  // Set the position/appearance of the "Create new record" link:
2068  if (isset($config['foreign_selector']) && $config['foreign_selector'] && (!isset($config['appearance']['useCombination']) || !$config['appearance']['useCombination'])) {
2069  $config['appearance']['levelLinksPosition'] = 'none';
2070  } elseif (!isset($config['appearance']['levelLinksPosition']) || !in_array($config['appearance']['levelLinksPosition'], array('top', 'bottom', 'both', 'none'))) {
2071  $config['appearance']['levelLinksPosition'] = 'top';
2072  }
2073  // Defines which controls should be shown in header of each record:
2074  $enabledControls = array(
2075  'info' => TRUE,
2076  'new' => TRUE,
2077  'dragdrop' => TRUE,
2078  'sort' => TRUE,
2079  'hide' => TRUE,
2080  'delete' => TRUE,
2081  'localize' => TRUE
2082  );
2083  if (isset($config['appearance']['enabledControls']) && is_array($config['appearance']['enabledControls'])) {
2084  $config['appearance']['enabledControls'] = array_merge($enabledControls, $config['appearance']['enabledControls']);
2085  } else {
2086  $config['appearance']['enabledControls'] = $enabledControls;
2087  }
2088  return TRUE;
2089  }
2090 
2101  public function checkAccess($cmd, $table, $theUid) {
2102  // Checking if the user has permissions? (Only working as a precaution, because the final permission check is always down in TCE. But it's good to notify the user on beforehand...)
2103  // First, resetting flags.
2104  $hasAccess = 0;
2105  // Admin users always have access:
2106  if ($GLOBALS['BE_USER']->isAdmin()) {
2107  return TRUE;
2108  }
2109  // If the command is to create a NEW record...:
2110  if ($cmd == 'new') {
2111  // If the pid is numerical, check if it's possible to write to this page:
2112  if (MathUtility::canBeInterpretedAsInteger($this->inlineFirstPid)) {
2113  $calcPRec = BackendUtility::getRecord('pages', $this->inlineFirstPid);
2114  if (!is_array($calcPRec)) {
2115  return FALSE;
2116  }
2117  // Permissions for the parent page
2118  $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
2119  // If pages:
2120  if ($table == 'pages') {
2121  // Are we allowed to create new subpages?
2122  $hasAccess = $CALC_PERMS & 8 ? 1 : 0;
2123  } else {
2124  // Are we allowed to edit content on this page?
2125  $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
2126  // Are we allowed to edit the page?
2127  if ($table === 'sys_file_reference' && $this->isMediaOnPages($theUid)) {
2128  $hasAccess = (bool)($CALC_PERMS & 2);
2129  }
2130  if (!$hasAccess) {
2131  // Are we allowed to edit content on this page?
2132  $hasAccess = (bool)($CALC_PERMS & 16);
2133  }
2134  }
2135  } else {
2136  $hasAccess = 1;
2137  }
2138  } else {
2139  // Edit:
2140  $calcPRec = BackendUtility::getRecord($table, $theUid);
2141  BackendUtility::fixVersioningPid($table, $calcPRec);
2142  if (is_array($calcPRec)) {
2143  // If pages:
2144  if ($table == 'pages') {
2145  $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
2146  $hasAccess = $CALC_PERMS & 2 ? 1 : 0;
2147  } else {
2148  // Fetching pid-record first.
2149  $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(BackendUtility::getRecord('pages', $calcPRec['pid']));
2150  if ($table === 'sys_file_reference' && $this->isMediaOnPages($theUid)) {
2151  $hasAccess = (bool)($CALC_PERMS & 2);
2152  }
2153  if (!$hasAccess) {
2154  $hasAccess = (bool)($CALC_PERMS & 16);
2155  }
2156  }
2157  // Check internals regarding access:
2158  $isRootLevelRestrictionIgnored = BackendUtility::isRootLevelRestrictionIgnored($table);
2159  if ($hasAccess || (int)$calcPRec['pid'] === 0 && $isRootLevelRestrictionIgnored) {
2160  $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
2161  }
2162  }
2163  }
2164  if (!$GLOBALS['BE_USER']->check('tables_modify', $table)) {
2165  $hasAccess = 0;
2166  }
2167  if (
2168  !empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'])
2169  && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'])
2170  ) {
2171  foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'] as $_funcRef) {
2172  $_params = array(
2173  'table' => $table,
2174  'uid' => $theUid,
2175  'cmd' => $cmd,
2176  'hasAccess' => $hasAccess
2177  );
2178  $hasAccess = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2179  }
2180  }
2181  if (!$hasAccess) {
2182  $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
2183  if ($deniedAccessReason) {
2184  debug($deniedAccessReason);
2185  }
2186  }
2187  return $hasAccess ? TRUE : FALSE;
2188  }
2189 
2199  public function compareStructureConfiguration($compare) {
2200  $level = $this->getStructureLevel(-1);
2201  $result = $this->arrayCompareComplex($level, $compare);
2202  return $result;
2203  }
2204 
2212  public function normalizeUid($string) {
2213  $parts = explode('|', $string);
2214  return $parts[0];
2215  }
2216 
2226  public function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array()) {
2227  $style = '';
2228  $table = '';
2229  foreach ($styleAttrs as $key => $value) {
2230  $style .= ($style ? ' ' : '') . $key . ': ' . htmlspecialchars($value) . '; ';
2231  }
2232  if ($style) {
2233  $style = ' style="' . $style . '"';
2234  }
2235  if (!$tableAttrs['background'] && $this->fObj->borderStyle[2]) {
2236  $tableAttrs['background'] = $this->backPath . $this->borderStyle[2];
2237  }
2238  if (!$tableAttrs['class'] && $this->borderStyle[3]) {
2239  $tableAttrs['class'] = $this->borderStyle[3];
2240  }
2241  foreach ($tableAttrs as $key => $value) {
2242  $table .= ($table ? ' ' : '') . $key . '="' . htmlspecialchars($value) . '"';
2243  }
2244  $out = '<table ' . $table . $style . '>' . $section . '</table>';
2245  return $out;
2246  }
2247 
2258  public function isInlineChildAndLabelField($table, $field) {
2259  $level = $this->getStructureLevel(-1);
2260  if ($level['config']['foreign_label']) {
2261  $label = $level['config']['foreign_label'];
2262  } else {
2263  $label = $GLOBALS['TCA'][$table]['ctrl']['label'];
2264  }
2265  return $level['config']['foreign_table'] === $table && $label == $field ? TRUE : FALSE;
2266  }
2267 
2275  public function getStructureDepth() {
2276  return count($this->inlineStructure['stable']);
2277  }
2278 
2312  public function arrayCompareComplex($subjectArray, $searchArray, $type = '') {
2313  $localMatches = 0;
2314  $localEntries = 0;
2315  if (is_array($searchArray) && count($searchArray)) {
2316  // If no type was passed, try to determine
2317  if (!$type) {
2318  reset($searchArray);
2319  $type = key($searchArray);
2320  $searchArray = current($searchArray);
2321  }
2322  // We use '%AND' and '%OR' in uppercase
2323  $type = strtoupper($type);
2324  // Split regular elements from sub elements
2325  foreach ($searchArray as $key => $value) {
2326  $localEntries++;
2327  // Process a sub-group of OR-conditions
2328  if ($key == '%OR') {
2329  $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
2330  } elseif ($key == '%AND') {
2331  $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
2332  } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
2333  $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
2334  } elseif (is_array($value)) {
2335  $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
2336  } else {
2337  if (isset($subjectArray[$key]) && isset($value)) {
2338  // Boolean match:
2339  if (is_bool($value)) {
2340  $localMatches += !($subjectArray[$key] xor $value) ? 1 : 0;
2341  } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
2342  $localMatches += $subjectArray[$key] == $value ? 1 : 0;
2343  } else {
2344  $localMatches += $subjectArray[$key] === $value ? 1 : 0;
2345  }
2346  }
2347  }
2348  // If one or more matches are required ('OR'), return TRUE after the first successful match
2349  if ($type == '%OR' && $localMatches > 0) {
2350  return TRUE;
2351  }
2352  // If all matches are required ('AND') and we have no result after the first run, return FALSE
2353  if ($type == '%AND' && $localMatches == 0) {
2354  return FALSE;
2355  }
2356  }
2357  }
2358  // Return the result for '%AND' (if nothing was checked, TRUE is returned)
2359  return $localEntries == $localMatches ? TRUE : FALSE;
2360  }
2361 
2369  public function isAssociativeArray($object) {
2370  return is_array($object) && count($object) && array_keys($object) !== range(0, sizeof($object) - 1) ? TRUE : FALSE;
2371  }
2372 
2382  public function removeFromArray($needle, $haystack, $strict = NULL) {
2383  $pos = array_search($needle, $haystack, $strict);
2384  if ($pos !== FALSE) {
2385  unset($haystack[$pos]);
2386  }
2387  return $haystack;
2388  }
2389 
2399  public function getPossibleRecordsFlat($possibleRecords) {
2400  $flat = FALSE;
2401  if (is_array($possibleRecords)) {
2402  $flat = array();
2403  foreach ($possibleRecords as $record) {
2404  $flat[$record[1]] = $record[0];
2405  }
2406  }
2407  return $flat;
2408  }
2409 
2418  public function getPossibleRecordsSelectorConfig($conf, $field = '') {
2419  $foreign_table = $conf['foreign_table'];
2420  $foreign_selector = $conf['foreign_selector'];
2421  $PA = FALSE;
2422  $type = FALSE;
2423  $table = FALSE;
2424  $selector = FALSE;
2425  if ($field) {
2426  $PA = array();
2427  $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$field];
2428  if ($PA['fieldConf'] && $conf['foreign_selector_fieldTcaOverride']) {
2429  ArrayUtility::mergeRecursiveWithOverrule($PA['fieldConf'], $conf['foreign_selector_fieldTcaOverride']);
2430  }
2431  $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ?: $PA['fieldConf']['config']['type'];
2432  // Using "form_type" locally in this script
2433  $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table, array(), $field);
2434  $config = $PA['fieldConf']['config'];
2435  // Determine type of Selector:
2436  $type = $this->getPossibleRecordsSelectorType($config);
2437  // Return table on this level:
2438  $table = $type == 'select' ? $config['foreign_table'] : $config['allowed'];
2439  // Return type of the selector if foreign_selector is defined and points to the same field as in $field:
2440  if ($foreign_selector && $foreign_selector == $field && $type) {
2441  $selector = $type;
2442  }
2443  }
2444  return array(
2445  'PA' => $PA,
2446  'type' => $type,
2447  'table' => $table,
2448  'selector' => $selector
2449  );
2450  }
2451 
2459  public function getPossibleRecordsSelectorType($config) {
2460  $type = FALSE;
2461  if ($config['type'] == 'select') {
2462  $type = 'select';
2463  } elseif ($config['type'] == 'group' && $config['internal_type'] == 'db') {
2464  $type = 'groupdb';
2465  }
2466  return $type;
2467  }
2468 
2480  public function skipField($table, $field, $row, $config) {
2481  $skipThisField = FALSE;
2482  if ($this->getStructureDepth()) {
2483  $searchArray = array(
2484  '%OR' => array(
2485  'config' => array(
2486  0 => array(
2487  '%AND' => array(
2488  'foreign_table' => $table,
2489  '%OR' => array(
2490  '%AND' => array(
2491  'appearance' => array('useCombination' => TRUE),
2492  'foreign_selector' => $field
2493  ),
2494  'MM' => $config['MM']
2495  )
2496  )
2497  ),
2498  1 => array(
2499  '%AND' => array(
2500  'foreign_table' => $config['foreign_table'],
2501  'foreign_selector' => $config['foreign_field']
2502  )
2503  )
2504  )
2505  )
2506  );
2507  // Get the parent record from structure stack
2508  $level = $this->getStructureLevel(-1);
2509  // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
2510  if (RelationHandler::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
2511  $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $field;
2512  $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $field;
2513  } else {
2514  $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $field;
2515  $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $field;
2516  }
2517  $skipThisField = $this->compareStructureConfiguration($searchArray, TRUE);
2518  }
2519  return $skipThisField;
2520  }
2521 
2530  public function getExpandedCollapsedState($table, $uid) {
2531  if (isset($this->inlineView[$table]) && is_array($this->inlineView[$table])) {
2532  if (in_array($uid, $this->inlineView[$table]) !== FALSE) {
2533  return TRUE;
2534  }
2535  }
2536  return FALSE;
2537  }
2538 
2547  static public function updateInlineView(&$uc, $tce) {
2548  if (isset($uc['inlineView']) && is_array($uc['inlineView'])) {
2549  $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
2550  foreach ($uc['inlineView'] as $topTable => $topRecords) {
2551  foreach ($topRecords as $topUid => $childElements) {
2552  foreach ($childElements as $childTable => $childRecords) {
2553  $uids = array_keys($tce->substNEWwithIDs_table, $childTable);
2554  if (count($uids)) {
2555  $newExpandedChildren = array();
2556  foreach ($childRecords as $childUid => $state) {
2557  if ($state && in_array($childUid, $uids)) {
2558  $newChildUid = $tce->substNEWwithIDs[$childUid];
2559  $newExpandedChildren[] = $newChildUid;
2560  }
2561  }
2562  // Add new expanded child records to UC (if any):
2563  if (count($newExpandedChildren)) {
2564  $inlineViewCurrent = &$inlineView[$topTable][$topUid][$childTable];
2565  if (is_array($inlineViewCurrent)) {
2566  $inlineViewCurrent = array_unique(array_merge($inlineViewCurrent, $newExpandedChildren));
2567  } else {
2568  $inlineViewCurrent = $newExpandedChildren;
2569  }
2570  }
2571  }
2572  }
2573  }
2574  }
2575  $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
2576  $GLOBALS['BE_USER']->writeUC();
2577  }
2578  }
2579 
2586  public function getLevelMargin() {
2587  $margin = ($this->inlineStyles['margin-right'] + 1) * 2;
2588  return $margin;
2589  }
2590 
2596  protected function getHeadTags() {
2597  $headTags = array();
2598  $headDataRaw = $this->fObj->JStop() . $this->getJavaScriptAndStyleSheetsOfPageRenderer();
2599  if ($headDataRaw) {
2600  // Create instance of the HTML parser:
2601  $parseObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Html\\HtmlParser');
2602  // Removes script wraps:
2603  $headDataRaw = str_replace(array('/*<![CDATA[*/', '/*]]>*/'), '', $headDataRaw);
2604  // Removes leading spaces of a multi-line string:
2605  $headDataRaw = trim(preg_replace('/(^|\\r|\\n)( |\\t)+/', '$1', $headDataRaw));
2606  // Get script and link tags:
2607  $tags = array_merge($parseObj->getAllParts($parseObj->splitTags('link', $headDataRaw)), $parseObj->getAllParts($parseObj->splitIntoBlock('script', $headDataRaw)));
2608  foreach ($tags as $tagData) {
2609  $tagAttributes = $parseObj->get_tag_attributes($parseObj->getFirstTag($tagData), TRUE);
2610  $headTags[] = array(
2611  'name' => $parseObj->getFirstTagName($tagData),
2612  'attributes' => $tagAttributes[0],
2613  'innerHTML' => $parseObj->removeFirstAndLastTag($tagData)
2614  );
2615  }
2616  }
2617  return $headTags;
2618  }
2619 
2628  protected function getJavaScriptAndStyleSheetsOfPageRenderer() {
2630  $pageRenderer = clone $GLOBALS['SOBE']->doc->getPageRenderer();
2631  $pageRenderer->setCharSet($GLOBALS['LANG']->charSet);
2632  $pageRenderer->setTemplateFile('EXT:backend/Resources/Private/Templates/helper_javascript_css.html');
2633  $javaScriptAndStyleSheets = $pageRenderer->render();
2634  return $javaScriptAndStyleSheets;
2635  }
2636 
2645  protected function wrapWithAnchor($text, $link, $attributes = array()) {
2646  $link = trim($link);
2647  $result = '<a href="' . ($link ?: '#') . '"';
2648  foreach ($attributes as $key => $value) {
2649  $result .= ' ' . $key . '="' . htmlspecialchars(trim($value)) . '"';
2650  }
2651  $result .= '>' . $text . '</a>';
2652  return $result;
2653  }
2654 
2662  protected function extractFlexFormParts($formElementName) {
2663  $flexFormParts = NULL;
2664 
2665  $matches = array();
2666  $prefix = preg_quote($this->fObj->prependFormFieldNames, '#');
2667 
2668  if (preg_match('#^' . $prefix . '(?:\[[^]]+\]){3}(\[data\](?:\[[^]]+\]){4,})$#', $formElementName, $matches)) {
2669  $flexFormParts = GeneralUtility::trimExplode(
2670  '][',
2671  trim($matches[1], '[]')
2672  );
2673  }
2674 
2675  return $flexFormParts;
2676  }
2677 
2684  protected function isMediaOnPages($theUid) {
2685  if (strpos($theUid, 'NEW') === 0) {
2686  return TRUE;
2687  }
2688  $row = BackendUtility::getRecord('sys_file_reference', $theUid);
2689  return ($row['fieldname'] === 'media') && ($row['tablenames'] === 'pages');
2690  }
2691 
2695  protected function getLanguageService() {
2696  return $GLOBALS['LANG'];
2697  }
2698 
2702  protected function getDatabaseConnection() {
2703  return $GLOBALS['TYPO3_DB'];
2704  }
2705 
2706 }
removeFromArray($needle, $haystack, $strict=NULL)
wrapFormsSection($section, $styleAttrs=array(), $tableAttrs=array())
static mergeRecursiveWithOverrule(array &$original, array $overrule, $addKeys=TRUE, $includeEmptyValues=TRUE, $enableUnsetFeature=TRUE)
skipField($table, $field, $row, $config)
static getRecordWSOL($table, $uid, $fields=' *', $where='', $useDeleteClause=TRUE, $unsetMovePointers=FALSE)
static readPageAccess($id, $perms_clause)
static getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields=' *')
arrayCompareComplex($subjectArray, $searchArray, $type='')
$parameters
Definition: FileDumpEID.php:15
getLocalizationDifferences($table, array $options, array $recordsOriginal, array $recordsLocalization)
getUniqueIds($records, $conf=array(), $splitValue=FALSE)
renderPossibleRecordsSelector($selItems, $conf, $uniqueIds=array())
parseStructureString($domObjectId, $loadConfig=TRUE)
static forceIntegerInRange($theInt, $min, $max=2000000000, $defaultValue=0)
Definition: MathUtility.php:32
getStructureItemName($levelData, $disposal=self::Disposal_AttributeId)
$uid
Definition: server.php:36
wrapWithAnchor($text, $link, $attributes=array())
static getUserObj($classRef, $checkPrefix='', $silent=FALSE)
static hmac($input, $additionalSecret='')
renderMainFields($table, array $row, array $overruleTypesArray=array())
createNewRecord($domObjectId, $foreignUid=0)
renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config=array(), $isVirtualRecord=FALSE)
static trimExplode($delim, $string, $removeEmptyValues=FALSE, $limit=0)
static callUserFunction($funcName, &$params, &$ref, $checkPrefix='', $errorMode=0)
renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord=FALSE)
static getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars=0, $uid=0, $forceResult=TRUE)
getExecuteChangesJsonArray($oldItemList, $newItemList)
static getRecordTitle($table, $row, $prep=FALSE, $forceResult=TRUE)
static getSpriteIconForRecord($table, array $row, array $options=array())
static getInlineLocalizationMode($table, $fieldOrConfig)
static isOnSymmetricSide($parentUid, $parentConf, $childRec)
getPossibleRecords($table, $field, $row, $conf, $checkForConfField='foreign_selector')
if($list_of_literals) if(!empty($literals)) if(!empty($literals)) $result
Analyse literals to prepend the N char to them if their contents aren&#39;t numeric.
getLevelInteractionLink($type, $objectPrefix, $conf=array())
static getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type='', $dontValidateList='', $setDefaultList='')
renderForeignRecord($parentUid, $rec, $config=array())
static getSpriteIcon($iconName, array $options=array(), array $overlays=array())
renderCombinationTable(&$rec, $appendFormFieldNames, $config=array())
debug($variable='', $name=' *variable *', $line=' *line *', $file=' *file *', $recursiveDepth=3, $debugLevel=E_DEBUG)
static getRecordIconAltText($row, $table='pages')
static fixVersioningPid($table, &$rr, $ignoreWorkspaceMatch=FALSE)
static getRecordTitlePrep($title, $titleLength=0)
pushStructure($table, $uid, $field='', $config=array(), array $parameters=array())
if(!defined('TYPO3_MODE')) $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'][]
static revExplode($delimiter, $string, $count=0)
getSingleField_typeInline($table, $field, $row, &$PA)
static xml2array($string, $NSprefix='', $reportDocTag=FALSE)
static getPagesTSconfig($id, $rootLine=NULL, $returnPartArray=FALSE)
if($ajaxRegistryEntry !==NULL) $ajaxObj
Definition: ajax.php:63
static keepItemsInArray(array $array, $keepItems, $getValueFunc=NULL)