Ooyala::ajax_download PHP Method

ajax_download() public method

Process download, return image ID to use as featured image.
public ajax_download ( )
    function ajax_download()
    {
        if (!$this->configured()) {
            $this->ajax_error(__('Plugin not configured', 'ooyala'));
        }
        // check nonce
        $this->ajax_check();
        $post_id = (int) filter_input(INPUT_POST, 'post_id', FILTER_VALIDATE_INT);
        $url = filter_input(INPUT_POST, 'image_url', FILTER_SANITIZE_URL);
        // sanity check inputs
        if (empty($url)) {
            $this->ajax_error(__('No image URL given', 'ooyala'));
        }
        // First check that we haven't already downloaded this image.
        $existing_id = $this->get_attachment_id($url);
        if ($existing_id) {
            $this->ajax_success(__('Attachment already exists', 'ooyala'), array('id' => $existing_id));
        }
        // The following code is copied and modified from media_sideload_image to
        // handle downloading of thumbnail assets from Ooyala.
        $image_name = basename($url);
        // Assume JPEG by default for Ooyala-downloaded thumbnails
        if (!preg_match($image_name, '/\\.(jpe?g|png|gif)$/i', $image_name)) {
            $image_name .= '.jpg';
        }
        $file_array = array('name' => $image_name);
        // Download file to temp location.
        $file_array['tmp_name'] = download_url($url);
        // If error storing temporarily, return the error.
        if (is_wp_error($file_array['tmp_name'])) {
            $this->ajax_error(sprintf(__('Failed to download image at %s', 'ooyala'), $url));
        }
        // Do the validation and storage stuff.
        $id = media_handle_sideload($file_array, $post_id);
        // If error storing permanently, unlink.
        if (is_wp_error($id)) {
            @unlink($file_array['tmp_name']);
            $this->ajax_error(__('Failed to store downloaded image', 'ooyala'));
        }
        update_post_meta($id, 'ooyala_source', $url);
        $this->ajax_success(__('Successfully downloaded image', 'ooyala'), array('id' => $id));
    }