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 // TRANS: Server exception thrown in oEmbed action if no API endpoint is available.
135 throw new ServerException(_('No oEmbed API endpoint available.'));
138 return self::getObjectFrom($api, $url, $params);
142 * Perform basic discovery.
145 static function discover($url)
147 // @fixme ideally skip this for non-HTML stuff!
148 $body = self::http($url);
149 return self::discoverFromHTML($url, $body);
153 * Partially ripped from OStatus' FeedDiscovery class.
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
159 static function discoverFromHTML($url, $body)
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);
169 throw new oEmbedHelper_BadHtmlException();
172 // Ok... now on to the links!
174 'application/json+oembed' => false,
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);
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;
197 // Return the highest-priority feed found
198 foreach ($feeds as $type => $url) {
204 throw new oEmbedHelper_DiscoveryException();
208 * Actually do an oEmbed lookup to a particular API endpoint.
210 * @param string $api oEmbed API endpoint URL
211 * @param string $url target URL to look up info about
212 * @param array $params
215 static function getObjectFrom($api, $url, $params=array())
217 $params['url'] = $url;
218 $params['format'] = 'json';
219 $data = self::json($api, $params);
220 return self::normalize($data);
224 * Normalize oEmbed format.
226 * @param object $orig
229 static function normalize($orig)
231 $data = clone($orig);
233 if (empty($data->type)) {
234 throw new Exception('Invalid oEmbed data: no type field.');
237 if ($data->type == 'image') {
239 $data->type = 'photo';
242 if (isset($data->thumbnail_url)) {
243 if (!isset($data->thumbnail_width)) {
245 $data->thumbnail_width = common_config('attachments', 'thumb_width');
246 $data->thumbnail_height = common_config('attachments', 'thumb_height');
254 * Using a local function for twitpic lookups, as oohembed's adapter
255 * doesn't return a valid result:
256 * http://code.google.com/p/oohembed/issues/detail?id=19
258 * This code fetches metadata from Twitpic's own API, and attempts
259 * to guess proper thumbnail size from the original's size.
261 * @todo respect maxwidth and maxheight params
264 * @param array $params
267 static function twitPic($url, $params=array())
270 if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) {
273 throw new Exception("Invalid twitpic URL");
276 // Grab metadata from twitpic's API...
277 // http://dev.twitpic.com/docs/2/media_show
278 $data = self::json('http://api.twitpic.com/2/media/show.json',
280 $oembed = (object)array('type' => 'photo',
281 'url' => 'http://twitpic.com/show/full/' . $data->short_id,
282 'width' => $data->width,
283 'height' => $data->height);
284 if (!empty($data->message)) {
285 $oembed->title = $data->message;
288 // Thumbnail is cropped and scaled to 150x150 box:
289 // http://dev.twitpic.com/docs/thumbnails/
291 $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id;
292 $oembed->thumbnail_width = $thumbSize;
293 $oembed->thumbnail_height = $thumbSize;
299 * Fetch some URL and return JSON data.
302 * @param array $params query-string params
305 static protected function json($url, $params=array())
307 $data = self::http($url, $params);
308 return json_decode($data);
312 * Hit some web API and return data on success.
314 * @param array $params
317 static protected function http($url, $params=array())
319 $client = HTTPClient::start();
321 $query = http_build_query($params, null, '&');
322 if (strpos($url, '?') === false) {
323 $url .= '?' . $query;
325 $url .= '&' . $query;
328 $response = $client->get($url);
329 if ($response->isOk()) {
330 return $response->getBody();
332 throw new Exception('Bad HTTP response code: ' . $response->getStatus());
337 class oEmbedHelper_Exception extends Exception
339 public function __construct($message = "", $code = 0, $previous = null)
341 parent::__construct($message, $code);
345 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
347 function __construct($previous=null)
349 return parent::__construct('Bad HTML in discovery data.', 0, $previous);
353 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
355 function __construct($previous=null)
357 return parent::__construct('No oEmbed discovery data.', 0, $previous);