xref: /dokuwiki/inc/parser/code.php (revision badb3b57090d676d4332f4ffe9bb18c0fcfa16e5)
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        if(!$filename) $filename = 'snippet.'.$language;
25        $filename = utf8_basename($filename);
26        $filename = utf8_stripspecials($filename, '_');
27
28        // send CRLF to Windows clients
29        if(strpos($INPUT->server->str('HTTP_USER_AGENT'), 'Windows') !== false) {
30            $text = str_replace("\n", "\r\n", $text);
31        }
32
33        if($this->_codeblock == $INPUT->str('codeblock')) {
34            header("Content-Type: text/plain; charset=utf-8");
35            header("Content-Disposition: attachment; filename=$filename");
36            header("X-Robots-Tag: noindex");
37            echo trim($text, "\r\n");
38            exit;
39        }
40
41        $this->_codeblock++;
42    }
43
44    /**
45     * Wraps around code()
46     *
47     * @param string $text
48     * @param string $language
49     * @param string $filename
50     */
51    function file($text, $language = null, $filename = '') {
52        $this->code($text, $language, $filename);
53    }
54
55    /**
56     * This should never be reached, if it is send a 404
57     */
58    function document_end() {
59        http_status(404);
60        echo '404 - Not found';
61        exit;
62    }
63
64    /**
65     * Return the format of the renderer
66     *
67     * @returns string 'code'
68     */
69    function getFormat() {
70        return 'code';
71    }
72}
73