a08ce6a0b57af227110341bef84bcaaac00edbc8
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Html / RteHtmlParser.php
1 <?php
2 namespace TYPO3\CMS\Core\Html;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 1999-2013 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the text file GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29
30 use TYPO3\CMS\Backend\Utility\BackendUtility;
31 use TYPO3\CMS\Core\Utility\GeneralUtility;
32 use TYPO3\CMS\Core\Resource;
33
34 /**
35 * Class for parsing HTML for the Rich Text Editor. (also called transformations)
36 *
37 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
38 */
39 class RteHtmlParser extends \TYPO3\CMS\Core\Html\HtmlParser {
40
41 // Static:
42 /**
43 * @todo Define visibility
44 */
45 public $blockElementList = 'PRE,UL,OL,H1,H2,H3,H4,H5,H6,ADDRESS,DL,DD,HEADER,SECTION,FOOTER,NAV,ARTICLE,ASIDE';
46
47 // List of tags for these elements
48 // Internal, static:
49 // Set this to the pid of the record manipulated by the class.
50 /**
51 * @todo Define visibility
52 */
53 public $recPid = 0;
54
55 // Element reference [table]:[field], eg. "tt_content:bodytext"
56 /**
57 * @todo Define visibility
58 */
59 public $elRef = '';
60
61 // Relative path
62 /**
63 * @todo Define visibility
64 */
65 public $relPath = '';
66
67 // Relative back-path
68 /**
69 * @todo Define visibility
70 */
71 public $relBackPath = '';
72
73 // Current Page TSConfig
74 public $tsConfig = array();
75
76 // Set to the TSconfig options coming from Page TSconfig
77 /**
78 * @todo Define visibility
79 */
80 public $procOptions = array();
81
82 // Internal, dynamic
83 // Run-away brake for recursive calls.
84 /**
85 * @todo Define visibility
86 */
87 public $TS_transform_db_safecounter = 100;
88
89 // Parameters from TCA types configuration related to the RTE
90 /**
91 * @todo Define visibility
92 */
93 public $rte_p = '';
94
95 // Data caching for processing function
96 /**
97 * @todo Define visibility
98 */
99 public $getKeepTags_cache = array();
100
101 // Storage of the allowed CSS class names in the RTE
102 /**
103 * @todo Define visibility
104 */
105 public $allowedClasses = array();
106
107 // Set to tags to preserve from Page TSconfig configuration
108 /**
109 * @todo Define visibility
110 */
111 public $preserveTags = '';
112
113 /**
114 * Initialize, setting element reference and record PID
115 *
116 * @param string $elRef Element reference, eg "tt_content:bodytext
117 * @param integer $recPid PID of the record (page id)
118 * @return void
119 * @todo Define visibility
120 */
121 public function init($elRef = '', $recPid = 0) {
122 $this->recPid = $recPid;
123 $this->elRef = $elRef;
124 }
125
126 /**
127 * Setting the ->relPath and ->relBackPath to proper values so absolute references to links and images can be converted to relative dittos.
128 * This is used when editing files with the RTE
129 *
130 * @param string $path The relative path from PATH_site to the place where the file being edited is. Eg. "fileadmin/static".
131 * @return void There is no output, it is set in internal variables. With the above example of "fileadmin/static" as input this will yield ->relPath to be "fileadmin/static/" and ->relBackPath to be "../../
132 * @todo Define visibility
133 */
134 public function setRelPath($path) {
135 $path = trim($path);
136 $path = preg_replace('/^\\//', '', $path);
137 $path = preg_replace('/\\/$/', '', $path);
138 if ($path) {
139 $this->relPath = $path;
140 $this->relBackPath = '';
141 $partsC = count(explode('/', $this->relPath));
142 for ($a = 0; $a < $partsC; $a++) {
143 $this->relBackPath .= '../';
144 }
145 $this->relPath .= '/';
146 }
147 }
148
149 /**
150 * Evaluate the environment for editing a staticFileEdit file.
151 * Called for almost all fields being saved in the database. Is called without
152 * an instance of \TYPO3\CMS\Core\Html\RteHtmlParser::evalWriteFile()
153 *
154 * @param array $pArr Parameters for the current field as found in types-config
155 * @param array $currentRecord Current record we are editing.
156 * @return mixed On success an array with various information is returned, otherwise a string with an error message
157 */
158 static public function evalWriteFile($pArr, $currentRecord) {
159 // Write file configuration:
160 if (is_array($pArr)) {
161 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['staticFileEditPath'] && substr($GLOBALS['TYPO3_CONF_VARS']['BE']['staticFileEditPath'], -1) == '/' && @is_dir((PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['staticFileEditPath']))) {
162 $SW_p = $pArr['parameters'];
163 $SW_editFileField = trim($SW_p[0]);
164 $SW_editFile = $currentRecord[$SW_editFileField];
165 if ($SW_editFileField && $SW_editFile && GeneralUtility::validPathStr($SW_editFile)) {
166 $SW_relpath = $GLOBALS['TYPO3_CONF_VARS']['BE']['staticFileEditPath'] . $SW_editFile;
167 $SW_editFile = PATH_site . $SW_relpath;
168 if (@is_file($SW_editFile)) {
169 return array(
170 'editFile' => $SW_editFile,
171 'relEditFile' => $SW_relpath,
172 'contentField' => trim($SW_p[1]),
173 'markerField' => trim($SW_p[2]),
174 'loadFromFileField' => trim($SW_p[3]),
175 'statusField' => trim($SW_p[4])
176 );
177 } else {
178 return 'ERROR: Editfile \'' . $SW_relpath . '\' did not exist';
179 }
180 } else {
181 return 'ERROR: Edit file name could not be found or was bad.';
182 }
183 } else {
184 return 'ERROR: staticFileEditPath was not set, not set correctly or did not exist!';
185 }
186 }
187 }
188
189 /**********************************************
190 *
191 * Main function
192 *
193 **********************************************/
194 /**
195 * Transform value for RTE based on specConf in the direction specified by $direction (rte/db)
196 * This is the main function called from tcemain and transfer data classes
197 *
198 * @param string Input value
199 * @param array Special configuration for a field; This is coming from the types-configuration of the field in the TCA. In the types-configuration you can setup features for the field rendering and in particular the RTE takes al its major configuration options from there!
200 * @param string Direction of the transformation. Two keywords are allowed; "db" or "rte". If "db" it means the transformation will clean up content coming from the Rich Text Editor and goes into the database. The other direction, "rte", is of course when content is coming from database and must be transformed to fit the RTE.
201 * @param array Parsed TypoScript content configuring the RTE, probably coming from Page TSconfig.
202 * @return string Output value
203 * @todo Define visibility
204 */
205 public function RTE_transform($value, $specConf, $direction = 'rte', $thisConfig = array()) {
206 // Init:
207 $this->tsConfig = $thisConfig;
208 $this->procOptions = (array) $thisConfig['proc.'];
209 $this->preserveTags = strtoupper(implode(',', GeneralUtility::trimExplode(',', $this->procOptions['preserveTags'])));
210 // dynamic configuration of blockElementList
211 if ($this->procOptions['blockElementList']) {
212 $this->blockElementList = $this->procOptions['blockElementList'];
213 }
214 // Get parameters for rte_transformation:
215 $p = ($this->rte_p = BackendUtility::getSpecConfParametersFromArray($specConf['rte_transform']['parameters']));
216 // Setting modes:
217 if ((string)$this->procOptions['overruleMode'] !== '') {
218 $modes = array_unique(GeneralUtility::trimExplode(',', $this->procOptions['overruleMode']));
219 } else {
220 $modes = array_unique(GeneralUtility::trimExplode('-', $p['mode']));
221 }
222 $revmodes = array_flip($modes);
223 // Find special modes and extract them:
224 if (isset($revmodes['ts'])) {
225 $modes[$revmodes['ts']] = 'ts_transform,ts_preserve,ts_images,ts_links';
226 }
227 // Find special modes and extract them:
228 if (isset($revmodes['ts_css'])) {
229 $modes[$revmodes['ts_css']] = 'css_transform,ts_images,ts_links';
230 }
231 // Make list unique
232 $modes = array_unique(GeneralUtility::trimExplode(',', implode(',', $modes), TRUE));
233 // Reverse order if direction is "rte"
234 if ($direction == 'rte') {
235 $modes = array_reverse($modes);
236 }
237 // Getting additional HTML cleaner configuration. These are applied either before or after the main transformation is done and is thus totally independant processing options you can set up:
238 $entry_HTMLparser = $this->procOptions['entryHTMLparser_' . $direction] ? $this->HTMLparserConfig($this->procOptions['entryHTMLparser_' . $direction . '.']) : '';
239 $exit_HTMLparser = $this->procOptions['exitHTMLparser_' . $direction] ? $this->HTMLparserConfig($this->procOptions['exitHTMLparser_' . $direction . '.']) : '';
240 // Line breaks of content is unified into char-10 only (removing char 13)
241 if (!$this->procOptions['disableUnifyLineBreaks']) {
242 $value = str_replace(CRLF, LF, $value);
243 }
244 // In an entry-cleaner was configured, pass value through the HTMLcleaner with that:
245 if (is_array($entry_HTMLparser)) {
246 $value = $this->HTMLcleaner($value, $entry_HTMLparser[0], $entry_HTMLparser[1], $entry_HTMLparser[2], $entry_HTMLparser[3]);
247 }
248 // Traverse modes:
249 foreach ($modes as $cmd) {
250 // ->DB
251 if ($direction == 'db') {
252 // Checking for user defined transformation:
253 if ($_classRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['transformation'][$cmd]) {
254 $_procObj = GeneralUtility::getUserObj($_classRef);
255 $_procObj->pObj = $this;
256 $_procObj->transformationKey = $cmd;
257 $value = $_procObj->transform_db($value, $this);
258 } else {
259 // ... else use defaults:
260 switch ($cmd) {
261 case 'ts_images':
262 $value = $this->TS_images_db($value);
263 break;
264 case 'ts_reglinks':
265 $value = $this->TS_reglinks($value, 'db');
266 break;
267 case 'ts_links':
268 $value = $this->TS_links_db($value);
269 break;
270 case 'ts_preserve':
271 $value = $this->TS_preserve_db($value);
272 break;
273 case 'ts_transform':
274
275 case 'css_transform':
276 $this->allowedClasses = GeneralUtility::trimExplode(',', $this->procOptions['allowedClasses'], TRUE);
277 // CR has a very disturbing effect, so just remove all CR and rely on LF
278 $value = str_replace(CR, '', $value);
279 // Transform empty paragraphs into spacing paragraphs
280 $value = str_replace('<p></p>', '<p>&nbsp;</p>', $value);
281 // Double any trailing spacing paragraph so that it does not get removed by divideIntoLines()
282 $value = preg_replace('/<p>&nbsp;<\/p>$/', '<p>&nbsp;</p>' . '<p>&nbsp;</p>', $value);
283 $value = $this->TS_transform_db($value, $cmd == 'css_transform');
284 break;
285 case 'ts_strip':
286 $value = $this->TS_strip_db($value);
287 break;
288 default:
289 // Do nothing
290 }
291 }
292 }
293 // ->RTE
294 if ($direction == 'rte') {
295 // Checking for user defined transformation:
296 if ($_classRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['transformation'][$cmd]) {
297 $_procObj = GeneralUtility::getUserObj($_classRef);
298 $_procObj->pObj = $this;
299 $value = $_procObj->transform_rte($value, $this);
300 } else {
301 // ... else use defaults:
302 switch ($cmd) {
303 case 'ts_images':
304 $value = $this->TS_images_rte($value);
305 break;
306 case 'ts_reglinks':
307 $value = $this->TS_reglinks($value, 'rte');
308 break;
309 case 'ts_links':
310 $value = $this->TS_links_rte($value);
311 break;
312 case 'ts_preserve':
313 $value = $this->TS_preserve_rte($value);
314 break;
315 case 'ts_transform':
316
317 case 'css_transform':
318 // Has a very disturbing effect, so just remove all '13' - depend on '10'
319 $value = str_replace(CR, '', $value);
320 $value = $this->TS_transform_rte($value, $cmd == 'css_transform');
321 break;
322 default:
323 // Do nothing
324 }
325 }
326 }
327 }
328 // In an exit-cleaner was configured, pass value through the HTMLcleaner with that:
329 if (is_array($exit_HTMLparser)) {
330 $value = $this->HTMLcleaner($value, $exit_HTMLparser[0], $exit_HTMLparser[1], $exit_HTMLparser[2], $exit_HTMLparser[3]);
331 }
332 // Final clean up of linebreaks:
333 if (!$this->procOptions['disableUnifyLineBreaks']) {
334 // Make sure no \r\n sequences has entered in the meantime...
335 $value = str_replace(CRLF, LF, $value);
336 // ... and then change all \n into \r\n
337 $value = str_replace(LF, CRLF, $value);
338 }
339 // Return value:
340 return $value;
341 }
342
343 /************************************
344 *
345 * Specific RTE TRANSFORMATION functions
346 *
347 *************************************/
348 /**
349 * Transformation handler: 'ts_images' / direction: "db"
350 * Processing images inserted in the RTE.
351 * This is used when content goes from the RTE to the database.
352 * Images inserted in the RTE has an absolute URL applied to the src attribute. This URL is converted to a relative URL
353 * If it turns out that the URL is from another website than the current the image is read from that external URL and moved to the local server.
354 * Also "magic" images are processed here.
355 *
356 * @param string $value The content from RTE going to Database
357 * @return string Processed content
358 * @todo Define visibility
359 */
360 public function TS_images_db($value) {
361 // Split content by <img> tags and traverse the resulting array for processing:
362 $imgSplit = $this->splitTags('img', $value);
363 if (count($imgSplit) > 1) {
364 $siteUrl = $this->siteUrl();
365 $sitePath = str_replace(GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST'), '', $siteUrl);
366 /** @var $resourceFactory Resource\ResourceFactory */
367 $resourceFactory = Resource\ResourceFactory::getInstance();
368 /** @var $magicImageService Resource\Service\MagicImageService */
369 $magicImageService = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Service\\MagicImageService');
370 $magicImageService->setMagicImageMaximumDimensions($this->tsConfig);
371 foreach ($imgSplit as $k => $v) {
372 // Image found, do processing:
373 if ($k % 2) {
374 // Get attributes
375 $attribArray = $this->get_tag_attributes_classic($v, 1);
376 // It's always an absolute URL coming from the RTE into the Database.
377 $absoluteUrl = trim($attribArray['src']);
378 // Make path absolute if it is relative and we have a site path which is not '/'
379 $pI = pathinfo($absoluteUrl);
380 if ($sitePath && !$pI['scheme'] && GeneralUtility::isFirstPartOfStr($absoluteUrl, $sitePath)) {
381 // If site is in a subpath (eg. /~user_jim/) this path needs to be removed because it will be added with $siteUrl
382 $absoluteUrl = substr($absoluteUrl, strlen($sitePath));
383 $absoluteUrl = $siteUrl . $absoluteUrl;
384 }
385 // Image dimensions set in the img tag, if any
386 $imgTagDimensions = $this->getWHFromAttribs($attribArray);
387 if ($imgTagDimensions[0]) {
388 $attribArray['width'] = $imgTagDimensions[0];
389 }
390 if ($imgTagDimensions[1]) {
391 $attribArray['height'] = $imgTagDimensions[1];
392 }
393 $originalImageFile = NULL;
394 if ($attribArray['data-htmlarea-file-uid']) {
395 // An original image file uid is available
396 try {
397 /** @var $originalImageFile Resource\File */
398 $originalImageFile = $resourceFactory->getFileObject(intval($attribArray['data-htmlarea-file-uid']));
399 } catch (Resource\Exception\FileDoesNotExistException $fileDoesNotExistException) {
400 // Log the fact the file could not be retrieved.
401 $message = sprintf('Could not find file with uid "%s"', $attribArray['data-htmlarea-file-uid']);
402 $this->getLogger()->error($message);
403 }
404 }
405 if ($originalImageFile instanceof Resource\File) {
406 // Public url of local file is relative to the site url, absolute otherwise
407 if ($absoluteUrl == $originalImageFile->getPublicUrl() || $absoluteUrl == $siteUrl . $originalImageFile->getPublicUrl()) {
408 // This is a plain image, i.e. reference to the original image
409 if ($this->procOptions['plainImageMode']) {
410 // "plain image mode" is configured
411 // Find the dimensions of the original image
412 $imageInfo = array(
413 $originalImageFile->getProperty('width'),
414 $originalImageFile->getProperty('height')
415 );
416 if (!$imageInfo[0] || !$imageInfo[1]) {
417 $filePath = $originalImageFile->getForLocalProcessing(FALSE);
418 $imageInfo = @getimagesize($filePath);
419 }
420 $attribArray = $this->applyPlainImageModeSettings($imageInfo, $attribArray);
421 }
422 } else {
423 // Magic image case: get a processed file with the requested configuration
424 $imageConfiguration = array(
425 'width' => $imgTagDimensions[0],
426 'height' => $imgTagDimensions[1]
427 );
428 $magicImage = $magicImageService->createMagicImage($originalImageFile, $imageConfiguration);
429 $attribArray['width'] = $magicImage->getProperty('width');
430 $attribArray['height'] = $magicImage->getProperty('height');
431 $attribArray['src'] = $magicImage->getPublicUrl();
432 }
433 } elseif (!GeneralUtility::isFirstPartOfStr($absoluteUrl, $siteUrl) && !$this->procOptions['dontFetchExtPictures'] && TYPO3_MODE === 'BE') {
434 // External image from another URL: in that case, fetch image, unless the feature is disabled or we are not in backend mode
435 // Fetch the external image
436 $externalFile = $this->getUrl($absoluteUrl);
437 if ($externalFile) {
438 $pU = parse_url($absoluteUrl);
439 $pI = pathinfo($pU['path']);
440 if (GeneralUtility::inList('gif,png,jpeg,jpg', strtolower($pI['extension']))) {
441 $fileName = GeneralUtility::shortMD5($absoluteUrl) . '.' . $pI['extension'];
442 // We insert this image into the user default upload folder
443 $folder = $GLOBALS['BE_USER']->getDefaultUploadFolder();
444 $fileObject = $folder->createFile($fileName)->setContents($externalFile);
445 $imageConfiguration = array(
446 'width' => $attribArray['width'],
447 'height' => $attribArray['height']
448 );
449 $magicImage = $magicImageService->createMagicImage($fileObject, $imageConfiguration);
450 $attribArray['width'] = $magicImage->getProperty('width');
451 $attribArray['height'] = $magicImage->getProperty('height');
452 $attribArray['data-htmlarea-file-uid'] = $fileObject->getUid();
453 $attribArray['data-htmlarea-file-table'] = 'sys_file';
454 $attribArray['src'] = $magicImage->getPublicUrl();
455 }
456 }
457 } elseif (GeneralUtility::isFirstPartOfStr($absoluteUrl, $siteUrl)) {
458 // Finally, check image as local file (siteURL equals the one of the image)
459 // Image has no data-htmlarea-file-uid attribute
460 // Relative path, rawurldecoded for special characters.
461 $path = rawurldecode(substr($absoluteUrl, strlen($siteUrl)));
462 // Absolute filepath, locked to relative path of this project
463 $filepath = GeneralUtility::getFileAbsFileName($path);
464 // Check file existence (in relative directory to this installation!)
465 if ($filepath && @is_file($filepath)) {
466 // Treat it as a plain image
467 if ($this->procOptions['plainImageMode']) {
468 // If "plain image mode" has been configured
469 // Find the original dimensions of the image
470 $imageInfo = @getimagesize($filePath);
471 $attribArray = $this->applyPlainImageModeSettings($imageInfo, $attribArray);
472 }
473 // Let's try to find a file uid for this image
474 try {
475 $fileOrFolderObject = $resourceFactory->retrieveFileOrFolderObject($path);
476 if ($fileOrFolderObject instanceof Resource\FileInterface) {
477 $fileIdentifier = $fileOrFolderObject->getIdentifier();
478 $fileObject = $fileOrFolderObject->getStorage()->getFile($fileIdentifier);
479 // TODO: if the retrieved file is a processed file, get the original file...
480 $attribArray['data-htmlarea-file-uid'] = $fileObject->getUid();
481 $attribArray['data-htmlarea-file-table'] = 'sys_file';
482 }
483 } catch (Resource\Exception\ResourceDoesNotExistException $resourceDoesNotExistException) {
484 // Nothing to be done if file/folder not found
485 }
486 }
487 }
488 // Remove width and heigth from style attribute
489 $attribArray['style'] = preg_replace('/((?:^|)\\s*(?:width|height)\\s*:[^;]*(?:$|;))/si', '', $attribArray['style']);
490 // Must have alt attribute
491 if (!isset($attribArray['alt'])) {
492 $attribArray['alt'] = '';
493 }
494 // Convert absolute to relative url
495 if (GeneralUtility::isFirstPartOfStr($attribArray['src'], $siteUrl)) {
496 $attribArray['src'] = $this->relBackPath . substr($attribArray['src'], strlen($siteUrl));
497 }
498 $imgSplit[$k] = '<img ' . GeneralUtility::implodeAttributes($attribArray, 1, 1) . ' />';
499 }
500 }
501 }
502 return implode('', $imgSplit);
503 }
504
505 /**
506 * Transformation handler: 'ts_images' / direction: "rte"
507 * Processing images from database content going into the RTE.
508 * Processing includes converting the src attribute to an absolute URL.
509 *
510 * @param string $value Content input
511 * @return string Content output
512 */
513 public function TS_images_rte($value) {
514 // Split content by <img> tags and traverse the resulting array for processing:
515 $imgSplit = $this->splitTags('img', $value);
516 if (count($imgSplit) > 1) {
517 $siteUrl = $this->siteUrl();
518 $sitePath = str_replace(GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST'), '', $siteUrl);
519 foreach ($imgSplit as $k => $v) {
520 // Image found
521 if ($k % 2) {
522 // Get the attributes of the img tag
523 $attribArray = $this->get_tag_attributes_classic($v, 1);
524 $absoluteUrl = trim($attribArray['src']);
525 // Transform the src attribute into an absolute url, if it not already
526 if (strtolower(substr($absoluteUrl, 0, 4)) !== 'http') {
527 $attribArray['src'] = substr($attribArray['src'], strlen($this->relBackPath));
528 // If site is in a subpath (eg. /~user_jim/) this path needs to be removed because it will be added with $siteUrl
529 $attribArray['src'] = preg_replace('#^' . preg_quote($sitePath, '#') . '#', '', $attribArray['src']);
530 $attribArray['src'] = $siteUrl . $attribArray['src'];
531 }
532 // Must have alt attribute
533 if (!isset($attribArray['alt'])) {
534 $attribArray['alt'] = '';
535 }
536 $imgSplit[$k] = '<img ' . GeneralUtility::implodeAttributes($attribArray, 1, 1) . ' />';
537 }
538 }
539 }
540 // Return processed content:
541 return implode('', $imgSplit);
542 }
543
544 /**
545 * Transformation handler: 'ts_reglinks' / direction: "db"+"rte" depending on $direction variable.
546 * Converting <A>-tags to/from abs/rel
547 *
548 * @param string $value Content input
549 * @param string $direction Direction of conversion; "rte" (from database to RTE) or "db" (from RTE to database)
550 * @return string Content output
551 * @todo Define visibility
552 */
553 public function TS_reglinks($value, $direction) {
554 $retVal = '';
555 switch ($direction) {
556 case 'rte':
557 $retVal = $this->TS_AtagToAbs($value, 1);
558 break;
559 case 'db':
560 $siteURL = $this->siteUrl();
561 $blockSplit = $this->splitIntoBlock('A', $value);
562 foreach ($blockSplit as $k => $v) {
563 // Block
564 if ($k % 2) {
565 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v), 1);
566 // If the url is local, remove url-prefix
567 if ($siteURL && substr($attribArray['href'], 0, strlen($siteURL)) == $siteURL) {
568 $attribArray['href'] = $this->relBackPath . substr($attribArray['href'], strlen($siteURL));
569 }
570 $bTag = '<a ' . GeneralUtility::implodeAttributes($attribArray, 1) . '>';
571 $eTag = '</a>';
572 $blockSplit[$k] = $bTag . $this->TS_reglinks($this->removeFirstAndLastTag($blockSplit[$k]), $direction) . $eTag;
573 }
574 }
575 $retVal = implode('', $blockSplit);
576 break;
577 }
578 return $retVal;
579 }
580
581 /**
582 * Transformation handler: 'ts_links' / direction: "db"
583 * Converting <A>-tags to <link tags>
584 *
585 * @param string $value Content input
586 * @return string Content output
587 * @see TS_links_rte()
588 * @todo Define visibility
589 */
590 public function TS_links_db($value) {
591 $conf = array();
592 // Split content into <a> tag blocks and process:
593 $blockSplit = $this->splitIntoBlock('A', $value);
594 foreach ($blockSplit as $k => $v) {
595 // If an A-tag was found:
596 if ($k % 2) {
597 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v), 1);
598 $info = $this->urlInfoForLinkTags($attribArray['href']);
599 // Check options:
600 $attribArray_copy = $attribArray;
601 unset($attribArray_copy['href']);
602 unset($attribArray_copy['target']);
603 unset($attribArray_copy['class']);
604 unset($attribArray_copy['title']);
605 unset($attribArray_copy['data-htmlarea-external']);
606 // Unset "rteerror" and "style" attributes if "rteerror" is set!
607 if ($attribArray_copy['rteerror']) {
608 unset($attribArray_copy['style']);
609 unset($attribArray_copy['rteerror']);
610 }
611 // Remove additional parameters
612 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['removeParams_PostProc']) && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['removeParams_PostProc'])) {
613 $parameters = array(
614 'conf' => &$conf,
615 'aTagParams' => &$attribArray_copy
616 );
617 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['removeParams_PostProc'] as $objRef) {
618 $processor = GeneralUtility::getUserObj($objRef);
619 $attribArray_copy = $processor->removeParams($parameters, $this);
620 }
621 }
622 // Only if href, target, class and tile are the only attributes, we can alter the link!
623 if (!count($attribArray_copy)) {
624 // Quoting class and title attributes if they contain spaces
625 $attribArray['class'] = preg_match('/ /', $attribArray['class']) ? '"' . $attribArray['class'] . '"' : $attribArray['class'];
626 $attribArray['title'] = preg_match('/ /', $attribArray['title']) ? '"' . $attribArray['title'] . '"' : $attribArray['title'];
627 // Creating the TYPO3 pseudo-tag "<LINK>" for the link (includes href/url, target and class attributes):
628 // If data-htmlarea-external attribute is set, keep the href unchanged
629 if ($attribArray['data-htmlarea-external']) {
630 $href = $attribArray['href'];
631 } else {
632 $href = $info['url'] . ($info['query'] ? ',0,' . $info['query'] : '');
633 }
634 $bTag = '<link ' . $href . ($attribArray['target'] ? ' ' . $attribArray['target'] : ($attribArray['class'] || $attribArray['title'] ? ' -' : '')) . ($attribArray['class'] ? ' ' . $attribArray['class'] : ($attribArray['title'] ? ' -' : '')) . ($attribArray['title'] ? ' ' . $attribArray['title'] : '') . '>';
635 $eTag = '</link>';
636 // Modify parameters
637 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksDb_PostProc']) && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksDb_PostProc'])) {
638 $parameters = array(
639 'conf' => &$conf,
640 'currentBlock' => $v,
641 'url' => $href,
642 'attributes' => $attribArray
643 );
644 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksDb_PostProc'] as $objRef) {
645 $processor = GeneralUtility::getUserObj($objRef);
646 $blockSplit[$k] = $processor->modifyParamsLinksDb($parameters, $this);
647 }
648 } else {
649 $blockSplit[$k] = $bTag . $this->TS_links_db($this->removeFirstAndLastTag($blockSplit[$k])) . $eTag;
650 }
651 } else {
652 // ... otherwise store the link as a-tag.
653 // Unsetting 'rtekeep' attribute if that had been set.
654 unset($attribArray['rtekeep']);
655 if (!$attribArray['data-htmlarea-external']) {
656 $siteURL = $this->siteUrl();
657 // If the url is local, remove url-prefix
658 if ($siteURL && substr($attribArray['href'], 0, strlen($siteURL)) == $siteURL) {
659 $attribArray['href'] = $this->relBackPath . substr($attribArray['href'], strlen($siteURL));
660 }
661 // Check for FAL link-handler keyword
662 list($linkHandlerKeyword, $linkHandlerValue) = explode(':', $attribArray['href'], 2);
663 if ($linkHandlerKeyword === '?file') {
664 try {
665 $fileOrFolderObject = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->retrieveFileOrFolderObject(rawurldecode($linkHandlerValue));
666 if ($fileOrFolderObject instanceof \TYPO3\CMS\Core\Resource\FileInterface || $fileOrFolderObject instanceof \TYPO3\CMS\Core\Resource\Folder) {
667 $attribArray['href'] = $fileOrFolderObject->getPublicUrl();
668 }
669 } catch (\TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException $resourceDoesNotExistException) {
670 // The indentifier inserted in the RTE is already gone...
671 }
672 }
673 }
674 unset($attribArray['data-htmlarea-external']);
675 $bTag = '<a ' . GeneralUtility::implodeAttributes($attribArray, 1) . '>';
676 $eTag = '</a>';
677 $blockSplit[$k] = $bTag . $this->TS_links_db($this->removeFirstAndLastTag($blockSplit[$k])) . $eTag;
678 }
679 }
680 }
681 return implode('', $blockSplit);
682 }
683
684 /**
685 * Transformation handler: 'ts_links' / direction: "rte"
686 * Converting <link tags> to <A>-tags
687 *
688 * @param string $value Content input
689 * @return string Content output
690 * @see TS_links_rte()
691 * @todo Define visibility
692 */
693 public function TS_links_rte($value) {
694 $conf = array();
695 $value = $this->TS_AtagToAbs($value);
696 // Split content by the TYPO3 pseudo tag "<link>":
697 $blockSplit = $this->splitIntoBlock('link', $value, 1);
698 $siteUrl = $this->siteUrl();
699 foreach ($blockSplit as $k => $v) {
700 $error = '';
701 $external = FALSE;
702 // Block
703 if ($k % 2) {
704 $tagCode = GeneralUtility::unQuoteFilenames(trim(substr($this->getFirstTag($v), 0, -1)), TRUE);
705 $link_param = $tagCode[1];
706 $href = '';
707 // Parsing the typolink data. This parsing is roughly done like in tslib_content->typolink()
708 // Parse URL:
709 $pU = parse_url($link_param);
710 if (strstr($link_param, '@') && (!$pU['scheme'] || $pU['scheme'] == 'mailto')) {
711 // mailadr
712 $href = 'mailto:' . preg_replace('/^mailto:/i', '', $link_param);
713 } elseif ($link_param[0] === '#') {
714 // check if anchor
715 $href = $siteUrl . $link_param;
716 } else {
717 // Check for FAL link-handler keyword:
718 list($linkHandlerKeyword, $linkHandlerValue) = explode(':', trim($link_param), 2);
719 if ($linkHandlerKeyword === 'file') {
720 $href = $siteUrl . '?' . $linkHandlerKeyword . ':' . rawurlencode($linkHandlerValue);
721 } else {
722 $fileChar = (int)strpos($link_param, '/');
723 $urlChar = (int)strpos($link_param, '.');
724 // Detects if a file is found in site-root.
725 list($rootFileDat) = explode('?', $link_param);
726 $rFD_fI = pathinfo($rootFileDat);
727 if (trim($rootFileDat) && !strstr($link_param, '/') && (@is_file((PATH_site . $rootFileDat)) || GeneralUtility::inList('php,html,htm', strtolower($rFD_fI['extension'])))) {
728 $href = $siteUrl . $link_param;
729 } elseif ($pU['scheme'] || $urlChar && (!$fileChar || $urlChar < $fileChar)) {
730 // url (external): if has scheme or if a '.' comes before a '/'.
731 $href = $link_param;
732 if (!$pU['scheme']) {
733 $href = 'http://' . $href;
734 }
735 $external = TRUE;
736 } elseif ($fileChar) {
737 // It is an internal file or folder
738 // Try to transform the href into a FAL reference
739 try {
740 $fileOrFolderObject = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance()->retrieveFileOrFolderObject($link_param);
741 } catch (\TYPO3\CMS\Core\Resource\Exception\FolderDoesNotExistException $notFoundException) {
742 // Nothing to be done if file/folder not found
743 }
744 if ($fileOrFolderObject instanceof \TYPO3\CMS\Core\Resource\Folder) {
745 // It's a folder
746 $folderIdentifier = $fileOrFolderObject->getIdentifier();
747 $href = $siteUrl . '?file:' . rawurlencode($folderIdentifier);
748 } elseif ($fileOrFolderObject instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
749 // It's a file
750 $fileIdentifier = $fileOrFolderObject->getIdentifier();
751 $fileObject = $fileOrFolderObject->getStorage()->getFile($fileIdentifier);
752 $href = $siteUrl . '?file:' . $fileObject->getUid();
753 } else {
754 $href = $siteUrl . $link_param;
755 }
756 } else {
757 // integer or alias (alias is without slashes or periods or commas, that is 'nospace,alphanum_x,lower,unique' according to tables.php!!)
758 // Splitting the parameter by ',' and if the array counts more than 1 element it's a id/type/parameters triplet
759 $pairParts = GeneralUtility::trimExplode(',', $link_param, TRUE);
760 $idPart = $pairParts[0];
761 $link_params_parts = explode('#', $idPart);
762 $idPart = trim($link_params_parts[0]);
763 $sectionMark = trim($link_params_parts[1]);
764 if ((string)$idPart === '') {
765 $idPart = $this->recPid;
766 }
767 // If no id or alias is given, set it to class record pid
768 // Checking if the id-parameter is an alias.
769 if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($idPart)) {
770 list($idPartR) = BackendUtility::getRecordsByField('pages', 'alias', $idPart);
771 $idPart = (int)$idPartR['uid'];
772 }
773 $page = BackendUtility::getRecord('pages', $idPart);
774 if (is_array($page)) {
775 // Page must exist...
776 $href = $siteUrl . '?id=' . $idPart . ($pairParts[2] ? $pairParts[2] : '') . ($sectionMark ? '#' . $sectionMark : '');
777 } elseif (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['typolinkLinkHandler'][array_shift(explode(':', $link_param))])) {
778 $href = $link_param;
779 } else {
780 $href = $siteUrl . '?id=' . $link_param;
781 $error = 'No page found: ' . $idPart;
782 }
783 }
784 }
785 }
786 // Setting the A-tag:
787 $bTag = '<a href="' . htmlspecialchars($href) . '"' . ($tagCode[2] && $tagCode[2] != '-' ? ' target="' . htmlspecialchars($tagCode[2]) . '"' : '') . ($tagCode[3] && $tagCode[3] != '-' ? ' class="' . htmlspecialchars($tagCode[3]) . '"' : '') . ($tagCode[4] ? ' title="' . htmlspecialchars($tagCode[4]) . '"' : '') . ($external ? ' data-htmlarea-external="1"' : '') . ($error ? ' rteerror="' . htmlspecialchars($error) . '" style="background-color: yellow; border:2px red solid; color: black;"' : '') . '>';
788 $eTag = '</a>';
789 // Modify parameters
790 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksRte_PostProc']) && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksRte_PostProc'])) {
791 $parameters = array(
792 'conf' => &$conf,
793 'currentBlock' => $v,
794 'url' => $href,
795 'tagCode' => $tagCode,
796 'external' => $external,
797 'error' => $error
798 );
799 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksRte_PostProc'] as $objRef) {
800 $processor = GeneralUtility::getUserObj($objRef);
801 $blockSplit[$k] = $processor->modifyParamsLinksRte($parameters, $this);
802 }
803 } else {
804 $blockSplit[$k] = $bTag . $this->TS_links_rte($this->removeFirstAndLastTag($blockSplit[$k])) . $eTag;
805 }
806 }
807 }
808 // Return content:
809 return implode('', $blockSplit);
810 }
811
812 /**
813 * Preserve special tags
814 *
815 * @param string $value Content input
816 * @return string Content output
817 * @todo Define visibility
818 */
819 public function TS_preserve_db($value) {
820 if (!$this->preserveTags) {
821 return $value;
822 }
823 // Splitting into blocks for processing (span-tags are used for special tags)
824 $blockSplit = $this->splitIntoBlock('span', $value);
825 foreach ($blockSplit as $k => $v) {
826 // Block
827 if ($k % 2) {
828 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v));
829 if ($attribArray['specialtag']) {
830 $theTag = rawurldecode($attribArray['specialtag']);
831 $theTagName = $this->getFirstTagName($theTag);
832 $blockSplit[$k] = $theTag . $this->removeFirstAndLastTag($blockSplit[$k]) . '</' . $theTagName . '>';
833 }
834 }
835 }
836 return implode('', $blockSplit);
837 }
838
839 /**
840 * Preserve special tags
841 *
842 * @param string $value Content input
843 * @return string Content output
844 * @todo Define visibility
845 */
846 public function TS_preserve_rte($value) {
847 if (!$this->preserveTags) {
848 return $value;
849 }
850 $blockSplit = $this->splitIntoBlock($this->preserveTags, $value);
851 foreach ($blockSplit as $k => $v) {
852 // Block
853 if ($k % 2) {
854 $blockSplit[$k] = '<span specialtag="' . rawurlencode($this->getFirstTag($v)) . '">' . $this->removeFirstAndLastTag($blockSplit[$k]) . '</span>';
855 }
856 }
857 return implode('', $blockSplit);
858 }
859
860 /**
861 * Transformation handler: 'ts_transform' + 'css_transform' / direction: "db"
862 * Cleaning (->db) for standard content elements (ts)
863 *
864 * @param string $value Content input
865 * @param boolean $css If TRUE, the transformation was "css_transform", otherwise "ts_transform
866 * @return string Content output
867 * @see TS_transform_rte()
868 * @todo Define visibility
869 */
870 public function TS_transform_db($value, $css = FALSE) {
871 // Safety... so forever loops are avoided (they should not occur, but an error would potentially do this...)
872 $this->TS_transform_db_safecounter--;
873 if ($this->TS_transform_db_safecounter < 0) {
874 return $value;
875 }
876 // Split the content from RTE by the occurence of these blocks:
877 $blockSplit = $this->splitIntoBlock('TABLE,BLOCKQUOTE,' . ($this->procOptions['preserveDIVSections'] ? 'DIV,' : '') . $this->blockElementList, $value);
878 $cc = 0;
879 $aC = count($blockSplit);
880 // Avoid superfluous linebreaks by transform_db after ending headListTag
881 while ($aC && trim($blockSplit[($aC - 1)]) === '') {
882 unset($blockSplit[$aC - 1]);
883 $aC = count($blockSplit);
884 }
885 // Traverse the blocks
886 foreach ($blockSplit as $k => $v) {
887 $cc++;
888 $lastBR = $cc == $aC ? '' : LF;
889 if ($k % 2) {
890 // Inside block:
891 // Init:
892 $tag = $this->getFirstTag($v);
893 $tagName = strtolower($this->getFirstTagName($v));
894 // Process based on the tag:
895 switch ($tagName) {
896 case 'blockquote':
897
898 case 'dd':
899
900 case 'div':
901
902 case 'header':
903
904 case 'section':
905
906 case 'footer':
907
908 case 'nav':
909
910 case 'article':
911
912 case 'aside':
913 $blockSplit[$k] = $tag . $this->TS_transform_db($this->removeFirstAndLastTag($blockSplit[$k]), $css) . '</' . $tagName . '>' . $lastBR;
914 break;
915 case 'ol':
916
917 case 'ul':
918 // Transform lists into <typolist>-tags:
919 if (!$css) {
920 if (!isset($this->procOptions['typolist']) || $this->procOptions['typolist']) {
921 $parts = $this->getAllParts($this->splitIntoBlock('LI', $this->removeFirstAndLastTag($blockSplit[$k])), 1, 0);
922 foreach ($parts as $k2 => $value) {
923 $parts[$k2] = preg_replace('/[' . LF . CR . ']+/', '', $parts[$k2]);
924 // remove all linesbreaks!
925 $parts[$k2] = $this->defaultTStagMapping($parts[$k2], 'db');
926 $parts[$k2] = $this->cleanFontTags($parts[$k2], 0, 0, 0);
927 $parts[$k2] = $this->HTMLcleaner_db($parts[$k2], strtolower($this->procOptions['allowTagsInTypolists'] ? $this->procOptions['allowTagsInTypolists'] : 'br,font,b,i,u,a,img,span,strong,em'));
928 }
929 if ($tagName == 'ol') {
930 $params = ' type="1"';
931 } else {
932 $params = '';
933 }
934 $blockSplit[$k] = '<typolist' . $params . '>' . LF . implode(LF, $parts) . LF . '</typolist>' . $lastBR;
935 }
936 } else {
937 $blockSplit[$k] = preg_replace(('/[' . LF . CR . ']+/'), ' ', $this->transformStyledATags($blockSplit[$k])) . $lastBR;
938 }
939 break;
940 case 'table':
941 // Tables are NOT allowed in any form (unless preserveTables is set or CSS is the mode)
942 if (!$this->procOptions['preserveTables'] && !$css) {
943 $blockSplit[$k] = $this->TS_transform_db($this->removeTables($blockSplit[$k]));
944 } else {
945 $blockSplit[$k] = preg_replace(('/[' . LF . CR . ']+/'), ' ', $this->transformStyledATags($blockSplit[$k])) . $lastBR;
946 }
947 break;
948 case 'h1':
949
950 case 'h2':
951
952 case 'h3':
953
954 case 'h4':
955
956 case 'h5':
957
958 case 'h6':
959 if (!$css) {
960 $attribArray = $this->get_tag_attributes_classic($tag);
961 // Processing inner content here:
962 $innerContent = $this->HTMLcleaner_db($this->removeFirstAndLastTag($blockSplit[$k]));
963 if (!isset($this->procOptions['typohead']) || $this->procOptions['typohead']) {
964 $type = (int)substr($tagName, 1);
965 $blockSplit[$k] = '<typohead' . ($type != 6 ? ' type="' . $type . '"' : '') . ($attribArray['align'] ? ' align="' . $attribArray['align'] . '"' : '') . ($attribArray['class'] ? ' class="' . $attribArray['class'] . '"' : '') . '>' . $innerContent . '</typohead>' . $lastBR;
966 } else {
967 $blockSplit[$k] = '<' . $tagName . ($attribArray['align'] ? ' align="' . htmlspecialchars($attribArray['align']) . '"' : '') . ($attribArray['class'] ? ' class="' . htmlspecialchars($attribArray['class']) . '"' : '') . '>' . $innerContent . '</' . $tagName . '>' . $lastBR;
968 }
969 } else {
970 // Eliminate true linebreaks inside Hx tags
971 $blockSplit[$k] = preg_replace(('/[' . LF . CR . ']+/'), ' ', $this->transformStyledATags($blockSplit[$k])) . $lastBR;
972 }
973 break;
974 default:
975 // Eliminate true linebreaks inside other headlist tags
976 $blockSplit[$k] = preg_replace(('/[' . LF . CR . ']+/'), ' ', $this->transformStyledATags($blockSplit[$k])) . $lastBR;
977 }
978 } else {
979 // NON-block:
980 if (trim($blockSplit[$k]) !== '') {
981 $blockSplit[$k] = preg_replace('/<hr\\/>/', '<hr />', $blockSplit[$k]);
982 // Remove linebreaks preceding hr tags
983 $blockSplit[$k] = preg_replace('/[' . LF . CR . ']+<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/', '<$1$2/>', $blockSplit[$k]);
984 // Remove linebreaks following hr tags
985 $blockSplit[$k] = preg_replace('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>[' . LF . CR . ']+/', '<$1$2/>', $blockSplit[$k]);
986 // Replace other linebreaks with space
987 $blockSplit[$k] = preg_replace('/[' . LF . CR . ']+/', ' ', $blockSplit[$k]);
988 $blockSplit[$k] = $this->divideIntoLines($blockSplit[$k]) . $lastBR;
989 $blockSplit[$k] = $this->transformStyledATags($blockSplit[$k]);
990 } else {
991 unset($blockSplit[$k]);
992 }
993 }
994 }
995 $this->TS_transform_db_safecounter++;
996 return implode('', $blockSplit);
997 }
998
999 /**
1000 * Wraps a-tags that contain a style attribute with a span-tag
1001 *
1002 * @param string $value Content input
1003 * @return string Content output
1004 * @todo Define visibility
1005 */
1006 public function transformStyledATags($value) {
1007 $blockSplit = $this->splitIntoBlock('A', $value);
1008 foreach ($blockSplit as $k => $v) {
1009 // If an A-tag was found
1010 if ($k % 2) {
1011 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v), 1);
1012 // If "style" attribute is set and rteerror is not set!
1013 if ($attribArray['style'] && !$attribArray['rteerror']) {
1014 $attribArray_copy['style'] = $attribArray['style'];
1015 unset($attribArray['style']);
1016 $bTag = '<span ' . GeneralUtility::implodeAttributes($attribArray_copy, 1) . '><a ' . GeneralUtility::implodeAttributes($attribArray, 1) . '>';
1017 $eTag = '</a></span>';
1018 $blockSplit[$k] = $bTag . $this->removeFirstAndLastTag($blockSplit[$k]) . $eTag;
1019 }
1020 }
1021 }
1022 return implode('', $blockSplit);
1023 }
1024
1025 /**
1026 * Transformation handler: 'ts_transform' + 'css_transform' / direction: "rte"
1027 * Set (->rte) for standard content elements (ts)
1028 *
1029 * @param string Content input
1030 * @param boolean If TRUE, the transformation was "css_transform", otherwise "ts_transform
1031 * @return string Content output
1032 * @see TS_transform_db()
1033 * @todo Define visibility
1034 */
1035 public function TS_transform_rte($value, $css = 0) {
1036 // Split the content from database by the occurence of the block elements
1037 $blockElementList = 'TABLE,BLOCKQUOTE,TYPOLIST,TYPOHEAD,' . ($this->procOptions['preserveDIVSections'] ? 'DIV,' : '') . $this->blockElementList;
1038 $blockSplit = $this->splitIntoBlock($blockElementList, $value);
1039 // Traverse the blocks
1040 foreach ($blockSplit as $k => $v) {
1041 if ($k % 2) {
1042 // Inside one of the blocks:
1043 // Init:
1044 $tag = $this->getFirstTag($v);
1045 $tagName = strtolower($this->getFirstTagName($v));
1046 $attribArray = $this->get_tag_attributes_classic($tag);
1047 // Based on tagname, we do transformations:
1048 switch ($tagName) {
1049 case 'blockquote':
1050
1051 case 'dd':
1052
1053 case 'div':
1054
1055 case 'header':
1056
1057 case 'section':
1058
1059 case 'footer':
1060
1061 case 'nav':
1062
1063 case 'article':
1064
1065 case 'aside':
1066 $blockSplit[$k] = $tag . $this->TS_transform_rte($this->removeFirstAndLastTag($blockSplit[$k]), $css) . '</' . $tagName . '>';
1067 break;
1068 case 'typolist':
1069 // Transform typolist blocks into OL/UL lists. Type 1 is expected to be numerical block
1070 if (!isset($this->procOptions['typolist']) || $this->procOptions['typolist']) {
1071 $tListContent = $this->removeFirstAndLastTag($blockSplit[$k]);
1072 $tListContent = preg_replace('/^[ ]*' . LF . '/', '', $tListContent);
1073 $tListContent = preg_replace('/' . LF . '[ ]*$/', '', $tListContent);
1074 $lines = explode(LF, $tListContent);
1075 $typ = $attribArray['type'] == 1 ? 'ol' : 'ul';
1076 $blockSplit[$k] = '<' . $typ . '>' . LF . '<li>' . implode(('</li>' . LF . '<li>'), $lines) . '</li>' . '</' . $typ . '>';
1077 }
1078 break;
1079 case 'typohead':
1080 // Transform typohead into Hx tags.
1081 if (!isset($this->procOptions['typohead']) || $this->procOptions['typohead']) {
1082 $tC = $this->removeFirstAndLastTag($blockSplit[$k]);
1083 $typ = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($attribArray['type'], 0, 6);
1084 if (!$typ) {
1085 $typ = 6;
1086 }
1087 $align = $attribArray['align'] ? ' align="' . $attribArray['align'] . '"' : '';
1088 $class = $attribArray['class'] ? ' class="' . $attribArray['class'] . '"' : '';
1089 $blockSplit[$k] = '<h' . $typ . $align . $class . '>' . $tC . '</h' . $typ . '>';
1090 }
1091 break;
1092 }
1093 $blockSplit[$k + 1] = preg_replace('/^[ ]*' . LF . '/', '', $blockSplit[$k + 1]);
1094 } else {
1095 // NON-block:
1096 $nextFTN = $this->getFirstTagName($blockSplit[$k + 1]);
1097 $onlyLineBreaks = (preg_match('/^[ ]*' . LF . '+[ ]*$/', $blockSplit[$k]) == 1);
1098 // If the line is followed by a block or is the last line:
1099 if (GeneralUtility::inList($blockElementList, $nextFTN) || !isset($blockSplit[$k + 1])) {
1100 // If the line contains more than just linebreaks, reduce the number of trailing linebreaks by 1
1101 if (!$onlyLineBreaks) {
1102 $blockSplit[$k] = preg_replace('/(' . LF . '*)' . LF . '[ ]*$/', '$1', $blockSplit[$k]);
1103 } else {
1104 // If the line contains only linebreaks, remove the leading linebreak
1105 $blockSplit[$k] = preg_replace('/^[ ]*' . LF . '/', '', $blockSplit[$k]);
1106 }
1107 }
1108 // If $blockSplit[$k] is blank then unset the line, unless the line only contained linebreaks
1109 if ((string)$blockSplit[$k] === '' && !$onlyLineBreaks) {
1110 unset($blockSplit[$k]);
1111 } else {
1112 $blockSplit[$k] = $this->setDivTags($blockSplit[$k], $this->procOptions['useDIVasParagraphTagForRTE'] ? 'div' : 'p');
1113 }
1114 }
1115 }
1116 return implode(LF, $blockSplit);
1117 }
1118
1119 /**
1120 * Transformation handler: 'ts_strip' / direction: "db"
1121 * Removing all non-allowed tags
1122 *
1123 * @param string $value Content input
1124 * @return string Content output
1125 * @todo Define visibility
1126 */
1127 public function TS_strip_db($value) {
1128 $value = strip_tags($value, '<' . implode('><', explode(',', 'b,i,u,a,img,br,div,center,pre,font,hr,sub,sup,p,strong,em,li,ul,ol,blockquote')) . '>');
1129 return $value;
1130 }
1131
1132 /***************************************************************
1133 *
1134 * Generic RTE transformation, analysis and helper functions
1135 *
1136 **************************************************************/
1137 /**
1138 * Reads the file or url $url and returns the content
1139 *
1140 * @param string $url Filepath/URL to read
1141 * @return string The content from the resource given as input.
1142 * @see \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl()
1143 * @todo Define visibility
1144 */
1145 public function getUrl($url) {
1146 return GeneralUtility::getUrl($url);
1147 }
1148
1149 /**
1150 * Function for cleaning content going into the database.
1151 * Content is cleaned eg. by removing unallowed HTML and ds-HSC content
1152 * It is basically calling HTMLcleaner from the parent class with some preset configuration specifically set up for cleaning content going from the RTE into the db
1153 *
1154 * @param string $content Content to clean up
1155 * @param string $tagList Comma list of tags to specifically allow. Default comes from getKeepTags and is
1156 * @return string Clean content
1157 * @see getKeepTags()
1158 * @todo Define visibility
1159 */
1160 public function HTMLcleaner_db($content, $tagList = '') {
1161 if (!$tagList) {
1162 $keepTags = $this->getKeepTags('db');
1163 } else {
1164 $keepTags = $this->getKeepTags('db', $tagList);
1165 }
1166 // Default: remove unknown tags.
1167 $kUknown = $this->procOptions['dontRemoveUnknownTags_db'] ? 1 : 0;
1168 // Default: re-convert literals to characters (that is &lt; to <)
1169 $hSC = $this->procOptions['dontUndoHSC_db'] ? 0 : -1;
1170 // Create additional configuration in order to honor the setting RTE.default.proc.HTMLparser_db.xhtml_cleaning=1
1171 $addConfig = array();
1172 if (is_array($this->procOptions['HTMLparser_db.']) && $this->procOptions['HTMLparser_db.']['xhtml_cleaning'] || is_array($this->procOptions['entryHTMLparser_db.']) && $this->procOptions['entryHTMLparser_db.']['xhtml_cleaning'] || is_array($this->procOptions['exitHTMLparser_db.']) && $this->procOptions['exitHTMLparser_db.']['xhtml_cleaning']) {
1173 $addConfig['xhtml'] = 1;
1174 }
1175 return $this->HTMLcleaner($content, $keepTags, $kUknown, $hSC, $addConfig);
1176 }
1177
1178 /**
1179 * Creates an array of configuration for the HTMLcleaner function based on whether content go TO or FROM the Rich Text Editor ($direction)
1180 * Unless "tagList" is given, the function will cache the configuration for next time processing goes on. (In this class that is the case only if we are processing a bulletlist)
1181 *
1182 * @param string $direction The direction of the content being processed by the output configuration; "db" (content going into the database FROM the rte) or "rte" (content going into the form)
1183 * @param string $tagList Comma list of tags to keep (overriding default which is to keep all + take notice of internal configuration)
1184 * @return array Configuration array
1185 * @see HTMLcleaner_db()
1186 * @todo Define visibility
1187 */
1188 public function getKeepTags($direction = 'rte', $tagList = '') {
1189 if (!is_array($this->getKeepTags_cache[$direction]) || $tagList) {
1190 // Setting up allowed tags:
1191 // If the $tagList input var is set, this will take precedence
1192 if ((string)$tagList !== '') {
1193 $keepTags = array_flip(GeneralUtility::trimExplode(',', $tagList, TRUE));
1194 } else {
1195 // Default is to get allowed/denied tags from internal array of processing options:
1196 // Construct default list of tags to keep:
1197 $typoScript_list = 'b,i,u,a,img,br,div,center,pre,font,hr,sub,sup,p,strong,em,li,ul,ol,blockquote,strike,span';
1198 $keepTags = array_flip(GeneralUtility::trimExplode(',', $typoScript_list . ',' . strtolower($this->procOptions['allowTags']), TRUE));
1199 // For tags to deny, remove them from $keepTags array:
1200 $denyTags = GeneralUtility::trimExplode(',', $this->procOptions['denyTags'], TRUE);
1201 foreach ($denyTags as $dKe) {
1202 unset($keepTags[$dKe]);
1203 }
1204 }
1205 // Based on the direction of content, set further options:
1206 switch ($direction) {
1207 case 'rte':
1208 if (!isset($this->procOptions['transformBoldAndItalicTags']) || $this->procOptions['transformBoldAndItalicTags']) {
1209 // Transform bold/italics tags to strong/em
1210 if (isset($keepTags['b'])) {
1211 $keepTags['b'] = array('remap' => 'STRONG');
1212 }
1213 if (isset($keepTags['i'])) {
1214 $keepTags['i'] = array('remap' => 'EM');
1215 }
1216 }
1217 // Transforming keepTags array so it can be understood by the HTMLcleaner function. This basically converts the format of the array from TypoScript (having .'s) to plain multi-dimensional array.
1218 list($keepTags) = $this->HTMLparserConfig($this->procOptions['HTMLparser_rte.'], $keepTags);
1219 break;
1220 case 'db':
1221 if (!isset($this->procOptions['transformBoldAndItalicTags']) || $this->procOptions['transformBoldAndItalicTags']) {
1222 // Transform strong/em back to bold/italics:
1223 if (isset($keepTags['strong'])) {
1224 $keepTags['strong'] = array('remap' => 'b');
1225 }
1226 if (isset($keepTags['em'])) {
1227 $keepTags['em'] = array('remap' => 'i');
1228 }
1229 }
1230 // Setting up span tags if they are allowed:
1231 if (isset($keepTags['span'])) {
1232 $classes = array_merge(array(''), $this->allowedClasses);
1233 $keepTags['span'] = array(
1234 'allowedAttribs' => 'id,class,style,title,lang,xml:lang,dir',
1235 'fixAttrib' => array(
1236 'class' => array(
1237 'list' => $classes,
1238 'removeIfFalse' => 1
1239 )
1240 ),
1241 'rmTagIfNoAttrib' => 1
1242 );
1243 if (!$this->procOptions['allowedClasses']) {
1244 unset($keepTags['span']['fixAttrib']['class']['list']);
1245 }
1246 }
1247 // Setting up font tags if they are allowed:
1248 if (isset($keepTags['font'])) {
1249 $colors = array_merge(array(''), GeneralUtility::trimExplode(',', $this->procOptions['allowedFontColors'], TRUE));
1250 $keepTags['font'] = array(
1251 'allowedAttribs' => 'face,color,size',
1252 'fixAttrib' => array(
1253 'face' => array(
1254 'removeIfFalse' => 1
1255 ),
1256 'color' => array(
1257 'removeIfFalse' => 1,
1258 'list' => $colors
1259 ),
1260 'size' => array(
1261 'removeIfFalse' => 1
1262 )
1263 ),
1264 'rmTagIfNoAttrib' => 1
1265 );
1266 if (!$this->procOptions['allowedFontColors']) {
1267 unset($keepTags['font']['fixAttrib']['color']['list']);
1268 }
1269 }
1270 // Setting further options, getting them from the processiong options:
1271 $TSc = $this->procOptions['HTMLparser_db.'];
1272 if (!$TSc['globalNesting']) {
1273 $TSc['globalNesting'] = 'b,i,u,a,center,font,sub,sup,strong,em,strike,span';
1274 }
1275 if (!$TSc['noAttrib']) {
1276 $TSc['noAttrib'] = 'b,i,u,br,center,hr,sub,sup,strong,em,li,ul,ol,blockquote,strike';
1277 }
1278 // Transforming the array from TypoScript to regular array:
1279 list($keepTags) = $this->HTMLparserConfig($TSc, $keepTags);
1280 break;
1281 }
1282 // Caching (internally, in object memory) the result unless tagList is set:
1283 if (!$tagList) {
1284 $this->getKeepTags_cache[$direction] = $keepTags;
1285 } else {
1286 return $keepTags;
1287 }
1288 }
1289 // Return result:
1290 return $this->getKeepTags_cache[$direction];
1291 }
1292
1293 /**
1294 * This resolves the $value into parts based on <div></div>-sections and <p>-sections and <br />-tags. These are returned as lines separated by LF.
1295 * This point is to resolve the HTML-code returned from RTE into ordinary lines so it's 'human-readable'
1296 * The function ->setDivTags does the opposite.
1297 * This function processes content to go into the database.
1298 *
1299 * @param string $value Value to process.
1300 * @param integer $count Recursion brake. Decremented on each recursion down to zero. Default is 5 (which equals the allowed nesting levels of p/div tags).
1301 * @param boolean $returnArray If TRUE, an array with the lines is returned, otherwise a string of the processed input value.
1302 * @return string Processed input value.
1303 * @see setDivTags()
1304 * @todo Define visibility
1305 */
1306 public function divideIntoLines($value, $count = 5, $returnArray = FALSE) {
1307 // Internalize font tags (move them from OUTSIDE p/div to inside it that is the case):
1308 if ($this->procOptions['internalizeFontTags']) {
1309 $value = $this->internalizeFontTags($value);
1310 }
1311 // Setting configuration for processing:
1312 $allowTagsOutside = GeneralUtility::trimExplode(',', strtolower($this->procOptions['allowTagsOutside'] ? 'hr,' . $this->procOptions['allowTagsOutside'] : 'hr,img'), TRUE);
1313 $remapParagraphTag = strtoupper($this->procOptions['remapParagraphTag']);
1314 $divSplit = $this->splitIntoBlock('div,p', $value, 1);
1315 // Setting the third param to 1 will eliminate false end-tags. Maybe this is a good thing to do...?
1316 if ($this->procOptions['keepPDIVattribs']) {
1317 $keepAttribListArr = GeneralUtility::trimExplode(',', strtolower($this->procOptions['keepPDIVattribs']), TRUE);
1318 } else {
1319 $keepAttribListArr = array();
1320 }
1321 // Returns plainly the value if there was no div/p sections in it
1322 if (count($divSplit) <= 1 || $count <= 0) {
1323 // Wrap hr tags with LF's
1324 $newValue = preg_replace('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/i', LF . '<$1$2/>' . LF, $value);
1325 $newValue = preg_replace('/' . LF . LF . '/i', LF, $newValue);
1326 $newValue = preg_replace('/(^' . LF . ')|(' . LF . '$)/i', '', $newValue);
1327 return $newValue;
1328 }
1329 // Traverse the splitted sections:
1330 foreach ($divSplit as $k => $v) {
1331 if ($k % 2) {
1332 // Inside
1333 $v = $this->removeFirstAndLastTag($v);
1334 // Fetching 'sub-lines' - which will explode any further p/div nesting...
1335 $subLines = $this->divideIntoLines($v, $count - 1, 1);
1336 // So, if there happend to be sub-nesting of p/div, this is written directly as the new content of THIS section. (This would be considered 'an error')
1337 if (is_array($subLines)) {
1338
1339 } else {
1340 //... but if NO subsection was found, we process it as a TRUE line without erronous content:
1341 $subLines = array($subLines);
1342 // process break-tags, if configured for. Simply, the breaktags will here be treated like if each was a line of content...
1343 if (!$this->procOptions['dontConvBRtoParagraph']) {
1344 $subLines = preg_split('/<br[[:space:]]*[\\/]?>/i', $v);
1345 }
1346 // Traverse sublines (there is typically one, except if <br/> has been converted to lines as well!)
1347 foreach ($subLines as $sk => $value) {
1348 // Clear up the subline for DB.
1349 $subLines[$sk] = $this->HTMLcleaner_db($subLines[$sk]);
1350 // Get first tag, attributes etc:
1351 $fTag = $this->getFirstTag($divSplit[$k]);
1352 $tagName = strtolower($this->getFirstTagName($divSplit[$k]));
1353 $attribs = $this->get_tag_attributes($fTag);
1354 // Keep attributes (lowercase)
1355 $newAttribs = array();
1356 if (count($keepAttribListArr)) {
1357 foreach ($keepAttribListArr as $keepA) {
1358 if (isset($attribs[0][$keepA])) {
1359 $newAttribs[$keepA] = $attribs[0][$keepA];
1360 }
1361 }
1362 }
1363 // ALIGN attribute:
1364 if (!$this->procOptions['skipAlign'] && trim($attribs[0]['align']) !== '' && strtolower($attribs[0]['align']) != 'left') {
1365 // Set to value, but not 'left'
1366 $newAttribs['align'] = strtolower($attribs[0]['align']);
1367 }
1368 // CLASS attribute:
1369 // Set to whatever value
1370 if (!$this->procOptions['skipClass'] && trim($attribs[0]['class']) !== '') {
1371 if (!count($this->allowedClasses) || in_array($attribs[0]['class'], $this->allowedClasses)) {
1372 $newAttribs['class'] = $attribs[0]['class'];
1373 } else {
1374 $classes = GeneralUtility::trimExplode(' ', $attribs[0]['class'], TRUE);
1375 $newClasses = array();
1376 foreach ($classes as $class) {
1377 if (in_array($class, $this->allowedClasses)) {
1378 $newClasses[] = $class;
1379 }
1380 }
1381 if (count($newClasses)) {
1382 $newAttribs['class'] = implode(' ', $newClasses);
1383 }
1384 }
1385 }
1386 // Remove any line break char (10 or 13)
1387 $subLines[$sk] = preg_replace('/' . LF . '|' . CR . '/', '', $subLines[$sk]);
1388 // If there are any attributes or if we are supposed to remap the tag, then do so:
1389 if (count($newAttribs) && $remapParagraphTag !== '1') {
1390 if ($remapParagraphTag === 'P') {
1391 $tagName = 'p';
1392 }
1393 if ($remapParagraphTag === 'DIV') {
1394 $tagName = 'div';
1395 }
1396 $subLines[$sk] = '<' . trim(($tagName . ' ' . $this->compileTagAttribs($newAttribs))) . '>' . $subLines[$sk] . '</' . $tagName . '>';
1397 }
1398 }
1399 }
1400 // Add the processed line(s)
1401 $divSplit[$k] = implode(LF, $subLines);
1402 // If it turns out the line is just blank (containing a &nbsp; possibly) then just make it pure blank.
1403 // But, prevent filtering of lines that are blank in sense above, but whose tags contain attributes.
1404 // Those attributes should have been filtered before; if they are still there they must be considered as possible content.
1405 if (trim(strip_tags($divSplit[$k])) == '&nbsp;' && !preg_match('/\\<(img)(\\s[^>]*)?\\/?>/si', $divSplit[$k]) && !preg_match('/\\<([^>]*)?( align| class| style| id| title| dir| lang| xml:lang)([^>]*)?>/si', trim($divSplit[$k]))) {
1406 $divSplit[$k] = '';
1407 }
1408 } else {
1409 // outside div:
1410 // Remove positions which are outside div/p tags and without content
1411 $divSplit[$k] = trim(strip_tags($divSplit[$k], '<' . implode('><', $allowTagsOutside) . '>'));
1412 // Wrap hr tags with LF's
1413 $divSplit[$k] = preg_replace('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/i', LF . '<$1$2/>' . LF, $divSplit[$k]);
1414 $divSplit[$k] = preg_replace('/' . LF . LF . '/i', LF, $divSplit[$k]);
1415 $divSplit[$k] = preg_replace('/(^' . LF . ')|(' . LF . '$)/i', '', $divSplit[$k]);
1416 if ((string)$divSplit[$k] === '') {
1417 unset($divSplit[$k]);
1418 }
1419 }
1420 }
1421 // Return value:
1422 return $returnArray ? $divSplit : implode(LF, $divSplit);
1423 }
1424
1425 /**
1426 * Converts all lines into <div></div>/<p></p>-sections (unless the line is a div-section already)
1427 * For processing of content going FROM database TO RTE.
1428 *
1429 * @param string $value Value to convert
1430 * @param string $dT Tag to wrap with. Either "p" or "div" should it be. Lowercase preferably.
1431 * @return string Processed value.
1432 * @see divideIntoLines()
1433 * @todo Define visibility
1434 */
1435 public function setDivTags($value, $dT = 'p') {
1436 // First, setting configuration for the HTMLcleaner function. This will process each line between the <div>/<p> section on their way to the RTE
1437 $keepTags = $this->getKeepTags('rte');
1438 // Default: remove unknown tags.
1439 $kUknown = $this->procOptions['dontProtectUnknownTags_rte'] ? 0 : 'protect';
1440 // Default: re-convert literals to characters (that is &lt; to <)
1441 $hSC = $this->procOptions['dontHSC_rte'] ? 0 : 1;
1442 $convNBSP = !$this->procOptions['dontConvAmpInNBSP_rte'] ? 1 : 0;
1443 // Divide the content into lines, based on LF:
1444 $parts = explode(LF, $value);
1445 foreach ($parts as $k => $v) {
1446 // Processing of line content:
1447 // If the line is blank, set it to &nbsp;
1448 if (trim($parts[$k]) === '') {
1449 $parts[$k] = '&nbsp;';
1450 } else {
1451 // Clean the line content:
1452 $parts[$k] = $this->HTMLcleaner($parts[$k], $keepTags, $kUknown, $hSC);
1453 if ($convNBSP) {
1454 $parts[$k] = str_replace('&amp;nbsp;', '&nbsp;', $parts[$k]);
1455 }
1456 }
1457 // Wrapping the line in <$dT> if not already wrapped and does not contain an hr tag
1458 if (!preg_match('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/i', $parts[$k])) {
1459 $testStr = strtolower(trim($parts[$k]));
1460 if (substr($testStr, 0, 4) != '<div' || substr($testStr, -6) != '</div>') {
1461 if (substr($testStr, 0, 2) != '<p' || substr($testStr, -4) != '</p>') {
1462 // Only set p-tags if there is not already div or p tags:
1463 $parts[$k] = '<' . $dT . '>' . $parts[$k] . '</' . $dT . '>';
1464 }
1465 }
1466 }
1467 }
1468 // Implode result:
1469 return implode(LF, $parts);
1470 }
1471
1472 /**
1473 * This splits the $value in font-tag chunks.
1474 * If there are any <P>/<DIV> sections inside of them, the font-tag is wrapped AROUND the content INSIDE of the P/DIV sections and the outer font-tag is removed.
1475 * This functions seems to be a good choice for pre-processing content if it has been pasted into the RTE from eg. star-office.
1476 * In that case the font-tags are normally on the OUTSIDE of the sections.
1477 * This function is used by eg. divideIntoLines() if the procesing option 'internalizeFontTags' is set.
1478 *
1479 * @param string Input content
1480 * @return string Output content
1481 * @see divideIntoLines()
1482 * @todo Define visibility
1483 */
1484 public function internalizeFontTags($value) {
1485 // Splitting into font tag blocks:
1486 $fontSplit = $this->splitIntoBlock('font', $value);
1487 foreach ($fontSplit as $k => $v) {
1488 // Inside
1489 if ($k % 2) {
1490 // Fint font-tag
1491 $fTag = $this->getFirstTag($v);
1492 $divSplit_sub = $this->splitIntoBlock('div,p', $this->removeFirstAndLastTag($v), 1);
1493 // If there were div/p sections inside the font-tag, do something about it...
1494 if (count($divSplit_sub) > 1) {
1495 // Traverse those sections:
1496 foreach ($divSplit_sub as $k2 => $v2) {
1497 // Inside
1498 if ($k2 % 2) {
1499 // Fint font-tag
1500 $div_p = $this->getFirstTag($v2);
1501 // Fint font-tag
1502 $div_p_tagname = $this->getFirstTagName($v2);
1503 // ... and remove it from original.
1504 $v2 = $this->removeFirstAndLastTag($v2);
1505 $divSplit_sub[$k2] = $div_p . $fTag . $v2 . '</font>' . '</' . $div_p_tagname . '>';
1506 } elseif (trim(strip_tags($v2))) {
1507 $divSplit_sub[$k2] = $fTag . $v2 . '</font>';
1508 }
1509 }
1510 $fontSplit[$k] = implode('', $divSplit_sub);
1511 }
1512 }
1513 }
1514 return implode('', $fontSplit);
1515 }
1516
1517 /**
1518 * Returns SiteURL based on thisScript.
1519 *
1520 * @return string Value of GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
1521 * @see \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv()
1522 * @todo Define visibility
1523 */
1524 public function siteUrl() {
1525 return GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
1526 }
1527
1528 /**
1529 * Return the storage folder of RTE image files.
1530 * Default is $GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_imageStorageDir'] unless something else is configured in the types configuration for the RTE.
1531 * @deprecated since 6.2, will be removed in two versions
1532 * @return string
1533 */
1534 public function rteImageStorageDir() {
1535 GeneralUtility::logDeprecatedFunction();
1536 return $this->rte_p['imgpath'] ? $this->rte_p['imgpath'] : $GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_imageStorageDir'];
1537 }
1538
1539 /**
1540 * Remove all tables from incoming code
1541 * The function is trying to to this is some more or less respectfull way. The approach is to resolve each table cells content and implode it all by <br /> chars. Thus at least the content is preserved in some way.
1542 *
1543 * @param string $value Input value
1544 * @param string $breakChar Break character to use for linebreaks.
1545 * @return string Output value
1546 * @todo Define visibility
1547 */
1548 public function removeTables($value, $breakChar = '<br />') {
1549 // Splitting value into table blocks:
1550 $tableSplit = $this->splitIntoBlock('table', $value);
1551 // Traverse blocks of tables:
1552 foreach ($tableSplit as $k => $v) {
1553 if ($k % 2) {
1554 $tableSplit[$k] = '';
1555 $rowSplit = $this->splitIntoBlock('tr', $v);
1556 foreach ($rowSplit as $k2 => $v2) {
1557 if ($k2 % 2) {
1558 $cellSplit = $this->getAllParts($this->splitIntoBlock('td', $v2), 1, 0);
1559 foreach ($cellSplit as $k3 => $v3) {
1560 $tableSplit[$k] .= $v3 . $breakChar;
1561 }
1562 }
1563 }
1564 }
1565 }
1566 // Implode it all again:
1567 return implode($breakChar, $tableSplit);
1568 }
1569
1570 /**
1571 * Default tag mapping for TS
1572 *
1573 * @param string $code Input code to process
1574 * @param string $direction Direction To databsae (db) or from database to RTE (rte)
1575 * @return string Processed value
1576 * @todo Define visibility
1577 */
1578 public function defaultTStagMapping($code, $direction = 'rte') {
1579 if ($direction == 'db') {
1580 $code = $this->mapTags($code, array(
1581 // Map tags
1582 'strong' => 'b',
1583 'em' => 'i'
1584 ));
1585 }
1586 if ($direction == 'rte') {
1587 $code = $this->mapTags($code, array(
1588 // Map tags
1589 'b' => 'strong',
1590 'i' => 'em'
1591 ));
1592 }
1593 return $code;
1594 }
1595
1596 /**
1597 * Finds width and height from attrib-array
1598 * If the width and height is found in the style-attribute, use that!
1599 *
1600 * @param array $attribArray Array of attributes from tag in which to search. More specifically the content of the key "style" is used to extract "width:xxx / height:xxx" information
1601 * @return array Integer w/h in key 0/1. Zero is returned if not found.
1602 * @todo Define visibility
1603 */
1604 public function getWHFromAttribs($attribArray) {
1605 $style = trim($attribArray['style']);
1606 if ($style) {
1607 $regex = '[[:space:]]*:[[:space:]]*([0-9]*)[[:space:]]*px';
1608 // Width
1609 $reg = array();
1610 preg_match('/width' . $regex . '/i', $style, $reg);
1611 $w = (int)$reg[1];
1612 // Height
1613 preg_match('/height' . $regex . '/i', $style, $reg);
1614 $h = (int)$reg[1];
1615 }
1616 if (!$w) {
1617 $w = $attribArray['width'];
1618 }
1619 if (!$h) {
1620 $h = $attribArray['height'];
1621 }
1622 return array((int)$w, (int)$h);
1623 }
1624
1625 /**
1626 * Parse <A>-tag href and return status of email,external,file or page
1627 *
1628 * @param string $url URL to analyse.
1629 * @return array Information in an array about the URL
1630 * @todo Define visibility
1631 */
1632 public function urlInfoForLinkTags($url) {
1633 $info = array();
1634 $url = trim($url);
1635 if (substr(strtolower($url), 0, 7) == 'mailto:') {
1636 $info['url'] = trim(substr($url, 7));
1637 $info['type'] = 'email';
1638 } elseif (strpos($url, '?file:') !== FALSE) {
1639 $info['type'] = 'file';
1640 $info['url'] = rawurldecode(substr($url, strpos($url, '?file:') + 1));
1641 } else {
1642 $curURL = $this->siteUrl();
1643 $urlLength = strlen($url);
1644 for ($a = 0; $a < $urlLength; $a++) {
1645 if ($url[$a] != $curURL[$a]) {
1646 break;
1647 }
1648 }
1649 $info['relScriptPath'] = substr($curURL, $a);
1650 $info['relUrl'] = substr($url, $a);
1651 $info['url'] = $url;
1652 $info['type'] = 'ext';
1653 $siteUrl_parts = parse_url($url);
1654 $curUrl_parts = parse_url($curURL);
1655 // Hosts should match
1656 if ($siteUrl_parts['host'] == $curUrl_parts['host'] && (!$info['relScriptPath'] || defined('TYPO3_mainDir') && substr($info['relScriptPath'], 0, strlen(TYPO3_mainDir)) == TYPO3_mainDir)) {
1657 // If the script path seems to match or is empty (FE-EDIT)
1658 // New processing order 100502
1659 $uP = parse_url($info['relUrl']);
1660 if ($info['relUrl'] === '#' . $siteUrl_parts['fragment']) {
1661 $info['url'] = $info['relUrl'];
1662 $info['type'] = 'anchor';
1663 } elseif (!trim($uP['path']) || $uP['path'] === 'index.php') {
1664 // URL is a page (id parameter)
1665 $pp = preg_split('/^id=/', $uP['query']);
1666 $pp[1] = preg_replace('/&id=[^&]*/', '', $pp[1]);
1667 $parameters = explode('&', $pp[1]);
1668 $id = array_shift($parameters);
1669 if ($id) {
1670 $info['pageid'] = $id;
1671 $info['cElement'] = $uP['fragment'];
1672 $info['url'] = $id . ($info['cElement'] ? '#' . $info['cElement'] : '');
1673 $info['type'] = 'page';
1674 $info['query'] = $parameters[0] ? '&' . implode('&', $parameters) : '';
1675 }
1676 } else {
1677 $info['url'] = $info['relUrl'];
1678 $info['type'] = 'file';
1679 }
1680 } else {
1681 unset($info['relScriptPath']);
1682 unset($info['relUrl']);
1683 }
1684 }
1685 return $info;
1686 }
1687
1688 /**
1689 * Converting <A>-tags to absolute URLs (+ setting rtekeep attribute)
1690 *
1691 * @param string $value Content input
1692 * @param boolean $dontSetRTEKEEP If TRUE, then the "rtekeep" attribute will not be set.
1693 * @return string Content output
1694 * @todo Define visibility
1695 */
1696 public function TS_AtagToAbs($value, $dontSetRTEKEEP = FALSE) {
1697 $blockSplit = $this->splitIntoBlock('A', $value);
1698 foreach ($blockSplit as $k => $v) {
1699 // Block
1700 if ($k % 2) {
1701 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v), 1);
1702 // Checking if there is a scheme, and if not, prepend the current url.
1703 // ONLY do this if href has content - the <a> tag COULD be an anchor and if so, it should be preserved...
1704 if (strlen($attribArray['href'])) {
1705 $uP = parse_url(strtolower($attribArray['href']));
1706 if (!$uP['scheme']) {
1707 $attribArray['href'] = $this->siteUrl() . substr($attribArray['href'], strlen($this->relBackPath));
1708 } elseif ($uP['scheme'] != 'mailto') {
1709 $attribArray['data-htmlarea-external'] = 1;
1710 }
1711 } else {
1712 $attribArray['rtekeep'] = 1;
1713 }
1714 if (!$dontSetRTEKEEP) {
1715 $attribArray['rtekeep'] = 1;
1716 }
1717 $bTag = '<a ' . GeneralUtility::implodeAttributes($attribArray, 1) . '>';
1718 $eTag = '</a>';
1719 $blockSplit[$k] = $bTag . $this->TS_AtagToAbs($this->removeFirstAndLastTag($blockSplit[$k])) . $eTag;
1720 }
1721 }
1722 return implode('', $blockSplit);
1723 }
1724
1725 /**
1726 * Apply plain image settings to the dimensions of the image
1727 *
1728 * @param array $imageInfo: info array of the image
1729 * @param array $attribArray: array of attributes of an image tag
1730 *
1731 * @return array a modified attributes array
1732 */
1733 protected function applyPlainImageModeSettings($imageInfo, $attribArray) {
1734 if ($this->procOptions['plainImageMode']) {
1735 // Perform corrections to aspect ratio based on configuration
1736 switch ((string) $this->procOptions['plainImageMode']) {
1737 case 'lockDimensions':
1738 $attribArray['width'] = $imageInfo[0];
1739 $attribArray['height'] = $imageInfo[1];
1740 break;
1741 case 'lockRatioWhenSmaller':
1742 if ($attribArray['width'] > $imageInfo[0]) {
1743 $attribArray['width'] = $imageInfo[0];
1744 }
1745 case 'lockRatio':
1746 if ($imageInfo[0] > 0) {
1747 $attribArray['height'] = round($attribArray['width'] * ($imageInfo[1] / $imageInfo[0]));
1748 }
1749 break;
1750 }
1751 }
1752 return $attribArray;
1753 }
1754
1755 /**
1756 * @return \TYPO3\CMS\Core\Log\Logger
1757 */
1758 protected function getLogger() {
1759
1760 /** @var $logManager \TYPO3\CMS\Core\Log\LogManager */
1761 $logManager = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Log\\LogManager');
1762
1763 return $logManager->getLogger(get_class($this));
1764 }
1765
1766 }