HttpTimeProvider.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace RobThree\Auth\Providers\Time;
  3. use DateTime;
  4. /**
  5. * Takes the time from any webserver by doing a HEAD request on the specified URL and extracting the 'Date:' header
  6. */
  7. class HttpTimeProvider implements ITimeProvider
  8. {
  9. /** @var string */
  10. public $url;
  11. /** @var string */
  12. public $expectedtimeformat;
  13. /** @var array */
  14. public $options;
  15. /**
  16. * @param string $url
  17. * @param string $expectedtimeformat
  18. * @param array $options
  19. */
  20. public function __construct($url = 'https://google.com', $expectedtimeformat = 'D, d M Y H:i:s O+', array $options = null)
  21. {
  22. $this->url = $url;
  23. $this->expectedtimeformat = $expectedtimeformat;
  24. if ($options === null) {
  25. $options = array(
  26. 'http' => array(
  27. 'method' => 'HEAD',
  28. 'follow_location' => false,
  29. 'ignore_errors' => true,
  30. 'max_redirects' => 0,
  31. 'request_fulluri' => true,
  32. 'header' => array(
  33. 'Connection: close',
  34. 'User-agent: TwoFactorAuth HttpTimeProvider (https://github.com/RobThree/TwoFactorAuth)',
  35. 'Cache-Control: no-cache'
  36. )
  37. )
  38. );
  39. }
  40. $this->options = $options;
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function getTime()
  46. {
  47. try {
  48. $context = stream_context_create($this->options);
  49. $fd = fopen($this->url, 'rb', false, $context);
  50. $headers = stream_get_meta_data($fd);
  51. fclose($fd);
  52. foreach ($headers['wrapper_data'] as $h) {
  53. if (strcasecmp(substr($h, 0, 5), 'Date:') === 0) {
  54. return DateTime::createFromFormat($this->expectedtimeformat, trim(substr($h, 5)))->getTimestamp();
  55. }
  56. }
  57. throw new \Exception('Invalid or no "Date:" header found');
  58. } catch (\Exception $ex) {
  59. throw new TimeException(sprintf('Unable to retrieve time from %s (%s)', $this->url, $ex->getMessage()));
  60. }
  61. }
  62. }