]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/lib/oembedhelper.php
Debugging output in OStatus for easier reading+greping
[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('GNUSOCIAL')) { exit(1); }
21
22
23 /**
24  * Utility class to wrap basic oEmbed lookups.
25  *
26  * Blacklisted hosts will use an alternate lookup method:
27  *  - Twitpic
28  *
29  * Whitelisted hosts will use known oEmbed API endpoints:
30  *  - Flickr, YFrog
31  *
32  * Sites that provide discovery links will use them directly; a bug
33  * in use of discovery links with query strings is worked around.
34  *
35  * Others will fall back to oohembed (unless disabled).
36  * The API endpoint can be configured or disabled through config
37  * as 'oohembed'/'endpoint'.
38  */
39 class oEmbedHelper
40 {
41     protected static $apiMap = array(
42         'flickr.com' => 'https://www.flickr.com/services/oembed/',
43         'youtube.com' => 'https://www.youtube.com/oembed',
44         'viddler.com' => 'http://lab.viddler.com/services/oembed/',
45         'revision3.com' => 'https://revision3.com/api/oembed/',
46         'vimeo.com' => 'https://vimeo.com/api/oembed.json',
47     );
48
49     /**
50      * Perform or fake an oEmbed lookup for the given resource.
51      *
52      * Some known hosts are whitelisted with API endpoints where we
53      * know they exist but autodiscovery data isn't available.
54      * If autodiscovery links are missing and we don't recognize the
55      * host, we'll pass it to noembed.com's public service which
56      * will either proxy or fake info on a lot of sites.
57      *
58      * A few hosts are blacklisted due to known problems with oohembed,
59      * in which case we'll look up the info another way and return
60      * equivalent data.
61      *
62      * Throws exceptions on failure.
63      *
64      * @param string $url
65      * @param array $params
66      * @return object
67      */
68     public static function getObject($url, $params=array())
69     {
70         common_log(LOG_INFO, 'Checking for remote URL metadata for ' . $url);
71
72         // TODO: Make this class something like UrlMetadata, or use a dataobject?
73         $metadata = new stdClass();
74
75         if (Event::handle('GetRemoteUrlMetadata', array($url, &$metadata))) {
76             // If that event didn't return anything, try downloading the body and parse it
77
78             // don't use quickGet since we want to check Content-Type header for utf-8
79             $client = new HTTPClient();
80             $response = $client->get($url);
81             if (!$response->isOk()) {
82                 // TRANS: Exception. %s is the URL we tried to GET.
83                 throw new Exception(sprintf(_m('Could not GET URL %s.'), $url), $response->getStatus());
84             }
85             $body = $response->getBody();
86
87             // DOMDocument::loadHTML may throw warnings on unrecognized elements,
88             // and notices on unrecognized namespaces.
89             $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
90             
91             // DOMDocument assumes ISO-8859-1 per HTML spec
92             // use UTF-8 if we find any evidence of that encoding
93             $utf8_evidence = false;
94             $unicode_check_dom = new DOMDocument();
95             $ok = $unicode_check_dom->loadHTML($body);
96             if (!$ok) throw new oEmbedHelper_BadHtmlException();
97             $metaNodes = $unicode_check_dom->getElementsByTagName('meta');
98             foreach($metaNodes as $metaNode) {
99                 // case in-sensitive since Content-type and utf-8 can be written in many ways
100                 if(stristr($metaNode->getAttribute('http-equiv'),'content-type')
101                 && stristr($metaNode->getAttribute('content'),'utf-8')) {
102                     $utf8_evidence = true;        
103                     break;                  
104                 } elseif(stristr($metaNode->getAttribute('charset'),'utf-8')) {
105                     $utf8_evidence = true;        
106                     break;
107                 }
108             }
109             unset($unicode_check_dom);
110             
111             // The Content-Type HTTP response header overrides encoding metatags in DOM
112             if(stristr($response->getHeader('Content-Type'),'utf-8')) {
113                 $utf8_evidence = true;              
114             }
115            
116             // add utf-8 encoding prolog if we have reason to believe this is utf-8 content   
117             // DOMDocument('1.0', 'UTF-8') does not work!            
118             $utf8_tag = $utf8_evidence ? '<?xml encoding="utf-8" ?>' : '';          
119             
120             $dom = new DOMDocument();
121             $ok = $dom->loadHTML($utf8_tag.$body);
122             unset($body);   // storing the DOM in memory is enough...
123             error_reporting($old);
124
125             if (!$ok) {
126                 throw new oEmbedHelper_BadHtmlException();
127             }
128             
129             Event::handle('GetRemoteUrlMetadataFromDom', array($url, $dom, &$metadata));
130         }
131
132         return self::normalize($metadata);
133     }
134
135     /**
136      * Partially ripped from OStatus' FeedDiscovery class.
137      *
138      * @param string $url source URL, used to resolve relative links
139      * @param string $body HTML body text
140      * @return mixed string with URL or false if no target found
141      */
142     static function oEmbedEndpointFromHTML(DOMDocument $dom)
143     {
144         // Ok... now on to the links!
145         $feeds = array(
146             'application/json+oembed' => false,
147         );
148
149         $nodes = $dom->getElementsByTagName('link');
150         for ($i = 0; $i < $nodes->length; $i++) {
151             $node = $nodes->item($i);
152             if ($node->hasAttributes()) {
153                 $rel = $node->attributes->getNamedItem('rel');
154                 $type = $node->attributes->getNamedItem('type');
155                 $href = $node->attributes->getNamedItem('href');
156                 if ($rel && $type && $href) {
157                     $rel = array_filter(explode(" ", $rel->value));
158                     $type = trim($type->value);
159                     $href = trim($href->value);
160
161                     if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
162                         // Save the first feed found of each type...
163                         $feeds[$type] = $href;
164                     }
165                 }
166             }
167         }
168
169         // Return the highest-priority feed found
170         foreach ($feeds as $type => $url) {
171             if ($url) {
172                 return $url;
173             }
174         }
175
176         throw new oEmbedHelper_DiscoveryException();
177     }
178
179     /**
180      * Actually do an oEmbed lookup to a particular API endpoint.
181      *
182      * @param string $api oEmbed API endpoint URL
183      * @param string $url target URL to look up info about
184      * @param array $params
185      * @return object
186      */
187     static function getOembedFrom($api, $url, $params=array())
188     {
189         if (empty($api)) {
190             // TRANS: Server exception thrown in oEmbed action if no API endpoint is available.
191             throw new ServerException(_('No oEmbed API endpoint available.'));
192         }
193         $params['url'] = $url;
194         $params['format'] = 'json';
195         $key=common_config('oembed','apikey');
196         if(isset($key)) {
197             $params['key'] = common_config('oembed','apikey');
198         }
199         
200         $oembed_data = HTTPClient::quickGetJson($api, $params);
201         if (isset($oembed_data->html)) {
202             $oembed_data->html = common_purify($oembed_data->html);
203         }
204         
205         return $oembed_data;
206     }
207
208     /**
209      * Normalize oEmbed format.
210      *
211      * @param object $orig
212      * @return object
213      */
214     static function normalize(stdClass $data)
215     {
216         if (empty($data->type)) {
217             throw new Exception('Invalid oEmbed data: no type field.');
218         }
219         if ($data->type == 'image') {
220             // YFrog does this.
221             $data->type = 'photo';
222         }
223
224         if (isset($data->thumbnail_url)) {
225             if (!isset($data->thumbnail_width)) {
226                 // !?!?!
227                 $data->thumbnail_width = common_config('thumbnail', 'width');
228                 $data->thumbnail_height = common_config('thumbnail', 'height');
229             }
230         }
231
232         return $data;
233     }
234 }
235
236 class oEmbedHelper_Exception extends Exception
237 {
238     public function __construct($message = "", $code = 0, $previous = null)
239     {
240         parent::__construct($message, $code);
241     }
242 }
243
244 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
245 {
246     function __construct($previous=null)
247     {
248         return parent::__construct('Bad HTML in discovery data.', 0, $previous);
249     }
250 }
251
252 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
253 {
254     function __construct($previous=null)
255     {
256         return parent::__construct('No oEmbed discovery data.', 0, $previous);
257     }
258 }