ckratelimit.php 1.5 KB

1234567891011121314151617181920212223242526
  1. <?php
  2. function ckratelimit($headers) {
  3. $aaheaders=[];
  4. array_shift($headers);
  5. foreach ($headers as $header)
  6. if (preg_match('#^([^:]+): (.*)$#',$header,$matches)===1)
  7. $aaheaders[strtolower($matches[1])]=$matches[2];
  8. //$aaheaders['x-ratelimit-remaining']=0;
  9. //print_r($aaheaders);
  10. if (!isset($aaheaders['date'])) return ['ok'=>false,'error'=>'no «date» header'];
  11. if (!isset($aaheaders['x-ratelimit-reset'])) return ['ok'=>false,'error'=>'no «x-ratelimit-reset» header'];
  12. if (!isset($aaheaders['x-ratelimit-remaining'])) return ['ok'=>false,'error'=>'no «x-ratelimit-remaining» header'];
  13. if (preg_match('#^\d+$#',$aaheaders['x-ratelimit-remaining'])!==1) return ['ok'=>false,'error'=>'«x-ratelimit-remaining» header is not an integer'];
  14. $remaining=$aaheaders['x-ratelimit-remaining']+0;
  15. $date=@strtotime($aaheaders['date']);
  16. if (!is_int($date)) return ['ok'=>false,'error'=>'«date» header could not be converted to a unix timestamp'];
  17. $reset=@strtotime($aaheaders['x-ratelimit-reset']);
  18. if (!is_int($reset)) return ['ok'=>false,'error'=>'«x-ratelimit-reset» header could not be converted to a unix timestamp'];
  19. // don't do the one on the line below, since it happens lots of times
  20. //if ($reset<$date) return ['ok'=>false,'error'=>'the unix timestamp parsed from «x-ratelimit-reset» header is less than the unix timestamp parsed from «date» header'];
  21. if ($remaining==0)
  22. return ['ok'=>true,'sleep'=>$reset-$date+1,'remaining'=>$remaining];
  23. else
  24. return ['ok'=>true,'sleep'=>0,'remaining'=>$remaining];
  25. }
  26. ?>