You are here

function _tablesaw_filter in Responsive Tables Filter 7

Filter callback for tablesaw filter.

1 string reference to '_tablesaw_filter'
responsive_tables_filter_filter_info in ./responsive_tables_filter.module
Implements hook_filter_info().

File

./responsive_tables_filter.module, line 84
Make tables responsive, when filter is enabled for the field.

Code

function _tablesaw_filter($text, $filter, $format, $langcode, $cache, $cache_id) {

  // Older versions of libxml always add DOCTYPE, <html>, and <body> tags.
  // See http://www.php.net/manual/en/libxml.constants.php.
  // Sometimes, PHP is >= 5.4, but libxml is old enough that the constants are
  // not defined.
  static $new_libxml;
  if (!isset($new_libxml)) {
    $new_libxml = defined(LIBXML_VERSION) && LIBXML_VERSION >= 20708;
  }
  if ($text != '') {
    $tables = array();
    libxml_use_internal_errors(TRUE);

    // LibXML requires that the html is wrapped in a root node.
    $rooted_text = '<root>' . $text . '</root>';
    $dom = new DOMDocument();
    if ($new_libxml) {
      $dom
        ->loadHTML(mb_convert_encoding($rooted_text, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    }
    else {
      $dom
        ->loadHTML(mb_convert_encoding($rooted_text, 'HTML-ENTITIES', 'UTF-8'));
    }

    // Retrieve user-defined tables defined by xpath, or default to table tag.
    $query = variable_get('responsive_tables_filter_table_xpath', FALSE);
    if ($query) {
      $xpath = new DOMXPath($dom);
      $tables = $xpath
        ->query($query);
    }
    else {
      $tables = $dom
        ->getElementsByTagName('table');
    }

    // Find all tables in text.
    if ($tables->length !== 0) {
      foreach ($tables as $table) {

        // Find existing class attributes, if any, and append tablesaw class.
        $existing_classes = $table
          ->getAttribute('class');
        if (strpos($existing_classes, 'no-tablesaw') === FALSE) {
          $new_classes = !empty($existing_classes) ? $existing_classes . ' tablesaw tablesaw-stack' : 'tablesaw tablesaw-stack';
          $table
            ->setAttribute('class', $new_classes);

          // Force data-tablesaw-mode attribute to be "stack".
          $table
            ->setAttribute('data-tablesaw-mode', 'stack');
        }
      }

      // Get innerHTML of root node.
      $html = "";
      foreach ($dom
        ->getElementsByTagName('root')
        ->item(0)->childNodes as $child) {

        // Re-serialize the HTML.
        $html .= $dom
          ->saveHTML($child);
      }

      // For lower older libxml, use preg_replace to clean up DOCTYPE.
      if (!$new_libxml && strpos($html, '<html><body>') != FALSE) {
        $html_start = strpos($html, '<html><body>') + 12;
        $html_length = strpos($html, '</body></html>') - $html_start;
        $html = substr($html, $html_start, $html_length);
      }
      return $html;
    }
  }
  return $text;
}