code.php 2.0 KB

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