diff --git a/php/class-delivery.php b/php/class-delivery.php index 3e1a7f0f9..7b8fa3ae0 100644 --- a/php/class-delivery.php +++ b/php/class-delivery.php @@ -452,7 +452,9 @@ public function create_delivery( $attachment_id ) { } if ( empty( $sized_url ) ) { - $sized_url = Utils::get_path_from_url( wp_get_attachment_url( $attachment_id ), true ); + // The local URL, as get_sized() uses for images. The attachment URL filter could return the Cloudinary URL, + // or prepare this sync again from within itself. + $sized_url = Utils::get_path_from_url( $this->media->local_url( $attachment_id ), true ); } // Write the preserved values with the new relation itself. Restoring them afterwards would go through a deferred save that runs on shutdown, overwriting transformations the relation has just migrated out of post meta. self::create_size_relation( $attachment_id, $sized_url, $wh, $base, $preserve ); diff --git a/php/class-media.php b/php/class-media.php index 74924df24..011fd7f30 100644 --- a/php/class-media.php +++ b/php/class-media.php @@ -1788,14 +1788,17 @@ public function cloudinary_id( $attachment_id ) { } if ( ! $this->sync->is_synced( $attachment_id ) && ! defined( 'REST_REQUEST' ) ) { + // Preparing the sync can ask for this attachment's URL, e.g. the "delivery" sync type for a file without + // dimensions (PDF, audio, documents), and the attachment URL filter calls back into this method. + // Answer that nested call with the local URL instead of preparing the sync again, which would loop. + // The real ID replaces this placeholder below. + $cloudinary_ids[ $attachment_id ] = false; + $sync_type = $this->sync->maybe_prepare_sync( $attachment_id ); // Check sync type allows for continued rendering. i.e meta update, breakpoints etc, will still allow the URL to work, // Where is type "file" will not since it's still being uploaded. if ( $this->sync->is_required( $sync_type, $attachment_id ) ) { - // Cache ID to prevent multiple lookups. - $cloudinary_ids[ $attachment_id ] = false; - - return false; // Return and render local URLs. + return false; // Return and render local URLs. The placeholder above stays cached, to prevent multiple lookups. } } diff --git a/php/class-sync.php b/php/class-sync.php index 2db1f2277..6b35c96ad 100644 --- a/php/class-sync.php +++ b/php/class-sync.php @@ -113,6 +113,7 @@ class Sync implements Setup, Assets { 'version' => '_cloudinary_version', 'raw_url' => '_cloudinary_url', 'db_version' => '_cloudinary_db_version', + 'loop_errors_cleared' => '_cloudinary_delivery_loop_errors_cleared', 'debug' => '_cloudinary_debug', ); @@ -137,6 +138,59 @@ public function __construct( Plugin $plugin ) { // Register Settings. add_filter( 'cloudinary_admin_pages', array( $this, 'settings' ) ); + + add_action( 'cloudinary_version_upgrade', array( $this, 'clear_delivery_loop_errors' ) ); + } + + /** + * Get the sync error saved when a sync type keeps recursing without advancing. + * + * @param string $type The sync type that would not advance. + * + * @return string + */ + public static function get_loop_error_message( $type ) { + return sprintf( + /* translators: %s is the sync type that would not advance. */ + __( 'Sync loop detected: the "%s" sync state could not be saved.', 'cloudinary' ), + $type + ); + } + + /** + * Clear the sync loop errors that 3.3.9 flagged on the "delivery" sync type, so those attachments are retried. + * + * From 3.3.9, files without dimensions (PDF, SVG, documents, audio) got this error on upload, from a loop between + * preparing their sync and getting their URL. Now that the loop is fixed, they can sync without anyone clearing the + * error by hand. Only this exact error is cleared. + * + * Runs once, on the first upgrade to a version with the fix. The version upgraded from is then the last one without + * it, so the errors are cleared when it is 3.3.9 or later, whatever release that is. Loops flagged after the fix, + * which are genuine, stay visible. + * + * @param string $old_version The version upgrading from. + * + * @uses action:cloudinary_version_upgrade + */ + public function clear_delivery_loop_errors( $old_version ) { + if ( get_option( self::META_KEYS['loop_errors_cleared'] ) ) { + return; + } + update_option( self::META_KEYS['loop_errors_cleared'], true, false ); + + if ( version_compare( $old_version, '3.3.9', '<' ) ) { + return; + } + + // The plugin ships no translations, so the message is in English. Clear the current locale's too, in case a + // site translates it. + $messages = array( + 'Sync loop detected: the "delivery" sync state could not be saved.', + self::get_loop_error_message( 'delivery' ), + ); + foreach ( array_unique( $messages ) as $message ) { + delete_metadata( 'post', 0, self::META_KEYS['sync_error'], $message, true ); + } } /** @@ -947,15 +1001,7 @@ public function validate_sync_type( $type, $attachment_id ) { */ $limit = apply_filters( 'cloudinary_sync_type_retry_limit', 50, $type, $attachment_id ); if ( $depth[ $key ] > $limit ) { - update_post_meta( - $attachment_id, - self::META_KEYS['sync_error'], - sprintf( - /* translators: %s is the sync type that would not advance. */ - __( 'Sync loop detected: the "%s" sync state could not be saved.', 'cloudinary' ), - $type - ) - ); + update_post_meta( $attachment_id, self::META_KEYS['sync_error'], self::get_loop_error_message( $type ) ); return null; } diff --git a/tests/e2e/cloudinary-upload-sync.spec.js b/tests/e2e/cloudinary-upload-sync.spec.js new file mode 100644 index 000000000..b42504c70 --- /dev/null +++ b/tests/e2e/cloudinary-upload-sync.spec.js @@ -0,0 +1,259 @@ +/** + * External dependencies + */ +const fs = require( 'fs' ); +const path = require( 'path' ); +const { test, expect } = require( './fixtures' ); + +/** + * Internal dependencies + */ +const { ensureCloudinaryConnected } = require( './utils/connection' ); +const { phpJson, saveSettings } = require( './utils/settings' ); +const { wpCli, wpEvalFile } = require( './utils/wizard' ); + +const FIXTURES_DIR = path.join( __dirname, 'fixtures' ); + +/** + * The files to upload, one per kind of asset the plugin syncs. + * + * Most have no width and height, which is what sent files into a sync loop on + * upload. The image and the video check that files with dimensions still sync. + * Between them they cover Cloudinary's image, video and raw resource types. + * + * @type {string[]} + */ +const FILES = [ + 'test-document.pdf', + 'svg-valid.svg', + 'test-document.docx', + 'test-sheet.xlsx', + 'test-data.csv', + 'test-archive.zip', + 'test-audio.mp3', + 'test-image.jpg', + 'test-video.mp4', +]; + +/** + * Settings pinned for the spec, restored in afterAll. + * + * @type {Record} + */ +const SETTINGS = { + auto_sync: 'on', + offload: 'dual_full', + svg_support: 'on', +}; + +/** @type {Record|null} */ +let previousSettings = null; + +/** + * Attachment IDs the spec creates, removed in afterAll with their + * Cloudinary assets. + * + * @type {number[]} + */ +let attachmentIds = []; + +/** + * Get the sync state of the attachments with the given file names. + * + * Reads them all in one call, as each call boots WordPress. + * + * @param {string[]} filenames The file names. + * @return {Record} The sync state by file name, or null when there is no such attachment. + */ +function getSyncStates( filenames ) { + return JSON.parse( + wpEvalFile( ` + $plugin = get_plugin_instance(); + $media = $plugin->get_component( 'media' ); + $sync = $plugin->get_component( 'sync' ); + $states = array(); + foreach ( ${ phpJson( filenames ) } as $filename ) { + $ids = get_posts( + array( + 'post_type' => 'attachment', + 'post_status' => 'inherit', + 'fields' => 'ids', + 'meta_query' => array( + array( + 'key' => '_wp_attached_file', + 'value' => '/' . $filename, + 'compare' => 'LIKE', + ), + ), + ) + ); + $id = $ids ? (int) $ids[0] : 0; + $states[ $filename ] = $id ? array( + 'id' => $id, + 'error' => (string) get_post_meta( $id, Sync::META_KEYS['sync_error'], true ), + 'publicId' => $media->has_public_id( $id ) ? $media->get_public_id( $id ) : '', + 'synced' => $sync->is_synced( $id, true ), + 'url' => (string) $media->cloudinary_url( $id ), + ) : null; + } + echo wp_json_encode( $states ); + ` ) + ); +} + +// @serial: needs real credentials in `cloudinary_connect` to sync assets, +// while every analytics spec overwrites that option with fake ones. +test.describe( 'Cloudinary upload sync', { tag: '@serial' }, () => { + test.beforeAll( () => { + ensureCloudinaryConnected(); + previousSettings = saveSettings( SETTINGS ); + } ); + + test.afterAll( () => { + try { + if ( previousSettings ) { + saveSettings( previousSettings ); + previousSettings = null; + } + } finally { + const ids = attachmentIds; + attachmentIds = []; + + // Remove the assets directly, so a failed test does not leave + // them in the Cloudinary account. + if ( ids.length ) { + try { + wpEvalFile( ` + $plugin = get_plugin_instance(); + $media = $plugin->get_component( 'media' ); + $api = $plugin->get_component( 'connect' )->api; + foreach ( ${ phpJson( ids ) } as $id ) { + if ( $media->has_public_id( $id ) ) { + $api->destroy( $media->get_resource_type( $id ), array( 'public_id' => $media->get_public_id( $id ) ) ); + } + } + ` ); + } catch ( e ) { + console.warn( + 'Cleanup of the Cloudinary assets failed:', + e.message + ); + } + } + + for ( const id of ids ) { + try { + wpCli( [ 'post', 'delete', String( id ), '--force' ] ); + } catch ( e ) { + console.warn( + `Cleanup of post ${ id } failed:`, + e.message + ); + } + } + } + } ); + + // Uploads through the browser on purpose. A REST upload (`/wp/v2/media`, + // as the other specs use) skips the sync preparation that runs while the + // file is uploaded, and the plugin's admin URL filters, so it can't catch + // a sync loop between the two. + test( 'files uploaded through the Media Library sync to Cloudinary', async ( { + admin, + page, + } ) => { + // Above the default 60s: the sync poll alone may take up to 90s. + test.setTimeout( 150_000 ); + + // Fresh file names, so no asset from an earlier run applies. + const stamp = Date.now(); + const filenames = FILES.map( ( file ) => { + const { name, ext } = path.parse( file ); + return `upload-sync-${ name }-${ stamp }${ ext }`; + } ); + + await admin.visitAdminPage( 'media-new.php' ); + const input = page.locator( '#plupload-upload-ui input[type="file"]' ); + await expect( input ).toBeAttached(); + + // The uploader sends one request per file. + const responses = []; + const uploaded = new Promise( ( resolve ) => { + page.on( 'response', ( response ) => { + if ( + response.url().includes( '/wp-admin/async-upload.php' ) && + 'POST' === response.request().method() + ) { + responses.push( response ); + if ( responses.length === filenames.length ) { + resolve(); + } + } + } ); + } ); + await input.setInputFiles( + FILES.map( ( file, i ) => ( { + name: filenames[ i ], + mimeType: 'application/octet-stream', + buffer: fs.readFileSync( path.join( FIXTURES_DIR, file ) ), + } ) ) + ); + await uploaded; + for ( const response of responses ) { + expect( response.ok(), 'the upload should succeed' ).toBe( true ); + } + + let states = getSyncStates( filenames ); + for ( const filename of filenames ) { + if ( states[ filename ] ) { + attachmentIds.push( states[ filename ].id ); + } + } + + // Let the auto-sync queue push the files, as it does on a live site. + // Syncing them from the test as well would race with the queue. + await expect + .poll( + () => { + states = getSyncStates( filenames ); + return filenames.filter( + ( filename ) => + states[ filename ] && + ! states[ filename ].synced && + ! states[ filename ].error + ); + }, + { + message: 'every file should finish syncing', + timeout: 90000, + intervals: [ 1000 ], + } + ) + .toEqual( [] ); + + for ( const filename of filenames ) { + const state = states[ filename ]; + expect + .soft( state, `${ filename } should be in the Media Library` ) + .toBeTruthy(); + expect + .soft( + state?.error, + `${ filename } should not have a sync error` + ) + .toBe( '' ); + expect + .soft( state?.publicId, `${ filename } should get a public ID` ) + .toBeTruthy(); + expect + .soft( state?.synced, `${ filename } should be fully synced` ) + .toBe( true ); + expect + .soft( + state?.url, + `${ filename } should have a Cloudinary URL` + ) + .toContain( 'res.cloudinary.com' ); + } + } ); +} ); diff --git a/tests/e2e/fixtures/test-archive.zip b/tests/e2e/fixtures/test-archive.zip new file mode 100644 index 000000000..f8e1809ee Binary files /dev/null and b/tests/e2e/fixtures/test-archive.zip differ diff --git a/tests/e2e/fixtures/test-audio.mp3 b/tests/e2e/fixtures/test-audio.mp3 new file mode 100644 index 000000000..5aea47576 Binary files /dev/null and b/tests/e2e/fixtures/test-audio.mp3 differ diff --git a/tests/e2e/fixtures/test-data.csv b/tests/e2e/fixtures/test-data.csv new file mode 100644 index 000000000..bed40b0fc --- /dev/null +++ b/tests/e2e/fixtures/test-data.csv @@ -0,0 +1,3 @@ +name,value +alpha,1 +beta,2 diff --git a/tests/e2e/fixtures/test-document.docx b/tests/e2e/fixtures/test-document.docx new file mode 100644 index 000000000..532842ff1 Binary files /dev/null and b/tests/e2e/fixtures/test-document.docx differ diff --git a/tests/e2e/fixtures/test-document.pdf b/tests/e2e/fixtures/test-document.pdf new file mode 100644 index 000000000..61debf6b4 Binary files /dev/null and b/tests/e2e/fixtures/test-document.pdf differ diff --git a/tests/e2e/fixtures/test-sheet.xlsx b/tests/e2e/fixtures/test-sheet.xlsx new file mode 100644 index 000000000..ba33ce278 Binary files /dev/null and b/tests/e2e/fixtures/test-sheet.xlsx differ diff --git a/tests/phpunit/tests/test-media-cloudinary-id-reentry.php b/tests/phpunit/tests/test-media-cloudinary-id-reentry.php new file mode 100644 index 000000000..736288d9a --- /dev/null +++ b/tests/phpunit/tests/test-media-cloudinary-id-reentry.php @@ -0,0 +1,441 @@ +>endobj\n2 0 obj<>endobj\n3 0 obj<>endobj\ntrailer<>\n%%EOF\n"; + + /** + * The sync types live on the Sync component, which outlives any one test. Rebuild them once the hooks are + * restored, so a test's cloudinary_sync_base_struct filter doesn't leak into later tests. + * + * @return void + */ + public function tear_down() { + parent::tear_down(); + + \Cloudinary\get_plugin_instance()->get_component( 'sync' )->register_assets(); + } + + /** + * Get the Media component. + * + * @return \Cloudinary\Media + */ + protected function get_media() { + return \Cloudinary\get_plugin_instance()->get_component( 'media' ); + } + + /** + * Fake a connected site, so the sync types are registered and the components are wired, without reaching the + * network. Same setup as Test_Sync_Loop_Guard::get_sync(). + * + * @return Sync + */ + protected function get_sync() { + $plugin = \Cloudinary\get_plugin_instance(); + $connect = $plugin->get_component( 'connect' ); + + $plugin->settings->set_param( 'connected', true ); + set_transient( Connect::META_KEYS['usage'], array( 'placeholder' => true ), HOUR_IN_SECONDS ); + $plugin->settings->set_value( 'cloudinary_url', 'cloudinary://123456789012345:abcdefghijklmnopqrstuvwxyzABCDEF@test-cloud' ); + $connect->setup(); + + do_action( 'cloudinary_connected', $plugin ); + + $plugin->get_component( 'media' )->setup(); + $plugin->get_component( 'sync' )->setup(); + $plugin->get_component( 'delivery' )->setup(); + + $sync = $plugin->get_component( 'sync' ); + $sync->register_assets(); + + return $sync; + } + + /** + * Create an attachment from a file with the given contents. + * + * @param string $filename The file name. + * @param string $contents The file contents. + * + * @return int + */ + protected function create_attachment( $filename, $contents ) { + $path = trailingslashit( get_temp_dir() ) . wp_unique_filename( get_temp_dir(), $filename ); + file_put_contents( $path, $contents ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents + + $attachment_id = self::factory()->attachment->create_upload_object( $path ); + wp_delete_file( $path ); + + return $attachment_id; + } + + /** + * Get a sync type's saved signature for an attachment. + * + * @param Sync $sync The Sync component. + * @param int $attachment_id The attachment ID. + * @param string $type The sync type. + * + * @return mixed + */ + protected function get_signature_item( $sync, $attachment_id, $type ) { + $signature = $sync->get_signature( $attachment_id, false ); + + return isset( $signature[ $type ] ) ? $signature[ $type ] : null; + } + + /** + * Get the Cloudinary ID of an unsynced PDF with the admin's attachment URL filter in place, as when it's uploaded + * through the Media Library or first shown on an admin screen. Preparing its sync must save the "delivery" + * signature instead of looping until the guard flags it. + * + * @return void + */ + public function test_preparing_the_sync_of_a_pdf_does_not_loop() { + $sync = $this->get_sync(); + $media = $this->get_media(); + $media->add_live_url_filters(); + + $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + $this->assertEmpty( wp_get_attachment_metadata( $attachment_id )['width'] ?? null, 'The PDF must have no width, so create_delivery() falls back to its URL.' ); + + // Each check of the "delivery" sync type is one round of the loop. + $rounds = 0; + add_filter( + 'cloudinary_sync_type_retry_limit', + function ( $limit, $type, $id ) use ( $attachment_id, &$rounds ) { + if ( 'delivery' === $type && $attachment_id === $id ) { + ++$rounds; + } + + return $limit; + }, + 10, + 3 + ); + + $media->cloudinary_id( $attachment_id ); + + $this->assertEmpty( get_post_meta( $attachment_id, Sync::META_KEYS['sync_error'], true ), 'The PDF must not be flagged with a sync loop error.' ); + $this->assertNotNull( $this->get_signature_item( $sync, $attachment_id, 'delivery' ), 'The "delivery" signature must be saved.' ); + $this->assertLessThanOrEqual( 2, $rounds, 'The "delivery" sync type must not be prepared again from within itself.' ); + } + + /** + * Within its own sync preparation, the attachment URL must be the local one, even for an attachment that already + * has a public ID, which the admin's attachment URL filter would turn into a Cloudinary URL. + * + * @return void + */ + public function test_the_nested_attachment_url_is_the_local_one() { + $this->get_sync(); + $media = $this->get_media(); + $media->add_live_url_filters(); + // Match an admin request: this frontend-only filter is registered because tests don't run in the admin. + remove_filter( 'wp_get_attachment_url', array( \Cloudinary\get_plugin_instance()->get_component( 'delivery' ), 'ensure_relation' ) ); + + $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + $media->update_post_meta( $attachment_id, Sync::META_KEYS['public_id'], 'sample' ); + $local_url = wp_get_upload_dir()['baseurl'] . '/' . get_post_meta( $attachment_id, '_wp_attached_file', true ); + + $nested_urls = array(); + add_filter( + 'wp_get_attachment_url', + function ( $url, $id ) use ( $attachment_id, &$nested_urls ) { + if ( $attachment_id === $id ) { + $nested_urls[] = $url; + } + + return $url; + }, + 11, + 2 + ); + + $media->cloudinary_id( $attachment_id ); + + $this->assertNotEmpty( $nested_urls, 'create_delivery() should have asked for the attachment URL.' ); + foreach ( $nested_urls as $url ) { + $this->assertStringNotContainsString( 'res.cloudinary.com', $url ); + $this->assertSame( $local_url, $url ); + } + } + + /** + * The guard only answers the nested call. Once its sync is prepared, the outer call returns the attachment's real + * Cloudinary ID, and later calls get it too, not the placeholder. + * + * @return void + */ + public function test_the_outer_call_still_gets_the_cloudinary_id() { + // cloudinary_id() returns the real ID once the sync is prepared, unless a sync type required to render the + // URL is still pending. For a new PDF, the upload ("file") is next, so make no type required for this test. + add_filter( + 'cloudinary_sync_base_struct', + function ( $struct ) { + foreach ( $struct as $type => $structure ) { + $struct[ $type ]['required'] = false; + } + + return $struct; + } + ); + $this->get_sync(); + $media = $this->get_media(); + $media->add_live_url_filters(); + + $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + $media->update_post_meta( $attachment_id, Sync::META_KEYS['public_id'], 'sample' ); + + // Count the "delivery" sync type runs, to check this call is the one that prepares the sync. + $rounds = 0; + add_filter( + 'cloudinary_sync_type_retry_limit', + function ( $limit, $type, $id ) use ( $attachment_id, &$rounds ) { + if ( 'delivery' === $type && $attachment_id === $id ) { + ++$rounds; + } + + return $limit; + }, + 10, + 3 + ); + + $cloudinary_id = $media->cloudinary_id( $attachment_id ); + + $this->assertGreaterThan( 0, $rounds, 'The call should have prepared the sync, setting the placeholder.' ); + $this->assertEmpty( get_post_meta( $attachment_id, Sync::META_KEYS['sync_error'], true ) ); + $this->assertNotEmpty( $cloudinary_id, 'The outer call must return the real Cloudinary ID, not the placeholder.' ); + $this->assertSame( $cloudinary_id, $media->cloudinary_id( $attachment_id ), 'Later calls must get the real Cloudinary ID too.' ); + } + + /** + * A call to cloudinary_id() for an attachment whose sync it is already preparing must not prepare it again, however + * the call is reached. + * + * @return void + */ + public function test_a_nested_call_does_not_prepare_the_sync_again() { + $this->get_sync(); + $media = $this->get_media(); + + $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + + // Call cloudinary_id() from within the sync preparation, and track how deep the preparations nest. Stop at 3, + // so the test ends even without the guard. + $depth = 0; + $max_depth = 0; + $nested = array(); + add_filter( + 'cloudinary_sync_type_retry_limit', + function ( $limit, $type, $id ) use ( $media, $attachment_id, &$depth, &$max_depth, &$nested ) { + if ( $attachment_id === $id && $depth < 3 ) { + ++$depth; + $max_depth = max( $max_depth, $depth ); + $nested[] = $media->cloudinary_id( $id ); + --$depth; + } + + return $limit; + }, + 10, + 3 + ); + + $media->cloudinary_id( $attachment_id ); + + $this->assertNotEmpty( $nested, 'The sync preparation should have made the nested call.' ); + $this->assertSame( 1, $max_depth, 'The nested call must not prepare the sync again.' ); + foreach ( $nested as $cloudinary_id ) { + $this->assertFalse( $cloudinary_id, 'The nested call must get the placeholder, so the local URL is used.' ); + } + } + + /** + * The "delivery" sync type must save the local path of a file without dimensions, even when the attachment URL + * filter returns its Cloudinary URL. + * + * @return void + */ + public function test_delivery_saves_the_local_path_of_a_file_without_dimensions() { + // Let cloudinary_id() return the real ID, as in test_the_outer_call_still_gets_the_cloudinary_id(). + add_filter( + 'cloudinary_sync_base_struct', + function ( $struct ) { + foreach ( $struct as $type => $structure ) { + $struct[ $type ]['required'] = false; + } + + return $struct; + } + ); + $this->get_sync(); + $media = $this->get_media(); + $delivery = \Cloudinary\get_plugin_instance()->get_component( 'delivery' ); + $media->add_live_url_filters(); + // Match an admin request: this frontend-only filter is registered because tests don't run in the admin. + remove_filter( 'wp_get_attachment_url', array( $delivery, 'ensure_relation' ) ); + + $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + $media->update_post_meta( $attachment_id, Sync::META_KEYS['public_id'], 'sample' ); + $this->assertNotEmpty( $media->cloudinary_id( $attachment_id ) ); + $this->assertStringContainsString( 'res.cloudinary.com', wp_get_attachment_url( $attachment_id ), 'The attachment URL should now be the Cloudinary one.' ); + + $delivery->create_delivery( $attachment_id ); + + $sized_url = Relationship::get_relationship( $attachment_id )->sized_url; + $this->assertStringNotContainsString( 'cloudinary.com', $sized_url ); + $this->assertSame( Utils::get_path_from_url( $media->local_url( $attachment_id ), true ), $sized_url ); + } + + /** + * Create an attachment flagged with a sync error. + * + * @param string $error The sync error. + * + * @return int + */ + protected function create_errored_attachment( $error ) { + $attachment_id = self::factory()->attachment->create_object( + array( + 'file' => 'errored.pdf', + 'post_mime_type' => 'application/pdf', + ) + ); + update_post_meta( $attachment_id, Sync::META_KEYS['sync_error'], $error ); + + return $attachment_id; + } + + /** + * The first upgrade to a version with the fix clears the "delivery" sync loop error, in English and in the current + * language, when the site ran 3.3.9 or a later release without the fix. Every other sync error is kept. + * + * @return void + */ + public function test_upgrade_from_3_3_9_or_later_clears_only_the_delivery_loop_error() { + $sync = $this->get_sync(); + $english = 'Sync loop detected: the "delivery" sync state could not be saved.'; + + // Pretend the site is in another language, so the translated message differs from the English one. + add_filter( + 'gettext', + function ( $translation, $text, $domain ) { + if ( 'cloudinary' === $domain && 'Sync loop detected: the "%s" sync state could not be saved.' === $text ) { + return 'Boucle de synchronisation : l’état "%s" n’a pas pu être enregistré.'; + } + + return $translation; + }, + 10, + 3 + ); + $this->assertNotSame( $english, Sync::get_loop_error_message( 'delivery' ) ); + + // 3.3.9 introduced the loop. Releases after it without the fix have it too. + foreach ( array( '3.3.9', '3.3.10', '3.4.0' ) as $old_version ) { + delete_option( Sync::META_KEYS['loop_errors_cleared'] ); + $english_loop = $this->create_errored_attachment( $english ); + $translated_loop = $this->create_errored_attachment( Sync::get_loop_error_message( 'delivery' ) ); + $other_loop = $this->create_errored_attachment( Sync::get_loop_error_message( 'file' ) ); + $other_error = $this->create_errored_attachment( 'Invalid file type' ); + + $sync->clear_delivery_loop_errors( $old_version ); + + $this->assertEmpty( get_post_meta( $english_loop, Sync::META_KEYS['sync_error'], true ), "Upgrading from $old_version must clear the English error." ); + $this->assertEmpty( get_post_meta( $translated_loop, Sync::META_KEYS['sync_error'], true ), "Upgrading from $old_version must clear the translated error." ); + $this->assertSame( Sync::get_loop_error_message( 'file' ), get_post_meta( $other_loop, Sync::META_KEYS['sync_error'], true ) ); + $this->assertSame( 'Invalid file type', get_post_meta( $other_error, Sync::META_KEYS['sync_error'], true ) ); + } + } + + /** + * Versions before 3.3.9 didn't have the loop, so after an upgrade from one of them, or a new install, a "delivery" + * sync loop error is a genuine one, and must stay visible. + * + * @return void + */ + public function test_upgrade_from_before_3_3_9_keeps_the_delivery_loop_error() { + $sync = $this->get_sync(); + $attachment_id = $this->create_errored_attachment( Sync::get_loop_error_message( 'delivery' ) ); + + // 2.0.1 is what the upgrade reports on a new install. + foreach ( array( '3.3.8', '2.0.1' ) as $old_version ) { + delete_option( Sync::META_KEYS['loop_errors_cleared'] ); + + $sync->clear_delivery_loop_errors( $old_version ); + + $this->assertSame( + Sync::get_loop_error_message( 'delivery' ), + get_post_meta( $attachment_id, Sync::META_KEYS['sync_error'], true ), + "Upgrading from $old_version must keep the error." + ); + } + } + + /** + * The cleanup runs only on the first upgrade to a version with the fix. Loops flagged after that are genuine, and + * later upgrades must keep them visible, including on sites that installed a version with the fix. + * + * @return void + */ + public function test_the_cleanup_runs_only_once() { + $sync = $this->get_sync(); + + foreach ( array( '3.3.9', '2.0.1' ) as $first_old_version ) { + delete_option( Sync::META_KEYS['loop_errors_cleared'] ); + $sync->clear_delivery_loop_errors( $first_old_version ); + + $attachment_id = $this->create_errored_attachment( Sync::get_loop_error_message( 'delivery' ) ); + $sync->clear_delivery_loop_errors( '3.4.1' ); + + $this->assertSame( + Sync::get_loop_error_message( 'delivery' ), + get_post_meta( $attachment_id, Sync::META_KEYS['sync_error'], true ), + "After a first upgrade from $first_old_version, a later upgrade must keep the error." + ); + } + } + + /** + * The cleanup runs on the plugin's version upgrade. + * + * @return void + */ + public function test_cleanup_is_hooked_to_the_version_upgrade() { + $sync = \Cloudinary\get_plugin_instance()->get_component( 'sync' ); + + $this->assertNotFalse( has_action( 'cloudinary_version_upgrade', array( $sync, 'clear_delivery_loop_errors' ) ) ); + } +}