]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/oembedhelper.php
Merge branch '1.0.x' into testing
[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         '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 oohembed.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 oohembed.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             throw new ServerException(_('No oEmbed API endpoint available.'));
135         }
136
137         return self::getObjectFrom($api, $url, $params);
138     }
139
140     /**
141      * Perform basic discovery.
142      * @return string
143      */
144     static function discover($url)
145     {
146         // @fixme ideally skip this for non-HTML stuff!
147         $body = self::http($url);
148         return self::discoverFromHTML($url, $body);
149     }
150
151     /**
152      * Partially ripped from OStatus' FeedDiscovery class.
153      *
154      * @param string $url source URL, used to resolve relative links
155      * @param string $body HTML body text
156      * @return mixed string with URL or false if no target found
157      */
158     static function discoverFromHTML($url, $body)
159     {
160         // DOMDocument::loadHTML may throw warnings on unrecognized elements,
161         // and notices on unrecognized namespaces.
162         $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
163         $dom = new DOMDocument();
164         $ok = $dom->loadHTML($body);
165         error_reporting($old);
166
167         if (!$ok) {
168             throw new oEmbedHelper_BadHtmlException();
169         }
170
171         // Ok... now on to the links!
172         $feeds = array(
173             'application/json+oembed' => false,
174         );
175
176         $nodes = $dom->getElementsByTagName('link');
177         for ($i = 0; $i < $nodes->length; $i++) {
178             $node = $nodes->item($i);
179             if ($node->hasAttributes()) {
180                 $rel = $node->attributes->getNamedItem('rel');
181                 $type = $node->attributes->getNamedItem('type');
182                 $href = $node->attributes->getNamedItem('href');
183                 if ($rel && $type && $href) {
184                     $rel = array_filter(explode(" ", $rel->value));
185                     $type = trim($type->value);
186                     $href = trim($href->value);
187
188                     if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
189                         // Save the first feed found of each type...
190                         $feeds[$type] = $href;
191                     }
192                 }
193             }
194         }
195
196         // Return the highest-priority feed found
197         foreach ($feeds as $type => $url) {
198             if ($url) {
199                 return $url;
200             }
201         }
202
203         throw new oEmbedHelper_DiscoveryException();
204     }
205
206     /**
207      * Actually do an oEmbed lookup to a particular API endpoint.
208      *
209      * @param string $api oEmbed API endpoint URL
210      * @param string $url target URL to look up info about
211      * @param array $params
212      * @return object
213      */
214     static function getObjectFrom($api, $url, $params=array())
215     {
216         $params['url'] = $url;
217         $params['format'] = 'json';
218         $data = self::json($api, $params);
219         return self::normalize($data);
220     }
221
222     /**
223      * Normalize oEmbed format.
224      *
225      * @param object $orig
226      * @return object
227      */
228     static function normalize($orig)
229     {
230         $data = clone($orig);
231
232         if (empty($data->type)) {
233             throw new Exception('Invalid oEmbed data: no type field.');
234         }
235
236         if ($data->type == 'image') {
237             // YFrog does this.
238             $data->type = 'photo';
239         }
240
241         if (isset($data->thumbnail_url)) {
242             if (!isset($data->thumbnail_width)) {
243                 // !?!?!
244                 $data->thumbnail_width = common_config('attachments', 'thumb_width');
245                 $data->thumbnail_height = common_config('attachments', 'thumb_height');
246             }
247         }
248
249         return $data;
250     }
251
252     /**
253      * Using a local function for twitpic lookups, as oohembed's adapter
254      * doesn't return a valid result:
255      * http://code.google.com/p/oohembed/issues/detail?id=19
256      *
257      * This code fetches metadata from Twitpic's own API, and attempts
258      * to guess proper thumbnail size from the original's size.
259      *
260      * @todo respect maxwidth and maxheight params
261      *
262      * @param string $url
263      * @param array $params
264      * @return object
265      */
266     static function twitPic($url, $params=array())
267     {
268         $matches = array();
269         if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) {
270             $id = $matches[1];
271         } else {
272             throw new Exception("Invalid twitpic URL");
273         }
274
275         // Grab metadata from twitpic's API...
276         // http://dev.twitpic.com/docs/2/media_show
277         $data = self::json('http://api.twitpic.com/2/media/show.json',
278                 array('id' => $id));
279         $oembed = (object)array('type' => 'photo',
280                                 'url' => 'http://twitpic.com/show/full/' . $data->short_id,
281                                 'width' => $data->width,
282                                 'height' => $data->height);
283         if (!empty($data->message)) {
284             $oembed->title = $data->message;
285         }
286
287         // Thumbnail is cropped and scaled to 150x150 box:
288         // http://dev.twitpic.com/docs/thumbnails/
289         $thumbSize = 150;
290         $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id;
291         $oembed->thumbnail_width = $thumbSize;
292         $oembed->thumbnail_height = $thumbSize;
293
294         return $oembed;
295     }
296
297     /**
298      * Fetch some URL and return JSON data.
299      *
300      * @param string $url
301      * @param array $params query-string params
302      * @return object
303      */
304     static protected function json($url, $params=array())
305     {
306         $data = self::http($url, $params);
307         return json_decode($data);
308     }
309
310     /**
311      * Hit some web API and return data on success.
312      * @param string $url
313      * @param array $params
314      * @return string
315      */
316     static protected function http($url, $params=array())
317     {
318         $client = HTTPClient::start();
319         if ($params) {
320             $query = http_build_query($params, null, '&');
321             if (strpos($url, '?') === false) {
322                 $url .= '?' . $query;
323             } else {
324                 $url .= '&' . $query;
325             }
326         }
327         $response = $client->get($url);
328         if ($response->isOk()) {
329             return $response->getBody();
330         } else {
331             throw new Exception('Bad HTTP response code: ' . $response->getStatus());
332         }
333     }
334 }
335
336 class oEmbedHelper_Exception extends Exception
337 {
338     public function __construct($message = "", $code = 0, $previous = null)
339     {
340         parent::__construct($message, $code);
341     }
342 }
343
344 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
345 {
346     function __construct($previous=null)
347     {
348         return parent::__construct('Bad HTML in discovery data.', 0, $previous);
349     }
350 }
351
352 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
353 {
354     function __construct($previous=null)
355     {
356         return parent::__construct('No oEmbed discovery data.', 0, $previous);
357     }
358 }