View.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php declare(strict_types=1);
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. */
  11. namespace PrivateBin;
  12. use Exception;
  13. use GlobIterator;
  14. /**
  15. * View
  16. *
  17. * Displays the templates
  18. */
  19. class View
  20. {
  21. /**
  22. * variables available in the template
  23. *
  24. * @access private
  25. * @var array
  26. */
  27. private $_variables = array();
  28. /**
  29. * assign variables to be used inside of the template
  30. *
  31. * @access public
  32. * @param string $name
  33. * @param mixed $value
  34. */
  35. public function assign($name, $value)
  36. {
  37. $this->_variables[$name] = $value;
  38. }
  39. /**
  40. * render a template
  41. *
  42. * @access public
  43. * @param string $template
  44. * @throws Exception
  45. */
  46. public function draw($template)
  47. {
  48. $dir = PATH . 'tpl' . DIRECTORY_SEPARATOR;
  49. $file = substr($template, 0, 10) === 'bootstrap-' ? 'bootstrap' : $template;
  50. $path = $dir . $file . '.php';
  51. if (!is_file($path)) {
  52. throw new Exception('Template ' . $template . ' not found in file ' . $path . '!', 80);
  53. }
  54. if (!in_array($path, glob($dir . '*.php', GLOB_NOSORT | GLOB_ERR), true)) {
  55. throw new Exception('Template ' . $file . '.php not found in ' . $dir . '!', 81);
  56. }
  57. extract($this->_variables);
  58. include $path;
  59. }
  60. /**
  61. * echo script tag incl. SRI hash for given script file
  62. *
  63. * @access private
  64. * @param string $file
  65. * @param string $attributes additional attributes to add into the script tag
  66. */
  67. private function _scriptTag($file, $attributes = '')
  68. {
  69. $sri = array_key_exists($file, $this->_variables['SRI']) ?
  70. ' integrity="' . $this->_variables['SRI'][$file] . '"' : '';
  71. // if the file isn't versioned (ends in a digit), add our own version
  72. $cacheBuster = (bool) preg_match('#[0-9]\.js$#', (string) $file) ?
  73. '' : '?' . rawurlencode($this->_variables['VERSION']);
  74. echo '<script ', $attributes,
  75. ' type="text/javascript" data-cfasync="false" src="', $file,
  76. $cacheBuster, '"', $sri, ' crossorigin="anonymous"></script>', PHP_EOL;
  77. }
  78. }