]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/lib/oembedhelper.php
Merge branch 'quitagram' into nightly
[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;
124             }
125         }
126
127         if (empty($api)) {
128             // TRANS: Server exception thrown in oEmbed action if no API endpoint is available.
129             throw new ServerException(_('No oEmbed API endpoint available.'));
130         }
131
132         return self::getObjectFrom($api, $url, $params);
133     }
134
135     /**
136      * Perform basic discovery.
137      * @return string
138      */
139     static function discover($url)
140     {
141         // @fixme ideally skip this for non-HTML stuff!
142         $body = self::http($url);
143         return self::discoverFromHTML($url, $body);
144     }
145
146     /**
147      * Partially ripped from OStatus' FeedDiscovery class.
148      *
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
152      */
153     static function discoverFromHTML($url, $body)
154     {
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);
161
162         if (!$ok) {
163             throw new oEmbedHelper_BadHtmlException();
164         }
165
166         // Ok... now on to the links!
167         $feeds = array(
168             'application/json+oembed' => false,
169         );
170
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);
182
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;
186                     }
187                 }
188             }
189         }
190
191         // Return the highest-priority feed found
192         foreach ($feeds as $type => $url) {
193             if ($url) {
194                 return $url;
195             }
196         }
197
198         throw new oEmbedHelper_DiscoveryException();
199     }
200
201     /**
202      * Actually do an oEmbed lookup to a particular API endpoint.
203      *
204      * @param string $api oEmbed API endpoint URL
205      * @param string $url target URL to look up info about
206      * @param array $params
207      * @return object
208      */
209     static function getObjectFrom($api, $url, $params=array())
210     {
211         $params['url'] = $url;
212         $params['format'] = 'json';
213         $key=common_config('oembed','apikey');
214         if(isset($key)) {
215             $params['key'] = common_config('oembed','apikey');
216         }
217         $data = self::json($api, $params);
218         return self::normalize($data);
219     }
220
221     /**
222      * Normalize oEmbed format.
223      *
224      * @param object $orig
225      * @return object
226      */
227     static function normalize($orig)
228     {
229         $data = clone($orig);
230
231         if (empty($data->type)) {
232             throw new Exception('Invalid oEmbed data: no type field.');
233         }
234
235         if ($data->type == 'image') {
236             // YFrog does this.
237             $data->type = 'photo';
238         }
239
240         if (isset($data->thumbnail_url)) {
241             if (!isset($data->thumbnail_width)) {
242                 // !?!?!
243                 $data->thumbnail_width = common_config('thumbnail', 'width');
244                 $data->thumbnail_height = common_config('thumbnail', 'height');
245             }
246         }
247
248         return $data;
249     }
250
251     /**
252      * Fetch some URL and return JSON data.
253      *
254      * @param string $url
255      * @param array $params query-string params
256      * @return object
257      */
258     static protected function json($url, $params=array())
259     {
260         $data = self::http($url, $params);
261         return json_decode($data);
262     }
263
264     /**
265      * Hit some web API and return data on success.
266      * @param string $url
267      * @param array $params
268      * @return string
269      */
270     static protected function http($url, $params=array())
271     {
272         $client = HTTPClient::start();
273         if ($params) {
274             $query = http_build_query($params, null, '&');
275             if (strpos($url, '?') === false) {
276                 $url .= '?' . $query;
277             } else {
278                 $url .= '&' . $query;
279             }
280         }
281         $response = $client->get($url);
282         if ($response->isOk()) {
283             return $response->getBody();
284         } else {
285             throw new Exception('Bad HTTP response code: ' . $response->getStatus());
286         }
287     }
288 }
289
290 class oEmbedHelper_Exception extends Exception
291 {
292     public function __construct($message = "", $code = 0, $previous = null)
293     {
294         parent::__construct($message, $code);
295     }
296 }
297
298 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
299 {
300     function __construct($previous=null)
301     {
302         return parent::__construct('Bad HTML in discovery data.', 0, $previous);
303     }
304 }
305
306 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
307 {
308     function __construct($previous=null)
309     {
310         return parent::__construct('No oEmbed discovery data.', 0, $previous);
311     }
312 }