]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/feeddiscovery.php
Merge branch 'testing' into 0.9.x
[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') && !defined('LACONICA')) { exit(1); }
26
27 class FeedSubBadURLException extends FeedSubException
28 {
29 }
30
31 class FeedSubBadResponseException extends FeedSubException
32 {
33 }
34
35 class FeedSubEmptyException extends FeedSubException
36 {
37 }
38
39 class FeedSubBadHTMLException extends FeedSubException
40 {
41 }
42
43 class FeedSubUnrecognizedTypeException extends FeedSubException
44 {
45 }
46
47 class FeedSubNoFeedException extends FeedSubException
48 {
49 }
50
51 class FeedSubBadXmlException extends FeedSubException
52 {
53 }
54
55 class FeedSubNoHubException extends FeedSubException
56 {
57 }
58
59 /**
60  * Given a web page or feed URL, discover the final location of the feed
61  * and return its current contents.
62  *
63  * @example
64  *   $feed = new FeedDiscovery();
65  *   if ($feed->discoverFromURL($url)) {
66  *     print $feed->uri;
67  *     print $feed->type;
68  *     processFeed($feed->feed); // DOMDocument
69  *   }
70  */
71 class FeedDiscovery
72 {
73     public $uri;
74     public $type;
75     public $feed;
76
77     /** Post-initialize query helper... */
78     public function getLink($rel, $type=null)
79     {
80         // @fixme check for non-Atom links in RSS2 feeds as well
81         return self::getAtomLink($rel, $type);
82     }
83
84     public function getAtomLink($rel, $type=null)
85     {
86         return ActivityUtils::getLink($this->feed->documentElement, $rel, $type);
87     }
88
89     /**
90      * @param string $url
91      * @param bool $htmlOk pass false here if you don't want to follow web pages.
92      * @return string with validated URL
93      * @throws FeedSubBadURLException
94      * @throws FeedSubBadHtmlException
95      * @throws FeedSubNoFeedException
96      * @throws FeedSubEmptyException
97      * @throws FeedSubUnrecognizedTypeException
98      */
99     function discoverFromURL($url, $htmlOk=true)
100     {
101         try {
102             $client = new HTTPClient();
103             $response = $client->get($url);
104         } catch (HTTP_Request2_Exception $e) {
105             common_log(LOG_ERR, __METHOD__ . " Failure for $url - " . $e->getMessage());
106             throw new FeedSubBadURLException($e);
107         }
108
109         if ($htmlOk) {
110             $type = $response->getHeader('Content-Type');
111             $isHtml = preg_match('!^(text/html|application/xhtml\+xml)!i', $type);
112             if ($isHtml) {
113                 $target = $this->discoverFromHTML($response->getUrl(), $response->getBody());
114                 if (!$target) {
115                     throw new FeedSubNoFeedException($url);
116                 }
117                 return $this->discoverFromURL($target, false);
118             }
119         }
120
121         return $this->initFromResponse($response);
122     }
123
124     function discoverFromFeedURL($url)
125     {
126         return $this->discoverFromURL($url, false);
127     }
128
129     function initFromResponse($response)
130     {
131         if (!$response->isOk()) {
132             throw new FeedSubBadResponseException($response->getStatus());
133         }
134
135         $sourceurl = $response->getUrl();
136         $body = $response->getBody();
137         if (!$body) {
138             throw new FeedSubEmptyException($sourceurl);
139         }
140
141         $type = $response->getHeader('Content-Type');
142         if (preg_match('!^(text/xml|application/xml|application/(rss|atom)\+xml)!i', $type)) {
143             return $this->init($sourceurl, $type, $body);
144         } else {
145             common_log(LOG_WARNING, "Unrecognized feed type $type for $sourceurl");
146             throw new FeedSubUnrecognizedTypeException($type);
147         }
148     }
149
150     function init($sourceurl, $type, $body)
151     {
152         $feed = new DOMDocument();
153         if ($feed->loadXML($body)) {
154             $this->uri = $sourceurl;
155             $this->type = $type;
156             $this->feed = $feed;
157             return $this->uri;
158         } else {
159             throw new FeedSubBadXmlException($url);
160         }
161     }
162
163     /**
164      * @param string $url source URL, used to resolve relative links
165      * @param string $body HTML body text
166      * @return mixed string with URL or false if no target found
167      */
168     function discoverFromHTML($url, $body)
169     {
170         // DOMDocument::loadHTML may throw warnings on unrecognized elements.
171         $old = error_reporting(error_reporting() & ~E_WARNING);
172         $dom = new DOMDocument();
173         $ok = $dom->loadHTML($body);
174         error_reporting($old);
175
176         if (!$ok) {
177             throw new FeedSubBadHtmlException();
178         }
179
180         // Autodiscovery links may be relative to the page's URL or <base href>
181         $base = false;
182         $nodes = $dom->getElementsByTagName('base');
183         for ($i = 0; $i < $nodes->length; $i++) {
184             $node = $nodes->item($i);
185             if ($node->hasAttributes()) {
186                 $href = $node->attributes->getNamedItem('href');
187                 if ($href) {
188                     $base = trim($href->value);
189                 }
190             }
191         }
192         if ($base) {
193             $base = $this->resolveURI($base, $url);
194         } else {
195             $base = $url;
196         }
197
198         // Ok... now on to the links!
199         // Types listed in order of priority -- we'll prefer Atom if available.
200         // @fixme merge with the munger link checks
201         $feeds = array(
202             'application/atom+xml' => false,
203             'application/rss+xml' => false,
204         );
205
206         $nodes = $dom->getElementsByTagName('link');
207         for ($i = 0; $i < $nodes->length; $i++) {
208             $node = $nodes->item($i);
209             if ($node->hasAttributes()) {
210                 $rel = $node->attributes->getNamedItem('rel');
211                 $type = $node->attributes->getNamedItem('type');
212                 $href = $node->attributes->getNamedItem('href');
213                 if ($rel && $type && $href) {
214                     $rel = array_filter(explode(" ", $rel->value));
215                     $type = trim($type->value);
216                     $href = trim($href->value);
217
218                     if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
219                         // Save the first feed found of each type...
220                         $feeds[$type] = $this->resolveURI($href, $base);
221                     }
222                 }
223             }
224         }
225
226         // Return the highest-priority feed found
227         foreach ($feeds as $type => $url) {
228             if ($url) {
229                 return $url;
230             }
231         }
232
233         return false;
234     }
235
236     /**
237      * Resolve a possibly relative URL against some absolute base URL
238      * @param string $rel relative or absolute URL
239      * @param string $base absolute URL
240      * @return string absolute URL, or original URL if could not be resolved.
241      */
242     function resolveURI($rel, $base)
243     {
244         require_once "Net/URL2.php";
245         try {
246             $relUrl = new Net_URL2($rel);
247             if ($relUrl->isAbsolute()) {
248                 return $rel;
249             }
250             $baseUrl = new Net_URL2($base);
251             $absUrl = $baseUrl->resolve($relUrl);
252             return $absUrl->getURL();
253         } catch (Exception $e) {
254             common_log(LOG_WARNING, 'Unable to resolve relative link "' .
255                 $rel . '" against base "' . $base . '": ' . $e->getMessage());
256             return $rel;
257         }
258     }
259 }