1

Topic: Example htmLawed config to filter style properties from TinyMCE

I've spent quite a bit of time investigating how to thoroughly sanitise html and inline css submitted from a TinyMCE textarea, without finding as straightforward a solution as I'd expected for such an essential process with such a widely used editor. This is adapted from an older post by patnaik (thanks!), and I thought someone might find it useful (or point out any obvious flaws!). It only lets through the specific style properties that I want TinyMCE to be able to set, eg text color, and doesn't allow any attributes other than style and href.

require_once('htmLawed.php');
$config = array('safe'=>1, 'cdata'=>1, 'comment'=>1, 'deny_attribute'=>'* -href -style', 'elements'=>'a, em, strong, p, hr, br, ul, ol, li, sub, sup, span, div', 'keep_bad'=>0, 'hook_tag' => 'my_css_filter');
$posted = htmLawed(stripslashes($_REQUEST['posted']), $config); 
$posted = mysql_real_escape_string($posted);
$out = htmLawed($in, $config);


function my_css_filter($element, $attribute_array=0){
    // If second argument is not received, it means a closing tag is being handled
    if(is_numeric($attribute_array)){
        return "</$element>";
    } 
    if (isset($attribute_array['style'])) {
        $css = explode(';', $attribute_array['style']);
        $style = array();
        foreach ($css as $v) {
            if (($p = strpos($v, ':')) > 1 && $p < strlen($v)) {
                $prop_name = trim(substr($v, 0, $p));
                $prop_val = trim(substr($v, $p+1));
                // this list might need adapting if you want to allow different properties
                if ($prop_name == 'color' || $prop_name == 'background-color' || $prop_name == 'font-size' || $prop_name == 'font-family' || $prop_name == 'text-align' || $prop_name == 'text-decoration' || $prop_name == 'padding-left') {
                    $style[] = "$prop_name: $prop_val";
                };
            };
        };
        if (!empty($style)){
            $attribute_array['style'] = implode('; ', $style);
        } else {
            unset($attribute_array['style']);
        };
    };
    $attributes = '';
    foreach ($attribute_array as $k=>$v) {
        $attributes .= " {$k}=\"{$v}\"";
    };
    static $empty_elements = array('br'=>1, 'hr'=>1);
    return "<{$element}{$attributes}". (isset($empty_elements[$element]) ? ' /' : ''). '>';
}

2

Re: Example htmLawed config to filter style properties from TinyMCE

Thanks for the config example... will be helpful to many.