3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2010, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET')) {
26 * Utility class to wrap basic oEmbed lookups.
28 * Blacklisted hosts will use an alternate lookup method:
31 * Whitelisted hosts will use known oEmbed API endpoints:
34 * Sites that provide discovery links will use them directly; a bug
35 * in use of discovery links with query strings is worked around.
37 * Others will fall back to oohembed (unless disabled).
38 * The API endpoint can be configured or disabled through config
39 * as 'oohembed'/'endpoint'.
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',
54 protected static $functionMap = array(
55 'twitpic.com' => 'oEmbedHelper::twitPic',
59 * Perform or fake an oEmbed lookup for the given resource.
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.
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
71 * Throws exceptions on failure.
74 * @param array $params
77 public static function getObject($url, $params=array())
79 $host = parse_url($url, PHP_URL_HOST);
80 if (substr($host, 0, 4) == 'www.') {
81 $host = substr($host, 4);
84 common_log(LOG_INFO, 'Checking for oEmbed data for ' . $url);
86 // You can fiddle with the order of discovery -- either skipping
87 // some types or re-ordering them.
89 $order = common_config('oembed', 'order');
91 foreach ($order as $method) {
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);
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 . '"');
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);
120 } catch (Exception $e) {
121 common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers.');
126 $api = common_config('oembed', 'endpoint');
127 common_log(LOG_INFO, 'Using service API endpoint ' . $api);
134 throw new ServerException(_('No oEmbed API endpoint available.'));
137 return self::getObjectFrom($api, $url, $params);
141 * Perform basic discovery.
144 static function discover($url)
146 // @fixme ideally skip this for non-HTML stuff!
147 $body = self::http($url);
148 return self::discoverFromHTML($url, $body);
152 * Partially ripped from OStatus' FeedDiscovery class.
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
158 static function discoverFromHTML($url, $body)
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);
168 throw new oEmbedHelper_BadHtmlException();
171 // Ok... now on to the links!
173 'application/json+oembed' => false,
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);
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;
196 // Return the highest-priority feed found
197 foreach ($feeds as $type => $url) {
203 throw new oEmbedHelper_DiscoveryException();
207 * Actually do an oEmbed lookup to a particular API endpoint.
209 * @param string $api oEmbed API endpoint URL
210 * @param string $url target URL to look up info about
211 * @param array $params
214 static function getObjectFrom($api, $url, $params=array())
216 $params['url'] = $url;
217 $params['format'] = 'json';
218 $data = self::json($api, $params);
219 return self::normalize($data);
223 * Normalize oEmbed format.
225 * @param object $orig
228 static function normalize($orig)
230 $data = clone($orig);
232 if (empty($data->type)) {
233 throw new Exception('Invalid oEmbed data: no type field.');
236 if ($data->type == 'image') {
238 $data->type = 'photo';
241 if (isset($data->thumbnail_url)) {
242 if (!isset($data->thumbnail_width)) {
244 $data->thumbnail_width = common_config('attachments', 'thumb_width');
245 $data->thumbnail_height = common_config('attachments', 'thumb_height');
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
257 * This code fetches metadata from Twitpic's own API, and attempts
258 * to guess proper thumbnail size from the original's size.
260 * @todo respect maxwidth and maxheight params
263 * @param array $params
266 static function twitPic($url, $params=array())
269 if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) {
272 throw new Exception("Invalid twitpic URL");
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',
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;
287 // Thumbnail is cropped and scaled to 150x150 box:
288 // http://dev.twitpic.com/docs/thumbnails/
290 $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id;
291 $oembed->thumbnail_width = $thumbSize;
292 $oembed->thumbnail_height = $thumbSize;
298 * Fetch some URL and return JSON data.
301 * @param array $params query-string params
304 static protected function json($url, $params=array())
306 $data = self::http($url, $params);
307 return json_decode($data);
311 * Hit some web API and return data on success.
313 * @param array $params
316 static protected function http($url, $params=array())
318 $client = HTTPClient::start();
320 $query = http_build_query($params, null, '&');
321 if (strpos($url, '?') === false) {
322 $url .= '?' . $query;
324 $url .= '&' . $query;
327 $response = $client->get($url);
328 if ($response->isOk()) {
329 return $response->getBody();
331 throw new Exception('Bad HTTP response code: ' . $response->getStatus());
336 class oEmbedHelper_Exception extends Exception
338 public function __construct($message = "", $code = 0, $previous = null)
340 parent::__construct($message, $code);
344 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
346 function __construct($previous=null)
348 return parent::__construct('Bad HTML in discovery data.', 0, $previous);
352 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
354 function __construct($previous=null)
356 return parent::__construct('No oEmbed discovery data.', 0, $previous);