]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/oembedhelper.php
8cd4a9dc4a96aaecf718ca6f45fe50704cd8faeb
[quix0rs-gnu-social.git] / lib / oembedhelper.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008-2010, 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 if (!defined('STATUSNET')) {
21     exit(1);
22 }
23
24
25 /**
26  * Utility class to wrap basic oEmbed lookups.
27  *
28  * Blacklisted hosts will use an alternate lookup method:
29  *  - Twitpic
30  *
31  * Whitelisted hosts will use known oEmbed API endpoints:
32  *  - Flickr, YFrog
33  *
34  * Sites that provide discovery links will use them directly; a bug
35  * in use of discovery links with query strings is worked around.
36  *
37  * Others will fall back to oohembed (unless disabled).
38  * The API endpoint can be configured or disabled through config
39  * as 'oohembed'/'endpoint'.
40  */
41 class oEmbedHelper
42 {
43     protected static $apiMap = array(
44         'flickr.com' => 'http://www.flickr.com/services/oembed/',
45         'yfrog.com' => 'http://www.yfrog.com/api/oembed',
46     );
47     protected static $functionMap = array(
48         'twitpic.com' => 'oEmbedHelper::twitPic',
49     );
50
51     /**
52      * Perform or fake an oEmbed lookup for the given resource.
53      *
54      * Some known hosts are whitelisted with API endpoints where we
55      * know they exist but autodiscovery data isn't available.
56      * If autodiscovery links are missing and we don't recognize the
57      * host, we'll pass it to oohembed.com's public service which
58      * will either proxy or fake info on a lot of sites.
59      *
60      * A few hosts are blacklisted due to known problems with oohembed,
61      * in which case we'll look up the info another way and return
62      * equivalent data.
63      *
64      * Throws exceptions on failure.
65      *
66      * @param string $url
67      * @param array $params
68      * @return object
69      */
70     public static function getObject($url, $params=array())
71     {
72         $host = parse_url($url, PHP_URL_HOST);
73         if (substr($host, 0, 4) == 'www.') {
74             $host = substr($host, 4);
75         }
76
77         // Blacklist: systems with no oEmbed API of their own, which are
78         // either missing from or broken on oohembed.com's proxy.
79         // we know how to look data up in another way...
80         if (array_key_exists($host, self::$functionMap)) {
81             $func = self::$functionMap[$host];
82             return call_user_func($func, $url, $params);
83         }
84
85         // Whitelist: known API endpoints for sites that don't provide discovery...
86         if (array_key_exists($host, self::$apiMap)) {
87             $api = self::$apiMap[$host];
88         } else {
89             try {
90                 $api = self::discover($url);
91             } catch (Exception $e) {
92                 // Discovery failed... fall back to oohembed if enabled.
93                 $oohembed = common_config('oohembed', 'endpoint');
94                 if ($oohembed) {
95                     $api = $oohembed;
96                 } else {
97                     throw $e;
98                 }
99             }
100         }
101         return self::getObjectFrom($api, $url, $params);
102     }
103
104     /**
105      * Perform basic discovery.
106      * @return string
107      */
108     static function discover($url)
109     {
110         // @fixme ideally skip this for non-HTML stuff!
111         $body = self::http($url);
112         return self::discoverFromHTML($url, $body);
113     }
114
115     /**
116      * Partially ripped from OStatus' FeedDiscovery class.
117      *
118      * @param string $url source URL, used to resolve relative links
119      * @param string $body HTML body text
120      * @return mixed string with URL or false if no target found
121      */
122     static function discoverFromHTML($url, $body)
123     {
124         // DOMDocument::loadHTML may throw warnings on unrecognized elements,
125         // and notices on unrecognized namespaces.
126         $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
127         $dom = new DOMDocument();
128         $ok = $dom->loadHTML($body);
129         error_reporting($old);
130
131         if (!$ok) {
132             throw new oEmbedHelper_BadHtmlException();
133         }
134
135         // Ok... now on to the links!
136         $feeds = array(
137             'application/json+oembed' => false,
138         );
139
140         $nodes = $dom->getElementsByTagName('link');
141         for ($i = 0; $i < $nodes->length; $i++) {
142             $node = $nodes->item($i);
143             if ($node->hasAttributes()) {
144                 $rel = $node->attributes->getNamedItem('rel');
145                 $type = $node->attributes->getNamedItem('type');
146                 $href = $node->attributes->getNamedItem('href');
147                 if ($rel && $type && $href) {
148                     $rel = array_filter(explode(" ", $rel->value));
149                     $type = trim($type->value);
150                     $href = trim($href->value);
151
152                     if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
153                         // Save the first feed found of each type...
154                         $feeds[$type] = $href;
155                     }
156                 }
157             }
158         }
159
160         // Return the highest-priority feed found
161         foreach ($feeds as $type => $url) {
162             if ($url) {
163                 return $url;
164             }
165         }
166
167         return false;
168         throw new oEmbedHelper_DiscoveryException();
169     }
170
171     /**
172      * Actually do an oEmbed lookup to a particular API endpoint.
173      *
174      * @param string $api oEmbed API endpoint URL
175      * @param string $url target URL to look up info about
176      * @param array $params
177      * @return object
178      */
179     static function getObjectFrom($api, $url, $params=array())
180     {
181         $params['url'] = $url;
182         $params['format'] = 'json';
183         $data = self::json($api, $params);
184         return self::normalize($data);
185     }
186
187     /**
188      * Normalize oEmbed format.
189      *
190      * @param object $orig
191      * @return object
192      */
193     static function normalize($orig)
194     {
195         $data = clone($orig);
196
197         if (empty($data->type)) {
198             throw new Exception('Invalid oEmbed data: no type field.');
199         }
200
201         if ($data->type == 'image') {
202             // YFrog does this.
203             $data->type = 'photo';
204         }
205
206         if (isset($data->thumbnail_url)) {
207             if (!isset($data->thumbnail_width)) {
208                 // !?!?!
209                 $data->thumbnail_width = common_config('attachments', 'thumb_width');
210                 $data->thumbnail_height = common_config('attachments', 'thumb_height');
211             }
212         }
213
214         return $data;
215     }
216
217     /**
218      * Using a local function for twitpic lookups, as oohembed's adapter
219      * doesn't return a valid result:
220      * http://code.google.com/p/oohembed/issues/detail?id=19
221      *
222      * This code fetches metadata from Twitpic's own API, and attempts
223      * to guess proper thumbnail size from the original's size.
224      *
225      * @todo respect maxwidth and maxheight params
226      *
227      * @param string $url
228      * @param array $params
229      * @return object
230      */
231     static function twitPic($url, $params=array())
232     {
233         $matches = array();
234         if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) {
235             $id = $matches[1];
236         } else {
237             throw new Exception("Invalid twitpic URL");
238         }
239
240         // Grab metadata from twitpic's API...
241         // http://dev.twitpic.com/docs/2/media_show
242         $data = self::json('http://api.twitpic.com/2/media/show.json',
243                 array('id' => $id));
244         $oembed = (object)array('type' => 'photo',
245                                 'url' => 'http://twitpic.com/show/full/' . $data->short_id,
246                                 'width' => $data->width,
247                                 'height' => $data->height);
248         if (!empty($data->message)) {
249             $oembed->title = $data->message;
250         }
251
252         // Thumbnail is cropped and scaled to 150x150 box:
253         // http://dev.twitpic.com/docs/thumbnails/
254         $thumbSize = 150;
255         $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id;
256         $oembed->thumbnail_width = $thumbSize;
257         $oembed->thumbnail_height = $thumbSize;
258
259         return $oembed;
260     }
261
262     /**
263      * Fetch some URL and return JSON data.
264      *
265      * @param string $url
266      * @param array $params query-string params
267      * @return object
268      */
269     static protected function json($url, $params=array())
270     {
271         $data = self::http($url, $params);
272         return json_decode($data);
273     }
274
275     /**
276      * Hit some web API and return data on success.
277      * @param string $url
278      * @param array $params
279      * @return string
280      */
281     static protected function http($url, $params=array())
282     {
283         $client = HTTPClient::start();
284         if ($params) {
285             $query = http_build_query($params, null, '&');
286             if (strpos($url, '?') === false) {
287                 $url .= '?' . $query;
288             } else {
289                 $url .= '&' . $query;
290             }
291         }
292         $response = $client->get($url);
293         if ($response->isOk()) {
294             return $response->getBody();
295         } else {
296             throw new Exception('Bad HTTP response code: ' . $response->getStatus());
297         }
298     }
299 }
300
301 class oEmbedHelper_Exception extends Exception
302 {
303 }
304
305 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
306 {
307     function __construct($previous=null)
308     {
309         return parent::__construct('Bad HTML in discovery data.', 0, $previous);
310     }
311 }
312
313 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
314 {
315     function __construct($previous=null)
316     {
317         return parent::__construct('No oEmbed discovery data.', 0, $previous);
318     }
319 }