5 protected $feeds = array();
7 public function __construct($directory = 'feeds')
9 $this->setDirectory($directory);
12 public function setDirectory($directory)
14 $this->directory
= $directory;
15 foreach (glob($this->directory
.'/*.xml') as $feed) {
16 $this->feeds
[basename($feed, '.xml')] = filemtime($feed);
20 public function url2name($url)
22 return preg_replace('/[^\w\.-]+/', '_', $url);
25 public function hasFeed($url)
27 return isset($this->feeds
[$this->url2name($url)]);
30 public function addFeed($url)
32 $r = $this->setupRequest($url);
34 $this->handleResponse($r);
37 public function addFeeds($urls)
39 $pool = new HttpRequestPool
;
40 foreach ($urls as $url) {
41 $pool->attach($r = $this->setupRequest($url));
45 foreach ($pool as $request) {
46 $this->handleResponse($request);
50 public function getFeed($url)
53 return $this->loadFeed($this->url2name($url));
56 public function getFeeds($urls)
59 $this->addFeeds($urls);
60 foreach ($urls as $url) {
61 $feeds[] = $this->loadFeed($this->url2name($url));
66 protected function saveFeed($file, $contents)
68 if (file_put_contents($this->directory
.'/'. $file .'.xml', $contents)) {
69 $this->feeds
[$file] = time();
71 throw new Exception("Could not save feed contents to $file.xml");
75 protected function loadFeed($file)
77 if (isset($this->feeds
[$file])) {
78 if ($data = file_get_contents($this->directory
.'/'. $file .'.xml')) {
81 throw new Exception("Could not load feed contents from $file.xml");
84 throw new Exception("Unknown feed/file $file.xml");
88 protected function setupRequest($url)
90 $r = new HttpRequest($url);
91 $r->setOptions(array('redirect' => true));
93 $file = $this->url2name($url);
95 if (isset($this->feeds
[$file])) {
96 $r->setOptions(array('lastmodified' => $this->feeds
[$file]));
102 protected function handleResponse(HttpRequest
$r)
104 if ($r->getResponseCode() != 304) {
105 if ($r->getResponseCode() != 200) {
106 throw new Exception("Unexpected response code ". $r->getResponseCode());
108 if (!strlen($body = $r->getResponseBody())) {
109 throw new Exception("Received empty feed from ". $r->getUrl());
111 $this->saveFeed($this->url2name($r->getUrl()), $body);