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',
47 protected static $functionMap = array(
48 'twitpic.com' => 'oEmbedHelper::twitPic',
52 * Perform or fake an oEmbed lookup for the given resource.
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.
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
64 * Throws exceptions on failure.
67 * @param array $params
70 public static function getObject($url, $params=array())
72 $host = parse_url($url, PHP_URL_HOST);
73 if (substr($host, 0, 4) == 'www.') {
74 $host = substr($host, 4);
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);
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];
90 $api = self::discover($url);
91 } catch (Exception $e) {
92 // Discovery failed... fall back to oohembed if enabled.
93 $oohembed = common_config('oohembed', 'endpoint');
101 return self::getObjectFrom($api, $url, $params);
105 * Perform basic discovery.
108 static function discover($url)
110 // @fixme ideally skip this for non-HTML stuff!
111 $body = self::http($url);
112 return self::discoverFromHTML($url, $body);
116 * Partially ripped from OStatus' FeedDiscovery class.
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
122 static function discoverFromHTML($url, $body)
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);
132 throw new oEmbedHelper_BadHtmlException();
135 // Ok... now on to the links!
137 'application/json+oembed' => false,
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);
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;
160 // Return the highest-priority feed found
161 foreach ($feeds as $type => $url) {
167 throw new oEmbedHelper_DiscoveryException();
171 * Actually do an oEmbed lookup to a particular API endpoint.
173 * @param string $api oEmbed API endpoint URL
174 * @param string $url target URL to look up info about
175 * @param array $params
178 static function getObjectFrom($api, $url, $params=array())
180 $params['url'] = $url;
181 $params['format'] = 'json';
182 $data = self::json($api, $params);
183 return self::normalize($data);
187 * Normalize oEmbed format.
189 * @param object $orig
192 static function normalize($orig)
194 $data = clone($orig);
196 if (empty($data->type)) {
197 throw new Exception('Invalid oEmbed data: no type field.');
200 if ($data->type == 'image') {
202 $data->type = 'photo';
205 if (isset($data->thumbnail_url)) {
206 if (!isset($data->thumbnail_width)) {
208 $data->thumbnail_width = common_config('attachments', 'thumb_width');
209 $data->thumbnail_height = common_config('attachments', 'thumb_height');
217 * Using a local function for twitpic lookups, as oohembed's adapter
218 * doesn't return a valid result:
219 * http://code.google.com/p/oohembed/issues/detail?id=19
221 * This code fetches metadata from Twitpic's own API, and attempts
222 * to guess proper thumbnail size from the original's size.
224 * @todo respect maxwidth and maxheight params
227 * @param array $params
230 static function twitPic($url, $params=array())
233 if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) {
236 throw new Exception("Invalid twitpic URL");
239 // Grab metadata from twitpic's API...
240 // http://dev.twitpic.com/docs/2/media_show
241 $data = self::json('http://api.twitpic.com/2/media/show.json',
243 $oembed = (object)array('type' => 'photo',
244 'url' => 'http://twitpic.com/show/full/' . $data->short_id,
245 'width' => $data->width,
246 'height' => $data->height);
247 if (!empty($data->message)) {
248 $oembed->title = $data->message;
251 // Thumbnail is cropped and scaled to 150x150 box:
252 // http://dev.twitpic.com/docs/thumbnails/
254 $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id;
255 $oembed->thumbnail_width = $thumbSize;
256 $oembed->thumbnail_height = $thumbSize;
262 * Fetch some URL and return JSON data.
265 * @param array $params query-string params
268 static protected function json($url, $params=array())
270 $data = self::http($url, $params);
271 return json_decode($data);
275 * Hit some web API and return data on success.
277 * @param array $params
280 static protected function http($url, $params=array())
282 $client = HTTPClient::start();
284 $query = http_build_query($params, null, '&');
285 if (strpos($url, '?') === false) {
286 $url .= '?' . $query;
288 $url .= '&' . $query;
291 $response = $client->get($url);
292 if ($response->isOk()) {
293 return $response->getBody();
295 throw new Exception('Bad HTTP response code: ' . $response->getStatus());
300 class oEmbedHelper_Exception extends Exception
304 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
306 function __construct($previous=null)
308 return parent::__construct('Bad HTML in discovery data.', 0, $previous);
312 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
314 function __construct($previous=null)
316 return parent::__construct('No oEmbed discovery data.', 0, $previous);