]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/lib/oembedhelper.php
Moved oEmbed stuff out to a plugin (Oembed).
[quix0rs-gnu-social.git] / plugins / Oembed / 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         'youtube.com' => 'http://www.youtube.com/oembed',
47         'viddler.com' => 'http://lab.viddler.com/services/oembed/',
48         'qik.com' => 'http://qik.com/api/oembed.json',
49         'revision3.com' => 'http://revision3.com/api/oembed/',
50         'hulu.com' => 'http://www.hulu.com/api/oembed.json',
51         'vimeo.com' => 'http://www.vimeo.com/api/oembed.json',
52         'my.opera.com' => 'http://my.opera.com/service/oembed',
53     );
54     protected static $functionMap = array(
55         'twitpic.com' => 'oEmbedHelper::twitPic',
56     );
57
58     /**
59      * Perform or fake an oEmbed lookup for the given resource.
60      *
61      * Some known hosts are whitelisted with API endpoints where we
62      * know they exist but autodiscovery data isn't available.
63      * If autodiscovery links are missing and we don't recognize the
64      * host, we'll pass it to noembed.com's public service which
65      * will either proxy or fake info on a lot of sites.
66      *
67      * A few hosts are blacklisted due to known problems with oohembed,
68      * in which case we'll look up the info another way and return
69      * equivalent data.
70      *
71      * Throws exceptions on failure.
72      *
73      * @param string $url
74      * @param array $params
75      * @return object
76      */
77     public static function getObject($url, $params=array())
78     {
79         $host = parse_url($url, PHP_URL_HOST);
80         if (substr($host, 0, 4) == 'www.') {
81             $host = substr($host, 4);
82         }
83
84         common_log(LOG_INFO, 'Checking for oEmbed data for ' . $url);
85
86         // You can fiddle with the order of discovery -- either skipping
87         // some types or re-ordering them.
88
89         $order = common_config('oembed', 'order');
90
91         foreach ($order as $method) {
92
93             switch ($method) {
94             case 'built-in':
95                 common_log(LOG_INFO, 'Considering built-in oEmbed methods...');
96                 // Blacklist: systems with no oEmbed API of their own, which are
97                 // either missing from or broken on noembed.com's proxy.
98                 // we know how to look data up in another way...
99                 if (array_key_exists($host, self::$functionMap)) {
100                     common_log(LOG_INFO, 'We have a built-in method for ' . $host);
101                     $func = self::$functionMap[$host];
102                     return call_user_func($func, $url, $params);
103                 }
104                 break;
105             case 'well-known':
106                 common_log(LOG_INFO, 'Considering well-known oEmbed endpoints...');
107                 // Whitelist: known API endpoints for sites that don't provide discovery...
108                 if (array_key_exists($host, self::$apiMap)) {
109                     $api = self::$apiMap[$host];
110                     common_log(LOG_INFO, 'Using well-known endpoint "' . $api . '" for "' . $host . '"');
111                     break 2;
112                 }
113                 break;
114             case 'discovery':
115                 try {
116                     common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.');
117                     $api = self::discover($url);
118                     common_log(LOG_INFO, 'Found API endpoint ' . $api . ' for URL ' . $url);
119                     break 2;
120                 } catch (Exception $e) {
121                     common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers.');
122                     // Just ignore it!
123                 }
124                 break;
125             case 'service':
126                 $api = common_config('oembed', 'endpoint');
127                 common_log(LOG_INFO, 'Using service API endpoint ' . $api);
128                 break 2;
129                 break;
130             }
131         }
132
133         if (empty($api)) {
134             // TRANS: Server exception thrown in oEmbed action if no API endpoint is available.
135             throw new ServerException(_('No oEmbed API endpoint available.'));
136         }
137
138         return self::getObjectFrom($api, $url, $params);
139     }
140
141     /**
142      * Perform basic discovery.
143      * @return string
144      */
145     static function discover($url)
146     {
147         // @fixme ideally skip this for non-HTML stuff!
148         $body = self::http($url);
149         return self::discoverFromHTML($url, $body);
150     }
151
152     /**
153      * Partially ripped from OStatus' FeedDiscovery class.
154      *
155      * @param string $url source URL, used to resolve relative links
156      * @param string $body HTML body text
157      * @return mixed string with URL or false if no target found
158      */
159     static function discoverFromHTML($url, $body)
160     {
161         // DOMDocument::loadHTML may throw warnings on unrecognized elements,
162         // and notices on unrecognized namespaces.
163         $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
164         $dom = new DOMDocument();
165         $ok = $dom->loadHTML($body);
166         error_reporting($old);
167
168         if (!$ok) {
169             throw new oEmbedHelper_BadHtmlException();
170         }
171
172         // Ok... now on to the links!
173         $feeds = array(
174             'application/json+oembed' => false,
175         );
176
177         $nodes = $dom->getElementsByTagName('link');
178         for ($i = 0; $i < $nodes->length; $i++) {
179             $node = $nodes->item($i);
180             if ($node->hasAttributes()) {
181                 $rel = $node->attributes->getNamedItem('rel');
182                 $type = $node->attributes->getNamedItem('type');
183                 $href = $node->attributes->getNamedItem('href');
184                 if ($rel && $type && $href) {
185                     $rel = array_filter(explode(" ", $rel->value));
186                     $type = trim($type->value);
187                     $href = trim($href->value);
188
189                     if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
190                         // Save the first feed found of each type...
191                         $feeds[$type] = $href;
192                     }
193                 }
194             }
195         }
196
197         // Return the highest-priority feed found
198         foreach ($feeds as $type => $url) {
199             if ($url) {
200                 return $url;
201             }
202         }
203
204         throw new oEmbedHelper_DiscoveryException();
205     }
206
207     /**
208      * Actually do an oEmbed lookup to a particular API endpoint.
209      *
210      * @param string $api oEmbed API endpoint URL
211      * @param string $url target URL to look up info about
212      * @param array $params
213      * @return object
214      */
215     static function getObjectFrom($api, $url, $params=array())
216     {
217         $params['url'] = $url;
218         $params['format'] = 'json';
219         $key=common_config('oembed','apikey');
220         if(isset($key)) {
221             $params['key'] = common_config('oembed','apikey');
222         }
223         $data = self::json($api, $params);
224         return self::normalize($data);
225     }
226
227     /**
228      * Normalize oEmbed format.
229      *
230      * @param object $orig
231      * @return object
232      */
233     static function normalize($orig)
234     {
235         $data = clone($orig);
236
237         if (empty($data->type)) {
238             throw new Exception('Invalid oEmbed data: no type field.');
239         }
240
241         if ($data->type == 'image') {
242             // YFrog does this.
243             $data->type = 'photo';
244         }
245
246         if (isset($data->thumbnail_url)) {
247             if (!isset($data->thumbnail_width)) {
248                 // !?!?!
249                 $data->thumbnail_width = common_config('thumbnail', 'width');
250                 $data->thumbnail_height = common_config('thumbnail', 'height');
251             }
252         }
253
254         return $data;
255     }
256
257     /**
258      * Using a local function for twitpic lookups, as oohembed's adapter
259      * doesn't return a valid result:
260      * http://code.google.com/p/oohembed/issues/detail?id=19
261      *
262      * This code fetches metadata from Twitpic's own API, and attempts
263      * to guess proper thumbnail size from the original's size.
264      *
265      * @todo respect maxwidth and maxheight params
266      *
267      * @param string $url
268      * @param array $params
269      * @return object
270      */
271     static function twitPic($url, $params=array())
272     {
273         $matches = array();
274         if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) {
275             $id = $matches[1];
276         } else {
277             throw new Exception("Invalid twitpic URL");
278         }
279
280         // Grab metadata from twitpic's API...
281         // http://dev.twitpic.com/docs/2/media_show
282         $data = self::json('http://api.twitpic.com/2/media/show.json',
283                 array('id' => $id));
284         $oembed = (object)array('type' => 'photo',
285                                 'url' => 'http://twitpic.com/show/full/' . $data->short_id,
286                                 'width' => $data->width,
287                                 'height' => $data->height);
288         if (!empty($data->message)) {
289             $oembed->title = $data->message;
290         }
291
292         // Thumbnail is cropped and scaled to 150x150 box:
293         // http://dev.twitpic.com/docs/thumbnails/
294         $thumbSize = 150;
295         $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id;
296         $oembed->thumbnail_width = $thumbSize;
297         $oembed->thumbnail_height = $thumbSize;
298
299         return $oembed;
300     }
301
302     /**
303      * Fetch some URL and return JSON data.
304      *
305      * @param string $url
306      * @param array $params query-string params
307      * @return object
308      */
309     static protected function json($url, $params=array())
310     {
311         $data = self::http($url, $params);
312         return json_decode($data);
313     }
314
315     /**
316      * Hit some web API and return data on success.
317      * @param string $url
318      * @param array $params
319      * @return string
320      */
321     static protected function http($url, $params=array())
322     {
323         $client = HTTPClient::start();
324         if ($params) {
325             $query = http_build_query($params, null, '&');
326             if (strpos($url, '?') === false) {
327                 $url .= '?' . $query;
328             } else {
329                 $url .= '&' . $query;
330             }
331         }
332         $response = $client->get($url);
333         if ($response->isOk()) {
334             return $response->getBody();
335         } else {
336             throw new Exception('Bad HTTP response code: ' . $response->getStatus());
337         }
338     }
339 }
340
341 class oEmbedHelper_Exception extends Exception
342 {
343     public function __construct($message = "", $code = 0, $previous = null)
344     {
345         parent::__construct($message, $code);
346     }
347 }
348
349 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
350 {
351     function __construct($previous=null)
352     {
353         return parent::__construct('Bad HTML in discovery data.', 0, $previous);
354     }
355 }
356
357 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
358 {
359     function __construct($previous=null)
360     {
361         return parent::__construct('No oEmbed discovery data.', 0, $previous);
362     }
363 }