IFrameUrlHelper.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Drupal\media;
  3. use Drupal\Component\Utility\Crypt;
  4. use Drupal\Core\PrivateKey;
  5. use Drupal\Core\Routing\RequestContext;
  6. use Drupal\Core\Site\Settings;
  7. /**
  8. * Providers helper functions for displaying oEmbed resources in an iFrame.
  9. *
  10. * @internal
  11. * This is an internal part of the oEmbed system and should only be used by
  12. * oEmbed-related code in Drupal core.
  13. */
  14. class IFrameUrlHelper {
  15. /**
  16. * The request context service.
  17. *
  18. * @var \Drupal\Core\Routing\RequestContext
  19. */
  20. protected $requestContext;
  21. /**
  22. * The private key service.
  23. *
  24. * @var \Drupal\Core\PrivateKey
  25. */
  26. protected $privateKey;
  27. /**
  28. * IFrameUrlHelper constructor.
  29. *
  30. * @param \Drupal\Core\Routing\RequestContext $request_context
  31. * The request context service.
  32. * @param \Drupal\Core\PrivateKey $private_key
  33. * The private key service.
  34. */
  35. public function __construct(RequestContext $request_context, PrivateKey $private_key) {
  36. $this->requestContext = $request_context;
  37. $this->privateKey = $private_key;
  38. }
  39. /**
  40. * Hashes an oEmbed resource URL.
  41. *
  42. * @param string $url
  43. * The resource URL.
  44. * @param int $max_width
  45. * (optional) The maximum width of the resource.
  46. * @param int $max_height
  47. * (optional) The maximum height of the resource.
  48. *
  49. * @return string
  50. * The hashed URL.
  51. */
  52. public function getHash($url, $max_width = NULL, $max_height = NULL) {
  53. return Crypt::hmacBase64("$url:$max_width:$max_height", $this->privateKey->get() . Settings::getHashSalt());
  54. }
  55. /**
  56. * Checks if an oEmbed URL can be securely displayed in an frame.
  57. *
  58. * @param string $url
  59. * The URL to check.
  60. *
  61. * @return bool
  62. * TRUE if the URL is considered secure, otherwise FALSE.
  63. */
  64. public function isSecure($url) {
  65. if (!$url) {
  66. return FALSE;
  67. }
  68. $url_host = parse_url($url, PHP_URL_HOST);
  69. $system_host = parse_url($this->requestContext->getCompleteBaseUrl(), PHP_URL_HOST);
  70. // The URL is secure if its domain is not the same as the domain of the base
  71. // URL of the current request.
  72. return $url_host && $system_host && $url_host !== $system_host;
  73. }
  74. }