<?php

function equation_callback($match) {
  $ret = new html2text(str_replace('\\', '\\\\', $match[0]));
  return $ret->get_text();
}

class htmlFilter {
  public static function filterText($text, $edit = false) {
    if ($edit === false) $url = sfConfig::get('app_latex_service');
    else $url = sfConfig::get('app_latex_service_for_editor');
    return preg_replace('@\$\$(.*?)\$\$@', '<img src="'.$url.'$1" align="absmiddle"/>', $text);
  }

  public static function preFilter($text) {
    $config = array(
      'indent'           => false,
      'clean'            => true,
      'output-xhtml'     => true,
      'fix-backslash'    => false,
      'fix-bad-comments' => true,
      'hide-comments'    => true,
      'input-encoding'   => 'utf8',
      'char-encoding'    => 'utf8',
      'output-encoding'  => 'utf8',
      'show-body-only'   => true,
      'word-2000'        => false,
      'wrap'             => 0);
    $tidy = tidy_repair_string($text, $config, 'utf8');
    $text = preg_replace_callback('@\$\$.*?\$\$@', 'equation_callback', $tidy);
    $url  = preg_quote(sfConfig::get('app_latex_service_for_editor'));
    $text = preg_replace('@<img src="'.$url.'(.*?)" border="0" align="absmiddle" />@', '\$\$$1\$\$', $text);
    return $text;
  }

  public static function validateHtml($text) {
    $tidy = new tidy();
    if (!$tidy->parseString($text, array('input-encoding'=>'utf8', 'output-encoding'=>'utf8'))) return '';
    $content = '';
    foreach ($tidy->head()->child as $el) {
      if (@$el->name != 'title') $content .= $el->value;
    }
    foreach ($tidy->body()->child as $el) {
      $content .= $el->value;
    }
    return trim($content);
  }
}
