[BUGFIX] CSC: file references not working with image compression
[Packages/TYPO3.CMS.git] / typo3 / sysext / css_styled_content / Classes / Controller / CssStyledContentController.php
1 <?php
2 namespace TYPO3\CMS\CssStyledContent\Controller;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 1999-2013 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the text file GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29
30 use TYPO3\CMS\Core\Utility\GeneralUtility;
31 use TYPO3\CMS\Core\Utility\MathUtility;
32
33 /**
34 * Plugin class - instantiated from TypoScript.
35 * Rendering some content elements from tt_content table.
36 *
37 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
38 */
39 class CssStyledContentController extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin {
40
41 /**
42 * Same as class name
43 *
44 * @todo Define visibility
45 */
46 public $prefixId = 'tx_cssstyledcontent_pi1';
47
48 /**
49 * Path to this script relative to the extension dir.
50 *
51 * @todo Define visibility
52 */
53 public $scriptRelPath = 'pi1/class.tx_cssstyledcontent_pi1.php';
54
55 /**
56 * The extension key
57 *
58 * @todo Define visibility
59 */
60 public $extKey = 'css_styled_content';
61
62 /**
63 * @todo Define visibility
64 */
65 public $conf = array();
66
67 /***********************************
68 * Rendering of Content Elements:
69 ***********************************/
70
71 /**
72 * Rendering the "Bulletlist" type content element, called from TypoScript (tt_content.bullets.20)
73 *
74 * @param string $content Content input. Not used, ignore.
75 * @param array $conf TypoScript configuration
76 * @return string HTML output.
77 */
78 public function render_bullets($content, $conf) {
79 // Look for hook before running default code for function
80 if ($hookObj = $this->hookRequest('render_bullets')) {
81 return $hookObj->render_bullets($content, $conf);
82 } else {
83 // Get bodytext field content, returning blank if empty:
84 $field = isset($conf['field']) && trim($conf['field']) ? trim($conf['field']) : 'bodytext';
85 $content = trim($this->cObj->data[$field]);
86 if ($content === '') {
87 return '';
88 }
89 // Split into single lines:
90 $lines = GeneralUtility::trimExplode(LF, $content);
91 foreach ($lines as &$val) {
92 $val = '<li>' . $this->cObj->stdWrap($val, $conf['innerStdWrap.']) . '</li>';
93 }
94 unset($val);
95 // Set header type:
96 $type = (int)$this->cObj->data['layout'];
97 // Compile list:
98 $out = '
99 <ul class="csc-bulletlist csc-bulletlist-' . $type . '">' . implode('', $lines) . '
100 </ul>';
101 // Return value
102 return $out;
103 }
104 }
105
106 /**
107 * Rendering the "Table" type content element, called from TypoScript (tt_content.table.20)
108 *
109 * @param string $content Content input. Not used, ignore.
110 * @param array $conf TypoScript configuration
111 * @return string HTML output.
112 */
113 public function render_table($content, $conf) {
114 // Look for hook before running default code for function
115 if ($hookObj = $this->hookRequest('render_table')) {
116 return $hookObj->render_table($content, $conf);
117 } else {
118 // Init FlexForm configuration
119 $this->pi_initPIflexForm();
120 // Get bodytext field content
121 $field = isset($conf['field']) && trim($conf['field']) ? trim($conf['field']) : 'bodytext';
122 $content = trim($this->cObj->data[$field]);
123 if ($content === '') {
124 return '';
125 }
126 // get flexform values
127 $caption = trim(htmlspecialchars($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'acctables_caption')));
128 $useTfoot = trim($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'acctables_tfoot'));
129 $headerPos = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'acctables_headerpos');
130 $noStyles = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'acctables_nostyles');
131 $tableClass = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'acctables_tableclass');
132 $delimiter = trim($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'tableparsing_delimiter', 's_parsing'));
133 if ($delimiter) {
134 $delimiter = chr((int)$delimiter);
135 } else {
136 $delimiter = '|';
137 }
138 $quotedInput = trim($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'tableparsing_quote', 's_parsing'));
139 if ($quotedInput) {
140 $quotedInput = chr((int)$quotedInput);
141 } else {
142 $quotedInput = '';
143 }
144 // Generate id prefix for accessible header
145 $headerScope = $headerPos == 'top' ? 'col' : 'row';
146 $headerIdPrefix = $headerScope . $this->cObj->data['uid'] . '-';
147 // Split into single lines (will become table-rows):
148 $rows = GeneralUtility::trimExplode(LF, $content);
149 reset($rows);
150 // Find number of columns to render:
151 $cols = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange(
152 $this->cObj->data['cols'] ? $this->cObj->data['cols'] : count(str_getcsv(current($rows), $delimiter, $quotedInput)),
153 0,
154 100
155 );
156 // Traverse rows (rendering the table here)
157 $rCount = count($rows);
158 foreach ($rows as $k => $v) {
159 $cells = str_getcsv($v, $delimiter, $quotedInput);
160 $newCells = array();
161 for ($a = 0; $a < $cols; $a++) {
162 if (trim($cells[$a]) === '') {
163 $cells[$a] = '&nbsp;';
164 }
165 $cellAttribs = $noStyles ? '' : ($a > 0 && $cols - 1 == $a ? ' class="td-last td-' . $a . '"' : ' class="td-' . $a . '"');
166 if ($headerPos == 'top' && !$k || $headerPos == 'left' && !$a) {
167 $scope = ' scope="' . $headerScope . '"';
168 $scope .= ' id="' . $headerIdPrefix . ($headerScope == 'col' ? $a : $k) . '"';
169 $newCells[$a] = '
170 <th' . $cellAttribs . $scope . '>' . $this->cObj->stdWrap($cells[$a], $conf['innerStdWrap.']) . '</th>';
171 } else {
172 if (empty($headerPos)) {
173 $accessibleHeader = '';
174 } else {
175 $accessibleHeader = ' headers="' . $headerIdPrefix . ($headerScope == 'col' ? $a : $k) . '"';
176 }
177 $newCells[$a] = '
178 <td' . $cellAttribs . $accessibleHeader . '>' . $this->cObj->stdWrap($cells[$a], $conf['innerStdWrap.']) . '</td>';
179 }
180 }
181 if (!$noStyles) {
182 $oddEven = $k % 2 ? 'tr-odd' : 'tr-even';
183 $rowAttribs = $k > 0 && $rCount - 1 == $k ? ' class="' . $oddEven . ' tr-last"' : ' class="' . $oddEven . ' tr-' . $k . '"';
184 }
185 $rows[$k] = '
186 <tr' . $rowAttribs . '>' . implode('', $newCells) . '
187 </tr>';
188 }
189 $addTbody = 0;
190 $tableContents = '';
191 if ($caption) {
192 $tableContents .= '
193 <caption>' . $caption . '</caption>';
194 }
195 if ($headerPos == 'top' && $rows[0]) {
196 $tableContents .= '<thead>' . $rows[0] . '
197 </thead>';
198 unset($rows[0]);
199 $addTbody = 1;
200 }
201 if ($useTfoot) {
202 $tableContents .= '
203 <tfoot>' . $rows[($rCount - 1)] . '</tfoot>';
204 unset($rows[$rCount - 1]);
205 $addTbody = 1;
206 }
207 $tmpTable = implode('', $rows);
208 if ($addTbody) {
209 $tmpTable = '<tbody>' . $tmpTable . '</tbody>';
210 }
211 $tableContents .= $tmpTable;
212 // Set header type:
213 $type = (int)$this->cObj->data['layout'];
214 // Table tag params.
215 $tableTagParams = $this->getTableAttributes($conf, $type);
216 if (!$noStyles) {
217 $tableTagParams['class'] = 'contenttable contenttable-' . $type . ($tableClass ? ' ' . $tableClass : '') . $tableTagParams['class'];
218 } elseif ($tableClass) {
219 $tableTagParams['class'] = $tableClass;
220 }
221 // Compile table output:
222 $out = '
223 <table ' . GeneralUtility::implodeAttributes($tableTagParams) . '>' . $tableContents . '
224 </table>';
225 // Return value
226 return $out;
227 }
228 }
229
230 /**
231 * Rendering the "Filelinks" type content element, called from TypoScript (tt_content.uploads.20)
232 *
233 * @param string $content Content input. Not used, ignore.
234 * @param array $conf TypoScript configuration
235 * @return string HTML output.
236 */
237 public function render_uploads($content, $conf) {
238 // Look for hook before running default code for function
239 if ($hookObj = $this->hookRequest('render_uploads')) {
240 return $hookObj->render_uploads($content, $conf);
241 } else {
242 // Loading language-labels
243 $this->pi_loadLL();
244 $out = '';
245 // Set layout type:
246 $type = (int)$this->cObj->data['layout'];
247 // See if the file path variable is set, this takes precedence
248 $filePathConf = $this->cObj->stdWrap($conf['filePath'], $conf['filePath.']);
249 if ($filePathConf) {
250 $fileList = $this->cObj->filelist($filePathConf);
251 list($path) = explode('|', $filePathConf);
252 } else {
253 // Get the list of files from the field
254 $field = trim($conf['field']) ?: 'media';
255 $fileList = $this->cObj->data[$field];
256 $path = 'uploads/media/';
257 if (
258 is_array($GLOBALS['TCA']['tt_content']['columns'][$field]) &&
259 !empty($GLOBALS['TCA']['tt_content']['columns'][$field]['config']['uploadfolder'])
260 ) {
261 // In TCA-Array folders are saved without trailing slash, so $path.$fileName won't work
262 $path = $GLOBALS['TCA']['tt_content']['columns'][$field]['config']['uploadfolder'] . '/';
263 }
264 }
265 $path = trim($path);
266 // Explode into an array:
267 $fileArray = GeneralUtility::trimExplode(',', $fileList, TRUE);
268 // If there were files to list...:
269 if (count($fileArray)) {
270 // Get the descriptions for the files (if any):
271 $descriptions = GeneralUtility::trimExplode(LF, $this->cObj->data['imagecaption']);
272 // Get the titles for the files (if any)
273 $titles = GeneralUtility::trimExplode(LF, $this->cObj->data['titleText']);
274 // Get the alternative text for icons/thumbnails
275 $altTexts = GeneralUtility::trimExplode(LF, $this->cObj->data['altText']);
276 // Add the target to linkProc when explicitly set
277 if ($this->cObj->data['target']) {
278 $conf['linkProc.']['target'] = $this->cObj->data['target'];
279 unset($conf['linkProc.']['target.']);
280 }
281 // Adding hardcoded TS to linkProc configuration:
282 $conf['linkProc.']['path.']['current'] = 1;
283 if ($conf['linkProc.']['combinedLink']) {
284 $conf['linkProc.']['icon'] = $type > 0 ? 1 : 0;
285 } else {
286 // Always render icon - is inserted by PHP if needed.
287 $conf['linkProc.']['icon'] = 1;
288 // Temporary, internal split-token!
289 $conf['linkProc.']['icon.']['wrap'] = ' | //**//';
290 // ALways link the icon
291 $conf['linkProc.']['icon_link'] = 1;
292 }
293 $conf['linkProc.']['icon_image_ext_list'] = $type == 2 || $type == 3 ? $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] : '';
294 // If the layout is type 2 or 3 we will render an image based icon if possible.
295 if ($conf['labelStdWrap.']) {
296 $conf['linkProc.']['labelStdWrap.'] = $conf['labelStdWrap.'];
297 }
298 if ($conf['useSpacesInLinkText'] || $conf['stripFileExtensionFromLinkText']) {
299 $conf['linkProc.']['removePrependedNumbers'] = 0;
300 }
301 // Traverse the files found:
302 $filesData = array();
303 foreach ($fileArray as $key => $fileName) {
304 $absPath = GeneralUtility::getFileAbsFileName(GeneralUtility::resolveBackPath($path . $fileName));
305 if (@is_file($absPath)) {
306 $fI = pathinfo($fileName);
307 $filesData[$key] = array();
308 $currentPath = $path;
309 if (GeneralUtility::isFirstPartOfStr($fileName, '../../')) {
310 $currentPath = '';
311 $fileName = substr($fileName, 6);
312 }
313 $filesData[$key]['filename'] = $fileName;
314 $filesData[$key]['path'] = $currentPath;
315 $filesData[$key]['filesize'] = filesize($absPath);
316 $filesData[$key]['fileextension'] = strtolower($fI['extension']);
317 $filesData[$key]['description'] = trim($descriptions[$key]);
318 $filesData[$key]['titletext'] = trim($titles[$key]);
319 $filesData[$key]['alttext'] = trim($altTexts[$key]);
320 $conf['linkProc.']['title'] = trim($titles[$key]);
321 if (isset($altTexts[$key]) && !empty($altTexts[$key])) {
322 $altText = trim($altTexts[$key]);
323 } else {
324 $altText = sprintf($this->pi_getLL('uploads.icon'), $fileName);
325 }
326 $conf['linkProc.']['altText'] = ($conf['linkProc.']['iconCObject.']['altText'] = $altText);
327 $this->cObj->setCurrentVal($currentPath);
328 $GLOBALS['TSFE']->register['ICON_REL_PATH'] = $currentPath . $fileName;
329 $GLOBALS['TSFE']->register['filename'] = $filesData[$key]['filename'];
330 $GLOBALS['TSFE']->register['path'] = $filesData[$key]['path'];
331 $GLOBALS['TSFE']->register['fileSize'] = $filesData[$key]['filesize'];
332 $GLOBALS['TSFE']->register['fileExtension'] = $filesData[$key]['fileextension'];
333 $GLOBALS['TSFE']->register['description'] = $filesData[$key]['description'];
334 $GLOBALS['TSFE']->register['titleText'] = $filesData[$key]['titletext'];
335 $GLOBALS['TSFE']->register['altText'] = $filesData[$key]['alttext'];
336
337 $filesData[$key]['linkedFilenameParts'] = $this->beautifyFileLink(
338 explode('//**//', $this->cObj->filelink($fileName, $conf['linkProc.'])),
339 $fileName,
340 $conf['useSpacesInLinkText'],
341 $conf['stripFileExtensionFromLinkText']
342 );
343 }
344 }
345 // optionSplit applied to conf to allow differnt settings per file
346 $splitConf = $GLOBALS['TSFE']->tmpl->splitConfArray($conf, count($filesData));
347 // Now, lets render the list!
348 $outputEntries = array();
349 foreach ($filesData as $key => $fileData) {
350 $GLOBALS['TSFE']->register['linkedIcon'] = $fileData['linkedFilenameParts'][0];
351 $GLOBALS['TSFE']->register['linkedLabel'] = $fileData['linkedFilenameParts'][1];
352 $GLOBALS['TSFE']->register['filename'] = $fileData['filename'];
353 $GLOBALS['TSFE']->register['path'] = $fileData['path'];
354 $GLOBALS['TSFE']->register['description'] = $fileData['description'];
355 $GLOBALS['TSFE']->register['fileSize'] = $fileData['filesize'];
356 $GLOBALS['TSFE']->register['fileExtension'] = $fileData['fileextension'];
357 $GLOBALS['TSFE']->register['titleText'] = $fileData['titletext'];
358 $GLOBALS['TSFE']->register['altText'] = $fileData['alttext'];
359 $outputEntries[] = $this->cObj->cObjGetSingle($splitConf[$key]['itemRendering'], $splitConf[$key]['itemRendering.']);
360 }
361 if (isset($conf['outerWrap'])) {
362 // Wrap around the whole content
363 $outerWrap = $this->cObj->stdWrap($conf['outerWrap'], $conf['outerWrap.']);
364 } else {
365 // Table tag params
366 $tableTagParams = $this->getTableAttributes($conf, $type);
367 $tableTagParams['class'] = 'csc-uploads csc-uploads-' . $type;
368 $outerWrap = '<table ' . GeneralUtility::implodeAttributes($tableTagParams) . '>|</table>';
369 }
370 // Compile it all into table tags:
371 $out = $this->cObj->wrap(implode('', $outputEntries), $outerWrap);
372 }
373 // Return value
374 return $out;
375 }
376 }
377
378 /**
379 * Returns an array containing width relations for $colCount columns.
380 *
381 * Tries to use "colRelations" setting given by TS.
382 * uses "1:1" column relations by default.
383 *
384 * @param array $conf TS configuration for img
385 * @param integer $colCount number of columns
386 * @return array
387 */
388 protected function getImgColumnRelations($conf, $colCount) {
389 $relations = array();
390 $equalRelations = array_fill(0, $colCount, 1);
391 $colRelationsTypoScript = trim($this->cObj->stdWrap($conf['colRelations'], $conf['colRelations.']));
392 if ($colRelationsTypoScript) {
393 // Try to use column width relations given by TS
394 $relationParts = explode(':', $colRelationsTypoScript);
395 // Enough columns defined?
396 if (count($relationParts) >= $colCount) {
397 $out = array();
398 for ($a = 0; $a < $colCount; $a++) {
399 $currentRelationValue = (int)$relationParts[$a];
400 if ($currentRelationValue >= 1) {
401 $out[$a] = $currentRelationValue;
402 } else {
403 GeneralUtility::devLog('colRelations used with a value smaller than 1 therefore colRelations setting is ignored.', $this->extKey, 2);
404 unset($out);
405 break;
406 }
407 }
408 if (max($out) / min($out) <= 10) {
409 $relations = $out;
410 } else {
411 GeneralUtility::devLog(
412 'The difference in size between the largest and smallest colRelation was not within' .
413 ' a factor of ten therefore colRelations setting is ignored..',
414 $this->extKey,
415 2
416 );
417 }
418 }
419 }
420 return $relations ?: $equalRelations;
421 }
422
423 /**
424 * Returns an array containing the image widths for an image row with $colCount columns.
425 *
426 * @param array $conf TS configuration of img
427 * @param integer $colCount number of columns
428 * @param integer $netW max usable width for images (without spaces and borders)
429 * @return array
430 */
431 protected function getImgColumnWidths($conf, $colCount, $netW) {
432 $columnWidths = array();
433 $colRelations = $this->getImgColumnRelations($conf, $colCount);
434 $accumWidth = 0;
435 $accumDesiredWidth = 0;
436 $relUnitCount = array_sum($colRelations);
437 for ($a = 0; $a < $colCount; $a++) {
438 // This much width is available for the remaining images in this row (int)
439 $availableWidth = $netW - $accumWidth;
440 // Theoretical width of resized image. (float)
441 $desiredWidth = $netW / $relUnitCount * $colRelations[$a];
442 // Add this width. $accumDesiredWidth becomes the desired horizontal position
443 $accumDesiredWidth += $desiredWidth;
444 // Calculate width by comparing actual and desired horizontal position.
445 // this evenly distributes rounding errors across all images in this row.
446 $suggestedWidth = round($accumDesiredWidth - $accumWidth);
447 // finalImgWidth may not exceed $availableWidth
448 $finalImgWidth = (int)min($availableWidth, $suggestedWidth);
449 $accumWidth += $finalImgWidth;
450 $columnWidths[$a] = $finalImgWidth;
451 }
452 return $columnWidths;
453 }
454
455 /**
456 * Rendering the IMGTEXT content element, called from TypoScript (tt_content.textpic.20)
457 *
458 * @param string $content Content input. Not used, ignore.
459 * @param array $conf TypoScript configuration. See TSRef "IMGTEXT". This function aims to be compatible.
460 * @return string HTML output.
461 * @coauthor Ernesto Baschny <ernst@cron-it.de>
462 * @coauthor Patrick Broens <patrick@patrickbroens.nl>
463 */
464 public function render_textpic($content, $conf) {
465 // Look for hook before running default code for function
466 if (method_exists($this, 'hookRequest') && ($hookObj = $this->hookRequest('render_textpic'))) {
467 return $hookObj->render_textpic($content, $conf);
468 }
469 $renderMethod = $this->cObj->stdWrap($conf['renderMethod'], $conf['renderMethod.']);
470 // Render using the default IMGTEXT code (table-based)
471 if (!$renderMethod || $renderMethod == 'table') {
472 return $this->cObj->IMGTEXT($conf);
473 }
474 if (isset($conf['preRenderRegisters.'])) {
475 $this->cObj->LOAD_REGISTER($conf['preRenderRegisters.'], 'LOAD_REGISTER');
476 }
477 // Specific configuration for the chosen rendering method
478 if (is_array($conf['rendering.'][$renderMethod . '.'])) {
479 $conf = array_replace_recursive($conf, $conf['rendering.'][$renderMethod . '.']);
480 }
481 // Image or Text with Image?
482 if (is_array($conf['text.'])) {
483 $content = $this->cObj->stdWrap($this->cObj->cObjGet($conf['text.'], 'text.'), $conf['text.']);
484 }
485 $imgList = trim($this->cObj->stdWrap($conf['imgList'], $conf['imgList.']));
486 if (!$imgList) {
487 // No images, that's easy
488 return $content;
489 }
490 $imgs = GeneralUtility::trimExplode(',', $imgList, TRUE);
491 if (count($imgs) === 0) {
492 // The imgList was not empty but did only contain empty values
493 return $content;
494 }
495 $imgStart = (int)$this->cObj->stdWrap($conf['imgStart'], $conf['imgStart.']);
496 $imgCount = count($imgs) - $imgStart;
497 $imgMax = (int)$this->cObj->stdWrap($conf['imgMax'], $conf['imgMax.']);
498 if ($imgMax) {
499 $imgCount = MathUtility::forceIntegerInRange($imgCount, 0, $imgMax);
500 }
501 $imgPath = $this->cObj->stdWrap($conf['imgPath'], $conf['imgPath.']);
502 // Does we need to render a "global caption" (below the whole image block)?
503 $renderGlobalCaption = !$conf['captionSplit'] && !$conf['imageTextSplit'] && is_array($conf['caption.']);
504 if ($imgCount == 1) {
505 // If we just have one image, the caption relates to the image, so it is not "global"
506 $renderGlobalCaption = FALSE;
507 }
508 $imgListContainsReferenceUids = (bool)(isset($conf['imgListContainsReferenceUids.'])
509 ? $this->cObj->stdWrap($conf['imgListContainsReferenceUids'], $conf['imgListContainsReferenceUids.'])
510 : $conf['imgListContainsReferenceUids']);
511 // Use the calculated information (amount of images, if global caption is wanted) to choose a different rendering method for the images-block
512 $GLOBALS['TSFE']->register['imageCount'] = $imgCount;
513 $GLOBALS['TSFE']->register['renderGlobalCaption'] = $renderGlobalCaption;
514 $fallbackRenderMethod = '';
515 if ($conf['fallbackRendering']) {
516 $fallbackRenderMethod = $this->cObj->cObjGetSingle($conf['fallbackRendering'], $conf['fallbackRendering.']);
517 }
518 if ($fallbackRenderMethod && is_array($conf['rendering.'][$fallbackRenderMethod . '.'])) {
519 $conf = array_replace_recursive($conf, $conf['rendering.'][$fallbackRenderMethod . '.']);
520 }
521 // Set the accessibility mode which uses a different type of markup, used 4.7+
522 $accessibilityMode = FALSE;
523 if (strpos(strtolower($renderMethod), 'caption') || strpos(strtolower($fallbackRenderMethod), 'caption')) {
524 $accessibilityMode = TRUE;
525 }
526 // Global caption
527 $globalCaption = '';
528 if ($renderGlobalCaption) {
529 $globalCaption = $this->cObj->stdWrap($this->cObj->cObjGet($conf['caption.'], 'caption.'), $conf['caption.']);
530 }
531 // Positioning
532 $position = $this->cObj->stdWrap($conf['textPos'], $conf['textPos.']);
533 // 0,1,2 = center,right,left
534 $imagePosition = $position & 7;
535 // 0,8,16,24 (above,below,intext,intext-wrap)
536 $contentPosition = $position & 24;
537 $textMargin = (int)$this->cObj->stdWrap($conf['textMargin'], $conf['textMargin.']);
538 if (!$conf['textMargin_outOfText'] && $contentPosition < 16) {
539 $textMargin = 0;
540 }
541 $colspacing = (int)$this->cObj->stdWrap($conf['colSpace'], $conf['colSpace.']);
542 $border = (int)$this->cObj->stdWrap($conf['border'], $conf['border.']) ? 1 : 0;
543 $borderThickness = (int)$this->cObj->stdWrap($conf['borderThick'], $conf['borderThick.']);
544 $borderThickness = $borderThickness ?: 1;
545 $borderSpace = $conf['borderSpace'] && $border ? (int)$conf['borderSpace'] : 0;
546 // Generate cols
547 $cols = (int)$this->cObj->stdWrap($conf['cols'], $conf['cols.']);
548 $colCount = $cols > 1 ? $cols : 1;
549 if ($colCount > $imgCount) {
550 $colCount = $imgCount;
551 }
552 $rowCount = ceil($imgCount / $colCount);
553 // Generate rows
554 $rows = (int)$this->cObj->stdWrap($conf['rows'], $conf['rows.']);
555 if ($rows > 1) {
556 $rowCount = $rows;
557 if ($rowCount > $imgCount) {
558 $rowCount = $imgCount;
559 }
560 $colCount = $rowCount > 1 ? ceil($imgCount / $rowCount) : $imgCount;
561 }
562 // Max Width
563 $maxW = (int)$this->cObj->stdWrap($conf['maxW'], $conf['maxW.']);
564 $maxWInText = (int)$this->cObj->stdWrap($conf['maxWInText'], $conf['maxWInText.']);
565 $fiftyPercentWidthInText = round($maxW / 100 * 50);
566 // in Text
567 if ($contentPosition >= 16) {
568 if (!$maxWInText) {
569 // If maxWInText is not set, it's calculated to the 50% of the max
570 $maxW = $fiftyPercentWidthInText;
571 } else {
572 $maxW = $maxWInText;
573 }
574 }
575 // max usuable width for images (without spacers and borders)
576 $netW = $maxW - $colspacing * ($colCount - 1) - $colCount * $border * ($borderThickness + $borderSpace) * 2;
577 // Specify the maximum width for each column
578 $columnWidths = $this->getImgColumnWidths($conf, $colCount, $netW);
579 $image_compression = (int)$this->cObj->stdWrap($conf['image_compression'], $conf['image_compression.']);
580 $image_effects = (int)$this->cObj->stdWrap($conf['image_effects'], $conf['image_effects.']);
581 $image_frames = (int)$this->cObj->stdWrap($conf['image_frames.']['key'], $conf['image_frames.']['key.']);
582 // EqualHeight
583 $equalHeight = (int)$this->cObj->stdWrap($conf['equalH'], $conf['equalH.']);
584 if ($equalHeight) {
585 $relations_cols = array();
586 // contains the individual width of all images after scaling to $equalHeight
587 $imgWidths = array();
588 for ($a = 0; $a < $imgCount; $a++) {
589 $imgKey = $a + $imgStart;
590
591 /** @var $file \TYPO3\CMS\Core\Resource\File */
592 if (MathUtility::canBeInterpretedAsInteger($imgs[$imgKey])) {
593 if ($imgListContainsReferenceUids) {
594 $file = $this->getResourceFactory()->getFileReferenceObject((int)$imgs[$imgKey])->getOriginalFile();
595 } else {
596 $file = $this->getResourceFactory()->getFileObject((int)$imgs[$imgKey]);
597 }
598
599 } else {
600 $file = $this->getResourceFactory()->getFileObjectFromCombinedIdentifier($imgPath . $imgs[$imgKey]);
601 }
602
603 // relationship between the original height and the wished height
604 $rel = $file->getProperty('height') / $equalHeight;
605 // if relations is zero, then the addition of this value is omitted as the image is not expected to display because of some error.
606 if ($rel) {
607 $imgWidths[$a] = $file->getProperty('width') / $rel;
608 // counts the total width of the row with the new height taken into consideration.
609 $relations_cols[(int)floor($a / $colCount)] += $imgWidths[$a];
610 }
611 }
612 }
613 // Fetches pictures
614 $splitArr = array();
615 $splitArr['imgObjNum'] = $conf['imgObjNum'];
616 $splitArr = $GLOBALS['TSFE']->tmpl->splitConfArray($splitArr, $imgCount);
617 // Contains the width of every image row
618 $imageRowsFinalWidths = array();
619 // Array index of $imgsTag will be the same as in $imgs, but $imgsTag only contains the images that are actually shown
620 $imgsTag = array();
621 $origImages = array();
622 $rowIdx = 0;
623 for ($a = 0; $a < $imgCount; $a++) {
624 $imgKey = $a + $imgStart;
625 // If the image cannot be interpreted as integer (therefore filename and no FAL id), add the image path
626 if (MathUtility::canBeInterpretedAsInteger($imgs[$imgKey])) {
627 $totalImagePath = (int)$imgs[$imgKey];
628 $this->initializeCurrentFileInContentObjectRenderer($totalImagePath, $imgListContainsReferenceUids);
629 } else {
630 $totalImagePath = $imgPath . $imgs[$imgKey];
631 }
632 // register IMG_NUM is kept for backwards compatibility
633 $GLOBALS['TSFE']->register['IMAGE_NUM'] = $imgKey;
634 $GLOBALS['TSFE']->register['IMAGE_NUM_CURRENT'] = $imgKey;
635 $GLOBALS['TSFE']->register['ORIG_FILENAME'] = $totalImagePath;
636 $this->cObj->data[$this->cObj->currentValKey] = $totalImagePath;
637 $imgObjNum = (int)$splitArr[$a]['imgObjNum'];
638 $imgConf = $conf[$imgObjNum . '.'];
639 if ($equalHeight) {
640 if ($a % $colCount == 0) {
641 // A new row starts
642 // Reset accumulated net width
643 $accumWidth = 0;
644 // Reset accumulated desired width
645 $accumDesiredWidth = 0;
646 $rowTotalMaxW = $relations_cols[$rowIdx];
647 if ($rowTotalMaxW > $netW && $netW > 0) {
648 $scale = $rowTotalMaxW / $netW;
649 } else {
650 $scale = 1;
651 }
652 $desiredHeight = $equalHeight / $scale;
653 $rowIdx++;
654 }
655 // This much width is available for the remaining images in this row (int)
656 $availableWidth = $netW - $accumWidth;
657 // Theoretical width of resized image. (float)
658 $desiredWidth = $imgWidths[$a] / $scale;
659 // Add this width. $accumDesiredWidth becomes the desired horizontal position
660 $accumDesiredWidth += $desiredWidth;
661 // Calculate width by comparing actual and desired horizontal position.
662 // this evenly distributes rounding errors across all images in this row.
663 $suggestedWidth = round($accumDesiredWidth - $accumWidth);
664 // finalImgWidth may not exceed $availableWidth
665 $finalImgWidth = (int)min($availableWidth, $suggestedWidth);
666 $accumWidth += $finalImgWidth;
667 $imgConf['file.']['width'] = $finalImgWidth;
668 $imgConf['file.']['height'] = round($desiredHeight);
669 // other stuff will be calculated accordingly:
670 unset($imgConf['file.']['maxW']);
671 unset($imgConf['file.']['maxH']);
672 unset($imgConf['file.']['minW']);
673 unset($imgConf['file.']['minH']);
674 unset($imgConf['file.']['width.']);
675 unset($imgConf['file.']['maxW.']);
676 unset($imgConf['file.']['maxH.']);
677 unset($imgConf['file.']['minW.']);
678 unset($imgConf['file.']['minH.']);
679 } else {
680 $imgConf['file.']['maxW'] = $columnWidths[$a % $colCount];
681 }
682 $titleInLink = $this->cObj->stdWrap($imgConf['titleInLink'], $imgConf['titleInLink.']);
683 $titleInLinkAndImg = $this->cObj->stdWrap($imgConf['titleInLinkAndImg'], $imgConf['titleInLinkAndImg.']);
684 $oldATagParms = $GLOBALS['TSFE']->ATagParams;
685 if ($titleInLink) {
686 // Title in A-tag instead of IMG-tag
687 $titleText = trim($this->cObj->stdWrap($imgConf['titleText'], $imgConf['titleText.']));
688 if ($titleText) {
689 // This will be used by the IMAGE call later:
690 $GLOBALS['TSFE']->ATagParams .= ' title="' . htmlspecialchars($titleText) . '"';
691 }
692 }
693
694 // hook to allow custom rendering of a single element
695 // This hook is needed to render alternative content which is not just a plain image,
696 // like showing other FAL content, like videos, things which need to be embedded as JS, ...
697 $customRendering = '';
698 if (isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['css_styled_content']['pi1_hooks']['render_singleMediaElement'])
699 && is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['css_styled_content']['pi1_hooks']['render_singleMediaElement'])) {
700 $hookParameters = array(
701 'file' => $totalImagePath,
702 'imageConfiguration' => $imgConf
703 );
704
705 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['css_styled_content']['pi1_hooks']['render_singleMediaElement'] as $reference) {
706 $customRendering = \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($reference, $hookParameters, $this);
707 // if there is a renderer found, don't run through the other renderers
708 if (!empty($customRendering)) {
709 break;
710 }
711 }
712 }
713
714 if (!empty($customRendering)) {
715 $imgsTag[$imgKey] = $customRendering;
716 } elseif ($imgConf || $imgConf['file']) {
717 if ($this->cObj->image_effects[$image_effects]) {
718 $imgConf['file.']['params'] .= ' ' . $this->cObj->image_effects[$image_effects];
719 }
720 if ($image_frames) {
721 if (is_array($conf['image_frames.'][$image_frames . '.'])) {
722 $imgConf['file.']['m.'] = $conf['image_frames.'][$image_frames . '.'];
723 }
724 }
725 if ($image_compression && $imgConf['file'] != 'GIFBUILDER') {
726 if ($image_compression == 1) {
727 $tempImport = $imgConf['file.']['import'];
728 $tempImport_dot = $imgConf['file.']['import.'];
729 $tempTreatIdAsReference = $imgConf['file.']['treatIdAsReference'];
730 unset($imgConf['file.']);
731 $imgConf['file.']['import'] = $tempImport;
732 $imgConf['file.']['import.'] = $tempImport_dot;
733 $imgConf['file.']['treatIdAsReference'] = $tempTreatIdAsReference;
734 } elseif (isset($this->cObj->image_compression[$image_compression])) {
735 $imgConf['file.']['params'] .= ' ' . $this->cObj->image_compression[$image_compression]['params'];
736 $imgConf['file.']['ext'] = $this->cObj->image_compression[$image_compression]['ext'];
737 unset($imgConf['file.']['ext.']);
738 }
739 }
740 if ($titleInLink && !$titleInLinkAndImg) {
741 // Check if the image will be linked
742 $link = $this->cObj->imageLinkWrap('', $this->cObj->getCurrentFile() ?: $totalImagePath, $imgConf['imageLinkWrap.']);
743 if ($link) {
744 // Title in A-tag only (set above: ATagParams), not in IMG-tag
745 unset($imgConf['titleText']);
746 unset($imgConf['titleText.']);
747 $imgConf['emptyTitleHandling'] = 'removeAttr';
748 }
749 }
750 $imgsTag[$imgKey] = $this->cObj->IMAGE($imgConf);
751 } else {
752 // currentValKey !!!
753 $imgsTag[$imgKey] = $this->cObj->IMAGE(array('file' => $totalImagePath));
754 }
755 // Restore our ATagParams
756 $GLOBALS['TSFE']->ATagParams = $oldATagParms;
757 // Store the original filepath
758 $origImages[$imgKey] = $GLOBALS['TSFE']->lastImageInfo;
759 if ($GLOBALS['TSFE']->lastImageInfo[0] == 0) {
760 $imageRowsFinalWidths[(int)floor($a / $colCount)] += $this->cObj->data['imagewidth'];
761 } else {
762 $imageRowsFinalWidths[(int)floor($a / $colCount)] += $GLOBALS['TSFE']->lastImageInfo[0];
763 }
764 }
765 // How much space will the image-block occupy?
766 $imageBlockWidth = max($imageRowsFinalWidths) + $colspacing * ($colCount - 1) + $colCount * $border * ($borderSpace + $borderThickness) * 2;
767 $GLOBALS['TSFE']->register['rowwidth'] = $imageBlockWidth;
768 $GLOBALS['TSFE']->register['rowWidthPlusTextMargin'] = $imageBlockWidth + $textMargin;
769 // noRows is in fact just one ROW, with the amount of columns specified, where the images are placed in.
770 // noCols is just one COLUMN, each images placed side by side on each row
771 $noRows = $this->cObj->stdWrap($conf['noRows'], $conf['noRows.']);
772 $noCols = $this->cObj->stdWrap($conf['noCols'], $conf['noCols.']);
773 // noRows overrides noCols. They cannot exist at the same time.
774 if ($noRows) {
775 $noCols = 0;
776 $rowCount = 1;
777 }
778 if ($noCols) {
779 $colCount = 1;
780 }
781 // Edit icons:
782 if (!is_array($conf['editIcons.'])) {
783 $conf['editIcons.'] = array();
784 }
785 $editIconsHTML = $conf['editIcons'] && $GLOBALS['TSFE']->beUserLogin ? $this->cObj->editIcons('', $conf['editIcons'], $conf['editIcons.']) : '';
786 // If noRows, we need multiple imagecolumn wraps
787 $imageWrapCols = 1;
788 if ($noRows) {
789 $imageWrapCols = $colCount;
790 }
791 // User wants to separate the rows, but only do that if we do have rows
792 $separateRows = $this->cObj->stdWrap($conf['separateRows'], $conf['separateRows.']);
793 if ($noRows) {
794 $separateRows = 0;
795 }
796 if ($rowCount == 1) {
797 $separateRows = 0;
798 }
799 if ($accessibilityMode) {
800 $imagesInColumns = round($imgCount / ($rowCount * $colCount), 0, PHP_ROUND_HALF_UP);
801 // Apply optionSplit to the list of classes that we want to add to each column
802 $addClassesCol = $conf['addClassesCol'];
803 if (isset($conf['addClassesCol.'])) {
804 $addClassesCol = $this->cObj->stdWrap($addClassesCol, $conf['addClassesCol.']);
805 }
806 $addClassesColConf = $GLOBALS['TSFE']->tmpl->splitConfArray(array('addClassesCol' => $addClassesCol), $colCount);
807 // Apply optionSplit to the list of classes that we want to add to each image
808 $addClassesImage = $conf['addClassesImage'];
809 if (isset($conf['addClassesImage.'])) {
810 $addClassesImage = $this->cObj->stdWrap($addClassesImage, $conf['addClassesImage.']);
811 }
812 $addClassesImageConf = $GLOBALS['TSFE']->tmpl->splitConfArray(array('addClassesImage' => $addClassesImage), $imagesInColumns);
813 $rows = array();
814 $currentImage = 0;
815 // Set the class for the caption (split or global)
816 $classCaptionAlign = array(
817 'center' => 'csc-textpic-caption-c',
818 'right' => 'csc-textpic-caption-r',
819 'left' => 'csc-textpic-caption-l'
820 );
821 $captionAlign = $this->cObj->stdWrap($conf['captionAlign'], $conf['captionAlign.']);
822 // Iterate over the rows
823 for ($rowCounter = 1; $rowCounter <= $rowCount; $rowCounter++) {
824 $rowColumns = array();
825 // Iterate over the columns
826 for ($columnCounter = 1; $columnCounter <= $colCount; $columnCounter++) {
827 $columnImages = array();
828 // Iterate over the amount of images allowed in a column
829 for ($imagesCounter = 1; $imagesCounter <= $imagesInColumns; $imagesCounter++) {
830 $image = NULL;
831 $splitCaption = NULL;
832 $imageMarkers = ($captionMarkers = array());
833 $single = '&nbsp;';
834 // Set the key of the current image
835 $imageKey = $currentImage + $imgStart;
836 // Register IMAGE_NUM_CURRENT for the caption
837 $GLOBALS['TSFE']->register['IMAGE_NUM_CURRENT'] = $imageKey;
838 $this->cObj->data[$this->cObj->currentValKey] = $origImages[$imageKey]['origFile'];
839 if (MathUtility::canBeInterpretedAsInteger($imgs[$imageKey])) {
840 $this->initializeCurrentFileInContentObjectRenderer((int)$imgs[$imageKey], $imgListContainsReferenceUids);
841 } elseif (!isset($imgs[$imageKey])) {
842 // If not all columns in the last row are filled $imageKey gets larger than
843 // the array. In that case we clear the current file.
844 $this->cObj->setCurrentFile(NULL);
845 }
846 // Get the image if not an empty cell
847 if (isset($imgsTag[$imageKey])) {
848 $image = $this->cObj->stdWrap($imgsTag[$imageKey], $conf['imgTagStdWrap.']);
849 // Add the edit icons
850 if ($editIconsHTML) {
851 $image .= $this->cObj->stdWrap($editIconsHTML, $conf['editIconsStdWrap.']);
852 }
853 // Wrap the single image
854 $single = $this->cObj->stdWrap($image, $conf['singleStdWrap.']);
855 // Get the caption
856 if (!$renderGlobalCaption) {
857 $imageMarkers['caption'] = $this->cObj->stdWrap($this->cObj->cObjGet($conf['caption.'], 'caption.'), $conf['caption.']);
858 if ($captionAlign) {
859 $captionMarkers['classes'] = ' ' . $classCaptionAlign[$captionAlign];
860 }
861 $imageMarkers['caption'] = $this->cObj->substituteMarkerArray($imageMarkers['caption'], $captionMarkers, '###|###', 1, 1);
862 }
863 if ($addClassesImageConf[$imagesCounter - 1]['addClassesImage']) {
864 $imageMarkers['classes'] = ' ' . $addClassesImageConf[($imagesCounter - 1)]['addClassesImage'];
865 }
866 }
867 $columnImages[] = $this->cObj->substituteMarkerArray($single, $imageMarkers, '###|###', 1, 1);
868 $currentImage++;
869 }
870 $rowColumn = $this->cObj->stdWrap(implode(LF, $columnImages), $conf['columnStdWrap.']);
871 // Start filling the markers for columnStdWrap
872 $columnMarkers = array();
873 if ($addClassesColConf[$columnCounter - 1]['addClassesCol']) {
874 $columnMarkers['classes'] = ' ' . $addClassesColConf[($columnCounter - 1)]['addClassesCol'];
875 }
876 $rowColumns[] = $this->cObj->substituteMarkerArray($rowColumn, $columnMarkers, '###|###', 1, 1);
877 }
878 if ($noRows) {
879 $rowConfiguration = $conf['noRowsStdWrap.'];
880 } elseif ($rowCounter == $rowCount) {
881 $rowConfiguration = $conf['lastRowStdWrap.'];
882 } else {
883 $rowConfiguration = $conf['rowStdWrap.'];
884 }
885 $row = $this->cObj->stdWrap(implode(LF, $rowColumns), $rowConfiguration);
886 // Start filling the markers for columnStdWrap
887 $rowMarkers = array();
888 $rows[] = $this->cObj->substituteMarkerArray($row, $rowMarkers, '###|###', 1, 1);
889 }
890 $images = $this->cObj->stdWrap(implode(LF, $rows), $conf['allStdWrap.']);
891 // Start filling the markers for allStdWrap
892 $allMarkers = array();
893 $classes = array();
894 // Add the global caption to the allStdWrap marker array if set
895 if ($globalCaption) {
896 $allMarkers['caption'] = $globalCaption;
897 if ($captionAlign) {
898 $classes[] = $classCaptionAlign[$captionAlign];
899 }
900 }
901 // Set the margin for image + text, no wrap always to avoid multiple stylesheets
902 $noWrapMargin = (int)(($maxWInText ? $maxWInText : $fiftyPercentWidthInText) + (int)$this->cObj->stdWrap($conf['textMargin'], $conf['textMargin.']));
903 $this->addPageStyle('.csc-textpic-intext-right-nowrap .csc-textpic-text', 'margin-right: ' . $noWrapMargin . 'px;');
904 $this->addPageStyle('.csc-textpic-intext-left-nowrap .csc-textpic-text', 'margin-left: ' . $noWrapMargin . 'px;');
905 // Beside Text where the image block width is not equal to maxW
906 if ($contentPosition == 24 && $maxW != $imageBlockWidth) {
907 $noWrapMargin = $imageBlockWidth + $textMargin;
908 // Beside Text, Right
909 if ($imagePosition == 1) {
910 $this->addPageStyle('.csc-textpic-intext-right-nowrap-' . $noWrapMargin . ' .csc-textpic-text', 'margin-right: ' . $noWrapMargin . 'px;');
911 $classes[] = 'csc-textpic-intext-right-nowrap-' . $noWrapMargin;
912 } elseif ($imagePosition == 2) {
913 $this->addPageStyle('.csc-textpic-intext-left-nowrap-' . $noWrapMargin . ' .csc-textpic-text', 'margin-left: ' . $noWrapMargin . 'px;');
914 $classes[] = 'csc-textpic-intext-left-nowrap-' . $noWrapMargin;
915 }
916 }
917 // Add the border class if needed
918 if ($border) {
919 $classes[] = $conf['borderClass'] ?: 'csc-textpic-border';
920 }
921 // Add the class for equal height if needed
922 if ($equalHeight) {
923 $classes[] = 'csc-textpic-equalheight';
924 }
925 $addClasses = $this->cObj->stdWrap($conf['addClasses'], $conf['addClasses.']);
926 if ($addClasses) {
927 $classes[] = $addClasses;
928 }
929 if ($classes) {
930 $class = ' ' . implode(' ', $classes);
931 }
932 // Fill the markers for the allStdWrap
933 $images = $this->cObj->substituteMarkerArray($images, $allMarkers, '###|###', 1, 1);
934 } else {
935 // Apply optionSplit to the list of classes that we want to add to each image
936 $addClassesImage = $conf['addClassesImage'];
937 if (isset($conf['addClassesImage.'])) {
938 $addClassesImage = $this->cObj->stdWrap($addClassesImage, $conf['addClassesImage.']);
939 }
940 $addClassesImageConf = $GLOBALS['TSFE']->tmpl->splitConfArray(array('addClassesImage' => $addClassesImage), $colCount);
941 // Render the images
942 $images = '';
943 for ($c = 0; $c < $imageWrapCols; $c++) {
944 $tmpColspacing = $colspacing;
945 if ($c == $imageWrapCols - 1 && $imagePosition == 2 || $c == 0 && ($imagePosition == 1 || $imagePosition == 0)) {
946 // Do not add spacing after column if we are first column (left) or last column (center/right)
947 $tmpColspacing = 0;
948 }
949 $thisImages = '';
950 $allRows = '';
951 $maxImageSpace = 0;
952 $imgsTagCount = count($imgsTag);
953 for ($i = $c; $i < $imgsTagCount; $i = $i + $imageWrapCols) {
954 $imgKey = $i + $imgStart;
955 $colPos = $i % $colCount;
956 if ($separateRows && $colPos == 0) {
957 $thisRow = '';
958 }
959 // Render one image
960 if ($origImages[$imgKey][0] == 0) {
961 $imageSpace = $this->cObj->data['imagewidth'] + $border * ($borderSpace + $borderThickness) * 2;
962 } else {
963 $imageSpace = $origImages[$imgKey][0] + $border * ($borderSpace + $borderThickness) * 2;
964 }
965 $GLOBALS['TSFE']->register['IMAGE_NUM'] = $imgKey;
966 $GLOBALS['TSFE']->register['IMAGE_NUM_CURRENT'] = $imgKey;
967 $GLOBALS['TSFE']->register['ORIG_FILENAME'] = $origImages[$imgKey]['origFile'];
968 $GLOBALS['TSFE']->register['imagewidth'] = $origImages[$imgKey][0];
969 $GLOBALS['TSFE']->register['imagespace'] = $imageSpace;
970 $GLOBALS['TSFE']->register['imageheight'] = $origImages[$imgKey][1];
971 if (MathUtility::canBeInterpretedAsInteger($imgs[$imgKey])) {
972 $this->initializeCurrentFileInContentObjectRenderer(intval($imgs[$imgKey]), $imgListContainsReferenceUids);
973 }
974 if ($imageSpace > $maxImageSpace) {
975 $maxImageSpace = $imageSpace;
976 }
977 $thisImage = '';
978 $thisImage .= $this->cObj->stdWrap($imgsTag[$imgKey], $conf['imgTagStdWrap.']);
979 if (!$renderGlobalCaption) {
980 $thisImage .= $this->cObj->stdWrap($this->cObj->cObjGet($conf['caption.'], 'caption.'), $conf['caption.']);
981 }
982 if ($editIconsHTML) {
983 $thisImage .= $this->cObj->stdWrap($editIconsHTML, $conf['editIconsStdWrap.']);
984 }
985 $thisImage = $this->cObj->stdWrap($thisImage, $conf['oneImageStdWrap.']);
986 $classes = '';
987 if ($addClassesImageConf[$colPos]['addClassesImage']) {
988 $classes = ' ' . $addClassesImageConf[$colPos]['addClassesImage'];
989 }
990 $thisImage = str_replace('###CLASSES###', $classes, $thisImage);
991 if ($separateRows) {
992 $thisRow .= $thisImage;
993 } else {
994 $allRows .= $thisImage;
995 }
996 $GLOBALS['TSFE']->register['columnwidth'] = $maxImageSpace + $tmpColspacing;
997 // Close this row at the end (colCount), or the last row at the final end
998 if ($separateRows && $i + 1 == count($imgsTag)) {
999 // Close the very last row with either normal configuration or lastRow stdWrap
1000 $allRows .= $this->cObj->stdWrap(
1001 $thisRow,
1002 is_array($conf['imageLastRowStdWrap.']) ? $conf['imageLastRowStdWrap.'] : $conf['imageRowStdWrap.']
1003 );
1004 } elseif ($separateRows && $colPos == $colCount - 1) {
1005 $allRows .= $this->cObj->stdWrap($thisRow, $conf['imageRowStdWrap.']);
1006 }
1007 }
1008 if ($separateRows) {
1009 $thisImages .= $allRows;
1010 } else {
1011 $thisImages .= $this->cObj->stdWrap($allRows, $conf['noRowsStdWrap.']);
1012 }
1013 if ($noRows) {
1014 // Only needed to make columns, rather than rows:
1015 $images .= $this->cObj->stdWrap($thisImages, $conf['imageColumnStdWrap.']);
1016 } else {
1017 $images .= $thisImages;
1018 }
1019 }
1020 // Add the global caption, if not split
1021 if ($globalCaption) {
1022 $images .= $globalCaption;
1023 }
1024 // CSS-classes
1025 $captionClass = '';
1026 $classCaptionAlign = array(
1027 'center' => 'csc-textpic-caption-c',
1028 'right' => 'csc-textpic-caption-r',
1029 'left' => 'csc-textpic-caption-l'
1030 );
1031 $captionAlign = $this->cObj->stdWrap($conf['captionAlign'], $conf['captionAlign.']);
1032 if ($captionAlign) {
1033 $captionClass = $classCaptionAlign[$captionAlign];
1034 }
1035 $borderClass = '';
1036 if ($border) {
1037 $borderClass = $conf['borderClass'] ?: 'csc-textpic-border';
1038 }
1039 // Multiple classes with all properties, to be styled in CSS
1040 $class = '';
1041 $class .= $borderClass ? ' ' . $borderClass : '';
1042 $class .= $captionClass ? ' ' . $captionClass : '';
1043 $class .= $equalHeight ? ' csc-textpic-equalheight' : '';
1044 $addClasses = $this->cObj->stdWrap($conf['addClasses'], $conf['addClasses.']);
1045 $class .= $addClasses ? ' ' . $addClasses : '';
1046 // Do we need a width in our wrap around images?
1047 $imgWrapWidth = '';
1048 if ($position == 0 || $position == 8) {
1049 // For 'center' we always need a width: without one, the margin:auto trick won't work
1050 $imgWrapWidth = $imageBlockWidth;
1051 }
1052 if ($rowCount > 1) {
1053 // For multiple rows we also need a width, so that the images will wrap
1054 $imgWrapWidth = $imageBlockWidth;
1055 }
1056 if ($globalCaption) {
1057 // If we have a global caption, we need the width so that the caption will wrap
1058 $imgWrapWidth = $imageBlockWidth;
1059 }
1060 // Wrap around the whole image block
1061 $GLOBALS['TSFE']->register['totalwidth'] = $imgWrapWidth;
1062 if ($imgWrapWidth) {
1063 $images = $this->cObj->stdWrap($images, $conf['imageStdWrap.']);
1064 } else {
1065 $images = $this->cObj->stdWrap($images, $conf['imageStdWrapNoWidth.']);
1066 }
1067 }
1068
1069 $output = str_replace(
1070 array(
1071 '###TEXT###',
1072 '###IMAGES###',
1073 '###CLASSES###'
1074 ),
1075 array(
1076 $content,
1077 $images,
1078 $class
1079 ),
1080 $this->cObj->cObjGetSingle($conf['layout'], $conf['layout.'])
1081 );
1082
1083 if (isset($conf['preRenderRegisters.'])) {
1084 $this->cObj->LOAD_REGISTER($conf['preRenderRegisters.'], 'RESTORE_REGISTER');
1085 }
1086
1087 return $output;
1088 }
1089
1090 /**
1091 * Loads the file / file reference object and sets it in the
1092 * currentFile property of the ContentObjectRenderer.
1093 *
1094 * This makes the file data available during image rendering.
1095 *
1096 * @param int $fileUid The UID of the file or file reference (depending on $treatAsReference) that should be loaded.
1097 * @param bool $treatAsReference If TRUE the given UID will be used to load a file reference otherwise it will be used to load a regular file.
1098 * @return void
1099 */
1100 protected function initializeCurrentFileInContentObjectRenderer($fileUid, $treatAsReference) {
1101 $resourceFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
1102 if ($treatAsReference) {
1103 $imageFile = $resourceFactory->getFileReferenceObject($fileUid);
1104 } else {
1105 $imageFile = $resourceFactory->getFileObject($fileUid);
1106 }
1107 $this->cObj->setCurrentFile($imageFile);
1108 }
1109
1110 /***********************************
1111 * Rendering of Content Element properties
1112 ***********************************/
1113
1114 /**
1115 * Add top or bottom margin to the content element
1116 *
1117 * Constructs and adds a class to the content element. This class selector
1118 * and its declaration are added to the specific page styles.
1119 *
1120 * @param string $content Content input. Not used, ignore.
1121 * @param array $configuration TypoScript configuration
1122 * @return string The class name
1123 */
1124 public function renderSpace($content, array $configuration) {
1125 // Look for hook before running default code for function
1126 if (method_exists($this, 'hookRequest') && ($hookObject = $this->hookRequest('renderSpace'))) {
1127 return $hookObject->renderSpace($content, $configuration);
1128 }
1129 if (isset($configuration['space']) && in_array($configuration['space'], array('before', 'after'))) {
1130 $constant = (int)$configuration['constant'];
1131 if ($configuration['space'] === 'before') {
1132 $value = $constant + $this->cObj->data['spaceBefore'];
1133 $declaration = 'margin-top: ' . $value . 'px !important;';
1134 } else {
1135 $value = $constant + $this->cObj->data['spaceAfter'];
1136 $declaration = 'margin-bottom: ' . $value . 'px !important;';
1137 }
1138 if (!empty($value)) {
1139 if ($configuration['classStdWrap.']) {
1140 $className = $this->cObj->stdWrap($value, $configuration['classStdWrap.']);
1141 } else {
1142 $className = $value;
1143 }
1144 $selector = '.' . trim($className);
1145 $this->addPageStyle($selector, $declaration);
1146 return $className;
1147 }
1148 }
1149 }
1150
1151 /************************************
1152 * Helper functions
1153 ************************************/
1154
1155 /**
1156 * Returns a link text string which replaces underscores in filename with
1157 * blanks.
1158 *
1159 * Has the possibility to cut off FileType.
1160 *
1161 * @param array $links
1162 * @param string $fileName
1163 * @param boolean $useSpaces
1164 * @param boolean $cutFileExtension
1165 * @return array modified array with new link text
1166 */
1167 protected function beautifyFileLink(array $links, $fileName, $useSpaces = FALSE, $cutFileExtension = FALSE) {
1168 $linkText = $fileName;
1169 if ($useSpaces) {
1170 $linkText = str_replace('_', ' ', $linkText);
1171 }
1172 if ($cutFileExtension) {
1173 $pos = strrpos($linkText, '.');
1174 $linkText = substr($linkText, 0, $pos);
1175 }
1176 $links[1] = str_replace('>' . $fileName . '<', '>' . htmlspecialchars($linkText) . '<', $links[1]);
1177 return $links;
1178 }
1179
1180 /**
1181 * Returns table attributes for uploads / tables.
1182 *
1183 * @param array $conf TypoScript configuration array
1184 * @param integer $type The "layout" type
1185 * @return array Array with attributes inside.
1186 * @todo Define visibility
1187 */
1188 public function getTableAttributes($conf, $type) {
1189 // Initializing:
1190 $tableTagParams_conf = $conf['tableParams_' . $type . '.'];
1191 $border = $this->cObj->data['table_border'] ? (int)$this->cObj->data['table_border'] : $tableTagParams_conf['border'];
1192 $cellSpacing = $this->cObj->data['table_cellspacing'] ? (int)$this->cObj->data['table_cellspacing'] : $tableTagParams_conf['cellspacing'];
1193 $cellPadding = $this->cObj->data['table_cellpadding'] ? (int)$this->cObj->data['table_cellpadding'] : $tableTagParams_conf['cellpadding'];
1194 $summary = trim(htmlspecialchars($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'acctables_summary')));
1195 // Create table attributes and classes array:
1196 $tableTagParams = ($classes = array());
1197 // Table attributes for all doctypes except HTML5
1198 if ($GLOBALS['TSFE']->config['config']['doctype'] !== 'html5') {
1199 $tableTagParams['border'] = $border;
1200 $tableTagParams['cellspacing'] = $cellSpacing;
1201 $tableTagParams['cellpadding'] = $cellPadding;
1202 if ($summary) {
1203 $tableTagParams['summary'] = $summary;
1204 }
1205 } else {
1206 if ($border) {
1207 // Border property has changed, now with class
1208 $borderClass = 'contenttable-border-' . $border;
1209 $borderDeclaration = 'border-width: ' . $border . 'px; border-style: solid;';
1210 $this->addPageStyle('.' . $borderClass, $borderDeclaration);
1211 $classes[] = $borderClass;
1212 }
1213 if ($cellSpacing) {
1214 // Border attribute for HTML5 is 1 when there is cell spacing
1215 $tableTagParams['border'] = 1;
1216 // Use CSS3 border-spacing in class to have cell spacing
1217 $cellSpacingClass = 'contenttable-cellspacing-' . $cellSpacing;
1218 $cellSpacingDeclaration = 'border-spacing: ' . $cellSpacing . 'px;';
1219 $this->addPageStyle('.' . $cellSpacingClass, $cellSpacingDeclaration);
1220 $classes[] = $cellSpacingClass;
1221 }
1222 if ($cellPadding) {
1223 // Cell padding property has changed, now with class
1224 $cellPaddingClass = 'contenttable-cellpadding-' . $cellPadding;
1225 $cellSpacingSelector = '.' . $cellPaddingClass . ' td, .' . $cellPaddingClass . ' th';
1226 $cellPaddingDeclaration = 'padding: ' . $cellPadding . 'px;';
1227 $this->addPageStyle($cellSpacingSelector, $cellPaddingDeclaration);
1228 $classes[] = $cellPaddingClass;
1229 }
1230 }
1231 // Background color is class
1232 if (isset($conf['color.'][$this->cObj->data['table_bgColor']]) && !empty($conf['color.'][$this->cObj->data['table_bgColor']])) {
1233 $classes[] = 'contenttable-color-' . $this->cObj->data['table_bgColor'];
1234 }
1235 if (!empty($classes)) {
1236 $tableTagParams['class'] = ' ' . implode(' ', $classes);
1237 }
1238 // Return result:
1239 return $tableTagParams;
1240 }
1241
1242 /**
1243 * Add a style to the page, specific for this page
1244 *
1245 * The selector can be a contextual selector, like '#id .class p'
1246 * The presence of the selector is checked to avoid multiple entries of the
1247 * same selector.
1248 *
1249 * @param string $selector The selector
1250 * @param string $declaration The declaration
1251 * @return void
1252 */
1253 protected function addPageStyle($selector, $declaration) {
1254 if (!isset($GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_cssstyledcontent.']['_CSS_PAGE_STYLE'])) {
1255 $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_cssstyledcontent.']['_CSS_PAGE_STYLE'] = array();
1256 }
1257 if (!isset($GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_cssstyledcontent.']['_CSS_PAGE_STYLE'][$selector])) {
1258 $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_cssstyledcontent.']['_CSS_PAGE_STYLE'][$selector] = TAB . $selector . ' { ' . $declaration . ' }';
1259 }
1260 }
1261
1262 /**
1263 * Returns an object reference to the hook object if any
1264 *
1265 * @param string $functionName Name of the function you want to call / hook key
1266 * @return object Hook object, if any. Otherwise NULL.
1267 * @todo Define visibility
1268 */
1269 public function hookRequest($functionName) {
1270 global $TYPO3_CONF_VARS;
1271 // Hook: menuConfig_preProcessModMenu
1272 if ($TYPO3_CONF_VARS['EXTCONF']['css_styled_content']['pi1_hooks'][$functionName]) {
1273 $hookObj = GeneralUtility::getUserObj($TYPO3_CONF_VARS['EXTCONF']['css_styled_content']['pi1_hooks'][$functionName]);
1274 if (method_exists($hookObj, $functionName)) {
1275 $hookObj->pObj = $this;
1276 return $hookObj;
1277 }
1278 }
1279 }
1280
1281 /**
1282 * Get the ResourceFactory
1283 *
1284 * @return \TYPO3\CMS\Core\Resource\ResourceFactory
1285 */
1286 protected function getResourceFactory() {
1287 return \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
1288 }
1289 }