2 namespace TYPO3\CMS\Core\Html
;
5 * This file is part of the TYPO3 CMS project.
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
17 use TYPO3\CMS\Backend\Utility\BackendUtility
;
18 use TYPO3\CMS\Core\Utility\GeneralUtility
;
19 use TYPO3\CMS\Core\Utility\StringUtility
;
20 use TYPO3\CMS\Core\Resource
;
21 use TYPO3\CMS\Frontend\Service\TypoLinkCodecService
;
24 * Class for parsing HTML for the Rich Text Editor. (also called transformations)
26 class RteHtmlParser
extends \TYPO3\CMS\Core\Html\HtmlParser
31 public $blockElementList = 'PRE,UL,OL,H1,H2,H3,H4,H5,H6,ADDRESS,DL,DD,HEADER,SECTION,FOOTER,NAV,ARTICLE,ASIDE';
34 * Set this to the pid of the record manipulated by the class.
41 * Element reference [table]:[field], eg. "tt_content:bodytext"
59 public $relBackPath = '';
62 * Current Page TSConfig
66 public $tsConfig = array();
69 * Set to the TSconfig options coming from Page TSconfig
73 public $procOptions = array();
76 * Run-away brake for recursive calls.
80 public $TS_transform_db_safecounter = 100;
83 * Parameters from TCA types configuration related to the RTE
90 * Data caching for processing function
94 public $getKeepTags_cache = array();
97 * Storage of the allowed CSS class names in the RTE
101 public $allowedClasses = array();
104 * Set to tags to preserve from Page TSconfig configuration
108 public $preserveTags = '';
111 * Initialize, setting element reference and record PID
113 * @param string $elRef Element reference, eg "tt_content:bodytext
114 * @param int $recPid PID of the record (page id)
117 public function init($elRef = '', $recPid = 0)
119 $this->recPid
= $recPid;
120 $this->elRef
= $elRef;
124 * Setting the ->relPath and ->relBackPath to proper values so absolute references to links and images can be converted to relative dittos.
125 * This is used when editing files with the RTE
127 * @param string $path The relative path from PATH_site to the place where the file being edited is. Eg. "fileadmin/static".
128 * @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 "../../
129 * @TODO: Check if relPath and relBackPath are used for anything useful after removal of "static file edit" with #63818
131 public function setRelPath($path)
134 $path = preg_replace('/^\\//', '', $path);
135 $path = preg_replace('/\\/$/', '', $path);
137 $this->relPath
= $path;
138 $this->relBackPath
= '';
139 $partsC = count(explode('/', $this->relPath
));
140 for ($a = 0; $a < $partsC; $a++
) {
141 $this->relBackPath
.= '../';
143 $this->relPath
.= '/';
148 * Evaluate the environment for editing a staticFileEdit file.
149 * Called for almost all fields being saved in the database. Is called without
150 * an instance of \TYPO3\CMS\Core\Html\RteHtmlParser::evalWriteFile()
152 * @param array $pArr Parameters for the current field as found in types-config
153 * @param array $currentRecord Current record we are editing.
154 * @return mixed On success an array with various information is returned, otherwise a string with an error message
155 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
157 public static function evalWriteFile($pArr, $currentRecord)
159 GeneralUtility
::logDeprecatedFunction();
162 /**********************************************
166 **********************************************/
168 * Transform value for RTE based on specConf in the direction specified by $direction (rte/db)
169 * This is the main function called from tcemain and transfer data classes
171 * @param string Input value
172 * @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!
173 * @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.
174 * @param array Parsed TypoScript content configuring the RTE, probably coming from Page TSconfig.
175 * @return string Output value
177 public function RTE_transform($value, $specConf, $direction = 'rte', $thisConfig = array())
180 $this->tsConfig
= $thisConfig;
181 $this->procOptions
= (array)$thisConfig['proc.'];
182 $this->preserveTags
= strtoupper(implode(',', GeneralUtility
::trimExplode(',', $this->procOptions
['preserveTags'])));
183 // dynamic configuration of blockElementList
184 if ($this->procOptions
['blockElementList']) {
185 $this->blockElementList
= $this->procOptions
['blockElementList'];
187 // Get parameters for rte_transformation:
188 $p = ($this->rte_p
= BackendUtility
::getSpecConfParametersFromArray($specConf['rte_transform']['parameters']));
190 if ((string)$this->procOptions
['overruleMode'] !== '') {
191 $modes = array_unique(GeneralUtility
::trimExplode(',', $this->procOptions
['overruleMode']));
193 $modes = array_unique(GeneralUtility
::trimExplode('-', $p['mode']));
195 $revmodes = array_flip($modes);
196 // Find special modes and extract them:
197 if (isset($revmodes['ts'])) {
198 $modes[$revmodes['ts']] = 'ts_transform,ts_preserve,ts_images,ts_links';
200 // Find special modes and extract them:
201 if (isset($revmodes['ts_css'])) {
202 $modes[$revmodes['ts_css']] = 'css_transform,ts_images,ts_links';
205 $modes = array_unique(GeneralUtility
::trimExplode(',', implode(',', $modes), true
));
206 // Reverse order if direction is "rte"
207 if ($direction == 'rte') {
208 $modes = array_reverse($modes);
210 // Getting additional HTML cleaner configuration. These are applied either before or after the main transformation is done and is thus totally independent processing options you can set up:
211 $entry_HTMLparser = $this->procOptions
['entryHTMLparser_' . $direction] ?
$this->HTMLparserConfig($this->procOptions
['entryHTMLparser_' . $direction . '.']) : '';
212 $exit_HTMLparser = $this->procOptions
['exitHTMLparser_' . $direction] ?
$this->HTMLparserConfig($this->procOptions
['exitHTMLparser_' . $direction . '.']) : '';
213 // Line breaks of content is unified into char-10 only (removing char 13)
214 if (!$this->procOptions
['disableUnifyLineBreaks']) {
215 $value = str_replace(CRLF
, LF
, $value);
217 // In an entry-cleaner was configured, pass value through the HTMLcleaner with that:
218 if (is_array($entry_HTMLparser)) {
219 $value = $this->HTMLcleaner($value, $entry_HTMLparser[0], $entry_HTMLparser[1], $entry_HTMLparser[2], $entry_HTMLparser[3]);
222 foreach ($modes as $cmd) {
224 if ($direction == 'db') {
225 // Checking for user defined transformation:
226 if ($_classRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['transformation'][$cmd]) {
227 $_procObj = GeneralUtility
::getUserObj($_classRef);
228 $_procObj->pObj
= $this;
229 $_procObj->transformationKey
= $cmd;
230 $value = $_procObj->transform_db($value, $this);
232 // ... else use defaults:
235 $value = $this->TS_images_db($value);
238 $value = $this->TS_reglinks($value, 'db');
241 $value = $this->TS_links_db($value);
244 $value = $this->TS_preserve_db($value);
248 case 'css_transform':
249 $this->allowedClasses
= GeneralUtility
::trimExplode(',', $this->procOptions
['allowedClasses'], true
);
250 // CR has a very disturbing effect, so just remove all CR and rely on LF
251 $value = str_replace(CR
, '', $value);
252 // Transform empty paragraphs into spacing paragraphs
253 $value = str_replace('<p></p>', '<p> </p>', $value);
254 // Double any trailing spacing paragraph so that it does not get removed by divideIntoLines()
255 $value = preg_replace('/<p> <\/p>$/', '<p> </p>' . '<p> </p>', $value);
256 $value = $this->TS_transform_db($value, $cmd == 'css_transform');
259 $value = $this->TS_strip_db($value);
267 if ($direction == 'rte') {
268 // Checking for user defined transformation:
269 if ($_classRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['transformation'][$cmd]) {
270 $_procObj = GeneralUtility
::getUserObj($_classRef);
271 $_procObj->pObj
= $this;
272 $value = $_procObj->transform_rte($value, $this);
274 // ... else use defaults:
277 $value = $this->TS_images_rte($value);
280 $value = $this->TS_reglinks($value, 'rte');
283 $value = $this->TS_links_rte($value);
286 $value = $this->TS_preserve_rte($value);
290 case 'css_transform':
291 // Has a very disturbing effect, so just remove all '13' - depend on '10'
292 $value = str_replace(CR
, '', $value);
293 $value = $this->TS_transform_rte($value, $cmd == 'css_transform');
301 // In an exit-cleaner was configured, pass value through the HTMLcleaner with that:
302 if (is_array($exit_HTMLparser)) {
303 $value = $this->HTMLcleaner($value, $exit_HTMLparser[0], $exit_HTMLparser[1], $exit_HTMLparser[2], $exit_HTMLparser[3]);
305 // Final clean up of linebreaks:
306 if (!$this->procOptions
['disableUnifyLineBreaks']) {
307 // Make sure no \r\n sequences has entered in the meantime...
308 $value = str_replace(CRLF
, LF
, $value);
309 // ... and then change all \n into \r\n
310 $value = str_replace(LF
, CRLF
, $value);
316 /************************************
318 * Specific RTE TRANSFORMATION functions
320 *************************************/
322 * Transformation handler: 'ts_images' / direction: "db"
323 * Processing images inserted in the RTE.
324 * This is used when content goes from the RTE to the database.
325 * Images inserted in the RTE has an absolute URL applied to the src attribute. This URL is converted to a relative URL
326 * 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.
327 * Also "magic" images are processed here.
329 * @param string $value The content from RTE going to Database
330 * @return string Processed content
332 public function TS_images_db($value)
334 // Split content by <img> tags and traverse the resulting array for processing:
335 $imgSplit = $this->splitTags('img', $value);
336 if (count($imgSplit) > 1) {
337 $siteUrl = $this->siteUrl();
338 $sitePath = str_replace(GeneralUtility
::getIndpEnv('TYPO3_REQUEST_HOST'), '', $siteUrl);
339 /** @var $resourceFactory Resource\ResourceFactory */
340 $resourceFactory = Resource\ResourceFactory
::getInstance();
341 /** @var $magicImageService Resource\Service\MagicImageService */
342 $magicImageService = GeneralUtility
::makeInstance(\TYPO3\CMS\Core\Resource\Service\MagicImageService
::class);
343 $magicImageService->setMagicImageMaximumDimensions($this->tsConfig
);
344 foreach ($imgSplit as $k => $v) {
345 // Image found, do processing:
348 $attribArray = $this->get_tag_attributes_classic($v, 1);
349 // It's always an absolute URL coming from the RTE into the Database.
350 $absoluteUrl = trim($attribArray['src']);
351 // Make path absolute if it is relative and we have a site path which is not '/'
352 $pI = pathinfo($absoluteUrl);
353 if ($sitePath && !$pI['scheme'] && GeneralUtility
::isFirstPartOfStr($absoluteUrl, $sitePath)) {
354 // If site is in a subpath (eg. /~user_jim/) this path needs to be removed because it will be added with $siteUrl
355 $absoluteUrl = substr($absoluteUrl, strlen($sitePath));
356 $absoluteUrl = $siteUrl . $absoluteUrl;
358 // Image dimensions set in the img tag, if any
359 $imgTagDimensions = $this->getWHFromAttribs($attribArray);
360 if ($imgTagDimensions[0]) {
361 $attribArray['width'] = $imgTagDimensions[0];
363 if ($imgTagDimensions[1]) {
364 $attribArray['height'] = $imgTagDimensions[1];
366 $originalImageFile = null
;
367 if ($attribArray['data-htmlarea-file-uid']) {
368 // An original image file uid is available
370 /** @var $originalImageFile Resource\File */
371 $originalImageFile = $resourceFactory->getFileObject(intval($attribArray['data-htmlarea-file-uid']));
372 } catch (Resource\Exception\FileDoesNotExistException
$fileDoesNotExistException) {
373 // Log the fact the file could not be retrieved.
374 $message = sprintf('Could not find file with uid "%s"', $attribArray['data-htmlarea-file-uid']);
375 $this->getLogger()->error($message);
378 if ($originalImageFile instanceof Resource\File
) {
379 // Public url of local file is relative to the site url, absolute otherwise
380 if ($absoluteUrl == $originalImageFile->getPublicUrl() ||
$absoluteUrl == $siteUrl . $originalImageFile->getPublicUrl()) {
381 // This is a plain image, i.e. reference to the original image
382 if ($this->procOptions
['plainImageMode']) {
383 // "plain image mode" is configured
384 // Find the dimensions of the original image
386 $originalImageFile->getProperty('width'),
387 $originalImageFile->getProperty('height')
389 if (!$imageInfo[0] ||
!$imageInfo[1]) {
390 $filePath = $originalImageFile->getForLocalProcessing(false
);
391 $imageInfo = @getimagesize
($filePath);
393 $attribArray = $this->applyPlainImageModeSettings($imageInfo, $attribArray);
396 // Magic image case: get a processed file with the requested configuration
397 $imageConfiguration = array(
398 'width' => $imgTagDimensions[0],
399 'height' => $imgTagDimensions[1]
401 $magicImage = $magicImageService->createMagicImage($originalImageFile, $imageConfiguration);
402 $attribArray['width'] = $magicImage->getProperty('width');
403 $attribArray['height'] = $magicImage->getProperty('height');
404 $attribArray['src'] = $magicImage->getPublicUrl();
406 } elseif (!GeneralUtility
::isFirstPartOfStr($absoluteUrl, $siteUrl) && !$this->procOptions
['dontFetchExtPictures'] && TYPO3_MODE
=== 'BE') {
407 // External image from another URL: in that case, fetch image, unless the feature is disabled or we are not in backend mode
408 // Fetch the external image
409 $externalFile = $this->getUrl($absoluteUrl);
411 $pU = parse_url($absoluteUrl);
412 $pI = pathinfo($pU['path']);
413 if (GeneralUtility
::inList('gif,png,jpeg,jpg', strtolower($pI['extension']))) {
414 $fileName = GeneralUtility
::shortMD5($absoluteUrl) . '.' . $pI['extension'];
415 // We insert this image into the user default upload folder
416 list($table, $field) = explode(':', $this->elRef
);
417 $folder = $GLOBALS['BE_USER']->getDefaultUploadFolder($this->recPid
, $table, $field);
418 $fileObject = $folder->createFile($fileName)->setContents($externalFile);
419 $imageConfiguration = array(
420 'width' => $attribArray['width'],
421 'height' => $attribArray['height']
423 $magicImage = $magicImageService->createMagicImage($fileObject, $imageConfiguration);
424 $attribArray['width'] = $magicImage->getProperty('width');
425 $attribArray['height'] = $magicImage->getProperty('height');
426 $attribArray['data-htmlarea-file-uid'] = $fileObject->getUid();
427 $attribArray['src'] = $magicImage->getPublicUrl();
430 } elseif (GeneralUtility
::isFirstPartOfStr($absoluteUrl, $siteUrl)) {
431 // Finally, check image as local file (siteURL equals the one of the image)
432 // Image has no data-htmlarea-file-uid attribute
433 // Relative path, rawurldecoded for special characters.
434 $path = rawurldecode(substr($absoluteUrl, strlen($siteUrl)));
435 // Absolute filepath, locked to relative path of this project
436 $filepath = GeneralUtility
::getFileAbsFileName($path);
437 // Check file existence (in relative directory to this installation!)
438 if ($filepath && @is_file
($filepath)) {
439 // Treat it as a plain image
440 if ($this->procOptions
['plainImageMode']) {
441 // If "plain image mode" has been configured
442 // Find the original dimensions of the image
443 $imageInfo = @getimagesize
($filepath);
444 $attribArray = $this->applyPlainImageModeSettings($imageInfo, $attribArray);
446 // Let's try to find a file uid for this image
448 $fileOrFolderObject = $resourceFactory->retrieveFileOrFolderObject($path);
449 if ($fileOrFolderObject instanceof Resource\FileInterface
) {
450 $fileIdentifier = $fileOrFolderObject->getIdentifier();
451 $fileObject = $fileOrFolderObject->getStorage()->getFile($fileIdentifier);
452 // @todo if the retrieved file is a processed file, get the original file...
453 $attribArray['data-htmlarea-file-uid'] = $fileObject->getUid();
455 } catch (Resource\Exception\ResourceDoesNotExistException
$resourceDoesNotExistException) {
456 // Nothing to be done if file/folder not found
460 // Remove width and height from style attribute
461 $attribArray['style'] = preg_replace('/((?:^|)\\s*(?:width|height)\\s*:[^;]*(?:$|;))/si', '', $attribArray['style']);
462 // Must have alt attribute
463 if (!isset($attribArray['alt'])) {
464 $attribArray['alt'] = '';
466 // Convert absolute to relative url
467 if (GeneralUtility
::isFirstPartOfStr($attribArray['src'], $siteUrl)) {
468 $attribArray['src'] = $this->relBackPath
. substr($attribArray['src'], strlen($siteUrl));
470 $imgSplit[$k] = '<img ' . GeneralUtility
::implodeAttributes($attribArray, 1, 1) . ' />';
474 return implode('', $imgSplit);
478 * Transformation handler: 'ts_images' / direction: "rte"
479 * Processing images from database content going into the RTE.
480 * Processing includes converting the src attribute to an absolute URL.
482 * @param string $value Content input
483 * @return string Content output
485 public function TS_images_rte($value)
487 // Split content by <img> tags and traverse the resulting array for processing:
488 $imgSplit = $this->splitTags('img', $value);
489 if (count($imgSplit) > 1) {
490 $siteUrl = $this->siteUrl();
491 $sitePath = str_replace(GeneralUtility
::getIndpEnv('TYPO3_REQUEST_HOST'), '', $siteUrl);
492 foreach ($imgSplit as $k => $v) {
495 // Get the attributes of the img tag
496 $attribArray = $this->get_tag_attributes_classic($v, 1);
497 $absoluteUrl = trim($attribArray['src']);
498 // Transform the src attribute into an absolute url, if it not already
499 if (strtolower(substr($absoluteUrl, 0, 4)) !== 'http') {
500 $attribArray['src'] = substr($attribArray['src'], strlen($this->relBackPath
));
501 // If site is in a subpath (eg. /~user_jim/) this path needs to be removed because it will be added with $siteUrl
502 $attribArray['src'] = preg_replace('#^' . preg_quote($sitePath, '#') . '#', '', $attribArray['src']);
503 $attribArray['src'] = $siteUrl . $attribArray['src'];
505 // Must have alt attribute
506 if (!isset($attribArray['alt'])) {
507 $attribArray['alt'] = '';
509 $imgSplit[$k] = '<img ' . GeneralUtility
::implodeAttributes($attribArray, 1, 1) . ' />';
513 // Return processed content:
514 return implode('', $imgSplit);
518 * Transformation handler: 'ts_reglinks' / direction: "db"+"rte" depending on $direction variable.
519 * Converting <A>-tags to/from abs/rel
521 * @param string $value Content input
522 * @param string $direction Direction of conversion; "rte" (from database to RTE) or "db" (from RTE to database)
523 * @return string Content output
525 public function TS_reglinks($value, $direction)
528 switch ($direction) {
530 $retVal = $this->TS_AtagToAbs($value, 1);
533 $siteURL = $this->siteUrl();
534 $blockSplit = $this->splitIntoBlock('A', $value);
535 foreach ($blockSplit as $k => $v) {
538 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v), 1);
539 // If the url is local, remove url-prefix
540 if ($siteURL && substr($attribArray['href'], 0, strlen($siteURL)) == $siteURL) {
541 $attribArray['href'] = $this->relBackPath
. substr($attribArray['href'], strlen($siteURL));
543 $bTag = '<a ' . GeneralUtility
::implodeAttributes($attribArray, 1) . '>';
545 $blockSplit[$k] = $bTag . $this->TS_reglinks($this->removeFirstAndLastTag($blockSplit[$k]), $direction) . $eTag;
548 $retVal = implode('', $blockSplit);
555 * Transformation handler: 'ts_links' / direction: "db"
556 * Converting <A>-tags to <link tags>
558 * @param string $value Content input
559 * @return string Content output
560 * @see TS_links_rte()
562 public function TS_links_db($value)
565 // Split content into <a> tag blocks and process:
566 $blockSplit = $this->splitIntoBlock('A', $value);
567 foreach ($blockSplit as $k => $v) {
568 // If an A-tag was found:
570 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v), 1);
571 $info = $this->urlInfoForLinkTags($attribArray['href']);
573 $attribArray_copy = $attribArray;
574 unset($attribArray_copy['href']);
575 unset($attribArray_copy['target']);
576 unset($attribArray_copy['class']);
577 unset($attribArray_copy['title']);
578 unset($attribArray_copy['data-htmlarea-external']);
579 // Unset "rteerror" and "style" attributes if "rteerror" is set!
580 if ($attribArray_copy['rteerror']) {
581 unset($attribArray_copy['style']);
582 unset($attribArray_copy['rteerror']);
584 // Remove additional parameters
585 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'])) {
588 'aTagParams' => &$attribArray_copy
590 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['removeParams_PostProc'] as $objRef) {
591 $processor = GeneralUtility
::getUserObj($objRef);
592 $attribArray_copy = $processor->removeParams($parameters, $this);
595 // Only if href, target, class and tile are the only attributes, we can alter the link!
596 if (empty($attribArray_copy)) {
597 // Quoting class and title attributes if they contain spaces
598 $attribArray['class'] = preg_match('/ /', $attribArray['class']) ?
'"' . $attribArray['class'] . '"' : $attribArray['class'];
599 $attribArray['title'] = preg_match('/ /', $attribArray['title']) ?
'"' . $attribArray['title'] . '"' : $attribArray['title'];
600 // Creating the TYPO3 pseudo-tag "<LINK>" for the link (includes href/url, target and class attributes):
601 // If data-htmlarea-external attribute is set, keep the href unchanged
602 if ($attribArray['data-htmlarea-external']) {
603 $href = $attribArray['href'];
605 $href = $info['url'] . ($info['query'] ?
',0,' . $info['query'] : '');
607 $bTag = '<link ' . $href . ($attribArray['target'] ?
' ' . $attribArray['target'] : ($attribArray['class'] ||
$attribArray['title'] ?
' -' : '')) . ($attribArray['class'] ?
' ' . $attribArray['class'] : ($attribArray['title'] ?
' -' : '')) . ($attribArray['title'] ?
' ' . $attribArray['title'] : '') . '>';
610 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'])) {
613 'currentBlock' => $v,
615 'attributes' => $attribArray
617 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksDb_PostProc'] as $objRef) {
618 $processor = GeneralUtility
::getUserObj($objRef);
619 $blockSplit[$k] = $processor->modifyParamsLinksDb($parameters, $this);
622 $blockSplit[$k] = $bTag . $this->TS_links_db($this->removeFirstAndLastTag($blockSplit[$k])) . $eTag;
625 // ... otherwise store the link as a-tag.
626 // Unsetting 'rtekeep' attribute if that had been set.
627 unset($attribArray['rtekeep']);
628 if (!$attribArray['data-htmlarea-external']) {
629 $siteURL = $this->siteUrl();
630 // If the url is local, remove url-prefix
631 if ($siteURL && substr($attribArray['href'], 0, strlen($siteURL)) == $siteURL) {
632 $attribArray['href'] = $this->relBackPath
. substr($attribArray['href'], strlen($siteURL));
634 // Check for FAL link-handler keyword
635 list($linkHandlerKeyword, $linkHandlerValue) = explode(':', $attribArray['href'], 2);
636 if ($linkHandlerKeyword === '?file') {
638 $fileOrFolderObject = \TYPO3\CMS\Core\Resource\ResourceFactory
::getInstance()->retrieveFileOrFolderObject(rawurldecode($linkHandlerValue));
639 if ($fileOrFolderObject instanceof \TYPO3\CMS\Core\Resource\FileInterface ||
$fileOrFolderObject instanceof \TYPO3\CMS\Core\Resource\Folder
) {
640 $attribArray['href'] = $fileOrFolderObject->getPublicUrl();
642 } catch (\TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException
$resourceDoesNotExistException) {
643 // The indentifier inserted in the RTE is already gone...
647 unset($attribArray['data-htmlarea-external']);
648 $bTag = '<a ' . GeneralUtility
::implodeAttributes($attribArray, 1) . '>';
650 $blockSplit[$k] = $bTag . $this->TS_links_db($this->removeFirstAndLastTag($blockSplit[$k])) . $eTag;
654 return implode('', $blockSplit);
658 * Transformation handler: 'ts_links' / direction: "rte"
659 * Converting <link tags> to <A>-tags
661 * @param string $value Content input
662 * @return string Content output
663 * @see TS_links_rte()
665 public function TS_links_rte($value)
668 $value = $this->TS_AtagToAbs($value);
669 // Split content by the TYPO3 pseudo tag "<link>":
670 $blockSplit = $this->splitIntoBlock('link', $value, 1);
671 $siteUrl = $this->siteUrl();
672 foreach ($blockSplit as $k => $v) {
677 // split away the first "<link" part
678 $typolink = explode(' ', substr($this->getFirstTag($v), 0, -1), 2)[1];
679 $tagCode = GeneralUtility
::makeInstance(TypoLinkCodecService
::class)->decode($typolink);
681 $link_param = $tagCode['url'];
682 // Parsing the typolink data. This parsing is roughly done like in \TYPO3\CMS\Frontend\ContentObject->typoLink()
684 $pU = parse_url($link_param);
685 if (strstr($link_param, '@') && (!$pU['scheme'] ||
$pU['scheme'] == 'mailto')) {
687 $href = 'mailto:' . preg_replace('/^mailto:/i', '', $link_param);
688 } elseif ($link_param[0] === '#') {
690 $href = $siteUrl . $link_param;
692 // Check for FAL link-handler keyword:
693 list($linkHandlerKeyword, $linkHandlerValue) = explode(':', trim($link_param), 2);
694 if ($linkHandlerKeyword === 'file' && !StringUtility
::beginsWith($link_param, 'file://')) {
695 $href = $siteUrl . '?' . $linkHandlerKeyword . ':' . rawurlencode($linkHandlerValue);
697 $fileChar = (int)strpos($link_param, '/');
698 $urlChar = (int)strpos($link_param, '.');
699 // Detects if a file is found in site-root.
700 list($rootFileDat) = explode('?', $link_param);
701 $rFD_fI = pathinfo($rootFileDat);
702 if (trim($rootFileDat) && !strstr($link_param, '/') && (@is_file
((PATH_site
. $rootFileDat)) || GeneralUtility
::inList('php,html,htm', strtolower($rFD_fI['extension'])))) {
703 $href = $siteUrl . $link_param;
707 && !isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['typolinkLinkHandler'][$pU['scheme']])
709 ||
$urlChar && (!$fileChar ||
$urlChar < $fileChar)
711 // url (external): if has scheme or if a '.' comes before a '/'.
713 if (!$pU['scheme']) {
714 $href = 'http://' . $href;
717 } elseif ($fileChar) {
718 // It is an internal file or folder
719 // Try to transform the href into a FAL reference
721 $fileOrFolderObject = \TYPO3\CMS\Core\Resource\ResourceFactory
::getInstance()->retrieveFileOrFolderObject($link_param);
722 } catch (\TYPO3\CMS\Core\Resource\Exception
$exception) {
723 // Nothing to be done if file/folder not found or path invalid
724 $fileOrFolderObject = null
;
726 if ($fileOrFolderObject instanceof \TYPO3\CMS\Core\Resource\Folder
) {
728 $folderIdentifier = $fileOrFolderObject->getIdentifier();
729 $href = $siteUrl . '?file:' . rawurlencode($folderIdentifier);
730 } elseif ($fileOrFolderObject instanceof \TYPO3\CMS\Core\Resource\FileInterface
) {
732 $fileIdentifier = $fileOrFolderObject->getIdentifier();
733 $fileObject = $fileOrFolderObject->getStorage()->getFile($fileIdentifier);
734 $href = $siteUrl . '?file:' . $fileObject->getUid();
736 $href = $siteUrl . $link_param;
739 // integer or alias (alias is without slashes or periods or commas, that is 'nospace,alphanum_x,lower,unique' according to tables.php!!)
740 // Splitting the parameter by ',' and if the array counts more than 1 element it's an id/type/parameters triplet
741 $pairParts = GeneralUtility
::trimExplode(',', $link_param, true
);
742 $idPart = $pairParts[0];
743 $link_params_parts = explode('#', $idPart);
744 $idPart = trim($link_params_parts[0]);
745 $sectionMark = trim($link_params_parts[1]);
746 if ((string)$idPart === '') {
747 $idPart = $this->recPid
;
749 // If no id or alias is given, set it to class record pid
750 // Checking if the id-parameter is an alias.
751 if (!\TYPO3\CMS\Core\Utility\MathUtility
::canBeInterpretedAsInteger($idPart)) {
752 list($idPartR) = BackendUtility
::getRecordsByField('pages', 'alias', $idPart);
753 $idPart = (int)$idPartR['uid'];
755 $page = BackendUtility
::getRecord('pages', $idPart);
756 if (is_array($page)) {
757 // Page must exist...
758 $href = $siteUrl . '?id=' . $idPart . ($pairParts[2] ?
$pairParts[2] : '') . ($sectionMark ?
'#' . $sectionMark : '');
759 } elseif (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_content.php']['typolinkLinkHandler'][array_shift(explode(':', $link_param))])) {
762 $href = $siteUrl . '?id=' . $link_param;
763 $error = 'No page found: ' . $idPart;
768 // Setting the A-tag:
769 $bTag = '<a href="' . htmlspecialchars($href) . '"'
770 . ($tagCode['target'] ?
' target="' . htmlspecialchars($tagCode['target']) . '"' : '')
771 . ($tagCode['class'] ?
' class="' . htmlspecialchars($tagCode['class']) . '"' : '')
772 . ($tagCode['title'] ?
' title="' . htmlspecialchars($tagCode['title']) . '"' : '')
773 . ($external ?
' data-htmlarea-external="1"' : '')
774 . ($error ?
' rteerror="' . htmlspecialchars($error) . '" style="background-color: yellow; border:2px red solid; color: black;"' : '') . '>';
777 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'])) {
780 'currentBlock' => $v,
782 'tagCode' => $tagCode,
783 'external' => $external,
786 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksRte_PostProc'] as $objRef) {
787 $processor = GeneralUtility
::getUserObj($objRef);
788 $blockSplit[$k] = $processor->modifyParamsLinksRte($parameters, $this);
791 $blockSplit[$k] = $bTag . $this->TS_links_rte($this->removeFirstAndLastTag($blockSplit[$k])) . $eTag;
796 return implode('', $blockSplit);
800 * Preserve special tags
802 * @param string $value Content input
803 * @return string Content output
805 public function TS_preserve_db($value)
807 if (!$this->preserveTags
) {
810 // Splitting into blocks for processing (span-tags are used for special tags)
811 $blockSplit = $this->splitIntoBlock('span', $value);
812 foreach ($blockSplit as $k => $v) {
815 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v));
816 if ($attribArray['specialtag']) {
817 $theTag = rawurldecode($attribArray['specialtag']);
818 $theTagName = $this->getFirstTagName($theTag);
819 $blockSplit[$k] = $theTag . $this->removeFirstAndLastTag($blockSplit[$k]) . '</' . $theTagName . '>';
823 return implode('', $blockSplit);
827 * Preserve special tags
829 * @param string $value Content input
830 * @return string Content output
832 public function TS_preserve_rte($value)
834 if (!$this->preserveTags
) {
837 $blockSplit = $this->splitIntoBlock($this->preserveTags
, $value);
838 foreach ($blockSplit as $k => $v) {
841 $blockSplit[$k] = '<span specialtag="' . rawurlencode($this->getFirstTag($v)) . '">' . $this->removeFirstAndLastTag($blockSplit[$k]) . '</span>';
844 return implode('', $blockSplit);
848 * Transformation handler: 'ts_transform' + 'css_transform' / direction: "db"
849 * Cleaning (->db) for standard content elements (ts)
851 * @param string $value Content input
852 * @param bool $css If TRUE, the transformation was "css_transform", otherwise "ts_transform
853 * @return string Content output
854 * @see TS_transform_rte()
856 public function TS_transform_db($value, $css = false
)
858 // Safety... so forever loops are avoided (they should not occur, but an error would potentially do this...)
859 $this->TS_transform_db_safecounter
--;
860 if ($this->TS_transform_db_safecounter
< 0) {
863 // Split the content from RTE by the occurrence of these blocks:
864 $blockSplit = $this->splitIntoBlock('TABLE,BLOCKQUOTE,' . ($this->procOptions
['preserveDIVSections'] ?
'DIV,' : '') . $this->blockElementList
, $value);
866 $aC = count($blockSplit);
867 // Avoid superfluous linebreaks by transform_db after ending headListTag
868 while ($aC && trim($blockSplit[$aC - 1]) === '') {
869 unset($blockSplit[$aC - 1]);
870 $aC = count($blockSplit);
872 // Traverse the blocks
873 foreach ($blockSplit as $k => $v) {
875 $lastBR = $cc == $aC ?
'' : LF
;
879 $tag = $this->getFirstTag($v);
880 $tagName = strtolower($this->getFirstTagName($v));
881 // Process based on the tag:
900 $blockSplit[$k] = $tag . $this->TS_transform_db($this->removeFirstAndLastTag($blockSplit[$k]), $css) . '</' . $tagName . '>' . $lastBR;
906 $blockSplit[$k] = preg_replace(('/[' . LF
. CR
. ']+/'), ' ', $this->transformStyledATags($blockSplit[$k])) . $lastBR;
910 // Tables are NOT allowed in any form (unless preserveTables is set or CSS is the mode)
911 if (!$this->procOptions
['preserveTables'] && !$css) {
912 $blockSplit[$k] = $this->TS_transform_db($this->removeTables($blockSplit[$k]));
914 $blockSplit[$k] = preg_replace(('/[' . LF
. CR
. ']+/'), ' ', $this->transformStyledATags($blockSplit[$k])) . $lastBR;
929 $attribArray = $this->get_tag_attributes_classic($tag);
930 // Processing inner content here:
931 $innerContent = $this->HTMLcleaner_db($this->removeFirstAndLastTag($blockSplit[$k]));
932 $blockSplit[$k] = '<' . $tagName . ($attribArray['align'] ?
' align="' . htmlspecialchars($attribArray['align']) . '"' : '') . ($attribArray['class'] ?
' class="' . htmlspecialchars($attribArray['class']) . '"' : '') . '>' . $innerContent . '</' . $tagName . '>' . $lastBR;
934 // Eliminate true linebreaks inside Hx tags
935 $blockSplit[$k] = preg_replace(('/[' . LF
. CR
. ']+/'), ' ', $this->transformStyledATags($blockSplit[$k])) . $lastBR;
939 // Eliminate true linebreaks inside other headlist tags
940 $blockSplit[$k] = preg_replace(('/[' . LF
. CR
. ']+/'), ' ', $this->transformStyledATags($blockSplit[$k])) . $lastBR;
944 if (trim($blockSplit[$k]) !== '') {
945 $blockSplit[$k] = preg_replace('/<hr\\/>/', '<hr />', $blockSplit[$k]);
946 // Remove linebreaks preceding hr tags
947 $blockSplit[$k] = preg_replace('/[' . LF
. CR
. ']+<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/', '<$1$2/>', $blockSplit[$k]);
948 // Remove linebreaks following hr tags
949 $blockSplit[$k] = preg_replace('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>[' . LF
. CR
. ']+/', '<$1$2/>', $blockSplit[$k]);
950 // Replace other linebreaks with space
951 $blockSplit[$k] = preg_replace('/[' . LF
. CR
. ']+/', ' ', $blockSplit[$k]);
952 $blockSplit[$k] = $this->divideIntoLines($blockSplit[$k]) . $lastBR;
953 $blockSplit[$k] = $this->transformStyledATags($blockSplit[$k]);
955 unset($blockSplit[$k]);
959 $this->TS_transform_db_safecounter++
;
960 return implode('', $blockSplit);
964 * Wraps a-tags that contain a style attribute with a span-tag
966 * @param string $value Content input
967 * @return string Content output
969 public function transformStyledATags($value)
971 $blockSplit = $this->splitIntoBlock('A', $value);
972 foreach ($blockSplit as $k => $v) {
973 // If an A-tag was found
975 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v), 1);
976 // If "style" attribute is set and rteerror is not set!
977 if ($attribArray['style'] && !$attribArray['rteerror']) {
978 $attribArray_copy['style'] = $attribArray['style'];
979 unset($attribArray['style']);
980 $bTag = '<span ' . GeneralUtility
::implodeAttributes($attribArray_copy, 1) . '><a ' . GeneralUtility
::implodeAttributes($attribArray, 1) . '>';
981 $eTag = '</a></span>';
982 $blockSplit[$k] = $bTag . $this->removeFirstAndLastTag($blockSplit[$k]) . $eTag;
986 return implode('', $blockSplit);
990 * Transformation handler: 'ts_transform' + 'css_transform' / direction: "rte"
991 * Set (->rte) for standard content elements (ts)
993 * @param string Content input
994 * @param bool If TRUE, the transformation was "css_transform", otherwise "ts_transform
995 * @return string Content output
996 * @see TS_transform_db()
998 public function TS_transform_rte($value, $css = 0)
1000 // Split the content from database by the occurrence of the block elements
1001 $blockElementList = 'TABLE,BLOCKQUOTE,' . ($this->procOptions
['preserveDIVSections'] ?
'DIV,' : '') . $this->blockElementList
;
1002 $blockSplit = $this->splitIntoBlock($blockElementList, $value);
1003 // Traverse the blocks
1004 foreach ($blockSplit as $k => $v) {
1006 // Inside one of the blocks:
1008 $tag = $this->getFirstTag($v);
1009 $tagName = strtolower($this->getFirstTagName($v));
1010 $attribArray = $this->get_tag_attributes_classic($tag);
1011 // Based on tagname, we do transformations:
1030 $blockSplit[$k] = $tag . $this->TS_transform_rte($this->removeFirstAndLastTag($blockSplit[$k]), $css) . '</' . $tagName . '>';
1033 $blockSplit[$k +
1] = preg_replace('/^[ ]*' . LF
. '/', '', $blockSplit[$k +
1]);
1036 $nextFTN = $this->getFirstTagName($blockSplit[$k +
1]);
1037 $onlyLineBreaks = (preg_match('/^[ ]*' . LF
. '+[ ]*$/', $blockSplit[$k]) == 1);
1038 // If the line is followed by a block or is the last line:
1039 if (GeneralUtility
::inList($blockElementList, $nextFTN) ||
!isset($blockSplit[$k +
1])) {
1040 // If the line contains more than just linebreaks, reduce the number of trailing linebreaks by 1
1041 if (!$onlyLineBreaks) {
1042 $blockSplit[$k] = preg_replace('/(' . LF
. '*)' . LF
. '[ ]*$/', '$1', $blockSplit[$k]);
1044 // If the line contains only linebreaks, remove the leading linebreak
1045 $blockSplit[$k] = preg_replace('/^[ ]*' . LF
. '/', '', $blockSplit[$k]);
1048 // If $blockSplit[$k] is blank then unset the line, unless the line only contained linebreaks
1049 if ((string)$blockSplit[$k] === '' && !$onlyLineBreaks) {
1050 unset($blockSplit[$k]);
1052 $blockSplit[$k] = $this->setDivTags($blockSplit[$k], $this->procOptions
['useDIVasParagraphTagForRTE'] ?
'div' : 'p');
1056 return implode(LF
, $blockSplit);
1060 * Transformation handler: 'ts_strip' / direction: "db"
1061 * Removing all non-allowed tags
1063 * @param string $value Content input
1064 * @return string Content output
1066 public function TS_strip_db($value)
1068 $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')) . '>');
1072 /***************************************************************
1074 * Generic RTE transformation, analysis and helper functions
1076 **************************************************************/
1078 * Reads the file or url $url and returns the content
1080 * @param string $url Filepath/URL to read
1081 * @return string The content from the resource given as input.
1082 * @see \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl()
1084 public function getUrl($url)
1086 return GeneralUtility
::getUrl($url);
1090 * Function for cleaning content going into the database.
1091 * Content is cleaned eg. by removing unallowed HTML and ds-HSC content
1092 * 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
1094 * @param string $content Content to clean up
1095 * @param string $tagList Comma list of tags to specifically allow. Default comes from getKeepTags and is
1096 * @return string Clean content
1097 * @see getKeepTags()
1099 public function HTMLcleaner_db($content, $tagList = '')
1102 $keepTags = $this->getKeepTags('db');
1104 $keepTags = $this->getKeepTags('db', $tagList);
1106 // Default: remove unknown tags.
1107 $kUknown = $this->procOptions
['dontRemoveUnknownTags_db'] ?
1 : 0;
1108 // Default: re-convert literals to characters (that is < to <)
1109 $hSC = $this->procOptions
['dontUndoHSC_db'] ?
0 : -1;
1110 // Create additional configuration in order to honor the setting RTE.default.proc.HTMLparser_db.xhtml_cleaning=1
1111 $addConfig = array();
1112 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']) {
1113 $addConfig['xhtml'] = 1;
1115 return $this->HTMLcleaner($content, $keepTags, $kUknown, $hSC, $addConfig);
1119 * Creates an array of configuration for the HTMLcleaner function based on whether content go TO or FROM the Rich Text Editor ($direction)
1120 * 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)
1122 * @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)
1123 * @param string $tagList Comma list of tags to keep (overriding default which is to keep all + take notice of internal configuration)
1124 * @return array Configuration array
1125 * @see HTMLcleaner_db()
1127 public function getKeepTags($direction = 'rte', $tagList = '')
1129 if (!is_array($this->getKeepTags_cache
[$direction]) ||
$tagList) {
1130 // Setting up allowed tags:
1131 // If the $tagList input var is set, this will take precedence
1132 if ((string)$tagList !== '') {
1133 $keepTags = array_flip(GeneralUtility
::trimExplode(',', $tagList, true
));
1135 // Default is to get allowed/denied tags from internal array of processing options:
1136 // Construct default list of tags to keep:
1137 $typoScript_list = 'b,i,u,a,img,br,div,center,pre,font,hr,sub,sup,p,strong,em,li,ul,ol,blockquote,strike,span';
1138 $keepTags = array_flip(GeneralUtility
::trimExplode(',', $typoScript_list . ',' . strtolower($this->procOptions
['allowTags']), true
));
1139 // For tags to deny, remove them from $keepTags array:
1140 $denyTags = GeneralUtility
::trimExplode(',', $this->procOptions
['denyTags'], true
);
1141 foreach ($denyTags as $dKe) {
1142 unset($keepTags[$dKe]);
1145 // Based on the direction of content, set further options:
1146 switch ($direction) {
1148 if (!isset($this->procOptions
['transformBoldAndItalicTags']) ||
$this->procOptions
['transformBoldAndItalicTags']) {
1149 // Transform bold/italics tags to strong/em
1150 if (isset($keepTags['b'])) {
1151 $keepTags['b'] = array('remap' => 'STRONG');
1153 if (isset($keepTags['i'])) {
1154 $keepTags['i'] = array('remap' => 'EM');
1157 // 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.
1158 list($keepTags) = $this->HTMLparserConfig($this->procOptions
['HTMLparser_rte.'], $keepTags);
1161 if (!isset($this->procOptions
['transformBoldAndItalicTags']) ||
$this->procOptions
['transformBoldAndItalicTags']) {
1162 // Transform strong/em back to bold/italics:
1163 if (isset($keepTags['strong'])) {
1164 $keepTags['strong'] = array('remap' => 'b');
1166 if (isset($keepTags['em'])) {
1167 $keepTags['em'] = array('remap' => 'i');
1170 // Setting up span tags if they are allowed:
1171 if (isset($keepTags['span'])) {
1172 $classes = array_merge(array(''), $this->allowedClasses
);
1173 $keepTags['span'] = array(
1174 'allowedAttribs' => 'id,class,style,title,lang,xml:lang,dir,itemscope,itemtype,itemprop',
1175 'fixAttrib' => array(
1178 'removeIfFalse' => 1
1181 'rmTagIfNoAttrib' => 1
1183 if (!$this->procOptions
['allowedClasses']) {
1184 unset($keepTags['span']['fixAttrib']['class']['list']);
1187 // Setting up font tags if they are allowed:
1188 if (isset($keepTags['font'])) {
1189 $colors = array_merge(array(''), GeneralUtility
::trimExplode(',', $this->procOptions
['allowedFontColors'], true
));
1190 $keepTags['font'] = array(
1191 'allowedAttribs' => 'face,color,size',
1192 'fixAttrib' => array(
1194 'removeIfFalse' => 1
1197 'removeIfFalse' => 1,
1201 'removeIfFalse' => 1
1204 'rmTagIfNoAttrib' => 1
1206 if (!$this->procOptions
['allowedFontColors']) {
1207 unset($keepTags['font']['fixAttrib']['color']['list']);
1210 // Setting further options, getting them from the processiong options:
1211 $TSc = $this->procOptions
['HTMLparser_db.'];
1212 if (!$TSc['globalNesting']) {
1213 $TSc['globalNesting'] = 'b,i,u,a,center,font,sub,sup,strong,em,strike,span';
1215 if (!$TSc['noAttrib']) {
1216 $TSc['noAttrib'] = 'b,i,u,br,center,hr,sub,sup,strong,em,li,ul,ol,blockquote,strike';
1218 // Transforming the array from TypoScript to regular array:
1219 list($keepTags) = $this->HTMLparserConfig($TSc, $keepTags);
1222 // Caching (internally, in object memory) the result unless tagList is set:
1224 $this->getKeepTags_cache
[$direction] = $keepTags;
1230 return $this->getKeepTags_cache
[$direction];
1234 * 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.
1235 * This point is to resolve the HTML-code returned from RTE into ordinary lines so it's 'human-readable'
1236 * The function ->setDivTags does the opposite.
1237 * This function processes content to go into the database.
1239 * @param string $value Value to process.
1240 * @param int $count Recursion brake. Decremented on each recursion down to zero. Default is 5 (which equals the allowed nesting levels of p/div tags).
1241 * @param bool $returnArray If TRUE, an array with the lines is returned, otherwise a string of the processed input value.
1242 * @return string Processed input value.
1245 public function divideIntoLines($value, $count = 5, $returnArray = false
)
1247 // Setting configuration for processing:
1248 $allowTagsOutside = GeneralUtility
::trimExplode(',', strtolower($this->procOptions
['allowTagsOutside'] ?
'hr,' . $this->procOptions
['allowTagsOutside'] : 'hr,img'), true
);
1249 $remapParagraphTag = strtoupper($this->procOptions
['remapParagraphTag']);
1250 $divSplit = $this->splitIntoBlock('div,p', $value, 1);
1251 // Setting the third param to 1 will eliminate false end-tags. Maybe this is a good thing to do...?
1252 if ($this->procOptions
['keepPDIVattribs']) {
1253 $keepAttribListArr = GeneralUtility
::trimExplode(',', strtolower($this->procOptions
['keepPDIVattribs']), true
);
1255 $keepAttribListArr = array();
1257 // Returns plainly the value if there was no div/p sections in it
1258 if (count($divSplit) <= 1 ||
$count <= 0) {
1259 // Wrap hr tags with LF's
1260 $newValue = preg_replace('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/i', LF
. '<$1$2/>' . LF
, $value);
1261 $newValue = preg_replace('/' . LF
. LF
. '/i', LF
, $newValue);
1262 $newValue = preg_replace('/(^' . LF
. ')|(' . LF
. '$)/i', '', $newValue);
1265 // Traverse the splitted sections:
1266 foreach ($divSplit as $k => $v) {
1269 $v = $this->removeFirstAndLastTag($v);
1270 // Fetching 'sub-lines' - which will explode any further p/div nesting...
1271 $subLines = $this->divideIntoLines($v, $count - 1, 1);
1272 // 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')
1273 if (is_array($subLines)) {
1275 //... but if NO subsection was found, we process it as a TRUE line without erronous content:
1276 $subLines = array($subLines);
1277 // process break-tags, if configured for. Simply, the breaktags will here be treated like if each was a line of content...
1278 if (!$this->procOptions
['dontConvBRtoParagraph']) {
1279 $subLines = preg_split('/<br[[:space:]]*[\\/]?>/i', $v);
1281 // Traverse sublines (there is typically one, except if <br/> has been converted to lines as well!)
1282 foreach ($subLines as $sk => $value) {
1283 // Clear up the subline for DB.
1284 $subLines[$sk] = $this->HTMLcleaner_db($subLines[$sk]);
1285 // Get first tag, attributes etc:
1286 $fTag = $this->getFirstTag($divSplit[$k]);
1287 $tagName = strtolower($this->getFirstTagName($divSplit[$k]));
1288 $attribs = $this->get_tag_attributes($fTag);
1289 // Keep attributes (lowercase)
1290 $newAttribs = array();
1291 if (!empty($keepAttribListArr)) {
1292 foreach ($keepAttribListArr as $keepA) {
1293 if (isset($attribs[0][$keepA])) {
1294 $newAttribs[$keepA] = $attribs[0][$keepA];
1299 if (!$this->procOptions
['skipAlign'] && trim($attribs[0]['align']) !== '' && strtolower($attribs[0]['align']) != 'left') {
1300 // Set to value, but not 'left'
1301 $newAttribs['align'] = strtolower($attribs[0]['align']);
1304 // Set to whatever value
1305 if (!$this->procOptions
['skipClass'] && trim($attribs[0]['class']) !== '') {
1306 if (empty($this->allowedClasses
) ||
in_array($attribs[0]['class'], $this->allowedClasses
)) {
1307 $newAttribs['class'] = $attribs[0]['class'];
1309 $classes = GeneralUtility
::trimExplode(' ', $attribs[0]['class'], true
);
1310 $newClasses = array();
1311 foreach ($classes as $class) {
1312 if (in_array($class, $this->allowedClasses
)) {
1313 $newClasses[] = $class;
1316 if (!empty($newClasses)) {
1317 $newAttribs['class'] = implode(' ', $newClasses);
1321 // Remove any line break char (10 or 13)
1322 $subLines[$sk] = preg_replace('/' . LF
. '|' . CR
. '/', '', $subLines[$sk]);
1323 // If there are any attributes or if we are supposed to remap the tag, then do so:
1324 if (!empty($newAttribs) && $remapParagraphTag !== '1') {
1325 if ($remapParagraphTag === 'P') {
1328 if ($remapParagraphTag === 'DIV') {
1331 $subLines[$sk] = '<' . trim($tagName . ' ' . $this->compileTagAttribs($newAttribs)) . '>' . $subLines[$sk] . '</' . $tagName . '>';
1335 // Add the processed line(s)
1336 $divSplit[$k] = implode(LF
, $subLines);
1337 // If it turns out the line is just blank (containing a possibly) then just make it pure blank.
1338 // But, prevent filtering of lines that are blank in sense above, but whose tags contain attributes.
1339 // Those attributes should have been filtered before; if they are still there they must be considered as possible content.
1340 if (trim(strip_tags($divSplit[$k])) == ' ' && !preg_match('/\\<(img)(\\s[^>]*)?\\/?>/si', $divSplit[$k]) && !preg_match('/\\<([^>]*)?( align| class| style| id| title| dir| lang| xml:lang)([^>]*)?>/si', trim($divSplit[$k]))) {
1345 // Remove positions which are outside div/p tags and without content
1346 $divSplit[$k] = trim(strip_tags($divSplit[$k], '<' . implode('><', $allowTagsOutside) . '>'));
1347 // Wrap hr tags with LF's
1348 $divSplit[$k] = preg_replace('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/i', LF
. '<$1$2/>' . LF
, $divSplit[$k]);
1349 $divSplit[$k] = preg_replace('/' . LF
. LF
. '/i', LF
, $divSplit[$k]);
1350 $divSplit[$k] = preg_replace('/(^' . LF
. ')|(' . LF
. '$)/i', '', $divSplit[$k]);
1351 if ((string)$divSplit[$k] === '') {
1352 unset($divSplit[$k]);
1357 return $returnArray ?
$divSplit : implode(LF
, $divSplit);
1361 * Converts all lines into <div></div>/<p></p>-sections (unless the line is a div-section already)
1362 * For processing of content going FROM database TO RTE.
1364 * @param string $value Value to convert
1365 * @param string $dT Tag to wrap with. Either "p" or "div" should it be. Lowercase preferably.
1366 * @return string Processed value.
1367 * @see divideIntoLines()
1369 public function setDivTags($value, $dT = 'p')
1371 // First, setting configuration for the HTMLcleaner function. This will process each line between the <div>/<p> section on their way to the RTE
1372 $keepTags = $this->getKeepTags('rte');
1373 // Default: remove unknown tags.
1374 $kUknown = $this->procOptions
['dontProtectUnknownTags_rte'] ?
0 : 'protect';
1375 // Default: re-convert literals to characters (that is < to <)
1376 $hSC = $this->procOptions
['dontHSC_rte'] ?
0 : 1;
1377 $convNBSP = !$this->procOptions
['dontConvAmpInNBSP_rte'] ?
1 : 0;
1378 // Divide the content into lines, based on LF:
1379 $parts = explode(LF
, $value);
1380 foreach ($parts as $k => $v) {
1381 // Processing of line content:
1382 // If the line is blank, set it to
1383 if (trim($parts[$k]) === '') {
1384 $parts[$k] = ' ';
1386 // Clean the line content:
1387 $parts[$k] = $this->HTMLcleaner($parts[$k], $keepTags, $kUknown, $hSC);
1389 $parts[$k] = str_replace('&nbsp;', ' ', $parts[$k]);
1392 // Wrapping the line in <$dT> if not already wrapped and does not contain an hr tag
1393 if (!preg_match('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/i', $parts[$k])) {
1394 $testStr = strtolower(trim($parts[$k]));
1395 if (substr($testStr, 0, 4) != '<div' ||
substr($testStr, -6) != '</div>') {
1396 if (substr($testStr, 0, 2) != '<p' ||
substr($testStr, -4) != '</p>') {
1397 // Only set p-tags if there is not already div or p tags:
1398 $parts[$k] = '<' . $dT . '>' . $parts[$k] . '</' . $dT . '>';
1404 return implode(LF
, $parts);
1409 * Returns SiteURL based on thisScript.
1411 * @return string Value of GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
1412 * @see \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv()
1414 public function siteUrl()
1416 return GeneralUtility
::getIndpEnv('TYPO3_SITE_URL');
1420 * Remove all tables from incoming code
1421 * 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.
1423 * @param string $value Input value
1424 * @param string $breakChar Break character to use for linebreaks.
1425 * @return string Output value
1427 public function removeTables($value, $breakChar = '<br />')
1429 // Splitting value into table blocks:
1430 $tableSplit = $this->splitIntoBlock('table', $value);
1431 // Traverse blocks of tables:
1432 foreach ($tableSplit as $k => $v) {
1434 $tableSplit[$k] = '';
1435 $rowSplit = $this->splitIntoBlock('tr', $v);
1436 foreach ($rowSplit as $k2 => $v2) {
1438 $cellSplit = $this->getAllParts($this->splitIntoBlock('td', $v2), 1, 0);
1439 foreach ($cellSplit as $k3 => $v3) {
1440 $tableSplit[$k] .= $v3 . $breakChar;
1446 // Implode it all again:
1447 return implode($breakChar, $tableSplit);
1451 * Default tag mapping for TS
1453 * @param string $code Input code to process
1454 * @param string $direction Direction To databsae (db) or from database to RTE (rte)
1455 * @return string Processed value
1457 public function defaultTStagMapping($code, $direction = 'rte')
1459 if ($direction == 'db') {
1460 $code = $this->mapTags($code, array(
1466 if ($direction == 'rte') {
1467 $code = $this->mapTags($code, array(
1477 * Finds width and height from attrib-array
1478 * If the width and height is found in the style-attribute, use that!
1480 * @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
1481 * @return array Integer w/h in key 0/1. Zero is returned if not found.
1483 public function getWHFromAttribs($attribArray)
1485 $style = trim($attribArray['style']);
1487 $regex = '[[:space:]]*:[[:space:]]*([0-9]*)[[:space:]]*px';
1490 preg_match('/width' . $regex . '/i', $style, $reg);
1493 preg_match('/height' . $regex . '/i', $style, $reg);
1497 $w = $attribArray['width'];
1500 $h = $attribArray['height'];
1502 return array((int)$w, (int)$h);
1506 * Parse <A>-tag href and return status of email,external,file or page
1508 * @param string $url URL to analyse.
1509 * @return array Information in an array about the URL
1511 public function urlInfoForLinkTags($url)
1515 if (substr(strtolower($url), 0, 7) == 'mailto:') {
1516 $info['url'] = trim(substr($url, 7));
1517 $info['type'] = 'email';
1518 } elseif (strpos($url, '?file:') !== false
) {
1519 $info['type'] = 'file';
1520 $info['url'] = rawurldecode(substr($url, strpos($url, '?file:') +
1));
1522 $curURL = $this->siteUrl();
1523 $urlLength = strlen($url);
1524 for ($a = 0; $a < $urlLength; $a++
) {
1525 if ($url[$a] != $curURL[$a]) {
1529 $info['relScriptPath'] = substr($curURL, $a);
1530 $info['relUrl'] = substr($url, $a);
1531 $info['url'] = $url;
1532 $info['type'] = 'ext';
1533 $siteUrl_parts = parse_url($url);
1534 $curUrl_parts = parse_url($curURL);
1535 // Hosts should match
1536 if ($siteUrl_parts['host'] == $curUrl_parts['host'] && (!$info['relScriptPath'] ||
defined('TYPO3_mainDir') && substr($info['relScriptPath'], 0, strlen(TYPO3_mainDir
)) == TYPO3_mainDir
)) {
1537 // If the script path seems to match or is empty (FE-EDIT)
1538 // New processing order 100502
1539 $uP = parse_url($info['relUrl']);
1540 if ($info['relUrl'] === '#' . $siteUrl_parts['fragment']) {
1541 $info['url'] = $info['relUrl'];
1542 $info['type'] = 'anchor';
1543 } elseif (!trim($uP['path']) ||
$uP['path'] === 'index.php') {
1544 // URL is a page (id parameter)
1545 $pp = preg_split('/^id=/', $uP['query']);
1546 $pp[1] = preg_replace('/&id=[^&]*/', '', $pp[1]);
1547 $parameters = explode('&', $pp[1]);
1548 $id = array_shift($parameters);
1550 $info['pageid'] = $id;
1551 $info['cElement'] = $uP['fragment'];
1552 $info['url'] = $id . ($info['cElement'] ?
'#' . $info['cElement'] : '');
1553 $info['type'] = 'page';
1554 $info['query'] = $parameters[0] ?
'&' . implode('&', $parameters) : '';
1557 $info['url'] = $info['relUrl'];
1558 $info['type'] = 'file';
1561 unset($info['relScriptPath']);
1562 unset($info['relUrl']);
1569 * Converting <A>-tags to absolute URLs (+ setting rtekeep attribute)
1571 * @param string $value Content input
1572 * @param bool $dontSetRTEKEEP If TRUE, then the "rtekeep" attribute will not be set.
1573 * @return string Content output
1575 public function TS_AtagToAbs($value, $dontSetRTEKEEP = false
)
1577 $blockSplit = $this->splitIntoBlock('A', $value);
1578 foreach ($blockSplit as $k => $v) {
1581 $attribArray = $this->get_tag_attributes_classic($this->getFirstTag($v), 1);
1582 // Checking if there is a scheme, and if not, prepend the current url.
1583 // ONLY do this if href has content - the <a> tag COULD be an anchor and if so, it should be preserved...
1584 if ($attribArray['href'] !== '') {
1585 $uP = parse_url(strtolower($attribArray['href']));
1586 if (!$uP['scheme']) {
1587 $attribArray['href'] = $this->siteUrl() . substr($attribArray['href'], strlen($this->relBackPath
));
1588 } elseif ($uP['scheme'] != 'mailto') {
1589 $attribArray['data-htmlarea-external'] = 1;
1592 $attribArray['rtekeep'] = 1;
1594 if (!$dontSetRTEKEEP) {
1595 $attribArray['rtekeep'] = 1;
1597 $bTag = '<a ' . GeneralUtility
::implodeAttributes($attribArray, 1) . '>';
1599 $blockSplit[$k] = $bTag . $this->TS_AtagToAbs($this->removeFirstAndLastTag($blockSplit[$k])) . $eTag;
1602 return implode('', $blockSplit);
1606 * Apply plain image settings to the dimensions of the image
1608 * @param array $imageInfo: info array of the image
1609 * @param array $attribArray: array of attributes of an image tag
1611 * @return array a modified attributes array
1613 protected function applyPlainImageModeSettings($imageInfo, $attribArray)
1615 if ($this->procOptions
['plainImageMode']) {
1616 // Perform corrections to aspect ratio based on configuration
1617 switch ((string)$this->procOptions
['plainImageMode']) {
1618 case 'lockDimensions':
1619 $attribArray['width'] = $imageInfo[0];
1620 $attribArray['height'] = $imageInfo[1];
1622 case 'lockRatioWhenSmaller':
1623 if ($attribArray['width'] > $imageInfo[0]) {
1624 $attribArray['width'] = $imageInfo[0];
1627 if ($imageInfo[0] > 0) {
1628 $attribArray['height'] = round($attribArray['width'] * ($imageInfo[1] / $imageInfo[0]));
1633 return $attribArray;
1637 * @return \TYPO3\CMS\Core\Log\Logger
1639 protected function getLogger()
1641 /** @var $logManager \TYPO3\CMS\Core\Log\LogManager */
1642 $logManager = GeneralUtility
::makeInstance(\TYPO3\CMS\Core\Log\LogManager
::class);
1644 return $logManager->getLogger(get_class($this));