Unverified Commit 9b856dd9 authored by Joe Hoyle's avatar Joe Hoyle
Browse files

Fix PDF attachment metadata and thumbnail creation

parent 70d50a23
Loading
Loading
Loading
Loading
+39 −0
Original line number Diff line number Diff line
@@ -2,6 +2,8 @@

class S3_Uploads_Image_Editor_Imagick extends WP_Image_Editor_Imagick {

	protected $temp_file_to_cleanup = null;

	/**
	 * Imagick by default can't handle s3:// paths
	 * for saving images. We have instead save it to a file file,
@@ -44,4 +46,41 @@ class S3_Uploads_Image_Editor_Imagick extends WP_Image_Editor_Imagick {
			'mime-type' => $mime_type,
		);
	}

	public function load() {
		$result = parent::load();

		// `load` can call pdf_setup() which has to copy the file to a temp local copy.
		// In this event we want to clean it up once `load` has been completed.
		if ( $this->temp_file_to_cleanup ) {
			unlink( $this->temp_file_to_cleanup );
			$this->temp_file_to_cleanup = null;
		}
		return $result;
	}

	/**
	 * Sets up Imagick for PDF processing.
	 * Increases rendering DPI and only loads first page.
	 *
	 * @since 4.7.0
	 *
	 * @return string|WP_Error File to load or WP_Error on failure.
	 */
	protected function pdf_setup() {
		$temp_filename = tempnam( get_temp_dir(), 's3-uploads' );
		$this->temp_file_to_cleanup = $temp_filename;
		copy( $this->file, $temp_filename );

		try {
			// By default, PDFs are rendered in a very low resolution.
			// We want the thumbnail to be readable, so increase the rendering DPI.
			$this->image->setResolution( 128, 128 );

			// Only load the first page.
			return $temp_filename . '[0]';
		} catch ( Exception $e ) {
			return new WP_Error( 'pdf_setup_failed', $e->getMessage(), $this->file );
		}
	}
}

tests/data/gdpr.pdf

0 → 100644
+1.98 MiB

File added.

No diff preview for this file type.

+24 −0
Original line number Diff line number Diff line
@@ -116,6 +116,30 @@ class Test_S3_Uploads extends WP_UnitTestCase {
		}
	}

	public function test_generate_attachment_metadata_for_pdf() {
		S3_Uploads::get_instance()->setup();
		$upload_dir = wp_upload_dir();
		copy( dirname( __FILE__ ) . '/data/gdpr.pdf', $upload_dir['path'] . '/gdpr.pdf' );
		$test_file = $upload_dir['path'] . '/gdpr.pdf';
		$attachment_id = $this->factory->attachment->create_object( $test_file, 0, array(
			'post_mime_type' => 'application/pdf',
			'post_excerpt'   => 'A sample caption',
		) );

		$meta_data = wp_generate_attachment_metadata( $attachment_id, $test_file );

		$this->assertEquals( array(
			'file'      => 'gdpr-pdf-106x150.jpg',
			'width'     => 106,
			'height'    => 150,
			'mime-type' => 'image/jpeg',
		), $meta_data['sizes']['thumbnail'] );


		$wp_upload_dir = wp_upload_dir();
		$this->assertTrue( file_exists( $wp_upload_dir['path'] . '/gdpr-pdf-106x150.jpg' ) );
	}

	function test_get_s3_bucket_location() {

		$uploads = new S3_Uploads( 'hmn-uploads', S3_UPLOADS_KEY, S3_UPLOADS_SECRET, null, S3_UPLOADS_REGION );