oembedhelper.php 11.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2008-2010, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.     If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('STATUSNET')) {
    exit(1);
}


/**
26
 * Utility class to wrap basic oEmbed lookups.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 *
 * Blacklisted hosts will use an alternate lookup method:
 *  - Twitpic
 *
 * Whitelisted hosts will use known oEmbed API endpoints:
 *  - Flickr, YFrog
 *
 * Sites that provide discovery links will use them directly; a bug
 * in use of discovery links with query strings is worked around.
 *
 * Others will fall back to oohembed (unless disabled).
 * The API endpoint can be configured or disabled through config
 * as 'oohembed'/'endpoint'.
 */
class oEmbedHelper
{
    protected static $apiMap = array(
        'flickr.com' => 'http://www.flickr.com/services/oembed/',
        'yfrog.com' => 'http://www.yfrog.com/api/oembed',
46 47 48 49 50 51 52
        'youtube.com' => 'http://www.youtube.com/oembed',
        'viddler.com' => 'http://lab.viddler.com/services/oembed/',
        'qik.com' => 'http://qik.com/api/oembed.json',
        'revision3.com' => 'http://revision3.com/api/oembed/',
        'hulu.com' => 'http://www.hulu.com/api/oembed.json',
        'vimeo.com' => 'http://www.vimeo.com/api/oembed.json',
        'my.opera.com' => 'http://my.opera.com/service/oembed',
53 54 55 56 57 58 59 60 61 62 63
    );
    protected static $functionMap = array(
        'twitpic.com' => 'oEmbedHelper::twitPic',
    );

    /**
     * Perform or fake an oEmbed lookup for the given resource.
     *
     * Some known hosts are whitelisted with API endpoints where we
     * know they exist but autodiscovery data isn't available.
     * If autodiscovery links are missing and we don't recognize the
64
     * host, we'll pass it to noembed.com's public service which
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
     * will either proxy or fake info on a lot of sites.
     *
     * A few hosts are blacklisted due to known problems with oohembed,
     * in which case we'll look up the info another way and return
     * equivalent data.
     *
     * Throws exceptions on failure.
     *
     * @param string $url
     * @param array $params
     * @return object
     */
    public static function getObject($url, $params=array())
    {
        $host = parse_url($url, PHP_URL_HOST);
        if (substr($host, 0, 4) == 'www.') {
            $host = substr($host, 4);
        }

84 85 86 87 88 89
        common_log(LOG_INFO, 'Checking for oEmbed data for ' . $url);

        // You can fiddle with the order of discovery -- either skipping
        // some types or re-ordering them.

        $order = common_config('oembed', 'order');
90

91 92 93 94 95 96
        foreach ($order as $method) {

            switch ($method) {
            case 'built-in':
                common_log(LOG_INFO, 'Considering built-in oEmbed methods...');
                // Blacklist: systems with no oEmbed API of their own, which are
97
                // either missing from or broken on noembed.com's proxy.
98 99 100 101 102 103 104 105 106 107 108 109 110 111
                // we know how to look data up in another way...
                if (array_key_exists($host, self::$functionMap)) {
                    common_log(LOG_INFO, 'We have a built-in method for ' . $host);
                    $func = self::$functionMap[$host];
                    return call_user_func($func, $url, $params);
                }
                break;
            case 'well-known':
                common_log(LOG_INFO, 'Considering well-known oEmbed endpoints...');
                // Whitelist: known API endpoints for sites that don't provide discovery...
                if (array_key_exists($host, self::$apiMap)) {
                    $api = self::$apiMap[$host];
                    common_log(LOG_INFO, 'Using well-known endpoint "' . $api . '" for "' . $host . '"');
                    break 2;
112
                }
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
                break;
            case 'discovery':
                try {
                    common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.');
                    $api = self::discover($url);
                    common_log(LOG_INFO, 'Found API endpoint ' . $api . ' for URL ' . $url);
                    break 2;
                } catch (Exception $e) {
                    common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers.');
                    // Just ignore it!
                }
                break;
            case 'service':
                $api = common_config('oembed', 'endpoint');
                common_log(LOG_INFO, 'Using service API endpoint ' . $api);
                break 2;
                break;
130
            }
131
        }
132 133

        if (empty($api)) {
134
            // TRANS: Server exception thrown in oEmbed action if no API endpoint is available.
135 136 137
            throw new ServerException(_('No oEmbed API endpoint available.'));
        }

138 139 140 141
        return self::getObjectFrom($api, $url, $params);
    }

    /**
142 143 144 145 146 147 148 149 150 151 152 153
     * Perform basic discovery.
     * @return string
     */
    static function discover($url)
    {
        // @fixme ideally skip this for non-HTML stuff!
        $body = self::http($url);
        return self::discoverFromHTML($url, $body);
    }

