GriefNorth

Untitled

Sep 8th, 2013
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. class curs
  2. {
  3. const REFRESH_INTERVAL=3600;
  4. private $dataFile;
  5. private $source = "http://www.cbr.ru/scripts/XML_daily.asp";
  6. private $refreshTime;
  7. public $cursNew;
  8. public $cursOld;
  9.  
  10. private $error;
  11.  
  12. public function __construct($dataFile)
  13. {
  14. $this->dataFile=$dataFile;
  15.  
  16. if(!$f=fopen($this->dataFile, "r")) {
  17. $this->refresh();
  18. $this->error=true;
  19. return false;
  20. }
  21. $data=fread($f, filesize($this->dataFile));
  22. fclose($f);
  23. $data=unserialize($data);
  24. $this->refreshTime=$data['refresh_time'];
  25. $this->cursNew=$data['curs']['new'];
  26. $this->cursOld=$data['curs']['old'];
  27. $this->refresh();
  28. }
  29.  
  30. public function save()
  31. {
  32. $data=array(
  33. "refresh_time"=>$this->refreshTime,
  34. "curs" => array(
  35. "new"=>$this->cursNew,
  36. "old"=>$this->cursOld
  37. )
  38. );
  39.  
  40.  
  41. if(!$f=fopen($this->dataFile, "w+")) return false;
  42. fwrite($f, serialize($data));
  43. fclose($f);
  44. }
  45.  
  46. public function refresh()
  47. {
  48. if((time()-self::REFRESH_INTERVAL)<$this->refreshTime) return true;
  49.  
  50. if(isset($this->cursNew['date']) && $this->cursNew['date']>=$this->get_timestamp(date("d.m.y"))) return true;
  51.  
  52. $new_data=$this->readFromCbr();
  53. $this->refreshTime=time();
  54. if(is_array($new_data)){
  55. if($new_data['date']>$this->cursNew['date']){
  56. $this->cursOld=$this->cursNew;
  57. $this->cursNew=$new_data;
  58. $this->save();
  59. } else {
  60. return true;
  61. }
  62. } else {
  63. return false;
  64. }
  65. }
  66.  
  67. private function readFromCbr()
  68. {
  69. if(!$xml=simplexml_load_file($this->source)) return false;
  70. $curs['date']=self::get_timestamp($xml->attributes()->Date);
  71. foreach($xml->Valute as $m){
  72. if($m->CharCode=="USD" || $m->CharCode=="EUR"){
  73. $curs[(string)$m->CharCode]=(float)str_replace(",", ".", (string)$m->Value);
  74. }
  75. }
  76. return $curs;
  77. }
  78.  
  79. public static function get_timestamp($date)
  80. {
  81. list($d, $m, $y) = explode('.', $date);
  82. return mktime(0, 0, 0, $m, $d, $y);
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment