ActionController.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * MINZ - Copyright 2011 Marien Fressinaud
  4. * Sous licence AGPL3 <http://www.gnu.org/licenses/>
  5. */
  6. /**
  7. * The Minz_ActionController class is a controller in the MVC paradigm
  8. */
  9. class Minz_ActionController {
  10. protected $view;
  11. private $csp_policies = array(
  12. 'default-src' => "'self'",
  13. );
  14. // Gives the possibility to override the default View type.
  15. public static $viewType = 'Minz_View';
  16. public function __construct () {
  17. if (class_exists(self::$viewType)) {
  18. $this->view = new self::$viewType();
  19. } else {
  20. $this->view = new Minz_View();
  21. }
  22. $view_path = Minz_Request::controllerName() . '/' . Minz_Request::actionName() . '.phtml';
  23. $this->view->_path($view_path);
  24. $this->view->attributeParams ();
  25. }
  26. /**
  27. * Getteur
  28. */
  29. public function view () {
  30. return $this->view;
  31. }
  32. /**
  33. * Set CSP policies.
  34. *
  35. * A default-src directive should always be given.
  36. *
  37. * References:
  38. * - https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
  39. * - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/default-src
  40. *
  41. * @param array $policies An array where keys are directives and values are sources.
  42. */
  43. protected function _csp($policies) {
  44. if (!isset($policies['default-src'])) {
  45. $action = Minz_Request::controllerName() . '#' . Minz_Request::actionName();
  46. Minz_Log::warning(
  47. "Default CSP policy is not declared for action {$action}.",
  48. ADMIN_LOG
  49. );
  50. }
  51. $this->csp_policies = $policies;
  52. }
  53. /**
  54. * Send HTTP Content-Security-Policy header based on declared policies.
  55. */
  56. public function declareCspHeader() {
  57. $policies = [];
  58. foreach ($this->csp_policies as $directive => $sources) {
  59. $policies[] = $directive . ' ' . $sources;
  60. }
  61. header('Content-Security-Policy: ' . implode('; ', $policies));
  62. }
  63. /**
  64. * Méthodes à redéfinir (ou non) par héritage
  65. * firstAction est la première méthode exécutée par le Dispatcher
  66. * lastAction est la dernière
  67. */
  68. public function init () { }
  69. public function firstAction () { }
  70. public function lastAction () { }
  71. }