class.t3lib_parsehtml.php

Go to the documentation of this file.
00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 1999-2010 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 8145 2010-07-09 07:34:38Z steffenk $
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=TAB)
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 = self::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 = self::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                                     foreach ($tags[$tagName]['fixAttrib'] as $attr => $params) {
00798                                         if (strlen($params['set'])) $tagAttrib[0][$attr] = $params['set'];
00799                                         if (strlen($params['unset']))   unset($tagAttrib[0][$attr]);
00800                                         if (strcmp($params['default'],'') && !isset($tagAttrib[0][$attr]))  $tagAttrib[0][$attr]=$params['default'];
00801                                         if ($params['always'] || isset($tagAttrib[0][$attr]))   {
00802                                             if ($params['trim'])    {$tagAttrib[0][$attr]=trim($tagAttrib[0][$attr]);}
00803                                             if ($params['intval'])  {$tagAttrib[0][$attr]=intval($tagAttrib[0][$attr]);}
00804                                             if ($params['lower'])   {$tagAttrib[0][$attr]=strtolower($tagAttrib[0][$attr]);}
00805                                             if ($params['upper'])   {$tagAttrib[0][$attr]=strtoupper($tagAttrib[0][$attr]);}
00806                                             if ($params['range'])   {
00807                                                 if (isset($params['range'][1])) {
00808                                                     $tagAttrib[0][$attr]=t3lib_div::intInRange($tagAttrib[0][$attr],intval($params['range'][0]),intval($params['range'][1]));
00809                                                 } else {
00810                                                     $tagAttrib[0][$attr]=t3lib_div::intInRange($tagAttrib[0][$attr],intval($params['range'][0]));
00811                                                 }
00812                                             }
00813                                             if (is_array($params['list'])) {
00814                                                     // For the class attribute, remove from the attribute value any class not in the list
00815                                                     // Classes are case sensitive
00816                                                 if ($attr == 'class') {
00817                                                     $newClasses = array();
00818                                                     $classes = t3lib_div::trimExplode(' ', $tagAttrib[0][$attr], TRUE);
00819                                                     foreach ($classes as $class) {
00820                                                         if (in_array($class, $params['list'])) {
00821                                                             $newClasses[] = $class;
00822                                                         }
00823                                                     }
00824                                                     if (count($newClasses)) {
00825                                                         $tagAttrib[0][$attr] = implode(' ', $newClasses);
00826                                                     } else {
00827                                                         $tagAttrib[0][$attr] = '';
00828                                                     }
00829                                                 } else {
00830                                                     if (!in_array($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['list'],$params['casesensitiveComp'],$tagName))) {
00831                                                         $tagAttrib[0][$attr]=$params['list'][0];
00832                                                     }
00833                                                 }
00834                                             }
00835                                             if (($params['removeIfFalse'] && $params['removeIfFalse']!='blank' && !$tagAttrib[0][$attr]) || ($params['removeIfFalse']=='blank' && !strcmp($tagAttrib[0][$attr],'')))    {
00836                                                 unset($tagAttrib[0][$attr]);
00837                                             }
00838                                             if (strcmp($params['removeIfEquals'],'') && !strcmp($this->caseShift($tagAttrib[0][$attr],$params['casesensitiveComp']),$this->caseShift($params['removeIfEquals'],$params['casesensitiveComp'])))  {
00839                                                 unset($tagAttrib[0][$attr]);
00840                                             }
00841                                             if ($params['prefixLocalAnchors'])  {
00842                                                 if (substr($tagAttrib[0][$attr],0,1)=='#')  {
00843                                                     $prefix = t3lib_div::getIndpEnv('TYPO3_REQUEST_URL');
00844                                                     $tagAttrib[0][$attr] = $prefix.$tagAttrib[0][$attr];
00845                                                     if ($params['prefixLocalAnchors']==2 && t3lib_div::isFirstPartOfStr($prefix,t3lib_div::getIndpEnv('TYPO3_SITE_URL')))       {
00846                                                         $tagAttrib[0][$attr] = substr($tagAttrib[0][$attr],strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
00847                                                     }
00848                                                 }
00849                                             }
00850                                             if ($params['prefixRelPathWith'])   {
00851                                                 $urlParts = parse_url($tagAttrib[0][$attr]);
00852                                                 if (!$urlParts['scheme'] && substr($urlParts['path'],0,1)!='/') {   // If it is NOT an absolute URL (by http: or starting "/")
00853                                                     $tagAttrib[0][$attr] = $params['prefixRelPathWith'].$tagAttrib[0][$attr];
00854                                                 }
00855                                             }
00856                                             if ($params['userFunc'])    {
00857                                                 $tagAttrib[0][$attr] = t3lib_div::callUserFunction($params['userFunc'],$tagAttrib[0][$attr],$this);
00858                                             }
00859                                         }
00860                                     }
00861                                     $tagParts[1]=$this->compileTagAttribs($tagAttrib[0],$tagAttrib[1]);
00862                                 }
00863                             } else {    // If endTag, remove any possible attributes:
00864                                 $tagParts[1]='';
00865                             }
00866 
00867                                 // Protecting the tag by converting < and > to &lt; and &gt; ??
00868                             if ($tags[$tagName]['protect']) {
00869                                 $lt = '&lt;';   $gt = '&gt;';
00870                             } else {
00871                                 $lt = '<';  $gt = '>';
00872                             }
00873                                 // Remapping tag name?
00874                             if ($tags[$tagName]['remap'])   $tagParts[0] = $tags[$tagName]['remap'];
00875 
00876                                 // rmTagIfNoAttrib
00877                             if ($endTag || trim($tagParts[1]) || !$tags[$tagName]['rmTagIfNoAttrib'])   {
00878                                 $setTag=1;
00879 
00880                                 if ($tags[$tagName]['nesting']) {
00881                                     if (!is_array($tagRegister[$tagName]))  $tagRegister[$tagName]=array();
00882 
00883                                     if ($endTag)    {
00884 /*                                      if ($tags[$tagName]['nesting']=='global')   {
00885                                             $lastEl = end($tagStack);
00886                                             $correctTag = !strcmp($tagName,$lastEl);
00887                                         } else $correctTag=1;
00888     */
00889                                         $correctTag=1;
00890                                         if ($tags[$tagName]['nesting']=='global')   {
00891                                             $lastEl = end($tagStack);
00892                                             if (strcmp($tagName,$lastEl))   {
00893                                                 if (in_array($tagName,$tagStack))   {
00894                                                     while(count($tagStack) && strcmp($tagName,$lastEl)) {
00895                                                         $elPos = end($tagRegister[$lastEl]);
00896                                                         unset($newContent[$elPos]);
00897 
00898                                                         array_pop($tagRegister[$lastEl]);
00899                                                         array_pop($tagStack);
00900                                                         $lastEl = end($tagStack);
00901                                                     }
00902                                                 } else {
00903                                                     $correctTag=0;  // In this case the
00904                                                 }
00905                                             }
00906                                         }
00907                                         if (!count($tagRegister[$tagName]) || !$correctTag) {
00908                                             $setTag=0;
00909                                         } else {
00910                                             array_pop($tagRegister[$tagName]);
00911                                             if ($tags[$tagName]['nesting']=='global')   {array_pop($tagStack);}
00912                                         }
00913                                     } else {
00914                                         array_push($tagRegister[$tagName],$c);
00915                                         if ($tags[$tagName]['nesting']=='global')   {array_push($tagStack,$tagName);}
00916                                     }
00917                                 }
00918 
00919                                 if ($setTag)    {
00920                                         // Setting the tag
00921                                     $newContent[$c++]=$this->processTag($lt.($endTag?'/':'').trim($tagParts[0].' '.$tagParts[1]).$gt,$addConfig,$endTag,$lt=='&lt;');
00922                                 }
00923                             }
00924                         } else {
00925                             $newContent[$c++]=$this->processTag('<'.($endTag?'/':'').$tagContent.'>',$addConfig,$endTag);
00926                         }
00927                     } elseif ($keepAll) {   // This is if the tag was not defined in the array for processing:
00928                         if (!strcmp($keepAll,'protect'))    {
00929                             $lt = '&lt;';   $gt = '&gt;';
00930                         } else {
00931                             $lt = '<';  $gt = '>';
00932                         }
00933                         $newContent[$c++]=$this->processTag($lt.($endTag?'/':'').$tagContent.$gt,$addConfig,$endTag,$lt=='&lt;');
00934                     }
00935                     $newContent[$c++]=$this->processContent(substr($tok,$tagEnd+1),$hSC,$addConfig);
00936                 } else {
00937                     $newContent[$c++]=$this->processContent('<'.$tok,$hSC,$addConfig);  // There were not end-bracket, so no tag...
00938                 }
00939             } else {
00940                 $newContent[$c++]=$this->processContent(($skipTag ? '' : '<') . $tok, $hSC, $addConfig);    // It was not a tag anyways
00941                 $skipTag = false;
00942             }
00943         }
00944 
00945             // Unsetting tags:
00946         foreach ($tagRegister as $tag => $positions)    {
00947             foreach ($positions as $pKey)   {
00948                 unset($newContent[$pKey]);
00949             }
00950         }
00951 
00952         return implode('',$newContent);
00953     }
00954 
00955     /**
00956      * Converts htmlspecialchars forth ($dir=1) AND back ($dir=-1)
00957      *
00958      * @param   string      Input value
00959      * @param   integer     Direction: forth ($dir=1, dir=2 for preserving entities) AND back ($dir=-1)
00960      * @return  string      Output value
00961      */
00962     function bidir_htmlspecialchars($value,$dir)    {
00963         if ($dir==1)    {
00964             $value = htmlspecialchars($value);
00965         } elseif ($dir==2)  {
00966             $value = t3lib_div::deHSCentities(htmlspecialchars($value));
00967         } elseif ($dir==-1) {
00968             $value = str_replace('&gt;','>',$value);
00969             $value = str_replace('&lt;','<',$value);
00970             $value = str_replace('&quot;','"',$value);
00971             $value = str_replace('&amp;','&',$value);
00972         }
00973         return $value;
00974     }
00975 
00976     /**
00977      * 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
00978      *
00979      * @param   string      Prefix string
00980      * @param   string      HTML content
00981      * @param   array       Array with alternative prefixes for certain of the tags. key=>value pairs where the keys are the tag element names in uppercase
00982      * @param   string      Suffix string (put after the resource).
00983      * @return  string      Processed HTML content
00984      */
00985     function prefixResourcePath($main_prefix,$content,$alternatives=array(),$suffix='') {
00986 
00987         $parts = $this->splitTags('embed,td,table,body,img,input,form,link,script,a,param',$content);
00988         foreach ($parts as $k => $v)    {
00989             if ($k%2)   {
00990                 $params = $this->get_tag_attributes($v);
00991                 $tagEnd = substr($v,-2)=='/>' ? ' />' : '>';    // Detect tag-ending so that it is re-applied correctly.
00992                 $firstTagName = $this->getFirstTagName($v); // The 'name' of the first tag
00993                 $somethingDone=0;
00994                 $prefix = isset($alternatives[strtoupper($firstTagName)]) ? $alternatives[strtoupper($firstTagName)] : $main_prefix;
00995                 switch(strtolower($firstTagName))   {
00996                         // background - attribute:
00997                     case 'td':
00998                     case 'body':
00999                     case 'table':
01000                         $src = $params[0]['background'];
01001                         if ($src)   {
01002                             $params[0]['background'] = $this->prefixRelPath($prefix,$params[0]['background'],$suffix);
01003                             $somethingDone=1;
01004                         }
01005                     break;
01006                         // src attribute
01007                     case 'img':
01008                     case 'input':
01009                     case 'script':
01010                     case 'embed':
01011                         $src = $params[0]['src'];
01012                         if ($src)   {
01013                             $params[0]['src'] = $this->prefixRelPath($prefix,$params[0]['src'],$suffix);
01014                             $somethingDone=1;
01015                         }
01016                     break;
01017                     case 'link':
01018                     case 'a':
01019                         $src = $params[0]['href'];
01020                         if ($src)   {
01021                             $params[0]['href'] = $this->prefixRelPath($prefix,$params[0]['href'],$suffix);
01022                             $somethingDone=1;
01023                         }
01024                     break;
01025                         // action attribute
01026                     case 'form':
01027                         $src = $params[0]['action'];
01028                         if ($src)   {
01029                             $params[0]['action'] = $this->prefixRelPath($prefix,$params[0]['action'],$suffix);
01030                             $somethingDone=1;
01031                         }
01032                     break;
01033                         // value attribute
01034                     case 'param':
01035                         $test = $params[0]['name'];
01036                         if ($test && $test === 'movie') {
01037                             if ($params[0]['value']) {
01038                                 $params[0]['value'] = $this->prefixRelPath($prefix, $params[0]['value'], $suffix);
01039                                 $somethingDone = 1;
01040                             }
01041                         }
01042                     break;
01043                 }
01044                 if ($somethingDone) {
01045                     $tagParts = preg_split('/\s+/s',$v,2);
01046                     $tagParts[1]=$this->compileTagAttribs($params[0],$params[1]);
01047                     $parts[$k] = '<'.trim(strtolower($firstTagName).' '.$tagParts[1]).$tagEnd;
01048                 }
01049             }
01050         }
01051         $content = implode('',$parts);
01052 
01053             // Fix <style> section:
01054         $prefix = isset($alternatives['style']) ? $alternatives['style'] : $main_prefix;
01055         if (strlen($prefix))    {
01056             $parts = $this->splitIntoBlock('style',$content);
01057             foreach($parts as $k => $v) {
01058                 if ($k%2)   {
01059                     $parts[$k] = preg_replace('/(url[[:space:]]*\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\))/i','\1'.$prefix.'\2'.$suffix.'\3',$parts[$k]);
01060                 }
01061             }
01062             $content = implode('',$parts);
01063         }
01064 
01065         return $content;
01066     }
01067 
01068     /**
01069      * Internal sub-function for ->prefixResourcePath()
01070      *
01071      * @param   string      Prefix string
01072      * @param   string      Relative path/URL
01073      * @param   string      Suffix string
01074      * @return  string      Output path, prefixed if no scheme in input string
01075      * @access private
01076      */
01077     function prefixRelPath($prefix, $srcVal, $suffix = '') {
01078             // Only prefix if it's not an absolute URL or
01079             // only a link to a section within the page.
01080         if (substr($srcVal, 0, 1) != '/' && substr($srcVal, 0, 1) != '#') {
01081             $urlParts = parse_url($srcVal);
01082                 // only prefix URLs without a scheme
01083             if (!$urlParts['scheme']) {
01084                 $srcVal = $prefix . $srcVal . $suffix;
01085             }
01086         }
01087         return $srcVal;
01088     }
01089 
01090     /**
01091      * Cleans up the input $value for fonttags.
01092      * If keepFace,-Size and -Color is set then font-tags with an allowed property is kept. Else deleted.
01093      *
01094      * @param   string      HTML content with font-tags inside to clean up.
01095      * @param   boolean     If set, keep "face" attribute
01096      * @param   boolean     If set, keep "size" attribute
01097      * @param   boolean     If set, keep "color" attribute
01098      * @return  string      Processed HTML content
01099      */
01100     function cleanFontTags($value,$keepFace=0,$keepSize=0,$keepColor=0) {
01101         $fontSplit = $this->splitIntoBlock('font',$value);  // ,1 ?? - could probably be more stable if splitTags() was used since this depends on end-tags being properly set!
01102         foreach ($fontSplit as $k => $v)    {
01103             if ($k%2)   {   // font:
01104                 $attribArray=$this->get_tag_attributes_classic($this->getFirstTag($v));
01105                 $newAttribs=array();
01106                 if ($keepFace && $attribArray['face'])  $newAttribs[]='face="'.$attribArray['face'].'"';
01107                 if ($keepSize && $attribArray['size'])  $newAttribs[]='size="'.$attribArray['size'].'"';
01108                 if ($keepColor && $attribArray['color'])    $newAttribs[]='color="'.$attribArray['color'].'"';
01109 
01110                 $innerContent = $this->cleanFontTags($this->removeFirstAndLastTag($v),$keepFace,$keepSize,$keepColor);
01111                 if (count($newAttribs)) {
01112                     $fontSplit[$k]='<font '.implode(' ',$newAttribs).'>'.$innerContent.'</font>';
01113                 } else {
01114                     $fontSplit[$k]=$innerContent;
01115                 }
01116             }
01117         }
01118         return implode('',$fontSplit);
01119     }
01120 
01121     /**
01122      * This is used to map certain tag-names into other names.
01123      *
01124      * @param   string      HTML content
01125      * @param   array       Array with tag key=>value pairs where key is from-tag and value is to-tag
01126      * @param   string      Alternative less-than char to search for (search regex string)
01127      * @param   string      Alternative less-than char to replace with (replace regex string)
01128      * @return  string      Processed HTML content
01129      */
01130     function mapTags($value,$tags=array(),$ltChar='<',$ltChar2='<') {
01131 
01132         foreach($tags as $from => $to)  {
01133             $value = preg_replace('/'.preg_quote($ltChar).'(\/)?'.$from.'\s([^\>])*(\/)?\>/', $ltChar2.'$1'.$to.' $2$3>', $value);
01134         }
01135         return $value;
01136     }
01137 
01138     /**
01139      * 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
01140      *
01141      * @param   string      HTML content
01142      * @param   string      Tag list, separated by comma. Lowercase!
01143      * @return  string      Processed HTML content
01144      */
01145     function unprotectTags($content,$tagList='')    {
01146         $tagsArray = t3lib_div::trimExplode(',',$tagList,1);
01147         $contentParts = explode('&lt;',$content);
01148         next($contentParts);    // bypass the first
01149         while(list($k,$tok)=each($contentParts))    {
01150             $firstChar = substr($tok,0,1);
01151             if (strcmp(trim($firstChar),''))    {
01152                 $subparts = explode('&gt;',$tok,2);
01153                 $tagEnd = strlen($subparts[0]);
01154                 if (strlen($tok)!=$tagEnd)  {
01155                     $endTag = $firstChar=='/' ? 1 : 0;
01156                     $tagContent = substr($tok,$endTag,$tagEnd-$endTag);
01157                     $tagParts = preg_split('/\s+/s',$tagContent,2);
01158                     $tagName = strtolower($tagParts[0]);
01159                     if (!strcmp($tagList,'') || in_array($tagName,$tagsArray))  {
01160                         $contentParts[$k] = '<'.$subparts[0].'>'.$subparts[1];
01161                     } else $contentParts[$k] = '&lt;'.$tok;
01162                 } else $contentParts[$k] = '&lt;'.$tok;
01163             } else $contentParts[$k] = '&lt;'.$tok;
01164         }
01165 
01166         return implode('',$contentParts);
01167     }
01168 
01169     /**
01170      * Strips tags except the tags in the list, $tagList
01171      * OBSOLETE - use PHP function strip_tags()
01172      *
01173      * @param   string      Value to process
01174      * @param   string      List of tags
01175      * @return  string      Output value
01176      * @ignore
01177      */
01178     function stripTagsExcept($value,$tagList)   {
01179         $tags=t3lib_div::trimExplode(',',$tagList,1);
01180         $forthArr=array();
01181         $backArr=array();
01182         foreach ($tags as $theTag)  {
01183             $forthArr[$theTag]=md5($theTag);
01184             $backArr[md5($theTag)]=$theTag;
01185         }
01186         $value = $this->mapTags($value,$forthArr,'<','_');
01187         $value=strip_tags($value);
01188         $value = $this->mapTags($value,$backArr,'_','<');
01189         return $value;
01190     }
01191 
01192     /**
01193      * Internal function for case shifting of a string or whole array
01194      *
01195      * @param   mixed       Input string/array
01196      * @param   boolean     If $str is a string AND this boolean(caseSensitive) is false, the string is returned in uppercase
01197      * @param   string      Key string used for internal caching of the results. Could be an MD5 hash of the serialized version of the input $str if that is an array.
01198      * @return  string      Output string, processed
01199      * @access private
01200      */
01201     function caseShift($str,$flag,$cacheKey='') {
01202         $cacheKey .= $flag?1:0;
01203         if (is_array($str)) {
01204             if (!$cacheKey || !isset($this->caseShift_cache[$cacheKey]))    {
01205                 reset($str);
01206                 foreach ($str as $k => $v)  {
01207                     if (!$flag) {
01208                         $str[$k] = strtoupper($v);
01209                     }
01210                 }
01211                 if ($cacheKey)  $this->caseShift_cache[$cacheKey]=$str;
01212             } else {
01213                 $str = $this->caseShift_cache[$cacheKey];
01214             }
01215         } elseif (!$flag)   { $str = strtoupper($str); }
01216         return $str;
01217     }
01218 
01219     /**
01220      * Compiling an array with tag attributes into a string
01221      *
01222      * @param   array       Tag attributes
01223      * @param   array       Meta information about these attributes (like if they were quoted)
01224      * @param   boolean     If set, then the attribute names will be set in lower case, value quotes in double-quotes and the value will be htmlspecialchar()'ed
01225      * @return  string      Imploded attributes, eg: 'attribute="value" attrib2="value2"'
01226      * @access private
01227      */
01228     function compileTagAttribs($tagAttrib,$meta=array(), $xhtmlClean=0) {
01229         $accu=array();
01230         foreach ($tagAttrib as $k =>$v) {
01231             if ($xhtmlClean)    {
01232                 $attr=strtolower($k);
01233                 if (strcmp($v,'') || isset($meta[$k]['dashType']))  {
01234                     $attr.='="'.htmlspecialchars($v).'"';
01235                 }
01236             } else {
01237                 $attr=$meta[$k]['origTag']?$meta[$k]['origTag']:$k;
01238                 if (strcmp($v,'') || isset($meta[$k]['dashType']))  {
01239                     $dash=$meta[$k]['dashType']?$meta[$k]['dashType']:(t3lib_div::testInt($v)?'':'"');
01240                     $attr.='='.$dash.$v.$dash;
01241                 }
01242             }
01243             $accu[]=$attr;
01244         }
01245         return implode(' ',$accu);
01246     }
01247 
01248     /**
01249      * Get tag attributes, the classic version (which had some limitations?)
01250      *
01251      * @param   string      The tag
01252      * @param   boolean     De-htmlspecialchar flag.
01253      * @return  array
01254      * @access private
01255      */
01256     function get_tag_attributes_classic($tag,$deHSC=0)  {
01257         $attr=$this->get_tag_attributes($tag,$deHSC);
01258         return is_array($attr[0])?$attr[0]:array();
01259     }
01260 
01261     /**
01262      * Indents input content with $number instances of $indentChar
01263      *
01264      * @param   string      Content string, multiple lines.
01265      * @param   integer     Number of indents
01266      * @param   string      Indent character/string
01267      * @return  string      Indented code (typ. HTML)
01268      */
01269     function indentLines($content, $number=1, $indentChar=TAB)  {
01270         $preTab = str_pad('', $number*strlen($indentChar), $indentChar);
01271         $lines = explode(LF,str_replace(CR,'',$content));
01272         foreach ($lines as $k => $v)    {
01273             $lines[$k] = $preTab.$v;
01274         }
01275         return implode(LF, $lines);
01276     }
01277 
01278     /**
01279      * Converts TSconfig into an array for the HTMLcleaner function.
01280      *
01281      * @param   array       TSconfig for HTMLcleaner
01282      * @param   array       Array of tags to keep (?)
01283      * @return  array
01284      * @access private
01285      */
01286     function HTMLparserConfig($TSconfig,$keepTags=array())  {
01287             // Allow tags (base list, merged with incoming array)
01288         $alTags = array_flip(t3lib_div::trimExplode(',',strtolower($TSconfig['allowTags']),1));
01289         $keepTags = array_merge($alTags,$keepTags);
01290 
01291             // Set config properties.
01292         if (is_array($TSconfig['tags.']))   {
01293             foreach ($TSconfig['tags.'] as $key => $tagC) {
01294                 if (!is_array($tagC) && $key==strtolower($key)) {
01295                     if (!strcmp($tagC,'0')) unset($keepTags[$key]);
01296                     if (!strcmp($tagC,'1') && !isset($keepTags[$key]))  $keepTags[$key]=1;
01297                 }
01298             }
01299 
01300             foreach ($TSconfig['tags.'] as $key => $tagC)   {
01301                 if (is_array($tagC) && $key==strtolower($key))  {
01302                     $key=substr($key,0,-1);
01303                     if (!is_array($keepTags[$key])) $keepTags[$key]=array();
01304                     if (is_array($tagC['fixAttrib.']))  {
01305                         foreach ($tagC['fixAttrib.'] as $atName => $atConfig) {
01306                             if (is_array($atConfig))    {
01307                                 $atName=substr($atName,0,-1);
01308                                 if (!is_array($keepTags[$key]['fixAttrib'][$atName]))   {
01309                                     $keepTags[$key]['fixAttrib'][$atName]=array();
01310                                 }
01311                                 $keepTags[$key]['fixAttrib'][$atName] = array_merge($keepTags[$key]['fixAttrib'][$atName],$atConfig);       // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
01312                                 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['range'],''))  $keepTags[$key]['fixAttrib'][$atName]['range'] = t3lib_div::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['range']);
01313                                 if (strcmp($keepTags[$key]['fixAttrib'][$atName]['list'],''))   $keepTags[$key]['fixAttrib'][$atName]['list'] = t3lib_div::trimExplode(',',$keepTags[$key]['fixAttrib'][$atName]['list']);
01314                             }
01315                         }
01316                     }
01317                     unset($tagC['fixAttrib.']);
01318                     unset($tagC['fixAttrib']);
01319                     $keepTags[$key] = array_merge($keepTags[$key],$tagC);           // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
01320                 }
01321             }
01322         }
01323             // localNesting
01324         if ($TSconfig['localNesting'])  {
01325             $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['localNesting']),1);
01326             foreach ($lN as $tn) {
01327                 if (isset($keepTags[$tn]))  {
01328                     $keepTags[$tn]['nesting']=1;
01329                 }
01330             }
01331         }
01332         if ($TSconfig['globalNesting']) {
01333             $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['globalNesting']),1);
01334             foreach ($lN as $tn) {
01335                 if (isset($keepTags[$tn]))  {
01336                     if (!is_array($keepTags[$tn]))  $keepTags[$tn]=array();
01337                     $keepTags[$tn]['nesting']='global';
01338                 }
01339             }
01340         }
01341         if ($TSconfig['rmTagIfNoAttrib'])   {
01342             $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['rmTagIfNoAttrib']),1);
01343             foreach ($lN as $tn) {
01344                 if (isset($keepTags[$tn]))  {
01345                     if (!is_array($keepTags[$tn]))  $keepTags[$tn]=array();
01346                     $keepTags[$tn]['rmTagIfNoAttrib']=1;
01347                 }
01348             }
01349         }
01350         if ($TSconfig['noAttrib'])  {
01351             $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['noAttrib']),1);
01352             foreach ($lN as $tn) {
01353                 if (isset($keepTags[$tn]))  {
01354                     if (!is_array($keepTags[$tn]))  $keepTags[$tn]=array();
01355                     $keepTags[$tn]['allowedAttribs']=0;
01356                 }
01357             }
01358         }
01359         if ($TSconfig['removeTags'])    {
01360             $lN = t3lib_div::trimExplode(',',strtolower($TSconfig['removeTags']),1);
01361             foreach ($lN as $tn) {
01362                 $keepTags[$tn]=array();
01363                 $keepTags[$tn]['allowedAttribs']=0;
01364                 $keepTags[$tn]['rmTagIfNoAttrib']=1;
01365             }
01366         }
01367 
01368             // Create additional configuration:
01369         $addConfig=array();
01370         if ($TSconfig['xhtml_cleaning'])    {
01371             $addConfig['xhtml']=1;
01372         }
01373 
01374         return array(
01375             $keepTags,
01376             ''.$TSconfig['keepNonMatchedTags'],
01377             intval($TSconfig['htmlSpecialChars']),
01378             $addConfig
01379         );
01380     }
01381 
01382     /**
01383      * Tries to convert the content to be XHTML compliant and other stuff like that.
01384      * STILL EXPERIMENTAL. See comments below.
01385      *
01386      *          What it does NOT do (yet) according to XHTML specs.:
01387      *          - Wellformedness: Nesting is NOT checked
01388      *          - name/id attribute issue is not observed at this point.
01389      *          - Certain nesting of elements not allowed. Most interesting, <PRE> cannot contain img, big,small,sub,sup ...
01390      *          - Wrapping scripts and style element contents in CDATA - or alternatively they should have entitites converted.
01391      *          - Setting charsets may put some special requirements on both XML declaration/ meta-http-equiv. (C.9)
01392      *          - UTF-8 encoding is in fact expected by XML!!
01393      *          - stylesheet element and attribute names are NOT converted to lowercase
01394      *          - ampersands (and entities in general I think) MUST be converted to an entity reference! (&amps;). This may mean further conversion of non-tag content before output to page. May be related to the charset issue as a whole.
01395      *          - Minimized values not allowed: Must do this: selected="selected"
01396      *
01397      *          What it does at this point:
01398      *          - All tags (frame,base,meta,link + img,br,hr,area,input) is ended with "/>" - others?
01399      *          - Lowercase for elements and attributes
01400      *          - All attributes in quotes
01401      *          - Add "alt" attribute to img-tags if it's not there already.
01402      *
01403      * @param   string      Content to clean up
01404      * @return  string      Cleaned up content returned.
01405      * @access private
01406      */
01407     function XHTML_clean($content)  {
01408         $content = $this->HTMLcleaner(
01409             $content,
01410             array(),    // No tags treated specially
01411             1,          // Keep ALL tags.
01412             0,          // All content is htmlspecialchar()'ed (or ??) - if we do, <script> content will break...
01413             array('xhtml' => 1)
01414         );
01415         return $content;
01416     }
01417 
01418     /**
01419      * Processing all tags themselves
01420      * (Some additions by Sacha Vorbeck)
01421      *
01422      * @param   string      Tag to process
01423      * @param   array       Configuration array passing instructions for processing. If count()==0, function will return value unprocessed. See source code for details
01424      * @param   boolean     Is endtag, then set this.
01425      * @param   boolean     If set, just return value straight away
01426      * @return  string      Processed value.
01427      * @access private
01428      */
01429     function processTag($value,$conf,$endTag,$protected=0)  {
01430             // Return immediately if protected or no parameters
01431         if ($protected || !count($conf))    return $value;
01432             // OK then, begin processing for XHTML output:
01433             // STILL VERY EXPERIMENTAL!!
01434         if ($conf['xhtml']) {
01435             if ($endTag)    {   // Endtags are just set lowercase right away
01436                 $value = strtolower($value);
01437             } elseif (substr($value,0,4)!='<!--') { // ... and comments are ignored.
01438                 $inValue = substr($value,1,(substr($value,-2)=='/>'?-2:-1));    // Finding inner value with out < >
01439                 list($tagName,$tagP)=preg_split('/\s+/s',$inValue,2);   // Separate attributes and tagname
01440                 $tagName = strtolower($tagName);
01441 
01442                     // Process attributes
01443                 $tagAttrib = $this->get_tag_attributes($tagP);
01444                 if (!strcmp($tagName,'img') && !isset($tagAttrib[0]['alt']))        $tagAttrib[0]['alt']='';    // Set alt attribute for all images (not XHTML though...)
01445                 if (!strcmp($tagName,'script') && !isset($tagAttrib[0]['type']))    $tagAttrib[0]['type']='text/javascript';    // Set type attribute for all script-tags
01446                 $outA=array();
01447                 foreach ($tagAttrib[0] as $attrib_name => $attrib_value) {
01448                         // Set attributes: lowercase, always in quotes, with htmlspecialchars converted.
01449                     $outA[]=$attrib_name.'="'.$this->bidir_htmlspecialchars($attrib_value,2).'"';
01450                 }
01451                 $newTag='<'.trim($tagName.' '.implode(' ',$outA));
01452                     // All tags that are standalone (not wrapping, not having endtags) should be ended with '/>'
01453                 if (t3lib_div::inList('img,br,hr,meta,link,base,area,input,param,col',$tagName) || substr($value,-2)=='/>') {
01454                     $newTag.=' />';
01455                 } else {
01456                     $newTag.='>';
01457                 }
01458                 $value = $newTag;
01459             }
01460         }
01461 
01462         return $value;
01463     }
01464 
01465     /**
01466      * Processing content between tags for HTML_cleaner
01467      *
01468      * @param   string      The value
01469      * @param   integer     Direction, either -1 or +1. 0 (zero) means no change to input value.
01470      * @param   mixed       Not used, ignore.
01471      * @return  string      The processed value.
01472      * @access private
01473      */
01474     function processContent($value,$dir,$conf)  {
01475         if ($dir!=0)    $value = $this->bidir_htmlspecialchars($value,$dir);
01476         return $value;
01477     }
01478 }
01479 
01480 
01481 
01482 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_parsehtml.php']) {
01483     include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_parsehtml.php']);
01484 }
01485 
01486 ?>

Generated on Sat Jul 24 04:17:17 2010 for TYPO3 API by  doxygen 1.4.7