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:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 
<?php
namespace Omeka\Media\Ingester;

use Omeka\Api\Request;
use Omeka\Entity\Media;
use Omeka\File\Downloader;
use Omeka\Stdlib\ErrorStore;
use Zend\Dom\Query;
use Zend\Form\Element\Url as UrlElement;
use Zend\Http\Client as HttpClient;
use Zend\Uri\Http as HttpUri;
use Zend\View\Renderer\PhpRenderer;

class OEmbed implements IngesterInterface
{
    /**
     * @var array
     */
    protected $whitelist;

    /**
     * @var HttpClient
     */
    protected $httpClient;

    /**
     * @var Downloader
     */
    protected $downloader;

    public function __construct(array $whitelist, HttpClient $httpClient,
        Downloader $downloader
    ) {
        $this->whitelist = $whitelist;
        $this->httpClient = $httpClient;
        $this->downloader = $downloader;
    }

    public function getLabel()
    {
        return 'oEmbed'; // @translate
    }

    public function getRenderer()
    {
        return 'oembed';
    }

    public function ingest(Media $media, Request $request, ErrorStore $errorStore)
    {
        $data = $request->getContent();

        if (!isset($data['o:source'])) {
            $errorStore->addError('o:source', 'No OEmbed URL specified');
            return;
        }

        $whitelisted = false;
        foreach ($this->whitelist as $regex) {
            if (preg_match($regex, $data['o:source']) === 1) {
                $whitelisted = true;
                break;
            }
        }

        if (!$whitelisted) {
            $errorStore->addError('o:source', 'Invalid OEmbed URL');
            return;
        }

        $source = $data['o:source'];

        $response = $this->makeRequest($source, 'OEmbed URL', $errorStore);
        if (!$response) {
            return;
        }

        $document = $response->getBody();
        $dom = new Query($document);
        $oEmbedLinks = $dom->queryXpath('//link[@rel="alternate" or @rel="alternative"][@type="application/json+oembed"]');
        if (!count($oEmbedLinks)) {
            $errorStore->addError('o:source', 'No OEmbed links were found at the given URI');
            return;
        }

        $oEmbedLink = $oEmbedLinks[0];
        $linkResponse = $this->makeRequest($oEmbedLink->getAttribute('href'),
            'OEmbed link URL', $errorStore);
        if (!$linkResponse) {
            return;
        }

        $mediaData = json_decode($linkResponse->getBody(), true);
        if (!$mediaData) {
            $errorStore->addError('o:source', 'Error decoding OEmbed JSON');
            return;
        }

        if (isset($mediaData['thumbnail_url'])) {
            $tempFile = $this->downloader->download($mediaData['thumbnail_url']);
            if ($tempFile) {
                if ($tempFile->storeThumbnails()) {
                    $media->setStorageId($tempFile->getStorageId());
                    $media->setHasThumbnails(true);
                }
            }
            $tempFile->delete();
        }

        $media->setData($mediaData);
        $media->setSource($source);
    }

    /**
     * {@inheritDoc}
     */
    public function form(PhpRenderer $view, array $options = [])
    {
        $urlInput = new UrlElement('o:media[__index__][o:source]');
        $urlInput->setOptions([
            'label' => 'oEmbed URL', // @translate
            'info' => 'URL for the media to embed.', // @translate
        ]);
        $urlInput->setAttributes([
            'id' => 'media-oembed-source-__index__',
            'required' => true,
        ]);
        return $view->formRow($urlInput);
    }

    /**
     * Make a request and handle any errors that might occur.
     *
     * @param string $url URL to request
     * @param string $type Type of URL (used to compose error messages)
     * @param ErrorStore $errorStore
     */
    protected function makeRequest($url, $type, ErrorStore $errorStore)
    {
        $uri = new HttpUri($url);
        if (!($uri->isValid() && $uri->isAbsolute())) {
            $errorStore->addError('o:source', "Invalid $type specified");
            return false;
        }

        $client = $this->httpClient;
        $client->reset();
        $client->setUri($uri);
        $response = $client->send();

        if (!$response->isOk()) {
            $errorStore->addError('o:source', sprintf(
                "Error reading %s: %s (%s)",
                $type,
                $response->getReasonPhrase(),
                $response->getStatusCode()
            ));
            return false;
        }

        return $response;
    }
}