]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/feeddiscovery.php
Merge commit 'refs/merge-requests/199' of git://gitorious.org/statusnet/mainline...
[quix0rs-gnu-social.git] / plugins / OStatus / lib / feeddiscovery.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /**
21  * @package FeedSubPlugin
22  * @maintainer Brion Vibber <brion@status.net>
23  */
24
25 if (!defined('STATUSNET')) {
26     exit(1);
27 }
28
29 class FeedSubBadURLException extends FeedSubException
30 {
31 }
32
33 class FeedSubBadResponseException extends FeedSubException
34 {
35 }
36
37 class FeedSubEmptyException extends FeedSubException
38 {
39 }
40
41 class FeedSubBadHTMLException extends FeedSubException
42 {
43 }
44
45 class FeedSubUnrecognizedTypeException extends FeedSubException
46 {
47 }
48
49 class FeedSubNoFeedException extends FeedSubException
50 {
51 }
52
53 class FeedSubBadXmlException extends FeedSubException
54 {
55 }
56
57 class FeedSubNoHubException extends FeedSubException
58 {
59 }
60
61 /**
62  * Given a web page or feed URL, discover the final location of the feed
63  * and return its current contents.
64  *
65  * @example
66  *   $feed = new FeedDiscovery();
67  *   if ($feed->discoverFromURL($url)) {
68  *     print $feed->uri;
69  *     print $feed->type;
70  *     processFeed($feed->feed); // DOMDocument
71  *   }
72  */
73 class FeedDiscovery
74 {
75     public $uri;
76     public $type;
77     public $feed;
78     public $root;
79
80     /** Post-initialize query helper... */
81     public function getLink($rel, $type=null)
82     {
83         // @fixme check for non-Atom links in RSS2 feeds as well
84         return self::getAtomLink($rel, $type);
85     }
86
87     public function getAtomLink($rel, $type=null)
88     {
89         return ActivityUtils::getLink($this->root, $rel, $type);
90     }
91
92     /**
93      * Get the referenced PuSH hub link from an Atom feed.
94      *
95      * @return mixed string or false
96      */
97     public function getHubLink()
98     {
99         return $this->getAtomLink('hub');
100     }
101
102     /**
103      * @param string $url
104      * @param bool $htmlOk pass false here if you don't want to follow web pages.
105      * @return string with validated URL
106      * @throws FeedSubBadURLException
107      * @throws FeedSubBadHtmlException
108      * @throws FeedSubNoFeedException
109      * @throws FeedSubEmptyException
110      * @throws FeedSubUnrecognizedTypeException
111      */
112     function discoverFromURL($url, $htmlOk=true)
113     {
114         try {
115             $client = new HTTPClient();
116             $response = $client->get($url);
117         } catch (HTTP_Request2_Exception $e) {
118             common_log(LOG_ERR, __METHOD__ . " Failure for $url - " . $e->getMessage());
119             throw new FeedSubBadURLException($e->getMessage());
120         }
121
122         if ($htmlOk) {
123             $type = $response->getHeader('Content-Type');
124             $isHtml = preg_match('!^(text/html|application/xhtml\+xml)!i', $type);
125             if ($isHtml) {
126                 $target = $this->discoverFromHTML($response->getUrl(), $response->getBody());
127                 if (!$target) {
128                     throw new FeedSubNoFeedException($url);
129                 }
130                 return $this->discoverFromURL($target, false);
131             }
132         }
133
134         return $this->initFromResponse($response);
135     }
136
137     function discoverFromFeedURL($url)
138     {
139         return $this->discoverFromURL($url, false);
140     }
141
142     function initFromResponse($response)
143     {
144         if (!$response->isOk()) {
145             throw new FeedSubBadResponseException($response->getStatus());
146         }
147
148         $sourceurl = $response->getUrl();
149         $body = $response->getBody();
150         if (!$body) {
151             throw new FeedSubEmptyException($sourceurl);
152         }
153
154         $type = $response->getHeader('Content-Type');
155         if (preg_match('!^(text/xml|application/xml|application/(rss|atom)\+xml)!i', $type)) {
156             return $this->init($sourceurl, $type, $body);
157         } else {
158             common_log(LOG_WARNING, "Unrecognized feed type $type for $sourceurl");
159             throw new FeedSubUnrecognizedTypeException($type);
160         }
161     }
162
163     function init($sourceurl, $type, $body)
164     {
165         $feed = new DOMDocument();
166         if ($feed->loadXML($body)) {
167             $this->uri = $sourceurl;
168             $this->type = $type;
169             $this->feed = $feed;
170
171             $el = $this->feed->documentElement;
172
173             // Looking for the "root" element: RSS channel or Atom feed
174
175             if ($el->tagName == 'rss') {
176                 $channels = $el->getElementsByTagName('channel');
177                 if ($channels->length > 0) {
178                     $this->root = $channels->item(0);
179                 } else {
180                     throw new FeedSubBadXmlException($sourceurl);
181                 }
182             } else if ($el->tagName == 'feed') {
183                 $this->root = $el;
184             } else {
185                 throw new FeedSubBadXmlException($sourceurl);
186             }
187
188             return $this->uri;
189         } else {
190             throw new FeedSubBadXmlException($sourceurl);
191         }
192     }
193
194     /**
195      * @param string $url source URL, used to resolve relative links
196      * @param string $body HTML body text
197      * @return mixed string with URL or false if no target found
198      */
199     function discoverFromHTML($url, $body)
200     {
201         // DOMDocument::loadHTML may throw warnings on unrecognized elements,
202         // and notices on unrecognized namespaces.
203         $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
204         $dom = new DOMDocument();
205         $ok = $dom->loadHTML($body);
206         error_reporting($old);
207
208         if (!$ok) {
209             throw new FeedSubBadHtmlException();
210         }
211
212         // Autodiscovery links may be relative to the page's URL or <base href>
213         $base = false;
214         $nodes = $dom->getElementsByTagName('base');
215         for ($i = 0; $i < $nodes->length; $i++) {
216             $node = $nodes->item($i);
217             if ($node->hasAttributes()) {
218                 $href = $node->attributes->getNamedItem('href');
219                 if ($href) {
220                     $base = trim($href->value);
221                 }
222             }
223         }
224         if ($base) {
225             $base = $this->resolveURI($base, $url);
226         } else {
227             $base = $url;
228         }
229
230         // Ok... now on to the links!
231         // Types listed in order of priority -- we'll prefer Atom if available.
232         // @fixme merge with the munger link checks
233         $feeds = array(
234             'application/atom+xml' => false,
235             'application/rss+xml' => false,
236         );
237
238         $nodes = $dom->getElementsByTagName('link');
239         for ($i = 0; $i < $nodes->length; $i++) {
240             $node = $nodes->item($i);
241             if ($node->hasAttributes()) {
242                 $rel = $node->attributes->getNamedItem('rel');
243                 $type = $node->attributes->getNamedItem('type');
244                 $href = $node->attributes->getNamedItem('href');
245                 if ($rel && $type && $href) {
246                     $rel = array_filter(explode(" ", $rel->value));
247                     $type = trim($type->value);
248                     $href = trim($href->value);
249
250                     if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
251                         // Save the first feed found of each type...
252                         $feeds[$type] = $this->resolveURI($href, $base);
253                     }
254                 }
255             }
256         }
257
258         // Return the highest-priority feed found
259         foreach ($feeds as $type => $url) {
260             if ($url) {
261                 return $url;
262             }
263         }
264
265         return false;
266     }
267
268     /**
269      * Resolve a possibly relative URL against some absolute base URL
270      * @param string $rel relative or absolute URL
271      * @param string $base absolute URL
272      * @return string absolute URL, or original URL if could not be resolved.
273      */
274     function resolveURI($rel, $base)
275     {
276         require_once "Net/URL2.php";
277         try {
278             $relUrl = new Net_URL2($rel);
279             if ($relUrl->isAbsolute()) {
280                 return $rel;
281             }
282             $baseUrl = new Net_URL2($base);
283             $absUrl = $baseUrl->resolve($relUrl);
284             return $absUrl->getURL();
285         } catch (Exception $e) {
286             common_log(LOG_WARNING, 'Unable to resolve relative link "' .
287                 $rel . '" against base "' . $base . '": ' . $e->getMessage());
288             return $rel;
289         }
290     }
291 }