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