]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/lib/oembedhelper.php
spring cleaning in Oembed helper list
[quix0rs-gnu-social.git] / plugins / Oembed / 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' => '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',
49     );
50     protected static $functionMap = array(
51         'twitpic.com' => 'oEmbedHelper::twitPic',
52     );
53
54     /**
55      * Perform or fake an oEmbed lookup for the given resource.
56      *
57      * Some known hosts are whitelisted with API endpoints where we
58      * know they exist but autodiscovery data isn't available.
59      * If autodiscovery links are missing and we don't recognize the
60      * host, we'll pass it to noembed.com's public service which
61      * will either proxy or fake info on a lot of sites.
62      *
63      * A few hosts are blacklisted due to known problems with oohembed,
64      * in which case we'll look up the info another way and return
65      * equivalent data.
66      *
67      * Throws exceptions on failure.
68      *
69      * @param string $url
70      * @param array $params
71      * @return object
72      */
73     public static function getObject($url, $params=array())
74     {
75         $host = parse_url($url, PHP_URL_HOST);
76         if (substr($host, 0, 4) == 'www.') {
77             $host = substr($host, 4);
78         }
79
80         common_log(LOG_INFO, 'Checking for oEmbed data for ' . $url);
81
82         // You can fiddle with the order of discovery -- either skipping
83         // some types or re-ordering them.
84
85         $order = common_config('oembed', 'order');
86
87         foreach ($order as $method) {
88
89             switch ($method) {
90             case 'built-in':
91                 common_log(LOG_INFO, 'Considering built-in oEmbed methods...');
92                 // Blacklist: systems with no oEmbed API of their own, which are
93                 // either missing from or broken on noembed.com's proxy.
94                 // we know how to look data up in another way...
95                 if (array_key_exists($host, self::$functionMap)) {
96                     common_log(LOG_INFO, 'We have a built-in method for ' . $host);
97                     $func = self::$functionMap[$host];
98                     return call_user_func($func, $url, $params);
99                 }
100                 break;
101             case 'well-known':
102                 common_log(LOG_INFO, 'Considering well-known oEmbed endpoints...');
103                 // Whitelist: known API endpoints for sites that don't provide discovery...
104                 if (array_key_exists($host, self::$apiMap)) {
105                     $api = self::$apiMap[$host];
106                     common_log(LOG_INFO, 'Using well-known endpoint "' . $api . '" for "' . $host . '"');
107                     break 2;
108                 }
109                 break;
110             case 'discovery':
111                 try {
112                     common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.');
113                     $api = self::discover($url);
114                     common_log(LOG_INFO, 'Found API endpoint ' . $api . ' for URL ' . $url);
115                     break 2;
116                 } catch (Exception $e) {
117                     common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers.');
118                     // Just ignore it!
119                 }
120                 break;
121             case 'service':
122                 $api = common_config('oembed', 'endpoint');
123                 common_log(LOG_INFO, 'Using service API endpoint ' . $api);
124                 break 2;
125                 break;
126             }
127         }
128
129         if (empty($api)) {
130             // TRANS: Server exception thrown in oEmbed action if no API endpoint is available.
131             throw new ServerException(_('No oEmbed API endpoint available.'));
132         }
133
134         return self::getObjectFrom($api, $url, $params);
135     }
136
137     /**
138      * Perform basic discovery.
139      * @return string
140      */
141     static function discover($url)
142     {
143         // @fixme ideally skip this for non-HTML stuff!
144         $body = self::http($url);
145         return self::discoverFromHTML($url, $body);
146     }
147
148     /**
149      * Partially ripped from OStatus' FeedDiscovery class.
150      *
151      * @param string $url source URL, used to resolve relative links
152      * @param string $body HTML body text
153      * @return mixed string with URL or false if no target found
154      */
155     static function discoverFromHTML($url, $body)
156     {
157         // DOMDocument::loadHTML may throw warnings on unrecognized elements,
158         // and notices on unrecognized namespaces.
159         $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
160         $dom = new DOMDocument();
161         $ok = $dom->loadHTML($body);
162         error_reporting($old);
163
164         if (!$ok) {
165             throw new oEmbedHelper_BadHtmlException();
166         }
167
168         // Ok... now on to the links!
169         $feeds = array(
170             'application/json+oembed' => false,
171         );
172
173         $nodes = $dom->getElementsByTagName('link');
174         for ($i = 0; $i < $nodes->length; $i++) {
175             $node = $nodes->item($i);
176             if ($node->hasAttributes()) {
177                 $rel = $node->attributes->getNamedItem('rel');
178                 $type = $node->attributes->getNamedItem('type');
179                 $href = $node->attributes->getNamedItem('href');
180                 if ($rel && $type && $href) {
181                     $rel = array_filter(explode(" ", $rel->value));
182                     $type = trim($type->value);
183                     $href = trim($href->value);
184
185                     if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
186                         // Save the first feed found of each type...
187                         $feeds[$type] = $href;
188                     }
189                 }
190             }
191         }
192
193         // Return the highest-priority feed found
194         foreach ($feeds as $type => $url) {
195             if ($url) {
196                 return $url;
197             }
198         }
199
200         throw new oEmbedHelper_DiscoveryException();
201     }
202
203     /**
204      * Actually do an oEmbed lookup to a particular API endpoint.
205      *
206      * @param string $api oEmbed API endpoint URL
207      * @param string $url target URL to look up info about
208      * @param array $params
209      * @return object
210      */
211     static function getObjectFrom($api, $url, $params=array())
212     {
213         $params['url'] = $url;
214         $params['format'] = 'json';
215         $key=common_config('oembed','apikey');
216         if(isset($key)) {
217             $params['key'] = common_config('oembed','apikey');
218         }
219         $data = self::json($api, $params);
220         return self::normalize($data);
221     }
222
223     /**
224      * Normalize oEmbed format.
225      *
226      * @param object $orig
227      * @return object
228      */
229     static function normalize($orig)
230     {
231         $data = clone($orig);
232
233         if (empty($data->type)) {
234             throw new Exception('Invalid oEmbed data: no type field.');
235         }
236
237         if ($data->type == 'image') {
238             // YFrog does this.
239             $data->type = 'photo';
240         }
241
242         if (isset($data->thumbnail_url)) {
243             if (!isset($data->thumbnail_width)) {
244                 // !?!?!
245                 $data->thumbnail_width = common_config('thumbnail', 'width');
246                 $data->thumbnail_height = common_config('thumbnail', 'height');
247             }
248         }
249
250         return $data;
251     }
252
253     /**
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
257      *
258      * This code fetches metadata from Twitpic's own API, and attempts
259      * to guess proper thumbnail size from the original's size.
260      *
261      * @todo respect maxwidth and maxheight params
262      *
263      * @param string $url
264      * @param array $params
265      * @return object
266      */
267     static function twitPic($url, $params=array())
268     {
269         $matches = array();
270         if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) {
271             $id = $matches[1];
272         } else {
273             throw new Exception("Invalid twitpic URL");
274         }
275
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',
279                 array('id' => $id));
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;
286         }
287
288         // Thumbnail is cropped and scaled to 150x150 box:
289         // http://dev.twitpic.com/docs/thumbnails/
290         $thumbSize = 150;
291         $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id;
292         $oembed->thumbnail_width = $thumbSize;
293         $oembed->thumbnail_height = $thumbSize;
294
295         return $oembed;
296     }
297
298     /**
299      * Fetch some URL and return JSON data.
300      *
301      * @param string $url
302      * @param array $params query-string params
303      * @return object
304      */
305     static protected function json($url, $params=array())
306     {
307         $data = self::http($url, $params);
308         return json_decode($data);
309     }
310
311     /**
312      * Hit some web API and return data on success.
313      * @param string $url
314      * @param array $params
315      * @return string
316      */
317     static protected function http($url, $params=array())
318     {
319         $client = HTTPClient::start();
320         if ($params) {
321             $query = http_build_query($params, null, '&');
322             if (strpos($url, '?') === false) {
323                 $url .= '?' . $query;
324             } else {
325                 $url .= '&' . $query;
326             }
327         }
328         $response = $client->get($url);
329         if ($response->isOk()) {
330             return $response->getBody();
331         } else {
332             throw new Exception('Bad HTTP response code: ' . $response->getStatus());
333         }
334     }
335 }
336
337 class oEmbedHelper_Exception extends Exception
338 {
339     public function __construct($message = "", $code = 0, $previous = null)
340     {
341         parent::__construct($message, $code);
342     }
343 }
344
345 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
346 {
347     function __construct($previous=null)
348     {
349         return parent::__construct('Bad HTML in discovery data.', 0, $previous);
350     }
351 }
352
353 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
354 {
355     function __construct($previous=null)
356     {
357         return parent::__construct('No oEmbed discovery data.', 0, $previous);
358     }
359 }