View.php 2.3 KB

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