You are here

function htmltidy_node_prepare in HTML Tidy 7

Implementation of hook_node_prepare().

File

./htmltidy.node.inc, line 11
The HTML Tidy hook implementations for Drupal's Node system.

Code

function htmltidy_node_prepare($node) {

  // We only have to tidy things on the edit form, not the create form.
  // As such, if this is new content, simply return.  There's nothing to tidy.
  if (!isset($node->nid)) {
    return;
  }

  // Get a list of all formats that have this filter enabled.
  $formats = htmltidy_get_formats();

  // Iterate through each field.
  $field_list = field_info_instances('node', $node->type);
  foreach ($field_list as $field_name => $field_data) {

    // Iterate through the language of each field.
    foreach ($node->{$field_name} as $language => $instances) {

      // Iterate through each language's instance.
      foreach ($instances as $instance_id => $instance) {

        // Skip through non-numerically keyed values to avoid items like
        // "[add_more] => Add another item".
        if (!is_numeric($instance_id)) {
          continue;
        }

        // Get a reference to the contents of this instance.
        $contents =& $node->{$field_name}[$language][$instance_id]['value'];

        // Act only on instances that are set to something.
        if (isset($contents)) {

          // Determine the text format of the instance.
          $format =& $node->{$field_name}[$language][$instance_id]['format'];

          // It's possible that the format may not be set because some field
          // types (like plain text) don't specify text formats.  As such, they
          // won't want any filters run on them.  We can simply ignore these
          // instances.
          // Check if this format has our filter enabled.
          if (isset($format) && array_key_exists($format, $formats)) {

            // If there are any settings, format them properly and remove
            // any extraneous data elements.
            if (isset($formats[$format])) {
              $settings = unserialize($formats[$format]);
              $settings = $settings['htmltidy_filter_' . $format];
            }

            // If not, create an empty container.
            $settings = isset($settings) ? $settings : array();

            // Replace the contents with a tidied version of itself.
            $contents = htmltidy_fragment($contents, FALSE, $settings, $errors, $warnings);

            // Report any errors.
            if (!empty($errors)) {
              $errors = array_map('htmlentities', $errors);
              form_set_error($field_name, theme('item_list', $errors));
            }
          }
        }
      }
    }
  }
}