You are here

function htmltidy_run in HTML Tidy 5

Same name and namespace in other branches
  1. 6 htmltidy.module \htmltidy_run()
  2. 7 htmltidy.module \htmltidy_run()
1 call to htmltidy_run()
htmltidy_string in ./htmltidy.module
Process whatever we are given and return the htmltidy response The output and warnings will be returned as arrays by reference.

File

./htmltidy.module, line 546

Code

function htmltidy_run($input, $args, &$output, &$errors, &$warnings) {
  $tidypath = variable_get('htmltidy_apppath', '/usr/bin/tidy');
  if (!file_exists($tidypath)) {
    watchdog('htmltidy', t('Failed to find htmltidy executable at %htmltidy_apppath, not using tidy', array(
      '%htmltidy_apppath' => $tidypath,
    )), WATCHDOG_WARNING);
    $output = '';
    return 2;
  }

  // write input to a file because tidy doesn't take input from stdin.
  $dirtyFilename = tempnam(file_directory_temp(), 'drup');
  $f = fopen($dirtyFilename, 'w');
  fwrite($f, $input);
  fclose($f);

  // warnings are saved to file
  $warningsFilename = tempnam(file_directory_temp(), 'warn');
  $args[] = '-f ' . $warningsFilename;

  // Run Tidy with the right options.
  $command = $tidypath . ' ' . implode(' ', $args) . ' ' . $dirtyFilename;
  system($command, $return_value);

  // return_value 0 means success. 1 means warning. 2 means error, the file
  // will be there, but not have been touched.
  switch ($return_value) {
    case 0:
      $warnings = $errors = array();
      $output = file_get_contents($dirtyFilename);
      break;
    case 1:
      $errors = array();
      $warnings = array_map('trim', file($warningsFilename));
      $output = file_get_contents($dirtyFilename);
      break;
    case 2:

      // separate errors and warnings into two different arrays
      foreach (file($warningsFilename) as $line) {
        $line = trim($line);
        if (preg_match('|^line \\d+ column \\d+ - Warning:|', $line)) {
          $warnings[] = $line;
        }
        else {
          $errors[] = $line;
        }
      }
      $output = $input;
      break;
  }

  // delete the temporary files.
  unlink($dirtyFilename);
  unlink($warningsFilename);
  return $return_value;
}