- print doesn't like commas
[m6w6/ext-http] / docs / examples / Simple_Feed_Aggregator.php
1 <?php
2 class FeedAggregator
3 {
4 public $directory;
5 protected $feeds = array();
6
7 public function __construct($directory = 'feeds')
8 {
9 $this->setDirectory($directory);
10 }
11
12 public function setDirectory($directory)
13 {
14 $this->directory = $directory;
15 foreach (glob($this->directory .'/*.xml') as $feed) {
16 $this->feeds[basename($feed, '.xml')] = filemtime($feed);
17 }
18 }
19
20 public function url2name($url)
21 {
22 return preg_replace('/[^\w\.-]+/', '_', $url);
23 }
24
25 public function hasFeed($url)
26 {
27 return isset($this->feeds[$this->url2name($url)]);
28 }
29
30 public function addFeed($url)
31 {
32 $r = $this->setupRequest($url);
33 $r->send();
34 $this->handleResponse($r);
35 }
36
37 public function addFeeds($urls)
38 {
39 $pool = new HttpRequestPool;
40 foreach ($urls as $url) {
41 $pool->attach($r = $this->setupRequest($url));
42 }
43 $pool->send();
44
45 foreach ($pool as $request) {
46 $this->handleResponse($request);
47 }
48 }
49
50 public function getFeed($url)
51 {
52 $this->addFeed($url);
53 return $this->loadFeed($this->url2name($url));
54 }
55
56 public function getFeeds($urls)
57 {
58 $feeds = array();
59 $this->addFeeds($urls);
60 foreach ($urls as $url) {
61 $feeds[] = $this->loadFeed($this->url2name($url));
62 }
63 return $feeds;
64 }
65
66 protected function saveFeed($file, $contents)
67 {
68 if (file_put_contents($this->directory .'/'. $file .'.xml', $contents)) {
69 $this->feeds[$file] = time();
70 } else {
71 throw new Exception("Could not save feed contents to $file.xml");
72 }
73 }
74
75 protected function loadFeed($file)
76 {
77 if (isset($this->feeds[$file])) {
78 if ($data = file_get_contents($this->directory .'/'. $file .'.xml')) {
79 return $data;
80 } else {
81 throw new Exception("Could not load feed contents from $file.xml");
82 }
83 } else {
84 throw new Exception("Unknown feed/file $file.xml");
85 }
86 }
87
88 protected function setupRequest($url)
89 {
90 $r = new HttpRequest($url);
91 $r->setOptions(array('redirect' => true));
92
93 $file = $this->url2name($url);
94
95 if (isset($this->feeds[$file])) {
96 $r->setOptions(array('lastmodified' => $this->feeds[$file]));
97 }
98
99 return $r;
100 }
101
102 protected function handleResponse(HttpRequest $r)
103 {
104 if ($r->getResponseCode() != 304) {
105 if ($r->getResponseCode() != 200) {
106 throw new Exception("Unexpected response code ". $r->getResponseCode());
107 }
108 if (!strlen($body = $r->getResponseBody())) {
109 throw new Exception("Received empty feed from ". $r->getUrl());
110 }
111 $this->saveFeed($this->url2name($r->getUrl()), $body);
112 }
113 }
114 }
115 ?>