    /**
     * Partially ripped from OStatus' FeedDiscovery class.
154
     *
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
     * @param string $url source URL, used to resolve relative links
     * @param string $body HTML body text
     * @return mixed string with URL or false if no target found
     */
    static function discoverFromHTML($url, $body)
    {
        // DOMDocument::loadHTML may throw warnings on unrecognized elements,
        // and notices on unrecognized namespaces.
        $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
        $dom = new DOMDocument();
        $ok = $dom->loadHTML($body);
        error_reporting($old);

        if (!$ok) {
            throw new oEmbedHelper_BadHtmlException();
        }

        // Ok... now on to the links!
        $feeds = array(
            'application/json+oembed' => false,
        );

        $nodes = $dom->getElementsByTagName('link');
        for ($i = 0; $i < $nodes->length; $i++) {
            $node = $nodes->item($i);
            if ($node->hasAttributes()) {
                $rel = $node->attributes->getNamedItem('rel');
                $type = $node->attributes->getNamedItem('type');
                $href = $node->attributes->getNamedItem('href');
                if ($rel && $type && $href) {
                    $rel = array_filter(explode(" ", $rel->value));
                    $type = trim($type->value);
                    $href = trim($href->value);

                    if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
                        // Save the first feed found of each type...
                        $feeds[$type] = $href;
                    }
                }
            }
        }

        // Return the highest-priority feed found
        foreach ($feeds as $type => $url) {
            if ($url) {
                return $url;
            }
        }

        throw new oEmbedHelper_DiscoveryException();
    }

    /**
     * Actually do an oEmbed lookup to a particular API endpoint.
     *
     * @param string $api oEmbed API endpoint URL
211 212 213 214
     * @param string $url target URL to look up info about
     * @param array $params
     * @return object
     */
215
    static function getObjectFrom($api, $url, $params=array())
216
    {
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        $params['url'] = $url;
        $params['format'] = 'json';
        $data = self::json($api, $params);
        return self::normalize($data);
    }

    /**
     * Normalize oEmbed format.
     *
     * @param object $orig
     * @return object
     */
    static function normalize($orig)
    {
        $data = clone($orig);

        if (empty($data->type)) {
            throw new Exception('Invalid oEmbed data: no type field.');
235 236
        }

237 238 239 240 241 242 243 244 245 246
        if ($data->type == 'image') {
            // YFrog does this.
            $data->type = 'photo';
        }

        if (isset($data->thumbnail_url)) {
            if (!isset($data->thumbnail_width)) {
                // !?!?!
                $data->thumbnail_width = common_config('attachments', 'thumb_width');
                $data->thumbnail_height = common_config('attachments', 'thumb_height');
247 248 249
            }
        }

250
        return $data;
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
    }

    /**
     * Using a local function for twitpic lookups, as oohembed's adapter
     * doesn't return a valid result:
     * http://code.google.com/p/oohembed/issues/detail?id=19
     *
     * This code fetches metadata from Twitpic's own API, and attempts
     * to guess proper thumbnail size from the original's size.
     *
     * @todo respect maxwidth and maxheight params
     *
     * @param string $url
     * @param array $params
     * @return object
     */
    static function twitPic($url, $params=array())
    {
        $matches = array();
        if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) {
            $id = $matches[1];
        } else {
            throw new Exception("Invalid twitpic URL");
        }

        // Grab metadata from twitpic's API...
        // http://dev.twitpic.com/docs/2/media_show
        $data = self::json('http://api.twitpic.com/2/media/show.json',
                array('id' => $id));
        $oembed = (object)array('type' => 'photo',
                                'url' => 'http://twitpic.com/show/full/' . $data->short_id,
                                'width' => $data->width,
                                'height' => $data->height);
        if (!empty($data->message)) {
            $oembed->title = $data->message;
        }

        // Thumbnail is cropped and scaled to 150x150 box:
        // http://dev.twitpic.com/docs/thumbnails/
        $thumbSize = 150;
        $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id;
        $oembed->thumbnail_width = $thumbSize;
        $oembed->thumbnail_height = $thumbSize;

        return $oembed;
    }

    /**
     * Fetch some URL and return JSON data.
     *
     * @param string $url
     * @param array $params query-string params
     * @return object
     */
    static protected function json($url, $params=array())
    {
        $data = self::http($url, $params);
        return json_decode($data);
    }

    /**
     * Hit some web API and return data on success.
     * @param string $url
     * @param array $params
     * @return string
     */
    static protected function http($url, $params=array())
    {
        $client = HTTPClient::start();
        if ($params) {
            $query = http_build_query($params, null, '&');
            if (strpos($url, '?') === false) {
                $url .= '?' . $query;
            } else {
                $url .= '&' . $query;
            }
        }
        $response = $client->get($url);
        if ($response->isOk()) {
            return $response->getBody();
        } else {
            throw new Exception('Bad HTTP response code: ' . $response->getStatus());
        }
    }
}

337 338
class oEmbedHelper_Exception extends Exception
{
339 340
    public function __construct($message = "", $code = 0, $previous = null)
    {
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 354 355
class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
{
    function __construct($previous=null)
356
    {
357
        return parent::__construct('No oEmbed discovery data.', 0, $previous);
358
    }
359
}