4 * Simple Feed Aggregator
7 * @copyright Michael Wallner, <mike@iworks.at>
8 * @license BSD, revised
26 protected $feeds = array();
31 * @param string $directory
33 public function __construct($directory = 'feeds')
35 $this->setDirectory($directory);
41 * @param string $directory
43 public function setDirectory($directory)
45 $this->directory
= $directory;
46 foreach (glob($this->directory
.'/*.xml') as $feed) {
47 $this->feeds
[basename($feed, '.xml')] = filemtime($feed);
52 * Strips all special chars
57 public function url2name($url)
59 return preg_replace('/[^\w\.-]+/', '_', $url);
63 * Checks if $url is a known feed
68 public function hasFeed($url)
70 return isset($this->feeds
[$this->url2name($url)]);
80 public function addFeed($url)
82 $r = $this->setupRequest($url);
84 $this->handleResponse($r);
88 * Add several URLs as feeds
94 public function addFeeds(array $urls)
96 $pool = new HttpRequestPool
;
97 foreach ($urls as $url) {
98 $pool->attach($r = $this->setupRequest($url));
102 foreach ($pool as $request) {
103 $this->handleResponse($request);
108 * Load a feed (from cache)
114 public function getFeed($url)
116 $this->addFeed($url);
117 return $this->loadFeed($this->url2name($url));
121 * Load several feeds (from cache)
127 public function getFeeds(array $urls)
130 $this->addFeeds($urls);
131 foreach ($urls as $url) {
132 $feeds[] = $this->loadFeed($this->url2name($url));
137 protected function saveFeed($file, $contents)
139 if (file_put_contents($this->directory
.'/'. $file .'.xml', $contents)) {
140 $this->feeds
[$file] = time();
142 throw new Exception("Could not save feed contents to $file.xml");
146 protected function loadFeed($file)
148 if (isset($this->feeds
[$file])) {
149 if ($data = file_get_contents($this->directory
.'/'. $file .'.xml')) {
152 throw new Exception("Could not load feed contents from $file.xml");
155 throw new Exception("Unknown feed/file $file.xml");
159 protected function setupRequest($url, $escape = true)
161 $r = new HttpRequest($url);
162 $r->setOptions(array('redirect' => true));
164 $file = $escape ?
$this->url2name($url) : $url;
166 if (isset($this->feeds
[$file])) {
167 $r->setOptions(array('lastmodified' => $this->feeds
[$file]));
173 protected function handleResponse(HttpRequest
$r)
175 if ($r->getResponseCode() != 304) {
176 if ($r->getResponseCode() != 200) {
177 throw new Exception("Unexpected response code ". $r->getResponseCode());
179 if (!strlen($body = $r->getResponseBody())) {
180 throw new Exception("Received empty feed from ". $r->getUrl());
182 $this->saveFeed($this->url2name($r->getUrl()), $body);