Welcome to the Question2Answer Q&A. There's also a demo if you just want to try it out.
+2 votes
2.3k views
in Q2A Core by
closed by

Following my post on How to modify qa-htmLawed.php to better sanitize/clean html posts I would like to share how to sanitize posted CSS styles.

The class and id attributes you can filter by using the config parameter of htmLawed:
$config['deny_attribute'] = 'class, id';
as it has beend described here: Stricter HTML Sanitizing in q2a by changing htmLawed config parameters

Now the big task was to filter style attributes that are unwanted by the admin, e.g. margin-top:200px; or the like.

The developer of htmLawed was so nice to help me out. I implemented the css filter function in qa-base.php:

1. go to function qa_sanitize_html_hook_tag.

2. There before $html='<'.$element; (line 734) you add the following code:

// only allow certain css style elements
if (isset($attributes['style'])) {
    $css = explode(';', $attributes['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));
            if ($prop_name == 'color' || $prop_name == 'background-color' || $prop_name == 'font-weight' || $prop_name == 'text-decoration' || $prop_name == 'width') {
                $style[] = "$prop_name: $prop_val";
            };
        };
    };
    if (!empty($style)){
        $attributes['style'] = implode('; ', $style);
    }
    else {
        unset($attributes['style']);
    };
};
// end


Result: All posted content and read content from the database that hold css styles apart from {color,background-color,font-weight,text-decoration,width} get filtered!

You can, of course, add your own whiteliste styles!

 

PS: The performance is not effected much "only ~10%-15% (to an overall time of ~16 ms in my setup)." thanks @patnaik

 

Result (example):

htmlawed example 1

htmlawed example 2

Q2A version: 1.5.3
closed with the note: done
...