HttpTimeProvider.php 1.9 KB

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