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