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