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' => 'https://www.flickr.com/services/oembed/',
45 'youtube.com' => 'https://www.youtube.com/oembed',
46 'viddler.com' => 'http://lab.viddler.com/services/oembed/',
47 'revision3.com' => 'https://revision3.com/api/oembed/',
48 'vimeo.com' => 'https://vimeo.com/api/oembed.json',
50 protected static $functionMap = array(
54 * Perform or fake an oEmbed lookup for the given resource.
56 * Some known hosts are whitelisted with API endpoints where we
57 * know they exist but autodiscovery data isn't available.
58 * If autodiscovery links are missing and we don't recognize the
59 * host, we'll pass it to noembed.com's public service which
60 * will either proxy or fake info on a lot of sites.
62 * A few hosts are blacklisted due to known problems with oohembed,
63 * in which case we'll look up the info another way and return
66 * Throws exceptions on failure.
69 * @param array $params
72 public static function getObject($url, $params=array())
74 $host = parse_url($url, PHP_URL_HOST);
75 if (substr($host, 0, 4) == 'www.') {
76 $host = substr($host, 4);
79 common_log(LOG_INFO, 'Checking for oEmbed data for ' . $url);
81 // You can fiddle with the order of discovery -- either skipping
82 // some types or re-ordering them.
84 $order = common_config('oembed', 'order');
86 foreach ($order as $method) {
90 common_log(LOG_INFO, 'Considering built-in oEmbed methods...');
91 // Blacklist: systems with no oEmbed API of their own, which are
92 // either missing from or broken on noembed.com's proxy.
93 // we know how to look data up in another way...
94 if (array_key_exists($host, self::$functionMap)) {
95 common_log(LOG_INFO, 'We have a built-in method for ' . $host);
96 $func = self::$functionMap[$host];
97 return call_user_func($func, $url, $params);
101 common_log(LOG_INFO, 'Considering well-known oEmbed endpoints...');
102 // Whitelist: known API endpoints for sites that don't provide discovery...
103 if (array_key_exists($host, self::$apiMap)) {
104 $api = self::$apiMap[$host];
105 common_log(LOG_INFO, 'Using well-known endpoint "' . $api . '" for "' . $host . '"');
111 common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.');
112 $api = self::discover($url);
113 common_log(LOG_INFO, 'Found API endpoint ' . $api . ' for URL ' . $url);
115 } catch (Exception $e) {
116 common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers.');
121 $api = common_config('oembed', 'endpoint');
122 common_log(LOG_INFO, 'Using service API endpoint ' . $api);
128 // TRANS: Server exception thrown in oEmbed action if no API endpoint is available.
129 throw new ServerException(_('No oEmbed API endpoint available.'));
132 return self::getObjectFrom($api, $url, $params);
136 * Perform basic discovery.
139 static function discover($url)
141 // @fixme ideally skip this for non-HTML stuff!
142 $body = self::http($url);
143 return self::discoverFromHTML($url, $body);
147 * Partially ripped from OStatus' FeedDiscovery class.
149 * @param string $url source URL, used to resolve relative links
150 * @param string $body HTML body text
151 * @return mixed string with URL or false if no target found
153 static function discoverFromHTML($url, $body)
155 // DOMDocument::loadHTML may throw warnings on unrecognized elements,
156 // and notices on unrecognized namespaces.
157 $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
158 $dom = new DOMDocument();
159 $ok = $dom->loadHTML($body);
160 error_reporting($old);
163 throw new oEmbedHelper_BadHtmlException();
166 // Ok... now on to the links!
168 'application/json+oembed' => false,
171 $nodes = $dom->getElementsByTagName('link');
172 for ($i = 0; $i < $nodes->length; $i++) {
173 $node = $nodes->item($i);
174 if ($node->hasAttributes()) {
175 $rel = $node->attributes->getNamedItem('rel');
176 $type = $node->attributes->getNamedItem('type');
177 $href = $node->attributes->getNamedItem('href');
178 if ($rel && $type && $href) {
179 $rel = array_filter(explode(" ", $rel->value));
180 $type = trim($type->value);
181 $href = trim($href->value);
183 if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
184 // Save the first feed found of each type...
185 $feeds[$type] = $href;
191 // Return the highest-priority feed found
192 foreach ($feeds as $type => $url) {
198 throw new oEmbedHelper_DiscoveryException();
202 * Actually do an oEmbed lookup to a particular API endpoint.
204 * @param string $api oEmbed API endpoint URL
205 * @param string $url target URL to look up info about
206 * @param array $params
209 static function getObjectFrom($api, $url, $params=array())
211 $params['url'] = $url;
212 $params['format'] = 'json';
213 $key=common_config('oembed','apikey');
215 $params['key'] = common_config('oembed','apikey');
217 $data = self::json($api, $params);
218 return self::normalize($data);
222 * Normalize oEmbed format.
224 * @param object $orig
227 static function normalize($orig)
229 $data = clone($orig);
231 if (empty($data->type)) {
232 throw new Exception('Invalid oEmbed data: no type field.');
235 if ($data->type == 'image') {
237 $data->type = 'photo';
240 if (isset($data->thumbnail_url)) {
241 if (!isset($data->thumbnail_width)) {
243 $data->thumbnail_width = common_config('thumbnail', 'width');
244 $data->thumbnail_height = common_config('thumbnail', 'height');
252 * Fetch some URL and return JSON data.
255 * @param array $params query-string params
258 static protected function json($url, $params=array())
260 $data = self::http($url, $params);
261 return json_decode($data);
265 * Hit some web API and return data on success.
267 * @param array $params
270 static protected function http($url, $params=array())
272 $client = HTTPClient::start();
274 $query = http_build_query($params, null, '&');
275 if (strpos($url, '?') === false) {
276 $url .= '?' . $query;
278 $url .= '&' . $query;
281 $response = $client->get($url);
282 if ($response->isOk()) {
283 return $response->getBody();
285 throw new Exception('Bad HTTP response code: ' . $response->getStatus());
290 class oEmbedHelper_Exception extends Exception
292 public function __construct($message = "", $code = 0, $previous = null)
294 parent::__construct($message, $code);
298 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
300 function __construct($previous=null)
302 return parent::__construct('Bad HTML in discovery data.', 0, $previous);
306 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
308 function __construct($previous=null)
310 return parent::__construct('No oEmbed discovery data.', 0, $previous);