]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/oembedhelper.php
Merge branch '1.0.x' of git://gitorious.org/statusnet/mainline into 1.0.x
[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     );
47     protected static $functionMap = array(
48         'twitpic.com' => 'oEmbedHelper::twitPic',
49     );
50
51     /**
52      * Perform or fake an oEmbed lookup for the given resource.
53      *
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.
59      *
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
62      * equivalent data.
63      *
64      * Throws exceptions on failure.
65      *
66      * @param string $url
67      * @param array $params
68      * @return object
69      */
70     public static function getObject($url, $params=array())
71     {
72         $host = parse_url($url, PHP_URL_HOST);
73         if (substr($host, 0, 4) == 'www.') {
74             $host = substr($host, 4);
75         }
76
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);
83         }
84
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];
88         } else {
89             try {
90                 $api = self::discover($url);
91             } catch (Exception $e) {
92                 // Discovery failed... fall back to oohembed if enabled.
93                 $oohembed = common_config('oohembed', 'endpoint');
94                 if ($oohembed) {
95                     $api = $oohembed;
96                 } else {
97                     throw $e;
98                 }
99             }
100         }
101         return self::getObjectFrom($api, $url, $params);
102     }
103
104     /**
105      * Perform basic discovery.
106      * @return string
107      */
108     static function discover($url)
109     {
110         // @fixme ideally skip this for non-HTML stuff!
111         $body = self::http($url);
112         return self::discoverFromHTML($url, $body);
113     }
114
115     /**
116      * Partially ripped from OStatus' FeedDiscovery class.
117      *
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
121      */
122     static function discoverFromHTML($url, $body)
123     {
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);
130
131         if (!$ok) {
132             throw new oEmbedHelper_BadHtmlException();
133         }
134
135         // Ok... now on to the links!
136         $feeds = array(
137             'application/json+oembed' => false,
138         );
139
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);
151
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;
155                     }
156                 }
157             }
158         }
159
160         // Return the highest-priority feed found
161         foreach ($feeds as $type => $url) {
162             if ($url) {
163                 return $url;
164             }
165         }
166
167         throw new oEmbedHelper_DiscoveryException();
168     }
169
170     /**
171      * Actually do an oEmbed lookup to a particular API endpoint.
172      *
173      * @param string $api oEmbed API endpoint URL
174      * @param string $url target URL to look up info about
175      * @param array $params
176      * @return object
177      */
178     static function getObjectFrom($api, $url, $params=array())
179     {
180         $params['url'] = $url;
181         $params['format'] = 'json';
182         $data = self::json($api, $params);
183         return self::normalize($data);
184     }
185
186     /**
187      * Normalize oEmbed format.
188      *
189      * @param object $orig
190      * @return object
191      */
192     static function normalize($orig)
193     {
194         $data = clone($orig);
195
196         if (empty($data->type)) {
197             throw new Exception('Invalid oEmbed data: no type field.');
198         }
199
200         if ($data->type == 'image') {
201             // YFrog does this.
202             $data->type = 'photo';
203         }
204
205         if (isset($data->thumbnail_url)) {
206             if (!isset($data->thumbnail_width)) {
207                 // !?!?!
208                 $data->thumbnail_width = common_config('attachments', 'thumb_width');
209                 $data->thumbnail_height = common_config('attachments', 'thumb_height');
210             }
211         }
212
213         return $data;
214     }
215
216     /**
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
220      *
221      * This code fetches metadata from Twitpic's own API, and attempts
222      * to guess proper thumbnail size from the original's size.
223      *
224      * @todo respect maxwidth and maxheight params
225      *
226      * @param string $url
227      * @param array $params
228      * @return object
229      */
230     static function twitPic($url, $params=array())
231     {
232         $matches = array();
233         if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) {
234             $id = $matches[1];
235         } else {
236             throw new Exception("Invalid twitpic URL");
237         }
238
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',
242                 array('id' => $id));
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;
249         }
250
251         // Thumbnail is cropped and scaled to 150x150 box:
252         // http://dev.twitpic.com/docs/thumbnails/
253         $thumbSize = 150;
254         $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id;
255         $oembed->thumbnail_width = $thumbSize;
256         $oembed->thumbnail_height = $thumbSize;
257
258         return $oembed;
259     }
260
261     /**
262      * Fetch some URL and return JSON data.
263      *
264      * @param string $url
265      * @param array $params query-string params
266      * @return object
267      */
268     static protected function json($url, $params=array())
269     {
270         $data = self::http($url, $params);
271         return json_decode($data);
272     }
273
274     /**
275      * Hit some web API and return data on success.
276      * @param string $url
277      * @param array $params
278      * @return string
279      */
280     static protected function http($url, $params=array())
281     {
282         $client = HTTPClient::start();
283         if ($params) {
284             $query = http_build_query($params, null, '&');
285             if (strpos($url, '?') === false) {
286                 $url .= '?' . $query;
287             } else {
288                 $url .= '&' . $query;
289             }
290         }
291         $response = $client->get($url);
292         if ($response->isOk()) {
293             return $response->getBody();
294         } else {
295             throw new Exception('Bad HTTP response code: ' . $response->getStatus());
296         }
297     }
298 }
299
300 class oEmbedHelper_Exception extends Exception
301 {
302     public function __construct($message = "", $code = 0, $previous = null)
303     {
304         parent::__construct($message, $code);
305     }
306 }
307
308 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
309 {
310     function __construct($previous=null)
311     {
312         return parent::__construct('Bad HTML in discovery data.', 0, $previous);
313     }
314 }
315
316 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
317 {
318     function __construct($previous=null)
319     {
320         return parent::__construct('No oEmbed discovery data.', 0, $previous);
321     }
322 }