]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/lib/oembedhelper.php
Oembed slimmed to only do discovery (soon we get og: discovery too)
[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             $body = HTTPClient::quickGet($url);
78
79             // DOMDocument::loadHTML may throw warnings on unrecognized elements,
80             // and notices on unrecognized namespaces.
81             $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
82             $dom = new DOMDocument();
83             $ok = $dom->loadHTML($body);
84             unset($body);   // storing the DOM in memory is enough...
85             error_reporting($old);
86
87             if (!$ok) {
88                 throw new oEmbedHelper_BadHtmlException();
89             }
90
91             Event::handle('GetRemoteUrlMetadataFromDom', array($url, $dom, &$metadata));
92         }
93
94         return self::normalize($metadata);
95     }
96
97     /**
98      * Partially ripped from OStatus' FeedDiscovery class.
99      *
100      * @param string $url source URL, used to resolve relative links
101      * @param string $body HTML body text
102      * @return mixed string with URL or false if no target found
103      */
104     static function oEmbedEndpointFromHTML(DOMDocument $dom)
105     {
106         // Ok... now on to the links!
107         $feeds = array(
108             'application/json+oembed' => false,
109         );
110
111         $nodes = $dom->getElementsByTagName('link');
112         for ($i = 0; $i < $nodes->length; $i++) {
113             $node = $nodes->item($i);
114             if ($node->hasAttributes()) {
115                 $rel = $node->attributes->getNamedItem('rel');
116                 $type = $node->attributes->getNamedItem('type');
117                 $href = $node->attributes->getNamedItem('href');
118                 if ($rel && $type && $href) {
119                     $rel = array_filter(explode(" ", $rel->value));
120                     $type = trim($type->value);
121                     $href = trim($href->value);
122
123                     if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
124                         // Save the first feed found of each type...
125                         $feeds[$type] = $href;
126                     }
127                 }
128             }
129         }
130
131         // Return the highest-priority feed found
132         foreach ($feeds as $type => $url) {
133             if ($url) {
134                 return $url;
135             }
136         }
137
138         throw new oEmbedHelper_DiscoveryException();
139     }
140
141     /**
142      * Actually do an oEmbed lookup to a particular API endpoint.
143      *
144      * @param string $api oEmbed API endpoint URL
145      * @param string $url target URL to look up info about
146      * @param array $params
147      * @return object
148      */
149     static function getOembedFrom($api, $url, $params=array())
150     {
151         if (empty($api)) {
152             // TRANS: Server exception thrown in oEmbed action if no API endpoint is available.
153             throw new ServerException(_('No oEmbed API endpoint available.'));
154         }
155         $params['url'] = $url;
156         $params['format'] = 'json';
157         $key=common_config('oembed','apikey');
158         if(isset($key)) {
159             $params['key'] = common_config('oembed','apikey');
160         }
161         return HTTPClient::quickGetJson($api, $params);
162     }
163
164     /**
165      * Normalize oEmbed format.
166      *
167      * @param object $orig
168      * @return object
169      */
170     static function normalize(stdClass $data)
171     {
172         if (empty($data->type)) {
173             throw new Exception('Invalid oEmbed data: no type field.');
174         }
175         if ($data->type == 'image') {
176             // YFrog does this.
177             $data->type = 'photo';
178         }
179
180         if (isset($data->thumbnail_url)) {
181             if (!isset($data->thumbnail_width)) {
182                 // !?!?!
183                 $data->thumbnail_width = common_config('thumbnail', 'width');
184                 $data->thumbnail_height = common_config('thumbnail', 'height');
185             }
186         }
187
188         return $data;
189     }
190 }
191
192 class oEmbedHelper_Exception extends Exception
193 {
194     public function __construct($message = "", $code = 0, $previous = null)
195     {
196         parent::__construct($message, $code);
197     }
198 }
199
200 class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
201 {
202     function __construct($previous=null)
203     {
204         return parent::__construct('Bad HTML in discovery data.', 0, $previous);
205     }
206 }
207
208 class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
209 {
210     function __construct($previous=null)
211     {
212         return parent::__construct('No oEmbed discovery data.', 0, $previous);
213     }
214 }