1 filter.module _filter_image_align($text)

Implements callback_filter_process().

Replaces img data-align attributes with figure and figcaption elements.

Related topics

File

core/modules/filter/filter.module, line 2597
Framework for handling the filtering of content.

Code

function _filter_image_align($text) {
  if (stristr($text, 'data-align') === FALSE) {
    return $text;
  }

  // Load the text as a DOM object for manipulation.
  $dom = filter_dom_load($text);
  $xpath = new DOMXPath($dom);

  foreach ($xpath->query('//*[@data-align]') as $node) {
    // Read the data-align attribute's value, then delete it.
    $align = $node->getAttribute('data-align');
    $node->removeAttribute('data-align');

    // If one of the allowed alignments, add the corresponding class.
    if (in_array($align, array('left', 'center', 'right'))) {
      // If the image is under a figure, apply the class to the wrapper.
      $parent = $node->parentNode;
      if ($parent && $parent->nodeName === 'figure') {
        $target = $parent;
      }
      else {
        $target = $node;
      }
      $classes = $target->getAttribute('class');
      $classes = (strlen($classes) > 0) ? explode(' ', $classes) : array();
      $classes[] = 'align-' . $align;
      $target->setAttribute('class', implode(' ', $classes));

      // Center aligned content requires an additional wrapper to set
      // text-align: center.
      if ($align === 'center') {
        $wrapper_div = $dom->createElement('div');
        $wrapper_attribute = $dom->createAttribute('class');
        $wrapper_attribute->value = 'centered-wrapper';
        $wrapper_div->appendChild($wrapper_attribute);
        $wrapper_div->appendChild($target->cloneNode(TRUE));
        $target->parentNode->replaceChild($wrapper_div, $target);
      }
    }
  }

  return filter_dom_serialize($dom);
}