summaryrefslogtreecommitdiff
path: root/platform/www/inc/parser/code.php
blob: cded87d6d6ce217b31e99c651e1381c2f5943a6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
/**
 * A simple renderer that allows downloading of code and file snippets
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
class Doku_Renderer_code extends Doku_Renderer {
    protected $_codeblock = 0;

    /**
     * Send the wanted code block to the browser
     *
     * When the correct block was found it exits the script.
     *
     * @param string $text
     * @param string $language
     * @param string $filename
     */
    public function code($text, $language = null, $filename = '') {
        global $INPUT;
        if(!$language) $language = 'txt';
        $language = preg_replace(PREG_PATTERN_VALID_LANGUAGE, '', $language);
        if(!$filename) $filename = 'snippet.'.$language;
        $filename = \dokuwiki\Utf8\PhpString::basename($filename);
        $filename = \dokuwiki\Utf8\Clean::stripspecials($filename, '_');

        // send CRLF to Windows clients
        if(strpos($INPUT->server->str('HTTP_USER_AGENT'), 'Windows') !== false) {
            $text = str_replace("\n", "\r\n", $text);
        }

        if($this->_codeblock == $INPUT->str('codeblock')) {
            header("Content-Type: text/plain; charset=utf-8");
            header("Content-Disposition: attachment; filename=$filename");
            header("X-Robots-Tag: noindex");
            echo trim($text, "\r\n");
            exit;
        }

        $this->_codeblock++;
    }

    /**
     * Wraps around code()
     *
     * @param string $text
     * @param string $language
     * @param string $filename
     */
    public function file($text, $language = null, $filename = '') {
        $this->code($text, $language, $filename);
    }

    /**
     * This should never be reached, if it is send a 404
     */
    public function document_end() {
        http_status(404);
        echo '404 - Not found';
        exit;
    }

    /**
     * Return the format of the renderer
     *
     * @returns string 'code'
     */
    public function getFormat() {
        return 'code';
    }
}