xref: /dokuwiki/inc/parser/code.php (revision 68d9ab902296b21ef6bb4220780c9ea5b573c888)
1<?php
2/**
3 * A simple renderer that allows downloading of code and file snippets
4 *
5 * @author Andreas Gohr <andi@splitbrain.org>
6 */
7if(!defined('DOKU_INC')) die('meh.');
8
9class Doku_Renderer_code extends Doku_Renderer {
10    var $_codeblock = 0;
11
12    /**
13     * Send the wanted code block to the browser
14     *
15     * When the correct block was found it exits the script.
16     *
17     * @param string $text
18     * @param string $language
19     * @param string $filename
20     */
21    function code($text, $language = null, $filename = '') {
22        global $INPUT;
23        if(!$language) $language = 'txt';
24        $language = preg_replace(PREG_PATTERN_VALID_LANGUAGE, '', $language);
25        if(!$filename) $filename = 'snippet.'.$language;
26        $filename = utf8_basename($filename);
27        $filename = utf8_stripspecials($filename, '_');
28
29        // send CRLF to Windows clients
30        if(strpos($INPUT->server->str('HTTP_USER_AGENT'), 'Windows') !== false) {
31            $text = str_replace("\n", "\r\n", $text);
32        }
33
34        if($this->_codeblock == $INPUT->str('codeblock')) {
35            header("Content-Type: text/plain; charset=utf-8");
36            header("Content-Disposition: attachment; filename=$filename");
37            header("X-Robots-Tag: noindex");
38            echo trim($text, "\r\n");
39            exit;
40        }
41
42        $this->_codeblock++;
43    }
44
45    /**
46     * Wraps around code()
47     *
48     * @param string $text
49     * @param string $language
50     * @param string $filename
51     */
52    function file($text, $language = null, $filename = '') {
53        $this->code($text, $language, $filename);
54    }
55
56    /**
57     * This should never be reached, if it is send a 404
58     */
59    function document_end() {
60        http_status(404);
61        echo '404 - Not found';
62        exit;
63    }
64
65    /**
66     * Return the format of the renderer
67     *
68     * @returns string 'code'
69     */
70    function getFormat() {
71        return 'code';
72    }
73}
74