You are here

function _htmlpurifier_add_css in HTML Purifier 7

Same name and namespace in other branches
  1. 6.2 htmlpurifier.module \_htmlpurifier_add_css()
  2. 7.2 htmlpurifier.module \_htmlpurifier_add_css()

Helper function for hook_nodeapi Finds extracted style blocks based on a cache link left by hook_filter Aggregates the extracted style blocks and adds them to the document head Also removes the cache link left in hook_filter to the CSS cache

Parameters

string &$field: Field to process, this should be the actual field value ex. $node->content['body']['#value']

int $nid: Node ID of the node to which these stylesheets belong Since filters don't know their node context, we have to use a token to generate the stylesheet scope, and replace it in hook_nodeapi

1 call to _htmlpurifier_add_css()
htmlpurifier_nodeapi in ./htmlpurifier.module
Implements of hook_nodeapi().

File

./htmlpurifier.module, line 172
Implements HTML Purifier as a Drupal filter.

Code

function _htmlpurifier_add_css(&$field, $nid) {

  // Some basic validation to assure we really got a rendered field
  if (!is_string($field)) {
    return;
  }
  $cache_matches = array();
  $cache_match = preg_match('#<!-- HTML Purifier Cache \\#([-\\w]*:[\\w]*) -->#', $field, $cache_matches);

  // If there's an HTML Purifier Cache #, we need to load CSSTidy blocks
  if ($cache_match == 1) {
    $cid = 'css:' . $cache_matches[1];
    $old = cache_get($cid, 'cache_htmlpurifier');

    // We should always have some cached style blocks to load, but if we don't, just bail
    if ($old) {
      $styles = array();
      $style_rendered = '';
      foreach ($old->data as $i => $style) {

        // Replace Node ID tokens if necessary, otherwise use cached CSSTidy blocks
        // NOTE: This token is forgeable, but we expect that if the user
        // is able to invoke this transformation, it will be relatively
        // harmless.
        if (strpos($style, '[%HTMLPURIFIER:NID%]') !== FALSE) {
          $styles[$i] = str_replace('[%HTMLPURIFIER:NID%]', (int) $nid, $style);
        }
        else {
          $styles[$i] = $style;
        }

        // Save any CSSTidy blocks we find to be rendered in the document head
        if (!empty($style)) {
          $style_rendered .= $styles[$i] . "\n";
        }
      }

      // Add the rendered stylesheet to the document header
      if ($style_rendered != '') {
        drupal_set_html_head('<style type="text/css">' . "\n" . '<!--' . "\n" . $style_rendered . '--></style>');
      }

      // Remove the HTML Purifier cache key from the field argument
      $field = str_replace($cache_matches[0], '', $field);

      // If we had to update CSSTidy blocks, cache the results
      if ($old->data != $styles) {
        cache_set($cid, $styles, 'cache_htmlpurifier', CACHE_PERMANENT);
      }
    }
  }
}