]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/lib/oembedhelper.php
Merge commit 'refs/merge-requests/30' of https://gitorious.org/social/mainline into...
[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     );
52
53     /**
54      * Perform or fake an oEmbed lookup for the given resource.
55      *
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.
61      *
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
64      * equivalent data.
65      *
66      * Throws exceptions on failure.
67      *
68      * @param string $url
69      * @param array $params
70      * @return object
71      */
72     public static function getObject($url, $params=array())
73     {
74         $host = parse_url($url, PHP_URL_HOST);
75         if (substr($host, 0, 4) == 'www.') {
76             $host = substr($host, 4);
77         }
78
79         common_log(LOG_INFO, 'Checking for oEmbed data for ' . $url);
80
81         // You can fiddle with the order of discovery -- either skipping
82         // some types or re-ordering them.
83
84         $order = common_config('oembed', 'order');
85
86         foreach ($order as $method) {
87
88             switch ($method) {
89             case 'built-in':
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);
98                 }
99                 break;
100             case 'well-known':
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 . '"');
106                     break 2;
107                 }
108                 break;
109             case 'discovery':
110                 try {
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);
114                     break 2;
115                 } catch (Exception $e) {
116                     common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers.');
117                     // Just ignore it!
118                 }
119                 break;
120             case 'service':
121                 $api = common_config('oembed', 'endpoint');
122                 common_log(LOG_INFO, 'Using service API endpoint ' . $api);
123                 break 2;
124                 break;
125             }
126         }
127
128         if (empty($api)) {
129             // TRANS: Server exception thrown in oEmbed action if no API endpoint is available.
130             throw new ServerException(_('No oEmbed API endpoint available.'));
131         }
132
133         return self::getObjectFrom($api, $url, $params);
134     }
135
136     /**
137      * Perform basic discovery.
138      * @return string
139      */
140     static function discover($url)
141     {
142         // @fixme ideally skip this for non-HTML stuff!
143         $body = self::http($url);
144         return self::discoverFromHTML($url, $body);
145     }
146
147     /**
148      * Partially ripped from OStatus' FeedDiscovery class.
149      *
150      * @param string $url source URL, used to resolve relative links
151      * @param string $body HTML body text
152      * @return mixed string with URL or false if no target found
153      */
154     static function discoverFromHTML($url, $body)
155     {
156         // DOMDocument::loadHTML may throw warnings on unrecognized elements,
157         // and notices on unrecognized namespaces.
158         $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
159         $dom = new DOMDocument();
160         $ok = $dom->loadHTML($body);
161         error_reporting($old);
162
163         if (!$ok) {
164             throw new oEmbedHelper_BadHtmlException();
165         }
166
167         // Ok... now on to the links!
168         $feeds = array(
169             'application/json+oembed' => false,
170         );
171
172         $nodes = $dom->getElementsByTagName('link');
173         for ($i = 0; $i < $nodes->length; $i++) {
174             $node = $nodes->item($i);
175             if ($node->hasAttributes()) {
176                 $rel = $node->attributes->getNamedItem('rel');
177                 $type = $node->attributes->getNamedItem('type');
178                 $href = $node->attributes->getNamedItem('href');
179                 if ($rel && $type && $href) {
180                     $rel = array_filter(explode(" ", $rel->value));
181                     $type = trim($type->value);
182                     $href = trim($href->value);
183
184                     if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
185                         // Save the first feed found of each type...
186                         $feeds[$type] = $href;
187                     }
188                 }
189             }
190         }
191
192         // Return the highest-priority feed found
193         foreach ($feeds as $type => $url) {
194             if ($url) {
195                 return $url;
196             }
197         }
198
199         throw new oEmbedHelper_DiscoveryException();
200     }
201
202     /**
203      * Actually do an oEmbed lookup to a particular API endpoint.
204      *
205      * @param string $api oEmbed API endpoint URL
206      * @param string $url target URL to look up info about
207      * @param array $params
208      * @return object
209      */
210     static function getObjectFrom($api, $url, $params=array())
211     {
212         $params['url'] = $url;
213         $params['format'] = 'json';
214         $key=common_config('oembed','apikey');
215         if(isset($key)) {
216             $params['key'] = common_config('oembed','apikey');
217         }
218         $data = self::json($api, $params);
219         return self::normalize($data);
220     }
221
222     /**
223      * Normalize oEmbed format.
224      *
225      * @param object $orig
226      * @return object
227      */
228     static function normalize($orig)
229     {
230         $data = clone($orig);
231
232         if (empty($data->type)) {
233             throw new Exception('Invalid oEmbed data: no type field.');
234         }
235
236         if ($data->type == 'image') {
237             // YFrog does this.
238             $data->type = 'photo';
239         }
240
241         if (isset($data->thumbnail_url)) {
242             if (!isset($data->thumbnail_width)) {
243                 // !?!?!
244                 $data->thumbnail_width = common_config('thumbnail', 'width');
245                 $data->thumbnail_height = common_config('thumbnail', 'height');
246             }
247         }
248
249         return $data;
250     }
251
252     /**
253      * Fetch some URL and return JSON data.
254      *
255      * @param string $url
256      * @param array $params query-string params
257      * @return object
258      */
259     static protected function json($url, $params=array())
260     {
261         $data = self::http($url, $params);
262         return json_decode($data);
263     }
264
265     /**
266      * Hit some web API and return data on success.
267      * @param string $url
268      * @param array $params
269      * @return string
270      */
271     static protected function http($url, $params=array())
272     {
273         $client = HTTPClient::start();
274         if ($params) {
275             $query = http_build_query($params, null, '&');
276             if (strpos($url, '?') === false) {
277                 $url .= '?' . $query;
278             } else {
279                 $url .= '&' . $query;
280             }
281         }
282         $response = $client->get($url);
283         if ($response->isOk()) {
284             return $response->getBody();
285         } else {
286             throw new Exception('Bad HTTP response code: ' . $response->getStatus());
287         }
288     }
289 }
290
291 class oEmbedHelper_Exception extends Exception
292 {
293     public function __construct($message = "", $code = 0, $previous = null)
294     {
295         parent::__construct($message, $code);
296     }
297 }
298
299 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
300 {
301     function __construct($previous=null)
302     {
303         return parent::__construct('Bad HTML in discovery data.', 0, $previous);
304     }
305 }
306
307 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
308 {
309     function __construct($previous=null)
310     {
311         return parent::__construct('No oEmbed discovery data.', 0, $previous);
312     }
313 }