class.t3lib_parsehtml.php

Go to the documentation of this file.
00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 1999-2008 Kasper Skaarhoj (kasperYYYY@typo3.com)
00006 *  All rights reserved
00007 *
00008 *  This script is part of the TYPO3 project. The TYPO3 project is
00009 *  free software; you can redistribute it and/or modify
00010 *  it under the terms of the GNU General Public License as published by
00011 *  the Free Software Foundation; either version 2 of the License, or
00012 *  (at your option) any later version.
00013 *
00014 *  The GNU General Public License can be found at
00015 *  http://www.gnu.org/copyleft/gpl.html.
00016 *  A copy is found in the textfile GPL.txt and important notices to the license
00017 *  from the author is found in LICENSE.txt distributed with these scripts.
00018 *
00019 *
00020 *  This script is distributed in the hope that it will be useful,
00021 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023 *  GNU General Public License for more details.
00024 *
00025 *  This copyright notice MUST APPEAR in all copies of the script!
00026 ***************************************************************/
00027 /**
00028  * Contains class with functions for parsing HTML code.
00029  *
00030  * $Id: class.t3lib_parsehtml.php 4432 2008-11-07 03:52:22Z flyguide $
00031  * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
00032  *
00033  * @author  Kasper Skaarhoj <kasperYYYY@typo3.com>
00034  */
00035 /**
00036  * [CLASS/FUNCTION INDEX of SCRIPT]
00037  *
00038  *
00039  *
00040  *  106: class t3lib_parsehtml
00041  *  123:     function getSubpart($content, $marker)
00042  *  156:     function substituteSubpart($content,$marker,$subpartContent,$recursive=1,$keepMarker=0)
00043  *
00044  *              SECTION: Parsing HTML code
00045  *  247:     function splitIntoBlock($tag,$content,$eliminateExtraEndTags=0)
00046  *  308:     function splitIntoBlockRecursiveProc($tag,$content,&$procObj,$callBackContent,$callBackTags,$level=0)
00047  *  344:     function splitTags($tag,$content)
00048  *  378:     function getAllParts($parts,$tag_parts=1,$include_tag=1)
00049  *  396:     function removeFirstAndLastTag($str)
00050  *  412:     function getFirstTag($str)
00051  *  426:     function getFirstTagName($str,$preserveCase=FALSE)
00052  *  445:     function get_tag_attributes($tag,$deHSC=0)
00053  *  486:     function split_tag_attributes($tag)
00054  *  524:     function checkTagTypeCounts($content,$blockTags='a,b,blockquote,body,div,em,font,form,h1,h2,h3,h4,h5,h6,i,li,map,ol,option,p,pre,select,span,strong,table,td,textarea,tr,u,ul', $soloTags='br,hr,img,input,area')
00055  *
00056  *              SECTION: Clean HTML code
00057  *  617:     function HTMLcleaner($content, $tags=array(),$keepAll=0,$hSC=0,$addConfig=array())
00058  *  814:     function bidir_htmlspecialchars($value,$dir)
00059  *  837:     function prefixResourcePath($main_prefix,$content,$alternatives=array(),$suffix='')
00060  *  919:     function prefixRelPath($prefix,$srcVal,$suffix='')
00061  *  937:     function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0)
00062  *  967:     function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<')
00063  *  982:     function unprotectTags($content,$tagList='')
00064  * 1015:     function stripTagsExcept($value,$tagList)
00065  * 1038:     function caseShift($str,$flag,$cacheKey='')
00066  * 1065:     function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0)
00067  * 1093:     function get_tag_attributes_classic($tag,$deHSC=0)
00068  * 1106:     function indentLines($content, $number=1, $indentChar="\t")
00069  * 1123:     function HTMLparserConfig($TSconfig,$keepTags=array())
00070  * 1247:     function XHTML_clean($content)
00071  * 1269:     function processTag($value,$conf,$endTag,$protected=0)
00072  * 1315:     function processContent($value,$dir,$conf)
00073  *
00074  * TOTAL FUNCTIONS: 28
00075  * (This index is automatically created/updated by the extension "extdeveval")
00076  *
00077  */
00078 
00079 
00080 
00081 
00082 
00083 
00084 
00085 
00086 
00087 
00088 
00089 
00090 
00091 
00092 
00093 
00094 
00095 
00096 
00097 
00098 /**
00099  * Functions for parsing HTML.
00100  * You are encouraged to use this class in your own applications
00101  *
00102  * @author  Kasper Skaarhoj <kasperYYYY@typo3.com>
00103  * @package TYPO3
00104  * @subpackage t3lib
00105  */
00106 class t3lib_parsehtml   {
00107 
00108     protected $caseShift_cache = array();
00109 
00110     /**
00111      * Returns the first subpart encapsulated in the marker, $marker
00112      * (possibly present in $content as a HTML comment)
00113      *
00114      * @param   string      Content with subpart wrapped in fx. "###CONTENT_PART###" inside.
00115      * @param   string      Marker string, eg. "###CONTENT_PART###"
00116      * @return  string
00117      */
00118     public static function getSubpart($content, $marker) {
00119         $start = strpos($content, $marker);
00120 
00121         if ($start === false) {
00122             return '';
00123         }
00124 
00125         $start += strlen($marker);
00126         $stop   = strpos($content, $marker, $start);
00127 
00128             // Q: What shall get returned if no stop marker is given
00129             // /*everything till the end*/ or nothing?
00130         if ($stop===false) {
00131             return ''; /*substr($content, $start)*/
00132         }
00133 
00134         $content = substr($content, $start, $stop-$start);
00135 
00136         $matches = array();
00137         if (preg_match('/^([^\<]*\-\-\>)(.*)(\<\!\-\-[^\>]*)$/s', $content, $matches) === 1) {
00138             return $matches[2];
00139         }
00140 
00141         $matches = array(); // resetting $matches
00142         if (preg_match('/(.*)(\<\!\-\-[^\>]*)$/s', $content, $matches) === 1) {
00143             return $matches[1];
00144         }
00145 
00146         $matches = array(); // resetting $matches
00147         if (preg_match('/^([^\<]*\-\-\>)(.*)$/s', $content, $matches) === 1) {
00148             return $matches[2];
00149         }
00150 
00151         return $content;
00152     }
00153 
00154     /**
00155      * Substitutes a subpart in $content with the content of $subpartContent.
00156      *
00157      * @param   string      Content with subpart wrapped in fx. "###CONTENT_PART###" inside.
00158      * @param   string      Marker string, eg. "###CONTENT_PART###"
00159      * @param   array       If $subpartContent happens to be an array, it's [0] and [1] elements are wrapped around the content of the subpart (fetched by getSubpart())
00160      * @param   boolean     If $recursive is set, the function calls itself with the content set to the remaining part of the content after the second marker. This means that proceding subparts are ALSO substituted!
00161      * @param   boolean     If set, the marker around the subpart is not removed, but kept in the output
00162      * @return  string      Processed input content
00163      */
00164     public static function substituteSubpart($content, $marker, $subpartContent, $recursive = 1, $keepMarker = 0) {
00165         $start = strpos($content, $marker);
00166 
00167         if ($start === false) {
00168             return $content;
00169         }
00170 
00171         $startAM = $start + strlen($marker);
00172         $stop    = strpos($content, $marker, $startAM);
00173 
00174         if ($stop===false) {
00175             return $content;
00176         }
00177 
00178         $stopAM  = $stop + strlen($marker);
00179         $before  = substr($content, 0, $start);
00180         $after   = substr($content, $stopAM);
00181         $between = substr($content, $startAM, $stop-$startAM);
00182 
00183         if ($recursive) {
00184             $after = t3lib_parsehtml::substituteSubpart(
00185                 $after,
00186                 $marker,
00187                 $subpartContent,
00188                 $recursive,
00189                 $keepMarker
00190             );
00191         }
00192 
00193         if ($keepMarker) {
00194             $matches = array();
00195             if (preg_match('/^([^\<]*\-\-\>)(.*)(\<\!\-\-[^\>]*)$/s', $between, $matches) === 1) {
00196                 $before  .= $marker.$matches[1];
00197                 $between  = $matches[2];
00198                 $after    = $matches[3] . $marker . $after;
00199             } elseif (preg_match('/^(.*)(\<\!\-\-[^\>]*)$/s', $between, $matches) === 1) {
00200                 $before  .= $marker;
00201                 $between  = $matches[1];
00202                 $after    = $matches[2] . $marker . $after;
00203             } elseif (preg_match('/^([^\<]*\-\-\>)(.*)$/s', $between, $matches) === 1) {
00204                 $before  .= $marker . $matches[1];
00205                 $between  = $matches[2];
00206                 $after    = $marker . $after;
00207             } else  {
00208                 $before .= $marker;
00209                 $after   = $marker . $after;
00210             }
00211 
00212         } else {
00213             $matches = array();
00214             if (preg_match('/^(.*)\<\!\-\-[^\>]*$/s', $before, $matches) === 1) {
00215                 $before = $matches[1];
00216             }
00217 
00218             if (is_array($subpartContent)) {
00219                 $matches = array();
00220                 if (preg_match('/^([^\<]*\-\-\>)(.*)(\<\!\-\-[^\>]*)$/s', $between, $matches) === 1) {
00221                     $between = $matches[2];
00222                 } elseif (preg_match('/^(.*)(\<\!\-\-[^\>]*)$/s', $between, $matches)===1) {
00223                     $between = $matches[1];
00224                 } elseif (preg_match('/^([^\<]*\-\-\>)(.*)$/s', $between, $matches)===1) {
00225                     $between = $matches[2];
00226                 }
00227             }
00228 
00229             $matches = array(); // resetting $matches
00230             if (preg_match('/^[^\<]*\-\-\>(.*)$/s', $after, $matches) === 1) {
00231                 $after = $matches[1];
00232             }
00233         }
00234 
00235         if (is_array($subpartContent)) {
00236             $between = $subpartContent[0] . $between . $subpartContent[1];
00237         } else  {
00238             $between = $subpartContent;
00239         }
00240 
00241         return $before . $between . $after;
00242     }
00243 
00244     /**
00245      * Substitues multiple subparts at once
00246      *
00247      * @param   string      The content stream, typically HTML template content.
00248      * @param   array       The array of key/value pairs being subpart/content values used in the substitution. For each element in this array the function will substitute a subpart in the content stream with the content.
00249      * @return  string      The processed HTML content string.
00250      */
00251     public static function substituteSubpartArray($content, array $subpartsContent) {
00252         foreach ($subpartsContent as $subpartMarker => $subpartContent) {
00253             $content = t3lib_parsehtml::substituteSubpart(
00254                 $content,
00255                 $subpartMarker,
00256                 $subpartContent
00257             );
00258         }
00259 
00260         return $content;
00261     }
00262 
00263 
00264     /**
00265      * Substitutes a marker string in the input content
00266      * (by a simple str_replace())
00267      *
00268      * @param   string      The content stream, typically HTML template content.
00269      * @param   string      The marker string, typically on the form "###[the marker string]###"
00270      * @param   mixed       The content to insert instead of the marker string found.
00271      * @return  string      The processed HTML content string.
00272      * @see substituteSubpart()
00273      */
00274     public static function substituteMarker($content, $marker, $markContent) {
00275         return str_replace($marker, $markContent, $content);
00276     }
00277 
00278 
00279     /**
00280      * Traverses the input $markContentArray array and for each key the marker
00281      * by the same name (possibly wrapped and in upper case) will be
00282      * substituted with the keys value in the array. This is very useful if you
00283      * have a data-record to substitute in some content. In particular when you
00284      * use the $wrap and $uppercase values to pre-process the markers. Eg. a
00285      * key name like "myfield" could effectively be represented by the marker
00286      * "###MYFIELD###" if the wrap value was "###|###" and the $uppercase
00287      * boolean true.
00288      *
00289      * @param   string      The content stream, typically HTML template content.
00290      * @param   array       The array of key/value pairs being marker/content values used in the substitution. For each element in this array the function will substitute a marker in the content stream with the content.
00291      * @param   string      A wrap value - [part 1] | [part 2] - for the markers before substitution
00292      * @param   boolean     If set, all marker string substitution is done with upper-case markers.
00293      * @param   boolean     If set, all unused marker are deleted.
00294      * @return  string      The processed output stream
00295      * @see substituteMarker(), substituteMarkerInObject(), TEMPLATE()
00296      */
00297     public static function substituteMarkerArray($content, $markContentArray, $wrap = '', $uppercase = 0, $deleteUnused = 0) {
00298         if (is_array($markContentArray)) {
00299             $wrapArr = t3lib_div::trimExplode('|', $wrap);
00300 
00301             foreach ($markContentArray as $marker => $markContent) {
00302                 if ($uppercase) {
00303                         // use strtr instead of strtoupper to avoid locale problems with Turkish
00304                     $marker = strtr(
00305                         $marker,
00306                         'abcdefghijklmnopqrstuvwxyz',
00307                         'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
00308                     );
00309                 }
00310 
00311                 if (count($wrapArr) > 0) {
00312                     $marker = $wrapArr[0] . $marker . $wrapArr[1];
00313                 }
00314 
00315                 $content = str_replace($marker, $markContent, $content);
00316             }
00317 
00318             if ($deleteUnused) {
00319                 if (empty($wrap)) {
00320                     $wrapArr = array('###', '###');
00321                 }
00322 
00323                 $content = preg_replace('/'.preg_quote($wrapArr[0]).'([A-Z0-9_-|]*)'.preg_quote($wrapArr[1]).'/is', '', $content);
00324             }
00325         }
00326 
00327         return $content;
00328     }
00329 
00330 
00331 
00332 
00333 
00334 
00335 
00336     /************************************
00337      *
00338      * Parsing HTML code
00339      *
00340      ************************************/
00341 
00342     /**
00343      * Returns an array with the $content divided by tag-blocks specified with the list of tags, $tag
00344      * Even numbers in the array are outside the blocks, Odd numbers are block-content.
00345      * Use ->getAllParts() and ->removeFirstAndLastTag() to process the content if needed.
00346      *
00347      * @param   string      List of tags, comma separated.
00348      * @param   string      HTML-content
00349      * @param   boolean     If set, excessive end tags are ignored - you should probably set this in most cases.
00350      * @return  array       Even numbers in the array are outside the blocks, Odd numbers are block-content.
00351      * @see splitTags(), getAllParts(), removeFirstAndLastTag()
00352      */
00353     function splitIntoBlock($tag,$content,$eliminateExtraEndTags=0) {
00354         $tags=array_unique(t3lib_div::trimExplode(',',$tag,1));
00355         $regexStr = '/\<\/?('.implode('|', $tags).')(\s*\>|\s[^\>]*\>)/si';
00356 
00357         $parts = preg_split($regexStr, $content);
00358 
00359         $newParts=array();
00360         $pointer=strlen($parts[0]);
00361         $buffer=$parts[0];
00362         $nested=0;
00363         reset($parts);
00364         next($parts);
00365         while(list($k,$v)=each($parts)) {
00366             $isEndTag= substr($content,$pointer,2)=='</' ? 1 : 0;
00367             $tagLen = strcspn(substr($content,$pointer),'>')+1;
00368 
00369             if (!$isEndTag) {   // We meet a start-tag:
00370                 if (!$nested)   {   // Ground level:
00371                     $newParts[]=$buffer;    // previous buffer stored
00372                     $buffer='';
00373                 }
00374                 $nested++;  // We are inside now!
00375                 $mbuffer=substr($content,$pointer,strlen($v)+$tagLen);  // New buffer set and pointer increased
00376                 $pointer+=strlen($mbuffer);
00377                 $buffer.=$mbuffer;
00378             } else {    // If we meet an endtag:
00379                 $nested--;  // decrease nested-level
00380                 $eliminated=0;
00381                 if ($eliminateExtraEndTags && $nested<0)    {
00382                     $nested=0;
00383                     $eliminated=1;
00384                 } else {
00385                     $buffer.=substr($content,$pointer,$tagLen); // In any case, add the endtag to current buffer and increase pointer
00386                 }
00387                 $pointer+=$tagLen;
00388                 if (!$nested && !$eliminated)   {   // if we're back on ground level, (and not by eliminating tags...
00389                     $newParts[]=$buffer;
00390                     $buffer='';
00391                 }
00392                 $mbuffer=substr($content,$pointer,strlen($v));  // New buffer set and pointer increased
00393                 $pointer+=strlen($mbuffer);
00394                 $buffer.=$mbuffer;
00395             }
00396 
00397         }
00398         $newParts[]=$buffer;
00399         return $newParts;
00400     }
00401 
00402     /**
00403      * Splitting content into blocks *recursively* and processing tags/content with call back functions.
00404      *
00405      * @param   string      Tag list, see splitIntoBlock()
00406      * @param   string      Content, see splitIntoBlock()
00407      * @param   object      Object where call back methods are.
00408      * @param   string      Name of call back method for content; "function callBackContent($str,$level)"
00409      * @param   string      Name of call back method for tags; "function callBackTags($tags,$level)"
00410      * @param   integer     Indent level
00411      * @return  string      Processed content
00412      * @see splitIntoBlock()
00413      */
00414     function splitIntoBlockRecursiveProc($tag,$content,&$procObj,$callBackContent,$callBackTags,$level=0)   {
00415         $parts = $this->splitIntoBlock($tag,$content,TRUE);
00416         foreach($parts as $k => $v) {
00417             if ($k%2)   {
00418                 $firstTagName = $this->getFirstTagName($v, TRUE);
00419                 $tagsArray = array();
00420                 $tagsArray['tag_start'] = $this->getFirstTag($v);
00421                 $tagsArray['tag_end'] = '</'.$firstTagName.'>';
00422                 $tagsArray['tag_name'] = strtolower($firstTagName);
00423                 $tagsArray['add_level'] = 1;
00424                 $tagsArray['content'] = $this->splitIntoBlockRecursiveProc($tag,$this->removeFirstAndLastTag($v),$procObj,$callBackContent,$callBackTags,$level+$tagsArray['add_level']);
00425 
00426                 if ($callBackTags)  $tagsArray = $procObj->$callBackTags($tagsArray,$level);
00427 
00428                 $parts[$k] =
00429                     $tagsArray['tag_start'].
00430                     $tagsArray['content'].
00431                     $tagsArray['tag_end'];
00432             } else {
00433                 if ($callBackContent)   $parts[$k] = $procObj->$callBackContent($parts[$k],$level);
00434             }
00435         }
00436 
00437         return implode('',$parts);
00438     }
00439 
00440     /**
00441      * Returns an array with the $content divided by tag-blocks specified with the list of tags, $tag
00442      * Even numbers in the array are outside the blocks, Odd numbers are block-content.
00443      * Use ->getAllParts() and ->removeFirstAndLastTag() to process the content if needed.
00444      *
00445      * @param   string      List of tags
00446      * @param   string      HTML-content
00447      * @return  array       Even numbers in the array are outside the blocks, Odd numbers are block-content.
00448      * @see splitIntoBlock(), getAllParts(), removeFirstAndLastTag()
00449      */
00450     function splitTags($tag,$content)   {
00451         $tags = t3lib_div::trimExplode(',',$tag,1);
00452         $regexStr = '/\<('.implode('|', $tags).')(\s[^>]*)?\/?>/si';
00453         $parts = preg_split($regexStr, $content);
00454 
00455         $pointer = strlen($parts[0]);
00456         $newParts = array();
00457         $newParts[] = $parts[0];
00458         reset($parts);
00459         next($parts);
00460         while(list($k,$v)=each($parts)) {
00461             $tagLen = strcspn(substr($content,$pointer),'>')+1;
00462 
00463                 // Set tag:
00464             $tag = substr($content,$pointer,$tagLen);   // New buffer set and pointer increased
00465             $newParts[] = $tag;
00466             $pointer+= strlen($tag);
00467 
00468                 // Set content:
00469             $newParts[] = $v;
00470             $pointer+= strlen($v);
00471         }
00472         return $newParts;
00473     }
00474 
00475     /**
00476      * Returns an array with either tag or non-tag content of the result from ->splitIntoBlock()/->splitTags()
00477      *
00478      * @param   array       Parts generated by ->splitIntoBlock() or >splitTags()
00479      * @param   boolean     Whether to return the tag-parts (default,true) or what was outside the tags.
00480      * @param   boolean     Whether to include the tags in the tag-parts (most useful for input made by ->splitIntoBlock())
00481      * @return  array       Tag-parts/Non-tag-parts depending on input argument settings
00482      * @see splitIntoBlock(), splitTags()
00483      */
00484     function getAllParts($parts,$tag_parts=1,$include_tag=1)    {
00485         $newParts=array();
00486         foreach ($parts as $k => $v)    {
00487             if (($k+($tag_parts?0:1))%2)    {
00488                 if (!$include_tag)  $v=$this->removeFirstAndLastTag($v);
00489                 $newParts[]=$v;
00490             }
00491         }
00492         return $newParts;
00493     }
00494 
00495     /**
00496      * Removes the first and last tag in the string
00497      * Anything before the first and after the last tags respectively is also removed
00498      *
00499      * @param   string      String to process
00500      * @return  string
00501      */
00502     function removeFirstAndLastTag($str)    {
00503             // End of first tag:
00504         $start = strpos($str,'>');
00505             // Begin of last tag:
00506         $end = strrpos($str,'<');
00507             // return
00508         return substr($str, $start+1, $end-$start-1);
00509     }
00510 
00511     /**
00512      * Returns the first tag in $str
00513      * Actually everything from the begining of the $str is returned, so you better make sure the tag is the first thing...
00514      *
00515      * @param   string      HTML string with tags
00516      * @return  string
00517      */
00518     function getFirstTag($str)  {
00519             // First:
00520         $endLen = strpos($str,'>')+1;
00521         return substr($str,0,$endLen);
00522     }
00523 
00524     /**
00525      * Returns the NAME of the first tag in $str
00526      *
00527      * @param   string      HTML tag (The element name MUST be separated from the attributes by a space character! Just *whitespace* will not do)
00528      * @param   boolean     If set, then the tag is NOT converted to uppercase by case is preserved.
00529      * @return  string      Tag name in upper case
00530      * @see getFirstTag()
00531      */
00532     function getFirstTagName($str,$preserveCase=FALSE)  {
00533         $matches = array();
00534         if (preg_match('/^\s*\<([^\s\>]+)(\s|\>)/', $str, $matches)===1)    {
00535             if (!$preserveCase) {
00536                 return strtoupper($matches[1]);
00537             }
00538             return $matches[1];
00539         }
00540         return '';
00541     }
00542 
00543     /**
00544      * Returns an array with all attributes as keys. Attributes are only lowercase a-z
00545      * If a attribute is empty (shorthand), then the value for the key is empty. You can check if it existed with isset()
00546      *
00547      * @param   string      Tag: $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
00548      * @param   boolean     If set, the attribute values are de-htmlspecialchar'ed. Should actually always be set!
00549      * @return  array       array(Tag attributes,Attribute meta-data)
00550      */
00551     function get_tag_attributes($tag,$deHSC=0)  {
00552         list($components,$metaC) = $this->split_tag_attributes($tag);
00553         $name = '';  // attribute name is stored here
00554         $valuemode = false;
00555         $attributes = array();
00556         $attributesMeta = array();
00557         if (is_array($components))  {
00558             foreach ($components as $key => $val)   {
00559                 if ($val != '=')    {   // Only if $name is set (if there is an attribute, that waits for a value), that valuemode is enabled. This ensures that the attribute is assigned it's value
00560                     if ($valuemode) {
00561                         if ($name)  {
00562                             $attributes[$name] = $deHSC?t3lib_div::htmlspecialchars_decode($val):$val;
00563                             $attributesMeta[$name]['dashType']=$metaC[$key];
00564                             $name = '';
00565                         }
00566                     } else {
00567                         if ($namekey = preg_replace('/[^[:alnum:]_\:\-]/','',$val)) {
00568                             $name = strtolower($namekey);
00569                             $attributesMeta[$name]=array();
00570                             $attributesMeta[$name]['origTag']=$namekey;
00571                             $attributes[$name] = '';
00572                         }
00573                     }
00574                     $valuemode = false;
00575                 } else {
00576                     $valuemode = true;
00577                 }
00578             }
00579             return array($attributes,$attributesMeta);
00580         }
00581     }
00582 
00583     /**
00584      * Returns an array with the 'components' from an attribute list. The result is normally analyzed by get_tag_attributes
00585      * Removes tag-name if found
00586      *
00587      * @param   string      The tag or attributes
00588      * @return  array
00589      * @access private
00590      * @see t3lib_div::split_tag_attributes()
00591      */
00592     function split_tag_attributes($tag) {
00593         $matches = array();
00594         if (preg_match('/(\<[^\s]+\s+)?(.*?)\s*(\>)?$/s', $tag, $matches)!==1)  {
00595             return array(array(), array());
00596         }
00597         $tag_tmp = $matches[2];
00598 
00599         $metaValue = array();
00600         $value = array();
00601         $matches = array();
00602         if (preg_match_all('/("[^"]*"|\'[^\']*\'|[^\s"\'\=]+|\=)/s', $tag_tmp, $matches)>0) {
00603             foreach ($matches[1] as $part)  {
00604                 $firstChar = substr($part, 0, 1);
00605                 if ($firstChar=='"' || $firstChar=="'") {
00606                     $metaValue[] = $firstChar;
00607                     $value[] = substr($part, 1, -1);
00608                 } else  {
00609                     $metaValue[] = '';
00610                     $value[] = $part;
00611                 }
00612             }
00613         }
00614         return array($value,$metaValue);
00615     }
00616 
00617     /**
00618      * Checks whether block/solo tags are found in the correct amounts in HTML content
00619      * Block tags are tags which are required to have an equal amount of start and end tags, eg. "<table>...</table>"
00620      * Solo tags are tags which are required to have ONLY start tags (possibly with an XHTML ending like ".../>")
00621      * NOTICE: Correct XHTML might actually fail since "<br></br>" is allowed as well as "<br/>". However only the LATTER is accepted by this function (with "br" in the "solo-tag" list), the first example will result in a warning.
00622      * NOTICE: Correct XHTML might actually fail since "<p/>" is allowed as well as "<p></p>". However only the LATTER is accepted by this function (with "p" in the "block-tag" list), the first example will result in an ERROR!
00623      * NOTICE: Correct HTML version "something" allows eg. <p> and <li> to be NON-ended (implicitly ended by other tags). However this is NOT accepted by this function (with "p" and "li" in the block-tag list) and it will result in an ERROR!
00624      *
00625      * @param   string      HTML content to analyze
00626      * @param   string      Tag names for block tags (eg. table or div or p) in lowercase, commalist (eg. "table,div,p")
00627      * @param   string      Tag names for solo tags (eg. img, br or input) in lowercase, commalist ("img,br,input")
00628      * @return  array       Analyse data.
00629      */
00630     function checkTagTypeCounts($content,$blockTags='a,b,blockquote,body,div,em,font,form,h1,h2,h3,h4,h5,h6,i,li,map,ol,option,p,pre,select,span,strong,table,td,textarea,tr,u,ul', $soloTags='br,hr,img,input,area')   {
00631         $content = strtolower($content);
00632         $analyzedOutput=array();
00633         $analyzedOutput['counts']=array();  // Counts appearances of start-tags
00634         $analyzedOutput['errors']=array();  // Lists ERRORS
00635         $analyzedOutput['warnings']=array();    // Lists warnings.
00636         $analyzedOutput['blocks']=array();  // Lists stats for block-tags
00637         $analyzedOutput['solo']=array();    // Lists stats for solo-tags
00638 
00639             // Block tags, must have endings...
00640         $blockTags = explode(',',$blockTags);
00641         foreach($blockTags as $tagName) {
00642             $countBegin = count(preg_split('/\<'.$tagName.'(\s|\>)/s',$content))-1;
00643             $countEnd = count(preg_split('/\<\/'.$tagName.'(\s|\>)/s',$content))-1;
00644             $analyzedOutput['blocks'][$tagName]=array($countBegin,$countEnd,$countBegin-$countEnd);
00645             if ($countBegin)    $analyzedOutput['counts'][$tagName]=$countBegin;
00646             if ($countBegin-$countEnd)  {
00647                 if ($countBegin-$countEnd > 0)  {
00648                     $analyzedOutput['errors'][$tagName]='There were more start-tags ('.$countBegin.') than end-tags ('.$countEnd.') for the element "'.$tagName.'". There should be an equal amount!';
00649                 } else {
00650                     $analyzedOutput['warnings'][$tagName]='There were more end-tags ('.$countEnd.') than start-tags ('.$countBegin.') for the element "'.$tagName.'". There should be an equal amount! However the problem is not fatal.';
00651                 }
00652             }
00653         }
00654 
00655             // Solo tags, must NOT have endings...
00656         $soloTags = explode(',',$soloTags);
00657         foreach($soloTags as $tagName)  {
00658             $countBegin = count(preg_split('/\<'.$tagName.'(\s|\>)/s',$content))-1;
00659             $countEnd = count(preg_split('/\<\/'.$tagName.'(\s|\>)/s',$content))-1;
00660             $analyzedOutput['solo'][$tagName]=array($countBegin,$countEnd);
00661             if ($countBegin)    $analyzedOutput['counts'][$tagName]=$countBegin;
00662             if ($countEnd)  {
00663                 $analyzedOutput['warnings'][$tagName]='There were end-tags found ('.$countEnd.') for the element "'.$tagName.'". This was not expected (although XHTML technically allows it).';
00664             }
00665         }
00666 
00667         return $analyzedOutput;
00668     }
00669 
00670 
00671 
00672 
00673 
00674 
00675 
00676 
00677 
00678 
00679 
00680 
00681     /*********************************
00682      *
00683      * Clean HTML code
00684      *
00685      *********************************/
00686 
00687     /**
00688      * Function that can clean up HTML content according to configuration given in the $tags array.
00689      *
00690      * Initializing the $tags array to allow a list of tags (in this case <B>,<I>,<U> and <A>), set it like this:        $tags = array_flip(explode(',','b,a,i,u'))
00691      * If the value of the $tags[$tagname] entry is an array, advanced processing of the tags is initialized. These are the options:
00692      *
00693      *  $tags[$tagname] = Array(
00694      *      'overrideAttribs' => ''     If set, this string is preset as the attributes of the tag
00695      *      'allowedAttribs' =>   '0' (zero) = no attributes allowed, '[commalist of attributes]' = only allowed attributes. If blank, all attributes are allowed.
00696      *      'fixAttrib' => Array(
00697      *          '[attribute name]' => Array (
00698      *              'set' => Force the attribute value to this value.
00699      *              'unset' => Boolean: If set, the attribute is unset.
00700      *              'default' =>    If no attribute exists by this name, this value is set as default value (if this value is not blank)
00701      *              'always' =>     Boolean. If set, the attribute is always processed. Normally an attribute is processed only if it exists
00702      *              'trim,intval,lower,upper' =>    All booleans. If any of these keys are set, the value is passed through the respective PHP-functions.
00703      *              'range' => Array ('[low limit]','[high limit, optional]')       Setting integer range.
00704      *              'list' => Array ('[value1/default]','[value2]','[value3]')      Attribute must be in this list. If not, the value is set to the first element.
00705      *              'removeIfFalse' =>  Boolean/'blank'.    If set, then the attribute is removed if it is 'false'. If this value is set to 'blank' then the value must be a blank string (that means a 'zero' value will not be removed)
00706      *              'removeIfEquals' =>     [value] If the attribute value matches the value set here, then it is removed.
00707      *              'casesensitiveComp' => 1    If set, then the removeIfEquals and list comparisons will be case sensitive. Otherwise not.
00708      *          )
00709      *      ),
00710      *      'protect' => '',    Boolean. If set, the tag <> is converted to &lt; and &gt;
00711      *      'remap' => '',      String. If set, the tagname is remapped to this tagname
00712      *      'rmTagIfNoAttrib' => '',    Boolean. If set, then the tag is removed if no attributes happend to be there.
00713      *      'nesting' => '',    Boolean/'global'. If set true, then this tag must have starting and ending tags in the correct order. Any tags not in this order will be discarded. Thus '</B><B><I></B></I></B>' will be converted to '<B><I></B></I>'. Is the value 'global' then true nesting in relation to other tags marked for 'global' nesting control is preserved. This means that if <B> and <I> are set for global nesting then this string '</B><B><I></B></I></B>' is converted to '<B></B>'
00714      *  )
00715      *
00716      * @param   string      $content; is the HTML-content being processed. This is also the result being returned.
00717      * @param   array       $tags; is an array where each key is a tagname in lowercase. Only tags present as keys in this array are preserved. The value of the key can be an array with a vast number of options to configure.
00718      * @param   string      $keepAll; boolean/'protect', if set, then all tags are kept regardless of tags present as keys in $tags-array. If 'protect' then the preserved tags have their <> converted to &lt; and &gt;
00719      * @param   integer     $hSC; Values -1,0,1,2: Set to zero= disabled, set to 1 then the content BETWEEN tags is htmlspecialchar()'ed, set to -1 its the opposite and set to 2 the content will be HSC'ed BUT with preservation for real entities (eg. "&amp;" or "&#234;")
00720      * @param   array       Configuration array send along as $conf to the internal functions ->processContent() and ->processTag()
00721      * @return  string      Processed HTML content
00722      */
00723     function HTMLcleaner($content, $tags=array(),$keepAll=0,$hSC=0,$addConfig=array())  {
00724         $newContent = array();
00725         $tokArr = explode('<',$content);
00726         $newContent[] = $this->processContent(current($tokArr),$hSC,$addConfig);
00727         next($tokArr);
00728 
00729         $c = 1;
00730         $tagRegister = array();
00731         $tagStack = array();
00732         $inComment = false; $skipTag = false;
00733         while(list(,$tok)=each($tokArr))    {
00734             if ($inComment) {
00735                 if (($eocPos = strpos($tok, '-->')) === false) {
00736                     // End of comment is not found in the token. Go futher until end of comment is found in other tokens.
00737                     $newContent[$c++] = '<' . $tok;
00738                     continue;
00739                 }
00740                 // Comment ends in the middle of the token: add comment and proceed with rest of the token
00741                 $newContent[$c++] = '<' . substr($tok, 0, $eocPos + 3);
00742                 $tok = substr($tok, $eocPos + 3);
00743                 $inComment = false; $skipTag = true;
00744             }
00745             elseif (substr($tok, 0, 3) == '!--') {
00746                 if (($eocPos = strpos($tok, '-->')) === false) {
00747                     // Comment started in this token but it does end in the same token. Set a flag to skip till the end of comment
00748                     $newContent[$c++] = '<' . $tok;
00749                     $inComment = true;
00750                     continue;
00751                 }
00752                 // Start and end of comment are both in the current token. Add comment and proceed with rest of the token
00753                 $newContent[$c++] = '<' . substr($tok, 0, $eocPos + 3);
00754                 $tok = substr($tok, $eocPos + 3);
00755                 $skipTag = true;
00756             }
00757             $firstChar = substr($tok,0,1);
00758             if (!$skipTag && preg_match('/[[:alnum:]\/]/',$firstChar)==1)   {       // It is a tag... (first char is a-z0-9 or /) (fixed 19/01 2004). This also avoids triggering on <?xml..> and <!DOCTYPE..>
00759                 $tagEnd = strpos($tok,'>');
00760                 if ($tagEnd)    {   // If there is and end-bracket...   tagEnd can't be 0 as the first character can't be a >
00761                     $endTag = $firstChar=='/' ? 1 : 0;
00762                     $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
00763                     $tagParts = preg_split('/\s+/s',$tagContent,2);
00764                     $tagName = strtolower($tagParts[0]);
00765                     if (isset($tags[$tagName])) {
00766                         if (is_array($tags[$tagName]))  {   // If there is processing to do for the tag:
00767 
00768                             if (!$endTag)   {   // If NOT an endtag, do attribute processing (added dec. 2003)
00769                                     // Override attributes
00770                                 if (strcmp($tags[$tagName]['overrideAttribs'],''))  {
00771                                     $tagParts[1]=$tags[$tagName]['overrideAttribs'];
00772                                 }
00773 
00774                                     // Allowed tags
00775                                 if (strcmp($tags[$tagName]['allowedAttribs'],''))   {
00776                                     if (!strcmp($tags[$tagName]['allowedAttribs'],'0')) {   // No attribs allowed
00777                                         $tagParts[1]='';
00778                                     } elseif (trim($tagParts[1])) {
00779                                         $tagAttrib = $this->get_tag_attributes($tagParts[1]);
00780                                         $tagParts[1]='';
00781                                         $newTagAttrib = array();
00782                                         if (!($tList = $tags[$tagName]['_allowedAttribs'])) {
00783                                                 // Just explode attribts for tag once
00784                                             $tList = $tags[$tagName]['_allowedAttribs'] = t3lib_div::trimExplode(',',strtolower($tags[$tagName]['allowedAttribs']),1);
00785                                         }
00786                                         foreach ($tList as $allowTag)   {
00787                                             if (isset($tagAttrib[0][$allowTag]))    $newTagAttrib[$allowTag]=$tagAttrib[0][$allowTag];
00788                                         }
00789                                         $tagParts[1]=$this->compileTagAttribs($newTagAttrib,$tagAttrib[1]);
00790                                     }
00791                                 }
00792 
00793                                     // Fixed attrib values
00794                                 if (is_array($tags[$tagName]['fixAttrib'])) {
00795                                     $tagAttrib = $this->get_tag_attributes($tagParts[1]);
00796                                     $tagParts[1]='';
00797                                     reset($tags[$tagName]['fixAttrib']);
00798                                     while(list($attr,$params)=each($tags[$tagName]['fixAttrib']))   {
00799                                         if (strlen($params['set'])) $tagAttrib[0][$attr] = $params['set'];
00800                                         if (strlen($params['unset']))   unset($tagAttrib[0][$attr]);
00801                                         if (strcmp($params['default'],'') && !isset($tagAttrib[0][$attr]))  $tagAttrib[0][$attr]=$params['default'];
00802                                         if ($params['always'] || isset($tagAttrib[0][$attr]))   {
00803                                             if ($params['trim'])    {$tagAttrib[0][$attr]=trim($tagAttrib[0][$attr]);}
00804                                             if ($params['intval'])  {$tagAttrib[0][$attr]=intval($tagAttrib[0][$attr]);}
00805                                             if ($params['lower'])   {$tagAttrib[0][$attr]=strtolower($tagAttrib[0][$attr]);}
00806                                             if ($params['upper'])   {$tagAttrib[0][$attr]=strtoupper($tagAttrib[0][$attr]);}
00807                                             if ($params['range'])   {
00808                                                 if (isset($params['range'][1])) {
00809                                                     $tagAttrib[0][$attr]=t3lib_div::intInRange($tagAttrib[0][$attr],intval($params['range'][0]),intval($params['range'][1]));
00810                                                 } else {
00811                                                     $tagAttrib[0][$attr]=t3lib_div::intInRange($tagAttrib[0][$attr],intval($params['range'][0]));
00812                                                 }
00813                                             }
00814                                             if (is_array($params['list']))  {
00815                                                 if (!in_array($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['list'],$params['casesensitiveComp'],$tagName))) $tagAttrib[0][$attr]=$params['list'][0];
00816                                             }
00817                                             if (($params['removeIfFalse'] && $params['removeIfFalse']!='blank' && !$tagAttrib[0][$attr]) || ($params['removeIfFalse']=='blank' && !strcmp($tagAttrib[0][$attr],'')))    {
00818                                                 unset($tagAttrib[0][$attr]);
00819                                             }
00820                                             if (strcmp($params['removeIfEquals'],'') && !strcmp($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['removeIfEquals'],$params['casesensitiveComp'])))  {
00821                                                 unset($tagAttrib[0][$attr]);
00822                                             }
00823                                             if ($params['prefixLocalAnchors'])  {
00824                                                 if (substr($tagAttrib[0][$attr],0,1)=='#')  {
00825                                                     $prefix = t3lib_div::getIndpEnv('TYPO3_REQUEST_URL');
00826                                                     $tagAttrib[0][$attr] = $prefix.$tagAttrib[0][$attr];
00827                                                     if ($params['prefixLocalAnchors']==2 && t3lib_div::isFirstPartOfStr($prefix,t3lib_div::getIndpEnv('TYPO3_SITE_URL')))       {
00828                                                         $tagAttrib[0][$attr] = substr($tagAttrib[0][$attr],strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
00829                                                     }
00830                                                 }
00831                                             }
00832                                             if ($params['prefixRelPathWith'])   {
00833                                                 $urlParts = parse_url($tagAttrib[0][$attr]);
00834                                                 if (!$urlParts['scheme'] && substr($urlParts['path'],0,1)!='/') {   // If it is NOT an absolute URL (by http: or starting "/")
00835                                                     $tagAttrib[0][$attr] = $params['prefixRelPathWith'].$tagAttrib[0][$attr];
00836                                                 }
00837                                             }
00838                                             if ($params['userFunc'])    {
00839                                                 $tagAttrib[0][$attr] = t3lib_div::callUserFunction($params['userFunc'],$tagAttrib[0][$attr],$this);
00840                                             }
00841                                         }
00842                                     }
00843                                     $tagParts[1]=$this->compileTagAttribs($tagAttrib[0],$tagAttrib[1]);
00844                                 }
00845                             } else {    // If endTag, remove any possible attributes:
00846                                 $tagParts[1]='';
00847                             }
00848 
00849                                 // Protecting the tag by converting < and > to &lt; and &gt; ??
00850                             if ($tags[$tagName]['protect']) {
00851                                 $lt = '&lt;';   $gt = '&gt;';
00852                             } else {
00853                                 $lt = '<';  $gt = '>';
00854                             }
00855                                 // Remapping tag name?
00856                             if ($tags[$tagName]['remap'])   $tagParts[0] = $tags[$tagName]['remap'];
00857 
00858                                 // rmTagIfNoAttrib
00859                             if ($endTag || trim($tagParts[1]) || !$tags[$tagName]['rmTagIfNoAttrib'])   {
00860                                 $setTag=1;
00861 
00862                                 if ($tags[$tagName]['nesting']) {
00863                                     if (!is_array($tagRegister[$tagName]))  $tagRegister[$tagName]=array();
00864 
00865                                     if ($endTag)    {
00866 /*                                      if ($tags[$tagName]['nesting']=='global')   {
00867                                             $lastEl = end($tagStack);
00868                                             $correctTag = !strcmp($tagName,$lastEl);
00869                                         } else $correctTag=1;
00870     */
00871                                         $correctTag=1;
00872                                         if ($tags[$tagName]['nesting']=='global')   {
00873                                             $lastEl = end($tagStack);
00874                                             if (strcmp($tagName,$lastEl))   {
00875                                                 if (in_array($tagName,$tagStack))   {
00876                                                     while(count($tagStack) && strcmp($tagName,$lastEl)) {
00877                                                         $elPos = end($tagRegister[$lastEl]);
00878                                                         unset($newContent[$elPos]);
00879 
00880                                                         array_pop($tagRegister[$lastEl]);
00881                                                         array_pop($tagStack);
00882                                                         $lastEl = end($tagStack);
00883                                                     }
00884                                                 } else {
00885                                                     $correctTag=0;  // In this case the
00886                                                 }
00887                                             }
00888                                         }
00889                                         if (!count($tagRegister[$tagName]) || !$correctTag) {
00890                                             $setTag=0;
00891                                         } else {
00892                                             array_pop($tagRegister[$tagName]);
00893                                             if ($tags[$tagName]['nesting']=='global')   {array_pop($tagStack);}
00894                                         }
00895                                     } else {
00896                                         array_push($tagRegister[$tagName],$c);
00897                                         if ($tags[$tagName]['nesting']=='global')   {array_push($tagStack,$tagName);}
00898                                     }
00899                                 }
00900 
00901                                 if ($setTag)    {
00902                                         // Setting the tag
00903                                     $newContent[$c++]=$this->processTag($lt.($endTag?'/':'').trim($tagParts[0].' '.$tagParts[1]).$gt,$addConfig,$endTag,$lt=='&lt;');
00904                                 }
00905                             }
00906                         } else {
00907                             $newContent[$c++]=$this->processTag('<'.($endTag?'/':'').$tagContent.'>',$addConfig,$endTag);
00908                         }
00909                     } elseif ($keepAll) {   // This is if the tag was not defined in the array for processing:
00910                         if (!strcmp($keepAll,'protect'))    {
00911                             $lt = '&lt;';   $gt = '&gt;';
00912                         } else {
00913                             $lt = '<';  $gt = '>';
00914                         }
00915                         $newContent[$c++]=$this->processTag($lt.($endTag?'/':'').$tagContent.$gt,$addConfig,$endTag,$lt=='&lt;');
00916                     }
00917                     $newContent[$c++]=$this->processContent(substr($tok,$tagEnd+1),$hSC,$addConfig);
00918                 } else {
00919                     $newContent[$c++]=$this->processContent('<'.$tok,$hSC,$addConfig);  // There were not end-bracket, so no tag...
00920                 }
00921             } else {
00922                 $newContent[$c++]=$this->processContent(($skipTag ? '' : '<') . $tok, $hSC, $addConfig);    // It was not a tag anyways
00923                 $skipTag = false;
00924             }
00925         }
00926 
00927             // Unsetting tags:
00928         foreach ($tagRegister as $tag => $positions)    {
00929             foreach ($positions as $pKey)   {
00930                 unset($newContent[$pKey]);
00931             }
00932         }
00933 
00934         return implode('',$newContent);
00935     }
00936 
00937     /**
00938      * Converts htmlspecialchars forth ($dir=1) AND back ($dir=-1)
00939      *
00940      * @param   string      Input value
00941      * @param   integer     Direction: forth ($dir=1, dir=2 for preserving entities) AND back ($dir=-1)
00942      * @return  string      Output value
00943      */
00944     function bidir_htmlspecialchars($value,$dir)    {
00945         if ($dir==1)    {
00946             $value = htmlspecialchars($value);
00947         } elseif ($dir==2)  {
00948             $value = t3lib_div::deHSCentities(htmlspecialchars($value));
00949         } elseif ($dir==-1) {
00950             $value = str_replace('&gt;','>',$value);
00951             $value = str_replace('&lt;','<',$value);
00952             $value = str_replace('&quot;','"',$value);
00953             $value = str_replace('&amp;','&',$value);
00954         }
00955         return $value;
00956     }
00957 
00958     /**
00959      * Prefixes the relative paths of hrefs/src/action in the tags [td,table,body,img,input,form,link,script,a] in the $content with the $main_prefix or and alternative given by $alternatives
00960      *
00961      * @param   string      Prefix string
00962      * @param   string      HTML content
00963      * @param   array       Array with alternative prefixes for certain of the tags. key=>value pairs where the keys are the tag element names in uppercase
00964      * @param   string      Suffix string (put after the resource).
00965      * @return  string      Processed HTML content
00966      */
00967     function prefixResourcePath($main_prefix,$content,$alternatives=array(),$suffix='') {
00968 
00969         $parts = $this->splitTags('embed,td,table,body,img,input,form,link,script,a',$content);
00970         foreach ($parts as $k => $v)    {
00971             if ($k%2)   {
00972                 $params = $this->get_tag_attributes($v,1);
00973                 $tagEnd = substr($v,-2)=='/>' ? ' />' : '>';    // Detect tag-ending so that it is re-applied correctly.
00974                 $firstTagName = $this->getFirstTagName($v); // The 'name' of the first tag
00975                 $somethingDone=0;
00976                 $prefix = isset($alternatives[strtoupper($firstTagName)]) ? $alternatives[strtoupper($firstTagName)] : $main_prefix;
00977                 switch(strtolower($firstTagName))   {
00978                         // background - attribute:
00979                     case 'td':
00980                     case 'body':
00981                     case 'table':
00982                         $src = $params[0]['background'];
00983                         if ($src)   {
00984                             $params[0]['background'] = $this->prefixRelPath($prefix,$params[0]['background'],$suffix);
00985                             $somethingDone=1;
00986                         }
00987                     break;
00988                         // src attribute
00989                     case 'img':
00990                     case 'input':
00991                     case 'script':
00992                     case 'embed':
00993                         $src = $params[0]['src'];
00994                         if ($src)   {
00995                             $params[0]['src'] = $this->prefixRelPath($prefix,$params[0]['src'],$suffix);
00996                             $somethingDone=1;
00997                         }
00998                     break;
00999                     case 'link':
01000                     case 'a':
01001                         $src = $params[0]['href'];
01002                         if ($src)   {
01003                             $params[0]['href'] = $this->prefixRelPath($prefix,$params[0]['href'],$suffix);
01004                             $somethingDone=1;
01005                         }
01006                     break;
01007                         // action attribute
01008                     case 'form':
01009                         $src = $params[0]['action'];
01010                         if ($src)   {
01011                             $params[0]['action'] = $this->prefixRelPath($prefix,$params[0]['action'],$suffix);
01012                             $somethingDone=1;
01013                         }
01014                     break;
01015                 }
01016                 if ($somethingDone) {
01017                     $tagParts = preg_split('/\s+/s',$v,2);
01018                     $tagParts[1]=$this->compileTagAttribs($params[0],$params[1]);
01019                     $parts[$k] = '<'.trim(strtolower($firstTagName).' '.$tagParts[1]).$tagEnd;
01020                 }
01021             }
01022         }
01023         $content = implode('',$parts);
01024 
01025             // Fix <style> section:
01026         $prefix = isset($alternatives['style']) ? $alternatives['style'] : $main_prefix;
01027         if (strlen($prefix))    {
01028             $parts = $this->splitIntoBlock('style',$content);
01029             foreach($parts as $k => $v) {
01030                 if ($k%2)   {
01031                     $parts[$k] = eregi_replace('(url[[:space:]]*\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\))','\1'.$prefix.'\2'.$suffix.'\3',$parts[$k]);
01032                 }
01033             }
01034             $content = implode('',$parts);
01035         }
01036 
01037         return $content;
01038     }
01039 
01040     /**
01041      * Internal sub-function for ->prefixResourcePath()
01042      *
01043      * @param   string      Prefix string
01044      * @param   string      Relative path/URL
01045      * @param   string      Suffix string
01046      * @return  string      Output path, prefixed if no scheme in input string
01047      * @access private
01048      */
01049     function prefixRelPath($prefix,$srcVal,$suffix='')  {
01050         $pU = parse_url($srcVal);
01051         if (!$pU['scheme'] && substr($srcVal, 0, 1)!='/')   { // If not an absolute URL.
01052             $srcVal = $prefix.$srcVal.$suffix;
01053         }
01054         return $srcVal;
01055     }
01056 
01057     /**
01058      * Cleans up the input $value for fonttags.
01059      * If keepFace,-Size and -Color is set then font-tags with an allowed property is kept. Else deleted.
01060      *
01061      * @param   string      HTML content with font-tags inside to clean up.
01062      * @param   boolean     If set, keep "face" attribute
01063      * @param   boolean     If set, keep "size" attribute
01064      * @param   boolean     If set, keep "color" attribute
01065      * @return  string      Processed HTML content
01066      */
01067     function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0) {
01068         $fontSplit = $this->splitIntoBlock('font',$value);  // ,1 ?? - could probably be more stable if splitTags() was used since this depends on end-tags being properly set!
01069         foreach ($fontSplit as $k => $v)    {
01070             if ($k%2)   {   // font:
01071                 $attribArray=$this->get_tag_attributes_classic($this->getFirstTag($v));
01072                 $newAttribs=array();
01073                 if ($keepFace && $attribArray['face'])  $newAttribs[]='face="'.$attribArray['face'].'"';
01074                 if ($keepSize && $attribArray['size'])  $newAttribs[]='size="'.$attribArray['size'].'"';
01075                 if ($keepColor && $attribArray['color'])    $newAttribs[]='color="'.$attribArray['color'].'"';
01076 
01077                 $innerContent = $this->cleanFontTags($this->removeFirstAndLastTag($v),$keepFace,$keepSize,$keepColor);
01078                 if (count($newAttribs)) {
01079                     $fontSplit[$k]='<font '.implode(' ',$newAttribs).'>'.$innerContent.'</font>';
01080                 } else {
01081                     $fontSplit[$k]=$innerContent;
01082                 }
01083             }
01084         }
01085         return implode('',$fontSplit);
01086     }
01087 
01088     /**
01089      * This is used to map certain tag-names into other names.
01090      *
01091      * @param   string      HTML content
01092      * @param   array       Array with tag key=>value pairs where key is from-tag and value is to-tag
01093      * @param   string      Alternative less-than char to search for (search regex string)
01094      * @param   string      Alternative less-than char to replace with (replace regex string)
01095      * @return  string      Processed HTML content
01096      */
01097     function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<') {
01098 
01099         foreach($tags as $from => $to)  {
01100             $value = preg_replace('/'.preg_quote($ltChar).'(\/)?'.$from.'\s([^\>])*(\/)?\>/', $ltChar2.'$1'.$to.' $2$3>', $value);
01101         }
01102         return $value;
01103     }
01104 
01105     /**
01106      * This converts htmlspecialchar()'ed tags (from $tagList) back to real tags. Eg. '&lt;strong&gt' would be converted back to '<strong>' if found in $tagList
01107      *
01108      * @param   string      HTML content
01109      * @param   string      Tag list, separated by comma. Lowercase!
01110      * @return  string      Processed HTML content
01111      */
01112     function unprotectTags($content,$tagList='')    {
01113         $tagsArray = t3lib_div::trimExplode(',',$tagList,1);
01114         $contentParts = explode('&lt;',$content);
01115         next($contentParts);    // bypass the first
01116         while(list($k,$tok)=each($contentParts))    {
01117             $firstChar = substr($tok,0,1);
01118             if (strcmp(trim($firstChar),''))    {
01119                 $subparts = explode('&gt;',$tok,2);
01120                 $tagEnd = strlen($subparts[0]);
01121                 if (strlen($tok)!=$tagEnd)  {
01122                     $endTag = $firstChar=='/' ? 1 : 0;
01123                     $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
01124                     $tagParts = preg_split('/\s+/s',$tagContent,2);
01125                     $tagName = strtolower($tagParts[0]);
01126                     if (!strcmp($tagList,'') || in_array($tagName,$tagsArray))  {
01127                         $contentParts[$k] = '<'.$subparts[0].'>'.$subparts[1];
01128                     } else $contentParts[$k] = '&lt;'.$tok;
01129                 } else $contentParts[$k] = '&lt;'.$tok;
01130             } else $contentParts[$k] = '&lt;'.$tok;
01131         }
01132 
01133         return implode('',$contentParts);
01134     }
01135 
01136     /**
01137      * Strips tags except the tags in the list, $tagList
01138      * OBSOLETE - use PHP function strip_tags()
01139      *
01140      * @param   string      Value to process
01141      * @param   string      List of tags
01142      * @return  string      Output value
01143      * @ignore
01144      */
01145     function stripTagsExcept($value,$tagList)   {
01146         $tags=t3lib_div::trimExplode(',',$tagList,1);
01147         $forthArr=array();
01148         $backArr=array();
01149         foreach ($tags as $theTag)  {
01150             $forthArr[$theTag]=md5($theTag);
01151             $backArr[md5($theTag)]=$theTag;
01152         }
01153         $value = $this->mapTags($value,$forthArr,'<','_');
01154         $value=strip_tags($value);
01155         $value = $this->mapTags($value,$backArr,'_','<');
01156         return $value;
01157     }
01158 
01159