rST rendering is possible now
[phorkie.git] / src / phorkie / Renderer / ReStructuredText.php
1 <?php
2 namespace phorkie;
3
4 /**
5  * Requires cli program "rst2html" (python docutils) to be installed
6  */
7 class Renderer_ReStructuredText
8 {
9     /**
10      * Converts the rST to HTML
11      *
12      * @param File $file File to render
13      *
14      * @return string HTML
15      */
16     public function toHtml(File $file)
17     {
18         $descriptorspec = array(
19             0 => array('pipe', 'r'),//stdin
20             1 => array('pipe', 'w'),//stdout
21             2 => array('pipe', 'w') //stderr
22         );
23         $process = proc_open('rst2html', $descriptorspec, $pipes);
24         if (!is_resource($process)) {
25             //FIXME: fallback to geshi
26             return $file->getContent();
27         }
28
29         fwrite($pipes[0], $file->getContent());
30         fclose($pipes[0]);
31
32         $html = stream_get_contents($pipes[1]);
33         fclose($pipes[1]);
34
35         $errors = stream_get_contents($pipes[2]);
36         fclose($pipes[2]);
37
38         $retval = proc_close($process);
39
40         //cheap extraction of the rst html body
41         $html = substr($html, strpos($html, '<body>') + 6);
42         $html = substr($html, 0, strpos($html, '</body>'));
43
44         if ($retval != 0) {
45             $html = '<div class="alert">'
46                 . 'rst2html encountered some error; return value ' . $retval . '<br/>'
47                 . 'Error message:' . $errors
48                 . '</div>'
49                 . $html;
50         }
51
52         return $html;
53     }
54 }
55
56 ?>