4d64c2602b7044c790c7f5680e7221392941b051
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Html / RteHtmlParser.php
1 <?php
2 namespace TYPO3\CMS\Core\Html;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
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.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\LinkHandling\LinkService;
19 use TYPO3\CMS\Core\Log\LogManager;
20 use TYPO3\CMS\Core\Resource;
21 use TYPO3\CMS\Core\Utility\GeneralUtility;
22 use TYPO3\CMS\Frontend\Service\TypoLinkCodecService;
23
24 /**
25 * Class for parsing HTML for the Rich Text Editor. (also called transformations)
26 *
27 * Concerning line breaks:
28 * Regardless if LF (Unix-style) or CRLF (Windows) was put in, the HtmlParser works with LFs and migrates all
29 * line breaks to LFs internally, however when all transformations are done, all LFs are transformed to CRLFs.
30 * This means: RteHtmlParser always returns CRLFs to be maximum compatible with all formats.
31 */
32 class RteHtmlParser extends HtmlParser
33 {
34 /**
35 * List of elements that are not wrapped into a "p" tag while doing the transformation.
36 * @var string
37 */
38 public $blockElementList = 'DIV,TABLE,BLOCKQUOTE,PRE,UL,OL,H1,H2,H3,H4,H5,H6,ADDRESS,DL,DD,HEADER,SECTION,FOOTER,NAV,ARTICLE,ASIDE';
39
40 /**
41 * List of all tags that are allowed by default
42 * @var string
43 */
44 protected $defaultAllowedTagsList = 'b,i,u,a,img,br,div,center,pre,font,hr,sub,sup,p,strong,em,li,ul,ol,blockquote,strike,span';
45
46 /**
47 * Set this to the pid of the record manipulated by the class.
48 *
49 * @var int
50 */
51 public $recPid = 0;
52
53 /**
54 * Element reference [table]:[field], eg. "tt_content:bodytext"
55 *
56 * @var string
57 */
58 public $elRef = '';
59
60 /**
61 * Current Page TSConfig
62 *
63 * @var array
64 */
65 public $tsConfig = [];
66
67 /**
68 * Set to the TSconfig options coming from Page TSconfig
69 *
70 * @var array
71 */
72 public $procOptions = [];
73
74 /**
75 * Run-away brake for recursive calls.
76 *
77 * @var int
78 */
79 public $TS_transform_db_safecounter = 100;
80
81 /**
82 * Data caching for processing function
83 *
84 * @var array
85 */
86 public $getKeepTags_cache = [];
87
88 /**
89 * Storage of the allowed CSS class names in the RTE
90 *
91 * @var array
92 */
93 public $allowedClasses = [];
94
95 /**
96 * A list of HTML attributes for <p> tags. Because <p> tags are wrapped currently in a special handling,
97 * they have a special place for configuration via 'proc.keepPDIVattribs'
98 *
99 * @var array
100 */
101 protected $allowedAttributesForParagraphTags = [
102 'class',
103 'align',
104 'id',
105 'title',
106 'dir',
107 'lang',
108 'xml:lang',
109 'itemscope',
110 'itemtype',
111 'itemprop'
112 ];
113
114 /**
115 * Any tags that are allowed outside of <p> sections - usually similar to the block elements
116 * plus some special tags like <hr> and <img> (if images are allowed).
117 * Completely overrideable via 'proc.allowTagsOutside'
118 *
119 * @var array
120 */
121 protected $allowedTagsOutsideOfParagraphs = [
122 'address',
123 'article',
124 'aside',
125 'blockquote',
126 'div',
127 'footer',
128 'header',
129 'hr',
130 'nav',
131 'section'
132 ];
133
134 /**
135 * Initialize, setting element reference and record PID
136 *
137 * @param string $elRef Element reference, eg "tt_content:bodytext
138 * @param int $recPid PID of the record (page id)
139 * @return void
140 */
141 public function init($elRef = '', $recPid = 0)
142 {
143 $this->recPid = $recPid;
144 $this->elRef = $elRef;
145 }
146
147 /**********************************************
148 *
149 * Main function
150 *
151 **********************************************/
152 /**
153 * Transform value for RTE based on specConf in the direction specified by $direction (rte/db)
154 * This is the main function called from DataHandler and transfer data classes
155 *
156 * @param string $value Input value
157 * @param array $specConf deprecated old "defaultExtras" parsed as array
158 * @param string $direction 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.
159 * @param array $thisConfig Parsed TypoScript content configuring the RTE, probably coming from Page TSconfig.
160 * @return string Output value
161 */
162 public function RTE_transform($value, $specConf = [], $direction = 'rte', $thisConfig = [])
163 {
164 $this->tsConfig = $thisConfig;
165 $this->procOptions = (array)$thisConfig['proc.'];
166 if (isset($this->procOptions['allowedClasses.'])) {
167 $this->allowedClasses = (array)$this->procOptions['allowedClasses.'];
168 } else {
169 $this->allowedClasses = GeneralUtility::trimExplode(',', $this->procOptions['allowedClasses'], true);
170 }
171
172 // Dynamic configuration of blockElementList
173 if ($this->procOptions['blockElementList']) {
174 $this->blockElementList = $this->procOptions['blockElementList'];
175 }
176
177 // Define which attributes are allowed on <p> tags
178 if (isset($this->procOptions['allowAttributes.'])) {
179 $this->allowedAttributesForParagraphTags = $this->procOptions['allowAttributes.'];
180 } elseif (isset($this->procOptions['keepPDIVattribs'])) {
181 $this->allowedAttributesForParagraphTags = GeneralUtility::trimExplode(',', strtolower($this->procOptions['keepPDIVattribs']), true);
182 }
183 // Override tags which are allowed outside of <p> tags
184 if (isset($this->procOptions['allowTagsOutside'])) {
185 if (!isset($this->procOptions['allowTagsOutside.'])) {
186 $this->allowedTagsOutsideOfParagraphs = GeneralUtility::trimExplode(',', strtolower($this->procOptions['allowTagsOutside']), true);
187 } else {
188 $this->allowedTagsOutsideOfParagraphs = (array)$this->procOptions['allowTagsOutside.'];
189 }
190 }
191
192 // Setting modes / transformations to be called
193 if ((string)$this->procOptions['overruleMode'] !== '') {
194 $modes = GeneralUtility::trimExplode(',', $this->procOptions['overruleMode']);
195 } elseif (!empty($this->procOptions['mode'])) {
196 $modes = [$this->procOptions['mode']];
197 } else {
198 // Get parameters for rte_transformation:
199 // @deprecated since TYPO3 v8, will be removed in TYPO3 v9 - the else{} part can be removed in v9
200 GeneralUtility::deprecationLog(
201 'Argument 2 of RteHtmlParser::RTE_transform() is deprecated. Transformations should be given in $thisConfig[\'proc.\'][\'overruleMode\']'
202 );
203 $specialFieldConfiguration = BackendUtility::getSpecConfParametersFromArray($specConf['rte_transform']['parameters']);
204 $modes = GeneralUtility::trimExplode('-', $specialFieldConfiguration['mode']);
205 }
206 $modes = $this->resolveAppliedTransformationModes($direction, $modes);
207
208 $value = $this->streamlineLineBreaksForProcessing($value);
209
210 // If an entry HTML cleaner was configured, pass the content through the HTMLcleaner
211 $value = $this->runHtmlParserIfConfigured($value, 'entryHTMLparser_' . $direction);
212
213 // Traverse modes
214 foreach ($modes as $cmd) {
215 if ($direction === 'db') {
216 // Checking for user defined transformation:
217 if ($_classRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['transformation'][$cmd]) {
218 $_procObj = GeneralUtility::getUserObj($_classRef);
219 $_procObj->pObj = $this;
220 $_procObj->transformationKey = $cmd;
221 $value = $_procObj->transform_db($value, $this);
222 } else {
223 // ... else use defaults:
224 switch ($cmd) {
225 case 'detectbrokenlinks':
226 $value = $this->removeBrokenLinkMarkers($value);
227 break;
228 case 'ts_images':
229 $value = $this->TS_images_db($value);
230 break;
231 case 'ts_links':
232 $value = $this->TS_links_db($value);
233 break;
234 case 'css_transform':
235 // Transform empty paragraphs into spacing paragraphs
236 $value = str_replace('<p></p>', '<p>&nbsp;</p>', $value);
237 // Double any trailing spacing paragraph so that it does not get removed by divideIntoLines()
238 $value = preg_replace('/<p>&nbsp;<\/p>$/', '<p>&nbsp;</p>' . '<p>&nbsp;</p>', $value);
239 $value = $this->TS_transform_db($value);
240 break;
241 default:
242 // Do nothing
243 }
244 }
245 } elseif ($direction === 'rte') {
246 // Checking for user defined transformation:
247 if ($_classRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['transformation'][$cmd]) {
248 $_procObj = GeneralUtility::getUserObj($_classRef);
249 $_procObj->pObj = $this;
250 $value = $_procObj->transform_rte($value, $this);
251 } else {
252 // ... else use defaults:
253 switch ($cmd) {
254 case 'detectbrokenlinks':
255 $value = $this->markBrokenLinks($value);
256 break;
257 case 'ts_images':
258 $value = $this->TS_images_rte($value);
259 break;
260 case 'ts_links':
261 $value = $this->TS_links_rte($value);
262 break;
263 case 'css_transform':
264 $value = $this->TS_transform_rte($value);
265 break;
266 default:
267 // Do nothing
268 }
269 }
270 }
271 }
272
273 // If an exit HTML cleaner was configured, pass the content through the HTMLcleaner
274 $value = $this->runHtmlParserIfConfigured($value, 'exitHTMLparser_' . $direction);
275
276 // Final clean up of linebreaks
277 $value = $this->streamlineLineBreaksAfterProcessing($value);
278
279 return $value;
280 }
281
282 /**
283 * Ensures what transformation modes should be executed, and that they are only executed once.
284 *
285 * @param string $direction
286 * @param array $modes
287 * @return array the resolved transformation modes
288 */
289 protected function resolveAppliedTransformationModes(string $direction, array $modes)
290 {
291 $modeList = implode(',', $modes);
292
293 // Replace the shortcut "default" with all custom modes
294 $modeList = str_replace('default', 'detectbrokenlinks,css_transform,ts_images,ts_links', $modeList);
295 // Replace the shortcut "ts_css" with all custom modes
296 // @deprecated since TYPO3 v8, will be removed in TYPO3 v9 - NEXT line can be removed in v9
297 $modeList = str_replace('ts_css', 'detectbrokenlinks,css_transform,ts_images,ts_links', $modeList);
298
299 // Make list unique
300 $modes = array_unique(GeneralUtility::trimExplode(',', $modeList, true));
301 // Reverse order if direction is "rte"
302 if ($direction === 'rte') {
303 $modes = array_reverse($modes);
304 }
305
306 return $modes;
307 }
308
309 /**
310 * Runs the HTML parser if it is configured
311 * Getting additional HTML cleaner configuration. These are applied either before or after the main transformation
312 * is done and thus totally independent processing options you can set up.
313 *
314 * This is only possible via TSconfig (procOptions) currently.
315 *
316 * @param string $content
317 * @param string $configurationDirective used to look up in the procOptions if enabled, and then fetch the
318 * @return string the processed content
319 */
320 protected function runHtmlParserIfConfigured($content, $configurationDirective)
321 {
322 if ($this->procOptions[$configurationDirective]) {
323 list($keepTags, $keepNonMatchedTags, $hscMode, $additionalConfiguration) = $this->HTMLparserConfig($this->procOptions[$configurationDirective . '.']);
324 $content = $this->HTMLcleaner($content, $keepTags, $keepNonMatchedTags, $hscMode, $additionalConfiguration);
325 }
326 return $content;
327 }
328
329 /************************************
330 *
331 * Specific RTE TRANSFORMATION functions
332 *
333 *************************************/
334 /**
335 * Transformation handler: 'ts_images' / direction: "db"
336 * Processing images inserted in the RTE.
337 * This is used when content goes from the RTE to the database.
338 * Images inserted in the RTE has an absolute URL applied to the src attribute. This URL is converted to a relative URL
339 * 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.
340 * Also "magic" images are processed here.
341 *
342 * @param string $value The content from RTE going to Database
343 * @return string Processed content
344 */
345 public function TS_images_db($value)
346 {
347 // Split content by <img> tags and traverse the resulting array for processing:
348 $imgSplit = $this->splitTags('img', $value);
349 if (count($imgSplit) > 1) {
350 $siteUrl = GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
351 $sitePath = str_replace(GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST'), '', $siteUrl);
352 /** @var $resourceFactory Resource\ResourceFactory */
353 $resourceFactory = Resource\ResourceFactory::getInstance();
354 /** @var $magicImageService Resource\Service\MagicImageService */
355 $magicImageService = GeneralUtility::makeInstance(Resource\Service\MagicImageService::class);
356 $magicImageService->setMagicImageMaximumDimensions($this->tsConfig);
357 foreach ($imgSplit as $k => $v) {
358 // Image found, do processing:
359 if ($k % 2) {
360 // Get attributes
361 list($attribArray) = $this->get_tag_attributes($v, true);
362 // It's always an absolute URL coming from the RTE into the Database.
363 $absoluteUrl = trim($attribArray['src']);
364 // Make path absolute if it is relative and we have a site path which is not '/'
365 $pI = pathinfo($absoluteUrl);
366 if ($sitePath && !$pI['scheme'] && GeneralUtility::isFirstPartOfStr($absoluteUrl, $sitePath)) {
367 // If site is in a subpath (eg. /~user_jim/) this path needs to be removed because it will be added with $siteUrl
368 $absoluteUrl = substr($absoluteUrl, strlen($sitePath));
369 $absoluteUrl = $siteUrl . $absoluteUrl;
370 }
371 // Image dimensions set in the img tag, if any
372 $imgTagDimensions = $this->getWHFromAttribs($attribArray);
373 if ($imgTagDimensions[0]) {
374 $attribArray['width'] = $imgTagDimensions[0];
375 }
376 if ($imgTagDimensions[1]) {
377 $attribArray['height'] = $imgTagDimensions[1];
378 }
379 $originalImageFile = null;
380 if ($attribArray['data-htmlarea-file-uid']) {
381 // An original image file uid is available
382 try {
383 /** @var $originalImageFile Resource\File */
384 $originalImageFile = $resourceFactory->getFileObject((int)$attribArray['data-htmlarea-file-uid']);
385 } catch (Resource\Exception\FileDoesNotExistException $fileDoesNotExistException) {
386 // Log the fact the file could not be retrieved.
387 $message = sprintf('Could not find file with uid "%s"', $attribArray['data-htmlarea-file-uid']);
388 $this->getLogger()->error($message);
389 }
390 }
391 if ($originalImageFile instanceof Resource\File) {
392 // Public url of local file is relative to the site url, absolute otherwise
393 if ($absoluteUrl == $originalImageFile->getPublicUrl() || $absoluteUrl == $siteUrl . $originalImageFile->getPublicUrl()) {
394 // This is a plain image, i.e. reference to the original image
395 if ($this->procOptions['plainImageMode']) {
396 // "plain image mode" is configured
397 // Find the dimensions of the original image
398 $imageInfo = [
399 $originalImageFile->getProperty('width'),
400 $originalImageFile->getProperty('height')
401 ];
402 if (!$imageInfo[0] || !$imageInfo[1]) {
403 $filePath = $originalImageFile->getForLocalProcessing(false);
404 $imageInfo = @getimagesize($filePath);
405 }
406 $attribArray = $this->applyPlainImageModeSettings($imageInfo, $attribArray);
407 }
408 } else {
409 // Magic image case: get a processed file with the requested configuration
410 $imageConfiguration = [
411 'width' => $imgTagDimensions[0],
412 'height' => $imgTagDimensions[1]
413 ];
414 $magicImage = $magicImageService->createMagicImage($originalImageFile, $imageConfiguration);
415 $attribArray['width'] = $magicImage->getProperty('width');
416 $attribArray['height'] = $magicImage->getProperty('height');
417 $attribArray['src'] = $magicImage->getPublicUrl();
418 }
419 } elseif (!GeneralUtility::isFirstPartOfStr($absoluteUrl, $siteUrl) && !$this->procOptions['dontFetchExtPictures'] && TYPO3_MODE === 'BE') {
420 // External image from another URL: in that case, fetch image, unless the feature is disabled or we are not in backend mode
421 // Fetch the external image
422 $externalFile = GeneralUtility::getUrl($absoluteUrl);
423 if ($externalFile) {
424 $pU = parse_url($absoluteUrl);
425 $pI = pathinfo($pU['path']);
426 $extension = strtolower($pI['extension']);
427 if ($extension === 'jpg' || $extension === 'jpeg' || $extension === 'gif' || $extension === 'png') {
428 $fileName = GeneralUtility::shortMD5($absoluteUrl) . '.' . $pI['extension'];
429 // We insert this image into the user default upload folder
430 list($table, $field) = explode(':', $this->elRef);
431 /** @var Resource\Folder $folder */
432 $folder = $GLOBALS['BE_USER']->getDefaultUploadFolder($this->recPid, $table, $field);
433 /** @var Resource\File $fileObject */
434 $fileObject = $folder->createFile($fileName)->setContents($externalFile);
435 $imageConfiguration = [
436 'width' => $attribArray['width'],
437 'height' => $attribArray['height']
438 ];
439 $magicImage = $magicImageService->createMagicImage($fileObject, $imageConfiguration);
440 $attribArray['width'] = $magicImage->getProperty('width');
441 $attribArray['height'] = $magicImage->getProperty('height');
442 $attribArray['data-htmlarea-file-uid'] = $fileObject->getUid();
443 $attribArray['src'] = $magicImage->getPublicUrl();
444 }
445 }
446 } elseif (GeneralUtility::isFirstPartOfStr($absoluteUrl, $siteUrl)) {
447 // Finally, check image as local file (siteURL equals the one of the image)
448 // Image has no data-htmlarea-file-uid attribute
449 // Relative path, rawurldecoded for special characters.
450 $path = rawurldecode(substr($absoluteUrl, strlen($siteUrl)));
451 // Absolute filepath, locked to relative path of this project
452 $filepath = GeneralUtility::getFileAbsFileName($path);
453 // Check file existence (in relative directory to this installation!)
454 if ($filepath && @is_file($filepath)) {
455 // Treat it as a plain image
456 if ($this->procOptions['plainImageMode']) {
457 // If "plain image mode" has been configured
458 // Find the original dimensions of the image
459 $imageInfo = @getimagesize($filepath);
460 $attribArray = $this->applyPlainImageModeSettings($imageInfo, $attribArray);
461 }
462 // Let's try to find a file uid for this image
463 try {
464 $fileOrFolderObject = $resourceFactory->retrieveFileOrFolderObject($path);
465 if ($fileOrFolderObject instanceof Resource\FileInterface) {
466 $fileIdentifier = $fileOrFolderObject->getIdentifier();
467 /** @var Resource\AbstractFile $fileObject */
468 $fileObject = $fileOrFolderObject->getStorage()->getFile($fileIdentifier);
469 // @todo if the retrieved file is a processed file, get the original file...
470 $attribArray['data-htmlarea-file-uid'] = $fileObject->getUid();
471 }
472 } catch (Resource\Exception\ResourceDoesNotExistException $resourceDoesNotExistException) {
473 // Nothing to be done if file/folder not found
474 }
475 }
476 }
477 // Remove width and height from style attribute
478 $attribArray['style'] = preg_replace('/(?:^|[^-])(\\s*(?:width|height)\\s*:[^;]*(?:$|;))/si', '', $attribArray['style']);
479 // Must have alt attribute
480 if (!isset($attribArray['alt'])) {
481 $attribArray['alt'] = '';
482 }
483 // Convert absolute to relative url
484 if (GeneralUtility::isFirstPartOfStr($attribArray['src'], $siteUrl)) {
485 $attribArray['src'] = substr($attribArray['src'], strlen($siteUrl));
486 }
487 $imgSplit[$k] = '<img ' . GeneralUtility::implodeAttributes($attribArray, 1, 1) . ' />';
488 }
489 }
490 }
491 return implode('', $imgSplit);
492 }
493
494 /**
495 * Transformation handler: 'ts_images' / direction: "rte"
496 * Processing images from database content going into the RTE.
497 * Processing includes converting the src attribute to an absolute URL.
498 *
499 * @param string $value Content input
500 * @return string Content output
501 */
502 public function TS_images_rte($value)
503 {
504 // Split content by <img> tags and traverse the resulting array for processing:
505 $imgSplit = $this->splitTags('img', $value);
506 if (count($imgSplit) > 1) {
507 $siteUrl = GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
508 $sitePath = str_replace(GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST'), '', $siteUrl);
509 foreach ($imgSplit as $k => $v) {
510 // Image found
511 if ($k % 2) {
512 // Get the attributes of the img tag
513 list($attribArray) = $this->get_tag_attributes($v, true);
514 $absoluteUrl = trim($attribArray['src']);
515 // Transform the src attribute into an absolute url, if it not already
516 if (strtolower(substr($absoluteUrl, 0, 4)) !== 'http') {
517 // If site is in a subpath (eg. /~user_jim/) this path needs to be removed because it will be added with $siteUrl
518 $attribArray['src'] = preg_replace('#^' . preg_quote($sitePath, '#') . '#', '', $attribArray['src']);
519 $attribArray['src'] = $siteUrl . $attribArray['src'];
520 }
521 // Must have alt attribute
522 if (!isset($attribArray['alt'])) {
523 $attribArray['alt'] = '';
524 }
525 $imgSplit[$k] = '<img ' . GeneralUtility::implodeAttributes($attribArray, 1, 1) . ' />';
526 }
527 }
528 }
529 // Return processed content:
530 return implode('', $imgSplit);
531 }
532
533 /**
534 * Transformation handler: 'ts_links' / direction: "db"
535 * Processing anchor tags, and resolves them correctly again via the LinkService syntax
536 *
537 * Splits content into <a> tag blocks and processes each tag, and allows hooks to actually render
538 * the result.
539 *
540 * @param string $value Content input
541 * @return string Content output
542 * @see TS_links_rte()
543 */
544 public function TS_links_db($value)
545 {
546 $blockSplit = $this->splitIntoBlock('A', $value);
547 foreach ($blockSplit as $k => $v) {
548 if ($k % 2) {
549 list($tagAttributes) = $this->get_tag_attributes($this->getFirstTag($v), true);
550 $linkService = GeneralUtility::makeInstance(LinkService::class);
551 $linkInformation = $linkService->resolve($tagAttributes['href']);
552
553 // Modify parameters, this hook should be deprecated
554 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksDb_PostProc'])
555 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksDb_PostProc'])) {
556 $parameters = [
557 'currentBlock' => $v,
558 'linkInformation' => $linkInformation,
559 'url' => $linkInformation['href'],
560 'attributes' => $tagAttributes
561 ];
562 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksDb_PostProc'] as $objRef) {
563 $processor = GeneralUtility::getUserObj($objRef);
564 $blockSplit[$k] = $processor->modifyParamsLinksDb($parameters, $this);
565 }
566 } else {
567 // Otherwise store the link as <a> tag as default by TYPO3, with the new link service syntax
568 $tagAttributes['href'] = $linkService->asString($linkInformation);
569 $blockSplit[$k] = '<a ' . GeneralUtility::implodeAttributes($tagAttributes, true) . '>'
570 . $this->TS_links_db($this->removeFirstAndLastTag($blockSplit[$k])) . '</a>';
571 }
572 }
573 }
574 return implode('', $blockSplit);
575 }
576
577 /**
578 * Transformation handler: 'ts_links' / direction: "rte"
579 * Converting TYPO3-specific <link> tags to <a> tags
580 *
581 * This functionality is only used to convert legacy <link> tags to the new linking syntax using <a> tags, and will
582 * not be converted back to <link> tags anymore.
583 *
584 * @param string $value Content input
585 * @return string Content output
586 */
587 public function TS_links_rte($value)
588 {
589 $value = $this->TS_AtagToAbs($value);
590 // Split content by the TYPO3 pseudo tag "<link>"
591 $blockSplit = $this->splitIntoBlock('link', $value, true);
592 foreach ($blockSplit as $k => $v) {
593 // Block
594 if ($k % 2) {
595 // Split away the first "<link " part
596 $typoLinkData = explode(' ', substr($this->getFirstTag($v), 0, -1), 2)[1];
597 $tagCode = GeneralUtility::makeInstance(TypoLinkCodecService::class)->decode($typoLinkData);
598
599 // Parsing the TypoLink data. This parsing is done like in \TYPO3\CMS\Frontend\ContentObject->typoLink()
600 $linkService = GeneralUtility::makeInstance(LinkService::class);
601 $linkInformation = $linkService->resolve($tagCode['url']);
602
603 $href = $linkService->asString($linkInformation);
604
605 // Modify parameters by a hook
606 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'])) {
607 // backwards-compatibility: show an error message if the page is not found
608 $error = '';
609 if ($linkInformation['type'] === LinkService::TYPE_PAGE) {
610 $pageRecord = BackendUtility::getRecord('pages', $linkInformation['pageuid']);
611 // Page does not exist
612 if (!is_array($pageRecord)) {
613 $error = 'Page with ID ' . $linkInformation['pageuid'] . ' not found';
614 }
615 }
616 $parameters = [
617 'currentBlock' => $v,
618 'url' => $href,
619 'tagCode' => $tagCode,
620 'external' => $linkInformation['type'] === LinkService::TYPE_URL,
621 'error' => $error
622 ];
623 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_parsehtml_proc.php']['modifyParams_LinksRte_PostProc'] as $objRef) {
624 $processor = GeneralUtility::getUserObj($objRef);
625 $blockSplit[$k] = $processor->modifyParamsLinksRte($parameters, $this);
626 }
627 } else {
628 $anchorAttributes = [
629 'href' => $href,
630 'target' => $tagCode['target'],
631 'class' => $tagCode['class'],
632 'title' => $tagCode['title']
633 ];
634
635 // Setting the <a> tag
636 $blockSplit[$k] = '<a ' . GeneralUtility::implodeAttributes($anchorAttributes, true) . '>'
637 . $this->TS_links_rte($this->removeFirstAndLastTag($blockSplit[$k]))
638 . '</a>';
639 }
640 }
641 }
642 return implode('', $blockSplit);
643 }
644
645 /**
646 * Transformation handler: 'css_transform' / direction: "db"
647 * Cleaning (->db) for standard content elements (ts)
648 *
649 * @param string $value Content input
650 * @return string Content output
651 * @see TS_transform_rte()
652 */
653 public function TS_transform_db($value)
654 {
655 // Safety... so forever loops are avoided (they should not occur, but an error would potentially do this...)
656 $this->TS_transform_db_safecounter--;
657 if ($this->TS_transform_db_safecounter < 0) {
658 return $value;
659 }
660 // Split the content from RTE by the occurrence of these blocks:
661 $blockSplit = $this->splitIntoBlock($this->blockElementList, $value);
662
663 // Avoid superfluous linebreaks by transform_db after ending headListTag
664 while (count($blockSplit) > 0 && trim(end($blockSplit)) === '') {
665 array_pop($blockSplit);
666 }
667
668 // Traverse the blocks
669 foreach ($blockSplit as $k => $v) {
670 if ($k % 2) {
671 // Inside block:
672 // Init:
673 $tag = $this->getFirstTag($v);
674 $tagName = strtolower($this->getFirstTagName($v));
675 // Process based on the tag:
676 switch ($tagName) {
677 case 'blockquote':
678 case 'dd':
679 case 'div':
680 case 'header':
681 case 'section':
682 case 'footer':
683 case 'nav':
684 case 'article':
685 case 'aside':
686 $blockSplit[$k] = $tag . $this->TS_transform_db($this->removeFirstAndLastTag($blockSplit[$k])) . '</' . $tagName . '>';
687 break;
688 case 'pre':
689 break;
690 default:
691 // usually <hx> tags and <table> tags where no other block elements are within the tags
692 // Eliminate true linebreaks inside block element tags
693 $blockSplit[$k] = preg_replace(('/[' . LF . ']+/'), ' ', $blockSplit[$k]);
694 }
695 } else {
696 // NON-block:
697 if (trim($blockSplit[$k]) !== '') {
698 $blockSplit[$k] = str_replace('<hr/>', '<hr />', $blockSplit[$k]);
699 // Remove linebreaks preceding hr tags
700 $blockSplit[$k] = preg_replace('/[' . LF . ']+<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/', '<$1$2/>', $blockSplit[$k]);
701 // Remove linebreaks following hr tags
702 $blockSplit[$k] = preg_replace('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>[' . LF . ']+/', '<$1$2/>', $blockSplit[$k]);
703 // Replace other linebreaks with space
704 $blockSplit[$k] = preg_replace('/[' . LF . ']+/', ' ', $blockSplit[$k]);
705 $blockSplit[$k] = $this->divideIntoLines($blockSplit[$k]);
706 } else {
707 unset($blockSplit[$k]);
708 }
709 }
710 }
711 $this->TS_transform_db_safecounter++;
712 return implode(LF, $blockSplit);
713 }
714
715 /**
716 * Wraps a-tags that contain a style attribute with a span-tag
717 * This is not in use anymore, but was necessary before because <a> tags are transformed into <link> tags
718 * in the database, but <link> tags cannot handle style attributes. However, this is considered a
719 * bad approach as it leaves an ugly <span> tag in the database, if allowedTags=span with style attributes are
720 * allowed.
721 *
722 * @param string $value Content input
723 * @return string Content output
724 */
725 public function transformStyledATags($value)
726 {
727 $blockSplit = $this->splitIntoBlock('A', $value);
728 foreach ($blockSplit as $k => $v) {
729 // If an A-tag was found
730 if ($k % 2) {
731 list($attribArray) = $this->get_tag_attributes($this->getFirstTag($v), true);
732 // If "style" attribute is set and rteerror is not set!
733 if ($attribArray['style'] && !$attribArray['rteerror']) {
734 $attribArray_copy['style'] = $attribArray['style'];
735 unset($attribArray['style']);
736 $bTag = '<span ' . GeneralUtility::implodeAttributes($attribArray_copy, true) . '><a ' . GeneralUtility::implodeAttributes($attribArray, true) . '>';
737 $eTag = '</a></span>';
738 $blockSplit[$k] = $bTag . $this->removeFirstAndLastTag($blockSplit[$k]) . $eTag;
739 }
740 }
741 }
742 return implode('', $blockSplit);
743 }
744
745 /**
746 * Transformation handler: css_transform / direction: "rte"
747 * Set (->rte) for standard content elements (ts)
748 *
749 * @param string $value Content input
750 * @return string Content output
751 * @see TS_transform_db()
752 */
753 public function TS_transform_rte($value)
754 {
755 // Split the content from database by the occurrence of the block elements
756 $blockSplit = $this->splitIntoBlock($this->blockElementList, $value);
757 // Traverse the blocks
758 foreach ($blockSplit as $k => $v) {
759 if ($k % 2) {
760 // Inside one of the blocks:
761 // Init:
762 $tag = $this->getFirstTag($v);
763 $tagName = strtolower($this->getFirstTagName($v));
764 // Based on tagname, we do transformations:
765 switch ($tagName) {
766 case 'blockquote':
767 case 'dd':
768 case 'div':
769 case 'header':
770 case 'section':
771 case 'footer':
772 case 'nav':
773 case 'article':
774 case 'aside':
775 $blockSplit[$k] = $tag . $this->TS_transform_rte($this->removeFirstAndLastTag($blockSplit[$k])) . '</' . $tagName . '>';
776 break;
777 }
778 $blockSplit[$k + 1] = preg_replace('/^[ ]*' . LF . '/', '', $blockSplit[$k + 1]);
779 } else {
780 // NON-block:
781 $nextFTN = $this->getFirstTagName($blockSplit[$k + 1]);
782 $onlyLineBreaks = (preg_match('/^[ ]*' . LF . '+[ ]*$/', $blockSplit[$k]) == 1);
783 // If the line is followed by a block or is the last line:
784 if (GeneralUtility::inList($this->blockElementList, $nextFTN) || !isset($blockSplit[$k + 1])) {
785 // If the line contains more than just linebreaks, reduce the number of trailing linebreaks by 1
786 if (!$onlyLineBreaks) {
787 $blockSplit[$k] = preg_replace('/(' . LF . '*)' . LF . '[ ]*$/', '$1', $blockSplit[$k]);
788 } else {
789 // If the line contains only linebreaks, remove the leading linebreak
790 $blockSplit[$k] = preg_replace('/^[ ]*' . LF . '/', '', $blockSplit[$k]);
791 }
792 }
793 // If $blockSplit[$k] is blank then unset the line, unless the line only contained linebreaks
794 if ((string)$blockSplit[$k] === '' && !$onlyLineBreaks) {
795 unset($blockSplit[$k]);
796 } else {
797 $blockSplit[$k] = $this->setDivTags($blockSplit[$k]);
798 }
799 }
800 }
801 return implode(LF, $blockSplit);
802 }
803
804 /***************************************************************
805 *
806 * Generic RTE transformation, analysis and helper functions
807 *
808 **************************************************************/
809
810 /**
811 * Function for cleaning content going into the database.
812 * Content is cleaned eg. by removing unallowed HTML and ds-HSC content
813 * 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
814 *
815 * @param string $content Content to clean up
816 * @return string Clean content
817 * @see getKeepTags()
818 */
819 public function HTMLcleaner_db($content)
820 {
821 $keepTags = $this->getKeepTags('db');
822 // Default: remove unknown tags.
823 $keepUnknownTags = (bool)$this->procOptions['dontRemoveUnknownTags_db'];
824 return $this->HTMLcleaner($content, $keepTags, $keepUnknownTags);
825 }
826
827 /**
828 * Creates an array of configuration for the HTMLcleaner function based on whether content
829 * go TO or FROM the Rich Text Editor ($direction)
830 *
831 * @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)
832 * @return array Configuration array
833 * @see HTMLcleaner_db()
834 */
835 public function getKeepTags($direction = 'rte')
836 {
837 if (!is_array($this->getKeepTags_cache[$direction])) {
838 // Setting up allowed tags:
839 // Default is to get allowed/denied tags from internal array of processing options:
840 // Construct default list of tags to keep:
841 if (is_array($this->procOptions['allowTags.'])) {
842 $keepTags = implode(',', $this->procOptions['allowTags.']);
843 } else {
844 $keepTags = $this->procOptions['allowTags'];
845 }
846 $keepTags = array_flip(GeneralUtility::trimExplode(',', $this->defaultAllowedTagsList . ',' . strtolower($keepTags), true));
847 // For tags to deny, remove them from $keepTags array:
848 $denyTags = GeneralUtility::trimExplode(',', $this->procOptions['denyTags'], true);
849 foreach ($denyTags as $dKe) {
850 unset($keepTags[$dKe]);
851 }
852 // Based on the direction of content, set further options:
853 switch ($direction) {
854 case 'rte':
855 // Transforming keepTags array so it can be understood by the HTMLcleaner function.
856 // This basically converts the format of the array from TypoScript (having dots) to plain multi-dimensional array.
857 list($keepTags) = $this->HTMLparserConfig($this->procOptions['HTMLparser_rte.'], $keepTags);
858 break;
859 case 'db':
860 // Setting up span tags if they are allowed:
861 if (isset($keepTags['span'])) {
862 $keepTags['span'] = [
863 'allowedAttribs' => 'id,class,style,title,lang,xml:lang,dir,itemscope,itemtype,itemprop',
864 'fixAttrib' => [
865 'class' => [
866 'removeIfFalse' => 1
867 ]
868 ],
869 'rmTagIfNoAttrib' => 1
870 ];
871 if (!empty($this->allowedClasses)) {
872 $keepTags['span']['fixAttrib']['class']['list'] = $this->allowedClasses;
873 }
874 }
875 // Setting further options, getting them from the processing options
876 $TSc = $this->procOptions['HTMLparser_db.'];
877 if (!$TSc['globalNesting']) {
878 $TSc['globalNesting'] = 'b,i,u,a,center,font,sub,sup,strong,em,strike,span';
879 }
880 if (!$TSc['noAttrib']) {
881 $TSc['noAttrib'] = 'b,i,u,br,center,hr,sub,sup,strong,em,li,ul,ol,blockquote,strike';
882 }
883 // Transforming the array from TypoScript to regular array:
884 list($keepTags) = $this->HTMLparserConfig($TSc, $keepTags);
885 break;
886 }
887 // Caching (internally, in object memory) the result
888 $this->getKeepTags_cache[$direction] = $keepTags;
889 }
890 // Return result:
891 return $this->getKeepTags_cache[$direction];
892 }
893
894 /**
895 * This resolves the $value into parts based on <p>-sections. These are returned as lines separated by LF.
896 * This point is to resolve the HTML-code returned from RTE into ordinary lines so it's 'human-readable'
897 * The function ->setDivTags does the opposite.
898 * This function processes content to go into the database.
899 *
900 * @param string $value Value to process.
901 * @param int $count Recursion brake. Decremented on each recursion down to zero. Default is 5 (which equals the allowed nesting levels of p tags).
902 * @param bool $returnArray If TRUE, an array with the lines is returned, otherwise a string of the processed input value.
903 * @return string Processed input value.
904 * @see setDivTags()
905 */
906 public function divideIntoLines($value, $count = 5, $returnArray = false)
907 {
908 // Setting the third param will eliminate false end-tags. Maybe this is a good thing to do...?
909 $paragraphBlocks = $this->splitIntoBlock('p', $value, true);
910 // Returns plainly the content if there was no p sections in it
911 if (count($paragraphBlocks) <= 1 || $count <= 0) {
912 return $this->sanitizeLineBreaksForContentOnly($value);
913 }
914
915 // Traverse the splitted sections
916 foreach ($paragraphBlocks as $k => $v) {
917 if ($k % 2) {
918 // Inside a <p> section
919 $v = $this->removeFirstAndLastTag($v);
920 // Fetching 'sub-lines' - which will explode any further p nesting recursively
921 $subLines = $this->divideIntoLines($v, $count - 1, true);
922 // So, if there happened to be sub-nesting of p, this is written directly as the new content of THIS section. (This would be considered 'an error')
923 if (is_array($subLines)) {
924 $paragraphBlocks[$k] = implode(LF, $subLines);
925 } else {
926 //... but if NO subsection was found, we process it as a TRUE line without erroneous content:
927 $paragraphBlocks[$k] = $this->processContentWithinParagraph($subLines, $paragraphBlocks[$k]);
928 }
929 // If it turns out the line is just blank (containing a &nbsp; possibly) then just make it pure blank.
930 // But, prevent filtering of lines that are blank in sense above, but whose tags contain attributes.
931 // Those attributes should have been filtered before; if they are still there they must be considered as possible content.
932 if (trim(strip_tags($paragraphBlocks[$k])) === '&nbsp;' && !preg_match('/\\<(img)(\\s[^>]*)?\\/?>/si', $paragraphBlocks[$k]) && !preg_match('/\\<([^>]*)?( align| class| style| id| title| dir| lang| xml:lang)([^>]*)?>/si', trim($paragraphBlocks[$k]))) {
933 $paragraphBlocks[$k] = '';
934 }
935 } else {
936 // Outside a paragraph, if there is still something in there, just add a <p> tag
937 // Remove positions which are outside <p> tags and without content
938 $paragraphBlocks[$k] = trim(strip_tags($paragraphBlocks[$k], '<' . implode('><', $this->allowedTagsOutsideOfParagraphs) . '>'));
939 $paragraphBlocks[$k] = $this->sanitizeLineBreaksForContentOnly($paragraphBlocks[$k]);
940 if ((string)$paragraphBlocks[$k] === '') {
941 unset($paragraphBlocks[$k]);
942 } else {
943 // add <p> tags around the content
944 $paragraphBlocks[$k] = str_replace(strip_tags($paragraphBlocks[$k]), '<p>' . strip_tags($paragraphBlocks[$k]) . '</p>', $paragraphBlocks[$k]);
945 }
946 }
947 }
948 return $returnArray ? $paragraphBlocks : implode(LF, $paragraphBlocks);
949 }
950
951 /**
952 * Converts all lines into <p></p>-sections (unless the line has a p - tag already)
953 * For processing of content going FROM database TO RTE.
954 *
955 * @param string $value Value to convert
956 * @return string Processed value.
957 * @see divideIntoLines()
958 */
959 public function setDivTags($value)
960 {
961 // First, setting configuration for the HTMLcleaner function. This will process each line between the <div>/<p> section on their way to the RTE
962 $keepTags = $this->getKeepTags('rte');
963 // Divide the content into lines
964 $parts = explode(LF, $value);
965 foreach ($parts as $k => $v) {
966 // Processing of line content:
967 // If the line is blank, set it to &nbsp;
968 if (trim($parts[$k]) === '') {
969 $parts[$k] = '&nbsp;';
970 } else {
971 // Clean the line content, keeping unknown tags (as they can be removed in the entryHTMLparser)
972 $parts[$k] = $this->HTMLcleaner($parts[$k], $keepTags, 'protect');
973 // convert double-encoded &nbsp; into regular &nbsp; however this could also be reversed via the exitHTMLparser
974 // This was previously an option to disable called "dontConvAmpInNBSP_rte"
975 $parts[$k] = str_replace('&amp;nbsp;', '&nbsp;', $parts[$k]);
976 }
977 // Wrapping the line in <p> tags if not already wrapped and does not contain an hr tag
978 if (!preg_match('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/i', $parts[$k])) {
979 $testStr = strtolower(trim($parts[$k]));
980 if (substr($testStr, 0, 4) !== '<div' || substr($testStr, -6) !== '</div>') {
981 if (substr($testStr, 0, 2) !== '<p' || substr($testStr, -4) !== '</p>') {
982 // Only set p-tags if there is not already div or p tags:
983 $parts[$k] = '<p>' . $parts[$k] . '</p>';
984 }
985 }
986 }
987 }
988 // Implode result:
989 return implode(LF, $parts);
990 }
991
992 /**
993 * Used for transformation from RTE to DB
994 *
995 * Works on a single line within a <p> tag when storing into the database
996 * This always adds <p> tags and validates the arguments,
997 * additionally the content is cleaned up via the HTMLcleaner.
998 *
999 * @param string $content the content within the <p> tag
1000 * @param string $fullContentWithTag the whole <p> tag surrounded as well
1001 *
1002 * @return string the full <p> tag with cleaned content
1003 */
1004 protected function processContentWithinParagraph(string $content, string $fullContentWithTag)
1005 {
1006 // clean up the content
1007 $content = $this->HTMLcleaner_db($content);
1008 // Get the <p> tag, and validate the attributes
1009 $fTag = $this->getFirstTag($fullContentWithTag);
1010 // Check which attributes of the <p> tag to keep attributes
1011 if (!empty($this->allowedAttributesForParagraphTags)) {
1012 list($tagAttributes) = $this->get_tag_attributes($fTag);
1013 // Make sure the tag attributes only contain the ones that are defined to be allowed
1014 $tagAttributes = array_intersect_key($tagAttributes, array_flip($this->allowedAttributesForParagraphTags));
1015
1016 // Only allow classes that are whitelisted in $this->allowedClasses
1017 if (trim($tagAttributes['class']) !== '' && !empty($this->allowedClasses) && !in_array($tagAttributes['class'], $this->allowedClasses, true)) {
1018 $classes = GeneralUtility::trimExplode(' ', $tagAttributes['class'], true);
1019 $classes = array_intersect($classes, $this->allowedClasses);
1020 if (!empty($classes)) {
1021 $tagAttributes['class'] = implode(' ', $classes);
1022 } else {
1023 unset($tagAttributes['class']);
1024 }
1025 }
1026 } else {
1027 $tagAttributes = [];
1028 }
1029 // Remove any line break
1030 $content = str_replace(LF, '', $content);
1031 // Compile the surrounding <p> tag
1032 $content = '<' . rtrim('p ' . $this->compileTagAttribs($tagAttributes)) . '>' . $content . '</p>';
1033 return $content;
1034 }
1035
1036 /**
1037 * Wrap <hr> tags with LFs, and also remove double LFs, used when transforming from RTE to DB
1038 *
1039 * @param string $content
1040 * @return string the modified content
1041 */
1042 protected function sanitizeLineBreaksForContentOnly(string $content)
1043 {
1044 $content = preg_replace('/<(hr)(\\s[^>\\/]*)?[[:space:]]*\\/?>/i', LF . '<$1$2/>' . LF, $content);
1045 $content = str_replace(LF . LF, LF, $content);
1046 $content = preg_replace('/(^' . LF . ')|(' . LF . '$)/i', '', $content);
1047 return $content;
1048 }
1049
1050 /**
1051 * Finds width and height from attrib-array
1052 * If the width and height is found in the style-attribute, use that!
1053 *
1054 * @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
1055 * @return array Integer w/h in key 0/1. Zero is returned if not found.
1056 */
1057 public function getWHFromAttribs($attribArray)
1058 {
1059 $style = trim($attribArray['style']);
1060 $w = 0;
1061 $h = 0;
1062 if ($style) {
1063 $regex = '[[:space:]]*:[[:space:]]*([0-9]*)[[:space:]]*px';
1064 // Width
1065 $reg = [];
1066 preg_match('/width' . $regex . '/i', $style, $reg);
1067 $w = (int)$reg[1];
1068 // Height
1069 preg_match('/height' . $regex . '/i', $style, $reg);
1070 $h = (int)$reg[1];
1071 }
1072 if (!$w) {
1073 $w = $attribArray['width'];
1074 }
1075 if (!$h) {
1076 $h = $attribArray['height'];
1077 }
1078 return [(int)$w, (int)$h];
1079 }
1080
1081 /**
1082 * Parse <A>-tag href and return status of email,external,file or page
1083 * This functionality is not in use anymore
1084 *
1085 * @param string $url URL to analyse.
1086 * @return array Information in an array about the URL
1087 */
1088 public function urlInfoForLinkTags($url)
1089 {
1090 $info = [];
1091 $url = trim($url);
1092 if (substr(strtolower($url), 0, 7) === 'mailto:') {
1093 $info['url'] = trim(substr($url, 7));
1094 $info['type'] = 'email';
1095 } elseif (strpos($url, '?file:') !== false) {
1096 $info['type'] = 'file';
1097 $info['url'] = rawurldecode(substr($url, strpos($url, '?file:') + 1));
1098 } else {
1099 $curURL = GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
1100 $urlLength = strlen($url);
1101 for ($a = 0; $a < $urlLength; $a++) {
1102 if ($url[$a] != $curURL[$a]) {
1103 break;
1104 }
1105 }
1106 $info['relScriptPath'] = substr($curURL, $a);
1107 $info['relUrl'] = substr($url, $a);
1108 $info['url'] = $url;
1109 $info['type'] = 'ext';
1110 $siteUrl_parts = parse_url($url);
1111 $curUrl_parts = parse_url($curURL);
1112 // Hosts should match
1113 if ($siteUrl_parts['host'] == $curUrl_parts['host'] && (!$info['relScriptPath'] || defined('TYPO3_mainDir') && substr($info['relScriptPath'], 0, strlen(TYPO3_mainDir)) == TYPO3_mainDir)) {
1114 // If the script path seems to match or is empty (FE-EDIT)
1115 // New processing order 100502
1116 $uP = parse_url($info['relUrl']);
1117 if ($info['relUrl'] === '#' . $siteUrl_parts['fragment']) {
1118 $info['url'] = $info['relUrl'];
1119 $info['type'] = 'anchor';
1120 } elseif (!trim($uP['path']) || $uP['path'] === 'index.php') {
1121 // URL is a page (id parameter)
1122 $pp = preg_split('/^id=/', $uP['query']);
1123 $pp[1] = preg_replace('/&id=[^&]*/', '', $pp[1]);
1124 $parameters = explode('&', $pp[1]);
1125 $id = array_shift($parameters);
1126 if ($id) {
1127 $info['pageid'] = $id;
1128 $info['cElement'] = $uP['fragment'];
1129 $info['url'] = $id . ($info['cElement'] ? '#' . $info['cElement'] : '');
1130 $info['type'] = 'page';
1131 $info['query'] = $parameters[0] ? '&' . implode('&', $parameters) : '';
1132 }
1133 } else {
1134 $info['url'] = $info['relUrl'];
1135 $info['type'] = 'file';
1136 }
1137 } else {
1138 unset($info['relScriptPath']);
1139 unset($info['relUrl']);
1140 }
1141 }
1142 return $info;
1143 }
1144
1145 /**
1146 * Converting <A>-tags to absolute URLs (+ setting rtekeep attribute)
1147 *
1148 * @param string $value Content input
1149 * @param bool $dontSetRTEKEEP If TRUE, then the "rtekeep" attribute will not be set. (not in use anymore)
1150 * @return string Content output
1151 */
1152 public function TS_AtagToAbs($value, $dontSetRTEKEEP = false)
1153 {
1154 $blockSplit = $this->splitIntoBlock('A', $value);
1155 foreach ($blockSplit as $k => $v) {
1156 // Block
1157 if ($k % 2) {
1158 list($attribArray) = $this->get_tag_attributes($this->getFirstTag($v), true);
1159 // Checking if there is a scheme, and if not, prepend the current url.
1160 // ONLY do this if href has content - the <a> tag COULD be an anchor and if so, it should be preserved...
1161 if ($attribArray['href'] !== '') {
1162 $uP = parse_url(strtolower($attribArray['href']));
1163 if (!$uP['scheme']) {
1164 $attribArray['href'] = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . $attribArray['href'];
1165 }
1166 }
1167 $bTag = '<a ' . GeneralUtility::implodeAttributes($attribArray, true) . '>';
1168 $eTag = '</a>';
1169 $blockSplit[$k] = $bTag . $this->TS_AtagToAbs($this->removeFirstAndLastTag($blockSplit[$k])) . $eTag;
1170 }
1171 }
1172 return implode('', $blockSplit);
1173 }
1174
1175 /**
1176 * Apply plain image settings to the dimensions of the image
1177 *
1178 * @param array $imageInfo: info array of the image
1179 * @param array $attribArray: array of attributes of an image tag
1180 *
1181 * @return array a modified attributes array
1182 */
1183 protected function applyPlainImageModeSettings($imageInfo, $attribArray)
1184 {
1185 if ($this->procOptions['plainImageMode']) {
1186 // Perform corrections to aspect ratio based on configuration
1187 switch ((string)$this->procOptions['plainImageMode']) {
1188 case 'lockDimensions':
1189 $attribArray['width'] = $imageInfo[0];
1190 $attribArray['height'] = $imageInfo[1];
1191 break;
1192 case 'lockRatioWhenSmaller':
1193 if ($attribArray['width'] > $imageInfo[0]) {
1194 $attribArray['width'] = $imageInfo[0];
1195 }
1196 if ($imageInfo[0] > 0) {
1197 $attribArray['height'] = round($attribArray['width'] * ($imageInfo[1] / $imageInfo[0]));
1198 }
1199 break;
1200 case 'lockRatio':
1201 if ($imageInfo[0] > 0) {
1202 $attribArray['height'] = round($attribArray['width'] * ($imageInfo[1] / $imageInfo[0]));
1203 }
1204 break;
1205 }
1206 }
1207 return $attribArray;
1208 }
1209
1210 /**
1211 * Called before any processing / transformation is made
1212 * Removing any CRs (char 13) and only deal with LFs (char 10) internally.
1213 * CR has a very disturbing effect, so just remove all CR and rely on LF
1214 *
1215 * Historical note: Previously it was possible to disable this functionality via disableUnifyLineBreaks.
1216 *
1217 * @param string $content the content to process
1218 * @return string the modified content
1219 */
1220 protected function streamlineLineBreaksForProcessing(string $content)
1221 {
1222 return str_replace(CR, '', $content);
1223 }
1224
1225 /**
1226 * Called after any processing / transformation was made
1227 * just before the content is returned by the RTE parser all line breaks
1228 * get unified to be "CRLF"s again.
1229 *
1230 * Historical note: Previously it was possible to disable this functionality via disableUnifyLineBreaks.
1231 *
1232 * @param string $content the content to process
1233 * @return string the modified content
1234 */
1235 protected function streamlineLineBreaksAfterProcessing(string $content)
1236 {
1237 // Make sure no \r\n sequences has entered in the meantime
1238 $content = $this->streamlineLineBreaksForProcessing($content);
1239 // ... and then change all \n into \r\n
1240 return str_replace(LF, CRLF, $content);
1241 }
1242
1243 /**
1244 * Content Transformation from DB to RTE
1245 * Checks all <a> tags which reference a t3://page and checks if the page is available
1246 * If not, some offensive styling is added.
1247 *
1248 * @param string $content
1249 * @return string the modified content
1250 */
1251 protected function markBrokenLinks(string $content): string
1252 {
1253 $blocks = $this->splitIntoBlock('A', $content);
1254 $linkService = GeneralUtility::makeInstance(LinkService::class);
1255 foreach ($blocks as $position => $value) {
1256 if ($position % 2 === 0) {
1257 continue;
1258 }
1259 list($attributes) = $this->get_tag_attributes($this->getFirstTag($value), true);
1260 if (empty($attributes['href'])) {
1261 continue;
1262 }
1263 $hrefInformation = $linkService->resolve($attributes['href']);
1264 if ($hrefInformation['type'] === LinkService::TYPE_PAGE) {
1265 $pageRecord = BackendUtility::getRecord('pages', $hrefInformation['pageuid']);
1266 if (!is_array($pageRecord)) {
1267 // Page does not exist
1268 $attributes['data-rte-error'] = 'Page with ID ' . $hrefInformation['pageuid'] . ' not found';
1269 $styling = 'background-color: yellow; border:2px red solid; color: black;';
1270 if (empty($attributes['style'])) {
1271 $attributes['style'] = $styling;
1272 } else {
1273 $attributes['style'] .= ' ' . $styling;
1274 }
1275 }
1276 }
1277 // Always rewrite the block to allow the nested calling even if a page is found
1278 $blocks[$position] =
1279 '<a ' . GeneralUtility::implodeAttributes($attributes, true, true) . '>'
1280 . $this->markBrokenLinks($this->removeFirstAndLastTag($blocks[$position]))
1281 . '</a>';
1282 }
1283 return implode('', $blocks);
1284 }
1285
1286 /**
1287 * Content Transformation from RTE to DB
1288 * Removes link information error attributes from <a> tags that are added to broken links
1289 *
1290 * @param string $content the content to process
1291 * @return string the modified content
1292 */
1293 protected function removeBrokenLinkMarkers(string $content): string
1294 {
1295 $blocks = $this->splitIntoBlock('A', $content);
1296 foreach ($blocks as $position => $value) {
1297 if ($position % 2 === 0) {
1298 continue;
1299 }
1300 list($attributes) = $this->get_tag_attributes($this->getFirstTag($value), true);
1301 if (empty($attributes['href'])) {
1302 continue;
1303 }
1304 // Always remove the styling again (regardless of the page was found or not)
1305 // so the database does not contain ugly stuff
1306 unset($attributes['data-rte-error']);
1307 if (isset($attributes['style'])) {
1308 $attributes['style'] = trim(str_replace('background-color: yellow; border:2px red solid; color: black;', '', $attributes['style']));
1309 if (empty($attributes['style'])) {
1310 unset($attributes['style']);
1311 }
1312 }
1313 $blocks[$position] =
1314 '<a ' . GeneralUtility::implodeAttributes($attributes, true, true) . '>'
1315 . $this->removeBrokenLinkMarkers($this->removeFirstAndLastTag($blocks[$position]))
1316 . '</a>';
1317 }
1318 return implode('', $blocks);
1319 }
1320
1321 /**
1322 * Instantiates a logger
1323 *
1324 * @return \TYPO3\CMS\Core\Log\Logger
1325 */
1326 protected function getLogger()
1327 {
1328 /** @var $logManager LogManager */
1329 $logManager = GeneralUtility::makeInstance(LogManager::class);
1330 return $logManager->getLogger(get_class($this));
1331 }
1332 }