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