diff --git a/.github/workflows/wp_dam_hook_integrity_on_pull_request.yml b/.github/workflows/wp_dam_hook_integrity_on_pull_request.yml new file mode 100644 index 0000000000..d37de4b822 --- /dev/null +++ b/.github/workflows/wp_dam_hook_integrity_on_pull_request.yml @@ -0,0 +1,44 @@ +on: + pull_request: + # Deny-list, mirroring GODAM_EXCLUDED_ROOT_DIRS in + # bin/hook-check/shared.php — an allow-list of specific directories here + # previously meant attachment-touching code added to godam.php, lib/, or + # any new top-level directory would never even trigger this workflow. + # bin/hook-check/*.php is re-included as the one exception inside the + # otherwise-excluded bin/: those ARE the checker's own files, and a + # change to them needs to re-run the checks they define. + paths: + - '**/*.php' + - '!.git/**' + - '!.github/**' + - '!.husky/**' + - '!.idea/**' + - '!node_modules/**' + - '!tests/**' + - '!languages/**' + - '!bin/**' + - 'bin/hook-check/*.php' + +name: wp-dam hook integrity + +permissions: + contents: read + +jobs: + checkHooks: + name: Check rtgodam_before/after_attachment_lookup hook integrity + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.4' + coverage: none + - name: Run hook integrity check + run: php bin/hook-check/balance.php check + - name: Run attachment-access coverage check + if: always() + run: php bin/hook-check/coverage.php check diff --git a/.husky/pre-commit b/.husky/pre-commit index 1fb913e3d5..fd8e7b5380 100644 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1 +1 @@ -npm run lint:staged +npm run lint:staged && ./bin/hook-check/pre-commit.sh diff --git a/admin/class-rtgodam-retranscodemedia.php b/admin/class-rtgodam-retranscodemedia.php index e7e5d770ea..8e6c4db0f2 100644 --- a/admin/class-rtgodam-retranscodemedia.php +++ b/admin/class-rtgodam-retranscodemedia.php @@ -173,11 +173,21 @@ public function admin_enqueues( $hook_suffix ) { if ( ! empty( $ids ) ) { $ids = explode( ',', $ids ); } else { + /** + * Fires before this fallback "no explicit IDs" scan reads any + * attachment data, so integrations that centralize media on another + * site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + add_filter( 'posts_where', array( $this, 'add_search_mime_types' ) ); - $query = new WP_Query( array( 'post_type' => 'attachments' ) ); + $query = new WP_Query( array( 'post_type' => 'attachment' ) ); $media = $query->get_posts(); remove_filter( 'posts_where', array( $this, 'add_search_mime_types' ) ); if ( empty( $media ) || is_wp_error( $media ) ) { + do_action( 'rtgodam_after_attachment_lookup' ); // translators: Link to the media page. echo '

' . sprintf( esc_html__( "Unable to find any media. Are you sure some exist?", 'godam' ), esc_url( admin_url( 'upload.php' ) ) ) . '

'; @@ -198,6 +208,8 @@ public function admin_enqueues( $hook_suffix ) { ); } } + + do_action( 'rtgodam_after_attachment_lookup' ); } $stopping_text = esc_html__( 'Stopping...', 'godam' ); @@ -240,6 +252,17 @@ public function admin_enqueues( $hook_suffix ) { */ public function add_media_row_action( $actions, $post ) { + /** + * Fires before checking whether this attachment is a supported + * document type, so integrations that centralize media on another + * site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $is_supported_document = rtgodam_is_supported_document_attachment( $post->ID ); + do_action( 'rtgodam_after_attachment_lookup' ); + // Documents are included so files already in the library — which predate document // support and so were never sent to GoDAM Central — can have a preview generated // without re-uploading them. Tested against the attachment rather than its MIME alone, @@ -248,7 +271,7 @@ public function add_media_row_action( $actions, $post ) { if ( ( 'audio/' !== substr( $post->post_mime_type, 0, 6 ) && 'video/' !== substr( $post->post_mime_type, 0, 6 ) && - ! rtgodam_is_supported_document_attachment( $post->ID ) + ! $is_supported_document ) || // Safe fallback via filter; PHPCS can't resolve dynamic capability. // phpcs:ignore WordPress.WP.Capabilities.Undetermined @@ -375,6 +398,18 @@ public function retranscode_interface() { // Create the list of image IDs. $usage_info = get_option( 'rtgodam-usage' ); $ids = rtgodam_filter_input( INPUT_GET, 'ids', FILTER_SANITIZE_FULL_SPECIAL_CHARS ); + + /** + * Fires before either branch below reads attachment data + * (get_attached_file()/get_the_title(), explicit IDs or the + * fallback WP_Query scan), so integrations that centralize + * media on another site can switch context first. Unlike + * admin_enqueues(), both branches here touch attachment + * data, so both are wrapped. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); if ( ! empty( $ids ) ) { $media = array_map( 'intval', explode( ',', trim( $ids, ',' ) ) ); $ids = implode( ',', $media ); @@ -391,10 +426,11 @@ public function retranscode_interface() { } } else { add_filter( 'posts_where', array( $this, 'add_search_mime_types' ) ); - $query = new WP_Query( array( 'post_type' => 'attachments' ) ); + $query = new WP_Query( array( 'post_type' => 'attachment' ) ); $media = $query->get_posts(); remove_filter( 'posts_where', array( $this, 'add_search_mime_types' ) ); if ( empty( $media ) || is_wp_error( $media ) ) { + do_action( 'rtgodam_after_attachment_lookup' ); // translators: Link to the media page. echo '

' . sprintf( esc_html__( "Unable to find any media. Are you sure some exist?", 'godam' ), esc_url( admin_url( 'upload.php' ) ) ) . '

'; @@ -417,6 +453,7 @@ public function retranscode_interface() { } $ids = implode( ',', $ids ); } + do_action( 'rtgodam_after_attachment_lookup' ); if ( empty( $ids ) ) { echo '

' . esc_html__( 'There are no media available to send for transcoding.', 'godam' ) . '

'; @@ -556,8 +593,23 @@ public function retranscode_interface() { * @param string $message Error message. */ public function die_json_error_msg( $id, $message ) { + /** + * Fires before reading this attachment's title for the error payload below. + * + * No caller currently reaches this method (kept as a public JSON-error + * helper), but the read is wrapped defensively rather than relying on + * every future caller to remember to. die()/exit() never run a + * try/finally's finally block, so the after-hook fires here — before + * die() — rather than wrapping the die() call itself. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $title = get_the_title( $id ); + do_action( 'rtgodam_after_attachment_lookup' ); + // translators: Media name, Media ID and message for failed transcode. - die( wp_json_encode( array( 'error' => sprintf( __( '"%1$s" (ID %2$s) failed to send. The error message was: %3$s', 'godam' ), esc_html( get_the_title( $id ) ), $id, $message ) ) ) ); + die( wp_json_encode( array( 'error' => sprintf( __( '"%1$s" (ID %2$s) failed to send. The error message was: %3$s', 'godam' ), esc_html( $title ), $id, $message ) ) ) ); } /** @@ -595,7 +647,24 @@ public function rtgodam_before_thumbnail_store( $media_id = '', $post_request = return; } + /** + * Fires before this listener's own postmeta delete. + * + * 'rtgodam_before_thumbnail_store' is a public, third-party-triggerable + * extension point, not a private implementation detail — any code that + * fires it directly (a third-party plugin, WP-CLI, or a future GoDAM + * code path) would otherwise run this delete completely unwrapped. + * Wrapped here defensively rather than relying on + * add_media_thumbnails()'s own before/after pair to always be the one + * true caller. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + delete_post_meta( $media_id, 'rtgodam_media_thumbnails' ); + + do_action( 'rtgodam_after_attachment_lookup' ); } /** @@ -609,6 +678,21 @@ public function rtgodam_before_transcoded_media_store( $media_id = '', $transcod return; } + /** + * Fires before this listener's own postmeta read/delete. + * + * 'rtgodam_before_transcoded_media_store' is a public, + * third-party-triggerable extension point, not a private + * implementation detail — any code that fires it directly (a + * third-party plugin, WP-CLI, or a future GoDAM code path) would + * otherwise run this read/delete completely unwrapped. Wrapped here + * defensively rather than relying on add_transcoded_files()'s own + * before/after pair to always be the one true caller. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $current_files = get_post_meta( $media_id, 'rtgodam_media_transcoded_files', true ); if ( ! empty( $current_files ) && is_array( $current_files ) ) { @@ -619,6 +703,8 @@ public function rtgodam_before_transcoded_media_store( $media_id = '', $transcod } } delete_post_meta( $media_id, 'rtgodam_media_transcoded_files' ); + + do_action( 'rtgodam_after_attachment_lookup' ); } /** @@ -631,34 +717,55 @@ public function transcoded_thumbnails_added( $media_id = '' ) { return; } - $current_thumbnail = get_post_meta( $media_id, 'rtgodam_media_video_thumbnail', true ); - $custom_thumbnails = get_post_meta( $media_id, 'rtgodam_custom_media_thumbnails', true ); - $custom_thumbnails = is_array( $custom_thumbnails ) ? $custom_thumbnails : array(); - - // If the current selected thumbnail is one of the custom uploaded thumbnails, do not overwrite it. - if ( ! empty( $current_thumbnail ) && in_array( $current_thumbnail, $custom_thumbnails, true ) ) { - return; - } + /** + * Fires before this listener's own postmeta reads/writes. + * + * 'rtgodam_transcoded_thumbnails_added' is a public, + * third-party-triggerable extension point, not a private + * implementation detail — any code that fires it directly (a + * third-party plugin, WP-CLI, or a future GoDAM code path) would + * otherwise run this method's postmeta access completely unwrapped. + * Wrapped here defensively — in a try/finally, since this method has + * its own early return below — rather than relying on + * add_media_thumbnails()'s own before/after pair to always be the one + * true caller. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + + try { + $current_thumbnail = get_post_meta( $media_id, 'rtgodam_media_video_thumbnail', true ); + $custom_thumbnails = get_post_meta( $media_id, 'rtgodam_custom_media_thumbnails', true ); + $custom_thumbnails = is_array( $custom_thumbnails ) ? $custom_thumbnails : array(); + + // If the current selected thumbnail is one of the custom uploaded thumbnails, do not overwrite it. + if ( ! empty( $current_thumbnail ) && in_array( $current_thumbnail, $custom_thumbnails, true ) ) { + return; + } - $new_thumbs = get_post_meta( $media_id, 'rtgodam_media_thumbnails', true ); - $new_thumbs = is_array( $new_thumbs ) ? $new_thumbs : array(); + $new_thumbs = get_post_meta( $media_id, 'rtgodam_media_thumbnails', true ); + $new_thumbs = is_array( $new_thumbs ) ? $new_thumbs : array(); - if ( ! empty( $new_thumbs ) ) { - update_post_meta( $media_id, 'rtgodam_media_video_thumbnail', $new_thumbs[0] ); - } + if ( ! empty( $new_thumbs ) ) { + update_post_meta( $media_id, 'rtgodam_media_video_thumbnail', $new_thumbs[0] ); + } - $primary_remote_thumbnail_url = get_post_meta( $media_id, 'rtgodam_media_video_thumbnail', true ); + $primary_remote_thumbnail_url = get_post_meta( $media_id, 'rtgodam_media_video_thumbnail', true ); - if ( ! empty( $primary_remote_thumbnail_url ) ) { - do_action( 'rtgodam_primary_remote_thumbnail_set', $media_id, $primary_remote_thumbnail_url ); + if ( ! empty( $primary_remote_thumbnail_url ) ) { + do_action( 'rtgodam_primary_remote_thumbnail_set', $media_id, $primary_remote_thumbnail_url ); - // Sync placeholder thumbnail for the newly set primary thumbnail. - $godam_placeholder_map = get_post_meta( $media_id, 'rtgodam_media_placeholder_thumbnails', true ); - if ( is_array( $godam_placeholder_map ) && isset( $godam_placeholder_map[ $primary_remote_thumbnail_url ] ) ) { - update_post_meta( $media_id, 'rtgodam_media_video_placeholder_thumbnail', $godam_placeholder_map[ $primary_remote_thumbnail_url ] ); - } else { - delete_post_meta( $media_id, 'rtgodam_media_video_placeholder_thumbnail' ); + // Sync placeholder thumbnail for the newly set primary thumbnail. + $godam_placeholder_map = get_post_meta( $media_id, 'rtgodam_media_placeholder_thumbnails', true ); + if ( is_array( $godam_placeholder_map ) && isset( $godam_placeholder_map[ $primary_remote_thumbnail_url ] ) ) { + update_post_meta( $media_id, 'rtgodam_media_video_placeholder_thumbnail', $godam_placeholder_map[ $primary_remote_thumbnail_url ] ); + } else { + delete_post_meta( $media_id, 'rtgodam_media_video_placeholder_thumbnail' ); + } } + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } } @@ -674,6 +781,20 @@ public function rtgodam_handle_callback_finished( $attachment_id = '', $job_id = return; } + /** + * Fires before reading/clearing this attachment's retranscoding-sent + * flag, so integrations that centralize media on another site can + * switch context first. Unlike this class's other transcoder-pipeline + * hook handlers, the 'rtgodam_handle_callback_finished' action fires + * unconditionally at the end of handle_callback() + * (admin/class-rtgodam-transcoder-rest-routes.php), outside of any of + * that method's own per-branch before/after pairs, so this postmeta + * access has no coverage from its caller. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $is_retranscoding_job = get_post_meta( $attachment_id, 'rtgodam_retranscoding_sent', true ); if ( $is_retranscoding_job ) { @@ -681,6 +802,8 @@ public function rtgodam_handle_callback_finished( $attachment_id = '', $job_id = delete_post_meta( $attachment_id, 'rtgodam_retranscoding_sent' ); } + + do_action( 'rtgodam_after_attachment_lookup' ); } /** diff --git a/admin/class-rtgodam-transcoder-handler.php b/admin/class-rtgodam-transcoder-handler.php index e1ddbf1702..7ad06a3cb1 100644 --- a/admin/class-rtgodam-transcoder-handler.php +++ b/admin/class-rtgodam-transcoder-handler.php @@ -210,19 +210,33 @@ public function __construct( $no_init = false ) { * @param int $attachment_id ID of attachment. */ public function send_transcoding_request( $attachment_id ) { + /** + * Fires before reading this attachment's metadata and dispatching + * its transcoding request, so integrations that centralize media on + * another site can switch context first. Hooked to `add_attachment`, + * which can fire synchronously from inside an already-open bracket + * (e.g. create_virtual_attachment()) — this method's own attachment + * reads, and wp_media_transcoding()'s internal ones, both need it. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $metadata = wp_get_attachment_metadata( $attachment_id ); - $metadata = wp_get_attachment_metadata( $attachment_id ); + $mime_type = get_post_mime_type( $attachment_id ); - $mime_type = get_post_mime_type( $attachment_id ); + if ( empty( $metadata ) ) { + $metadata = array( 'mime_type' => $mime_type ); + } elseif ( empty( $metadata['mime_type'] ) ) { + $metadata['mime_type'] = $mime_type; + } - if ( empty( $metadata ) ) { - $metadata = array( 'mime_type' => $mime_type ); - } elseif ( empty( $metadata['mime_type'] ) ) { - $metadata['mime_type'] = $mime_type; + // Send the transcoding request. + $this->wp_media_transcoding( $metadata, $attachment_id ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } - - // Send the transcoding request. - $this->wp_media_transcoding( $metadata, $attachment_id ); } /** @@ -422,20 +436,12 @@ public function wp_media_transcoding( $wp_metadata, $attachment_id, $autoformat } } - if ( ! defined( 'RTGODAM_TRANSCODER_CALLBACK_URL' ) || empty( RTGODAM_TRANSCODER_CALLBACK_URL ) ) { - include_once RTGODAM_PATH . 'admin/class-rtgodam-transcoder-rest-routes.php'; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingCustomConstant - define( 'RTGODAM_TRANSCODER_CALLBACK_URL', RTGODAM_Transcoder_Rest_Routes::get_callback_url() ); - } - - $callback_url = RTGODAM_TRANSCODER_CALLBACK_URL; - - /** - * Manually setting the rest api endpoint, we can refactor that later to use similar functionality as callback_url. - */ - $status_callback_url = get_rest_url( get_current_blog_id(), '/godam/v1/transcoding/transcoding-status' ); + include_once RTGODAM_PATH . 'admin/class-rtgodam-transcoder-rest-routes.php'; + $callback_url = RTGODAM_Transcoder_Rest_Routes::get_callback_url(); + $status_callback_url = RTGODAM_Transcoder_Rest_Routes::get_callback_url( 'status' ); // Get attachment author information. - $attachment_author_id = get_post_field( 'post_author', $attachment_id ); + $attachment_author_id = get_post_field( 'post_author', $attachment_id ); // godam-coverage-ignore -- wp_media_transcoding(): covered transitively — every real call site (send_transcoding_request() here, Retranscode_Failed_Media::retranscode_failed_media(), and class-transcoding.php's retranscode_media() via retranscode_media_centralized()) already wraps the call in its own before/after pair. $attachment_author = get_user_by( 'id', $attachment_author_id ); $site_url = get_site_url(); @@ -477,7 +483,7 @@ public function wp_media_transcoding( $wp_metadata, $attachment_id, $autoformat 'video_quality' => $rtgodam_video_compress_quality, 'mime_type' => $metadata['mime_type'], 'title' => sanitize_text_field( get_the_title( $attachment_id ) ), - 'description' => sanitize_textarea_field( (string) get_post_field( 'post_content', $attachment_id ) ), + 'description' => sanitize_textarea_field( (string) get_post_field( 'post_content', $attachment_id ) ), // godam-coverage-ignore -- wp_media_transcoding(): covered transitively — every real call site (send_transcoding_request() here, Retranscode_Failed_Media::retranscode_failed_media(), and class-transcoding.php's retranscode_media() via retranscode_media_centralized()) already wraps the call in its own before/after pair. 'wp_author_email' => apply_filters( 'godam_author_email_to_send', $author_email, $attachment_id ), 'wp_site' => $site_url, 'wp_author_first_name' => apply_filters( 'godam_author_first_name_to_send', $author_first_name, $attachment_id ), @@ -797,17 +803,17 @@ public function add_media_thumbnails( $post_array ) { } // rtMedia support. - update_post_meta( $post_id, '_rt_media_source', $post_thumbs_array['job_for'] ); - update_post_meta( $post_id, '_rt_media_thumbnails', $thumbnail_urls ); + update_post_meta( $post_id, '_rt_media_source', $post_thumbs_array['job_for'] ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. + update_post_meta( $post_id, '_rt_media_thumbnails', $thumbnail_urls ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. - update_post_meta( $post_id, 'rtgodam_media_source', $post_thumbs_array['job_for'] ); - update_post_meta( $post_id, 'rtgodam_media_thumbnails', $thumbnail_urls ); + update_post_meta( $post_id, 'rtgodam_media_source', $post_thumbs_array['job_for'] ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. + update_post_meta( $post_id, 'rtgodam_media_thumbnails', $thumbnail_urls ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. // Store thumbnail → placeholder mapping, or clear stale meta when no valid placeholders. if ( ! empty( $placeholder_map ) ) { - update_post_meta( $post_id, 'rtgodam_media_placeholder_thumbnails', $placeholder_map ); + update_post_meta( $post_id, 'rtgodam_media_placeholder_thumbnails', $placeholder_map ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. } else { - delete_post_meta( $post_id, 'rtgodam_media_placeholder_thumbnails' ); + delete_post_meta( $post_id, 'rtgodam_media_placeholder_thumbnails' ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. } do_action( 'rtgodam_transcoded_thumbnails_added', $post_id ); @@ -815,25 +821,25 @@ public function add_media_thumbnails( $post_array ) { if ( $first_thumbnail_url ) { // rtMedia support. - update_post_meta( $post_id, '_rt_media_video_thumbnail', $first_thumbnail_url ); + update_post_meta( $post_id, '_rt_media_video_thumbnail', $first_thumbnail_url ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. if ( class_exists( 'RTMediaModel' ) && ! empty( $media_id ) ) { $model->update( array( 'cover_art' => $first_thumbnail_url ), array( 'media_id' => $post_id ) ); update_activity_after_thumb_set( $media_id ); } - $current_thumbnail = get_post_meta( $post_id, 'rtgodam_media_video_thumbnail', true ); - $custom_thumbnails = get_post_meta( $post_id, 'rtgodam_custom_media_thumbnails', true ); + $current_thumbnail = get_post_meta( $post_id, 'rtgodam_media_video_thumbnail', true ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. + $custom_thumbnails = get_post_meta( $post_id, 'rtgodam_custom_media_thumbnails', true ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. $custom_thumbnails = is_array( $custom_thumbnails ) ? $custom_thumbnails : array(); // If the current selected thumbnail is NOT one of the custom uploaded thumbnails, overwrite it. if ( empty( $current_thumbnail ) || ! in_array( $current_thumbnail, $custom_thumbnails, true ) ) { - update_post_meta( $post_id, 'rtgodam_media_video_thumbnail', $first_thumbnail_url ); + update_post_meta( $post_id, 'rtgodam_media_video_thumbnail', $first_thumbnail_url ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. // Sync placeholder for the newly set primary thumbnail using the verified map. if ( isset( $placeholder_map[ $first_thumbnail_url ] ) ) { - update_post_meta( $post_id, 'rtgodam_media_video_placeholder_thumbnail', $placeholder_map[ $first_thumbnail_url ] ); + update_post_meta( $post_id, 'rtgodam_media_video_placeholder_thumbnail', $placeholder_map[ $first_thumbnail_url ] ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. } else { - delete_post_meta( $post_id, 'rtgodam_media_video_placeholder_thumbnail' ); + delete_post_meta( $post_id, 'rtgodam_media_video_placeholder_thumbnail' ); // godam-coverage-ignore -- add_media_thumbnails(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. } } @@ -930,14 +936,14 @@ public function add_transcoded_files( $file_post_array, $attachment_id, $job_for $mime_type = get_post_mime_type( $attachment_id ); if ( strpos( $mime_type, 'audio' ) !== false ) { - wp_update_post( + wp_update_post( // godam-coverage-ignore -- add_transcoded_files(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. array( 'ID' => $attachment_id, 'post_mime_type' => 'audio/mp3', ) ); } else { - wp_update_post( + wp_update_post( // godam-coverage-ignore -- add_transcoded_files(): covered transitively — sole caller (handle_wp_media_transcoding_callback) already runs inside its own caller's before/after pair. array( 'ID' => $attachment_id, 'post_mime_type' => 'video/mp4', @@ -973,7 +979,7 @@ public function get_post_id_by_meta_key_and_value( $key, $value ) { $meta = wp_cache_get( $cache_key, 'godam' ); if ( empty( $meta ) ) { - $meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s", $key, $value ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery + $meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s", $key, $value ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, godam-coverage-ignore -- get_post_id_by_meta_key_and_value(): covered transitively — every real call site (rest-routes.php, including via handle_wp_media_transcoding_callback, and class-video-migration.php) already runs inside its own before/after pair. wp_cache_set( $cache_key, $meta, 'godam', HOUR_IN_SECONDS ); } diff --git a/admin/class-rtgodam-transcoder-rest-routes.php b/admin/class-rtgodam-transcoder-rest-routes.php index c9b86df5f8..138c364f91 100644 --- a/admin/class-rtgodam-transcoder-rest-routes.php +++ b/admin/class-rtgodam-transcoder-rest-routes.php @@ -37,10 +37,6 @@ class RTGODAM_Transcoder_Rest_Routes extends WP_REST_Controller { */ public function __construct() { $this->rtgodam_transcoder_handler = new RTGODAM_Transcoder_Handler( true ); - - if ( ! defined( 'RTGODAM_TRANSCODER_CALLBACK_URL' ) ) { - define( 'RTGODAM_TRANSCODER_CALLBACK_URL', self::get_callback_url() ); - } } /** @@ -198,12 +194,38 @@ public function register_routes() { } /** - * Return the callback URL for the transcoder. + * REST paths (relative to this namespace, each with a leading slash) that + * get_callback_url() ever builds a URL for — keyed by a short, + * referenceable name. The one canonical list backing that accessor, so + * any other code that needs the *complete* set of callback paths (e.g. an + * integration wrapping every centralized-media callback in a site switch) + * has one place to read it from, instead of a hand-maintained shadow list + * that can silently miss a newly added one. + * + * @var array + */ + const CALLBACK_PATHS = array( + 'transcoder' => '/transcoder-callback', + 'status' => '/transcoding/transcoding-status', + ); + + /** + * Return a transcoder callback URL for the *current* site. * + * The single, authoritative accessor for every callback URL this class + * constructs — call this directly at the point of use rather than caching + * the result in a define()'d constant. A constant, once defined, can't be + * recomputed if site context (e.g. a multisite switch_to_blog()) changes + * later in the same request; this way every caller always gets the URL for + * whichever site is current when it actually asks. + * + * @param string $type One of the keys in self::CALLBACK_PATHS. Defaults to + * 'transcoder', the original/most common callback. * @return string */ - public static function get_callback_url() { - return rest_url( self::$namespace_prefix . '/transcoder-callback' ); + public static function get_callback_url( $type = 'transcoder' ) { + $path = isset( self::CALLBACK_PATHS[ $type ] ) ? self::CALLBACK_PATHS[ $type ] : self::CALLBACK_PATHS['transcoder']; + return rest_url( self::$namespace_prefix . $path ); } /** @@ -265,12 +287,25 @@ public function handle_callback( WP_REST_Request $request ) { // information in post meta so the site admin can see what went wrong. if ( ! empty( $job_id ) && ! empty( $file_status ) && ( 'error' === $file_status ) ) { if ( 'wp-media' === $job_for ) { - $failed_id = $this->rtgodam_transcoder_handler->get_post_id_by_meta_key_and_value( 'rtgodam_transcoding_job_id', $job_id ); - if ( ! empty( $failed_id ) && is_numeric( $failed_id ) ) { - update_post_meta( $failed_id, 'rtgodam_transcoding_status', 'failed' ); - // Use rtgodam_transcoding_error_msg so the REST status endpoint can surface it. - if ( ! empty( $error_msg ) ) { - update_post_meta( $failed_id, 'rtgodam_transcoding_error_msg', sanitize_textarea_field( $error_msg ) ); + /** + * Fires before resolving/mutating attachment data for a + * failed transcoding job, so integrations that centralize + * media on another site can switch context first. The + * job-ID lookup itself needs this too — it's a direct + * $wpdb->postmeta query, just as site-scoped as + * get_post_meta(). + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $failed_id = $this->rtgodam_transcoder_handler->get_post_id_by_meta_key_and_value( 'rtgodam_transcoding_job_id', $job_id ); + if ( ! empty( $failed_id ) && is_numeric( $failed_id ) ) { + update_post_meta( $failed_id, 'rtgodam_transcoding_status', 'failed' ); + // Use rtgodam_transcoding_error_msg so the REST status endpoint can surface it. + if ( ! empty( $error_msg ) ) { + update_post_meta( $failed_id, 'rtgodam_transcoding_error_msg', sanitize_textarea_field( $error_msg ) ); + } } /* @@ -282,6 +317,8 @@ public function handle_callback( WP_REST_Request $request ) { if ( ! empty( $error_code ) ) { update_post_meta( $failed_id, 'rtgodam_transcoding_error_code', sanitize_text_field( $error_code ) ); } + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } } return new WP_REST_Response( @@ -297,130 +334,30 @@ public function handle_callback( WP_REST_Request $request ) { if ( isset( $job_for ) && ( 'wp-media' === $job_for ) ) { if ( isset( $job_id ) ) { - $has_thumbs = isset( $thumbnail ) ? true : false; - - $id = $this->rtgodam_transcoder_handler->get_post_id_by_meta_key_and_value( 'rtgodam_transcoding_job_id', $job_id ); - - if ( ! empty( $id ) && is_numeric( $id ) ) { - $attachment_id = $id; - $post_array = $request->get_params(); - $post_array['post_id'] = $attachment_id; - - // If thumbnail array is empty but thumbnail_url is provided, use it. - if ( empty( $post_array['thumbnail'] ) && ! empty( $post_array['thumbnail_url'] ) ) { - $post_array['thumbnail'] = array( - $post_array['thumbnail_url'], - ); - $has_thumbs = true; - } - - if ( $has_thumbs && ! empty( $post_array['thumbnail'] ) ) { - $thumbnail = $this->rtgodam_transcoder_handler->add_media_thumbnails( $post_array ); - } - - if ( isset( $format ) && 'thumbnail' === $format ) { - return new WP_REST_Response( __( 'Thumbnail created successfully.', 'godam' ), 200 ); - } - - if ( ! empty( $post_array['files'] ) ) { - if ( ! empty( $post_array['files']['mpd'] ) ) { - update_post_meta( $attachment_id, 'rtgodam_transcoded_url', $post_array['download_url'] ); - - delete_post_meta( $attachment_id, 'rtgodam_retranscoding_sent' ); - - $latest_attachment = get_option( 'rtgodam_new_attachment', false ); - - // Save hls url as well. - if ( isset( $post_array['hls_path'] ) && ! empty( trim( $post_array['hls_path'] ) ) ) { - update_post_meta( $attachment_id, 'rtgodam_hls_transcoded_url', sanitize_url( $post_array['hls_path'] ) ); - } - - if ( ! empty( $latest_attachment ) && $latest_attachment['attachment_id'] === $attachment_id ) { - $latest_attachment['transcoding_status'] = 'success'; - update_option( 'rtgodam_new_attachment', $latest_attachment, true ); - } - } else { - $this->rtgodam_transcoder_handler->add_transcoded_files( $post_array['files'], $attachment_id, $job_for ); - } - } - - /* - * Documents. `pdf` is a file that needed no conversion; `document` is an - * Office / OpenDocument / text file that GoDAM Central rendered to a preview - * PDF. For both, `download_url` is the file the author uploaded, on the CDN. - * - * The two URLs are NOT interchangeable for a `document`: only the preview may - * be rendered, and only the original may be offered as a download. Somebody - * who uploads report.xlsx and downloads preview.pdf will think something broke. - */ - if ( in_array( $job_type, array( 'pdf', 'document' ), true ) && ! empty( $post_array['download_url'] ) ) { - update_post_meta( $attachment_id, 'rtgodam_transcoded_url', esc_url_raw( $post_array['download_url'] ) ); - } - - if ( 'document' === $job_type ) { - if ( ! empty( $post_array['preview_pdf_url'] ) ) { - update_post_meta( $attachment_id, 'rtgodam_preview_pdf_url', esc_url_raw( $post_array['preview_pdf_url'] ) ); - } else { - /* - * No preview: the document is password protected, so Central stored it - * as-is and generated nothing to render. Deleting rather than skipping - * matters — a retranscode or in-place replace reuses the same job row, - * and leaving the key alone would keep serving the *previous* render's - * preview for a file that no longer has one. - */ - delete_post_meta( $attachment_id, 'rtgodam_preview_pdf_url' ); - } - } elseif ( 'pdf' === $job_type && ! empty( $post_array['download_url'] ) ) { - // A PDF is its own preview, so both keys point at the same file. Storing it - // here as well means every reader has a single key to consult. - update_post_meta( $attachment_id, 'rtgodam_preview_pdf_url', esc_url_raw( $post_array['download_url'] ) ); - } + /** + * Fires before resolving/mutating attachment data for this + * transcoding callback, so integrations that centralize + * media on another site can switch context first. The + * job-ID lookup inside handle_wp_media_transcoding_callback() + * needs this too — it's a direct $wpdb->postmeta query, just + * as site-scoped as get_post_meta(), even though it's + * invisible to a checker that only looks for named WP API + * calls. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $wp_media_result = $this->handle_wp_media_transcoding_callback( $request, $job_id, $job_for, $job_type, $thumbnail, $format ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } - if ( 'image' === $job_type && isset( $post_array['download_url'] ) && ! empty( $post_array['download_url'] ) ) { - // Setting the transcoded Image URL. - update_post_meta( $attachment_id, 'rtgodam_transcoded_url', esc_url_raw( $post_array['download_url'] ) ); - - // Request CDN image subsizes and store them in dedicated meta. - // This is a secondary async operation; a failure here must not cause a 500 response - // to GoDAM Central, which would mark the already-completed transcoding job as failed. - $subsize_result = \RTGODAM\Inc\REST_API\Media_Library::get_instance()->request_image_subsizes_for_attachment( $job_id, $attachment_id ); - - if ( is_wp_error( $subsize_result ) || empty( $subsize_result ) ) { - // translators: %s is replaced with the attachment ID for which subsizes generation failed. - error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging the error for debugging purposes. - // translators: %s is replaced with the attachment ID for which subsizes generation failed. - sprintf( __( 'GoDAM: Failed to request image subsizes for attachment ID %s. The transcoded image URL has been saved; subsizes may be retried separately.', 'godam' ), $attachment_id ) - ); - - $this->rtgodam_transcoder_handler->update_usage( $this->rtgodam_transcoder_handler->api_key ); - - return new WP_REST_Response( - array( - 'success' => false, - 'message' => __( 'Transcoded image URL saved, but failed to request subsizes.', 'godam' ), - ), - 200 - ); - } - } - } else { - // The attachment no longer exists (deleted between queuing and callback). - // Log for visibility but return 200 so GoDAM Central does not retry or mark - // the job as failed due to an error in the callback itself. - error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging the error for debugging purposes. - sprintf( 'GoDAM: Transcoder callback received for job %s but the corresponding attachment no longer exists. It may have been deleted.', sanitize_text_field( $job_id ) ) - ); - $this->rtgodam_transcoder_handler->update_usage( $this->rtgodam_transcoder_handler->api_key ); - return new WP_REST_Response( - array( - 'success' => false, - 'message' => __( 'Attachment not found; it may have been deleted.', 'godam' ), - ), - 200 - ); + if ( $wp_media_result instanceof WP_REST_Response ) { + return $wp_media_result; } - $this->rtgodam_transcoder_handler->update_usage( $this->rtgodam_transcoder_handler->api_key ); + $attachment_id = $wp_media_result; } } @@ -457,7 +394,7 @@ public function handle_callback( WP_REST_Request $request ) { if ( ! empty( $entry_data ) && ! empty( $entry_data['form_id'] ) ) { $form_id = $entry_data['form_id']; - update_post_meta( + update_post_meta( // godam-coverage-ignore -- handle_callback(): $form_id is a SureForms form ID used as a postmeta key (not an attachment ID) to stash the transcoded URL. $form_id, 'rtgodam_transcoded_url_sureforms_' . $form_id . '_' . $entry_id, $post_array['download_url'] @@ -525,6 +462,152 @@ public function handle_callback( WP_REST_Request $request ) { ); } + /** + * Does the actual work for handle_callback()'s 'wp-media' job_for branch. + * Always runs with the centralized media site active — see the + * before/after pair in the caller. + * + * @since 2.2.0 + * + * @param \WP_REST_Request $request The incoming request. + * @param string $job_id The transcoding job ID. + * @param string $job_for The 'job_for' request param — always 'wp-media' here, passed through unchanged to add_transcoded_files() for parity with the original inline code. + * @param string $job_type The 'job_type' request param (e.g. 'pdf', 'image'). + * @param mixed $thumbnail The 'thumbnail' request param. + * @param string $format The 'format' request param. + * @return WP_REST_Response|string|int A response to return immediately, or the resolved attachment ID (possibly empty) for the caller to continue with. + */ + private function handle_wp_media_transcoding_callback( \WP_REST_Request $request, $job_id, $job_for, $job_type, $thumbnail, $format ) { + $attachment_id = ''; + $has_thumbs = isset( $thumbnail ) ? true : false; + + $id = $this->rtgodam_transcoder_handler->get_post_id_by_meta_key_and_value( 'rtgodam_transcoding_job_id', $job_id ); + + if ( ! empty( $id ) && is_numeric( $id ) ) { + $attachment_id = $id; + $post_array = $request->get_params(); + $post_array['post_id'] = $attachment_id; + + // If thumbnail array is empty but thumbnail_url is provided, use it. + if ( empty( $post_array['thumbnail'] ) && ! empty( $post_array['thumbnail_url'] ) ) { + $post_array['thumbnail'] = array( + $post_array['thumbnail_url'], + ); + $has_thumbs = true; + } + + if ( $has_thumbs && ! empty( $post_array['thumbnail'] ) ) { + $thumbnail = $this->rtgodam_transcoder_handler->add_media_thumbnails( $post_array ); + } + + if ( isset( $format ) && 'thumbnail' === $format ) { + return new WP_REST_Response( __( 'Thumbnail created successfully.', 'godam' ), 200 ); + } + + if ( ! empty( $post_array['files'] ) ) { + if ( ! empty( $post_array['files']['mpd'] ) ) { + update_post_meta( $attachment_id, 'rtgodam_transcoded_url', $post_array['download_url'] ); // godam-coverage-ignore -- handle_wp_media_transcoding_callback(): covered transitively — caller (handle_callback) wraps the entire call in try/finally. + + delete_post_meta( $attachment_id, 'rtgodam_retranscoding_sent' ); // godam-coverage-ignore -- handle_wp_media_transcoding_callback(): covered transitively — caller (handle_callback) wraps the entire call in try/finally. + + $latest_attachment = get_option( 'rtgodam_new_attachment', false ); + + // Save hls url as well. + if ( isset( $post_array['hls_path'] ) && ! empty( trim( $post_array['hls_path'] ) ) ) { + update_post_meta( $attachment_id, 'rtgodam_hls_transcoded_url', sanitize_url( $post_array['hls_path'] ) ); // godam-coverage-ignore -- handle_wp_media_transcoding_callback(): covered transitively — caller (handle_callback) wraps the entire call in try/finally. + } + + if ( ! empty( $latest_attachment ) && $latest_attachment['attachment_id'] === $attachment_id ) { + $latest_attachment['transcoding_status'] = 'success'; + update_option( 'rtgodam_new_attachment', $latest_attachment, true ); + } + } else { + $this->rtgodam_transcoder_handler->add_transcoded_files( $post_array['files'], $attachment_id, $job_for ); + } + } + + if ( in_array( $job_type, array( 'pdf', 'document' ), true ) && isset( $post_array['download_url'] ) && ! empty( $post_array['download_url'] ) ) { + // Setting the transcoded PDF/document URL. + update_post_meta( $attachment_id, 'rtgodam_transcoded_url', esc_url_raw( $post_array['download_url'] ) ); // godam-coverage-ignore -- handle_wp_media_transcoding_callback(): covered transitively — caller (handle_callback) wraps the entire call in try/finally. + } + + /* + * Documents. `pdf` is a file that needed no conversion; `document` is an + * Office / OpenDocument / text file that GoDAM Central rendered to a preview + * PDF. For both, `download_url` is the file the author uploaded, on the CDN. + * + * The two URLs are NOT interchangeable for a `document`: only the preview may + * be rendered, and only the original may be offered as a download. Somebody + * who uploads report.xlsx and downloads preview.pdf will think something broke. + */ + if ( 'document' === $job_type ) { + if ( ! empty( $post_array['preview_pdf_url'] ) ) { + update_post_meta( $attachment_id, 'rtgodam_preview_pdf_url', esc_url_raw( $post_array['preview_pdf_url'] ) ); // godam-coverage-ignore -- handle_wp_media_transcoding_callback(): covered transitively — caller (handle_callback) wraps the entire call in try/finally. + } else { + /* + * No preview: the document is password protected, so Central stored it + * as-is and generated nothing to render. Deleting rather than skipping + * matters — a retranscode or in-place replace reuses the same job row, + * and leaving the key alone would keep serving the *previous* render's + * preview for a file that no longer has one. + */ + delete_post_meta( $attachment_id, 'rtgodam_preview_pdf_url' ); // godam-coverage-ignore -- handle_wp_media_transcoding_callback(): covered transitively — caller (handle_callback) wraps the entire call in try/finally. + } + } elseif ( 'pdf' === $job_type && ! empty( $post_array['download_url'] ) ) { + // A PDF is its own preview, so both keys point at the same file. Storing it + // here as well means every reader has a single key to consult. + update_post_meta( $attachment_id, 'rtgodam_preview_pdf_url', esc_url_raw( $post_array['download_url'] ) ); // godam-coverage-ignore -- handle_wp_media_transcoding_callback(): covered transitively — caller (handle_callback) wraps the entire call in try/finally. + } + + if ( 'image' === $job_type && isset( $post_array['download_url'] ) && ! empty( $post_array['download_url'] ) ) { + // Setting the transcoded Image URL. + update_post_meta( $attachment_id, 'rtgodam_transcoded_url', esc_url_raw( $post_array['download_url'] ) ); // godam-coverage-ignore -- handle_wp_media_transcoding_callback(): covered transitively — caller (handle_callback) wraps the entire call in try/finally. + + // Request CDN image subsizes and store them in dedicated meta. + // This is a secondary async operation; a failure here must not cause a 500 response + // to GoDAM Central, which would mark the already-completed transcoding job as failed. + $subsize_result = \RTGODAM\Inc\REST_API\Media_Library::get_instance()->request_image_subsizes_for_attachment( $job_id, $attachment_id ); + + if ( is_wp_error( $subsize_result ) || empty( $subsize_result ) ) { + // translators: %s is replaced with the attachment ID for which subsizes generation failed. + error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging the error for debugging purposes. + // translators: %s is replaced with the attachment ID for which subsizes generation failed. + sprintf( __( 'GoDAM: Failed to request image subsizes for attachment ID %s. The transcoded image URL has been saved; subsizes may be retried separately.', 'godam' ), $attachment_id ) + ); + + $this->rtgodam_transcoder_handler->update_usage( $this->rtgodam_transcoder_handler->api_key ); + + return new WP_REST_Response( + array( + 'success' => false, + 'message' => __( 'Transcoded image URL saved, but failed to request subsizes.', 'godam' ), + ), + 200 + ); + } + } + } else { + // The attachment no longer exists (deleted between queuing and callback). + // Log for visibility but return 200 so GoDAM Central does not retry or mark + // the job as failed due to an error in the callback itself. + error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging the error for debugging purposes. + sprintf( 'GoDAM: Transcoder callback received for job %s but the corresponding attachment no longer exists. It may have been deleted.', sanitize_text_field( $job_id ) ) + ); + $this->rtgodam_transcoder_handler->update_usage( $this->rtgodam_transcoder_handler->api_key ); + return new WP_REST_Response( + array( + 'success' => false, + 'message' => __( 'Attachment not found; it may have been deleted.', 'godam' ), + ), + 200 + ); + } + + $this->rtgodam_transcoder_handler->update_usage( $this->rtgodam_transcoder_handler->api_key ); + + return $attachment_id; + } + /** * Function to handle the transcription callback request. * @@ -552,36 +635,50 @@ public function handle_transcription_callback( WP_REST_Request $request ) { return new WP_Error( 'rtgodam_transcription_error', __( 'Transcript path is required.', 'godam' ), array( 'status' => 400 ) ); } - // Find video attachment by job ID. - $attachment_id = $this->rtgodam_transcoder_handler->get_post_id_by_meta_key_and_value( 'rtgodam_transcoding_job_id', $job_id ); + /** + * Fires before resolving/mutating attachment data for this + * transcription callback, so integrations that centralize media on + * another site can switch context first. The job-ID lookup itself + * needs this too — it's a direct $wpdb->postmeta query, just as + * site-scoped as get_post_meta(). + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + // Find video attachment by job ID. + $attachment_id = $this->rtgodam_transcoder_handler->get_post_id_by_meta_key_and_value( 'rtgodam_transcoding_job_id', $job_id ); - if ( empty( $attachment_id ) || ! is_numeric( $attachment_id ) ) { - return new WP_Error( 'rtgodam_transcription_error', __( 'Video attachment not found for the provided job ID.', 'godam' ), array( 'status' => 404 ) ); - } + if ( empty( $attachment_id ) || ! is_numeric( $attachment_id ) ) { + return new WP_Error( 'rtgodam_transcription_error', __( 'Video attachment not found for the provided job ID.', 'godam' ), array( 'status' => 404 ) ); + } - // If status is "Transcribed", save the transcript path. - if ( 'Transcribed' === $transcription_status ) { - // Save transcript path as post meta. - // The transcript_path parameter is already sanitized by the REST API framework via esc_url_raw sanitize_callback. - update_post_meta( $attachment_id, 'rtgodam_transcript_path', $transcript_path ); + // If status is "Transcribed", save the transcript path. + if ( 'Transcribed' === $transcription_status ) { + // Save transcript path as post meta. + // The transcript_path parameter is already sanitized by the REST API framework via esc_url_raw sanitize_callback. + update_post_meta( $attachment_id, 'rtgodam_transcript_path', $transcript_path ); + + return new WP_REST_Response( + array( + 'success' => true, + 'message' => __( 'Transcript path saved successfully.', 'godam' ), + ), + 200 + ); + } + // Return success response even if status is not "Transcribed" (e.g., "Processing", "Failed", etc.). return new WP_REST_Response( array( 'success' => true, - 'message' => __( 'Transcript path saved successfully.', 'godam' ), + 'message' => __( 'Transcription callback received.', 'godam' ), ), 200 ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } - - // Return success response even if status is not "Transcribed" (e.g., "Processing", "Failed", etc.). - return new WP_REST_Response( - array( - 'success' => true, - 'message' => __( 'Transcription callback received.', 'godam' ), - ), - 200 - ); } /** diff --git a/admin/godam-transcoder-actions.php b/admin/godam-transcoder-actions.php index e2b09511f1..063a3a283b 100644 --- a/admin/godam-transcoder-actions.php +++ b/admin/godam-transcoder-actions.php @@ -26,27 +26,39 @@ function rtgodam_add_transcoded_url_field( $form_fields, $post ) { return $form_fields; } + /** + * Fires before reading this attachment's MIME type, document-support + * status, and transcoded-URL/job-ID meta for the attachment edit + * screen, so integrations that centralize media on another site can + * switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + // Check if attachment is of type video. $mime_type = get_post_mime_type( $post->ID ); // The document test goes through the attachment, not the MIME alone: text/plain also // covers .srt/.asc/.c/.h, which are never transcoded and so have no CDN URL to show. + $is_supported_document = rtgodam_is_supported_document_attachment( $post->ID ); + + $transcoded_url = rtgodam_get_transcoded_url_from_attachment( $post->ID ); + $job_id = rtgodam_get_job_id_by_attachment_id( $post->ID ); + + do_action( 'rtgodam_after_attachment_lookup' ); + $is_allowed = ( str_starts_with( $mime_type, 'video/' ) || str_starts_with( $mime_type, 'audio/' ) || str_starts_with( $mime_type, 'image/' ) || - rtgodam_is_supported_document_attachment( $post->ID ) + $is_supported_document ); if ( ! $is_allowed ) { return $form_fields; } - $transcoded_url = rtgodam_get_transcoded_url_from_attachment( $post->ID ); - $job_id = rtgodam_get_job_id_by_attachment_id( $post->ID ); - - $easydam_settings = get_option( 'rtgodam-settings', array() ); - // Determine if the site has a valid API key (i.e., Premium user). $api_key = get_option( 'rtgodam-api-key', '' ); @@ -156,12 +168,25 @@ function rtgodam_save_transcoded_url_field( $post, $attachment ) { } if ( isset( $attachment['transcoded_url'] ) ) { - // Check the user's permissions. - if ( ! current_user_can( 'edit_post', $post['ID'] ) ) { - return $post; + /** + * Fires before checking this attachment's edit capability and + * writing its transcoded-url meta, so integrations that + * centralize media on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + // Check the user's permissions. + if ( ! current_user_can( 'edit_post', $post['ID'] ) ) { + return $post; + } + + // Update the post meta with the new value. + update_post_meta( $post['ID'], 'rtgodam_transcoded_url', esc_url_raw( $attachment['transcoded_url'] ) ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } - // Update the post meta with the new value. - update_post_meta( $post['ID'], 'rtgodam_transcoded_url', esc_url_raw( $attachment['transcoded_url'] ) ); } return $post; @@ -228,7 +253,7 @@ function rtgodam_rtt_set_video_thumbnail( $id ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Legacy hook name kept for backward compatibility. $final_file_url = apply_filters( 'transcoded_file_url', $final_file_url, $attachment_id ); - update_post_meta( $attachment_id, '_rt_media_video_thumbnail', $thumbnail ); + update_post_meta( $attachment_id, '_rt_media_video_thumbnail', $thumbnail ); // godam-coverage-ignore -- rtgodam_rtt_set_video_thumbnail(): dead code — rtMedia is not present in this codebase. } $model = new RTMediaModel(); diff --git a/admin/godam-transcoder-functions.php b/admin/godam-transcoder-functions.php index 95ca15d020..ea5e7d3916 100644 --- a/admin/godam-transcoder-functions.php +++ b/admin/godam-transcoder-functions.php @@ -85,15 +85,27 @@ function rtgodam_clear_api_key_invalid_timestamp() { * @return boolean */ function rtgodam_is_file_being_transcoded( $attachment_id ) { - $job_id = get_post_meta( $attachment_id, 'rtgodam_transcoding_job_id', true ); - if ( ! empty( $job_id ) ) { - $transcoded_files = get_post_meta( $attachment_id, 'rtgodam_transcoded_url', true ); - $transcoded_thumbs = get_post_meta( $attachment_id, 'rtgodam_media_thumbnails', true ); - if ( empty( $transcoded_files ) && empty( $transcoded_thumbs ) ) { - return true; + /** + * Fires before reading this attachment's transcoding-status meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $job_id = get_post_meta( $attachment_id, 'rtgodam_transcoding_job_id', true ); + if ( ! empty( $job_id ) ) { + $transcoded_files = get_post_meta( $attachment_id, 'rtgodam_transcoded_url', true ); + $transcoded_thumbs = get_post_meta( $attachment_id, 'rtgodam_media_thumbnails', true ); + if ( empty( $transcoded_files ) && empty( $transcoded_thumbs ) ) { + return true; + } } + return false; + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } - return false; } /** @@ -110,7 +122,19 @@ function rtgodam_is_file_being_transcoded( $attachment_id ) { * not allow an editing UI. */ function rtgodam_get_edit_post_link( $id = 0, $context = 'display' ) { + /** + * Fires before resolving this post by ID, so integrations that + * centralize media on another site can switch context first. $id can be + * an attachment ID — this function's own docblock documents attachments + * as a supported input alongside posts/pages/revisions, and no caller + * currently wraps this lookup. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $_post = get_post( $id ); + do_action( 'rtgodam_after_attachment_lookup' ); + if ( empty( $_post ) ) { return; } @@ -152,7 +176,16 @@ function rtgodam_get_job_id_by_attachment_id( $attachment_id ) { return 0; } + /** + * Fires before reading this attachment's transcoding job-id meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $job_id = get_post_meta( $attachment_id, 'rtgodam_transcoding_job_id', true ); + do_action( 'rtgodam_after_attachment_lookup' ); return $job_id ? $job_id : 0; } @@ -186,6 +219,15 @@ function rtgodam_delete_related_transcoded_files( $post_id ) { return false; } + /** + * Fires before reading/deleting this (about-to-be-deleted) attachment's + * transcoded-file meta, so integrations that centralize media on + * another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $transcoded_files = get_post_meta( $post_id, 'rtgodam_media_transcoded_files', true ); if ( ! empty( $transcoded_files ) && is_array( $transcoded_files ) ) { @@ -202,6 +244,8 @@ function rtgodam_delete_related_transcoded_files( $post_id ) { rtgodam_delete_transcoded_files( $thumbnails ); } delete_post_meta( $post_id, 'rtgodam_media_thumbnails' ); + + do_action( 'rtgodam_after_attachment_lookup' ); } add_action( 'delete_attachment', 'rtgodam_delete_related_transcoded_files', 99, 1 ); @@ -316,26 +360,38 @@ function rtgodam_add_status_columns_content( $column_name, $post_id ) { return; } - $transcoded_files = get_post_meta( $post_id, 'rtgodam_transcoded_url', true ); - - // Detect virtual media created from GoDAM tab. - $is_virtual = ! empty( get_post_meta( $post_id, '_godam_original_id', true ) ); + /** + * Fires before reading this attachment's transcoding-status meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $transcoded_files = get_post_meta( $post_id, 'rtgodam_transcoded_url', true ); + + // Detect virtual media created from GoDAM tab. + $is_virtual = ! empty( get_post_meta( $post_id, '_godam_original_id', true ) ); + + if ( $is_virtual ) { + ?> +
+
+ <?php esc_attr_e( 'GoDAM Logo', 'godam' ); ?> +
+ +
+ -
-
- <?php esc_attr_e( 'GoDAM Logo', 'godam' ); ?> -
- -
- post_type ) { + return ''; + } - if ( 'attachment' !== $attachment_obj->post_type ) { - return ''; + return get_post_meta( $attachment_id, 'rtgodam_transcoded_url', true ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } - - return get_post_meta( $attachment_id, 'rtgodam_transcoded_url', true ); } /** @@ -795,17 +863,29 @@ function rtgodam_get_hls_transcoded_url_from_attachment( $attachment ) { return ''; } - $attachment_obj = get_post( $attachment_id ); + /** + * Fires before resolving this attachment's post/HLS-transcoded-url + * meta, so integrations that centralize media on another site can + * switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $attachment_obj = get_post( $attachment_id ); - if ( empty( $attachment_obj ) || ! is_a( $attachment_obj, 'WP_Post' ) ) { - return ''; - } + if ( empty( $attachment_obj ) || ! is_a( $attachment_obj, 'WP_Post' ) ) { + return ''; + } - if ( 'attachment' !== $attachment_obj->post_type ) { - return ''; - } + if ( 'attachment' !== $attachment_obj->post_type ) { + return ''; + } - return get_post_meta( $attachment_id, 'rtgodam_hls_transcoded_url', true ); + return get_post_meta( $attachment_id, 'rtgodam_hls_transcoded_url', true ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } } /** @@ -830,17 +910,29 @@ function rtgodam_get_transcoded_status_from_attachment( $attachment ) { return ''; } - $attachment_obj = get_post( $attachment_id ); + /** + * Fires before resolving this attachment's post/transcoding-status + * meta, so integrations that centralize media on another site can + * switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $attachment_obj = get_post( $attachment_id ); - if ( 'attachment' !== $attachment_obj->post_type ) { - return ''; - } + if ( 'attachment' !== $attachment_obj->post_type ) { + return ''; + } - $status = strval( get_post_meta( $attachment_id, 'rtgodam_transcoding_status', true ) ); - $status = function_exists( 'mb_strtolower' ) ? mb_strtolower( $status ) : strtolower( $status ); - $status = empty( trim( $status ) ) ? 'not_started' : $status; + $status = strval( get_post_meta( $attachment_id, 'rtgodam_transcoding_status', true ) ); + $status = function_exists( 'mb_strtolower' ) ? mb_strtolower( $status ) : strtolower( $status ); + $status = empty( trim( $status ) ) ? 'not_started' : $status; - return $status; + return $status; + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } } /** @@ -865,11 +957,23 @@ function rtgodam_get_transcoded_error_message_from_attachment( $attachment ) { return ''; } - $attachment_obj = get_post( $attachment_id ); + /** + * Fires before resolving this attachment's post/transcoding-error + * meta, so integrations that centralize media on another site can + * switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $attachment_obj = get_post( $attachment_id ); - if ( 'attachment' !== $attachment_obj->post_type ) { - return ''; - } + if ( 'attachment' !== $attachment_obj->post_type ) { + return ''; + } - return strval( get_post_meta( $attachment_id, 'rtgodam_transcoding_error_msg', true ) ); + return strval( get_post_meta( $attachment_id, 'rtgodam_transcoding_error_msg', true ) ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } } diff --git a/assets/src/blocks/godam-audio/render.php b/assets/src/blocks/godam-audio/render.php index 561dddf94f..0d09aec279 100644 --- a/assets/src/blocks/godam-audio/render.php +++ b/assets/src/blocks/godam-audio/render.php @@ -18,116 +18,130 @@ $godam_description = ! empty( $attributes['description'] ) ? $attributes['description'] : ''; $godam_thumbnail = ! empty( $attributes['thumbnail'] ) ? esc_url( $attributes['thumbnail'] ) : ''; -// The [godam_audio] shortcode only passes an id (no title/thumbnail block -// attributes), so fall back to the attachment's own data — the title and the -// GoDAM cover stored in rtgodam_media_audio_thumbnail — to match the block. -if ( $godam_attachment_id ) { - if ( '' === $godam_audio_title ) { - $godam_audio_title = get_the_title( $godam_attachment_id ); - } - if ( '' === $godam_thumbnail ) { - $godam_meta_thumbnail = get_post_meta( $godam_attachment_id, 'rtgodam_media_audio_thumbnail', true ); - if ( ! empty( $godam_meta_thumbnail ) ) { - $godam_thumbnail = esc_url( $godam_meta_thumbnail ); +/** + * Fires before reading this attachment's title/thumbnail/chapters/transcript + * meta and its audio source URLs (below), so integrations that centralize + * media on another site can switch context first. + * + * @since 2.2.0 + */ +do_action( 'rtgodam_before_attachment_lookup' ); + +try { + // The [godam_audio] shortcode only passes an id (no title/thumbnail block + // attributes), so fall back to the attachment's own data — the title and the + // GoDAM cover stored in rtgodam_media_audio_thumbnail — to match the block. + if ( $godam_attachment_id ) { + if ( '' === $godam_audio_title ) { + $godam_audio_title = get_the_title( $godam_attachment_id ); + } + if ( '' === $godam_thumbnail ) { + $godam_meta_thumbnail = get_post_meta( $godam_attachment_id, 'rtgodam_media_audio_thumbnail', true ); + if ( ! empty( $godam_meta_thumbnail ) ) { + $godam_thumbnail = esc_url( $godam_meta_thumbnail ); + } } } -} - -// The transcript toggle defaults to on when the attribute is absent. -$godam_show_transcript = ! array_key_exists( 'showTranscript', $attributes ) || ! empty( $attributes['showTranscript'] ); -$godam_show_chapters = ! array_key_exists( 'showChapters', $attributes ) || ! empty( $attributes['showChapters'] ); -// Chapters live on the attachment's rtgodam_meta; the transcript is a caption -// file URL cached in the rtgodam_transcript_path meta. -$godam_meta_all = $godam_attachment_id ? get_post_meta( $godam_attachment_id, 'rtgodam_meta', true ) : array(); -$godam_chapters_raw = ( is_array( $godam_meta_all ) && ! empty( $godam_meta_all['chapters'] ) ) ? $godam_meta_all['chapters'] : array(); + // The transcript toggle defaults to on when the attribute is absent. + $godam_show_transcript = ! array_key_exists( 'showTranscript', $attributes ) || ! empty( $attributes['showTranscript'] ); + $godam_show_chapters = ! array_key_exists( 'showChapters', $attributes ) || ! empty( $attributes['showChapters'] ); -// Read ONLY the cached transcript path, and only when the toggle is on. Never -// call godam_get_transcript_path() at render time: on a cache miss it makes a -// blocking wp_remote_post() to the SaaS (on public, unauthenticated page loads) -// and re-caches the path without the delete guard, which would resurrect a -// transcript the user deleted. Discovery + caching happen in the authenticated -// editor (block canvas + customization editor) via the /godam/v1/transcription -// route, which applies that guard. -$godam_transcript_url = ( $godam_attachment_id && $godam_show_transcript ) - ? (string) get_post_meta( $godam_attachment_id, 'rtgodam_transcript_path', true ) - : ''; + // Chapters live on the attachment's rtgodam_meta; the transcript is a caption + // file URL cached in the rtgodam_transcript_path meta. + $godam_meta_all = $godam_attachment_id ? get_post_meta( $godam_attachment_id, 'rtgodam_meta', true ) : array(); + $godam_chapters_raw = ( is_array( $godam_meta_all ) && ! empty( $godam_meta_all['chapters'] ) ) ? $godam_meta_all['chapters'] : array(); -// Chapters are normally stored as an array, but tolerate a JSON string (old -// installs / external sources) so the foreach below never warns. -if ( is_string( $godam_chapters_raw ) ) { - $godam_decoded_chapters = json_decode( $godam_chapters_raw, true ); - $godam_chapters_raw = is_array( $godam_decoded_chapters ) ? $godam_decoded_chapters : array(); -} elseif ( ! is_array( $godam_chapters_raw ) ) { - $godam_chapters_raw = array(); -} + // Read ONLY the cached transcript path, and only when the toggle is on. Never + // call godam_get_transcript_path() at render time: on a cache miss it makes a + // blocking wp_remote_post() to the SaaS (on public, unauthenticated page loads) + // and re-caches the path without the delete guard, which would resurrect a + // transcript the user deleted. Discovery + caching happen in the authenticated + // editor (block canvas + customization editor) via the /godam/v1/transcription + // route, which applies that guard. + $godam_transcript_url = ( $godam_attachment_id && $godam_show_transcript ) + ? (string) get_post_meta( $godam_attachment_id, 'rtgodam_transcript_path', true ) + : ''; -// Normalise chapters for both server rendering and the front-end script. -$godam_chapters = array(); -foreach ( $godam_chapters_raw as $godam_chapter ) { - $godam_chapters[] = array( - 'start' => isset( $godam_chapter['startTime'] ) ? floatval( $godam_chapter['startTime'] ) : 0, - 'text' => isset( $godam_chapter['text'] ) ? (string) $godam_chapter['text'] : '', - ); -} - -// Sort by start time. Chapters are stored in authoring order (not necessarily -// chronological), but the rendered list and the front-end active-line logic -// (which derives each chapter's window from the next row) both assume ascending -// order — matching how the editor preview sorts via getChapterRows(). -usort( - $godam_chapters, - static function ( $a, $b ) { - return $a['start'] <=> $b['start']; + // Chapters are normally stored as an array, but tolerate a JSON string (old + // installs / external sources) so the foreach below never warns. + if ( is_string( $godam_chapters_raw ) ) { + $godam_decoded_chapters = json_decode( $godam_chapters_raw, true ); + $godam_chapters_raw = is_array( $godam_decoded_chapters ) ? $godam_decoded_chapters : array(); + } elseif ( ! is_array( $godam_chapters_raw ) ) { + $godam_chapters_raw = array(); } -); -// Each tab shows only when its own toggle is on and it has content; the panel -// appears when at least one tab is visible. -$godam_chapters_visible = $godam_show_chapters && ! empty( $godam_chapters ); -$godam_transcript_visible = $godam_show_transcript && ! empty( $godam_transcript_url ); -$godam_has_panel = $godam_chapters_visible || $godam_transcript_visible; + // Normalise chapters for both server rendering and the front-end script. + $godam_chapters = array(); + foreach ( $godam_chapters_raw as $godam_chapter ) { + $godam_chapters[] = array( + 'start' => isset( $godam_chapter['startTime'] ) ? floatval( $godam_chapter['startTime'] ) : 0, + 'text' => isset( $godam_chapter['text'] ) ? (string) $godam_chapter['text'] : '', + ); + } -// Chapters is the first tab, so it is active when visible; the transcript is -// active only when chapters is hidden. Pre-build class / aria / hidden strings -// so the markup only echoes escaped values. -$godam_chapters_active = $godam_chapters_visible; -$godam_transcript_active = $godam_transcript_visible && ! $godam_chapters_visible; -$godam_chapters_tab_class = 'godam-audio-tabs__tab' . ( $godam_chapters_active ? ' is-active' : '' ); -$godam_transcript_tab_class = 'godam-audio-tabs__tab' . ( $godam_transcript_active ? ' is-active' : '' ); -$godam_chapters_aria = $godam_chapters_active ? 'true' : 'false'; -$godam_transcript_aria = $godam_transcript_active ? 'true' : 'false'; -$godam_chapters_hidden = $godam_chapters_active ? '' : 'hidden'; -$godam_transcript_hidden = $godam_transcript_active ? '' : 'hidden'; + // Sort by start time. Chapters are stored in authoring order (not necessarily + // chronological), but the rendered list and the front-end active-line logic + // (which derives each chapter's window from the next row) both assume ascending + // order — matching how the editor preview sorts via getChapterRows(). + usort( + $godam_chapters, + static function ( $a, $b ) { + return $a['start'] <=> $b['start']; + } + ); -// Unique IDs to wire the ARIA tab pattern (role="tab" <-> role="tabpanel") so -// screen readers announce which panel each tab controls. wp_unique_id() keeps -// them unique even with multiple audio blocks on one page. Roving tabindex: -// only the active tab is in the tab order. -$godam_tabs_uid = wp_unique_id( 'godam-audio-tabs-' ); -$godam_chapters_tab_id = $godam_tabs_uid . '-tab-chapters'; -$godam_chapters_panel_id = $godam_tabs_uid . '-panel-chapters'; -$godam_transcript_tab_id = $godam_tabs_uid . '-tab-transcript'; -$godam_transcript_panel_id = $godam_tabs_uid . '-panel-transcript'; -$godam_chapters_tabindex = $godam_chapters_active ? '0' : '-1'; -$godam_transcript_tabindex = $godam_transcript_active ? '0' : '-1'; + // Each tab shows only when its own toggle is on and it has content; the panel + // appears when at least one tab is visible. + $godam_chapters_visible = $godam_show_chapters && ! empty( $godam_chapters ); + $godam_transcript_visible = $godam_show_transcript && ! empty( $godam_transcript_url ); + $godam_has_panel = $godam_chapters_visible || $godam_transcript_visible; -if ( ! $godam_attachment_id && empty( $godam_src ) ) { - return; -} + // Chapters is the first tab, so it is active when visible; the transcript is + // active only when chapters is hidden. Pre-build class / aria / hidden strings + // so the markup only echoes escaped values. + $godam_chapters_active = $godam_chapters_visible; + $godam_transcript_active = $godam_transcript_visible && ! $godam_chapters_visible; + $godam_chapters_tab_class = 'godam-audio-tabs__tab' . ( $godam_chapters_active ? ' is-active' : '' ); + $godam_transcript_tab_class = 'godam-audio-tabs__tab' . ( $godam_transcript_active ? ' is-active' : '' ); + $godam_chapters_aria = $godam_chapters_active ? 'true' : 'false'; + $godam_transcript_aria = $godam_transcript_active ? 'true' : 'false'; + $godam_chapters_hidden = $godam_chapters_active ? '' : 'hidden'; + $godam_transcript_hidden = $godam_transcript_active ? '' : 'hidden'; -if ( ! $godam_attachment_id && ! empty( $godam_src ) ) { - // Virtual attachment scenario. - $godam_primary_audio = $godam_src; - $godam_backup_audio = ''; -} else { - $godam_primary_audio = get_post_meta( $godam_attachment_id, 'rtgodam_transcoded_url', true ); - $godam_backup_audio = wp_get_attachment_url( $godam_attachment_id ); + // Unique IDs to wire the ARIA tab pattern (role="tab" <-> role="tabpanel") so + // screen readers announce which panel each tab controls. wp_unique_id() keeps + // them unique even with multiple audio blocks on one page. Roving tabindex: + // only the active tab is in the tab order. + $godam_tabs_uid = wp_unique_id( 'godam-audio-tabs-' ); + $godam_chapters_tab_id = $godam_tabs_uid . '-tab-chapters'; + $godam_chapters_panel_id = $godam_tabs_uid . '-panel-chapters'; + $godam_transcript_tab_id = $godam_tabs_uid . '-tab-transcript'; + $godam_transcript_panel_id = $godam_tabs_uid . '-panel-transcript'; + $godam_chapters_tabindex = $godam_chapters_active ? '0' : '-1'; + $godam_transcript_tabindex = $godam_transcript_active ? '0' : '-1'; - if ( empty( $godam_primary_audio ) && empty( $godam_backup_audio ) ) { + if ( ! $godam_attachment_id && empty( $godam_src ) ) { return; } + + if ( ! $godam_attachment_id && ! empty( $godam_src ) ) { + // Virtual attachment scenario. + $godam_primary_audio = $godam_src; + $godam_backup_audio = ''; + } else { + $godam_primary_audio = get_post_meta( $godam_attachment_id, 'rtgodam_transcoded_url', true ); + $godam_backup_audio = wp_get_attachment_url( $godam_attachment_id ); + + if ( empty( $godam_primary_audio ) && empty( $godam_backup_audio ) ) { + return; + } + } +} finally { + do_action( 'rtgodam_after_attachment_lookup' ); } + // Root wrapper: emit a stable `godam-audio` hook class that view.js targets on // both render paths. In block context also merge WordPress' block-support // attributes (align/spacing/etc.); the [godam_audio] shortcode sets diff --git a/assets/src/blocks/godam-image/render.php b/assets/src/blocks/godam-image/render.php index 2786d34679..4a38981aed 100644 --- a/assets/src/blocks/godam-image/render.php +++ b/assets/src/blocks/godam-image/render.php @@ -25,6 +25,16 @@ // The toggle defaults to on when the attribute is absent. $godam_show_layers = ! array_key_exists( 'showImageLayers', $attributes ) || ! empty( $attributes['showImageLayers'] ); +/** + * Fires before reading this attachment's URL/alt/dimensions, so integrations + * that centralize media on another site can switch context first. Closed + * explicitly before the early `return` just below (a bare `return` at file + * scope doesn't unwind through a `finally`), not held open across it. + * + * @since 2.2.0 + */ +do_action( 'rtgodam_before_attachment_lookup' ); + // Fall back to the attachment's own URL / alt / dimensions when not stored on // the block (e.g. a copied block that carries only the id). if ( $godam_attachment_id ) { @@ -43,6 +53,8 @@ } } +do_action( 'rtgodam_after_attachment_lookup' ); + if ( empty( $godam_src ) ) { return ''; } @@ -51,8 +63,16 @@ // timeline, so all layers are always visible. $godam_layers = array(); if ( $godam_show_layers && $godam_attachment_id ) { + /** + * Fires before reading this attachment's layer meta, so integrations + * that centralize media on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $godam_meta = get_post_meta( $godam_attachment_id, 'rtgodam_meta', true ); $godam_all_layers = ( is_array( $godam_meta ) && ! empty( $godam_meta['layers'] ) ) ? $godam_meta['layers'] : array(); + do_action( 'rtgodam_after_attachment_lookup' ); foreach ( $godam_all_layers as $godam_layer ) { if ( ! is_array( $godam_layer ) || empty( $godam_layer['type'] ) ) { continue; diff --git a/assets/src/blocks/godam-pdf/edit.js b/assets/src/blocks/godam-pdf/edit.js index d5bbd80dd9..54fa8d0977 100644 --- a/assets/src/blocks/godam-pdf/edit.js +++ b/assets/src/blocks/godam-pdf/edit.js @@ -24,6 +24,7 @@ import { MediaUpload, MediaUploadCheck, useBlockProps, + // eslint-disable-next-line import/no-unresolved -- resolver false positive: package resolves fine at build time, eslint-plugin-import can't parse @wordpress/block-editor's exports map. } from '@wordpress/block-editor'; import { __ } from '@wordpress/i18n'; import { useDispatch, useSelect } from '@wordpress/data'; diff --git a/assets/src/blocks/godam-pdf/render.php b/assets/src/blocks/godam-pdf/render.php index 2e3bfbe70b..e31f0a1d64 100644 --- a/assets/src/blocks/godam-pdf/render.php +++ b/assets/src/blocks/godam-pdf/render.php @@ -26,44 +26,57 @@ return; } -/* - * Two URLs, and they are not interchangeable. - * - * $godam_preview_url is always a PDF: either the file itself, or the preview PDF GoDAM - * Central rendered from a Word / Excel / PowerPoint / OpenDocument / text upload. It is the - * only thing that may be handed to the viewer. +/** + * Fires before reading this attachment's URL/transcoded-URL/title, so + * integrations that centralize media on another site can switch context + * first. * - * $godam_download_url is always the file the author uploaded. It is the only thing that may - * be offered as a download — somebody who uploads report.xlsx and gets preview.pdf back - * will think something broke. + * @since 2.2.0 */ -$godam_preview_url = rtgodam_get_document_preview_url( $godam_attachment_id, $godam_src ); -$godam_download_url = rtgodam_get_document_download_url( $godam_attachment_id, $godam_src ); - -if ( ! empty( $godam_attachment_id ) && is_numeric( $godam_attachment_id ) ) { - // Fall back to attachment title for doc title if editor left it empty. - if ( empty( $godam_doc_title ) ) { - $godam_post = get_post( $godam_attachment_id ); - $godam_doc_title = $godam_post ? get_the_title( $godam_post ) : ''; +do_action( 'rtgodam_before_attachment_lookup' ); + +try { + /* + * Two URLs, and they are not interchangeable. + * + * $godam_preview_url is always a PDF: either the file itself, or the preview PDF GoDAM + * Central rendered from a Word / Excel / PowerPoint / OpenDocument / text upload. It is the + * only thing that may be handed to the viewer. + * + * $godam_download_url is always the file the author uploaded. It is the only thing that may + * be offered as a download — somebody who uploads report.xlsx and gets preview.pdf back + * will think something broke. + */ + $godam_preview_url = rtgodam_get_document_preview_url( $godam_attachment_id, $godam_src ); + $godam_download_url = rtgodam_get_document_download_url( $godam_attachment_id, $godam_src ); + + if ( ! empty( $godam_attachment_id ) && is_numeric( $godam_attachment_id ) ) { + // Fall back to attachment title for doc title if editor left it empty. + if ( empty( $godam_doc_title ) ) { + $godam_post = get_post( $godam_attachment_id ); + $godam_doc_title = $godam_post ? get_the_title( $godam_post ) : ''; + } } -} -if ( empty( $godam_preview_url ) && empty( $godam_download_url ) ) { - return; -} + if ( empty( $godam_preview_url ) && empty( $godam_download_url ) ) { + return; + } -/* - * Formats outside rtgodam_get_supported_document_types() have no preview to show, so emit - * nothing rather than an empty frame; the editors surface an "unsupported format" notice so - * the author can see and fix it. - * - * Checked against the original attachment id / src rather than the resolved URLs above, - * because a preview URL's extension no longer reflects the source file. A numeric id - * resolves via its stored MIME type, so $godam_src is only consulted for GoDAM tab media - * and URL-only documents, exactly the cases where $godam_src is guaranteed set. - */ -if ( ! godam_is_supported_document( $godam_attachment_id, $godam_src ) ) { - return; + /* + * Formats outside rtgodam_get_supported_document_types() have no preview to show, so emit + * nothing rather than an empty frame; the editors surface an "unsupported format" notice so + * the author can see and fix it. + * + * Checked against the original attachment id / src rather than the resolved URLs above, + * because a preview URL's extension no longer reflects the source file. A numeric id + * resolves via its stored MIME type, so $godam_src is only consulted for GoDAM tab media + * and URL-only documents, exactly the cases where $godam_src is guaranteed set. + */ + if ( ! godam_is_supported_document( $godam_attachment_id, $godam_src ) ) { + return; + } +} finally { + do_action( 'rtgodam_after_attachment_lookup' ); } // Named from the original, not the preview, so the card's fallback label reads @@ -94,12 +107,14 @@ if ( $godam_custom_cover ) { $godam_cover_url = $godam_custom_cover; } elseif ( ! empty( $godam_attachment_id ) && is_numeric( $godam_attachment_id ) ) { + do_action( 'rtgodam_before_attachment_lookup' ); // Mirror set_media_library_thumbnail(): video thumbnail (transcoding callback) // takes priority over pdf-specific key (GoDAM tab import). $godam_thumb = get_post_meta( $godam_attachment_id, 'rtgodam_media_video_thumbnail', true ); if ( empty( $godam_thumb ) ) { $godam_thumb = get_post_meta( $godam_attachment_id, 'rtgodam_media_pdf_thumbnail', true ); } + do_action( 'rtgodam_after_attachment_lookup' ); if ( $godam_thumb ) { $godam_cover_url = $godam_thumb; // escaped at output below. } @@ -148,6 +163,7 @@ class="godam-pdf-card" $godam_meta_parts[] = sprintf( _n( '%d page', '%d pages', $godam_page_count, 'godam' ), $godam_page_count ); } if ( $godam_attachment_id ) { + do_action( 'rtgodam_before_attachment_lookup' ); // wp_get_attachment_metadata() stores filesize in the DB — // works even when files are on S3 / CDN (no local file needed). $godam_att_meta = wp_get_attachment_metadata( $godam_attachment_id ); @@ -159,6 +175,7 @@ class="godam-pdf-card" $godam_filesize = filesize( $godam_local ); } } + do_action( 'rtgodam_after_attachment_lookup' ); if ( $godam_filesize ) { $godam_meta_parts[] = $godam_filesize < 1048576 ? round( $godam_filesize / 1024 ) . ' KB' diff --git a/assets/src/blocks/godam-player/edit.js b/assets/src/blocks/godam-player/edit.js index e02f694d98..3537cc650b 100644 --- a/assets/src/blocks/godam-player/edit.js +++ b/assets/src/blocks/godam-player/edit.js @@ -36,6 +36,7 @@ import { MediaReplaceFlow, useBlockProps, InnerBlocks, + // eslint-disable-next-line import/no-unresolved -- resolver false positive: package resolves fine at build time, eslint-plugin-import can't parse @wordpress/block-editor's exports map. } from '@wordpress/block-editor'; import { useRef, useEffect, useState, useMemo } from '@wordpress/element'; import apiFetch from '@wordpress/api-fetch'; diff --git a/assets/src/blocks/godam-player/render.php b/assets/src/blocks/godam-player/render.php index d957f36319..16745ce266 100644 --- a/assets/src/blocks/godam-player/render.php +++ b/assets/src/blocks/godam-player/render.php @@ -18,7 +18,7 @@ * Inside a query loop or single post context. * Get attachment ID from postmeta. */ - $godam_query_loop_attachment_id = get_post_meta( $post->ID, '_godam_attachment_id', true ); + $godam_query_loop_attachment_id = get_post_meta( $post->ID, '_godam_attachment_id', true ); // godam-coverage-ignore -- Reads '_godam_attachment_id' off the host post (global $post), not off the attachment — this is host-post meta, not attachment data. /** * Set ID attribute if not already set. diff --git a/assets/src/blocks/godam-video-duration/render.php b/assets/src/blocks/godam-video-duration/render.php index 0dd9ecd967..802e126140 100644 --- a/assets/src/blocks/godam-video-duration/render.php +++ b/assets/src/blocks/godam-video-duration/render.php @@ -18,10 +18,18 @@ if ( $godam_video_post_id ) { // Get attachment ID from post meta. - $godam_attachment_id = get_post_meta( $godam_video_post_id, '_godam_attachment_id', true ); + $godam_attachment_id = get_post_meta( $godam_video_post_id, '_godam_attachment_id', true ); // godam-coverage-ignore -- Reads '_godam_attachment_id' off the host post (get_the_ID()), not off the attachment — the actual attachment meta read a few lines below already has its own before/after pair. + /** + * Fires before reading this attachment's duration meta, so integrations + * that centralize media on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); // Get video duration directly from attachment's meta. $godam_video_duration = absint( get_post_meta( $godam_attachment_id, '_video_duration', true ) ); + do_action( 'rtgodam_after_attachment_lookup' ); } // Format the duration using the formatting function. diff --git a/assets/src/blocks/godam-video-thumbnail/render.php b/assets/src/blocks/godam-video-thumbnail/render.php index 21a8088990..ca3695792c 100644 --- a/assets/src/blocks/godam-video-thumbnail/render.php +++ b/assets/src/blocks/godam-video-thumbnail/render.php @@ -20,13 +20,22 @@ if ( $godam_video_post_id ) { // Get attachment ID from post meta. - $godam_attachment_id = get_post_meta( $godam_video_post_id, '_godam_attachment_id', true ); - + $godam_attachment_id = get_post_meta( $godam_video_post_id, '_godam_attachment_id', true ); // godam-coverage-ignore -- Reads '_godam_attachment_id' off the host post (get_the_ID()), not off the attachment — the actual attachment meta read a few lines below already has its own before/after pair. + + /** + * Fires before reading this attachment's thumbnail meta, so + * integrations that centralize media on another site can switch context + * first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); // Get thumbnail URL directly from attachment's meta. $godam_thumbnail_url = get_post_meta( $godam_attachment_id, 'rtgodam_media_video_thumbnail', true ); + do_action( 'rtgodam_after_attachment_lookup' ); // Set alt text to the post title. - $godam_alt_text = get_the_title(); + $godam_alt_text = get_the_title(); // godam-coverage-ignore -- No argument: reads the title of the host post ($godam_video_post_id above), the same host-post distinction as the _godam_attachment_id read above — not the attachment. } $godam_wrapper_classes = 'godam-video-thumbnail__container'; diff --git a/assets/src/css/admin.scss b/assets/src/css/admin.scss index 6b96fb2064..509d762ec1 100644 --- a/assets/src/css/admin.scss +++ b/assets/src/css/admin.scss @@ -1024,34 +1024,6 @@ to ensure proper responsiveness and avoid layout issues. text-decoration: none; } -.godam-video-thumb-wrapper { - position: relative; - display: block; - - &.godam-locked img { - filter: blur(3px) brightness(0.7); - } - - .godam-lock-overlay { - position: absolute; - inset: 0; - display: flex; - align-items: center; - justify-content: center; - font-size: 28px; - color: #fff; - background: rgba(0,0,0,0.25); - border-radius: 4px; - pointer-events: none; - - filter: drop-shadow(0 2px 4px rgba(0,0,0,0.55)); - - svg { - filter: drop-shadow(0 2px 4px rgba(0,0,0,0.55)); - } - } -} - .godam-featured-video-gallery-notice { margin-left: 8px !important; margin-right: 8px !important; @@ -1122,6 +1094,34 @@ to ensure proper responsiveness and avoid layout issues. } } +.godam-video-thumb-wrapper { + position: relative; + display: block; + + &.godam-locked img { + filter: blur(3px) brightness(0.7); + } + + .godam-lock-overlay { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + font-size: 28px; + color: #fff; + background: rgba(0,0,0,0.25); + border-radius: 4px; + pointer-events: none; + + filter: drop-shadow(0 2px 4px rgba(0,0,0,0.55)); + + svg { + filter: drop-shadow(0 2px 4px rgba(0,0,0,0.55)); + } + } +} + @keyframes godam-elementor-thumbnail-spin { to { diff --git a/assets/src/js/media-library/views/attachment-browser.js b/assets/src/js/media-library/views/attachment-browser.js index 74ef691991..ed4a021179 100644 --- a/assets/src/js/media-library/views/attachment-browser.js +++ b/assets/src/js/media-library/views/attachment-browser.js @@ -20,7 +20,9 @@ const AttachmentsBrowser = wp?.media?.view?.AttachmentsBrowser; export default AttachmentsBrowser?.extend( { initialize() { - // Initialize the parent class. + // Initialize the parent class. AttachmentsBrowser's own initialize() + // does NOT call bindEvents() (that belongs to wp.media.view.Attachments, + // a different view), so the override below has to be invoked explicitly. AttachmentsBrowser.prototype.initialize.apply( this, arguments ); this.updateCollectionObserve(); @@ -29,6 +31,13 @@ export default AttachmentsBrowser?.extend( { }, bindEvents() { + // Chain to the parent's bindEvents (if any) so other code extending + // the same wp.media.view.AttachmentsBrowser (e.g. wp-dam) isn't + // silently dropped by this override. + if ( AttachmentsBrowser.prototype.bindEvents ) { + AttachmentsBrowser.prototype.bindEvents.apply( this, arguments ); + } + this.collection.props.on( 'change', this.updateCollectionObserve, this ); this.collection.props.on( 'change', this.addUploadParam, this ); }, diff --git a/bin/hook-check/balance.php b/bin/hook-check/balance.php new file mode 100644 index 0000000000..3afad0de24 --- /dev/null +++ b/bin/hook-check/balance.php @@ -0,0 +1,340 @@ + 'unclosed_before'|'stray_after', 'line' => int, 'open_count' => int] or null if balanced. + */ +function godam_check_hook_balance_in_range( $tokens, $range_start, $range_end, $skip_ranges = array() ) { + $open_before_lines = array(); + $checkpoints = array(); // Stack of $open_before_lines snapshots, pushed on '{', popped on '}'. + $count = count( $tokens ); + + for ( $i = $range_start; $i <= $range_end; $i++ ) { + $jumped = false; + foreach ( $skip_ranges as $skip ) { + if ( $i === $skip[0] ) { + $i = $skip[1]; + $jumped = true; + break; + } + } + if ( $jumped ) { + continue; + } + + $text = $tokens[ $i ]['text']; + + if ( '{' === $text ) { + $checkpoints[] = $open_before_lines; + continue; + } + + if ( '}' === $text ) { + array_pop( $checkpoints ); + continue; + } + + if ( godam_shared_is_scope_terminator( $tokens, $i, $count ) ) { + $checkpoint = empty( $checkpoints ) ? array() : end( $checkpoints ); + + if ( count( $open_before_lines ) > count( $checkpoint ) ) { + return array( + 'type' => 'unclosed_before', + 'line' => end( $open_before_lines ), + 'open_count' => count( $open_before_lines ) - count( $checkpoint ), + ); + } + + $open_before_lines = $checkpoint; // Rewind — see docblock. + continue; + } + + if ( godam_shared_is_hook_fire_at( $tokens, $i, WRAP_HOOK_NAME ) ) { + $open_before_lines[] = $tokens[ $i ]['line']; + continue; + } + + if ( godam_shared_is_hook_fire_at( $tokens, $i, AFTER_HOOK_NAME ) ) { + if ( empty( $open_before_lines ) ) { + return array( + 'type' => 'stray_after', + 'line' => $tokens[ $i ]['line'], + ); + } + array_pop( $open_before_lines ); + } + } + + if ( ! empty( $open_before_lines ) ) { + return array( + 'type' => 'unclosed_before', + 'line' => end( $open_before_lines ), + 'open_count' => count( $open_before_lines ), + ); + } + + return null; +} + +/** + * Runs godam_check_hook_balance_in_range() once per named function body, + * once per deferred closure, and once across the remaining top-level code + * (concatenated in file order). + * + * A deferred closure is excluded from its enclosing range and checked as + * its own independent scope instead — see the $skip_ranges parameter above. + * + * @param array[] $tokens Full token list for the file. + * @param array[] $functions This file's own godam_shared_find_functions() result. + * @return array[] Each finding: scope ('top-level code', a function name, or a deferred-closure + * label), plus the 'type'/'line'/'open_count' from godam_check_hook_balance_in_range(). + */ +function godam_check_hook_balance_findings( $tokens, $functions ) { + $findings = array(); + $count = count( $tokens ); + $top_level_indexes = array(); + $deferred_closures = godam_shared_find_deferred_closures( $tokens, $functions ); + + // Excludes deferred closures AND other nested functions/methods (ranges + // can nest, e.g. a method inside a function-scoped anonymous class) so + // an outer scope's walk doesn't also see a nested scope's own + // before()/after() calls. + $skip_ranges_for = function ( $range_start, $range_end ) use ( $deferred_closures, $functions ) { + return array_merge( + godam_shared_ranges_nested_in( $range_start, $range_end, $deferred_closures ), + godam_shared_ranges_nested_in( $range_start, $range_end, $functions ) + ); + }; + + for ( $i = 0; $i < $count; $i++ ) { + $inside_a_function = false; + + foreach ( $functions as $function ) { + if ( $i >= $function['body_start'] && $i <= $function['body_end'] ) { + $inside_a_function = true; + break; + } + } + + $inside_a_deferred_closure = false; + foreach ( $deferred_closures as $closure ) { + if ( $i >= $closure['body_start'] && $i <= $closure['body_end'] ) { + $inside_a_deferred_closure = true; + break; + } + } + + if ( ! $inside_a_function && ! $inside_a_deferred_closure ) { + $top_level_indexes[] = $i; + } + } + + foreach ( $functions as $function ) { + $result = godam_check_hook_balance_in_range( $tokens, $function['body_start'], $function['body_end'], $skip_ranges_for( $function['body_start'], $function['body_end'] ) ); + + if ( null !== $result ) { + $result['scope'] = null !== $function['class'] ? "{$function['class']}::{$function['name']}()" : "{$function['name']}()"; + $findings[] = $result; + } + } + + foreach ( $deferred_closures as $closure ) { + $result = godam_check_hook_balance_in_range( $tokens, $closure['body_start'], $closure['body_end'], $skip_ranges_for( $closure['body_start'], $closure['body_end'] ) ); + + if ( null !== $result ) { + $result['scope'] = null !== $closure['hook_name'] + ? "closure registered for '{$closure['hook_name']}' via add_action/add_filter()" + : 'closure registered via add_action/add_filter()'; + $findings[] = $result; + } + } + + if ( ! empty( $top_level_indexes ) ) { + // Reindexed to a contiguous array so the range walk isn't confused + // by the gaps left where function bodies were skipped. + $top_level_tokens = array_values( array_intersect_key( $tokens, array_flip( $top_level_indexes ) ) ); + $result = godam_check_hook_balance_in_range( $top_level_tokens, 0, count( $top_level_tokens ) - 1 ); + + if ( null !== $result ) { + $result['scope'] = 'top-level code'; + $findings[] = $result; + } + } + + return $findings; +} + +// Before/after hook balance, keyed "{file}:{line}" like the sibling +// coverage-check.php. Accepted only via a godam-coverage-ignore/-disable +// comment at the call site — reserved for a pairing this script can't +// trace, not for excepting a real bug. +$balance_findings = array(); +$directives_by_file = array(); +foreach ( $files as $file ) { + $tokens = godam_shared_tokenize( $file ); + $functions = godam_shared_find_functions( $tokens ); + $relative = ltrim( str_replace( $root, '', $file ), DIRECTORY_SEPARATOR ); + + $directives_by_file[ $relative ] = godam_shared_coverage_directives( $tokens ); + + foreach ( godam_check_hook_balance_findings( $tokens, $functions ) as $finding ) { + $key = "{$relative}:{$finding['line']}"; + + $balance_findings[ $key ] = array( + 'file' => $relative, + 'line' => $finding['line'], + 'type' => $finding['type'], + 'scope' => $finding['scope'], + 'open_count' => $finding['open_count'] ?? null, + ); + } +} + +ksort( $balance_findings ); + +// A disable with no matching enable is a hard error — otherwise it would +// silently suppress every finding for the rest of the file. +$dangling_disables = array(); +foreach ( $directives_by_file as $relative => $directives ) { + if ( null !== $directives['dangling_disable'] ) { + $dangling_disables[ $relative ] = $directives['dangling_disable']; + } +} + +if ( ! empty( $dangling_disables ) ) { + fwrite( STDERR, "DANGLING godam-coverage-disable — no matching godam-coverage-enable found\n" ); + fwrite( STDERR, "before end of file. This would otherwise silently suppress every finding\n" ); + fwrite( STDERR, "for the rest of the file with no reviewed reason at all:\n\n" ); + foreach ( $dangling_disables as $relative => $disable ) { + fwrite( STDERR, " - {$relative}:{$disable['line']} -- {$disable['reason']}\n" ); + } + fwrite( STDERR, "\nAdd a matching // godam-coverage-enable comment, or remove the disable if it's no longer needed.\n" ); + exit( 1 ); +} + +$directive_covered_balance = array(); +foreach ( $balance_findings as $key => $finding ) { + $directives = $directives_by_file[ $finding['file'] ] ?? null; + if ( null === $directives ) { + continue; + } + + if ( null !== $directives['ignore_file'] ) { + $directive_covered_balance[ $key ] = $directives['ignore_file']; + continue; + } + + $reason = godam_shared_coverage_directive_covers( $directives, $finding['line'] ); + if ( null !== $reason ) { + $directive_covered_balance[ $key ] = $reason; + } +} + +$balance_findings = array_diff_key( $balance_findings, $directive_covered_balance ); + +/** + * Builds one balance finding's own human-readable message. + * + * @param array $finding One of $balance_findings' own values. + * @return string + */ +function godam_check_format_balance_finding( $finding ) { + if ( 'stray_after' === $finding['type'] ) { + return "{$finding['file']}:{$finding['line']} — {$finding['scope']}: rtgodam_after_attachment_lookup fires with no matching rtgodam_before_attachment_lookup open at that point. A hook may have been added without its pairing before, or the before was removed while the after stayed."; + } + + $plural = 1 === $finding['open_count'] ? 'call' : 'calls'; + return "{$finding['file']}:{$finding['line']} — {$finding['scope']}: {$finding['open_count']} rtgodam_before_attachment_lookup {$plural} never reach a matching rtgodam_after_attachment_lookup before the end of this scope. The site context would stay switched to whatever site the before() call switched to for the rest of this request."; +} + +// Already filtered down to what no godam-coverage-* comment covers (see +// above); nothing left to diff against, so report directly. +$balance_failures = array_map( 'godam_check_format_balance_finding', $balance_findings ); + +echo 'Checked ' . count( $files ) . " file(s) for rtgodam_before_attachment_lookup/rtgodam_after_attachment_lookup balance.\n"; +echo 'Suppressed via inline godam-coverage-ignore/disable/ignore-file comments: ' . count( $directive_covered_balance ) . "\n\n"; + +if ( ! empty( $balance_failures ) ) { + echo "MALFORMED HOOK PAIRS (before/after don't balance — not just missing, wrong):\n"; + foreach ( $balance_failures as $balance_failure ) { + echo " - {$balance_failure}\n"; + } + echo "\n"; + echo "This check cannot prove centralization-compatibility on its own — see\n"; + echo "this file's own top-of-file comment for what it can and can't catch.\n"; + echo "A human still needs to look at the above.\n"; + exit( 1 ); +} + +echo "No malformed hook pairs detected.\n"; +exit( 0 ); diff --git a/bin/hook-check/coverage.php b/bin/hook-check/coverage.php new file mode 100644 index 0000000000..e80eb88705 --- /dev/null +++ b/bin/hook-check/coverage.php @@ -0,0 +1,1390 @@ + function name, 'arg' => unprefixed first-argument + * variable name, or '' if the first argument isn't a plain variable]. + * Returns null otherwise. + * + * Uses godam_shared_is_bare_call_to() for the same reason + * godam_shared_is_hook_fire_at()/godam_shared_is_scope_terminator() do: + * every ACCESS_FUNCTIONS name is a core global, never legitimately called + * via ->/::, so this only excludes a same-named user-defined method or + * declaration. 'name' is run through godam_shared_unqualified_name() so a + * qualified call reports as "get_post_meta()", not leaking its leading + * backslash — cosmetic only, findings are keyed on file:line. + * + * @param array[] $tokens Token list. + * @param int $i Index to check. + * @param int $count Token count. + * @return array|null + */ +function godam_coverage_access_call_at( $tokens, $i, $count ) { + if ( ! godam_shared_is_bare_call_to( $tokens, $i, ACCESS_FUNCTIONS, $count ) ) { + return null; + } + + $name = godam_shared_unqualified_name( $tokens[ $i ]['text'] ); + $open = godam_shared_skip_forward( $tokens, $i + 1, $count ); // The '(' itself. + $arg = godam_shared_skip_forward( $tokens, $open + 1, $count ); + + if ( $arg < $count && T_VARIABLE === ( $tokens[ $arg ]['id'] ?? null ) ) { + return array( + 'name' => $name, + 'arg' => ltrim( $tokens[ $arg ]['text'], '$' ), + ); + } + + return array( + 'name' => $name, + 'arg' => '', + ); +} + +/** + * If the token at $i starts a real, bare call to current_user_can() whose + * first argument is a literal string naming one of + * CURRENT_USER_CAN_META_CAPS and whose second argument (the object id) is + * present, returns ['name' => 'current_user_can', 'arg' => unprefixed + * second-argument variable name, or '' if it isn't a plain variable]. + * Returns null for every other current_user_can() shape -- a primitive + * capability, a meta cap called with no object id (current_user_can( + * 'edit_post' ) alone resolves against no specific post and never reaches + * get_post()), or a non-literal first argument this script can't resolve -- + * and for calls to any other function. + * + * Deliberately its own check rather than an ACCESS_FUNCTIONS entry: unlike + * every name in that list, most real current_user_can() calls + * (current_user_can( 'manage_options' ), current_user_can( 'upload_files' )) + * take no object argument at all, so matching on the bare function name + * would flag them as unresolvable "direct" findings and bury the real ones + * in noise. + * + * @param array[] $tokens Token list. + * @param int $i Index to check. + * @param int $count Token count. + * @return array|null + */ +function godam_coverage_current_user_can_at( $tokens, $i, $count ) { + if ( ! godam_shared_is_bare_call_to( $tokens, $i, array( 'current_user_can' ), $count ) ) { + return null; + } + + $open = godam_shared_skip_forward( $tokens, $i + 1, $count ); // The '(' itself. + $cap = godam_shared_skip_forward( $tokens, $open + 1, $count ); + + if ( $cap >= $count || T_CONSTANT_ENCAPSED_STRING !== ( $tokens[ $cap ]['id'] ?? null ) ) { + return null; + } + + if ( ! in_array( substr( $tokens[ $cap ]['text'], 1, -1 ), CURRENT_USER_CAN_META_CAPS, true ) ) { + return null; + } + + $comma = godam_shared_skip_forward( $tokens, $cap + 1, $count ); + if ( $comma >= $count || ',' !== $tokens[ $comma ]['text'] ) { + return null; // No second argument -- a primitive check, not object-scoped. + } + + $arg = godam_shared_skip_forward( $tokens, $comma + 1, $count ); + + if ( $arg < $count && T_VARIABLE === ( $tokens[ $arg ]['id'] ?? null ) ) { + return array( + 'name' => 'current_user_can', + 'arg' => ltrim( $tokens[ $arg ]['text'], '$' ), + ); + } + + return array( + 'name' => 'current_user_can', + 'arg' => '', + ); +} + +/** + * If the T_VARIABLE token at $i is immediately followed by a bare '=' (a + * real assignment — '==', '+=', etc. are their own distinct tokens), + * returns ['target' => name, 'safe_copy_of' => name|null]. 'safe_copy_of' + * is set only for two shapes, both immediately followed by ';' with + * nothing else: a bare copy of another variable ($x = $y;), or $target + * reassigned to a cast or single-argument call of itself ($id = + * absint($id);, $id = (int) $id;) — sanitizing/casting doesn't introduce + * new external data, so it shouldn't cost the value its safety. Anything + * else on the right gets 'safe_copy_of' => null. Returns null entirely if + * $i isn't an assignment target at all. + * + * Deliberately does NOT handle `list( $target, ... ) = ...` or + * `[ $target, ... ] = ...` — detected separately by + * godam_coverage_destructuring_targets_at(), since a destructured value is + * never a "bare copy" and should always revoke safety, never preserve it. + * + * @param array[] $tokens Token list. + * @param int $i Index of a token to check (only meaningful for a T_VARIABLE). + * @param int $count Token count. + * @return array|null + */ +function godam_coverage_assignment_at( $tokens, $i, $count ) { + if ( T_VARIABLE !== ( $tokens[ $i ]['id'] ?? null ) ) { + return null; + } + + $eq = godam_shared_skip_forward( $tokens, $i + 1, $count ); + if ( $eq >= $count || '=' !== $tokens[ $eq ]['text'] ) { + return null; + } + + $target = ltrim( $tokens[ $i ]['text'], '$' ); + $rhs = godam_shared_skip_forward( $tokens, $eq + 1, $count ); + + // Shape 1: a bare copy, e.g. $target = $other. + if ( $rhs < $count && T_VARIABLE === ( $tokens[ $rhs ]['id'] ?? null ) ) { + $after_rhs = godam_shared_skip_forward( $tokens, $rhs + 1, $count ); + if ( $after_rhs < $count && ';' === $tokens[ $after_rhs ]['text'] ) { + return array( + 'target' => $target, + 'safe_copy_of' => ltrim( $tokens[ $rhs ]['text'], '$' ), + ); + } + return array( + 'target' => $target, + 'safe_copy_of' => null, + ); // e.g. $x = $y->prop or $x = $y . 'z' — more than a bare copy. + } + + // Shape 2: a cast of itself, e.g. $target = (int) $target. + $cast_tokens = array( T_INT_CAST, T_DOUBLE_CAST, T_STRING_CAST, T_ARRAY_CAST, T_BOOL_CAST, T_UNSET_CAST ); + if ( $rhs < $count && in_array( $tokens[ $rhs ]['id'] ?? null, $cast_tokens, true ) ) { + $var = godam_shared_skip_forward( $tokens, $rhs + 1, $count ); + if ( $var < $count && T_VARIABLE === ( $tokens[ $var ]['id'] ?? null ) && ltrim( $tokens[ $var ]['text'], '$' ) === $target ) { + $after = godam_shared_skip_forward( $tokens, $var + 1, $count ); + if ( $after < $count && ';' === $tokens[ $after ]['text'] ) { + return array( + 'target' => $target, + 'safe_copy_of' => $target, + ); // Casting itself preserves whatever safety it already had. + } + } + return array( + 'target' => $target, + 'safe_copy_of' => null, + ); + } + + // Shape 3: a single-argument self-call, e.g. $target = absint( $target ) + // — bare or qualified (matching godam_shared_is_call_to()'s own + // qualified-name widening; no name list to check against here, so only + // the token types need accepting). + if ( $rhs < $count && in_array( $tokens[ $rhs ]['id'] ?? null, array( T_STRING, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED ), true ) ) { + $open = godam_shared_skip_forward( $tokens, $rhs + 1, $count ); + if ( $open < $count && '(' === $tokens[ $open ]['text'] ) { + $arg = godam_shared_skip_forward( $tokens, $open + 1, $count ); + if ( $arg < $count && T_VARIABLE === ( $tokens[ $arg ]['id'] ?? null ) && ltrim( $tokens[ $arg ]['text'], '$' ) === $target ) { + $close = godam_shared_skip_forward( $tokens, $arg + 1, $count ); + if ( $close < $count && ')' === $tokens[ $close ]['text'] ) { + $after = godam_shared_skip_forward( $tokens, $close + 1, $count ); + if ( $after < $count && ';' === $tokens[ $after ]['text'] ) { + return array( + 'target' => $target, + 'safe_copy_of' => $target, + ); // Single-arg self-transform (sanitize/format-style) preserves safety. + } + } + } + } + return array( + 'target' => $target, + 'safe_copy_of' => null, + ); + } + + // Anything else on the right — a literal, array(), a property access, + // a `new` expression, a multi-argument or chained call — isn't one of + // the recognized safety-preserving shapes above. + return array( + 'target' => $target, + 'safe_copy_of' => null, + ); +} + +/** + * If the token at $i starts a `list( ... ) = ...` or a statement-leading + * `[ ... ] = ...` (short-array destructuring), returns the unprefixed names + * of every variable named directly inside it — each is freshly assigned + * from the right-hand side, so every name here should have its safety + * revoked, never preserved. + * + * The `[` case is scoped to statement-start position (immediately after + * `;`, `{`, `}`) so an ordinary array literal or a `$arr[0]` subscript + * isn't mistaken for a destructuring target. Nested destructuring + * (`list( $a, list( $b, $c ) ) = ...`) only recognizes the outer level's + * own variables — a narrow, accepted gap for a rare shape. The + * statement-start check can also misfire on a `[...] =` that's the first + * top-level statement right after a function definition, since + * godam_coverage_file_findings()'s reindexed top-level token list cuts + * function bodies out — narrow and unlikely in a WordPress plugin. + * + * @param array[] $tokens Token list. + * @param int $i Index to check. + * @param int $count Token count. + * @return string[] Variable names (unprefixed), empty if $i isn't a recognized destructuring target. + */ +function godam_coverage_destructuring_targets_at( $tokens, $i, $count ) { + $is_list_keyword = T_LIST === ( $tokens[ $i ]['id'] ?? null ); + $is_bracket_open = null === ( $tokens[ $i ]['id'] ?? null ) && '[' === $tokens[ $i ]['text']; + + if ( ! $is_list_keyword && ! $is_bracket_open ) { + return array(); + } + + if ( $is_bracket_open ) { + $prev = godam_shared_skip_backward( $tokens, $i - 1 ); + $prev_text = $prev >= 0 ? $tokens[ $prev ]['text'] : ''; + if ( $prev >= 0 && ! in_array( $prev_text, array( ';', '{', '}' ), true ) ) { + return array(); // Not statement-start — an array literal or $arr[...] access, not a destructuring target. + } + } + + $open = $is_list_keyword ? godam_shared_skip_forward( $tokens, $i + 1, $count ) : $i; + if ( $open >= $count || ( '(' !== $tokens[ $open ]['text'] && '[' !== $tokens[ $open ]['text'] ) ) { + return array(); + } + + $targets = array(); + $paren_depth = 0; + $j = $open; + + for ( ; $j < $count; $j++ ) { + $text = $tokens[ $j ]['text']; + + if ( '(' === $text || '[' === $text ) { + ++$paren_depth; + continue; + } + if ( ')' === $text || ']' === $text ) { + --$paren_depth; + if ( 0 === $paren_depth ) { + break; + } + continue; + } + if ( 1 === $paren_depth && T_VARIABLE === ( $tokens[ $j ]['id'] ?? null ) ) { + $targets[] = ltrim( $tokens[ $j ]['text'], '$' ); + } + } + + if ( $j >= $count ) { + return array(); // Unbalanced brackets — bail rather than guess. + } + + $after = godam_shared_skip_forward( $tokens, $j + 1, $count ); + if ( $after >= $count || '=' !== $tokens[ $after ]['text'] ) { + return array(); // Not actually an assignment — e.g. a short-array literal used as a plain expression. + } + + return $targets; +} + +/** + * Thin wrapper around godam_shared_find_functions() — kept as its own + * function in case coverage-specific metadata is ever needed here without + * touching the sibling script. + * + * @param array[] $tokens Normalized tokens from godam_shared_tokenize(). + * @param array[] &$bodyless_declarations Output — see godam_shared_find_functions()'s own docblock. + * @return array[] Each: name, class, visibility, params (string[]), body_start, body_end. + */ +function godam_coverage_find_functions( $tokens, &$bodyless_declarations = array() ) { + return godam_shared_find_functions( $tokens, $bodyless_declarations ); +} + +/** + * Walks a token range tracking before/after balance exactly like + * godam_check_hook_balance_in_range() (same checkpoint-per-'{', + * rewind-on-scope-terminator algorithm), and additionally records every + * access-function call found with nothing open at that point, split into + * 'uncovered' (a non-parameter argument) and 'parameter_sourced' (the + * argument is one of the enclosing scope's own parameters, or a traceable + * alias of one — see godam_coverage_assignment_at()). + * + * Also records, in 'call_sites', every real call to a name in + * $known_call_targets (the codebase-wide set godam_coverage_trace_callers() + * might need to trace a parameter_sourced finding back to its callers), + * with whether a before/after bracket was open there — reusing this same + * walk rather than re-tokenizing the file a second time. + * + * The set of "safe" variable names starts from the enclosing scope's own + * parameters and evolves alongside the scan: a plain, unmodified copy of a + * currently-safe variable extends safety to the new name; any other + * reassignment (including destructuring) revokes it. This tracking has no + * branch-awareness, unlike the before/after balance tracking above — a + * deliberate simplification; safety differing across branches at an access + * call hasn't shown up as a real false positive or negative. + * + * @param array[] $tokens Full token list for the file. + * @param int $range_start Token index to start at (inclusive). + * @param int $range_end Token index to end at (inclusive). + * @param array $params Enclosing function's own parameter names (empty for top-level code). + * @param array $known_call_targets Set (name => true) of function/method names worth recording call sites for. + * @param array[] $skip_ranges Each [start, end] to jump past — deferred closures nested in this + * range, walked independently by godam_coverage_file_findings() + * with a fresh bracket state, since they can run at a different + * time than the function that merely defines them. + * @return array{uncovered: array[], parameter_sourced: array[], call_sites: array[]} + * uncovered/parameter_sourced entries: line, call. + * call_sites entries: name, line, covered (bool), method_style (bool — preceded by -> or ::). + */ +function godam_coverage_check_range( $tokens, $range_start, $range_end, $params, $known_call_targets, $skip_ranges = array() ) { + $open_before_lines = array(); + $checkpoints = array(); + $count = count( $tokens ); + $uncovered = array(); + $parameter_sourced = array(); + $call_sites = array(); + $safe_vars = $params; + + for ( $i = $range_start; $i <= $range_end; $i++ ) { + $jumped = false; + foreach ( $skip_ranges as $skip ) { + if ( $i === $skip[0] ) { + $i = $skip[1]; // The loop's own ++$i then lands just past it. + $jumped = true; + break; + } + } + if ( $jumped ) { + continue; + } + + $text = $tokens[ $i ]['text']; + + if ( '{' === $text ) { + $checkpoints[] = $open_before_lines; + continue; + } + + if ( '}' === $text ) { + array_pop( $checkpoints ); + continue; + } + + if ( godam_shared_is_scope_terminator( $tokens, $i, $count ) ) { + // Rewind to the state when the innermost enclosing block was + // entered — see godam_check_hook_balance_in_range() for the full + // reasoning. That script flags an actual imbalance; this one only + // cares whether access calls are covered, so it always rewinds + // unconditionally rather than also checking the over-open case. + $open_before_lines = empty( $checkpoints ) ? array() : end( $checkpoints ); + continue; + } + + if ( godam_shared_is_hook_fire_at( $tokens, $i, BEFORE_HOOK ) ) { + $open_before_lines[] = $tokens[ $i ]['line']; + continue; + } + + if ( godam_shared_is_hook_fire_at( $tokens, $i, AFTER_HOOK ) ) { + if ( ! empty( $open_before_lines ) ) { + array_pop( $open_before_lines ); + } + continue; + } + + $destructured = godam_coverage_destructuring_targets_at( $tokens, $i, $count ); + if ( ! empty( $destructured ) ) { + $safe_vars = array_values( array_diff( $safe_vars, $destructured ) ); + } + + $assignment = godam_coverage_assignment_at( $tokens, $i, $count ); + if ( null !== $assignment ) { + if ( null !== $assignment['safe_copy_of'] && in_array( $assignment['safe_copy_of'], $safe_vars, true ) ) { + $safe_vars[] = $assignment['target']; + } else { + $safe_vars = array_values( array_diff( $safe_vars, array( $assignment['target'] ) ) ); + } + } + + if ( T_STRING === ( $tokens[ $i ]['id'] ?? null ) && isset( $known_call_targets[ $tokens[ $i ]['text'] ] ) ) { + $n = godam_shared_skip_forward( $tokens, $i + 1, $count ); + if ( $n < $count && '(' === $tokens[ $n ]['text'] ) { + $p = godam_shared_skip_backward( $tokens, $i - 1 ); + + // A function's own declaration tokenizes identically to a call + // to a same-named function (T_STRING followed by '('). Harmless + // for a method (already excluded by the method_style check + // below), but a FREE function's own declaration line would + // otherwise be recorded as a fake call site to itself, always + // resolving as an unrecoverable gap. Also excludes `new + // ClassName(`: a class and a free function can share a bare + // name, and `known_call_targets` is keyed purely by text, so + // `new Helper()` would otherwise be indistinguishable from a + // call to a free function also named Helper. + $preceded_by_new = $p >= 0 && T_NEW === ( $tokens[ $p ]['id'] ?? null ); + + if ( ! $preceded_by_new && ! godam_shared_is_function_declaration_at( $tokens, $i ) ) { + $method_style = $p >= 0 && in_array( $tokens[ $p ]['text'], array( '->', '::' ), true ); + + $call_sites[] = array( + 'name' => $tokens[ $i ]['text'], + 'line' => $tokens[ $i ]['line'], + 'covered' => ! empty( $open_before_lines ), + 'method_style' => $method_style, + ); + } + } + } + + // Query-pattern calls (new WP_Query(), get_posts(), $wpdb->query()- + // style methods) are always treated as "direct" — never parameter- + // sourced, since none of them take a single attachment-ID argument + // to check against a safe-parameter set the way get_post_meta() + // does. + $query_pattern = godam_shared_query_pattern_at( $tokens, $i, $range_start, $range_end, $count ); + if ( null !== $query_pattern ) { + if ( empty( $open_before_lines ) && $query_pattern['is_attachment_shaped'] ) { + $uncovered[] = array( + 'line' => $tokens[ $i ]['line'], + 'call' => $query_pattern['name'], + ); + } + continue; + } + + $access = godam_coverage_access_call_at( $tokens, $i, $count ); + if ( null === $access ) { + $access = godam_coverage_current_user_can_at( $tokens, $i, $count ); + } + if ( null === $access ) { + continue; + } + + if ( ! empty( $open_before_lines ) ) { + continue; // Covered. + } + + if ( '' !== $access['arg'] && in_array( $access['arg'], $safe_vars, true ) ) { + $parameter_sourced[] = array( + 'line' => $tokens[ $i ]['line'], + 'call' => $access['name'], + ); + continue; + } + + $uncovered[] = array( + 'line' => $tokens[ $i ]['line'], + 'call' => $access['name'], + ); + } + + return array( + 'uncovered' => $uncovered, + 'parameter_sourced' => $parameter_sourced, + 'call_sites' => $call_sites, + ); +} + +/** + * Runs godam_coverage_check_range() across an entire file: once per named + * function's own parameter list, once per named function body, once per + * deferred closure (add_action()/add_filter() callback), plus once more + * across whatever top-level code remains — concatenated in file order. + * + * A deferred closure is excluded from its enclosing range and walked as its + * own independent scope (empty bracket state, its own parameters) — it can + * run at a completely different time than the function that defines it. + * Its parameter-sourced findings get fn_name = null: nothing else can call + * an anonymous closure by name, so there's nothing to trace. + * + * A function's own parameter list is walked as a SEPARATE range from its + * body, for a PHP 8.1+ "new in initializers" default value (`function + * search( $query = new WP_Query(...) )`), which sits before body_start and + * would otherwise be mislabeled as top-level code. Merging the two ranges + * into one walk is unsafe: `$query = new WP_Query(...)` looks like a real + * assignment, so godam_coverage_assignment_at() would wrongly revoke + * $query's safety for the rest of the function. The two independent calls + * share no mutable state, so they can't interfere; findings from both are + * merged under the same scope label. + * + * Every parameter-list finding carries 'from_param_list' => true: findings + * are keyed by "{file}:{line}", and a compact one-liner can put a + * parameter-list default and a body call on the same physical line, so the + * flag lets the caller disambiguate without changing the key format for + * every other finding. + * + * $bodyless_declarations gets the same parameter-list treatment as + * $functions, for the same "new in initializers" reason on an + * interface/abstract method's default value. Its findings get fn_name = + * null too: a bodyless declaration is deliberately never added to + * $definitions_by_name (see godam_shared_find_functions()), so there's no + * safe way to trace it as a caller/callee. + * + * @param array[] $tokens Full token list for the file. + * @param array[] $functions This file's own godam_coverage_find_functions() result. + * @param array $known_call_targets Passed straight through to godam_coverage_check_range(). + * @param array[] $bodyless_declarations This file's own godam_coverage_find_functions() by-reference output. + * @return array{uncovered: array[], parameter_sourced: array[], call_sites: array[]} + * uncovered/parameter_sourced entries: line, call, scope ('top-level code', a function + * name, or a deferred-closure label), from_param_list (bool, only ever true). + * call_sites entries: name, line, covered, method_style, scope, enclosing_fn_name (the + * enclosing function/method this call site itself sits inside — null for top-level code + * and for deferred closures, neither of which is callable by name). + */ +function godam_coverage_file_findings( $tokens, $functions, $known_call_targets, $bodyless_declarations = array() ) { + $uncovered = array(); + $parameter_sourced = array(); + $call_sites = array(); + $count = count( $tokens ); + $top_level_indexes = array(); + + $deferred_closures = godam_shared_find_deferred_closures( $tokens, $functions ); + + // Every function's own parameter-list range, plus every bodyless + // declaration's, represented the same way $functions/$deferred_closures + // entries are (body_start/body_end) so godam_shared_ranges_nested_in() + // can treat them identically. + $param_list_ranges = array(); + foreach ( $functions as $function ) { + $param_list_ranges[] = array( + 'body_start' => $function['params_open'], + 'body_end' => $function['params_close'], + ); + } + foreach ( $bodyless_declarations as $bodyless ) { + $param_list_ranges[] = array( + 'body_start' => $bodyless['params_open'], + 'body_end' => $bodyless['params_close'], + ); + } + + // Combines three independent exclusions into one $skip_ranges list, each + // walked separately below with its own state: (a) any deferred closure + // nested inside the range, (b) any OTHER named function/method nested + // inside it, and (c) any function's own parameter-list range nested + // inside it. (b) and (c) matter because function ranges can genuinely + // nest (a method inside a function-scoped anonymous class) — without + // excluding them, the outer walk would re-scan the nested scope's + // tokens under the OUTER function's params/bracket state. + $skip_ranges_for = function ( $range_start, $range_end ) use ( $deferred_closures, $functions, $param_list_ranges ) { + return array_merge( + godam_shared_ranges_nested_in( $range_start, $range_end, $deferred_closures ), + godam_shared_ranges_nested_in( $range_start, $range_end, $functions ), + godam_shared_ranges_nested_in( $range_start, $range_end, $param_list_ranges ) + ); + }; + + for ( $i = 0; $i < $count; $i++ ) { + $inside_a_function = false; + + foreach ( $functions as $function ) { + if ( $i >= $function['body_start'] && $i <= $function['body_end'] ) { + $inside_a_function = true; + break; + } + if ( $i >= $function['params_open'] && $i <= $function['params_close'] ) { + $inside_a_function = true; + break; + } + } + + if ( ! $inside_a_function ) { + foreach ( $bodyless_declarations as $bodyless ) { + if ( $i >= $bodyless['params_open'] && $i <= $bodyless['params_close'] ) { + $inside_a_function = true; + break; + } + } + } + + $inside_a_deferred_closure = false; + foreach ( $deferred_closures as $closure ) { + if ( $i >= $closure['body_start'] && $i <= $closure['body_end'] ) { + $inside_a_deferred_closure = true; + break; + } + } + + if ( ! $inside_a_function && ! $inside_a_deferred_closure ) { + $top_level_indexes[] = $i; + } + } + + foreach ( $functions as $function ) { + $scope = null !== $function['class'] ? "{$function['class']}::{$function['name']}()" : "{$function['name']}()"; + $result = godam_coverage_check_range( $tokens, $function['body_start'], $function['body_end'], $function['params'], $known_call_targets, $skip_ranges_for( $function['body_start'], $function['body_end'] ) ); + + foreach ( $result['uncovered'] as $finding ) { + $finding['scope'] = $scope; + $uncovered[] = $finding; + } + foreach ( $result['parameter_sourced'] as $finding ) { + $finding['scope'] = $scope; + $finding['fn_name'] = $function['name']; + $finding['class'] = $function['class']; + $parameter_sourced[] = $finding; + } + foreach ( $result['call_sites'] as $call_site ) { + $call_site['scope'] = $scope; + $call_site['enclosing_fn_name'] = $function['name']; + $call_sites[] = $call_site; + } + + // The function's own parameter list, walked independently (empty + // params/safe_vars, see this function's own docblock) so a "new in + // initializers" default value is found without sharing mutable + // state with the body walk above. + $param_result = godam_coverage_check_range( $tokens, $function['params_open'], $function['params_close'], array(), $known_call_targets, $skip_ranges_for( $function['params_open'], $function['params_close'] ) ); + + foreach ( $param_result['uncovered'] as $finding ) { + $finding['scope'] = $scope; + $finding['from_param_list'] = true; // See godam_coverage_file_findings()'s own docblock note on this flag. + $uncovered[] = $finding; + } + foreach ( $param_result['parameter_sourced'] as $finding ) { + $finding['scope'] = $scope; + $finding['fn_name'] = $function['name']; + $finding['class'] = $function['class']; + $finding['from_param_list'] = true; + $parameter_sourced[] = $finding; + } + foreach ( $param_result['call_sites'] as $call_site ) { + $call_site['scope'] = $scope; + $call_site['enclosing_fn_name'] = $function['name']; + $call_sites[] = $call_site; + } + } + + // Every bodyless declaration's own parameter list — same independent, + // empty-params walk as a regular function's, for the same "new in + // initializers" reason. fn_name is always null: a bodyless declaration + // is deliberately never added to $definitions_by_name (see + // godam_shared_find_functions()'s docblock), so there's no safe name to + // trace a finding through. + foreach ( $bodyless_declarations as $bodyless ) { + $scope = null !== $bodyless['class'] ? "{$bodyless['class']}::{$bodyless['name']}()" : "{$bodyless['name']}()"; + $param_result = godam_coverage_check_range( $tokens, $bodyless['params_open'], $bodyless['params_close'], array(), $known_call_targets, $skip_ranges_for( $bodyless['params_open'], $bodyless['params_close'] ) ); + + foreach ( $param_result['uncovered'] as $finding ) { + $finding['scope'] = $scope; + $finding['from_param_list'] = true; + $uncovered[] = $finding; + } + foreach ( $param_result['parameter_sourced'] as $finding ) { + $finding['scope'] = $scope; + $finding['fn_name'] = null; + $finding['class'] = null; + $finding['from_param_list'] = true; + $parameter_sourced[] = $finding; + } + foreach ( $param_result['call_sites'] as $call_site ) { + $call_site['scope'] = $scope; + $call_site['enclosing_fn_name'] = null; + $call_sites[] = $call_site; + } + } + + foreach ( $deferred_closures as $closure ) { + $scope = null !== $closure['hook_name'] + ? "closure registered for '{$closure['hook_name']}' via add_action/add_filter()" + : 'closure registered via add_action/add_filter()'; + $result = godam_coverage_check_range( $tokens, $closure['body_start'], $closure['body_end'], $closure['params'], $known_call_targets, $skip_ranges_for( $closure['body_start'], $closure['body_end'] ) ); + + foreach ( $result['uncovered'] as $finding ) { + $finding['scope'] = $scope; + $uncovered[] = $finding; + } + foreach ( $result['parameter_sourced'] as $finding ) { + $finding['scope'] = $scope; + $finding['fn_name'] = null; // Anonymous — nothing else can call it by name, so it can't be traced to a caller. + $finding['class'] = null; + $parameter_sourced[] = $finding; + } + foreach ( $result['call_sites'] as $call_site ) { + $call_site['scope'] = $scope; + $call_site['enclosing_fn_name'] = null; + $call_sites[] = $call_site; + } + } + + if ( ! empty( $top_level_indexes ) ) { + $top_level_tokens = array_values( array_intersect_key( $tokens, array_flip( $top_level_indexes ) ) ); + $result = godam_coverage_check_range( $top_level_tokens, 0, count( $top_level_tokens ) - 1, array(), $known_call_targets ); + + foreach ( $result['uncovered'] as $finding ) { + $finding['scope'] = 'top-level code'; + $uncovered[] = $finding; + } + foreach ( $result['parameter_sourced'] as $finding ) { + $finding['scope'] = 'top-level code'; + $finding['fn_name'] = null; + $finding['class'] = null; + $parameter_sourced[] = $finding; + } + foreach ( $result['call_sites'] as $call_site ) { + $call_site['scope'] = 'top-level code'; + $call_site['enclosing_fn_name'] = null; // Top-level code is never itself "called" — see godam_coverage_trace_callers(). + $call_sites[] = $call_site; + } + } + + return array( + 'uncovered' => $uncovered, + 'parameter_sourced' => $parameter_sourced, + 'call_sites' => $call_sites, + ); +} + +/** + * Recursively (with memoization and cycle-breaking) determines whether + * every real invocation of a codebase-wide-uniquely-named function/method + * is guaranteed to happen with a rtgodam_before_attachment_lookup bracket + * already open — either locally, or because the call site sits inside + * ANOTHER function that is itself always invoked under a bracket, + * arbitrarily many levels deep. + * + * Correct for an ARBITRARY number of hops because the recursion only asks + * "how is this function invoked," never "does this function touch + * attachment data." A fixed-depth or iterative version asking the latter + * would fail on a PURE forwarding function (no access call of its own): it + * could never resolve as "itself always covered," so any deeper call + * reached through it would be wrongly reported as a confirmed gap. + * + * Deliberately conservative regardless of chain depth: a name is only + * ever resolved automatically when it's unique across the entire + * codebase. A same-named method on an unrelated class is common in a + * WordPress plugin (render(), get_instance(), setup_hooks() all recur + * here), and a text-level search can't tell "a call to ClassA::render()" + * from "a call to ClassB::render()" — so an ambiguous name resolves to + * 'unknown' for a human to check. + * + * For a unique name, call sites are filtered to the shape its definition + * could actually be called through: + * - `private` method: only `$this->name(`/`self::name(`/`static::name(` + * sites, within the definition's own 'allowed_files' — ordinarily just + * its own file, but widened to every file that `use`s the trait when + * the method is defined inside a trait (see Pass 1 below). + * - non-private method: any `->name(`/`::name(` call site, anywhere. + * - free function: any bare `name(` call site, anywhere. + * + * Cycles are broken via $in_progress: hitting a name already being + * resolved higher up the call stack returns 'unknown' for that edge + * WITHOUT memoizing it, so the surrounding resolution can still finish + * using its other, non-cyclic call sites. Expected to be rare in + * practice — WordPress hook callbacks and REST routes are the real entry + * points here, not functions calling each other in a loop. + * + * @param string $name Bare function/method name to resolve. + * @param array $definitions_by_name Name => list of {file, class, visibility}. + * @param array $call_sites_by_name Name => list of call sites {file, line, covered, method_style, enclosing_fn_name}. + * @param array &$memo name => resolution result (see return shape). Shared across the whole trace; populated lazily. + * @param array &$in_progress Set (name => true) of names currently being resolved higher up the recursion stack. + * @return array{status: string, problem_candidates: array[], reason: string|null} status is 'covered'|'gap'|'unknown'. + */ +function godam_coverage_resolve_coverage( $name, $definitions_by_name, $call_sites_by_name, &$memo, &$in_progress ) { + if ( isset( $memo[ $name ] ) ) { + return $memo[ $name ]; + } + + if ( isset( $in_progress[ $name ] ) ) { + return array( + 'status' => 'unknown', + 'problem_candidates' => array(), + 'reason' => "circular caller relationship involving {$name}() — verify manually.", + ); + } + + $definitions = $definitions_by_name[ $name ] ?? array(); + + if ( 1 !== count( $definitions ) ) { + $result = array( + 'status' => 'unknown', + 'problem_candidates' => array(), + 'reason' => count( $definitions ) > 1 + ? sprintf( '%d functions/methods named %s() exist codebase-wide — call-graph tracing skipped to avoid a cross-class mismatch.', count( $definitions ), $name ) + : 'enclosing function/method definition not found (should not happen — tracing skipped defensively).', + ); + $memo[ $name ] = $result; + return $result; + } + + $definition = $definitions[0]; + $candidates = array(); + + foreach ( ( $call_sites_by_name[ $name ] ?? array() ) as $call_site ) { + if ( null === $definition['class'] ) { + // Free function: only a bare call is a real match; -> / :: means + // this text match is an unrelated method with the same name. + if ( ! $call_site['method_style'] ) { + $candidates[] = $call_site; + } + continue; + } + + // Method: only a -> / :: call is a real match. + if ( ! $call_site['method_style'] ) { + continue; + } + + if ( 'private' === $definition['visibility'] && ! in_array( $call_site['file'], $definition['allowed_files'], true ) ) { + continue; // Structurally uncallable from outside its own file (or, for a trait method, its consumer files). + } + + $candidates[] = $call_site; + } + + if ( empty( $candidates ) ) { + $result = array( + 'status' => 'unknown', + 'problem_candidates' => array(), + 'reason' => 'no caller found via static call-site search — may be a hook callback registered by name/array-callback, or genuinely unused code.', + ); + $memo[ $name ] = $result; + return $result; + } + + $in_progress[ $name ] = true; + + $problem_candidates = array(); + $any_unknown = false; + + foreach ( $candidates as $candidate ) { + if ( $candidate['covered'] ) { + continue; // Locally bracketed — definitely fine, no recursion needed. + } + + $enclosing = $candidate['enclosing_fn_name']; + + if ( null === $enclosing ) { + // Top-level code, not locally bracketed — there's no further + // caller to check (top-level code isn't itself "invoked" the + // way a function is), so this path is a definite gap. + $problem_candidates[] = $candidate; + continue; + } + + $enclosing_result = godam_coverage_resolve_coverage( $enclosing, $definitions_by_name, $call_sites_by_name, $memo, $in_progress ); + + if ( 'covered' === $enclosing_result['status'] ) { + continue; // This call inherits coverage from its own always-bracketed caller. + } + + if ( 'gap' === $enclosing_result['status'] ) { + $problem_candidates[] = $candidate; + continue; + } + + $any_unknown = true; + } + + unset( $in_progress[ $name ] ); + + if ( ! empty( $problem_candidates ) ) { + $result = array( + 'status' => 'gap', + 'problem_candidates' => $problem_candidates, + 'reason' => null, + ); + } elseif ( $any_unknown ) { + $result = array( + 'status' => 'unknown', + 'problem_candidates' => array(), + 'reason' => 'coverage depends on a caller this trace could not fully resolve — verify manually.', + ); + } else { + $result = array( + 'status' => 'covered', + 'problem_candidates' => array(), + 'reason' => null, + ); + } + + $memo[ $name ] = $result; + return $result; +} + +/** + * Recursively (with memoization and cycle-breaking) resolves every file a + * private trait method defined in $trait_name could actually be called + * from: every class that directly `use`s the trait, plus — for any such + * consumer that is itself a trait — every file that transitively consumes + * THAT trait too. + * + * Needed because trait composition genuinely nests: trait B can `use` + * trait A, and class C can `use` trait B. A private method in A is + * reachable from C, but C's file never appears in A's own direct + * $trait_consumers entry — only B's file does. Resolving only one level + * would miss C's file entirely, the same gap 'allowed_files' exists to + * close for the single-level case. No multi-level trait usage exists in + * this codebase today — this only guards against a future one. + * + * Same recursive/memoized/cycle-breaking shape as + * godam_coverage_resolve_coverage() above (a different graph — trait-uses- + * trait, not caller-calls-callee). A cycle breaks via $visiting, + * contributing no further files for that edge, without infinite recursion. + * + * @param string $trait_name Bare trait name to resolve. + * @param array $trait_consumers Trait name => list of {class, file} — every file's own, direct (one-hop) consumers. + * @param array $is_trait_by_name Class/trait name => bool. + * @param array &$memo trait name => fully-resolved file list. Shared across the whole trace; populated lazily. + * @param array &$visiting Set (trait name => true) of names currently being resolved higher up the recursion stack. + * @return string[] Every file (deduplicated) whose class could reach a method defined in $trait_name via `use`, directly or transitively. + */ +function godam_coverage_resolve_trait_consumer_files( $trait_name, $trait_consumers, $is_trait_by_name, &$memo, &$visiting ) { + if ( isset( $memo[ $trait_name ] ) ) { + return $memo[ $trait_name ]; + } + + if ( isset( $visiting[ $trait_name ] ) ) { + return array(); // Cycle — contribute nothing further for this edge rather than recurse forever. + } + + $visiting[ $trait_name ] = true; + + $files = array(); + foreach ( ( $trait_consumers[ $trait_name ] ?? array() ) as $consumer ) { + $files[] = $consumer['file']; + + if ( ! empty( $is_trait_by_name[ $consumer['class'] ] ) ) { + $files = array_merge( $files, godam_coverage_resolve_trait_consumer_files( $consumer['class'], $trait_consumers, $is_trait_by_name, $memo, $visiting ) ); + } + } + + unset( $visiting[ $trait_name ] ); + + $files = array_values( array_unique( $files ) ); + $memo[ $trait_name ] = $files; + return $files; +} + +/** + * Runs godam_coverage_resolve_coverage() for every parameter-sourced + * finding's own enclosing function, and sorts the findings into the three + * outcomes that function's 'status' can produce. Top-level-code findings + * (fn_name === null) bypass the resolver entirely — top-level code is never + * itself invoked the way a function is, so there's nothing to trace. + * + * @param array[] $parameter_sourced Every parameter_sourced finding across all files, each already + * carrying 'file', 'line', 'call', 'scope', 'fn_name', 'class'. + * @param array[] $call_sites Every recorded call site across all files, each carrying + * 'file', 'name', 'line', 'covered', 'method_style', 'scope', + * 'enclosing_fn_name' (null for top-level code). + * @param array[] $definitions_by_name Name => list of {file, class, visibility}, one entry per + * function/method definition sharing that bare name anywhere. + * @return array{confirmed: array[], unverified: array[], transitively_covered: array[]} + */ +function godam_coverage_trace_callers( $parameter_sourced, $call_sites, $definitions_by_name ) { + $call_sites_by_name = array(); + foreach ( $call_sites as $call_site ) { + $call_sites_by_name[ $call_site['name'] ][] = $call_site; + } + + $memo = array(); + $in_progress = array(); + + $confirmed = array(); + $unverified = array(); + $transitively_covered = array(); + + foreach ( $parameter_sourced as $finding ) { + if ( null === $finding['fn_name'] ) { + $finding['reason_unverified'] = 'top-level code' === $finding['scope'] + ? 'top-level code — coverage cannot be traced to a caller.' + : 'an anonymous closure — nothing else can call it by name, so coverage cannot be traced to a caller; only WordPress itself, via whichever hook it\'s registered for, ever actually invokes it.'; + $unverified[] = $finding; + continue; + } + + $result = godam_coverage_resolve_coverage( $finding['fn_name'], $definitions_by_name, $call_sites_by_name, $memo, $in_progress ); + + if ( 'covered' === $result['status'] ) { + $transitively_covered[] = $finding; + } elseif ( 'gap' === $result['status'] ) { + $finding['uncovered_callers'] = $result['problem_candidates']; + $confirmed[] = $finding; + } else { + $finding['reason_unverified'] = $result['reason']; + $unverified[] = $finding; + } + } + + return array( + 'confirmed' => $confirmed, + 'unverified' => $unverified, + 'transitively_covered' => $transitively_covered, + ); +} + +// --- Pass 1: tokenize every file once, find every function/method definition. --- +// +// 1a walks every file first to build two codebase-wide maps before any +// per-function work starts: which class/trait names are actually traits, +// and which files `use` each trait. Needed up front because a trait's +// consumers can be discovered in a file scanned AFTER the trait's own +// definition — 1b can't know a private trait method's real allowed files +// until every file has been looked at once. + +$root = dirname( __DIR__, 2 ); // Plugin root — this file lives two levels under it, in bin/hook-check/. +$files = godam_shared_list_all_php_files( $root ); + +$file_tokens = array(); +$file_classes = array(); +$is_trait_by_class_name = array(); +$trait_consumers = array(); // trait_name => list of {class, file} — every file's own, direct (one-hop) consumers. + +foreach ( $files as $file ) { + $tokens = godam_shared_tokenize( $file ); + $relative = ltrim( str_replace( $root, '', $file ), DIRECTORY_SEPARATOR ); + $classes = godam_shared_find_classes( $tokens ); + + $file_tokens[ $relative ] = $tokens; + $file_classes[ $relative ] = $classes; + + foreach ( $classes as $class ) { + $is_trait_by_class_name[ $class['name'] ] = $class['is_trait']; + } + + foreach ( godam_shared_find_trait_uses( $tokens, $classes ) as $trait_name => $consumer_classes ) { + foreach ( $consumer_classes as $consumer_class ) { + $trait_consumers[ $trait_name ][] = array( + 'class' => $consumer_class, + 'file' => $relative, + ); + } + } +} + +// 1b: per-function definitions, now that trait consumership is fully known. +$file_functions = array(); +$file_bodyless_declarations = array(); +$definitions_by_name = array(); +$trait_file_memo = array(); +$trait_file_visiting = array(); + +foreach ( $file_tokens as $relative => $tokens ) { + $bodyless = array(); + $functions = godam_coverage_find_functions( $tokens, $bodyless ); + $file_functions[ $relative ] = $functions; + $file_bodyless_declarations[ $relative ] = $bodyless; + + foreach ( $functions as $function ) { + $allowed_files = array( $relative ); + + if ( null !== $function['class'] && ! empty( $is_trait_by_class_name[ $function['class'] ] ) ) { + // A private trait method is only reachable from whichever class + // `use`s the trait, which can be a different file (and, when + // composition nests, more than one hop away — see + // godam_coverage_resolve_trait_consumer_files()). Widening + // allowed_files to every consumer file is what lets a private + // trait method's real callers be found at all. + $consumer_files = godam_coverage_resolve_trait_consumer_files( $function['class'], $trait_consumers, $is_trait_by_class_name, $trait_file_memo, $trait_file_visiting ); + $allowed_files = array_values( array_unique( array_merge( $allowed_files, $consumer_files ) ) ); + } + + $definitions_by_name[ $function['name'] ][] = array( + 'file' => $relative, + 'class' => $function['class'], + 'visibility' => $function['visibility'], + 'allowed_files' => $allowed_files, + ); + } +} + +$known_call_targets = array_fill_keys( array_keys( $definitions_by_name ), true ); + +// --- Pass 2: coverage + call-site discovery, reusing the cached tokens. --- + +$uncovered_findings = array(); // Keyed by file:line (or file:line:params — see below). +$parameter_sourced = array(); // Flat list, each carrying its own 'file'. +$all_call_sites = array(); // Flat list, each carrying its own 'file'. + +foreach ( $file_tokens as $relative => $tokens ) { + $result = godam_coverage_file_findings( $tokens, $file_functions[ $relative ], $known_call_targets, $file_bodyless_declarations[ $relative ] ); + + foreach ( $result['uncovered'] as $finding ) { + // A parameter-list finding gets a distinct ":params" key suffix so it + // can't collide with a body-level finding on the same physical line — + // routine for a compact one-liner like `function search( $query = new + // WP_Query(...) ) { get_post_meta(...); }`. + $key = ! empty( $finding['from_param_list'] ) ? "{$relative}:{$finding['line']}:params" : "{$relative}:{$finding['line']}"; + $uncovered_findings[ $key ] = array( + 'file' => $relative, + 'line' => $finding['line'], + 'call' => $finding['call'], + 'scope' => $finding['scope'], + 'kind' => FINDING_KIND_DIRECT, + ); + } + + foreach ( $result['parameter_sourced'] as $finding ) { + $finding['file'] = $relative; + $parameter_sourced[] = $finding; + } + + foreach ( $result['call_sites'] as $call_site ) { + $call_site['file'] = $relative; + $all_call_sites[] = $call_site; + } +} + +// --- Pass 3: reconcile parameter-sourced findings via the recursive call-graph trace. --- + +$traced = godam_coverage_trace_callers( $parameter_sourced, $all_call_sites, $definitions_by_name ); + +foreach ( $traced['confirmed'] as $finding ) { + $key = "{$finding['file']}:{$finding['line']}"; + $first = $finding['uncovered_callers'][0]; + + $uncovered_findings[ $key ] = array( + 'file' => $finding['file'], + 'line' => $finding['line'], + 'call' => $finding['call'], + 'scope' => $finding['scope'], + 'kind' => FINDING_KIND_CALLER_CONFIRMED, + 'caller_file' => $first['file'], + 'caller_line' => $first['line'], + 'caller_count' => count( $finding['uncovered_callers'] ), + ); +} + +$unverified_findings = array(); +foreach ( $traced['unverified'] as $finding ) { + $key = "{$finding['file']}:{$finding['line']}"; + + $unverified_findings[ $key ] = array( + 'file' => $finding['file'], + 'line' => $finding['line'], + 'call' => $finding['call'], + 'scope' => $finding['scope'], + 'kind' => FINDING_KIND_UNVERIFIED, + 'detail' => $finding['reason_unverified'], + ); +} + +ksort( $uncovered_findings ); +ksort( $unverified_findings ); + +// The two dicts never share a key (a parameter_sourced finding is, by +// definition, excluded from the direct uncovered pass), so a plain array +// union keeps both without a collision risk to reason about. +$findings = $uncovered_findings + $unverified_findings; + +// --- Pass 4: apply inline godam-coverage-ignore/disable/enable/ignore-file +// comments — checked once per file so a finding's own line is looked up in +// O(1) instead of re-scanning every file per finding. This is the *only* +// acceptance mechanism — there is no baseline file to fall back to. --- + +$directives_by_file = array(); +foreach ( $file_tokens as $relative => $tokens ) { + $directives_by_file[ $relative ] = godam_shared_coverage_directives( $tokens ); +} + +// A disable with no matching enable is a hard error: left alone, it would +// silently suppress every finding for the rest of the file with no +// human-reviewed reason at all. +$dangling_disables = array(); +foreach ( $directives_by_file as $relative => $directives ) { + if ( null !== $directives['dangling_disable'] ) { + $dangling_disables[ $relative ] = $directives['dangling_disable']; + } +} + +$directive_covered = array(); +foreach ( $findings as $key => $finding ) { + $directives = $directives_by_file[ $finding['file'] ] ?? null; + if ( null === $directives ) { + continue; + } + + if ( null !== $directives['ignore_file'] ) { + $directive_covered[ $key ] = $directives['ignore_file']; + continue; + } + + $reason = godam_shared_coverage_directive_covers( $directives, $finding['line'] ); + if ( null !== $reason ) { + $directive_covered[ $key ] = $reason; + } +} + +$findings = array_diff_key( $findings, $directive_covered ); + +if ( ! empty( $dangling_disables ) ) { + fwrite( STDERR, "DANGLING godam-coverage-disable — no matching godam-coverage-enable found\n" ); + fwrite( STDERR, "before end of file. This would otherwise silently suppress every finding\n" ); + fwrite( STDERR, "for the rest of the file with no reviewed reason at all:\n\n" ); + foreach ( $dangling_disables as $relative => $disable ) { + fwrite( STDERR, " - {$relative}:{$disable['line']} -- {$disable['reason']}\n" ); + } + fwrite( STDERR, "\nAdd a matching // godam-coverage-enable comment, or remove the disable if it's no longer needed.\n" ); + exit( 1 ); +} + +$direct = array_filter( + $findings, + function ( $f ) { + return FINDING_KIND_UNVERIFIED !== $f['kind']; + } +); +$unverified = array_filter( + $findings, + function ( $f ) { + return FINDING_KIND_UNVERIFIED === $f['kind']; + } +); + +echo 'Uncovered/unverified call sites: ' . count( $findings ) . "\n"; +echo 'Auto-resolved as transitively covered (no action needed): ' . count( $traced['transitively_covered'] ) . "\n"; +echo 'Suppressed via inline godam-coverage-ignore/disable/ignore-file comments: ' . count( $directive_covered ) . "\n\n"; + +$exit_code = 0; + +if ( ! empty( $direct ) ) { + $exit_code = 1; + echo "CONFIRMED UNCOVERED ACCESS CALLS:\n"; + foreach ( $direct as $key => $finding ) { + echo " - {$finding['file']}:{$finding['line']} in {$finding['scope']}: {$finding['call']}() runs with no\n"; + echo ' rtgodam_before_attachment_lookup open.'; + if ( FINDING_KIND_CALLER_CONFIRMED === $finding['kind'] ) { + echo " Confirmed via a real caller: {$finding['caller_file']}:{$finding['caller_line']}\n"; + echo " doesn't wrap this call either" . ( $finding['caller_count'] > 1 ? " ({$finding['caller_count']} uncovered callers total)" : '' ) . '.'; + } + echo "\n Add the hook pair around it, or if this call genuinely isn't attachment data\n"; + echo " needing centralization, add a // godam-coverage-ignore -- reason comment (see\n"; + echo " this script's own top-of-file comment for the exact syntax).\n\n"; + } +} + +if ( ! empty( $unverified ) ) { + $exit_code = 1; + echo "UNVERIFIED PARAMETER-SOURCED CALLS (coverage depends on a caller this script\n"; + echo "couldn't confirm — needs a human to check, not a proven gap):\n"; + foreach ( $unverified as $key => $finding ) { + echo " - {$finding['file']}:{$finding['line']} in {$finding['scope']}: {$finding['call']}() — {$finding['detail']}\n\n"; + } +} + +if ( 0 !== $exit_code ) { + echo "This script cannot prove a call site needs centralizing — see its own\n"; + echo "top-of-file comment for what it can and can't detect. A human still needs\n"; + echo "to read each finding above.\n"; + exit( $exit_code ); +} + +echo "No uncovered or unverified attachment-access call sites found.\n"; +exit( 0 ); diff --git a/bin/hook-check/pre-commit.sh b/bin/hook-check/pre-commit.sh new file mode 100755 index 0000000000..4d77f59355 --- /dev/null +++ b/bin/hook-check/pre-commit.sh @@ -0,0 +1,65 @@ +#!/bin/sh +# +# Blocks a commit that touches GoDAM's own attachment-handling code without +# keeping the rtgodam_before_attachment_lookup / rtgodam_after_attachment_lookup +# hook pair intact and balanced. +# +# Runs the same two checks as +# .github/workflows/wp_dam_hook_integrity_on_pull_request.yml — see that +# workflow and each check script's own top-of-file comment for what they can +# and can't catch. Scoped to the same paths that workflow watches; anything +# else exits immediately without running PHP at all. +# +# Invoked directly from .husky/pre-commit, after `npm run lint:staged`. +# +# Scoped to .php files specifically — both check scripts only ever tokenize +# .php files (see godam_shared_list_php_files() in shared.php), so a commit +# touching only a block's .js/.scss/.json can't contain anything either +# script would look at. +# +# Deny-list, mirroring GODAM_EXCLUDED_ROOT_DIRS in shared.php and the +# workflow's own path filter — an allow-list of specific directories here +# previously meant a commit touching godam.php, lib/, or any new top-level +# directory would silently skip this check entirely. Two grep passes +# (rather than one regex with a negative lookahead) so this stays portable +# to macOS's BSD grep, which has no -P/PCRE support. + +STAGED_FILES=$(git diff --cached --name-only) + +STAGED_PHP_FILES=$(echo "$STAGED_FILES" | grep -E '\.php$' | grep -Ev '^(\.git|\.github|\.husky|\.idea|node_modules|tests|languages|bin)/') +STAGED_HOOK_CHECK_FILES=$(echo "$STAGED_FILES" | grep -E '^bin/hook-check/.*\.php$') + +if [ -z "$STAGED_PHP_FILES" ] && [ -z "$STAGED_HOOK_CHECK_FILES" ]; then + exit 0 +fi + +if ! command -v php >/dev/null 2>&1; then + echo "" + echo "godam-hook-check: 'php' not found on PATH, so the wp-dam hook-integrity" + echo "checks can't run. This commit touches attachment-handling code, so" + echo "blocking rather than committing unchecked — make sure the PHP CLI is" + echo "available and commit again." + echo "" + exit 1 +fi + +echo "" +echo "Running wp-dam hook-integrity checks (staged changes touch tracked paths)..." +echo "" + +status=0 +php bin/hook-check/balance.php check || status=1 +php bin/hook-check/coverage.php check || status=1 + +if [ "$status" -ne 0 ]; then + echo "" + echo "godam-hook-check: commit blocked by the failure(s) above." + echo "If this is a reviewed, intentional change (not a missed or malformed" + echo "hook), add a // godam-coverage-ignore/-disable/-enable/-ignore-file" + echo "comment at the call site (see either script's own top-of-file comment" + echo "for the exact syntax), stage the change, and commit again." + echo "" + exit 1 +fi + +exit 0 diff --git a/bin/hook-check/shared.php b/bin/hook-check/shared.php new file mode 100644 index 0000000000..01e525254c --- /dev/null +++ b/bin/hook-check/shared.php @@ -0,0 +1,1556 @@ +getPathname(); + + if ( strpos( $path, DIRECTORY_SEPARATOR . 'build' . DIRECTORY_SEPARATOR ) !== false ) { + continue; // Compiled block output — not hand-hookable, out of scope. + } + + if ( strpos( $path, DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR ) !== false ) { + continue; // Third-party libraries, not GoDAM's own code. + } + + if ( 'php' === strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ) ) { + $files[] = $path; + } + } + + return $files; +} + +/** + * Top-level directories (root only, not matched deeper) that never hold + * hand-hookable plugin code — a deny-list, not an include-list, so a new + * top-level directory is scanned by default rather than staying invisible. + * `build`/`vendor` are already excluded at any depth; these are root-only + * since they're not expected to recur as nested directory names. + * + * @var string[] + */ +const GODAM_EXCLUDED_ROOT_DIRS = array( + '.git', + '.github', + '.husky', + '.idea', + 'node_modules', + 'tests', + 'bin', // This tooling's own scripts — not plugin runtime code. + 'languages', +); + +/** + * Recursively lists every .php file under the plugin root, excluding + * GODAM_EXCLUDED_ROOT_DIRS (root level only) plus the build/vendor + * exclusions godam_shared_list_php_files() applies at any depth. + * + * @param string $plugin_root Absolute path to the plugin root. + * @return string[] Absolute file paths. + */ +function godam_shared_list_all_php_files( $plugin_root ) { + $files = array(); + + foreach ( scandir( $plugin_root ) as $entry ) { + if ( '.' === $entry || '..' === $entry ) { + continue; + } + + $path = $plugin_root . DIRECTORY_SEPARATOR . $entry; + + if ( is_dir( $path ) ) { + if ( in_array( $entry, GODAM_EXCLUDED_ROOT_DIRS, true ) ) { + continue; + } + $files = array_merge( $files, godam_shared_list_php_files( $path ) ); + continue; + } + + if ( 'php' === strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ) ) { + $files[] = $path; // Root-level file, e.g. godam.php. + } + } + + return $files; +} + +/** + * Tokenizes a file into a flat list of ['id' => int|null, 'text' => string, + * 'line' => int], normalizing token_get_all()'s mix of arrays (named tokens) + * and bare strings (single-char tokens) into one consistent shape. + * + * @param string $file Absolute file path. + * @return array[] + */ +function godam_shared_tokenize( $file ) { + $contents = file_get_contents( $file ); + + if ( false === $contents ) { + return array(); + } + + $raw_tokens = token_get_all( $contents ); + $normalized = array(); + $line = 1; + + foreach ( $raw_tokens as $token ) { + if ( is_array( $token ) ) { + list( $id, $text, $token_line ) = $token; + $normalized[] = array( + 'id' => $id, + 'text' => $text, + 'line' => $token_line, + ); + $line = $token_line + substr_count( $text, "\n" ); + } else { + $normalized[] = array( + 'id' => null, + 'text' => $token, + 'line' => $line, + ); + $line += substr_count( $token, "\n" ); + } + } + + return $normalized; +} + +/** + * Skips whitespace/comment tokens forward from $i, returning the next + * meaningful index (or $count if none remain). + * + * @param array[] $tokens Token list. + * @param int $i Start index (checked first). + * @param int $count Token count. + * @return int + */ +function godam_shared_skip_forward( $tokens, $i, $count ) { + while ( $i < $count && in_array( $tokens[ $i ]['id'], GODAM_SKIPPABLE_TOKENS, true ) ) { + ++$i; + } + return $i; +} + +/** + * Skips whitespace/comment tokens backward from $i, returning the previous + * meaningful index (or -1 if none remain). + * + * @param array[] $tokens Token list. + * @param int $i Start index (checked first). + * @return int + */ +function godam_shared_skip_backward( $tokens, $i ) { + while ( $i >= 0 && in_array( $tokens[ $i ]['id'], GODAM_SKIPPABLE_TOKENS, true ) ) { + --$i; + } + return $i; +} + +/** + * Recognizes one of the four godam-coverage-* directive comments — mirrors + * phpcs:ignore/disable/enable/ignoreFile, minus a rule-code argument (each + * checker here only ever checks one thing). Checked in this order so + * "godam-coverage-ignore-file" is never misidentified as a plain "ignore". + * + * @param array[] $tokens Full token list for the file. + * @param int $i Index to check. + * @return array{directive: string, reason: string}|null One of + * 'ignore-file'/'disable'/'enable'/'ignore', or null if this token + * isn't a comment or doesn't contain a directive. + */ +function godam_shared_coverage_directive_at( $tokens, $i ) { + $id = $tokens[ $i ]['id'] ?? null; + if ( T_COMMENT !== $id && T_DOC_COMMENT !== $id ) { + return null; + } + + $text = $tokens[ $i ]['text']; + + $patterns = array( + 'ignore-file' => '/godam-coverage-ignore-file\b\s*(?:--\s*(.*))?/', + 'disable' => '/godam-coverage-disable\b\s*(?:--\s*(.*))?/', + 'enable' => '/godam-coverage-enable\b\s*(?:--\s*(.*))?/', + 'ignore' => '/godam-coverage-ignore\b\s*(?:--\s*(.*))?/', + ); + + foreach ( $patterns as $directive => $pattern ) { + if ( preg_match( $pattern, $text, $m ) ) { + $reason = trim( $m[1] ?? '' ); + return array( + 'directive' => $directive, + 'reason' => '' !== $reason ? $reason : '(no reason given)', + ); + } + } + + return null; +} + +/** + * Scans a file's tokens for godam-coverage-ignore/disable/enable/ignore-file + * comments and returns what they cover. Shared by both checker scripts so + * one comment suppresses both. + * + * `godam-coverage-ignore` follows phpcs:ignore's own placement rule: as a + * trailing comment it covers that same line; alone on its own line, it + * covers the line after. `godam-coverage-disable`/`-enable` bracket a + * range exclusive of both endpoints; multiple pairs per file are tracked. + * + * A disable with no matching enable before end of file is a hard error + * (see 'dangling_disable') rather than silently suppressing the rest of + * the file — the same footgun a forgotten phpcs:enable has in real phpcs. + * + * @param array[] $tokens Full token list for the file. + * @return array{ + * ignore_file: string|null, + * ignore_lines: array, + * disabled_ranges: array, + * dangling_disable: array{line:int, reason:string}|null, + * } + */ +function godam_shared_coverage_directives( $tokens ) { + $ignore_file = null; + $ignore_lines = array(); + $disabled_ranges = array(); + $open_disable = null; + + $count = count( $tokens ); + + for ( $i = 0; $i < $count; $i++ ) { + $directive = godam_shared_coverage_directive_at( $tokens, $i ); + if ( null === $directive ) { + continue; + } + + $line = $tokens[ $i ]['line']; + + switch ( $directive['directive'] ) { + case 'ignore-file': + $ignore_file = $directive['reason']; + break; + + case 'disable': + // A later, still-unclosed disable simply replaces the + // tracked start — only the last one can end up dangling. + $open_disable = array( + 'line' => $line, + 'reason' => $directive['reason'], + ); + break; + + case 'enable': + if ( null !== $open_disable ) { + $disabled_ranges[] = array( + 'start' => $open_disable['line'], + 'end' => $line, + 'reason' => $open_disable['reason'], + ); + $open_disable = null; + } + break; + + case 'ignore': + $prev = godam_shared_skip_backward( $tokens, $i - 1 ); + $same_line = $prev >= 0 && $tokens[ $prev ]['line'] === $line; + $target_line = $same_line ? $line : $line + 1; + + $ignore_lines[ $target_line ] = $directive['reason']; + break; + } + } + + return array( + 'ignore_file' => $ignore_file, + 'ignore_lines' => $ignore_lines, + 'disabled_ranges' => $disabled_ranges, + 'dangling_disable' => $open_disable, + ); +} + +/** + * Whether $line is covered by an ignore/disable directive already parsed + * into $directives (see godam_shared_coverage_directives()) — checks + * ignore_lines and disabled_ranges, NOT ignore_file (a whole-file ignore is + * cheaper to check once per file than once per line; callers already do). + * + * @param array $directives Result of godam_shared_coverage_directives(). + * @param int $line Line to check. + * @return string|null The reason text if covered, null otherwise. + */ +function godam_shared_coverage_directive_covers( $directives, $line ) { + if ( isset( $directives['ignore_lines'][ $line ] ) ) { + return $directives['ignore_lines'][ $line ]; + } + + foreach ( $directives['disabled_ranges'] as $range ) { + if ( $line > $range['start'] && $line < $range['end'] ) { + return $range['reason']; + } + } + + return null; +} + +/** + * Strips namespace qualification from $text, returning its final segment — + * "get_post_meta" from "\get_post_meta" or "Foo\Bar\get_post_meta" alike. + * + * PHP 8 tokenizes an entire qualified name as one T_NAME_FULLY_QUALIFIED/ + * T_NAME_QUALIFIED token, so a plain `ltrim( $text, '\\' )` only strips a + * leading backslash and still gets "Foo\get_post_meta" wrong. + * + * @param string $text Token text (already namespace-qualified or not). + * @return string + */ +function godam_shared_unqualified_name( $text ) { + return substr( strrchr( '\\' . ltrim( $text, '\\' ), '\\' ), 1 ); +} + +/** + * Whether the token at $i is a real call to one of $names: a T_STRING or + * qualified-name token (T_NAME_FULLY_QUALIFIED/T_NAME_QUALIFIED — see + * godam_shared_unqualified_name()) matching one of $names, immediately + * followed by '(', and NOT preceded by `new`. + * + * Qualified names matter so a leading-backslash call like + * `\get_post_meta(...)` (forcing global-namespace resolution from inside a + * namespaced file) isn't invisible to every check built on this. The `new` + * exclusion matters because a class and a free function can share a bare + * name — without it, `new Helper()` is indistinguishable from a call to a + * function also named Helper (e.g. `new do_action(...)` would otherwise + * fool hook-fire detection). + * + * @param array[] $tokens Full token list for the file. + * @param int $i Index to check. + * @param array $names Function names to match. + * @param int $count Token count. + * @return bool + */ +function godam_shared_is_call_to( $tokens, $i, $names, $count ) { + $id = $tokens[ $i ]['id'] ?? null; + if ( ! in_array( $id, array( T_STRING, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED ), true ) ) { + return false; + } + + $name = T_STRING === $id ? $tokens[ $i ]['text'] : godam_shared_unqualified_name( $tokens[ $i ]['text'] ); + if ( ! in_array( $name, $names, true ) ) { + return false; + } + + $n = godam_shared_skip_forward( $tokens, $i + 1, $count ); + if ( $n >= $count || '(' !== $tokens[ $n ]['text'] ) { + return false; + } + + $p = godam_shared_skip_backward( $tokens, $i - 1 ); + return ! ( $p >= 0 && T_NEW === ( $tokens[ $p ]['id'] ?? null ) ); +} + +/** + * Whether the token at $i is the NAME in a function/method declaration + * ("function name(" or "function &name(" for return-by-reference) rather + * than a call — both tokenize identically (T_STRING followed by '('), so + * anything matching by name+"(" needs this check wherever the matched set + * could include a real, user-defined function/method name. + * + * Needed by godam_shared_is_bare_call_to(): without it, a user-defined + * method named get_children() or get_posts() would have its own + * declaration misread as a call to the global function of the same name. + * + * @param array[] $tokens Full token list for the file. + * @param int $i Index to check. + * @return bool + */ +function godam_shared_is_function_declaration_at( $tokens, $i ) { + $p = godam_shared_skip_backward( $tokens, $i - 1 ); + + if ( $p >= 0 && T_FUNCTION === ( $tokens[ $p ]['id'] ?? null ) ) { + return true; + } + + if ( $p >= 0 && '&' === $tokens[ $p ]['text'] ) { + $before_amp = godam_shared_skip_backward( $tokens, $p - 1 ); + return $before_amp >= 0 && T_FUNCTION === ( $tokens[ $before_amp ]['id'] ?? null ); + } + + return false; +} + +/** + * Whether the token at $i is a real call to one of $names (per + * godam_shared_is_call_to()) that's neither method-style (preceded by -> + * or ::) nor a same-named function/method declaration + * (godam_shared_is_function_declaration_at()). + * + * Needed because a name match alone can't tell a global call apart from an + * unrelated class's own same-named method — e.g. $query->get_posts() reads + * an already-run WP_Query's cached results, not a fresh query, but + * tokenizes identically to the global get_posts() call. Used for + * get_posts()/get_children(); not needed for $wpdb calls (already gated on + * `$wpdb->`) or ACCESS_FUNCTIONS (no confirmed collision today). + * + * @param array[] $tokens Full token list for the file. + * @param int $i Index to check. + * @param array $names Function names to match. + * @param int $count Token count. + * @return bool + */ +function godam_shared_is_bare_call_to( $tokens, $i, $names, $count ) { + if ( ! godam_shared_is_call_to( $tokens, $i, $names, $count ) ) { + return false; + } + + if ( godam_shared_is_function_declaration_at( $tokens, $i ) ) { + return false; + } + + $p = godam_shared_skip_backward( $tokens, $i - 1 ); + return ! ( $p >= 0 && in_array( $tokens[ $p ]['text'], array( '->', '::' ), true ) ); +} + +/** + * Whether the T_CONSTANT_ENCAPSED_STRING token at $i is $hook_name, passed + * as the first argument to a real, bare call to one of $outer_functions — + * e.g. do_action( 'x' ). + * + * Uses godam_shared_is_bare_call_to() so a class with its own do_action() + * method can't fake a hook fire (e.g. $logger->do_action(...), an unrelated + * logging call). Safe: do_action()/wp_die()/wp_send_json*() are core + * globals, never legitimately called via ->/::. + * + * @param array[] $tokens Full token list for the file. + * @param int $i Index of the string token to check. + * @param string $hook_name Hook name to match (unquoted). + * @param array $outer_functions Function names that count as firing this hook. + * @return bool + */ +function godam_shared_is_hook_fire_at( $tokens, $i, $hook_name, $outer_functions = GODAM_HOOK_FIRE_FUNCTIONS ) { + if ( T_CONSTANT_ENCAPSED_STRING !== ( $tokens[ $i ]['id'] ?? null ) ) { + return false; + } + + // Strip the token's own quote characters (single or double) to compare. + if ( substr( $tokens[ $i ]['text'], 1, -1 ) !== $hook_name ) { + return false; + } + + $count = count( $tokens ); + + // Walk backward: '(' then a T_STRING matching one of the outer functions. + $p = godam_shared_skip_backward( $tokens, $i - 1 ); + if ( $p < 0 || '(' !== $tokens[ $p ]['text'] ) { + return false; + } + $p = godam_shared_skip_backward( $tokens, $p - 1 ); + + return $p >= 0 && godam_shared_is_bare_call_to( $tokens, $p, $outer_functions, $count ); +} + +/** + * $wpdb methods that execute a real, potentially attachment-touching query. + * Tracked separately from ACCESS_FUNCTIONS since these are only ever + * invoked as a method on the $wpdb global. + * + * @var string[] + */ +const GODAM_WPDB_QUERY_METHODS = array( 'get_results', 'get_row', 'get_col', 'get_var', 'query', 'update', 'delete', 'insert', 'replace' ); + +/** + * Whether the token at $i is a real call to one of $methods specifically on + * the $wpdb global — T_STRING matching one of $methods, immediately + * preceded by '->' and, before that, the T_VARIABLE $wpdb (skipping + * whitespace/comments), and immediately followed by '('. + * + * @param array[] $tokens Full token list for the file. + * @param int $i Index to check. + * @param array $methods Method names to match. + * @param int $count Token count. + * @return bool + */ +function godam_shared_is_wpdb_call_to( $tokens, $i, $methods, $count ) { + if ( T_STRING !== ( $tokens[ $i ]['id'] ?? null ) || ! in_array( $tokens[ $i ]['text'], $methods, true ) ) { + return false; + } + + $n = godam_shared_skip_forward( $tokens, $i + 1, $count ); + if ( $n >= $count || '(' !== $tokens[ $n ]['text'] ) { + return false; + } + + $p = godam_shared_skip_backward( $tokens, $i - 1 ); + if ( $p < 0 || T_OBJECT_OPERATOR !== ( $tokens[ $p ]['id'] ?? null ) ) { + return false; + } + + $p = godam_shared_skip_backward( $tokens, $p - 1 ); + return $p >= 0 && T_VARIABLE === ( $tokens[ $p ]['id'] ?? null ) && '$wpdb' === $tokens[ $p ]['text']; +} + +/** + * Whether the token at $i starts a `new WP_Query(` expression — bare + * (T_STRING) or namespace-qualified (T_NAME_FULLY_QUALIFIED/ + * T_NAME_QUALIFIED). This codebase uses both forms in different files, so a + * T_STRING-only check would silently miss the qualified ones. + * + * @param array[] $tokens Full token list for the file. + * @param int $i Index to check. + * @param int $count Token count. + * @return bool + */ +function godam_shared_is_new_wp_query_at( $tokens, $i, $count ) { + if ( T_NEW !== ( $tokens[ $i ]['id'] ?? null ) ) { + return false; + } + + $j = godam_shared_skip_forward( $tokens, $i + 1, $count ); + if ( $j >= $count ) { + return false; + } + + $is_class_name_token = in_array( $tokens[ $j ]['id'] ?? null, array( T_STRING, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED ), true ); + if ( ! $is_class_name_token || 'WP_Query' !== godam_shared_unqualified_name( $tokens[ $j ]['text'] ) ) { + return false; + } + + $n = godam_shared_skip_forward( $tokens, $j + 1, $count ); + return $n < $count && '(' === $tokens[ $n ]['text']; +} + +/** + * Given the index of an opening '(' or '[', returns its matching closer by + * tracking depth for that bracket type. Returns $count if unbalanced. + * + * General form of godam_shared_find_matching_paren() (kept as a thin + * '('-only wrapper since most callers only bound a call's own argument + * list); this version also bounds an array-literal `[ ... ]` post_type + * value. + * + * @param array[] $tokens Full token list for the file. + * @param int $open_index Index of the opening '(' or '['. + * @param int $count Token count. + * @return int + */ +function godam_shared_find_matching_bracket( $tokens, $open_index, $count ) { + $open_char = $tokens[ $open_index ]['text']; + $close_char = '(' === $open_char ? ')' : ']'; + $depth = 1; + $j = $open_index + 1; + + while ( $j < $count && $depth > 0 ) { + if ( $open_char === $tokens[ $j ]['text'] ) { + ++$depth; + } elseif ( $close_char === $tokens[ $j ]['text'] ) { + --$depth; + } + ++$j; + } + + return $depth > 0 ? $count : $j - 1; +} + +/** + * Given the index of a call's opening '(', returns the index of its + * matching ')' by tracking paren depth. Returns $count (out of range) if + * unbalanced. + * + * @param array[] $tokens Full token list for the file. + * @param int $open_index Index of the opening '('. + * @param int $count Token count. + * @return int + */ +function godam_shared_find_matching_paren( $tokens, $open_index, $count ) { + return godam_shared_find_matching_bracket( $tokens, $open_index, $count ); +} + +/** + * Given a target range and a list of candidate ranges (each with + * 'body_start'/'body_end' keys), returns every candidate STRICTLY NESTED + * inside the target range, as [start, end] pairs for a $skip_ranges + * argument. + * + * Excludes an exact self-match: when the candidate list is the same list a + * range came from (e.g. "what's nested inside function F" using the full + * $functions list F is itself in), F would otherwise match itself and the + * walk would jump straight past its own body on the first iteration — the + * same bug shape found and fixed for deferred closures earlier, now guarded + * here generically. + * + * @param int $range_start Token index to start at (inclusive). + * @param int $range_end Token index to end at (inclusive). + * @param array[] $candidates Each with 'body_start'/'body_end' keys. + * @return array[] Each [start, end] (inclusive token indexes). + */ +function godam_shared_ranges_nested_in( $range_start, $range_end, $candidates ) { + $nested = array(); + foreach ( $candidates as $candidate ) { + $is_self = $candidate['body_start'] === $range_start && $candidate['body_end'] === $range_end; + if ( ! $is_self && $candidate['body_start'] >= $range_start && $candidate['body_end'] <= $range_end ) { + $nested[] = array( $candidate['body_start'], $candidate['body_end'] ); + } + } + return $nested; +} + +/** + * Whether [$range_start, $range_end] contains a `'post_type' => + * 'attachment'/'any'` pair, or a `post_type => array(...)`/`[...]` value + * mentioning either string anywhere inside it (a common way to query more + * than one post type). + * + * The bare-string branch deliberately scans the WHOLE range rather than + * tracing the query's own $args variable — real query args in this + * codebase are built incrementally across several statements. This is a + * permissive heuristic: a false positive here just means one more finding + * for a human to dismiss, not a missed real gap. + * + * @param array[] $tokens Full token list for the file. + * @param int $range_start Token index to start at (inclusive). + * @param int $range_end Token index to end at (inclusive). + * @param int $count Token count. + * @return bool + */ +function godam_shared_range_targets_attachment_post_type( $tokens, $range_start, $range_end, $count ) { + for ( $i = $range_start; $i <= $range_end; $i++ ) { + if ( T_CONSTANT_ENCAPSED_STRING !== ( $tokens[ $i ]['id'] ?? null ) ) { + continue; + } + + if ( "'post_type'" !== $tokens[ $i ]['text'] && '"post_type"' !== $tokens[ $i ]['text'] ) { + continue; + } + + $arrow = godam_shared_skip_forward( $tokens, $i + 1, $count ); + if ( $arrow >= $count || T_DOUBLE_ARROW !== ( $tokens[ $arrow ]['id'] ?? null ) ) { + continue; + } + + $value = godam_shared_skip_forward( $tokens, $arrow + 1, $count ); + if ( $value >= $count ) { + continue; + } + + if ( T_CONSTANT_ENCAPSED_STRING === ( $tokens[ $value ]['id'] ?? null ) ) { + if ( in_array( substr( $tokens[ $value ]['text'], 1, -1 ), array( 'attachment', 'any' ), true ) ) { + return true; + } + continue; + } + + $is_array_call = T_ARRAY === ( $tokens[ $value ]['id'] ?? null ); + $is_array_literal = null === ( $tokens[ $value ]['id'] ?? null ) && '[' === $tokens[ $value ]['text']; + + if ( ! $is_array_call && ! $is_array_literal ) { + continue; // A variable, constant, or function call — not statically readable either way. + } + + $open = $is_array_call ? godam_shared_skip_forward( $tokens, $value + 1, $count ) : $value; + if ( $open >= $count || ( '(' !== $tokens[ $open ]['text'] && '[' !== $tokens[ $open ]['text'] ) ) { + continue; + } + + $close = godam_shared_find_matching_bracket( $tokens, $open, $count ); + + for ( $j = $open; $j <= $close && $j < $count; $j++ ) { + if ( T_CONSTANT_ENCAPSED_STRING === ( $tokens[ $j ]['id'] ?? null ) && in_array( substr( $tokens[ $j ]['text'], 1, -1 ), array( 'attachment', 'any' ), true ) ) { + return true; + } + } + } + + return false; +} + +/** + * Whether [$range_start, $range_end] (typically a $wpdb query's own + * argument list) mentions postmeta or wp_posts — used to flag a raw $wpdb + * query as attachment-shaped. Over-includes non-attachment queries too + * (both tables hold every post type) — the same permissive tradeoff as + * godam_shared_range_targets_attachment_post_type(). + * + * Also catches `$wpdb->posts`/`$wpdb->postmeta` referenced via string + * interpolation (braced or not) — PHP's tokenizer parses both exactly like + * code outside a string, landing $wpdb/->/posts as three separate tokens + * that never contain "wp_posts" as their own text, so the plain substring + * check above would otherwise miss e.g. `FROM {$wpdb->posts} p`. + * + * @param array[] $tokens Full token list for the file. + * @param int $range_start Token index to start at (inclusive). + * @param int $range_end Token index to end at (inclusive). + * @return bool + */ +function godam_shared_range_mentions_post_tables( $tokens, $range_start, $range_end ) { + $count = count( $tokens ); + + for ( $i = $range_start; $i <= $range_end; $i++ ) { + $text = strtolower( $tokens[ $i ]['text'] ); + if ( false !== strpos( $text, 'postmeta' ) || false !== strpos( $text, 'wp_posts' ) ) { + return true; + } + + if ( '$wpdb' !== $tokens[ $i ]['text'] ) { + continue; + } + + $arrow = godam_shared_skip_forward( $tokens, $i + 1, $count ); + if ( $arrow >= $count || '->' !== $tokens[ $arrow ]['text'] ) { + continue; + } + + $prop = godam_shared_skip_forward( $tokens, $arrow + 1, $count ); + if ( $prop < $count && in_array( strtolower( $tokens[ $prop ]['text'] ), array( 'posts', 'postmeta' ), true ) ) { + return true; + } + } + + return false; +} + +/** + * Whether the argument starting at the call's own opening '(' (index + * $open_index) is itself a bare call to another named function — e.g. the + * `helper()` in `new WP_Query( helper() )` — rather than an inline + * array/array literal or a variable built in the same scope. + * + * Used to widen godam_shared_query_pattern_at()'s attachment-shaped default + * for exactly this shape: godam_shared_range_targets_attachment_post_type() + * scans the calling scope's own tokens, so it can't see a 'post_type' + * literal that genuinely lives inside a callee it never looks into. A real + * gap this caught: a gallery template's query-mode WP_Query took its args + * from a helper that sets post_type => 'attachment' internally — the scan + * found nothing in the caller's own scope and the query was never flagged + * at all, despite running fully unwrapped. + * + * @param array[] $tokens Full token list for the file. + * @param int $open_index Index of the call's own opening '('. + * @param int $count Token count. + * @return bool + */ +function godam_shared_first_arg_is_function_call( $tokens, $open_index, $count ) { + $first = godam_shared_skip_forward( $tokens, $open_index + 1, $count ); + if ( $first >= $count || ! in_array( $tokens[ $first ]['id'] ?? null, array( T_STRING, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED ), true ) ) { + return false; + } + + $next = godam_shared_skip_forward( $tokens, $first + 1, $count ); + return $next < $count && '(' === $tokens[ $next ]['text']; +} + +/** + * If the token at $i starts a WP_Query/get_posts()/get_children()/$wpdb + * query-method call, returns ['kind' => ..., 'name' => ..., + * 'is_attachment_shaped' => bool]. Returns null otherwise. + * + * These read/write the same postmeta/posts data ACCESS_FUNCTIONS does, but + * aren't a plain `name(` call it can detect (see GODAM_WPDB_QUERY_METHODS). + * + * get_children()'s attachment-shaped check only catches an explicit + * post_type — a bare `get_children( $post_id )` also returns attachments by + * WP's own default, but that has no 'post_type' string to find, so it's an + * accepted gap rather than modeling core's default-argument behavior. + * + * get_posts()/get_children() use godam_shared_is_bare_call_to() to exclude + * method-style calls like `$query->get_posts()` (cached results, not a + * fresh query — see that function's own comment). + * + * Always a "direct" finding, never parameter-sourced: unlike + * get_post_meta( $id, ... ), none of these take a single attachment-ID + * argument to check against a safe-parameter set. + * + * @param array[] $tokens Full token list for the file. + * @param int $i Index to check. + * @param int $range_start Enclosing scope's start (for the post_type scan). + * @param int $range_end Enclosing scope's end. + * @param int $count Token count. + * @return array|null + */ +function godam_shared_query_pattern_at( $tokens, $i, $range_start, $range_end, $count ) { + if ( godam_shared_is_new_wp_query_at( $tokens, $i, $count ) ) { + $class_name_index = godam_shared_skip_forward( $tokens, $i + 1, $count ); + $open = godam_shared_skip_forward( $tokens, $class_name_index + 1, $count ); + + return array( + 'kind' => 'wp_query', + 'name' => 'new WP_Query', + 'is_attachment_shaped' => godam_shared_range_targets_attachment_post_type( $tokens, $range_start, $range_end, $count ) + || godam_shared_first_arg_is_function_call( $tokens, $open, $count ), + ); + } + + if ( godam_shared_is_bare_call_to( $tokens, $i, array( 'get_posts' ), $count ) ) { + $open = godam_shared_skip_forward( $tokens, $i + 1, $count ); + + return array( + 'kind' => 'get_posts', + 'name' => 'get_posts', + 'is_attachment_shaped' => godam_shared_range_targets_attachment_post_type( $tokens, $range_start, $range_end, $count ) + || godam_shared_first_arg_is_function_call( $tokens, $open, $count ), + ); + } + + if ( godam_shared_is_bare_call_to( $tokens, $i, array( 'get_children' ), $count ) ) { + $open = godam_shared_skip_forward( $tokens, $i + 1, $count ); + + return array( + 'kind' => 'get_children', + 'name' => 'get_children', + 'is_attachment_shaped' => godam_shared_range_targets_attachment_post_type( $tokens, $range_start, $range_end, $count ) + || godam_shared_first_arg_is_function_call( $tokens, $open, $count ), + ); + } + + if ( godam_shared_is_wpdb_call_to( $tokens, $i, GODAM_WPDB_QUERY_METHODS, $count ) ) { + $open = godam_shared_skip_forward( $tokens, $i + 1, $count ); + $close = godam_shared_find_matching_paren( $tokens, $open, $count ); + + return array( + 'kind' => 'wpdb', + 'name' => '$wpdb->' . $tokens[ $i ]['text'], + 'is_attachment_shaped' => godam_shared_range_mentions_post_tables( $tokens, $open, $close ), + ); + } + + return null; +} + +/** + * Whether the token at $i unconditionally ends the current function/request: + * `return`/`throw`/`exit`/`die` (T_EXIT covers both spellings), or a real, + * bare call to one of GODAM_TERMINATOR_FUNCTIONS. + * + * Uses godam_shared_is_bare_call_to() for the same reason + * godam_shared_is_hook_fire_at() does — a class with its own wp_die()-named + * method would otherwise wrongly end a scope early. Safe: all four names + * are core globals, never called via ->/::. + * + * @param array[] $tokens Full token list for the file. + * @param int $i Index to check. + * @param int $count Token count. + * @return bool + */ +function godam_shared_is_scope_terminator( $tokens, $i, $count ) { + if ( in_array( $tokens[ $i ]['id'] ?? null, array( T_RETURN, T_THROW, T_EXIT ), true ) ) { + return true; + } + + return godam_shared_is_bare_call_to( $tokens, $i, GODAM_TERMINATOR_FUNCTIONS, $count ); +} + +/** + * Finds named class/interface/trait declarations: name, whether it's a + * trait (T_TRAIT), and body token range, by tracking brace depth. + * + * The trait flag lets godam_shared_find_trait_uses() and the + * coverage-checker's caller trace widen a private trait method's search to + * every file that `use`s the trait. The name lets godam_shared_find_functions() + * class-qualify each method (`Foo::render()`, not a bare `render()`). + * + * @param array[] $tokens Normalized tokens from godam_shared_tokenize(). + * @return array[] Each: name, is_trait (bool), body_start, body_end (token indexes). + */ +function godam_shared_find_classes( $tokens ) { + $classes = array(); + $count = count( $tokens ); + + for ( $i = 0; $i < $count; $i++ ) { + if ( ! in_array( $tokens[ $i ]['id'] ?? null, array( T_CLASS, T_INTERFACE, T_TRAIT ), true ) ) { + continue; + } + + $is_trait = T_TRAIT === $tokens[ $i ]['id']; + + $j = godam_shared_skip_forward( $tokens, $i + 1, $count ); + if ( $j >= $count ) { + continue; + } + + if ( T_STRING === ( $tokens[ $j ]['id'] ?? null ) ) { + $name = $tokens[ $j ]['text']; + } else { + // Anonymous class — a synthetic name keyed by token index lets + // godam_shared_find_functions() still class-qualify its methods, + // instead of leaving class = null and matching a bare `name(` + // call site by mistake. + $name = "class@anonymous:{$i}"; + } + + while ( $j < $count && '{' !== $tokens[ $j ]['text'] ) { + ++$j; + } + if ( $j >= $count ) { + continue; + } + + $body_start = $j; + $brace_depth = 1; + ++$j; + while ( $j < $count && $brace_depth > 0 ) { + if ( '{' === $tokens[ $j ]['text'] ) { + ++$brace_depth; + } elseif ( '}' === $tokens[ $j ]['text'] ) { + --$brace_depth; + } + ++$j; + } + $body_end = $j - 1; + + $classes[] = array( + 'name' => $name, + 'is_trait' => $is_trait, + 'body_start' => $body_start, + 'body_end' => $body_end, + ); + + // Deliberately NOT jumping past this class's own body: an anonymous + // class can appear inside a method of an already-recorded outer + // class, and jumping past it would skip the anonymous class's own + // T_CLASS token, wrongly class-qualifying every method inside it as + // the OUTER class. The outer class's own token index has already + // been passed by the time its body is scanned, so it's never re-found. + } + + return $classes; +} + +/** + * Finds every `use TraitName[, ...];` statement inside a class body, + * returning which trait names each class imports. Scoped strictly between + * a class's own body_start/body_end — a class body can't have a + * namespace-import `use`, so this can't be confused with that. + * + * Excludes any OTHER class nested inside the one being scanned + * (godam_shared_ranges_nested_in()) — otherwise a `use` statement really + * only inside an inner (often anonymous) class would also be recorded as + * the outer class's own import. + * + * Trait names are normalized via godam_shared_unqualified_name() so a + * qualified `use \Foo\Bar\SomeTrait;` still matches a plain `trait + * SomeTrait` declaration found elsewhere. + * + * @param array[] $tokens Normalized tokens from godam_shared_tokenize(). + * @param array[] $classes This file's own godam_shared_find_classes() result. + * @return array Trait short name => list of (this file's) class names that `use` it. + */ +function godam_shared_find_trait_uses( $tokens, $classes ) { + $uses = array(); + $count = count( $tokens ); + + foreach ( $classes as $class ) { + $skip_ranges = godam_shared_ranges_nested_in( $class['body_start'], $class['body_end'], $classes ); + + for ( $i = $class['body_start']; $i <= $class['body_end']; $i++ ) { + $jumped = false; + foreach ( $skip_ranges as $skip ) { + if ( $i === $skip[0] ) { + $i = $skip[1]; + $jumped = true; + break; + } + } + if ( $jumped ) { + continue; + } + + if ( T_USE !== ( $tokens[ $i ]['id'] ?? null ) ) { + continue; + } + + $j = godam_shared_skip_forward( $tokens, $i + 1, $count ); + + while ( $j <= $class['body_end'] && in_array( $tokens[ $j ]['id'] ?? null, array( T_STRING, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED ), true ) ) { + $short_name = godam_shared_unqualified_name( $tokens[ $j ]['text'] ); + $uses[ $short_name ][] = $class['name']; + + $j = godam_shared_skip_forward( $tokens, $j + 1, $count ); + if ( $j <= $class['body_end'] && ',' === $tokens[ $j ]['text'] ) { + $j = godam_shared_skip_forward( $tokens, $j + 1, $count ); + continue; + } + break; + } + } + } + + return $uses; +} + +/** + * Function names whose typical call shape passes a callback (directly, or + * nested in an args array) that WordPress stores and invokes later, + * potentially on a different request than the one that registered it. + * + * Two of these, register_activation_hook()/register_deactivation_hook(), + * take __FILE__ (not a string) as their first argument, so hook_name comes + * back null for those. register_rest_route()'s callback, nested in its + * 'callback' => ... entry, is already handled since the search scans every + * token in the call's parens regardless of argument position. + * + * @var string[] + */ +const GODAM_DEFERRED_CALLBACK_FUNCTIONS = array( + 'add_action', + 'add_filter', + 'add_shortcode', + 'register_activation_hook', + 'register_deactivation_hook', + 'register_rest_route', +); + +/** + * Given a T_FUNCTION token confirmed to start an anonymous closure, + * extracts its parameter names and body token range by tracking + * paren/brace depth. Returns null if $j isn't an anonymous closure, or if + * $count is reached before a body is found (unbalanced — bail rather than + * guess). Shared by both ways godam_shared_find_deferred_closures() finds a + * deferred closure: passed inline, or assigned to a variable first. + * + * @param array[] $tokens Full token list for the file. + * @param int $j Index of the T_FUNCTION token. + * @param int $count Token count. + * @return array{params: string[], body_start: int, body_end: int}|null + */ +function godam_shared_extract_closure_at( $tokens, $j, $count ) { + $k = godam_shared_skip_forward( $tokens, $j + 1, $count ); + if ( $k < $count && '&' === $tokens[ $k ]['text'] ) { // Return-by-reference closure. + $k = godam_shared_skip_forward( $tokens, $k + 1, $count ); + } + if ( $k < $count && T_STRING === ( $tokens[ $k ]['id'] ?? null ) ) { + return null; // Named, not anonymous. + } + + while ( $k < $count && '(' !== $tokens[ $k ]['text'] ) { + ++$k; + } + if ( $k >= $count ) { + return null; + } + + // Parameter list, extracted the same way godam_shared_find_functions() + // does, so it can be walked as its own scope with its own params. + $params = array(); + $paren_depth = 1; + ++$k; + while ( $k < $count && $paren_depth > 0 ) { + if ( '(' === $tokens[ $k ]['text'] ) { + ++$paren_depth; + } elseif ( ')' === $tokens[ $k ]['text'] ) { + --$paren_depth; + } elseif ( 1 === $paren_depth && T_VARIABLE === ( $tokens[ $k ]['id'] ?? null ) ) { + $params[] = ltrim( $tokens[ $k ]['text'], '$' ); + } + ++$k; + } + + $body_start = $k; + while ( $body_start < $count && '{' !== $tokens[ $body_start ]['text'] ) { + ++$body_start; + } + if ( $body_start >= $count ) { + return null; + } + + $brace_depth = 1; + $body_end = $body_start + 1; + while ( $body_end < $count && $brace_depth > 0 ) { + if ( '{' === $tokens[ $body_end ]['text'] ) { + ++$brace_depth; + } elseif ( '}' === $tokens[ $body_end ]['text'] ) { + --$brace_depth; + } + ++$body_end; + } + --$body_end; + + if ( $body_end >= $count ) { + return null; + } + + return array( + 'params' => $params, + 'body_start' => $body_start, + 'body_end' => $body_end, + ); +} + +/** + * Finds every `$var = function(...) {...};` assignment anywhere in the + * token stream — a closure assigned to a variable first, rather than + * passed inline. Used so godam_shared_find_deferred_closures() can also + * recognize the "assign, then register by variable" shape. + * + * @param array[] $tokens Full token list for the file. + * @return array[] Each: var_name (unprefixed), params, body_start, body_end. + */ +function godam_shared_find_closure_assignments( $tokens ) { + $assignments = array(); + $count = count( $tokens ); + + for ( $i = 0; $i < $count; $i++ ) { + if ( T_VARIABLE !== ( $tokens[ $i ]['id'] ?? null ) ) { + continue; + } + + $eq = godam_shared_skip_forward( $tokens, $i + 1, $count ); + if ( $eq >= $count || '=' !== $tokens[ $eq ]['text'] ) { + continue; + } + + $fn = godam_shared_skip_forward( $tokens, $eq + 1, $count ); + if ( $fn >= $count || T_FUNCTION !== ( $tokens[ $fn ]['id'] ?? null ) ) { + continue; + } + + $closure = godam_shared_extract_closure_at( $tokens, $fn, $count ); + if ( null === $closure ) { + continue; + } + + $assignments[] = array_merge( + array( 'var_name' => ltrim( $tokens[ $i ]['text'], '$' ) ), + $closure + ); + + $i = $closure['body_end']; // Resume after this closure. + } + + return $assignments; +} + +/** + * Finds every anonymous closure effectively DEFERRED to one of + * GODAM_DEFERRED_CALLBACK_FUNCTIONS: passed directly (or nested in an args + * array) to a call to one of them, or assigned to a variable first and that + * variable passed later. Returns each closure's hook name (when the + * registration call's first argument is a plain string) and body range. + * + * A deferred callback does NOT inherit whatever before/after bracket + * happens to be open where it's merely DEFINED — it runs later, whenever + * the hook fires, possibly on a different request. Scoped to + * GODAM_DEFERRED_CALLBACK_FUNCTIONS specifically, not every closure — + * array_map()/usort()/an IIFE all run their closure synchronously inline, + * genuinely inheriting the surrounding bracket correctly. + * + * Only matches T_FUNCTION, not T_FN (arrow functions) — unused by any + * registration call in this codebase today, a narrow accepted gap. + * + * The variable-mediated shape requires the assignment and the registration + * call to share the same enclosing function + * (godam_shared_same_enclosing_function()) before matching by variable + * name, so two unrelated functions each using a same-named local (e.g. + * `$cb`) can't cross-match. + * + * Both registration-call scans use plain godam_shared_is_call_to(), not + * godam_shared_is_bare_call_to(): unlike do_action()/wp_die(), add_action()/ + * add_filter() have a genuine OOP equivalent (e.g. a Loader's + * `$this->loader->add_action(...)`) that must still be recognized here. A + * class with an unrelated, non-wrapper add_action()-named method produces a + * false positive instead — the safe direction to be wrong in. + * + * @param array[] $tokens Full token list for the file. + * @param array[] $functions This file's own godam_shared_find_functions() result — used only to scope the variable-mediated shape above. + * @return array[] Each: hook_name (string|null — null if the hook name + * isn't a plain string literal), params (string[] of the + * closure's own parameter names, unprefixed by $), + * body_start, body_end (token indexes of the closure's own + * '{'/'}'). + */ +function godam_shared_find_deferred_closures( $tokens, $functions ) { + $closures = array(); + $count = count( $tokens ); + + // Phase 1: an inline closure passed directly as (or nested inside an + // args array for) an argument to a registration call. + for ( $i = 0; $i < $count; $i++ ) { + if ( ! godam_shared_is_call_to( $tokens, $i, GODAM_DEFERRED_CALLBACK_FUNCTIONS, $count ) ) { + continue; + } + + $open = godam_shared_skip_forward( $tokens, $i + 1, $count ); + $close = godam_shared_find_matching_paren( $tokens, $open, $count ); + + if ( $close >= $count ) { + continue; // Unbalanced — bail rather than guess. + } + + $hook_name = null; + $first_arg = godam_shared_skip_forward( $tokens, $open + 1, $count ); + if ( $first_arg < $close && T_CONSTANT_ENCAPSED_STRING === ( $tokens[ $first_arg ]['id'] ?? null ) ) { + $hook_name = substr( $tokens[ $first_arg ]['text'], 1, -1 ); + } + + for ( $j = $open + 1; $j < $close; $j++ ) { + if ( T_FUNCTION !== ( $tokens[ $j ]['id'] ?? null ) ) { + continue; + } + + $closure = godam_shared_extract_closure_at( $tokens, $j, $count ); + if ( null === $closure ) { + continue; + } + + $closures[] = array_merge( array( 'hook_name' => $hook_name ), $closure ); + + $j = $closure['body_end']; // Resume after this closure. + } + } + + // Phase 2: a closure assigned to a variable first, then the variable + // passed to a registration call — e.g. `$cb = function(){}; add_action( + // 'init', $cb );`. Phase 1 can't see this: the call's args contain a + // T_VARIABLE, not a T_FUNCTION. + $assignments = godam_shared_find_closure_assignments( $tokens ); + if ( empty( $assignments ) ) { + return $closures; + } + + $assignments_by_var = array(); + foreach ( $assignments as $assignment ) { + // Uses the closure's own body_start as a stand-in for the assignment's position. + $assignment['enclosing'] = godam_shared_enclosing_function_at( $assignment['body_start'], $functions ); + $assignments_by_var[ $assignment['var_name'] ][] = $assignment; + } + + $already_deferred = array(); + foreach ( $closures as $closure ) { + $already_deferred[ $closure['body_start'] ] = true; + } + + for ( $i = 0; $i < $count; $i++ ) { + if ( ! godam_shared_is_call_to( $tokens, $i, GODAM_DEFERRED_CALLBACK_FUNCTIONS, $count ) ) { + continue; + } + + $open = godam_shared_skip_forward( $tokens, $i + 1, $count ); + $close = godam_shared_find_matching_paren( $tokens, $open, $count ); + + if ( $close >= $count ) { + continue; + } + + $hook_name = null; + $first_arg = godam_shared_skip_forward( $tokens, $open + 1, $count ); + if ( $first_arg < $close && T_CONSTANT_ENCAPSED_STRING === ( $tokens[ $first_arg ]['id'] ?? null ) ) { + $hook_name = substr( $tokens[ $first_arg ]['text'], 1, -1 ); + } + + $call_enclosing = godam_shared_enclosing_function_at( $i, $functions ); + + for ( $j = $open + 1; $j < $close; $j++ ) { + if ( T_VARIABLE !== ( $tokens[ $j ]['id'] ?? null ) ) { + continue; + } + + $var_name = ltrim( $tokens[ $j ]['text'], '$' ); + + foreach ( $assignments_by_var[ $var_name ] ?? array() as $assignment ) { + if ( isset( $already_deferred[ $assignment['body_start'] ] ) ) { + continue; // Already recorded via another registration call referencing the same variable. + } + + if ( ! godam_shared_same_enclosing_function( $assignment['enclosing'], $call_enclosing ) ) { + continue; // A different function's own local of the same name — not this assignment's value. + } + + $closures[] = array( + 'hook_name' => $hook_name, + 'params' => $assignment['params'], + 'body_start' => $assignment['body_start'], + 'body_end' => $assignment['body_end'], + ); + + $already_deferred[ $assignment['body_start'] ] = true; + } + } + } + + return $closures; +} + +/** + * Determines the visibility modifier on the method declaration whose + * `function` keyword is at $i, scanning backward over visibility/static/ + * abstract/final modifiers in any order. + * + * Used to scope the coverage-checker's call-site search: a `private` + * method can only be called from within its own class, so a same-file-only + * search suffices and sidesteps a same-name-in-a-different-class collision + * a codebase-wide search can't rule out without real type resolution. + * + * @param array[] $tokens Full token list. + * @param int $i Index of the T_FUNCTION token. + * @return string|null 'private', 'protected', 'public', or null (a free + * function, or a method with no explicit modifier — + * implicitly public in PHP). + */ +function godam_shared_function_visibility_at( $tokens, $i ) { + $modifier_tokens = array( T_PRIVATE, T_PROTECTED, T_PUBLIC, T_STATIC, T_ABSTRACT, T_FINAL ); + $visibility = null; + + $j = godam_shared_skip_backward( $tokens, $i - 1 ); + while ( $j >= 0 && in_array( $tokens[ $j ]['id'] ?? null, $modifier_tokens, true ) ) { + if ( in_array( $tokens[ $j ]['id'], array( T_PRIVATE, T_PROTECTED, T_PUBLIC ), true ) ) { + $visibility = strtolower( $tokens[ $j ]['text'] ); + } + $j = godam_shared_skip_backward( $tokens, $j - 1 ); + } + + return $visibility; +} + +/** + * Finds named function/method declarations: name, enclosing class, param + * names, parameter-list range, and body range, by tracking paren/brace + * depth. + * + * `params_open`/`params_close` are recorded separately from body_start/ + * body_end so a PHP 8.1+ "new in initializers" default (`function search( + * $query = new WP_Query(...) )`) can be attributed to this function without + * being walked as part of the body range — see godam_coverage_file_findings() + * for why they're walked independently rather than merged. + * + * An interface/abstract declaration can have this same shape in its + * parameter list, but is deliberately NOT added to $functions — doing so + * would give a name a second "definition," breaking + * godam_coverage_resolve_coverage()'s codebase-wide-uniqueness check. Its + * parameter-list range is still tracked, via the optional + * $bodyless_declarations output parameter. + * + * @param array[] $tokens Normalized tokens from godam_shared_tokenize(). + * @param array[] &$bodyless_declarations Output: each interface/abstract method + * declaration found, as {name, class, params_open, params_close} + * — never merged into the main return value, see above. + * @return array[] Each: name, class (string|null — enclosing class/interface/ + * trait name, null for a plain function), visibility + * (string|null — see godam_shared_function_visibility_at()), + * params (string[] of variable names, unprefixed by $), + * params_open, params_close, body_start, body_end (token + * indexes). + */ +function godam_shared_find_functions( $tokens, &$bodyless_declarations = array() ) { + $functions = array(); + $bodyless_declarations = array(); + $classes = godam_shared_find_classes( $tokens ); + $count = count( $tokens ); + + for ( $i = 0; $i < $count; $i++ ) { + if ( T_FUNCTION !== ( $tokens[ $i ]['id'] ?? null ) ) { + continue; + } + + $visibility = godam_shared_function_visibility_at( $tokens, $i ); + $j = godam_shared_skip_forward( $tokens, $i + 1, $count ); + + if ( $j < $count && '&' === $tokens[ $j ]['text'] ) { // Return-by-reference. + $j = godam_shared_skip_forward( $tokens, $j + 1, $count ); + } + + if ( $j >= $count || T_STRING !== ( $tokens[ $j ]['id'] ?? null ) ) { + continue; // Anonymous function/closure — its tokens stay part of whichever named function or top-level range encloses it. + } + + $name = $tokens[ $j ]['text']; + ++$j; + + while ( $j < $count && '(' !== $tokens[ $j ]['text'] ) { + ++$j; + } + if ( $j >= $count ) { + continue; + } + + $params_open = $j; + $params = array(); + $paren_depth = 1; + ++$j; + while ( $j < $count && $paren_depth > 0 ) { + if ( '(' === $tokens[ $j ]['text'] ) { + ++$paren_depth; + } elseif ( ')' === $tokens[ $j ]['text'] ) { + --$paren_depth; + } elseif ( 1 === $paren_depth && T_VARIABLE === ( $tokens[ $j ]['id'] ?? null ) ) { + $params[] = ltrim( $tokens[ $j ]['text'], '$' ); + } + ++$j; + } + $params_close = $j - 1; + + while ( $j < $count && '{' !== $tokens[ $j ]['text'] && ';' !== $tokens[ $j ]['text'] ) { + ++$j; + } + if ( $j >= $count ) { + continue; // Unbalanced — bail rather than guess. + } + if ( ';' === $tokens[ $j ]['text'] ) { + // Interface/abstract declaration — no body (see docblock). Uses + // $i in place of body_start to find the smallest-span enclosing + // class, same as a bodied function does below. + $class_name = null; + $class_name_span = null; + foreach ( $classes as $class ) { + if ( $i < $class['body_start'] || $i > $class['body_end'] ) { + continue; + } + $span = $class['body_end'] - $class['body_start']; + if ( null === $class_name_span || $span < $class_name_span ) { + $class_name = $class['name']; + $class_name_span = $span; + } + } + + $bodyless_declarations[] = array( + 'name' => $name, + 'class' => $class_name, + 'params_open' => $params_open, + 'params_close' => $params_close, + ); + continue; + } + + $body_start = $j; + $brace_depth = 1; + ++$j; + while ( $j < $count && $brace_depth > 0 ) { + if ( '{' === $tokens[ $j ]['text'] ) { + ++$brace_depth; + } elseif ( '}' === $tokens[ $j ]['text'] ) { + --$brace_depth; + } + ++$j; + } + $body_end = $j - 1; + + // Picks the SMALLEST (innermost) containing class, not the first + // match — class ranges can nest (an anonymous class inside an outer + // class's method), so body_start can fall within both at once, and + // the first match would wrongly class-qualify a method that's + // really on the inner class. + $class_name = null; + $class_name_span = null; + foreach ( $classes as $class ) { + if ( $body_start < $class['body_start'] || $body_start > $class['body_end'] ) { + continue; + } + $span = $class['body_end'] - $class['body_start']; + if ( null === $class_name_span || $span < $class_name_span ) { + $class_name = $class['name']; + $class_name_span = $span; + } + } + + $functions[] = array( + 'name' => $name, + 'class' => $class_name, + 'visibility' => $visibility, + 'params' => $params, + 'params_open' => $params_open, + 'params_close' => $params_close, + 'body_start' => $body_start, + 'body_end' => $body_end, + ); + + // Deliberately NOT jumping past body_end: this function's body can + // contain another named function/method (e.g. inside a `new class + // {...}` expression), and jumping past it would skip that T_FUNCTION + // token entirely. A genuinely anonymous closure is already excluded + // above without advancing $i, so scanning through linearly can't + // re-record anything. + } + + return $functions; +} + +/** + * Returns the INNERMOST (smallest-range) entry in $functions whose + * [body_start, body_end] contains $index, or null if none do. + * + * "Innermost" matters because function ranges can nest — a method inside a + * function-scoped anonymous class sits inside its enclosing function's + * range too, and is the more specific, correct answer. + * + * @param int $index Token index to check. + * @param array[] $functions godam_shared_find_functions() result. + * @return array|null + */ +function godam_shared_enclosing_function_at( $index, $functions ) { + $best = null; + foreach ( $functions as $function ) { + if ( $index < $function['body_start'] || $index > $function['body_end'] ) { + continue; + } + if ( null === $best || ( $function['body_end'] - $function['body_start'] ) < ( $best['body_end'] - $best['body_start'] ) ) { + $best = $function; + } + } + return $best; +} + +/** + * Whether $a and $b (each a godam_shared_enclosing_function_at() result or + * null) refer to the same scope: both null (top-level), or the same + * body_start/body_end. Compared by range, not identity — two independent + * calls never return the same array instance for the same function. + * + * @param array|null $a First enclosing-function result (or null for top-level). + * @param array|null $b Second enclosing-function result (or null for top-level). + * @return bool + */ +function godam_shared_same_enclosing_function( $a, $b ) { + if ( null === $a && null === $b ) { + return true; + } + if ( null === $a || null === $b ) { + return false; + } + return $a['body_start'] === $b['body_start'] && $a['body_end'] === $b['body_end']; +} diff --git a/inc/classes/class-demo-assets.php b/inc/classes/class-demo-assets.php index 15b1e2ccd2..687f0b572e 100644 --- a/inc/classes/class-demo-assets.php +++ b/inc/classes/class-demo-assets.php @@ -105,7 +105,19 @@ private static function get_or_create( $category, $file_name ) { * @return bool */ private static function is_valid_attachment( $attachment_id ) { + /** + * Fires before reading this candidate demo attachment's post record, + * so integrations that centralize media on another site can switch + * context first. Reads the attachment's own post_type/post_status to + * confirm the tracked id still points at a live (non-trashed) + * attachment. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $post = get_post( $attachment_id ); + do_action( 'rtgodam_after_attachment_lookup' ); + return $post instanceof \WP_Post && 'attachment' === $post->post_type && 'trash' !== $post->post_status; @@ -118,6 +130,16 @@ private static function is_valid_attachment( $attachment_id ) { * @return int Attachment id, or 0. */ private static function find_existing( $key ) { + /** + * Fires before querying for an existing demo attachment by its + * tracking key, so integrations that centralize media on another + * site can switch context first. This is a real attachment query + * (post_type => 'attachment') keyed on the KEY_META marker this + * class itself writes on every demo attachment it creates. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.get_posts_get_posts $ids = get_posts( array( @@ -132,6 +154,7 @@ private static function find_existing( $key ) { 'meta_value' => $key, ) ); + do_action( 'rtgodam_after_attachment_lookup' ); return ! empty( $ids ) ? (int) $ids[0] : 0; } @@ -217,7 +240,17 @@ private static function create_from_payload( $key, $file_name, $payload ) { return 0; } + /** + * Fires before writing this attachment's demo-asset marker, so + * integrations that centralize media on another site can switch + * context first — this runs after create_virtual_attachment()'s own + * wrap has already restored. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); update_post_meta( $attach_id, self::KEY_META, $key ); + do_action( 'rtgodam_after_attachment_lookup' ); return (int) $attach_id; } diff --git a/inc/classes/class-media-library-ajax.php b/inc/classes/class-media-library-ajax.php index 1529ee49bf..edb078103e 100644 --- a/inc/classes/class-media-library-ajax.php +++ b/inc/classes/class-media-library-ajax.php @@ -277,6 +277,20 @@ public function upload_media_to_frappe_backend( $attachment_id, $manual_retransc } } + // Captured before the switch below, so this is always the site this + // upload belongs to (the one currently active), not the media site. + $site_url = get_site_url(); + + /** + * Fires before reading this attachment's transcoding/virtual-media + * meta, so integrations that centralize media on another site can + * switch context first. Hooked to `add_attachment`, which can fire + * synchronously from inside an already-open bracket (e.g. + * create_virtual_attachment()). + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $transcoding_job_id = get_post_meta( $attachment_id, 'rtgodam_transcoding_job_id', true ); // Check virtual media status for transcoding requests. @@ -285,14 +299,17 @@ public function upload_media_to_frappe_backend( $attachment_id, $manual_retransc // Skip transcoding for virtual media. if ( $is_virtual_media ) { + do_action( 'rtgodam_after_attachment_lookup' ); return; } // Only if attachment type is image. $mime_type = get_post_mime_type( $attachment_id ); if ( 'image' !== substr( $mime_type, 0, 5 ) ) { + do_action( 'rtgodam_after_attachment_lookup' ); return; } + do_action( 'rtgodam_after_attachment_lookup' ); // Check if HTTP auth is enabled. if ( rtgodam_has_http_auth() ) { @@ -308,9 +325,11 @@ public function upload_media_to_frappe_backend( $attachment_id, $manual_retransc } // Update status to failed. + do_action( 'rtgodam_before_attachment_lookup' ); update_post_meta( $attachment_id, 'rtgodam_transcoding_status', 'failed' ); update_post_meta( $attachment_id, 'rtgodam_transcoding_error_msg', __( 'HTTP authentication is enabled on your site, preventing transcoding.', 'godam' ) ); update_post_meta( $attachment_id, 'rtgodam_transcoding_error_code', 'http_auth_enabled' ); + do_action( 'rtgodam_after_attachment_lookup' ); return; } @@ -323,6 +342,14 @@ public function upload_media_to_frappe_backend( $attachment_id, $manual_retransc $api_url = RTGODAM_API_BASE . '/api/resource/Transcoder Job' . ( empty( $transcoding_job_id ) ? '' : '/' . $transcoding_job_id ); + /** + * Fires before reading this attachment's URL/title/author/content, + * so integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $attachment_url = wp_get_attachment_url( $attachment_id ); $file_title = get_the_title( $attachment_id ); @@ -331,7 +358,9 @@ public function upload_media_to_frappe_backend( $attachment_id, $manual_retransc // Get attachment author information. $attachment_author_id = get_post_field( 'post_author', $attachment_id ); $attachment_author = get_user_by( 'id', $attachment_author_id ); - $site_url = get_site_url(); + + // Get attachment content, used as the transcoding request description below. + $attachment_content = get_post_field( 'post_content', $attachment_id ); // Get author name with fallback to username. $author_first_name = ''; @@ -348,18 +377,11 @@ public function upload_media_to_frappe_backend( $attachment_id, $manual_retransc $author_first_name = $attachment_author->user_login ?? ''; } } + do_action( 'rtgodam_after_attachment_lookup' ); - if ( ! defined( 'RTGODAM_TRANSCODER_CALLBACK_URL' ) ) { - include_once RTGODAM_PATH . 'admin/class-rtgodam-transcoder-rest-routes.php'; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingCustomConstant - define( 'RTGODAM_TRANSCODER_CALLBACK_URL', \RTGODAM_Transcoder_Rest_Routes::get_callback_url() ); - } - - $callback_url = RTGODAM_TRANSCODER_CALLBACK_URL; - - /** - * Manually setting the rest api endpoint, we can refactor that later to use similar functionality as callback_url. - */ - $status_callback_url = get_rest_url( get_current_blog_id(), '/godam/v1/transcoding/transcoding-status' ); + include_once RTGODAM_PATH . 'admin/class-rtgodam-transcoder-rest-routes.php'; + $callback_url = \RTGODAM_Transcoder_Rest_Routes::get_callback_url(); + $status_callback_url = \RTGODAM_Transcoder_Rest_Routes::get_callback_url( 'status' ); // Request params. $params = array( @@ -371,7 +393,7 @@ public function upload_media_to_frappe_backend( $attachment_id, $manual_retransc 'orignal_file_name' => $file_name ?? $file_title, 'mime_type' => $mime_type, 'title' => sanitize_text_field( $file_title ), - 'description' => sanitize_textarea_field( (string) get_post_field( 'post_content', $attachment_id ) ), + 'description' => sanitize_textarea_field( (string) $attachment_content ), 'callback_url' => rawurlencode( $callback_url ), 'status_callback' => rawurlencode( $status_callback_url ), 'wp_author_email' => apply_filters( 'godam_author_email_to_send', $author_email, $attachment_id ), @@ -487,7 +509,13 @@ public function add_media_transcoding_status_js( $response, $attachment ) { // than its MIME type alone: text/plain covers .srt/.asc/.c/.cc/.h as well as .txt, and // those are never transcoded, so a MIME-only test gave every subtitle and source file // in the library a transcoding spinner that never resolved. - $is_pdf = rtgodam_is_supported_document_attachment( $attachment->ID ); + // + // Fires its own before/after pair, separate from the one further below: this call + // happens ahead of the early "supported type" return, so it cannot share that later + // bracket without extending it across the return too. + do_action( 'rtgodam_before_attachment_lookup' ); + $is_pdf = rtgodam_is_supported_document_attachment( $attachment->ID ); + do_action( 'rtgodam_after_attachment_lookup' ); $is_image = 'image' === substr( $mime_type, 0, 5 ); // Only process supported attachment types. @@ -495,6 +523,18 @@ public function add_media_transcoding_status_js( $response, $attachment ) { return $response; } + /** + * Fires before resolving/reading this attachment's transcoding, + * virtual-media, and CDN image-size meta for the media library JS + * response, so integrations that centralize media on another site + * can switch context first. This reads and (re)writes several + * rtgodam_* postmeta keys plus the _godam_original_id marker, all + * keyed on $attachment->ID. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $transcoded_url = get_post_meta( $attachment->ID, 'rtgodam_transcoded_url', true ); $transcoding_status = get_post_meta( $attachment->ID, 'rtgodam_transcoding_status', true ); @@ -616,6 +656,8 @@ public function add_media_transcoding_status_js( $response, $attachment ) { } } + do_action( 'rtgodam_after_attachment_lookup' ); + return $response; } @@ -953,61 +995,81 @@ private function godam_replace_attachment_with_external_file( $attachment_id, $f return new \WP_Error( 'invalid_input', __( 'Invalid attachment ID or URL.', 'godam' ) ); } - // Validate the attachment. - $attachment = get_post( $attachment_id ); - if ( ! $attachment || 'attachment' !== $attachment->post_type ) { - return new \WP_Error( 'invalid_attachment', __( 'Invalid attachment ID.', 'godam' ) ); - } + /** + * Fires before validating that $attachment_id resolves to a real + * attachment post, and stays open through every subsequent read + * and write on that same attachment below -- update_attached_file(), + * wp_update_post()'s MIME-type update, and the final + * wp_update_attachment_metadata() -- so integrations that centralize + * media on another site can switch context once for this whole + * read-modify-write sequence instead of losing it between separate + * brackets. Wrapped in try/finally because this method returns + * early from several points (invalid attachment, missing + * filesystem, failed download, failed move). + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + // Validate the attachment. + $attachment = get_post( $attachment_id ); + if ( ! $attachment || 'attachment' !== $attachment->post_type ) { + return new \WP_Error( 'invalid_attachment', __( 'Invalid attachment ID.', 'godam' ) ); + } - require_once ABSPATH . 'wp-admin/includes/file.php'; - require_once ABSPATH . 'wp-admin/includes/media.php'; - require_once ABSPATH . 'wp-admin/includes/image.php'; + require_once ABSPATH . 'wp-admin/includes/file.php'; + require_once ABSPATH . 'wp-admin/includes/media.php'; + require_once ABSPATH . 'wp-admin/includes/image.php'; - global $wp_filesystem; + global $wp_filesystem; - WP_Filesystem(); + WP_Filesystem(); - if ( ! $wp_filesystem ) { - return new \WP_Error( 'fs_unavailable', __( 'Could not initialize WordPress filesystem.', 'godam' ) ); - } + if ( ! $wp_filesystem ) { + return new \WP_Error( 'fs_unavailable', __( 'Could not initialize WordPress filesystem.', 'godam' ) ); + } - // Download file to temporary location. - $temp_file = download_url( $file_url ); + // Download file to temporary location. + $temp_file = download_url( $file_url ); - if ( is_wp_error( $temp_file ) ) { - return $temp_file; - } + if ( is_wp_error( $temp_file ) ) { + return $temp_file; + } - // Prepare new file path in uploads. - $upload_dir = wp_upload_dir(); - $new_filename = wp_basename( wp_parse_url( $file_url, PHP_URL_PATH ) ); - $new_filepath = trailingslashit( $upload_dir['path'] ) . $new_filename; + // Prepare new file path in uploads. + $upload_dir = wp_upload_dir(); + $new_filename = wp_basename( wp_parse_url( $file_url, PHP_URL_PATH ) ); + $new_filepath = trailingslashit( $upload_dir['path'] ) . $new_filename; - // Move temp file into uploads with WP_Filesystem. - $moved = $wp_filesystem->move( $temp_file, $new_filepath, true ); + // Move temp file into uploads with WP_Filesystem. + $moved = $wp_filesystem->move( $temp_file, $new_filepath, true ); - if ( ! $moved ) { - $wp_filesystem->delete( $temp_file ); - return new \WP_Error( 'file_move_failed', __( 'Could not move file into uploads directory.', 'godam' ) ); - } + if ( ! $moved ) { + $wp_filesystem->delete( $temp_file ); + return new \WP_Error( 'file_move_failed', __( 'Could not move file into uploads directory.', 'godam' ) ); + } - // Update attachment file info. - update_attached_file( $attachment_id, $new_filepath ); + // Update attachment file info. + update_attached_file( $attachment_id, $new_filepath ); - // update mime type. - $filetype = wp_check_filetype( $new_filename, null ); - if ( $filetype['type'] ) { - wp_update_post( - array( - 'ID' => $attachment_id, - 'post_mime_type' => $filetype['type'], - ) - ); - } + // update mime type. + $filetype = wp_check_filetype( $new_filename, null ); + if ( $filetype['type'] ) { + wp_update_post( + array( + 'ID' => $attachment_id, + 'post_mime_type' => $filetype['type'], + ) + ); + } - // Regenerate metadata. - $metadata = wp_generate_attachment_metadata( $attachment_id, $new_filepath ); - wp_update_attachment_metadata( $attachment_id, $metadata ); + // Regenerate metadata. + $metadata = wp_generate_attachment_metadata( $attachment_id, $new_filepath ); + + wp_update_attachment_metadata( $attachment_id, $metadata ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } return $attachment_id; } @@ -1027,28 +1089,50 @@ public function download_transcoded_mp4_source( $attachment_id, $job_id, $job_fo return; } - // Check if video attachment. - $attachment_mime_type = get_post_mime_type( $attachment_id ); + /** + * Fires before reading/mutating this attachment's data, so + * integrations that centralize media on another site can switch + * context first. + * + * 'rtgodam_handle_callback_finished' is a public, third-party- + * triggerable extension point (see its docblock in + * class-rtgodam-transcoder-rest-routes.php) — and even for its own + * built-in caller, handle_callback()'s before/after bracket around + * the 'wp-media' branch has already closed by the time this fires, + * several lines later in that method. Wrapped here defensively, in + * a try/finally since this method returns early from several + * points, rather than relying on an already-open bracket from + * whichever caller triggered the hook. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + // Check if video attachment. + $attachment_mime_type = get_post_mime_type( $attachment_id ); - if ( 'video' !== substr( $attachment_mime_type, 0, 5 ) ) { - return; - } + if ( 'video' !== substr( $attachment_mime_type, 0, 5 ) ) { + return; + } - // Check if mp4_url is provided in the request. - $transcoded_mp4_url = esc_url( $request->get_param( 'mp4_url' ) ); + // Check if mp4_url is provided in the request. + $transcoded_mp4_url = esc_url( $request->get_param( 'mp4_url' ) ); - if ( empty( $transcoded_mp4_url ) ) { - return; - } + if ( empty( $transcoded_mp4_url ) ) { + return; + } - // Replace the existing attachment file with the transcoded MP4. - $attachment_id = $this->godam_replace_attachment_with_external_file( $attachment_id, $transcoded_mp4_url ); + // Replace the existing attachment file with the transcoded MP4. + $attachment_id = $this->godam_replace_attachment_with_external_file( $attachment_id, $transcoded_mp4_url ); - if ( is_wp_error( $attachment_id ) ) { - // Log the error for debugging purposes. - if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { - error_log( 'MP4 video replacement failed: ' . $attachment_id->get_error_message() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging. + if ( is_wp_error( $attachment_id ) ) { + // Log the error for debugging purposes. + if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { + error_log( 'MP4 video replacement failed: ' . $attachment_id->get_error_message() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging. + } } + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } } @@ -1063,32 +1147,47 @@ public function download_transcoded_mp4_source( $attachment_id, $job_id, $job_fo * @return string The filtered attachment URL. */ public function filter_attachment_url_for_virtual_media( $url, $post_id ) { - $attachment_mime_type = get_post_mime_type( $post_id ); - $godam_original_id = get_post_meta( $post_id, '_godam_original_id', true ); - - // For WordPress-uploaded images, use CDN URL only when GoDAM sizes map exists. - // Otherwise WP may build thumbnail URLs using local metadata + CDN base path, - // which breaks old images (dimension mismatch like 350x263 vs 350x262). - if ( 'image' === substr( $attachment_mime_type, 0, 5 ) ) { - $rtgodam_image_sizes = $this->get_rtgodam_image_sizes( $post_id ); - $rtgodam_transcoded_url = get_post_meta( $post_id, 'rtgodam_transcoded_url', true ); - $can_use_cdn_src = ( ! empty( $godam_original_id ) || ! empty( $rtgodam_image_sizes ) ); - - if ( $can_use_cdn_src && ! empty( $rtgodam_transcoded_url ) ) { - return esc_url( $rtgodam_transcoded_url ); + /** + * Fires before reading this attachment's mime type, GoDAM CDN + * image-size map, transcoded-URL meta, and (for virtual media) its + * post row/guid, so integrations that centralize media on another + * site can switch context first. Wrapped in try/finally because + * this method returns from several points once it determines which + * URL to use. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $attachment_mime_type = get_post_mime_type( $post_id ); + $godam_original_id = get_post_meta( $post_id, '_godam_original_id', true ); + + // For WordPress-uploaded images, use CDN URL only when GoDAM sizes map exists. + // Otherwise WP may build thumbnail URLs using local metadata + CDN base path, + // which breaks old images (dimension mismatch like 350x263 vs 350x262). + if ( 'image' === substr( $attachment_mime_type, 0, 5 ) ) { + $rtgodam_image_sizes = $this->get_rtgodam_image_sizes( $post_id ); + $rtgodam_transcoded_url = get_post_meta( $post_id, 'rtgodam_transcoded_url', true ); + $can_use_cdn_src = ( ! empty( $godam_original_id ) || ! empty( $rtgodam_image_sizes ) ); + + if ( $can_use_cdn_src && ! empty( $rtgodam_transcoded_url ) ) { + return esc_url( $rtgodam_transcoded_url ); + } } - } - if ( ! empty( $godam_original_id ) ) { - $attachment = get_post( $post_id ); - $transcoded_mp4_url = $attachment->guid; // For virtual media, we store the transcoded MP4 URL in the guid. + if ( ! empty( $godam_original_id ) ) { + $attachment = get_post( $post_id ); + $transcoded_mp4_url = $attachment->guid; // For virtual media, we store the transcoded MP4 URL in the guid. - if ( ! empty( $transcoded_mp4_url ) ) { - return esc_url( $transcoded_mp4_url ); + if ( ! empty( $transcoded_mp4_url ) ) { + return esc_url( $transcoded_mp4_url ); + } } - } - return $url; + return $url; + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } } /** @@ -1132,26 +1231,40 @@ public function filter_image_srcset_meta( $image_meta, $size_array, $image_src, return $image_meta; } - $rtgodam_image_sizes = $this->get_rtgodam_image_sizes( $attachment_id ); - if ( empty( $rtgodam_image_sizes ) ) { - return $image_meta; - } + /** + * Fires before reading this attachment's GoDAM CDN image-size map + * and transcoded-URL meta, so integrations that centralize media + * on another site can switch context first. Wrapped in try/finally + * because this method returns early once it determines no CDN data + * exists for the attachment. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $rtgodam_image_sizes = $this->get_rtgodam_image_sizes( $attachment_id ); + if ( empty( $rtgodam_image_sizes ) ) { + return $image_meta; + } - $cdn_src = get_post_meta( $attachment_id, 'rtgodam_transcoded_url', true ); - if ( empty( $cdn_src ) ) { - return $image_meta; - } + $cdn_src = get_post_meta( $attachment_id, 'rtgodam_transcoded_url', true ); + if ( empty( $cdn_src ) ) { + return $image_meta; + } - $cdn_host = wp_parse_url( $cdn_src, PHP_URL_HOST ); - $src_host = wp_parse_url( $image_src, PHP_URL_HOST ); + $cdn_host = wp_parse_url( $cdn_src, PHP_URL_HOST ); + $src_host = wp_parse_url( $image_src, PHP_URL_HOST ); - // Only act when the src is already served from the CDN and the file path - // still carries a sub-directory prefix (i.e. hasn't been stripped yet). - if ( $cdn_host && $src_host && $cdn_host === $src_host && wp_basename( $image_meta['file'] ) !== $image_meta['file'] ) { - $image_meta['file'] = wp_basename( $image_meta['file'] ); - } + // Only act when the src is already served from the CDN and the file path + // still carries a sub-directory prefix (i.e. hasn't been stripped yet). + if ( $cdn_host && $src_host && $cdn_host === $src_host && wp_basename( $image_meta['file'] ) !== $image_meta['file'] ) { + $image_meta['file'] = wp_basename( $image_meta['file'] ); + } - return $image_meta; + return $image_meta; + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } } /** @@ -1168,68 +1281,82 @@ public function filter_image_srcset_meta( $image_meta, $size_array, $image_src, * @return array|false Filtered sources array or false. */ public function filter_virtual_media_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- Filter signature requires these params. - $attachment_mime_type = get_post_mime_type( $attachment_id ); - if ( 'image' !== substr( $attachment_mime_type, 0, 5 ) ) { - return $sources; - } + /** + * Fires before reading this attachment's MIME type, virtual-media + * original-ID, and GoDAM CDN image-size meta, so integrations that + * centralize media on another site can switch context first. + * Wrapped in try/finally because this method returns early from + * several points while deciding whether/how to rebuild the srcset. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $attachment_mime_type = get_post_mime_type( $attachment_id ); + if ( 'image' !== substr( $attachment_mime_type, 0, 5 ) ) { + return $sources; + } - // Rebuild sources array for virtual media. - if ( empty( $sources ) || ! is_array( $sources ) ) { - return $sources; - } + // Rebuild sources array for virtual media. + if ( empty( $sources ) || ! is_array( $sources ) ) { + return $sources; + } - // Check if virtual media or if rtgodam_image_sizes meta exists (indicating GoDAM-managed image). - $godam_original_id = get_post_meta( $attachment_id, '_godam_original_id', true ); - $rtgodam_image_sizes = $this->get_rtgodam_image_sizes( $attachment_id ); + // Check if virtual media or if rtgodam_image_sizes meta exists (indicating GoDAM-managed image). + $godam_original_id = get_post_meta( $attachment_id, '_godam_original_id', true ); + $rtgodam_image_sizes = $this->get_rtgodam_image_sizes( $attachment_id ); - if ( empty( $godam_original_id ) && empty( $rtgodam_image_sizes ) ) { - return $sources; - } + if ( empty( $godam_original_id ) && empty( $rtgodam_image_sizes ) ) { + return $sources; + } - // If rtgodam_image_sizes meta exists, use it to build the srcset. - // This is the case for GoDAM-managed images which may not be virtual but still need correct srcset URLs. - if ( ! empty( $rtgodam_image_sizes ) ) { - - // Prepare new sources array based on rtgodam_image_sizes meta. - // Keyed by width to deduplicate and match WordPress's expected format. - $new_sources = array(); - foreach ( $rtgodam_image_sizes as $image_size ) { - // Skip entries that do not have a valid URL or width to avoid invalid srcset entries. - if ( empty( $image_size['url'] ) || empty( $image_size['width'] ) ) { - continue; - } + // If rtgodam_image_sizes meta exists, use it to build the srcset. + // This is the case for GoDAM-managed images which may not be virtual but still need correct srcset URLs. + if ( ! empty( $rtgodam_image_sizes ) ) { - $width = intval( $image_size['width'] ); - $new_sources[ $width ] = array( - 'url' => esc_url( $image_size['url'] ), - 'descriptor' => 'w', - 'value' => $width, - ); - } + // Prepare new sources array based on rtgodam_image_sizes meta. + // Keyed by width to deduplicate and match WordPress's expected format. + $new_sources = array(); + foreach ( $rtgodam_image_sizes as $image_size ) { + // Skip entries that do not have a valid URL or width to avoid invalid srcset entries. + if ( empty( $image_size['url'] ) || empty( $image_size['width'] ) ) { + continue; + } + + $width = intval( $image_size['width'] ); + $new_sources[ $width ] = array( + 'url' => esc_url( $image_size['url'] ), + 'descriptor' => 'w', + 'value' => $width, + ); + } - $sources = $new_sources; - } elseif ( ! empty( $godam_original_id ) ) { - // Compatibility handling for virtual media created before GoDAM image sizes meta was implemented. - // In this case, we will reconstruct the URLs based on the original image URL and the file names in the sources array. + $sources = $new_sources; + } elseif ( ! empty( $godam_original_id ) ) { + // Compatibility handling for virtual media created before GoDAM image sizes meta was implemented. + // In this case, we will reconstruct the URLs based on the original image URL and the file names in the sources array. - // Use the current image URL as the base for all subsizes. - $base_url = trailingslashit( untrailingslashit( dirname( $image_src ) ) ); + // Use the current image URL as the base for all subsizes. + $base_url = trailingslashit( untrailingslashit( dirname( $image_src ) ) ); - // Rebuild sources array for virtual media. - foreach ( $sources as &$source ) { + // Rebuild sources array for virtual media. + foreach ( $sources as &$source ) { - // Get last string after the last slash in the file url. - $file_basename = basename( $source['url'] ); + // Get last string after the last slash in the file url. + $file_basename = basename( $source['url'] ); - // Rebuild the full URL using the base URL and the file basename. - $url = $base_url . ltrim( $file_basename, '/' ); + // Rebuild the full URL using the base URL and the file basename. + $url = $base_url . ltrim( $file_basename, '/' ); - $source['url'] = esc_url( $url ); + $source['url'] = esc_url( $url ); + } + unset( $source ); // Break the reference. } - unset( $source ); // Break the reference. - } - return $sources; + return $sources; + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } } /** @@ -1320,46 +1447,61 @@ public function filter_rtgodam_content_img_tag( $filtered_image, $context, $atta return $filtered_image; } - $mime_type = get_post_mime_type( $attachment_id ); - if ( 'image' !== substr( $mime_type, 0, 5 ) ) { - return $filtered_image; - } - - // Don't change the image src for virtual media as well. - $godam_original_id = get_post_meta( $attachment_id, '_godam_original_id', true ); - if ( ! empty( $godam_original_id ) ) { - return $filtered_image; - } + /** + * Fires before reading this attachment's MIME type, virtual-media + * original-ID, and GoDAM CDN image-size/transcoded-URL meta, so + * integrations that centralize media on another site can switch + * context first. Wrapped in try/finally because this method + * returns from several points while deciding whether to rewrite + * the rendered src. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $mime_type = get_post_mime_type( $attachment_id ); + if ( 'image' !== substr( $mime_type, 0, 5 ) ) { + return $filtered_image; + } - // If rtgodam_image_sizes meta exists, it indicates this is a GoDAM-managed image and we should attempt to replace the src with the CDN URL if available. - $rtgodam_image_sizes = $this->get_rtgodam_image_sizes( $attachment_id ); - if ( empty( $rtgodam_image_sizes ) ) { - return $filtered_image; - } + // Don't change the image src for virtual media as well. + $godam_original_id = get_post_meta( $attachment_id, '_godam_original_id', true ); + if ( ! empty( $godam_original_id ) ) { + return $filtered_image; + } - $cdn_src = get_post_meta( $attachment_id, 'rtgodam_transcoded_url', true ); - if ( empty( $cdn_src ) ) { - return $filtered_image; - } + // If rtgodam_image_sizes meta exists, it indicates this is a GoDAM-managed image and we should attempt to replace the src with the CDN URL if available. + $rtgodam_image_sizes = $this->get_rtgodam_image_sizes( $attachment_id ); + if ( empty( $rtgodam_image_sizes ) ) { + return $filtered_image; + } - // If the current src is already on the same CDN host, it is already a correctly-sized - // CDN URL (e.g. a subsize chosen via the Image block). Don't overwrite it with the - // full-size CDN URL. - if ( preg_match( '/\bsrc="([^"]*)"/', $filtered_image, $src_match ) ) { - $cdn_host = wp_parse_url( $cdn_src, PHP_URL_HOST ); - $current_host = wp_parse_url( $src_match[1], PHP_URL_HOST ); - if ( $cdn_host && $current_host && $cdn_host === $current_host ) { + $cdn_src = get_post_meta( $attachment_id, 'rtgodam_transcoded_url', true ); + if ( empty( $cdn_src ) ) { return $filtered_image; } - } - $updated_image = preg_replace( - '/\bsrc="[^"]*"/', - ' src="' . esc_url( $cdn_src ) . '"', - $filtered_image, - 1 - ); + // If the current src is already on the same CDN host, it is already a correctly-sized + // CDN URL (e.g. a subsize chosen via the Image block). Don't overwrite it with the + // full-size CDN URL. + if ( preg_match( '/\bsrc="([^"]*)"/', $filtered_image, $src_match ) ) { + $cdn_host = wp_parse_url( $cdn_src, PHP_URL_HOST ); + $current_host = wp_parse_url( $src_match[1], PHP_URL_HOST ); + if ( $cdn_host && $current_host && $cdn_host === $current_host ) { + return $filtered_image; + } + } + + $updated_image = preg_replace( + '/\bsrc="[^"]*"/', + ' src="' . esc_url( $cdn_src ) . '"', + $filtered_image, + 1 + ); - return is_string( $updated_image ) ? $updated_image : $filtered_image; + return is_string( $updated_image ) ? $updated_image : $filtered_image; + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } } } diff --git a/inc/classes/class-media-usage-backfill.php b/inc/classes/class-media-usage-backfill.php index 66d6f1d89b..6260c7ce8c 100644 --- a/inc/classes/class-media-usage-backfill.php +++ b/inc/classes/class-media-usage-backfill.php @@ -393,7 +393,7 @@ private function run_timed_batches( $blog_id ) { } catch ( \Throwable $e ) { // Mark the post as processed so a single poisoned post cannot // stall the backfill in an infinite retry loop. - update_post_meta( (int) $post->ID, Media_Usage_Tracker::POST_META_KEY, array() ); + update_post_meta( (int) $post->ID, Media_Usage_Tracker::POST_META_KEY, array() ); // godam-coverage-ignore -- $post is the host post being scanned; POST_META_KEY is a 'processed' marker written on that host post, not on any attachment. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log sprintf( @@ -510,7 +510,7 @@ private function count_pending_posts() { $params = array_merge( $post_types, $statuses, array( Media_Usage_Tracker::POST_META_KEY ) ); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared - $count = (int) $wpdb->get_var( + $count = (int) $wpdb->get_var( // godam-coverage-ignore -- count_pending_posts(): counts pending HOST posts lacking POST_META_KEY (get_post_types() excludes 'attachment' from the query) — same host-post-scoped query as run_timed_batches(), never an attachment. $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} p WHERE p.post_type IN ( {$type_placeholders} ) @@ -540,7 +540,7 @@ private function count_pending_posts() { * @return \WP_Post[] */ private function fetch_pending_posts( $limit ) { - $query = new \WP_Query( + $query = new \WP_Query( // godam-coverage-ignore -- fetch_pending_posts(): queries HOST posts pending the backfill scan; build_wp_query_args()'s post_type comes from get_post_types(), which explicitly excludes 'attachment' via array_diff(), so this never touches attachment data. array_merge( $this->build_wp_query_args(), array( diff --git a/inc/classes/class-media-usage-tracker.php b/inc/classes/class-media-usage-tracker.php index 78f0d9c698..1a0551322a 100644 --- a/inc/classes/class-media-usage-tracker.php +++ b/inc/classes/class-media-usage-tracker.php @@ -253,7 +253,7 @@ private function is_tracked_post_type( $post_type ) { * @return void */ public function on_before_delete_post( $post_id ) { - if ( 'attachment' === get_post_type( $post_id ) ) { + if ( 'attachment' === get_post_type( $post_id ) ) { // godam-coverage-ignore -- on_before_delete_post(): before_delete_post fires for every post type being permanently deleted; this is the type-routing check that filters out attachments (their own usage cleanup happens elsewhere) so the rest of this method can treat $post_id as a host post — not attachment data access. return; } @@ -264,7 +264,7 @@ public function on_before_delete_post( $post_id ) { $this->unregister_media_usage( $attachment_id, $post_id, 'content' ); } - delete_post_meta( $post_id, self::POST_META_KEY ); + delete_post_meta( $post_id, self::POST_META_KEY ); // godam-coverage-ignore -- on_before_delete_post(): $post_id is guaranteed non-attachment (the function's own post_type guard returns early otherwise); deletes that host post's own POST_META_KEY tracking marker, not attachment data. } // ------------------------------------------------------------------------- @@ -284,7 +284,7 @@ public function sync_post_attachments( $post_id, $post_content ) { $new_ids = $this->extract_attachment_ids( $post_content ); // Featured image lives outside post_content — add it separately. - $thumbnail_id = (int) get_post_meta( $post_id, '_thumbnail_id', true ); + $thumbnail_id = (int) get_post_meta( $post_id, '_thumbnail_id', true ); // godam-coverage-ignore -- sync_post_attachments(): $post_id is always the host post being scanned (both callers exclude 'attachment'); reads that post's own '_thumbnail_id' pointer, not attachment data. if ( $thumbnail_id > 0 ) { $new_ids = array_values( array_unique( array_merge( $new_ids, array( $thumbnail_id ) ) ) ); } @@ -308,7 +308,7 @@ public function sync_post_attachments( $post_id, $post_content ) { } // Persist the new set so the next save can diff cheaply. - update_post_meta( $post_id, self::POST_META_KEY, array_values( $new_ids ) ); + update_post_meta( $post_id, self::POST_META_KEY, array_values( $new_ids ) ); // godam-coverage-ignore -- sync_post_attachments(): $post_id is always the host post being scanned; writes that post's own POST_META_KEY 'processed' marker (mirrors class-media-usage-backfill.php:396), not attachment data. } // ------------------------------------------------------------------------- @@ -344,26 +344,62 @@ public function register_media_usage( $attachment_id, $post_id, $source = 'conte return; } - $map = $this->get_usage_sources( $attachment_id ); - $existing = isset( $map[ $post_id ] ) ? $map[ $post_id ] : array(); + // Captured before the switch below, so this is always the site $post_id + // actually belongs to (the one currently active), not the media site. + $blog_id = get_current_blog_id(); + $key = $this->make_usage_key( $blog_id, $post_id ); + + /** + * Fires before reading/writing the attachment-keyed usage index, so + * integrations that centralize media on another site can switch + * context first. $post_id belongs to whatever site is currently + * active and must stay untouched, so the switch is scoped tightly to + * the attachment-meta calls below and is always restored before + * get_post_type( $post_id ) or schedule_log_media_view() run. + * + * May fire re-entrantly: this call can be nested inside another + * already-open before/after pair (see get_usage_sources() / + * save_usage_sources() below — each of which fires its own + * before/after pair around its own meta access while this outer + * bracket is still open). Listeners must balance switches with a + * stack (e.g. WordPress's own switch_to_blog()/restore_current_blog(), + * which already handles this via $_wp_switched_stack) rather than a + * single before/after flag, or the first inner after() will restore + * context prematurely. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + + $map = $this->get_usage_sources( $attachment_id, $blog_id ); + $existing = isset( $map[ $key ] ) ? $map[ $key ]['sources'] : array(); $was_referenced = ! empty( $existing ); if ( in_array( $source, $existing, true ) ) { + do_action( 'rtgodam_after_attachment_lookup' ); return; // Already recorded for this source; nothing changes. } - $existing[] = $source; - $map[ $post_id ] = $existing; - $this->save_usage_sources( $attachment_id, $map ); + $existing[] = $source; + $map[ $key ] = array( + 'blog_id' => $blog_id, + 'post_id' => $post_id, + 'sources' => $existing, + ); + $this->save_usage_sources( $attachment_id, $map, $blog_id ); - // First source to reference this pair → notify GoDAM Central. - if ( ! $was_referenced ) { - $godam_id = $this->get_godam_id_for_attachment( $attachment_id ); - if ( $godam_id ) { - $type = '' !== $post_type ? $post_type : (string) get_post_type( $post_id ); - $this->schedule_log_media_view( $godam_id, $post_id, $this->get_wp_site(), $type ); - } + $godam_id = ! $was_referenced ? $this->get_godam_id_for_attachment( $attachment_id ) : ''; + + do_action( 'rtgodam_after_attachment_lookup' ); + + // First source to reference this pair → notify GoDAM Central. get_post_type() + // and schedule_log_media_view() (which captures get_current_blog_id() for the + // async payload) must run against the post's own site, not the attachment's — + // hence running this after the lookup above has already been restored. + if ( $godam_id ) { + $type = '' !== $post_type ? $post_type : (string) get_post_type( $post_id ); // godam-coverage-ignore -- register_media_usage(): $post_id is the referencing HOST post (never the attachment — that's $attachment_id, already wrapped above via get_usage_sources()/save_usage_sources()); deliberately read only after that attachment-scoped lookup is restored, per the docblock above. + $this->schedule_log_media_view( $godam_id, $post_id, $this->get_wp_site(), $type ); } } @@ -389,28 +425,41 @@ public function unregister_media_usage( $attachment_id, $post_id, $source = 'con return; } - $map = $this->get_usage_sources( $attachment_id ); + // See register_media_usage(): captured before the switch below, so + // this is always the site $post_id actually belongs to. + $blog_id = get_current_blog_id(); + $key = $this->make_usage_key( $blog_id, $post_id ); + + // See register_media_usage(): scoped tightly to the attachment-meta + // calls below, always restored before schedule_remove_media_view() + // (which captures get_current_blog_id() for the async payload and + // needs the post's own, originating site). + do_action( 'rtgodam_before_attachment_lookup' ); + + $map = $this->get_usage_sources( $attachment_id, $blog_id ); - if ( ! isset( $map[ $post_id ] ) || ! in_array( $source, $map[ $post_id ], true ) ) { + if ( ! isset( $map[ $key ] ) || ! in_array( $source, $map[ $key ]['sources'], true ) ) { + do_action( 'rtgodam_after_attachment_lookup' ); return; // Nothing to remove for this source. } - $remaining = array_values( array_diff( $map[ $post_id ], array( $source ) ) ); + $remaining = array_values( array_diff( $map[ $key ]['sources'], array( $source ) ) ); if ( empty( $remaining ) ) { - unset( $map[ $post_id ] ); + unset( $map[ $key ] ); } else { - $map[ $post_id ] = $remaining; + $map[ $key ]['sources'] = $remaining; } - $this->save_usage_sources( $attachment_id, $map ); + $this->save_usage_sources( $attachment_id, $map, $blog_id ); + + $godam_id = empty( $remaining ) ? $this->get_godam_id_for_attachment( $attachment_id ) : ''; + + do_action( 'rtgodam_after_attachment_lookup' ); // Last source removed → notify GoDAM Central. - if ( empty( $remaining ) ) { - $godam_id = $this->get_godam_id_for_attachment( $attachment_id ); - if ( $godam_id ) { - $this->schedule_remove_media_view( $godam_id, $post_id, $this->get_wp_site() ); - } + if ( $godam_id ) { + $this->schedule_remove_media_view( $godam_id, $post_id, $this->get_wp_site() ); } } @@ -424,37 +473,103 @@ public function unregister_media_usage( $attachment_id, $post_id, $source = 'con * @return int[] */ public function get_usage_post_ids( $attachment_id ) { + /** + * Fires before reading this attachment's usage-index meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $ids = get_post_meta( $attachment_id, self::ATTACHMENT_META_KEY, true ); + do_action( 'rtgodam_after_attachment_lookup' ); + return is_array( $ids ) ? array_map( 'intval', $ids ) : array(); } + /** + * Build the composite, per-site-unique key used by the source-aware map. + * + * @param int $blog_id Blog ID the post belongs to. + * @param int $post_id Post ID, local to that blog. + * @return string + */ + private function make_usage_key( $blog_id, $post_id ) { + return ( (int) $blog_id ) . ':' . ( (int) $post_id ); + } + /** * Read the source-aware reference map for an attachment. * - * Lazily migrates legacy data: on installs predating the source map, the - * existing `_godam_usage_post_ids` entries are treated as the 'content' - * source (the only writer before this API existed). The migration is + * Lazily migrates legacy data, oldest first: entries from before blog_id + * qualification (bare `int $post_id => string[] $sources`) and entries from + * before the source map existed at all (`_godam_usage_post_ids` only) are both + * assumed to belong to `$blog_id` — the same assumption every older version of + * this code already made when it read the current blog directly, since neither + * legacy shape recorded a site of its own. This is necessarily a best-effort + * guess for pre-existing data (there is no way to recover which site actually + * wrote a bare legacy entry), but it never makes an already-correct pair + * ambiguous, and every write from here on is unambiguous. Migrations are * persisted on the next save_usage_sources() call. * * @param int $attachment_id Attachment WP post ID. - * @return array Map of post ID → source list. + * @param int $blog_id Blog ID to attribute migrated/legacy entries to. + * Callers must capture this via get_current_blog_id() + * BEFORE firing rtgodam_before_attachment_lookup, since + * this method itself runs inside that lookup bracket + * and a listener may have already switched sites by + * the time it executes. + * @return array Map keyed by make_usage_key(). */ - private function get_usage_sources( $attachment_id ) { + private function get_usage_sources( $attachment_id, $blog_id ) { + /** + * Fires before reading this attachment's source-aware usage map, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $map = get_post_meta( $attachment_id, self::SOURCES_META_KEY, true ); + do_action( 'rtgodam_after_attachment_lookup' ); if ( is_array( $map ) ) { $normalized = array(); - foreach ( $map as $post_id => $sources ) { - $normalized[ (int) $post_id ] = array_values( array_filter( array_map( 'strval', (array) $sources ) ) ); + foreach ( $map as $map_key => $entry ) { + if ( is_array( $entry ) && isset( $entry['post_id'], $entry['sources'] ) ) { + // Current shape already. + $entry_blog_id = isset( $entry['blog_id'] ) ? (int) $entry['blog_id'] : $blog_id; + $post_id = (int) $entry['post_id']; + $sources = array_values( array_filter( array_map( 'strval', (array) $entry['sources'] ) ) ); + } else { + // Legacy shape: bare int post_id => string[] sources. + $entry_blog_id = $blog_id; + $post_id = (int) $map_key; + $sources = array_values( array_filter( array_map( 'strval', (array) $entry ) ) ); + } + + if ( empty( $sources ) ) { + continue; + } + + $normalized[ $this->make_usage_key( $entry_blog_id, $post_id ) ] = array( + 'blog_id' => $entry_blog_id, + 'post_id' => $post_id, + 'sources' => $sources, + ); } return $normalized; } - // Lazy migration from the legacy post-ID list. + // Lazy migration from the even older legacy post-ID-only list. $legacy = $this->get_usage_post_ids( $attachment_id ); $map = array(); foreach ( $legacy as $post_id ) { - $map[ (int) $post_id ] = array( 'content' ); + $map[ $this->make_usage_key( $blog_id, $post_id ) ] = array( + 'blog_id' => $blog_id, + 'post_id' => (int) $post_id, + 'sources' => array( 'content' ), + ); } return $map; } @@ -462,38 +577,63 @@ private function get_usage_sources( $attachment_id ) { /** * Persist the source-aware reference map and keep the derived post-ID list in sync. * - * @param int $attachment_id Attachment WP post ID. - * @param array $map Map of post ID → source list. + * @param int $attachment_id Attachment WP post ID. + * @param array $map Map keyed by make_usage_key(). + * @param int $blog_id Fallback blog ID for any + * entry in $map missing its + * own (defensive — see + * get_usage_sources()). * @return void */ - private function save_usage_sources( $attachment_id, array $map ) { + private function save_usage_sources( $attachment_id, array $map, $blog_id ) { $clean = array(); - foreach ( $map as $post_id => $sources ) { - $sources = array_values( array_unique( array_filter( (array) $sources ) ) ); + foreach ( $map as $map_key => $entry ) { + $sources = array_values( array_unique( array_filter( (array) ( $entry['sources'] ?? array() ) ) ) ); if ( ! empty( $sources ) ) { - $clean[ (int) $post_id ] = $sources; + $clean[ $map_key ] = array( + 'blog_id' => (int) ( $entry['blog_id'] ?? $blog_id ), + 'post_id' => (int) ( $entry['post_id'] ?? 0 ), + 'sources' => $sources, + ); } } - if ( empty( $clean ) ) { - delete_post_meta( $attachment_id, self::SOURCES_META_KEY ); - delete_post_meta( $attachment_id, self::ATTACHMENT_META_KEY ); - return; - } - - update_post_meta( $attachment_id, self::SOURCES_META_KEY, $clean ); + /** + * Fires before writing this attachment's usage-index meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + if ( empty( $clean ) ) { + delete_post_meta( $attachment_id, self::SOURCES_META_KEY ); + delete_post_meta( $attachment_id, self::ATTACHMENT_META_KEY ); + return; + } - // Derived public list holds real post IDs only — the synthetic anchor 0 - // (block widgets, other non-post contexts) is recorded in the source map - // but never leaks into get_usage_post_ids(). - $post_ids = array(); - foreach ( array_keys( $clean ) as $post_id ) { - $post_id = (int) $post_id; - if ( $post_id > 0 ) { - $post_ids[] = $post_id; + update_post_meta( $attachment_id, self::SOURCES_META_KEY, $clean ); + + // Derived public list holds real post IDs only — the synthetic anchor 0 + // (block widgets, other non-post contexts) is recorded in the source map + // but never leaks into get_usage_post_ids(). Kept as a flat, network-wide + // set of post ID numbers (not blog-qualified) for backward compatibility + // with this method's own documented, unchanged public signature — nothing + // in this codebase resolves these IDs via get_post() without a caller-side + // site switch of its own, so the collapse across sites is informational + // only, not a correctness gap the way the write-side collision was. + $post_ids = array(); + foreach ( $clean as $entry ) { + $post_id = (int) $entry['post_id']; + if ( $post_id > 0 ) { + $post_ids[] = $post_id; + } } + update_post_meta( $attachment_id, self::ATTACHMENT_META_KEY, array_values( array_unique( $post_ids ) ) ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } - update_post_meta( $attachment_id, self::ATTACHMENT_META_KEY, $post_ids ); } /** @@ -503,7 +643,7 @@ private function save_usage_sources( $attachment_id, array $map ) { * @return int[] */ private function get_tracked_attachment_ids( $post_id ) { - $ids = get_post_meta( $post_id, self::POST_META_KEY, true ); + $ids = get_post_meta( $post_id, self::POST_META_KEY, true ); // godam-coverage-ignore -- get_tracked_attachment_ids(): $post_id is always the host post (both callers guarantee non-attachment); reads that post's own POST_META_KEY marker, not attachment data. return is_array( $ids ) ? array_map( 'intval', $ids ) : array(); } @@ -654,7 +794,7 @@ private function extract_ids_from_elementor( $post_id ) { return array(); } - $data = get_post_meta( $post_id, '_elementor_data', true ); + $data = get_post_meta( $post_id, '_elementor_data', true ); // godam-coverage-ignore -- extract_ids_from_elementor(): $post_id is the host post (sole caller is sync_post_attachments()); reads that post's own '_elementor_data' (never present on an attachment, per the elementor-gallery-widget-v1-to-v2 precedent). if ( empty( $data ) || ! is_string( $data ) ) { return array(); } @@ -1138,13 +1278,25 @@ private function maybe_switch_to_blog( $blog_id ) { * @return string GoDAM Central ID, or '' if not a Central media item. */ private function get_godam_id_for_attachment( $attachment_id ) { - $godam_id = get_post_meta( $attachment_id, '_godam_original_id', true ); - if ( ! empty( $godam_id ) ) { - return $godam_id; - } + /** + * Fires before reading this attachment's GoDAM Central identifier + * meta, so integrations that centralize media on another site can + * switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $godam_id = get_post_meta( $attachment_id, '_godam_original_id', true ); + if ( ! empty( $godam_id ) ) { + return $godam_id; + } - $job_id = get_post_meta( $attachment_id, 'rtgodam_transcoding_job_id', true ); - return ! empty( $job_id ) ? $job_id : ''; + $job_id = get_post_meta( $attachment_id, 'rtgodam_transcoding_job_id', true ); + return ! empty( $job_id ) ? $job_id : ''; + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } } /** @@ -1519,6 +1671,18 @@ private function get_attachment_id_by_godam_original_id( $godam_id ) { global $wpdb; + /** + * Fires before resolving a WP attachment post ID from its GoDAM + * Central identifier, so integrations that centralize media on + * another site can switch context first. This is a direct + * $wpdb->postmeta query for the attachment carrying this + * _godam_original_id value — the same attachment-scoped lookup + * get_post_meta() would do, just expressed as raw SQL for + * performance. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $post_id = (int) $wpdb->get_var( $wpdb->prepare( @@ -1526,6 +1690,7 @@ private function get_attachment_id_by_godam_original_id( $godam_id ) { $godam_id ) ); + do_action( 'rtgodam_after_attachment_lookup' ); $this->godam_id_cache[ $godam_id ] = $post_id; return $post_id; diff --git a/inc/classes/class-pages.php b/inc/classes/class-pages.php index 87bcb570cf..21521dd93a 100644 --- a/inc/classes/class-pages.php +++ b/inc/classes/class-pages.php @@ -422,7 +422,22 @@ public function render_video_editor_page() { // Check if user can edit media with given id. $attachment_id = isset( $_GET['id'] ) ? absint( $_GET['id'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended - if ( $attachment_id && ! current_user_can( 'edit_post', $attachment_id ) ) { + $can_edit = true; + + if ( $attachment_id ) { + /** + * Fires before this attachment-specific capability check, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $can_edit = current_user_can( 'edit_post', $attachment_id ); + do_action( 'rtgodam_after_attachment_lookup' ); + } + + if ( ! $can_edit ) { ?>

0 ) { + /** + * Fires before reading this attachment's saved layer meta, + * so integrations that centralize media on another site can + * switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $rtgodam_meta = get_post_meta( $analytics_video_id, 'rtgodam_meta', true ); + do_action( 'rtgodam_after_attachment_lookup' ); + $saved_layers = is_array( $rtgodam_meta ) && ! empty( $rtgodam_meta['layers'] ) && is_array( $rtgodam_meta['layers'] ) ? $rtgodam_meta['layers'] : array(); diff --git a/inc/classes/class-seo.php b/inc/classes/class-seo.php index b9e17ed571..ce213d69cb 100644 --- a/inc/classes/class-seo.php +++ b/inc/classes/class-seo.php @@ -205,8 +205,8 @@ public function save_seo_data_as_postmeta( $post_ID, $post ) { */ $video_seo_schema = apply_filters( 'godam_video_seo_cache_data', $video_seo_schema, $post_ID ); - update_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_META_KEY, $video_seo_schema ); - update_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_UPDATED_META_KEY, time() ); + update_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_META_KEY, $video_seo_schema ); // godam-coverage-ignore -- save_seo_data_as_postmeta(): $post_ID is the host post being saved (save_post action); writes its own cached video SEO schema meta, not attachment data. + update_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_UPDATED_META_KEY, time() ); // godam-coverage-ignore -- save_seo_data_as_postmeta(): $post_ID is the host post being saved (save_post action); writes its own cached-schema-updated timestamp meta, not attachment data. $this->update_attachment_post_mapping( $post_ID, array_unique( $attachments_used ) ); /** @@ -222,8 +222,8 @@ public function save_seo_data_as_postmeta( $post_ID, $post ) { */ do_action( 'godam_video_seo_schema_saved', $post_ID, $video_seo_schema ); } else { - delete_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_META_KEY ); - delete_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_UPDATED_META_KEY ); + delete_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_META_KEY ); // godam-coverage-ignore -- save_seo_data_as_postmeta(): $post_ID is the host post being saved (save_post action); clears its own cached video SEO schema meta, not attachment data. + delete_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_UPDATED_META_KEY ); // godam-coverage-ignore -- save_seo_data_as_postmeta(): $post_ID is the host post being saved (save_post action); clears its own cached-schema-updated timestamp meta, not attachment data. $this->update_attachment_post_mapping( $post_ID, array() ); /** @@ -313,25 +313,42 @@ private function extract_video_seo_schema_from_block( $block, $track_attachments * @return array The SEO data from the attachment. */ public function get_seo_from_attachment( $attachment_id ) { - $attachment = get_post( $attachment_id ); + /** + * Fires before resolving/reading this attachment's post object, + * postmeta, canonical URL and video metadata for SEO schema + * generation, so integrations that centralize media on another site + * can switch context first. Every read below (the attachment post + * itself, its rtgodam_transcoded_url/rtgodam_media_video_thumbnail + * postmeta, its attachment URL, and its video metadata) is scoped to + * this single attachment. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $attachment = get_post( $attachment_id ); - if ( ! $attachment || 'attachment' !== $attachment->post_type ) { - return array(); - } + if ( ! $attachment || 'attachment' !== $attachment->post_type ) { + return array(); + } - $meta = get_post_meta( $attachment_id ); + $meta = get_post_meta( $attachment_id ); - // Get transcoded URL or fallback to attachment URL. - $content_url = ''; - if ( ! empty( $meta['rtgodam_transcoded_url'][0] ) ) { - $content_url = $meta['rtgodam_transcoded_url'][0]; - } else { - $content_url = wp_get_attachment_url( $attachment_id ); + // Get transcoded URL or fallback to attachment URL. + $content_url = ''; + if ( ! empty( $meta['rtgodam_transcoded_url'][0] ) ) { + $content_url = $meta['rtgodam_transcoded_url'][0]; + } else { + $content_url = wp_get_attachment_url( $attachment_id ); + } + + // Get video duration in ISO 8601 format. + $attachment_meta = wp_get_attachment_metadata( $attachment_id ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } - // Get video duration in ISO 8601 format. - $duration = ''; - $attachment_meta = wp_get_attachment_metadata( $attachment_id ); + $duration = ''; if ( ! empty( $attachment_meta['length'] ) && is_numeric( $attachment_meta['length'] ) ) { $duration = $this->seconds_to_iso8601( (int) $attachment_meta['length'] ); } @@ -394,7 +411,7 @@ private function seconds_to_iso8601( $seconds ) { * @return bool True if it's an Elementor post, false otherwise. */ public function is_elementor_post( $post_id ) { - return 'builder' === get_post_meta( $post_id, '_elementor_edit_mode', true ); + return 'builder' === get_post_meta( $post_id, '_elementor_edit_mode', true ); // godam-coverage-ignore -- is_elementor_post(): $post_id is always a host post/page ID at every call site (never an attachment ID); reads that post's own '_elementor_edit_mode' flag. } /** @@ -406,7 +423,18 @@ public function is_elementor_post( $post_id ) { */ public function add_video_duration_for_video_seo( $response, $post ) { if ( 'video' === $post->post_mime_type || str_starts_with( $post->post_mime_type, 'video/' ) ) { + /** + * Fires before reading this attachment's video metadata (duration) + * for the REST API response, so integrations that centralize media + * on another site can switch context first. $post is the + * attachment being serialized by the `rest_prepare_attachment` + * filter, so this is genuinely attachment-scoped. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $meta = wp_get_attachment_metadata( $post->ID ); + do_action( 'rtgodam_after_attachment_lookup' ); if ( ! empty( $meta['length'] ) && is_numeric( $meta['length'] ) ) { $response->data['video_duration_iso8601'] = $this->seconds_to_iso8601( (int) $meta['length'] ); @@ -440,7 +468,7 @@ public function add_video_seo_schema() { } // Read cached SEO schema from post meta (fast!). - $cached_schemas = get_post_meta( $post_id, self::VIDEO_SEO_SCHEMA_META_KEY, true ); + $cached_schemas = get_post_meta( $post_id, self::VIDEO_SEO_SCHEMA_META_KEY, true ); // godam-coverage-ignore -- add_video_seo_schema(): $post_id is get_queried_object_id() (the current page); reads that page's own cached SEO meta, not attachment data. if ( empty( $cached_schemas ) || ! is_array( $cached_schemas ) ) { return; @@ -826,7 +854,7 @@ public function godam_get_video_seo_data_from_elementor( $post_id, $track_attach } // Get the raw Elementor data. - $data = get_post_meta( $post_id, '_elementor_data', true ); + $data = get_post_meta( $post_id, '_elementor_data', true ); // godam-coverage-ignore -- godam_get_video_seo_data_from_elementor(): $post_id is the host post being saved (sole caller passes save_post's $post_ID); reads that post's own '_elementor_data', not attachment data. if ( empty( $data ) ) { return $empty_result; } @@ -920,7 +948,7 @@ public function elementor_save_seo_data_as_postmeta( $post_ID ) { return; } - $edit_mode = get_post_meta( $post_ID, '_elementor_edit_mode', true ); + $edit_mode = get_post_meta( $post_ID, '_elementor_edit_mode', true ); // godam-coverage-ignore -- elementor_save_seo_data_as_postmeta(): $post_ID is the host post being saved; reads its own '_elementor_edit_mode' flag, not attachment data. if ( 'builder' !== $edit_mode ) { return; } @@ -933,13 +961,13 @@ public function elementor_save_seo_data_as_postmeta( $post_ID ) { /** This filter is documented in inc/classes/class-seo.php */ $video_seo_schema = apply_filters( 'godam_video_seo_cache_data', $video_seo_schema, $post_ID ); - update_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_META_KEY, $video_seo_schema ); - update_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_UPDATED_META_KEY, time() ); + update_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_META_KEY, $video_seo_schema ); // godam-coverage-ignore -- elementor_save_seo_data_as_postmeta(): $post_ID is the host post being saved; writes its own cached video SEO schema meta, not attachment data. + update_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_UPDATED_META_KEY, time() ); // godam-coverage-ignore -- elementor_save_seo_data_as_postmeta(): $post_ID is the host post being saved; writes its own cached-schema-updated timestamp meta, not attachment data. $this->update_attachment_post_mapping( $post_ID, array_unique( $attachments_used ) ); do_action( 'godam_video_seo_schema_saved', $post_ID, $video_seo_schema ); } else { - delete_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_META_KEY ); - delete_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_UPDATED_META_KEY ); + delete_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_META_KEY ); // godam-coverage-ignore -- elementor_save_seo_data_as_postmeta(): $post_ID is the host post being saved; clears its own cached video SEO schema meta, not attachment data. + delete_post_meta( $post_ID, self::VIDEO_SEO_SCHEMA_UPDATED_META_KEY ); // godam-coverage-ignore -- elementor_save_seo_data_as_postmeta(): $post_ID is the host post being saved; clears its own cached-schema-updated timestamp meta, not attachment data. $this->update_attachment_post_mapping( $post_ID, array() ); do_action( 'godam_video_seo_schema_cleared', $post_ID ); } @@ -1023,6 +1051,69 @@ public function godam_get_video_seo_data_from_wpbakery( $content, $track_attachm return $seo_data; } + /** + * Build a stable identity string for a [blog_id, post_id] pair, used only to + * compare/dedupe entries in memory — never persisted or parsed back apart. + * + * @param int $blog_id Blog ID the post belongs to. + * @param int $post_id Post ID, local to that blog. + * @return string + */ + private function make_post_ref_key( $blog_id, $post_id ) { + return ( (int) $blog_id ) . ':' . ( (int) $post_id ); + } + + /** + * Read the [blog_id, post_id] reference list for an attachment. + * + * Legacy entries (a bare post ID, from before blog_id qualification) are + * attributed to the *current* blog — the same assumption every older version + * of this code already made, since that shape never recorded a site. This is + * necessarily a best-effort guess for pre-existing data, but every write from + * here on is unambiguous. + * + * @param int $attachment_id Attachment WP post ID. + * @return array Keyed by make_post_ref_key(). + */ + private function get_attachment_post_refs( $attachment_id ) { + $raw = get_post_meta( $attachment_id, self::ATTACHMENT_POSTS_MAP_META_KEY, true ); + $raw = is_array( $raw ) ? $raw : array(); + + $refs = array(); + foreach ( $raw as $entry ) { + if ( is_array( $entry ) && isset( $entry['post_id'] ) ) { + $blog_id = isset( $entry['blog_id'] ) ? (int) $entry['blog_id'] : get_current_blog_id(); + $post_id = (int) $entry['post_id']; + } else { + $blog_id = get_current_blog_id(); + $post_id = (int) $entry; + } + if ( $post_id <= 0 ) { + continue; + } + $refs[ $this->make_post_ref_key( $blog_id, $post_id ) ] = array( + 'blog_id' => $blog_id, + 'post_id' => $post_id, + ); + } + return $refs; + } + + /** + * Persist the [blog_id, post_id] reference list for an attachment. + * + * @param int $attachment_id Attachment WP post ID. + * @param array $refs Keyed by make_post_ref_key(). + * @return void + */ + private function save_attachment_post_refs( $attachment_id, array $refs ) { + if ( empty( $refs ) ) { + delete_post_meta( $attachment_id, self::ATTACHMENT_POSTS_MAP_META_KEY ); + return; + } + update_post_meta( $attachment_id, self::ATTACHMENT_POSTS_MAP_META_KEY, array_values( $refs ) ); + } + /** * Update the mapping of which posts use a specific attachment for SEO schema generation. * @@ -1034,38 +1125,54 @@ private function update_attachment_post_mapping( $post_id, $attachments ) { $attachments = array_values( array_unique( array_filter( array_map( 'absint', $attachments ) ) ) ); // Get current attachments this post was using. - $previous_attachments = get_post_meta( $post_id, self::POST_ATTACHMENTS_META_KEY, true ); + $previous_attachments = get_post_meta( $post_id, self::POST_ATTACHMENTS_META_KEY, true ); // godam-coverage-ignore -- update_attachment_post_mapping(): $post_id is the post being saved; reads its own local POST_ATTACHMENTS_META_KEY tracking meta, not attachment data (see docblock a few lines below). $previous_attachments = is_array( $previous_attachments ) ? $previous_attachments : array(); + // Captured before the switch below, so this is always the site $post_id + // actually belongs to (the one currently active), not the media site. + $blog_id = get_current_blog_id(); + $post_ref = $this->make_post_ref_key( $blog_id, $post_id ); + + /** + * Fires before touching any attachment's reverse-index meta below, + * so integrations that centralize media on another site can switch + * context first. Deliberately does NOT wrap this method's own + * $post_id reads/writes (POST_ATTACHMENTS_META_KEY, above and + * below) — that's the current post being saved, not attachment + * data, and stays local. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + // Remove post from old attachments' mapping. $removed_attachments = array_diff( $previous_attachments, $attachments ); foreach ( $removed_attachments as $attachment_id ) { - $posts_using = get_post_meta( $attachment_id, self::ATTACHMENT_POSTS_MAP_META_KEY, true ); - $posts_using = is_array( $posts_using ) ? $posts_using : array(); - $posts_using = array_diff( $posts_using, array( $post_id ) ); - if ( ! empty( $posts_using ) ) { - update_post_meta( $attachment_id, self::ATTACHMENT_POSTS_MAP_META_KEY, array_values( $posts_using ) ); - } else { - delete_post_meta( $attachment_id, self::ATTACHMENT_POSTS_MAP_META_KEY ); - } + $posts_using = $this->get_attachment_post_refs( $attachment_id ); + unset( $posts_using[ $post_ref ] ); + $this->save_attachment_post_refs( $attachment_id, $posts_using ); } // Add post to new attachments' mapping. $new_attachments = array_diff( $attachments, $previous_attachments ); foreach ( $new_attachments as $attachment_id ) { - $posts_using = get_post_meta( $attachment_id, self::ATTACHMENT_POSTS_MAP_META_KEY, true ); - $posts_using = is_array( $posts_using ) ? $posts_using : array(); - if ( ! in_array( $post_id, $posts_using, true ) ) { - $posts_using[] = $post_id; - update_post_meta( $attachment_id, self::ATTACHMENT_POSTS_MAP_META_KEY, $posts_using ); + $posts_using = $this->get_attachment_post_refs( $attachment_id ); + if ( ! isset( $posts_using[ $post_ref ] ) ) { + $posts_using[ $post_ref ] = array( + 'blog_id' => $blog_id, + 'post_id' => $post_id, + ); + $this->save_attachment_post_refs( $attachment_id, $posts_using ); } } + do_action( 'rtgodam_after_attachment_lookup' ); + // Update post's attachment list. if ( ! empty( $attachments ) ) { - update_post_meta( $post_id, self::POST_ATTACHMENTS_META_KEY, $attachments ); + update_post_meta( $post_id, self::POST_ATTACHMENTS_META_KEY, $attachments ); // godam-coverage-ignore -- update_attachment_post_mapping(): $post_id is the post being saved; writes its own local POST_ATTACHMENTS_META_KEY tracking meta, not attachment data (see docblock above). } else { - delete_post_meta( $post_id, self::POST_ATTACHMENTS_META_KEY ); + delete_post_meta( $post_id, self::POST_ATTACHMENTS_META_KEY ); // godam-coverage-ignore -- update_attachment_post_mapping(): $post_id is the post being saved; clears its own local POST_ATTACHMENTS_META_KEY tracking meta, not attachment data (see docblock above). } } @@ -1075,16 +1182,32 @@ private function update_attachment_post_mapping( $post_id, $attachments ) { * @param int $attachment_id The attachment ID. */ public function schedule_seo_sync_for_attachment( $attachment_id ) { + /** + * Fires before resolving this attachment's post object and its + * reverse-index meta (which posts use it), so integrations that + * centralize media on another site can switch context first. + * $attachment_id arrives directly from WordPress core's + * `edit_attachment` action (fired with the attachment's own post ID), + * so it is genuinely an attachment ID here. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $attachment = get_post( $attachment_id ); // Only process video attachments. if ( ! $attachment || strpos( $attachment->post_mime_type, 'video/' ) !== 0 ) { + do_action( 'rtgodam_after_attachment_lookup' ); return; } // Check if any posts are using this attachment. - $posts_using = get_post_meta( $attachment_id, self::ATTACHMENT_POSTS_MAP_META_KEY, true ); - if ( empty( $posts_using ) || ! is_array( $posts_using ) ) { + $posts_using = $this->get_attachment_post_refs( $attachment_id ); + + do_action( 'rtgodam_after_attachment_lookup' ); + + if ( empty( $posts_using ) ) { return; } @@ -1098,28 +1221,58 @@ public function schedule_seo_sync_for_attachment( $attachment_id ) { * Sync SEO for all posts using a specific attachment. * This runs as a background task when an attachment is updated. * + * Each referencing post is resolved on its own originating site — not + * necessarily the site this background job happens to run on, and not the + * media site either — since ATTACHMENT_POSTS_MAP_META_KEY now records + * blog_id alongside each post ID. + * * @param int $attachment_id The attachment ID. */ public function sync_seo_for_attachment_posts( $attachment_id ) { - $posts_using = get_post_meta( $attachment_id, self::ATTACHMENT_POSTS_MAP_META_KEY, true ); + /** + * Fires before reading this attachment's reverse-index meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $posts_using = $this->get_attachment_post_refs( $attachment_id ); + do_action( 'rtgodam_after_attachment_lookup' ); - if ( empty( $posts_using ) || ! is_array( $posts_using ) ) { + if ( empty( $posts_using ) ) { return; } - foreach ( $posts_using as $post_id ) { - $post = get_post( $post_id ); - if ( ! $post ) { - continue; + $is_multisite = is_multisite(); + + foreach ( $posts_using as $ref ) { + $blog_id = $ref['blog_id']; + $post_id = $ref['post_id']; + + $switched = $is_multisite && $blog_id > 0 && get_current_blog_id() !== $blog_id; + if ( $switched ) { + switch_to_blog( $blog_id ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.switch_to_blog_switch_to_blog } - // Check if it's an Elementor post. - $is_elementor = $this->is_elementor_post( $post_id ); + try { + $post = get_post( $post_id ); // godam-coverage-ignore -- sync_seo_for_attachment_posts(): reads HOST posts referencing the attachment (see the docblock note on this exact line) — documented structural limitation, not a hook-fixable gap. + if ( ! $post ) { + continue; + } - if ( $is_elementor ) { - $this->elementor_save_seo_data_as_postmeta( $post_id ); - } else { - $this->save_seo_data_as_postmeta( $post_id, $post ); + // Check if it's an Elementor post. + $is_elementor = $this->is_elementor_post( $post_id ); + + if ( $is_elementor ) { + $this->elementor_save_seo_data_as_postmeta( $post_id ); + } else { + $this->save_seo_data_as_postmeta( $post_id, $post ); + } + } finally { + if ( $switched ) { + restore_current_blog(); + } } } } diff --git a/inc/classes/class-video-engagement.php b/inc/classes/class-video-engagement.php index da3ca7e769..9c230f802d 100644 --- a/inc/classes/class-video-engagement.php +++ b/inc/classes/class-video-engagement.php @@ -41,7 +41,21 @@ protected function __construct() { public function add_engagement_to_video( $attributes, $instance_id, $easydam_meta_data, $godam_settings ) { $attachment_id = ! empty( $attributes['id'] ) && is_numeric( $attributes['id'] ) ? intval( $attributes['id'] ) : ''; - if ( ! empty( $attachment_id ) && 'transcoded' !== strtolower( get_post_meta( $attachment_id, 'rtgodam_transcoding_status', true ) ) ) { + /** + * Fires before reading this attachment's transcoding status, so + * integrations that centralize media on another site can switch + * context first. A separate, small pair from the get_the_title() + * one below — check_if_engagements_enabled() runs in between and + * reads site-specific settings options, which must not be read from + * the media site. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $rtgodam_transcoding_status = ! empty( $attachment_id ) ? get_post_meta( $attachment_id, 'rtgodam_transcoding_status', true ) : ''; + do_action( 'rtgodam_after_attachment_lookup' ); + + if ( ! empty( $attachment_id ) && 'transcoded' !== strtolower( $rtgodam_transcoding_status ) ) { return ''; } @@ -56,7 +70,16 @@ public function add_engagement_to_video( $attributes, $instance_id, $easydam_met if ( empty( $attributes['title'] ) && ! empty( $attributes['seo']['headline'] ) ) { $attributes['title'] = $attributes['seo']['headline']; } + + /** + * Fires before this get_the_title() fallback, so integrations that + * centralize media on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $title = ! empty( $attributes['title'] ) ? $attributes['title'] : get_the_title( $attachment_id ); + do_action( 'rtgodam_after_attachment_lookup' ); $brand_color = '#000'; // Default brand color. diff --git a/inc/classes/class-video-metadata.php b/inc/classes/class-video-metadata.php index 517f0aabbe..f8f013e22c 100644 --- a/inc/classes/class-video-metadata.php +++ b/inc/classes/class-video-metadata.php @@ -87,31 +87,46 @@ public function save_video_metadata( $attachment_id ) { * @return void */ private function process_video_metadata( $attachment_id ) { - $file_path = get_attached_file( $attachment_id ); - - if ( $this->is_video_attachment( $attachment_id ) && file_exists( $file_path ) ) { - // Check if metadata already exists to avoid unnecessary processing. - $existing_duration = get_post_meta( $attachment_id, '_video_duration', true ); - $existing_size = get_post_meta( $attachment_id, '_video_file_size', true ); - - if ( empty( $existing_duration ) || empty( $existing_size ) ) { - if ( ! function_exists( 'wp_read_video_metadata' ) ) { - require_once ABSPATH . 'wp-admin/includes/media.php'; - } + /** + * Fires before reading/writing this attachment's file path and video + * duration/size meta, so integrations that centralize media on + * another site can switch context first. Hooked to `add_attachment`, + * which fires on every insert regardless of caller — some callers + * already switch before triggering it (safe, this just no-ops + * nested), but nothing guarantees all of them do. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $file_path = get_attached_file( $attachment_id ); + + if ( $this->is_video_attachment( $attachment_id ) && file_exists( $file_path ) ) { + // Check if metadata already exists to avoid unnecessary processing. + $existing_duration = get_post_meta( $attachment_id, '_video_duration', true ); + $existing_size = get_post_meta( $attachment_id, '_video_file_size', true ); + + if ( empty( $existing_duration ) || empty( $existing_size ) ) { + if ( ! function_exists( 'wp_read_video_metadata' ) ) { + require_once ABSPATH . 'wp-admin/includes/media.php'; + } - $metadata = wp_read_video_metadata( $file_path ); + $metadata = wp_read_video_metadata( $file_path ); - // Save duration. - if ( ! empty( $metadata['length'] ) ) { - update_post_meta( $attachment_id, '_video_duration', intval( $metadata['length'] ) ); - } + // Save duration. + if ( ! empty( $metadata['length'] ) ) { + update_post_meta( $attachment_id, '_video_duration', intval( $metadata['length'] ) ); + } - // Save file size. - $file_size = filesize( $file_path ); - if ( $file_size ) { - update_post_meta( $attachment_id, '_video_file_size', $file_size ); + // Save file size. + $file_size = filesize( $file_path ); + if ( $file_size ) { + update_post_meta( $attachment_id, '_video_file_size', $file_size ); + } } } + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } } @@ -137,6 +152,17 @@ private function migrate_existing_video_metadata() { $has_more_videos = true; while ( $has_more_videos ) { + /** + * Fires before querying for video attachments still missing + * duration/file-size meta, so integrations that centralize + * media on another site can switch context first. This + * get_posts() call reads directly from the attachment post + * type (post_type => attachment), batched across every + * matching video on the site. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); // Get a batch of video attachments without metadata. //phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.get_posts_get_posts $videos = get_posts( @@ -159,6 +185,7 @@ private function migrate_existing_video_metadata() { ), ) ); + do_action( 'rtgodam_after_attachment_lookup' ); if ( ! empty( $videos ) ) { // Process this batch. @@ -192,6 +219,19 @@ public function set_media_library_thumbnail( $response, $attachment, $meta ) { / $mime = isset( $response['mime'] ) ? $response['mime'] : ''; $thumbnail_url = ''; + /** + * Fires before reading this attachment's video/PDF/audio-thumbnail + * and `_wp_attachment_metadata` postmeta, so integrations that + * centralize media on another site can switch context first. This + * filter runs on every wp_prepare_attachment_for_js() call + * plugin-wide, including ones GoDAM doesn't control (WP core's + * media modal, REST responses) — self-wrapped so it's correct + * regardless of who triggered it. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + // Documents cover every convertible type, not just PDF: GoDAM Central rasterises page 0 // of the preview for all of them, so an .xlsx gets a real thumbnail too. Keyed off the // attachment rather than the MIME alone, since text/plain also covers .srt/.asc/.c/.h, @@ -220,6 +260,8 @@ public function set_media_library_thumbnail( $response, $attachment, $meta ) { / $response['image']['height'] = $attachment_meta['height'] ?? self::DEFAULT_THUMBNAIL_HEIGHT; } + do_action( 'rtgodam_after_attachment_lookup' ); + return $response; } @@ -235,14 +277,30 @@ public function filter_vimeo_migrated_urls(): void { add_filter( 'wp_get_attachment_url', function ( $url, $post_id ) { - $is_vimeo_migrated = get_post_meta( $post_id, 'rtgodam_is_migrated_vimeo_video', true ); - if ( $is_vimeo_migrated ) { - $remote_url = get_post_meta( $post_id, '_wp_attached_file', true ); - if ( ! empty( $remote_url ) ) { - return $remote_url; + /** + * Fires before reading this attachment's meta, so + * integrations that centralize media on another site can + * switch context first. This filter runs on every + * wp_get_attachment_url() call plugin-wide, including ones + * GoDAM doesn't control (WP core, other plugins) — + * self-wrapped so it's correct regardless of who triggered + * it. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $is_vimeo_migrated = get_post_meta( $post_id, 'rtgodam_is_migrated_vimeo_video', true ); + if ( $is_vimeo_migrated ) { + $remote_url = get_post_meta( $post_id, '_wp_attached_file', true ); + if ( ! empty( $remote_url ) ) { + return $remote_url; + } } + return $url; + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } - return $url; }, 10, 2 @@ -265,6 +323,21 @@ function ( $url, $post_id ) { public function set_media_library_list_thumbnail( $html, $attachment_id, $size, $icon ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- We dont use icon param. if ( is_admin() && 'upload' === get_current_screen()->id && array( 60, 60 ) === $size ) { + /** + * Fires before reading this attachment's video/audio-thumbnail, + * `_godam_icon`, and `_wp_attachment_metadata` postmeta, so + * integrations that centralize media on another site can + * switch context first. This filter runs on every + * wp_get_attachment_image() call plugin-wide, including ones + * GoDAM doesn't control — self-wrapped so it's correct + * regardless of who triggered it. Scoped to the admin + * upload-list-view branch, the only branch that touches + * attachment postmeta. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $thumbnail_url = get_post_meta( $attachment_id, 'rtgodam_media_video_thumbnail', true ); // Virtual GoDAM audio stores its cover in dedicated meta. @@ -284,6 +357,8 @@ public function set_media_library_list_thumbnail( $html, $attachment_id, $size, $height = $attachment_meta['height'] ?? self::DEFAULT_THUMBNAIL_HEIGHT; $html = sprintf( '', esc_attr( $width ), esc_attr( $height ), esc_url( rtgodam_convert_to_https_url( $thumbnail_url ) ) ); } + + do_action( 'rtgodam_after_attachment_lookup' ); } return $html; diff --git a/inc/classes/class-virtual-media-registrar.php b/inc/classes/class-virtual-media-registrar.php index 6df339c9df..b2a5686c4c 100644 --- a/inc/classes/class-virtual-media-registrar.php +++ b/inc/classes/class-virtual-media-registrar.php @@ -68,7 +68,7 @@ public function maybe_register_from_meta_change( $meta_id, $post_id, $meta_key ) return; } - if ( 'attachment' !== get_post_type( $post_id ) ) { + if ( 'attachment' !== get_post_type( $post_id ) ) { // godam-coverage-ignore -- maybe_register_from_meta_change(): added_post_meta/updated_post_meta fire for every post type; this is the type-routing check that filters down to attachments before schedule_register_virtual_media_site() (which wraps its own attachment-meta reads below) — not attachment data access itself. return; } @@ -84,21 +84,33 @@ public function maybe_register_from_meta_change( $meta_id, $post_id, $meta_key ) * @return void */ private function schedule_register_virtual_media_site( int $attachment_id ) { - // Demo assets are shared/public GoDAM media seeded for the onboarding tours, - // not this site's own uploads — don't register the site as a consumer. - if ( get_post_meta( $attachment_id, 'rtgodam_is_demo_attachment', true ) ) { - return; - } + /** + * Fires before reading this attachment's registration-state meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + // Demo assets are shared/public GoDAM media seeded for the onboarding tours, + // not this site's own uploads — don't register the site as a consumer. + if ( get_post_meta( $attachment_id, 'rtgodam_is_demo_attachment', true ) ) { + return; + } - $job_name = get_post_meta( $attachment_id, self::META_ORIGINAL_ID, true ); - // Bail early if there is nothing to register. - if ( empty( $job_name ) ) { - return; - } + $job_name = get_post_meta( $attachment_id, self::META_ORIGINAL_ID, true ); + // Bail early if there is nothing to register. + if ( empty( $job_name ) ) { + return; + } - // Already successfully registered — nothing to do. - if ( get_post_meta( $attachment_id, self::META_REGISTERED, true ) ) { - return; + // Already successfully registered — nothing to do. + if ( get_post_meta( $attachment_id, self::META_REGISTERED, true ) ) { + return; + } + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } if ( function_exists( 'as_enqueue_async_action' ) ) { @@ -207,7 +219,16 @@ public function register_site_for_attachment_if_needed( $attachment_id, $job_nam ); } + /** + * Fires before writing this attachment's registration-state meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); update_post_meta( $attachment_id, self::META_REGISTERED, 1 ); + do_action( 'rtgodam_after_attachment_lookup' ); // Invalidate the cached job ids. delete_transient( 'rtgodam_virtual_media_job_ids' ); @@ -225,8 +246,18 @@ public function register_site_for_attachment_if_needed( $attachment_id, $job_nam public function maybe_remove_virtual_media_site_on_delete( $post_id ) { $post_id = (int) $post_id; + /** + * Fires before reading this (about-to-be-deleted) attachment's + * original-id meta, so integrations that centralize media on + * another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); // Only for virtual media attachments. $job_name = get_post_meta( $post_id, self::META_ORIGINAL_ID, true ); + do_action( 'rtgodam_after_attachment_lookup' ); + if ( empty( $job_name ) ) { return; } diff --git a/inc/classes/cron-jobs/class-retranscode-failed-media.php b/inc/classes/cron-jobs/class-retranscode-failed-media.php index 8b3f375ca0..d4e4c348e9 100644 --- a/inc/classes/cron-jobs/class-retranscode-failed-media.php +++ b/inc/classes/cron-jobs/class-retranscode-failed-media.php @@ -112,6 +112,15 @@ public function retranscode_failed_media() { // If we have exhausted all retry attempts, mark the attachment as permanently // failed and remove it from the retry queue — persist immediately. if ( $retry_count >= self::MAX_RETRY_ATTEMPTS ) { + /** + * Fires before touching this attachment's meta/transcoding + * state, so integrations that centralize media on another + * site can switch context first. $real_attachment_id is a + * genuine attachment ID read from the stored retry queue. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); update_post_meta( $real_attachment_id, 'rtgodam_transcoding_status', 'failed' ); update_post_meta( $real_attachment_id, @@ -119,6 +128,7 @@ public function retranscode_failed_media() { // translators: %d is the maximum number of retry attempts. sprintf( __( 'Transcoding failed after %d retry attempts. GoDAM Central returned a server error on each attempt.', 'godam' ), self::MAX_RETRY_ATTEMPTS ) ); + do_action( 'rtgodam_after_attachment_lookup' ); unset( $failed_transcoding_attachments[ $attachment_id ] ); update_option( 'rtgodam-failed-transcoding-attachments', $failed_transcoding_attachments ); continue; @@ -132,7 +142,23 @@ public function retranscode_failed_media() { update_option( 'rtgodam-failed-transcoding-attachments', $failed_transcoding_attachments ); $transcoder_handler = new \RTGODAM_Transcoder_Handler(); - $transcoder_handler->wp_media_transcoding( $attachment['wp_metadata'], $real_attachment_id, $attachment['autoformat'], true ); + + /** + * Fires before wp_media_transcoding() reads/writes this + * attachment's meta internally, so integrations that centralize + * media on another site can switch context first — the + * checker's own "parameter is safe" exclusion means this call + * is invisible to it, since $real_attachment_id is a plain, + * unmodified parameter to wp_media_transcoding(). + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $transcoder_handler->wp_media_transcoding( $attachment['wp_metadata'], $real_attachment_id, $attachment['autoformat'], true ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } // NOTE: No final update_option here — wp_media_transcoding persists its own // changes (success → removes entry, failure → updates entry) independently. } diff --git a/inc/classes/elementor-widgets/class-godam-document.php b/inc/classes/elementor-widgets/class-godam-document.php index 14a9e80b23..57c3e5e9f9 100644 --- a/inc/classes/elementor-widgets/class-godam-document.php +++ b/inc/classes/elementor-widgets/class-godam-document.php @@ -193,7 +193,18 @@ protected function render() { // The shared render.php emits nothing for an unsupported format, which would leave // a silently empty widget, so flag it in the editor instead, where the author can // act on it. - if ( ! godam_is_supported_document( isset( $document_file['id'] ) ? $document_file['id'] : 0, $document_file['url'] ) ) { + /** + * Fires before checking whether this attachment is a supported + * document type, so integrations that centralize media on another + * site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $is_supported_document = godam_is_supported_document( isset( $document_file['id'] ) ? $document_file['id'] : 0, $document_file['url'] ); + do_action( 'rtgodam_after_attachment_lookup' ); + + if ( ! $is_supported_document ) { $this->render_unsupported_state(); return; } diff --git a/inc/classes/elementor-widgets/class-godam-image.php b/inc/classes/elementor-widgets/class-godam-image.php index 38c5e26b22..b1385125fd 100644 --- a/inc/classes/elementor-widgets/class-godam-image.php +++ b/inc/classes/elementor-widgets/class-godam-image.php @@ -110,8 +110,16 @@ protected function render() { return; } + /** + * Fires before reading this attachment's alt text, so integrations + * that centralize media on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); // Mirror the block: alt comes from the attachment's stored alt text. $alt = $image_id ? (string) get_post_meta( $image_id, '_wp_attachment_image_alt', true ) : ''; + do_action( 'rtgodam_after_attachment_lookup' ); $shortcode_atts = array( 'id' => $image_id, diff --git a/inc/classes/lifter-lms/class-lifter-lms.php b/inc/classes/lifter-lms/class-lifter-lms.php index 2273ca27b7..7d54d73e8a 100644 --- a/inc/classes/lifter-lms/class-lifter-lms.php +++ b/inc/classes/lifter-lms/class-lifter-lms.php @@ -136,7 +136,7 @@ public function has_godam_video_block(): bool { if ( ! $post_id ) { return false; } - $blocks = parse_blocks( get_post( $post_id )->post_content ); + $blocks = parse_blocks( get_post( $post_id )->post_content ); // godam-coverage-ignore -- has_godam_video_block(): $post_id is get_the_ID() (the current post); reads its own post_content, not attachment data. foreach ( $blocks as $block ) { if ( 'godam/video' === $block['blockName'] ) { diff --git a/inc/classes/media-library/class-media-folder-create-zip.php b/inc/classes/media-library/class-media-folder-create-zip.php index 364b2e96d7..cbc5e91034 100644 --- a/inc/classes/media-library/class-media-folder-create-zip.php +++ b/inc/classes/media-library/class-media-folder-create-zip.php @@ -120,7 +120,7 @@ private function get_taxonomy_attachments_batch( $folder_id, $offset = 0, $limit 'update_post_term_cache' => false, ); - $query = new \WP_Query( $args ); + $query = new \WP_Query( $args ); // godam-coverage-ignore -- get_taxonomy_attachments_batch(): covered transitively — sole caller (create_zip_file_batched) wraps the entire batching loop, including this call, in its own before/after pair. $attachment_ids = $query->posts; // Clean up. @@ -185,6 +185,15 @@ private function create_zip_file_batched( $folder_id, $zip_name, $total_attachme $processed = 0; $used_filenames = array(); // Track used filenames to avoid duplicates. + /** + * Fires before this batching loop's per-file get_attached_file() + * reads, so integrations that centralize media on another site can + * switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + // Process in batches. while ( $processed < $total_attachments ) { // Check memory usage before processing batch. @@ -236,6 +245,8 @@ private function create_zip_file_batched( $folder_id, $zip_name, $total_attachme unset( $batch_attachments ); } + do_action( 'rtgodam_after_attachment_lookup' ); + $zip->close(); // Check if any files were added. diff --git a/inc/classes/media-library/class-media-folder-utils.php b/inc/classes/media-library/class-media-folder-utils.php index 977b83f3ac..735b0424ce 100644 --- a/inc/classes/media-library/class-media-folder-utils.php +++ b/inc/classes/media-library/class-media-folder-utils.php @@ -58,6 +58,11 @@ public function get_attachment_count( $folder_id, $force_refresh = false, $mime_ $cache_key = 'attachment_count_' . $folder_id . '_' . $mime_type_key; // Try to get cached count first (unless force refresh is requested). + // This fast path must run before the rtgodam_before_attachment_lookup + // switch below: transients are per-blog options keyed off this site's + // own $folder_id term, so the cache check (and the write near the end + // of this method) has to stay against this site's own storage instead + // of resolving against whatever site gets switched to. if ( ! $force_refresh ) { $cached_count = get_transient( $cache_key ); @@ -66,68 +71,91 @@ public function get_attachment_count( $folder_id, $force_refresh = false, $mime_ } } - global $wpdb; + /** + * Fires before counting attachments in a folder, so integrations that + * centralize media on another site can switch context first — the + * folder taxonomy terms and the attachments assigned to them live + * wherever media is centralized, not necessarily the site issuing + * this call. + * + * This deliberately does not cover the transient cache above/below: + * transients are per-blog options (and go through the per-blog + * object-cache prefix), so caching must stay keyed to and stored on + * the calling site rather than the site this switches to — otherwise + * sites that happen to share a folder term ID would collide on the + * same cached count. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + global $wpdb; - // Build query based on mime type filtering. - if ( empty( $mime_type ) ) { - // No mime type filter. - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - $count = $wpdb->get_var( - $wpdb->prepare( - "SELECT COUNT(DISTINCT p.ID) - FROM {$wpdb->posts} p - INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id - INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id - WHERE p.post_type = 'attachment' - AND p.post_status = 'inherit' - AND tt.taxonomy = 'media-folder' - AND tt.term_id = %d", - $folder_id - ) - ); - } elseif ( is_array( $mime_type ) ) { - // Array of mime types - use IN clause. - $placeholders = implode( ', ', array_fill( 0, count( $mime_type ), '%s' ) ); - $query_params = array_merge( array( $folder_id ), $mime_type ); + // Build query based on mime type filtering. + if ( empty( $mime_type ) ) { + // No mime type filter. + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + $count = $wpdb->get_var( + $wpdb->prepare( + "SELECT COUNT(DISTINCT p.ID) + FROM {$wpdb->posts} p + INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id + INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id + WHERE p.post_type = 'attachment' + AND p.post_status = 'inherit' + AND tt.taxonomy = 'media-folder' + AND tt.term_id = %d", + $folder_id + ) + ); + } elseif ( is_array( $mime_type ) ) { + // Array of mime types - use IN clause. + $placeholders = implode( ', ', array_fill( 0, count( $mime_type ), '%s' ) ); + $query_params = array_merge( array( $folder_id ), $mime_type ); + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + $count = $wpdb->get_var( + $wpdb->prepare( + "SELECT COUNT(DISTINCT p.ID) + FROM {$wpdb->posts} p + INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id + INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id + WHERE p.post_type = 'attachment' + AND p.post_status = 'inherit' + AND tt.taxonomy = 'media-folder' + AND tt.term_id = %d + AND p.post_mime_type IN ($placeholders)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + $query_params + ) + ); + } else { + // Single mime type - use LIKE. + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + $count = $wpdb->get_var( + $wpdb->prepare( + "SELECT COUNT(DISTINCT p.ID) + FROM {$wpdb->posts} p + INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id + INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id + WHERE p.post_type = 'attachment' + AND p.post_status = 'inherit' + AND tt.taxonomy = 'media-folder' + AND tt.term_id = %d + AND p.post_mime_type LIKE %s", + $folder_id, + $wpdb->esc_like( $mime_type ) . '%' + ) + ); + } - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - $count = $wpdb->get_var( - $wpdb->prepare( - "SELECT COUNT(DISTINCT p.ID) - FROM {$wpdb->posts} p - INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id - INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id - WHERE p.post_type = 'attachment' - AND p.post_status = 'inherit' - AND tt.taxonomy = 'media-folder' - AND tt.term_id = %d - AND p.post_mime_type IN ($placeholders)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared - $query_params - ) - ); - } else { - // Single mime type - use LIKE. - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - $count = $wpdb->get_var( - $wpdb->prepare( - "SELECT COUNT(DISTINCT p.ID) - FROM {$wpdb->posts} p - INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id - INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id - WHERE p.post_type = 'attachment' - AND p.post_status = 'inherit' - AND tt.taxonomy = 'media-folder' - AND tt.term_id = %d - AND p.post_mime_type LIKE %s", - $folder_id, - $wpdb->esc_like( $mime_type ) . '%' - ) - ); + $count = absint( $count ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } - $count = absint( $count ); - - // Cache the result. + // Cache the result. This runs after the switch above has been unwound, + // so it's stored on the calling site's own options table under this + // site's own $cache_key rather than whatever site was switched to. set_transient( $cache_key, $count, self::CACHE_EXPIRATION ); return $count; diff --git a/inc/classes/migrations/class-elementor-gallery-widget-v1-to-v2.php b/inc/classes/migrations/class-elementor-gallery-widget-v1-to-v2.php index cae7e0a014..226f2bccca 100644 --- a/inc/classes/migrations/class-elementor-gallery-widget-v1-to-v2.php +++ b/inc/classes/migrations/class-elementor-gallery-widget-v1-to-v2.php @@ -102,7 +102,7 @@ public static function run() { // godam-gallery widget. LIKE is a coarse prefilter; a precise // confirmation check runs inside the loop before any write. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $rows = $wpdb->get_results( + $rows = $wpdb->get_results( // godam-coverage-ignore -- run(): the discovery query that finds candidate post IDs via a SQL LIKE prefilter on '_elementor_data' — same marker as lines 128/150, so it never matches an attachment post either. $wpdb->prepare( "SELECT p.ID FROM {$wpdb->posts} p @@ -125,7 +125,7 @@ public static function run() { foreach ( $rows as $row ) { $post_id = (int) $row->ID; - $raw = get_post_meta( $post_id, '_elementor_data', true ); + $raw = get_post_meta( $post_id, '_elementor_data', true ); // godam-coverage-ignore -- run(): reads '_elementor_data' on Elementor-built posts/pages (prefiltered by SQL) — never an attachment post type. if ( ! is_string( $raw ) || '' === $raw ) { ++$skipped; @@ -147,7 +147,7 @@ public static function run() { continue; } - $result = update_post_meta( + $result = update_post_meta( // godam-coverage-ignore -- run(): writes '_elementor_data' back to the same Elementor-built posts/pages — never an attachment post type. $post_id, '_elementor_data', wp_slash( wp_json_encode( $new_elements, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ) diff --git a/inc/classes/migrations/class-gallery-v1-to-v2.php b/inc/classes/migrations/class-gallery-v1-to-v2.php index cf053afca2..e31977c352 100644 --- a/inc/classes/migrations/class-gallery-v1-to-v2.php +++ b/inc/classes/migrations/class-gallery-v1-to-v2.php @@ -155,7 +155,7 @@ public static function run() { // LIKE clause – do not shift the window and cause later posts to // be silently skipped. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $rows = $wpdb->get_results( + $rows = $wpdb->get_results( // godam-coverage-ignore -- run(): post_status NOT IN (...,'inherit') excludes attachments by construction — scans HOST posts/pages for legacy block markup in their own post_content, not attachment data. $wpdb->prepare( "SELECT ID, post_content FROM {$wpdb->posts} @@ -191,7 +191,7 @@ public static function run() { continue; } - $result = wp_update_post( + $result = wp_update_post( // godam-coverage-ignore -- run(): updates the HOST post/page fetched by the SELECT above, whose post_status NOT IN (...,'inherit') excludes attachments by construction — rewrites legacy block markup in that post's own post_content, never attachment data. array( 'ID' => (int) $row->ID, 'post_content' => $new_content, diff --git a/inc/classes/migrations/class-godam-cpt-cleanup.php b/inc/classes/migrations/class-godam-cpt-cleanup.php index 3cc20fbf20..df30300664 100644 --- a/inc/classes/migrations/class-godam-cpt-cleanup.php +++ b/inc/classes/migrations/class-godam-cpt-cleanup.php @@ -263,7 +263,7 @@ public static function run() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $total = (int) $wpdb->get_var( + $total = (int) $wpdb->get_var( // godam-coverage-ignore -- run(): post_type = self::POST_TYPE ('godam-video') — a discontinued CPT being permanently deleted, never 'attachment'. $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s", self::POST_TYPE @@ -348,7 +348,7 @@ public static function process_batch( int $blog_id = 0 ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $ids = $wpdb->get_col( + $ids = $wpdb->get_col( // godam-coverage-ignore -- process_batch(): post_type = self::POST_TYPE ('godam-video'); same discontinued-CPT deletion as run(), not attachment data. $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s ORDER BY ID ASC LIMIT %d", self::POST_TYPE, @@ -392,7 +392,7 @@ public static function process_batch( int $blog_id = 0 ) { // Check how many posts remain to decide whether to queue another batch. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $remaining = (int) $wpdb->get_var( + $remaining = (int) $wpdb->get_var( // godam-coverage-ignore -- process_batch(): post_type = self::POST_TYPE ('godam-video'); the remaining-count check for the same discontinued-CPT deletion, not attachment data. $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s", self::POST_TYPE diff --git a/inc/classes/migrations/class-wpbakery-gallery-shortcode-v1-to-v2.php b/inc/classes/migrations/class-wpbakery-gallery-shortcode-v1-to-v2.php index abd5ee62cf..5d25059015 100644 --- a/inc/classes/migrations/class-wpbakery-gallery-shortcode-v1-to-v2.php +++ b/inc/classes/migrations/class-wpbakery-gallery-shortcode-v1-to-v2.php @@ -119,7 +119,7 @@ public static function run() { // prefilter; precise confirmation runs inside the loop before // any write. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $rows = $wpdb->get_results( + $rows = $wpdb->get_results( // godam-coverage-ignore -- run(): post_status NOT IN (...,'inherit') excludes attachments by construction — scans HOST posts/pages for a legacy shortcode in their own post_content, not attachment data. $wpdb->prepare( "SELECT ID, post_content FROM {$wpdb->posts} @@ -146,7 +146,7 @@ public static function run() { continue; } - $result = wp_update_post( + $result = wp_update_post( // godam-coverage-ignore -- run(): updates the HOST post/page fetched by the SELECT above, whose post_status NOT IN (...,'inherit') excludes attachments by construction — rewrites a legacy shortcode in that post's own post_content, never attachment data. array( 'ID' => (int) $row->ID, 'post_content' => $new_content, diff --git a/inc/classes/ninja-forms/class-ninja-forms-field-godam-recorder.php b/inc/classes/ninja-forms/class-ninja-forms-field-godam-recorder.php index 1a1e8c7b50..a0f5c59130 100644 --- a/inc/classes/ninja-forms/class-ninja-forms-field-godam-recorder.php +++ b/inc/classes/ninja-forms/class-ninja-forms-field-godam-recorder.php @@ -660,7 +660,7 @@ public function handle_transcoding_callback( $attachment_id, $job_id, $job_for, return; } - $form_id = get_post_meta( $entry_id, '_form_id', true ); + $form_id = get_post_meta( $entry_id, '_form_id', true ); // godam-coverage-ignore -- handle_transcoding_callback(): $entry_id is a Ninja Forms entry ID used as a postmeta key (not the function's own unused $attachment_id parameter). if ( empty( $form_id ) ) { return; @@ -669,7 +669,7 @@ public function handle_transcoding_callback( $attachment_id, $job_id, $job_for, $meta_key = 'rtgodam_transcoded_url_ninja-forms_' . $form_id . '_' . $entry_id; $meta_value = $post_array['download_url'] ?? ''; - update_post_meta( $entry_id, $meta_key, $meta_value ); + update_post_meta( $entry_id, $meta_key, $meta_value ); // godam-coverage-ignore -- handle_transcoding_callback(): $entry_id is a Ninja Forms entry ID used as a postmeta key (not the function's own unused $attachment_id parameter). } } } diff --git a/inc/classes/rest-api/class-ads.php b/inc/classes/rest-api/class-ads.php index bdf4bfb92b..338c37e17d 100644 --- a/inc/classes/rest-api/class-ads.php +++ b/inc/classes/rest-api/class-ads.php @@ -207,14 +207,26 @@ public function get_video_ad_tag_url( $request ) { return ''; } - // Check if the video exists. - $video = get_post( $video_id ); - if ( empty( $video ) || 'attachment' !== $video->post_type ) { - return ''; - } + /** + * Fires before resolving this attachment's existence/meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + // Check if the video exists. + $video = get_post( $video_id ); + if ( empty( $video ) || 'attachment' !== $video->post_type ) { + return ''; + } - // Get easydam_meta data. - $easydam_meta = get_post_meta( $video_id, 'rtgodam_meta', true ); + // Get easydam_meta data. + $easydam_meta = get_post_meta( $video_id, 'rtgodam_meta', true ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } if ( empty( $easydam_meta ) ) { return ''; diff --git a/inc/classes/rest-api/class-analytics.php b/inc/classes/rest-api/class-analytics.php index 4b050f4f27..b6280b6910 100644 --- a/inc/classes/rest-api/class-analytics.php +++ b/inc/classes/rest-api/class-analytics.php @@ -332,10 +332,21 @@ public function fetch_layer_analytics( WP_REST_Request $request ) { // sites within the same account. $job_id = ''; if ( $attachment_id ) { + /** + * Fires before resolving job_id from attachment meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $job_id = (string) get_post_meta( $attachment_id, 'rtgodam_transcoding_job_id', true ); if ( empty( $job_id ) ) { $job_id = (string) get_post_meta( $attachment_id, '_godam_original_id', true ); } + + do_action( 'rtgodam_after_attachment_lookup' ); } // site_url is a client-supplied *filter*, not a trust boundary: the @@ -479,7 +490,7 @@ private function enrich_placements( $placements ) { continue; } - $placement_post = $placement_post_id ? get_post( $placement_post_id ) : null; + $placement_post = $placement_post_id ? get_post( $placement_post_id ) : null; // godam-coverage-ignore -- enrich_placements(): $placement_post_id is the host page a video was placed on, not an attachment ID. // A trashed post is treated as gone even for users who can edit it: // WordPress maps edit_post on a trashed post to its pre-trash status @@ -488,7 +499,7 @@ private function enrich_placements( $placements ) { // 409). Surfacing an Edit link would be a dead end, and the page is // unreachable for visitors, so it belongs in the deleted state. $is_trashed = $placement_post && 'trash' === $placement_post->post_status; - $can_edit = $placement_post && ! $is_trashed && current_user_can( 'edit_post', $placement_post_id ); + $can_edit = $placement_post && ! $is_trashed && current_user_can( 'edit_post', $placement_post_id ); // godam-coverage-ignore -- enrich_placements(): checks edit capability on $placement_post_id, the host page a video was placed on, not an attachment ID (see get_post() above). $is_viewable = $placement_post && ! $is_trashed && is_post_publicly_viewable( $placement_post ); $edit_url = $can_edit ? get_edit_post_link( $placement_post_id, 'raw' ) : null; @@ -496,14 +507,14 @@ private function enrich_placements( $placements ) { // Public page: reveal title, permalink and (if capable) an edit link. $permalink = get_permalink( $placement_post ); - $placements[ $index ]['title'] = get_the_title( $placement_post ); + $placements[ $index ]['title'] = get_the_title( $placement_post ); // godam-coverage-ignore -- enrich_placements(): $placement_post is the host page a video was placed on, not an attachment (see get_post() above). $placements[ $index ]['permalink'] = $permalink ? $permalink : null; $placements[ $index ]['edit_url'] = $edit_url ? $edit_url : null; $placements[ $index ]['is_deleted'] = false; } elseif ( $can_edit ) { // Not public (private/draft/pending), but this user may edit it: // show the real title + an Edit link, without a public permalink. - $placements[ $index ]['title'] = get_the_title( $placement_post ); + $placements[ $index ]['title'] = get_the_title( $placement_post ); // godam-coverage-ignore -- enrich_placements(): $placement_post is the host page a video was placed on, not an attachment (see get_post() above). $placements[ $index ]['permalink'] = null; $placements[ $index ]['edit_url'] = $edit_url ? $edit_url : null; $placements[ $index ]['is_deleted'] = false; @@ -643,7 +654,7 @@ public function fetch_analytics_data( WP_REST_Request $request ) { if ( ! empty( $post_ids ) ) { // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.get_posts_get_posts - $posts = get_posts( + $posts = get_posts( // godam-coverage-ignore -- fetch_analytics_data(): $post_ids are HOST post IDs (post_type "any") from the external microservice's per-page view-count data, not attachment IDs — same host-page pattern as enrich_placements() above. array( 'post__in' => $post_ids, 'post_type' => 'any', @@ -657,7 +668,7 @@ public function fetch_analytics_data( WP_REST_Request $request ) { if ( isset( $post_views[ $post->ID ] ) ) { $post_details[] = array( 'id' => $post->ID, - 'title' => get_the_title( $post ), + 'title' => get_the_title( $post ), // godam-coverage-ignore -- fetch_analytics_data(): $post comes from $post_ids above, HOST post IDs (post_type "any"), not attachment IDs (see get_posts() above). 'url' => get_permalink( $post ), 'views' => $post_views[ $post->ID ], ); @@ -998,16 +1009,25 @@ public function fetch_top_videos( WP_REST_Request $request ) { $top_videos = $body['top_videos'] ?? array(); + /** + * Fires before enriching each top-video row with local attachment + * data, so integrations that centralize media on another site can + * switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + foreach ( $top_videos as &$video ) { if ( ! empty( $video['video_id'] ) ) { $attachment_id = intval( $video['video_id'] ); $attachment = get_post( $attachment_id ); - + if ( $attachment && 'attachment' === $attachment->post_type ) { // Check if this is virtual media (from GoDAM Tab). $godam_original_id = get_post_meta( $attachment_id, '_godam_original_id', true ); $is_virtual_media = ! empty( $godam_original_id ); - + // Get file size - different approach for virtual vs local media. if ( $is_virtual_media ) { // For virtual media, get size from metadata. @@ -1016,11 +1036,11 @@ public function fetch_top_videos( WP_REST_Request $request ) { } else { // For local media, get actual file size. $file_path = get_attached_file( $attachment_id ); - + $file_size = ( $file_path && file_exists( $file_path ) ) ? filesize( $file_path ) : 0; - + } - + $video['video_size'] = round( $file_size / ( 1024 * 1024 ), 2 ); $video['title'] = get_the_title( $attachment_id ); $video['exists'] = true; @@ -1039,6 +1059,14 @@ public function fetch_top_videos( WP_REST_Request $request ) { } } + /** + * Fires after enriching top-video rows, so integrations can restore + * the site context switched in `rtgodam_before_attachment_lookup`. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_after_attachment_lookup' ); + return new WP_REST_Response( array( 'status' => 'success', @@ -1105,8 +1133,10 @@ private function resolve_top_videos_id_filter( $search, $hide_deleted ) { $query_args['s'] = $search; } + do_action( 'rtgodam_before_attachment_lookup' ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.get_posts_get_posts -- bounded, `suppress_filters => false` (cacheable), and the common no-search case is transient-cached; matches the existing convention in this class. $ids = array_map( 'intval', (array) get_posts( $query_args ) ); + do_action( 'rtgodam_after_attachment_lookup' ); if ( $is_full_set ) { set_transient( $cache_key, $ids, 5 * MINUTE_IN_SECONDS ); diff --git a/inc/classes/rest-api/class-dynamic-gallery.php b/inc/classes/rest-api/class-dynamic-gallery.php index 9cb0c988fd..fcbe2f0f8f 100644 --- a/inc/classes/rest-api/class-dynamic-gallery.php +++ b/inc/classes/rest-api/class-dynamic-gallery.php @@ -146,6 +146,15 @@ public function render_gallery( WP_REST_Request $request ) { $args['offset'] = $offset; $args['no_found_rows'] = true; + /** + * Fires before querying and resolving this page's attachment + * (video) posts, so integrations that centralize media on another + * site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $query = new \WP_Query( $args ); ob_start(); @@ -199,6 +208,15 @@ public function render_gallery( WP_REST_Request $request ) { } } + /** + * Fires after resolving this page's attachment (video) posts, so + * integrations can restore the site context switched in + * `rtgodam_before_attachment_lookup`. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_after_attachment_lookup' ); + wp_reset_postdata(); return new WP_REST_Response( diff --git a/inc/classes/rest-api/class-dynamic-shortcode.php b/inc/classes/rest-api/class-dynamic-shortcode.php index 44daabe585..f87eefe118 100644 --- a/inc/classes/rest-api/class-dynamic-shortcode.php +++ b/inc/classes/rest-api/class-dynamic-shortcode.php @@ -79,24 +79,36 @@ public function render_shortcode( WP_REST_Request $request ) { $godam_context = $request->get_param( 'godam_context' ); - $attachment = get_post( $id ); - - if ( ! $attachment || 'attachment' !== $attachment->post_type ) { - return new WP_REST_Response( - array( - 'status' => 'error', - 'message' => 'Video not found.', - ), - 404 - ); + /** + * Fires before resolving this attachment's URL/meta/sources, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + $attachment = get_post( $id ); + + if ( ! $attachment || 'attachment' !== $attachment->post_type ) { + return new WP_REST_Response( + array( + 'status' => 'error', + 'message' => 'Video not found.', + ), + 404 + ); + } + + $transcoded_url = strval( rtgodam_get_transcoded_url_from_attachment( $id ) ); + $hls_transcoded_url = strval( rtgodam_get_hls_transcoded_url_from_attachment( $id ) ); + $video_src = strval( wp_get_attachment_url( $id ) ); + $video_src_type = strval( get_post_mime_type( $id ) ); + $sources = array(); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } - $transcoded_url = strval( rtgodam_get_transcoded_url_from_attachment( $id ) ); - $hls_transcoded_url = strval( rtgodam_get_hls_transcoded_url_from_attachment( $id ) ); - $video_src = strval( wp_get_attachment_url( $id ) ); - $video_src_type = strval( get_post_mime_type( $id ) ); - $sources = array(); - if ( ! empty( $transcoded_url ) ) { $sources[] = array( 'src' => $transcoded_url, @@ -124,9 +136,26 @@ public function render_shortcode( WP_REST_Request $request ) { do_action( 'rtgodam_shortcode_before_render', $id ); // Get the video title and date. + /** + * Fires before reading this attachment's title/date, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $video_title = get_the_title( $id ); $video_date = get_the_date( 'F j, Y', $id ); + /** + * Fires after reading this attachment's title/date, so + * integrations can restore the site context switched in + * `rtgodam_before_attachment_lookup`. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_after_attachment_lookup' ); + // Add filters for title and date. $video_title = apply_filters( 'rtgodam_shortcode_video_title', $video_title, $id ); $video_date = apply_filters( 'rtgodam_shortcode_video_date', $video_date, $id ); diff --git a/inc/classes/rest-api/class-engagement.php b/inc/classes/rest-api/class-engagement.php index f87da7b64c..55511453e4 100644 --- a/inc/classes/rest-api/class-engagement.php +++ b/inc/classes/rest-api/class-engagement.php @@ -933,7 +933,18 @@ public function get_transcoder_job_id( $video_id ) { if ( 0 === strpos( $video_id, 'cmmid_' ) ) { return preg_replace( '/^cmmid_/', '', $video_id ); } + + /** + * Fires before reading this attachment's transcoding job ID, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $transcoder_job_id = get_post_meta( $video_id, 'rtgodam_transcoding_job_id', true ); + do_action( 'rtgodam_after_attachment_lookup' ); + return ! empty( $transcoder_job_id ) ? $transcoder_job_id : null; } diff --git a/inc/classes/rest-api/class-jetpack.php b/inc/classes/rest-api/class-jetpack.php index e2cb19c8f5..937bc4876a 100644 --- a/inc/classes/rest-api/class-jetpack.php +++ b/inc/classes/rest-api/class-jetpack.php @@ -164,7 +164,7 @@ public function get_jetpack_forms( $request ) { do { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - $posts_with_forms = $wpdb->get_results( + $posts_with_forms = $wpdb->get_results( // godam-coverage-ignore -- get_jetpack_forms(): post_type IN ('page','post') is an explicit allow-list; scans ordinary content pages/posts for embedded Jetpack form blocks, never attachment. $wpdb->prepare( "SELECT DISTINCT p.ID, p.post_title, p.post_content FROM {$wpdb->posts} p @@ -301,7 +301,7 @@ public function get_jetpack_form( $request ) { $form_number = intval( $form_parts[1] ); // Get the post content. - $post = get_post( $post_id ); + $post = get_post( $post_id ); // godam-coverage-ignore -- get_jetpack_form(): $post_id is the host post embedding the Jetpack form block, not an attachment ID. if ( ! $post ) { return new \WP_Error( 'post_not_found', __( 'Post not found.', 'godam' ), array( 'status' => 404 ) ); } @@ -379,7 +379,7 @@ private function render_jetpack_form_directly( $form_block, $post_id ) { } // Store current post state. - $target_post = get_post( $post_id ); + $target_post = get_post( $post_id ); // godam-coverage-ignore -- render_jetpack_form_directly(): $post_id is the same host post embedding the Jetpack form block that its sole caller (get_jetpack_form) already resolved, not an attachment ID. if ( ! $target_post ) { return false; } @@ -431,7 +431,7 @@ public static function get_rendered_form_html_static( $form_id ) { $form_number = intval( $form_parts[1] ); // Get the post content. - $post = get_post( $post_id ); + $post = get_post( $post_id ); // godam-coverage-ignore -- get_rendered_form_html_static(): $post_id is the host post embedding the Jetpack form block, not an attachment ID. if ( ! $post ) { return false; } @@ -509,7 +509,7 @@ private static function render_jetpack_form_directly_static( $form_block, $post_ } // Store current post state. - $target_post = get_post( $post_id ); + $target_post = get_post( $post_id ); // godam-coverage-ignore -- render_jetpack_form_directly_static(): $post_id is the same host post embedding the Jetpack form block that its sole caller (get_rendered_form_html_static) already resolved, not an attachment ID. if ( ! $target_post ) { return false; } @@ -765,7 +765,7 @@ private function map_field_names( $frontend_fields, $original_form ) { */ private function load_form_into_memory_with_origin( $form_id, $form_hash, $origin_post_id ) { // Get the origin post. - $origin_post = get_post( $origin_post_id ); + $origin_post = get_post( $origin_post_id ); // godam-coverage-ignore -- load_form_into_memory_with_origin(): $origin_post_id is the host post that originated the form submission (REST "origin-post-id" param or the same form-ID parsing as get_jetpack_form), not an attachment ID. if ( ! $origin_post ) { return false; } diff --git a/inc/classes/rest-api/class-media-library.php b/inc/classes/rest-api/class-media-library.php index 6243deb368..2e2b6ca5b6 100644 --- a/inc/classes/rest-api/class-media-library.php +++ b/inc/classes/rest-api/class-media-library.php @@ -539,6 +539,40 @@ private function update_image_attachment_meta( $sizes, $job_id, $attachment_id = return false; } + /** + * Fires before resolving/mutating attachment data for this image + * subsize update, so integrations that centralize media on another + * site can switch context first. The job-ID fallback lookup below is + * a direct $wpdb->postmeta query, just as site-scoped as + * get_post_meta(). + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + return $this->update_image_attachment_meta_after_lookup( $sizes, $job_id, $attachment_id ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } + } + + /** + * Resolve the attachment ID (if not already known) and persist the + * generated image subsizes to attachment meta. + * + * Split out of update_image_attachment_meta() so the wp-dam site-switch + * bracket can wrap this entire body — including the job-ID fallback + * lookup, which is itself a raw, site-scoped $wpdb->postmeta query. + * + * @since 2.2.0 + * + * @param array $sizes Array of sizes data. + * @param int $job_id Job ID, used to resolve $attachment_id when it isn't already known. + * @param int $attachment_id Attachment ID, or 0/non-numeric to resolve via $job_id. + * + * @return bool True if successful, false otherwise. + */ + private function update_image_attachment_meta_after_lookup( $sizes, $job_id, $attachment_id ) { if ( empty( $attachment_id ) || ! is_numeric( $attachment_id ) ) { $attachment_id = rtgodam_get_post_id_by_meta_key_and_value( 'rtgodam_transcoding_job_id', $job_id ); } @@ -553,8 +587,8 @@ private function update_image_attachment_meta( $sizes, $job_id, $attachment_id = ); } - $attachment_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true ); - $is_virtual = ! empty( get_post_meta( $attachment_id, '_godam_original_id', true ) ); + $attachment_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true ); // godam-coverage-ignore -- update_image_attachment_meta_after_lookup(): covered transitively — caller (update_image_attachment_meta) wraps the entire call in try/finally. + $is_virtual = ! empty( get_post_meta( $attachment_id, '_godam_original_id', true ) ); // godam-coverage-ignore -- update_image_attachment_meta_after_lookup(): covered transitively — caller (update_image_attachment_meta) wraps the entire call in try/finally. // Normalize attachment meta to an array with a sizes key. if ( ! is_array( $attachment_meta ) ) { @@ -685,15 +719,15 @@ function ( $carry, $item ) { // Backfill the "file" key so WordPress does not bail early while building srcset. if ( empty( $attachment_meta['file'] ) ) { - $full_url = wp_get_attachment_url( $attachment_id ); + $full_url = wp_get_attachment_url( $attachment_id ); // godam-coverage-ignore -- update_image_attachment_meta_after_lookup(): covered transitively — caller (update_image_attachment_meta) wraps the entire call in try/finally. if ( $full_url ) { $path = wp_parse_url( $full_url, PHP_URL_PATH ); $attachment_meta['file'] = ltrim( wp_basename( $path ), '/' ); } } - update_post_meta( $attachment_id, '_wp_attachment_metadata', $attachment_meta ); - update_post_meta( $attachment_id, 'rtgodam_image_sizes', $rtgodam_image_sizes ); + update_post_meta( $attachment_id, '_wp_attachment_metadata', $attachment_meta ); // godam-coverage-ignore -- update_image_attachment_meta_after_lookup(): covered transitively — caller (update_image_attachment_meta) wraps the entire call in try/finally. + update_post_meta( $attachment_id, 'rtgodam_image_sizes', $rtgodam_image_sizes ); // godam-coverage-ignore -- update_image_attachment_meta_after_lookup(): covered transitively — caller (update_image_attachment_meta) wraps the entire call in try/finally. return true; } @@ -771,23 +805,38 @@ public function assign_images_to_folder( $request ) { return new \WP_Error( 'invalid_attachment', __( 'No attachment IDs provided.', 'godam' ), array( 'status' => 400 ) ); } - // Prime the post + object-term caches once so the per-id checks below don't each - // hit the database (a large drag-move otherwise fired hundreds of queries). - _prime_post_caches( $attachment_ids ); - update_object_term_cache( $attachment_ids, 'attachment' ); + /** + * Fires before resolving these attachments' post types and edit + * capabilities, so integrations that centralize media on another + * site can switch context first. Wraps the cache-priming calls + * too, since they resolve this same site-scoped post/term data for + * every ID in this request, and the loop below can return early + * per-attachment. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + // Prime the post + object-term caches once so the per-id checks below don't each + // hit the database (a large drag-move otherwise fired hundreds of queries). + _prime_post_caches( $attachment_ids ); + update_object_term_cache( $attachment_ids, 'attachment' ); - foreach ( $attachment_ids as $attachment_id ) { - if ( 'attachment' !== get_post_type( $attachment_id ) ) { - return new \WP_Error( 'invalid_attachment', __( 'Invalid attachment ID.', 'godam' ), array( 'status' => 400 ) ); - } + foreach ( $attachment_ids as $attachment_id ) { + if ( 'attachment' !== get_post_type( $attachment_id ) ) { + return new \WP_Error( 'invalid_attachment', __( 'Invalid attachment ID.', 'godam' ), array( 'status' => 400 ) ); + } - if ( ! current_user_can( 'edit_post', $attachment_id ) ) { - return new \WP_Error( - 'rest_forbidden', - __( 'You are not allowed to modify one or more of these attachments.', 'godam' ), - array( 'status' => 403 ) - ); + if ( ! current_user_can( 'edit_post', $attachment_id ) ) { + return new \WP_Error( + 'rest_forbidden', + __( 'You are not allowed to modify one or more of these attachments.', 'godam' ), + array( 'status' => 403 ) + ); + } } + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); } // Moving an attachment OUT of a locked folder empties that (protected) folder — @@ -894,8 +943,17 @@ private function remove_all_terms_from_id( $post_id, $taxonomy ) { public function get_exif_data( $request ) { $attachment_id = $request->get_param( 'attachment_id' ); + /** + * Fires before resolving this attachment's file path, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); // Get the file path of the image. $file_path = get_attached_file( $attachment_id ); + do_action( 'rtgodam_after_attachment_lookup' ); if ( ! file_exists( $file_path ) ) { return new \WP_Error( 'image_not_found', __( 'Image file not found.', 'godam' ), array( 'status' => 404 ) ); @@ -967,6 +1025,33 @@ private function format_fnumber( $fnumber ) { public function get_video_thumbnails( $request ) { $attachment_id = $request->get_param( 'attachment_id' ); + /** + * Fires before reading/mutating this attachment's thumbnail data, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + return $this->get_video_thumbnails_after_lookup( $attachment_id ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } + } + + /** + * Resolve and return this attachment's video thumbnail data. + * + * Split out of get_video_thumbnails() so the wp-dam site-switch bracket + * can wrap this entire body. + * + * @since 2.2.0 + * + * @param int $attachment_id Attachment ID. + * @return \WP_REST_Response|\WP_Error + */ + private function get_video_thumbnails_after_lookup( $attachment_id ) { // Check if attachment is of type video. $mime_type = get_post_mime_type( $attachment_id ); @@ -1169,6 +1254,34 @@ public function upload_custom_video_thumbnail( $request ) { $attachment_id = $request->get_param( 'attachment_id' ); $thumbnail_url = $request->get_param( 'thumbnail_url' ); + /** + * Fires before reading/mutating this attachment's thumbnail data, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + return $this->upload_custom_video_thumbnail_after_lookup( $attachment_id, $thumbnail_url ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } + } + + /** + * Validate and persist a custom video thumbnail for an attachment. + * + * Split out of upload_custom_video_thumbnail() so the wp-dam site-switch + * bracket can wrap this entire body. + * + * @since 2.2.0 + * + * @param int $attachment_id Attachment ID. + * @param string $thumbnail_url Thumbnail URL. + * @return \WP_REST_Response|\WP_Error + */ + private function upload_custom_video_thumbnail_after_lookup( $attachment_id, $thumbnail_url ) { $mime_type = get_post_mime_type( $attachment_id ); if ( ! preg_match( '/^video\//', $mime_type ) ) { @@ -1226,6 +1339,34 @@ public function remove_custom_video_thumbnail( $request ) { $attachment_id = $request->get_param( 'attachment_id' ); $thumbnail_url = $request->get_param( 'thumbnail_url' ); + /** + * Fires before reading/mutating this attachment's thumbnail data, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + return $this->remove_custom_video_thumbnail_after_lookup( $attachment_id, $thumbnail_url ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } + } + + /** + * Validate and remove a custom video thumbnail from an attachment. + * + * Split out of remove_custom_video_thumbnail() so the wp-dam site-switch + * bracket can wrap this entire body. + * + * @since 2.2.0 + * + * @param int $attachment_id Attachment ID. + * @param string $thumbnail_url Thumbnail URL. + * @return \WP_REST_Response|\WP_Error + */ + private function remove_custom_video_thumbnail_after_lookup( $attachment_id, $thumbnail_url ) { $mime_type = get_post_mime_type( $attachment_id ); if ( ! preg_match( '/^video\//', $mime_type ) ) { @@ -1285,6 +1426,35 @@ public function set_video_thumbnail( $request ) { $thumbnail_url = $request->get_param( 'thumbnail_url' ); $placeholder_thumbnail_url = $request->get_param( 'placeholder_thumbnail_url' ); + /** + * Fires before reading/mutating this attachment's thumbnail data, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + return $this->set_video_thumbnail_after_lookup( $attachment_id, $thumbnail_url, $placeholder_thumbnail_url ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } + } + + /** + * Validate and persist the selected video thumbnail for an attachment. + * + * Split out of set_video_thumbnail() so the wp-dam site-switch bracket + * can wrap this entire body. + * + * @since 2.2.0 + * + * @param int $attachment_id Attachment ID. + * @param string $thumbnail_url Thumbnail URL. + * @param string $placeholder_thumbnail_url Optional placeholder thumbnail URL. + * @return \WP_REST_Response|\WP_Error + */ + private function set_video_thumbnail_after_lookup( $attachment_id, $thumbnail_url, $placeholder_thumbnail_url ) { // Check if attachment is of type video. $mime_type = get_post_mime_type( $attachment_id ); @@ -2029,10 +2199,22 @@ public function create_media_entry( $request ) { ); } + /** + * Fires before reading this attachment's JS-shaped data, so + * integrations that centralize media on another site can switch + * context first — runs after create_virtual_attachment()'s own wrap + * has already restored. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $attachment_js_data = wp_prepare_attachment_for_js( $attach_id ); + do_action( 'rtgodam_after_attachment_lookup' ); + return new \WP_REST_Response( array( 'success' => true, - 'attachment' => wp_prepare_attachment_for_js( $attach_id ), + 'attachment' => $attachment_js_data, 'message' => __( 'Attachment ready', 'godam' ), ), 200 @@ -2056,6 +2238,35 @@ public function create_media_entry( $request ) { * @return int|\WP_Error Attachment ID, or WP_Error on failure. */ public function create_virtual_attachment( $data, $opts = array() ) { + /** + * Fires before resolving/creating this virtual attachment, so + * integrations that centralize media on another site can switch + * context first — the dedupe lookups and the eventual + * wp_insert_attachment() call all need to run against that site. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + return $this->create_virtual_attachment_after_lookup( $data, $opts ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } + } + + /** + * Resolve or create the virtual attachment and populate its metadata. + * + * Split out of create_virtual_attachment() so a wp-dam-style site-switch + * bracket can wrap this entire body. + * + * @since 2.2.0 + * + * @param array $data GoDAM media data. + * @param array $opts Options (e.g. 'is_demo'). + * @return int|\WP_Error Attachment ID, or WP_Error on insert failure. + */ + private function create_virtual_attachment_after_lookup( $data, $opts = array() ) { $is_demo = ! empty( $opts['is_demo'] ); // Sanitize the GoDAM ID. @@ -2063,14 +2274,14 @@ public function create_virtual_attachment( $data, $opts = array() ) { // If godam_id is numeric and already an attachment, reuse it. if ( is_numeric( $godam_id ) ) { - $attachment_post = get_post( $godam_id ); + $attachment_post = get_post( $godam_id ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. if ( $attachment_post && 'attachment' === $attachment_post->post_type ) { return (int) $godam_id; } } // Reuse an existing entry for this GoDAM id instead of duplicating. - $existing = new \WP_Query( + $existing = new \WP_Query( // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. array( 'post_type' => 'attachment', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Required for finding attachment by transcoding job ID. @@ -2100,13 +2311,13 @@ public function create_virtual_attachment( $data, $opts = array() ) { // demo marker is set first so the virtual-media registrar can skip demos. $pre_setter = function ( $new_id ) use ( $godam_id, $is_demo ) { if ( $is_demo ) { - update_post_meta( $new_id, 'rtgodam_is_demo_attachment', 1 ); + update_post_meta( $new_id, 'rtgodam_is_demo_attachment', 1 ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): $pre_setter closure — covered transitively, since it's registered on 'add_attachment' immediately before (and removed immediately after) the wp_insert_attachment() call a few lines above, which fires that hook synchronously on the same call stack. } - update_post_meta( $new_id, '_godam_original_id', $godam_id ); + update_post_meta( $new_id, '_godam_original_id', $godam_id ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): $pre_setter closure — covered transitively, since it's registered on 'add_attachment' immediately before (and removed immediately after) the wp_insert_attachment() call a few lines above, which fires that hook synchronously on the same call stack. }; add_action( 'add_attachment', $pre_setter, 1, 1 ); - $attach_id = wp_insert_attachment( $attachment, $data['title'] ); + $attach_id = wp_insert_attachment( $attachment, $data['title'] ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. remove_action( 'add_attachment', $pre_setter, 1 ); @@ -2116,14 +2327,14 @@ public function create_virtual_attachment( $data, $opts = array() ) { // Ensure markers are persisted (idempotent with the pre-setter). if ( $is_demo ) { - update_post_meta( $attach_id, 'rtgodam_is_demo_attachment', 1 ); + update_post_meta( $attach_id, 'rtgodam_is_demo_attachment', 1 ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. } - update_post_meta( $attach_id, '_godam_original_id', $godam_id ); - update_post_meta( $attach_id, '_owner_email', sanitize_email( $data['owner'] ?? '' ) ); - update_post_meta( $attach_id, 'rtgodam_transcoded_url', esc_url_raw( $data['mpd_url'] ?? '' ) ); - update_post_meta( $attach_id, 'rtgodam_transcoding_status', 'transcoded' ); - update_post_meta( $attach_id, 'rtgodam_transcoding_job_id', $godam_id ); - update_post_meta( $attach_id, '_wp_attached_file', sanitize_text_field( $data['filename'] ?? '' ) ); // Virtual media path. + update_post_meta( $attach_id, '_godam_original_id', $godam_id ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. + update_post_meta( $attach_id, '_owner_email', sanitize_email( $data['owner'] ?? '' ) ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. + update_post_meta( $attach_id, 'rtgodam_transcoded_url', esc_url_raw( $data['mpd_url'] ?? '' ) ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. + update_post_meta( $attach_id, 'rtgodam_transcoding_status', 'transcoded' ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. + update_post_meta( $attach_id, 'rtgodam_transcoding_job_id', $godam_id ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. + update_post_meta( $attach_id, '_wp_attached_file', sanitize_text_field( $data['filename'] ?? '' ) ); // Virtual media path. // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. $video_duration_in_seconds = 0; $video_duration_formatted = ''; @@ -2135,7 +2346,7 @@ public function create_virtual_attachment( $data, $opts = array() ) { $type = $data['type'] ?? ''; if ( 'video' === $type ) { - update_post_meta( $attach_id, 'rtgodam_hls_transcoded_url', esc_url_raw( $data['hls_url'] ?? '' ) ); + update_post_meta( $attach_id, 'rtgodam_hls_transcoded_url', esc_url_raw( $data['hls_url'] ?? '' ) ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. $wp_attachment_metadata = array( 'filesize' => isset( $data['filesizeInBytes'] ) ? (int) $data['filesizeInBytes'] : 0, @@ -2151,17 +2362,17 @@ public function create_virtual_attachment( $data, $opts = array() ) { } if ( ! empty( $video_duration_in_seconds ) ) { - update_post_meta( $attach_id, '_video_duration', $video_duration_in_seconds ); + update_post_meta( $attach_id, '_video_duration', $video_duration_in_seconds ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. $wp_attachment_metadata['length'] = $video_duration_in_seconds; $wp_attachment_metadata['length_formatted'] = $video_duration_formatted; } // Set Video thumbnail from icon URL if provided. if ( ! empty( $data['icon'] ) ) { - update_post_meta( $attach_id, 'rtgodam_media_video_thumbnail', esc_url_raw( $data['icon'] ) ); + update_post_meta( $attach_id, 'rtgodam_media_video_thumbnail', esc_url_raw( $data['icon'] ) ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. } - update_post_meta( $attach_id, '_wp_attachment_metadata', $wp_attachment_metadata ); + update_post_meta( $attach_id, '_wp_attachment_metadata', $wp_attachment_metadata ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. } elseif ( 'image' === $type ) { // Initialize metadata with basic info. $wp_attachment_metadata = array( @@ -2177,7 +2388,7 @@ public function create_virtual_attachment( $data, $opts = array() ) { $wp_attachment_metadata['height'] = $image_height; } - update_post_meta( $attach_id, '_wp_attachment_metadata', $wp_attachment_metadata ); + update_post_meta( $attach_id, '_wp_attachment_metadata', $wp_attachment_metadata ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. // Request image subsizes from GoDAM Central. $this->request_image_subsizes_from_godam( $godam_id, $attach_id ); @@ -2187,13 +2398,13 @@ public function create_virtual_attachment( $data, $opts = array() ) { 'mime_type' => $data['mime'], ); - update_post_meta( $attach_id, '_wp_attachment_metadata', $wp_attachment_metadata ); + update_post_meta( $attach_id, '_wp_attachment_metadata', $wp_attachment_metadata ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. // Persist the audio thumbnail from GoDAM Central (falls back to the // icon URL) so the block can surface it. Mirrors the video/PDF paths. $audio_thumbnail = ! empty( $data['thumbnail_url'] ) ? $data['thumbnail_url'] : ( $data['icon'] ?? '' ); if ( ! empty( $audio_thumbnail ) ) { - update_post_meta( $attach_id, 'rtgodam_media_audio_thumbnail', esc_url_raw( $audio_thumbnail ) ); + update_post_meta( $attach_id, 'rtgodam_media_audio_thumbnail', esc_url_raw( $audio_thumbnail ) ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. } } elseif ( 'pdf' === $type || 'document' === $type ) { // 'pdf' is a file Central stored as-is; 'document' is one it rendered to a preview @@ -2202,11 +2413,11 @@ public function create_virtual_attachment( $data, $opts = array() ) { 'filesize' => isset( $data['filesizeInBytes'] ) ? (int) $data['filesizeInBytes'] : 0, ); - update_post_meta( $attach_id, '_wp_attachment_metadata', $wp_attachment_metadata ); + update_post_meta( $attach_id, '_wp_attachment_metadata', $wp_attachment_metadata ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. // Set PDF thumbnail from icon URL if provided. if ( ! empty( $data['icon'] ) ) { - update_post_meta( $attach_id, 'rtgodam_media_pdf_thumbnail', esc_url_raw( $data['icon'] ) ); + update_post_meta( $attach_id, 'rtgodam_media_pdf_thumbnail', esc_url_raw( $data['icon'] ) ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. } /* @@ -2223,7 +2434,7 @@ public function create_virtual_attachment( $data, $opts = array() ) { : ( 'pdf' === $type ? ( $data['mpd_url'] ?? '' ) : '' ); if ( ! empty( $preview_pdf_url ) ) { - update_post_meta( $attach_id, 'rtgodam_preview_pdf_url', esc_url_raw( $preview_pdf_url ) ); + update_post_meta( $attach_id, 'rtgodam_preview_pdf_url', esc_url_raw( $preview_pdf_url ) ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. } } @@ -2245,11 +2456,11 @@ public function create_virtual_attachment( $data, $opts = array() ) { } if ( ! empty( $sanitized_chapters ) ) { - $rtgodam_meta = get_post_meta( $attach_id, 'rtgodam_meta', true ); + $rtgodam_meta = get_post_meta( $attach_id, 'rtgodam_meta', true ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. $rtgodam_meta = is_array( $rtgodam_meta ) ? $rtgodam_meta : array(); $rtgodam_meta['chapters'] = $sanitized_chapters; - update_post_meta( $attach_id, 'rtgodam_meta', $rtgodam_meta ); + update_post_meta( $attach_id, 'rtgodam_meta', $rtgodam_meta ); // godam-coverage-ignore -- create_virtual_attachment_after_lookup(): covered transitively — caller (create_virtual_attachment) wraps the entire call in try/finally. } } @@ -2275,6 +2486,17 @@ public function get_attachment_by_id( $request ) { // Sanitize the GoDAM media ID from the request. $godam_id = sanitize_text_field( $request['id'] ); + /** + * Fires before resolving/reading attachment data for a GoDAM-original-ID + * lookup, so integrations that centralize media on another site can + * switch context first. This covers both the WP_Query match on + * '_godam_original_id' and the internal core media request that follows, + * since both resolve the same attachment. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + // Try to find an attachment that matches the GoDAM original ID. $query = new \WP_Query( array( @@ -2301,6 +2523,8 @@ public function get_attachment_by_id( $request ) { // Execute the request and capture the response. $response = rest_do_request( $internal_request ); + do_action( 'rtgodam_after_attachment_lookup' ); + // Return the full media object (or WP_Error if not found). return $response; } @@ -2359,7 +2583,17 @@ public function get_count_by_category( $request ) { } } + /** + * Fires before counting attachments in this media folder, so + * integrations that centralize media on another site can switch + * context first. The WP_Query below counts attachment posts + * (post_type 'attachment') tagged with this media-folder term. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $query = new \WP_Query( $args ); + do_action( 'rtgodam_after_attachment_lookup' ); return rest_ensure_response( array( diff --git a/inc/classes/rest-api/class-meta-rest-fields.php b/inc/classes/rest-api/class-meta-rest-fields.php index e56724237d..3a73fcf484 100644 --- a/inc/classes/rest-api/class-meta-rest-fields.php +++ b/inc/classes/rest-api/class-meta-rest-fields.php @@ -37,10 +37,28 @@ public function add_meta_rest_fields() { 'rtgodam_meta', array( 'get_callback' => function ( $post ) { - return get_post_meta( $post['id'], 'rtgodam_meta', true ); + /** + * Fires before reading/mutating this attachment's meta, + * so integrations that centralize media on another site + * can switch context first. These get/update callbacks + * fire whenever WP core's own REST machinery serves or + * updates this attachment field — including from routes + * other than /wp/v2/media (e.g. `_embed` on another + * route) — self-wrapped so it's correct regardless of + * which route triggered it. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $value = get_post_meta( $post['id'], 'rtgodam_meta', true ); + do_action( 'rtgodam_after_attachment_lookup' ); + return $value; }, 'update_callback' => function ( $value, $post ) { - return update_post_meta( $post->ID, 'rtgodam_meta', $value ); + do_action( 'rtgodam_before_attachment_lookup' ); + $result = update_post_meta( $post->ID, 'rtgodam_meta', $value ); + do_action( 'rtgodam_after_attachment_lookup' ); + return $result; }, ) ); @@ -50,10 +68,16 @@ public function add_meta_rest_fields() { 'rtgodam_analytics', array( 'get_callback' => function ( $post ) { - return get_post_meta( $post['id'], 'rtgodam_analytics', true ); + do_action( 'rtgodam_before_attachment_lookup' ); + $value = get_post_meta( $post['id'], 'rtgodam_analytics', true ); + do_action( 'rtgodam_after_attachment_lookup' ); + return $value; }, 'update_callback' => function ( $value, $post ) { - return update_post_meta( $post->ID, 'rtgodam_analytics', $value ); + do_action( 'rtgodam_before_attachment_lookup' ); + $result = update_post_meta( $post->ID, 'rtgodam_analytics', $value ); + do_action( 'rtgodam_after_attachment_lookup' ); + return $result; }, ) ); @@ -173,7 +197,10 @@ public function add_meta_rest_fields() { return current_user_can( 'edit_posts' ); }, 'get_callback' => function ( $post ) { - return rtgodam_get_hls_transcoded_url_from_attachment( $post->ID ); + do_action( 'rtgodam_before_attachment_lookup' ); + $value = rtgodam_get_hls_transcoded_url_from_attachment( $post->ID ); + do_action( 'rtgodam_after_attachment_lookup' ); + return $value; }, ) ); diff --git a/inc/classes/rest-api/class-transcoding.php b/inc/classes/rest-api/class-transcoding.php index 355f78df58..43fdfb64f5 100644 --- a/inc/classes/rest-api/class-transcoding.php +++ b/inc/classes/rest-api/class-transcoding.php @@ -224,9 +224,24 @@ public function update_transcoding_status( \WP_REST_Request $request ) { $error_msg = $request->get_param( 'error_msg' ); $error_code = $request->get_param( 'error_code' ); + /** + * Fires before resolving/mutating attachment data for this + * transcoding status update, so integrations that centralize media + * on another site can switch context first. The job-ID lookup + * itself needs this too — it's a direct $wpdb->postmeta query, just + * as site-scoped as get_post_meta(). wp_send_json_error()/ + * wp_send_json_success() below both terminate via wp_die(), which + * bypasses try/finally, so the after() call is placed explicitly + * right before each one instead of relying on one. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $attachment_id = $this->get_post_id_by_meta_key_and_value( 'rtgodam_transcoding_job_id', $job_id ); if ( ! $attachment_id ) { + do_action( 'rtgodam_after_attachment_lookup' ); wp_send_json_error( array( 'message' => __( 'Attachment not found.', 'godam' ), @@ -245,6 +260,7 @@ public function update_transcoding_status( \WP_REST_Request $request ) { update_post_meta( $attachment_id, 'rtgodam_transcoding_status', $status ); update_post_meta( $attachment_id, 'rtgodam_transcoding_progress', $progress ); + do_action( 'rtgodam_after_attachment_lookup' ); wp_send_json_success( array( 'message' => __( 'Transcoding status updated successfully.', 'godam' ), @@ -281,83 +297,98 @@ public function get_transcoding_status( \WP_REST_Request $request ) { * @return string */ private function get_status_object_from_attachment( int $attachment_id ) { - // Check if video has a transcoding job ID. - $job_id = sanitize_text_field( get_post_meta( $attachment_id, 'rtgodam_transcoding_job_id', true ) ); + /** + * Fires before reading/writing this attachment's transcoding-status + * metadata (job ID, status, error code/message, progress, thumbnail + * ID, and the thumbnail-retry counter), so integrations that + * centralize media on another site can switch context first. Wrapped + * in try/finally because this method returns early from several + * branches below. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + // Check if video has a transcoding job ID. + $job_id = sanitize_text_field( get_post_meta( $attachment_id, 'rtgodam_transcoding_job_id', true ) ); - // Get and sanitize the transcoding status. - $status = sanitize_text_field( get_post_meta( $attachment_id, 'rtgodam_transcoding_status', true ) ); + // Get and sanitize the transcoding status. + $status = sanitize_text_field( get_post_meta( $attachment_id, 'rtgodam_transcoding_status', true ) ); - // Handle failure even if job id is missing. - if ( ! empty( $status ) && 'failed' === strtolower( $status ) ) { - $error_code = sanitize_text_field( get_post_meta( $attachment_id, 'rtgodam_transcoding_error_code', true ) ); - $error_msg = sanitize_textarea_field( get_post_meta( $attachment_id, 'rtgodam_transcoding_error_msg', true ) ); + // Handle failure even if job id is missing. + if ( ! empty( $status ) && 'failed' === strtolower( $status ) ) { + $error_code = sanitize_text_field( get_post_meta( $attachment_id, 'rtgodam_transcoding_error_code', true ) ); + $error_msg = sanitize_textarea_field( get_post_meta( $attachment_id, 'rtgodam_transcoding_error_msg', true ) ); - return array( - 'status' => 'failed', - 'progress' => 0, - 'error_code' => $error_code, - 'error_msg' => $error_msg, - ); - } + return array( + 'status' => 'failed', + 'progress' => 0, + 'error_code' => $error_code, + 'error_msg' => $error_msg, + ); + } - if ( empty( $job_id ) ) { - return array( - 'status' => 'not_transcoding', - 'message' => __( 'Media has not been transcoded.', 'godam' ), - ); - } + if ( empty( $job_id ) ) { + return array( + 'status' => 'not_transcoding', + 'message' => __( 'Media has not been transcoded.', 'godam' ), + ); + } - if ( empty( $status ) ) { - return array( - 'status' => 'not_started', - 'message' => __( 'Transcoding has not started.', 'godam' ), - ); - } + if ( empty( $status ) ) { + return array( + 'status' => 'not_started', + 'message' => __( 'Transcoding has not started.', 'godam' ), + ); + } - // Get and sanitize transcoding progress. - $progress = intval( get_post_meta( $attachment_id, 'rtgodam_transcoding_progress', true ) ); + // Get and sanitize transcoding progress. + $progress = intval( get_post_meta( $attachment_id, 'rtgodam_transcoding_progress', true ) ); - // Define status messages. - $status_messages = array( - 'Queued' => __( 'Media is queued for transcoding.', 'godam' ), - 'Downloading' => __( 'Media is downloading for transcoding.', 'godam' ), - 'Downloaded' => __( 'Media is downloaded for transcoding.', 'godam' ), - 'Transcoding' => __( 'Media is transcoding.', 'godam' ), - 'Transcoded' => __( 'Media is transcoded.', 'godam' ), - ); + // Define status messages. + $status_messages = array( + 'Queued' => __( 'Media is queued for transcoding.', 'godam' ), + 'Downloading' => __( 'Media is downloading for transcoding.', 'godam' ), + 'Downloaded' => __( 'Media is downloaded for transcoding.', 'godam' ), + 'Transcoding' => __( 'Media is transcoding.', 'godam' ), + 'Transcoded' => __( 'Media is transcoded.', 'godam' ), + ); - // Set default message for unknown status. - $message = isset( $status_messages[ $status ] ) ? $status_messages[ $status ] : __( 'Unknown transcoding status.', 'godam' ); + // Set default message for unknown status. + $message = isset( $status_messages[ $status ] ) ? $status_messages[ $status ] : __( 'Unknown transcoding status.', 'godam' ); - // Check if media has thumbnail generated after transcoding. - $thumbnail_id = get_post_meta( $attachment_id, 'rtgodam_media_video_thumbnail', true ); + // Check if media has thumbnail generated after transcoding. + $thumbnail_id = get_post_meta( $attachment_id, 'rtgodam_media_video_thumbnail', true ); - // Handle retry logic for missing thumbnails when transcoding is complete. - if ( 'transcoded' === strtolower( $status ) && empty( $thumbnail_id ) ) { - $retry_count = intval( get_post_meta( $attachment_id, 'rtgodam_thumbnail_retry_count', true ) ); - $max_retries = 3; + // Handle retry logic for missing thumbnails when transcoding is complete. + if ( 'transcoded' === strtolower( $status ) && empty( $thumbnail_id ) ) { + $retry_count = intval( get_post_meta( $attachment_id, 'rtgodam_thumbnail_retry_count', true ) ); + $max_retries = 3; - if ( $retry_count < $max_retries ) { - // Increment retry count. - update_post_meta( $attachment_id, 'rtgodam_thumbnail_retry_count', $retry_count + 1 ); + if ( $retry_count < $max_retries ) { + // Increment retry count. + update_post_meta( $attachment_id, 'rtgodam_thumbnail_retry_count', $retry_count + 1 ); - // Return transcoding status with 95% progress to indicate waiting for thumbnail. - return array( - 'status' => 'transcoding', - 'progress' => 95, - 'message' => __( 'Transcoding complete, generating thumbnail...', 'godam' ), - 'thumbnail' => '', - ); + // Return transcoding status with 95% progress to indicate waiting for thumbnail. + return array( + 'status' => 'transcoding', + 'progress' => 95, + 'message' => __( 'Transcoding complete, generating thumbnail...', 'godam' ), + 'thumbnail' => '', + ); + } + // If max retries reached, continue with normal flow (return transcoded status without thumbnail). } - // If max retries reached, continue with normal flow (return transcoded status without thumbnail). - } - return array( - 'status' => strtolower( $status ), - 'progress' => $progress, - 'message' => $message, - 'thumbnail' => ! empty( $thumbnail_id ) ? $thumbnail_id : '', - ); + return array( + 'status' => strtolower( $status ), + 'progress' => $progress, + 'message' => $message, + 'thumbnail' => ! empty( $thumbnail_id ) ? $thumbnail_id : '', + ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } } /** @@ -377,7 +408,7 @@ private function get_post_id_by_meta_key_and_value( $key, $value ) { $meta = wp_cache_get( $cache_key, 'godam' ); if ( empty( $meta ) ) { - $meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s", $key, $value ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery + $meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s", $key, $value ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, godam-coverage-ignore -- get_post_id_by_meta_key_and_value(): covered transitively — sole caller (update_transcoding_status) already wraps this call in its own before/after pair. wp_cache_set( $cache_key, $meta, 'godam', 3600 ); } @@ -511,6 +542,15 @@ public function get_media_require_retranscoding( $request ) { $paged = 1; $per_page = 200; + /** + * Fires before querying attachment posts to find media still + * requiring transcoding, so integrations that centralize media + * on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + do { $args = array( 'post_type' => 'attachment', @@ -542,6 +582,15 @@ public function get_media_require_retranscoding( $request ) { break; } } while ( true ); + + /** + * Fires after the attachment query above, so integrations can + * restore the site context switched in + * `rtgodam_before_attachment_lookup`. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_after_attachment_lookup' ); } return new \WP_REST_Response( @@ -576,6 +625,15 @@ private function get_document_attachments( array $mime_types ) { $paged = 1; $per_page = 200; + /** + * Fires before querying attachment posts to find convertible + * documents, so integrations that centralize media on another + * site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + do { $query = new \WP_Query( array( @@ -616,6 +674,15 @@ private function get_document_attachments( array $mime_types ) { ++$paged; } while ( true ); + /** + * Fires after the attachment query above, so integrations can + * restore the site context switched in + * `rtgodam_before_attachment_lookup`. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_after_attachment_lookup' ); + return array( 'eligible' => $eligible, 'untranscoded' => $untranscoded, @@ -642,6 +709,13 @@ public function check_transcoded_status( $request ) { $transcode_count = 0; $retranscode_count = 0; + /** + * Fires before this per-ID attachment meta loop, so integrations + * that centralize media on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); foreach ( $attachment_ids as $attachment_id ) { $transcoded_url = get_post_meta( $attachment_id, 'rtgodam_transcoded_url', true ); // If transcoded, it should have URL. @@ -651,6 +725,7 @@ public function check_transcoded_status( $request ) { ++$transcode_count; } } + do_action( 'rtgodam_after_attachment_lookup' ); return new \WP_REST_Response( array( @@ -683,6 +758,38 @@ public function retranscode_media( \WP_REST_Request $request ) { ); } + /** + * Fires before resolving/mutating this attachment's transcoding + * state, so integrations that centralize media on another site can + * switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + return $this->retranscode_media_centralized( $request, $attachment_id ); + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } + } + + /** + * Does the actual work of retranscode_media(), always running with the + * centralized media site active — see the before/after pair in the + * caller. + * + * Split out (rather than duplicating after_attachment_lookup before each + * of this method's ~7 early returns) so a try/finally in the thin public + * wrapper can't leak a switched site context even if a future edit adds + * more early returns to this body. + * + * @since 2.2.0 + * + * @param \WP_REST_Request $request REST request object. + * @param int $attachment_id Attachment ID. + * @return \WP_REST_Response + */ + private function retranscode_media_centralized( \WP_REST_Request $request, $attachment_id ) { $title = get_the_title( $attachment_id ); // Check if local development environment. diff --git a/inc/classes/rest-api/class-transcription.php b/inc/classes/rest-api/class-transcription.php index 9d2b888619..8092108c7c 100644 --- a/inc/classes/rest-api/class-transcription.php +++ b/inc/classes/rest-api/class-transcription.php @@ -121,7 +121,19 @@ public function edit_permission( \WP_REST_Request $request ) { if ( empty( $attachment_id ) ) { return current_user_can( 'upload_files' ); } - return current_user_can( 'edit_post', $attachment_id ); + + /** + * Fires before this attachment-specific capability check, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $can_edit = current_user_can( 'edit_post', $attachment_id ); + do_action( 'rtgodam_after_attachment_lookup' ); + + return $can_edit; } /** @@ -133,6 +145,15 @@ public function edit_permission( \WP_REST_Request $request ) { public function get_transcription( \WP_REST_Request $request ) { $attachment_id = absint( $request->get_param( 'attachment_id' ) ); + /** + * Fires before reading this attachment's transcript meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + // Locally-stored transcript takes precedence. $path = get_post_meta( $attachment_id, 'rtgodam_transcript_path', true ); @@ -145,6 +166,8 @@ public function get_transcription( \WP_REST_Request $request ) { $status = $path ? 'Transcribed' : (string) get_post_meta( $attachment_id, self::STATUS_META, true ); + do_action( 'rtgodam_after_attachment_lookup' ); + return rest_ensure_response( $this->shape( $path, $status ) ); } @@ -158,10 +181,21 @@ public function get_transcription( \WP_REST_Request $request ) { public function generate_transcription( \WP_REST_Request $request ) { $attachment_id = absint( $request->get_param( 'attachment_id' ) ); + /** + * Fires before reading this attachment's job-ID meta, so integrations + * that centralize media on another site can switch context first. + * Closed immediately after (not held open across the SaaS HTTP call + * below) — see the second, separate pair around the meta writes + * further down. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $job_id = get_post_meta( $attachment_id, 'rtgodam_transcoding_job_id', true ); if ( empty( $job_id ) ) { $job_id = get_post_meta( $attachment_id, '_godam_original_id', true ); } + do_action( 'rtgodam_after_attachment_lookup' ); if ( empty( $job_id ) ) { return new \WP_Error( @@ -208,6 +242,15 @@ public function generate_transcription( \WP_REST_Request $request ) { $status = isset( $payload['status'] ) ? sanitize_text_field( $payload['status'] ) : ''; $current_status = isset( $payload['current_status'] ) ? sanitize_text_field( $payload['current_status'] ) : ''; + /** + * Fires before writing this attachment's transcript/status meta, so + * integrations that centralize media on another site can switch + * context first — a second, separate pair from the one above, so + * the switch isn't held open across the SaaS HTTP call in between. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); if ( ! empty( $path ) ) { // A (re)generated transcript supersedes any prior delete. delete_post_meta( $attachment_id, self::DELETED_META ); @@ -221,6 +264,7 @@ public function generate_transcription( \WP_REST_Request $request ) { $track = $current_status ? $current_status : $status; update_post_meta( $attachment_id, self::STATUS_META, $track ); } + do_action( 'rtgodam_after_attachment_lookup' ); return rest_ensure_response( array( @@ -253,10 +297,19 @@ public function upload_transcription( \WP_REST_Request $request ) { ); } + /** + * Fires before writing this attachment's transcript meta, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); // An uploaded transcript supersedes any prior delete. delete_post_meta( $attachment_id, self::DELETED_META ); update_post_meta( $attachment_id, 'rtgodam_transcript_path', $url ); update_post_meta( $attachment_id, self::STATUS_META, 'Transcribed' ); + do_action( 'rtgodam_after_attachment_lookup' ); return rest_ensure_response( $this->shape( $url, 'Transcribed' ) ); } @@ -270,10 +323,19 @@ public function upload_transcription( \WP_REST_Request $request ) { public function delete_transcription( \WP_REST_Request $request ) { $attachment_id = absint( $request->get_param( 'attachment_id' ) ); + /** + * Fires before deleting/writing this attachment's transcript meta, + * so integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); delete_post_meta( $attachment_id, 'rtgodam_transcript_path' ); delete_post_meta( $attachment_id, self::STATUS_META ); // Mark as deleted so GET won't auto-resurrect it from the SaaS. update_post_meta( $attachment_id, self::DELETED_META, '1' ); + do_action( 'rtgodam_after_attachment_lookup' ); return rest_ensure_response( $this->shape( '', '' ) ); } diff --git a/inc/classes/rest-api/class-video-editor.php b/inc/classes/rest-api/class-video-editor.php index 256d8c8f35..0948c9d9b9 100644 --- a/inc/classes/rest-api/class-video-editor.php +++ b/inc/classes/rest-api/class-video-editor.php @@ -175,6 +175,15 @@ public function get_videos( $request ) { $args['meta_query'] = $meta_query; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query } + /** + * Fires before the video-editor's attachment listing query, so + * integrations that centralize media on another site can switch + * context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $query = new WP_Query( $args ); $items = array(); @@ -193,17 +202,29 @@ public function get_videos( $request ) { $items = $this->prioritize_item( $items, $prioritize_id, $per_page ); } + $found_posts = (int) $query->found_posts; + $max_num_pages = (int) $query->max_num_pages; + + /** + * Fires after the video-editor's attachment listing query, so + * integrations can restore the site context switched in + * `rtgodam_before_attachment_lookup`. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_after_attachment_lookup' ); + $response = new WP_REST_Response( array( 'items' => $items, - 'total' => (int) $query->found_posts, - 'totalPages' => (int) $query->max_num_pages, + 'total' => $found_posts, + 'totalPages' => $max_num_pages, ), 200 ); - $response->header( 'X-WP-Total', (int) $query->found_posts ); - $response->header( 'X-WP-TotalPages', (int) $query->max_num_pages ); + $response->header( 'X-WP-Total', $found_posts ); + $response->header( 'X-WP-TotalPages', $max_num_pages ); return $response; } @@ -238,8 +259,8 @@ private function prioritize_item( $items, $prioritize_id, $per_page ) { // Enforce the same author scoping as the list query: users who can't // edit others' content may only surface their own uploads, otherwise // this becomes an IDOR that leaks other users' private video metadata. - $owned = $post && ( current_user_can( 'edit_others_posts' ) || get_current_user_id() === (int) $post->post_author || 1 === (int) get_post_meta( $post->ID, 'rtgodam_is_demo_attachment', true ) ); - if ( $owned && 'attachment' === $post->post_type && 0 === strpos( (string) get_post_mime_type( $post ), 'video/' ) ) { + $owned = $post && ( current_user_can( 'edit_others_posts' ) || get_current_user_id() === (int) $post->post_author || 1 === (int) get_post_meta( $post->ID, 'rtgodam_is_demo_attachment', true ) ); // godam-coverage-ignore -- prioritize_item(): covered transitively — sole caller (get_videos) wraps the entire call in its own before/after pair. + if ( $owned && 'attachment' === $post->post_type && 0 === strpos( (string) get_post_mime_type( $post ), 'video/' ) ) { // godam-coverage-ignore -- prioritize_item(): covered transitively — sole caller (get_videos) wraps the entire call in its own before/after pair. $pinned = $this->prepare_video_item( $post ); } } diff --git a/inc/classes/rest-api/class-video-migration.php b/inc/classes/rest-api/class-video-migration.php index ced9f27e56..872706333f 100644 --- a/inc/classes/rest-api/class-video-migration.php +++ b/inc/classes/rest-api/class-video-migration.php @@ -636,7 +636,7 @@ private function release_migration_lock( string $lock_key ) { * @return bool True if post content was changed, false otherwise. */ private function migrate_single_post_video_blocks( $post_id ) { - $post = get_post( $post_id ); + $post = get_post( $post_id ); // godam-coverage-ignore -- migrate_single_post_video_blocks(): $post_id is the HOST post being scanned for an embedded core/video block, not an attachment — the attachment ID parsed from the block is already wrapped in traverse_and_migrate_core_video_blocks_recursive(). if ( ! $post || ! has_blocks( $post->post_content ) ) { return false; @@ -649,7 +649,7 @@ private function migrate_single_post_video_blocks( $post_id ) { if ( $changed ) { $new_content = serialize_blocks( $blocks ); - wp_update_post( + wp_update_post( // godam-coverage-ignore -- migrate_single_post_video_blocks(): rewrites the HOST post's own post_content after migrating its embedded core/video block, not attachment data — see the get_post( $post_id ) call above. array( 'ID' => $post_id, 'post_content' => $new_content, @@ -677,6 +677,16 @@ private function traverse_and_migrate_core_video_blocks_recursive( array &$block if ( 'core/video' === $block_name ) { $attrs = $block['attrs'] ?? array(); $attachment_id = isset( $attrs['id'] ) ? (int) $attrs['id'] : 0; + + /** + * Fires before reading this attachment's URL/sources/SEO + * data, so integrations that centralize media on another + * site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + if ( $attachment_id ) { $attrs['src'] = wp_get_attachment_url( $attachment_id ); } @@ -686,6 +696,15 @@ private function traverse_and_migrate_core_video_blocks_recursive( array &$block // Build default SEO data so the migrated block has SEO populated. $seo_data = $this->build_default_seo_data( $attachment_id, $attrs, $sources ); + /** + * Fires after reading this attachment's data, so + * integrations can restore the site context switched in + * `rtgodam_before_attachment_lookup`. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_after_attachment_lookup' ); + // Transform to custom block with attributes. $block = array( 'blockName' => 'godam/video', @@ -724,7 +743,7 @@ private function traverse_and_migrate_core_video_blocks_recursive( array &$block */ private function migrate_single_post_vimeo_blocks( $post_id ) { - $post = get_post( $post_id ); + $post = get_post( $post_id ); // godam-coverage-ignore -- migrate_single_post_vimeo_blocks(): $post_id is the HOST post being scanned for an embedded Vimeo block, not an attachment — the attachment ID resolved from the embed is already wrapped in traverse_and_migrate_vimeo_blocks_recursive(). if ( ! $post || ! has_blocks( $post->post_content ) ) { return false; @@ -739,7 +758,7 @@ private function migrate_single_post_vimeo_blocks( $post_id ) { if ( $changed ) { $new_content = serialize_blocks( $blocks ); - wp_update_post( + wp_update_post( // godam-coverage-ignore -- migrate_single_post_vimeo_blocks(): rewrites the HOST post's own post_content after migrating its embedded Vimeo block, not attachment data — see the get_post( $post_id ) call above. array( 'ID' => $post_id, 'post_content' => $new_content, @@ -782,13 +801,43 @@ private function traverse_and_migrate_vimeo_blocks_recursive( array &$blocks, in $attachment_id = $this->create_attachment_from_vimeo_video( $vimeo_url ); if ( ! is_wp_error( $attachment_id ) ) { + /** + * Fires before reading the migrated attachment's + * URL/sources/SEO data, so integrations that + * centralize media on another site can switch + * context first — this runs after + * create_attachment_from_vimeo_video()'s own + * wrap has already restored. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $video_url = wp_get_attachment_url( $attachment_id ); + $sources = array(); + $seo_data = array(); + if ( ! empty( $video_url ) ) { $sources = $this->build_video_sources_array( $attachment_id ); // Build default SEO data so the migrated block has SEO populated. $seo_data = $this->build_default_seo_data( $attachment_id, $attrs, $sources ); + } + + /** + * Fires after reading the migrated attachment's + * data, so integrations can restore the site + * context switched in + * `rtgodam_before_attachment_lookup`. Fired + * unconditionally — unlike the block-building + * below, which only runs when $video_url + * resolved — so the switch is always restored + * regardless of that outcome. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_after_attachment_lookup' ); + if ( ! empty( $video_url ) ) { $block = array( 'blockName' => 'godam/video', 'attrs' => array( @@ -956,9 +1005,26 @@ private function build_default_seo_data( int $attachment_id, array $attrs = arra } } - $headline = $attachment instanceof \WP_Post ? get_the_title( $attachment_id ) : ''; + $headline = $attachment instanceof \WP_Post ? get_the_title( $attachment_id ) : ''; + + /** + * Fires before reading this attachment's excerpt/content for the + * SEO description fallback, so integrations that centralize media + * on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $desc_field = $attachment instanceof \WP_Post ? get_post_field( 'post_excerpt', $attachment_id ) : ''; $description = ! empty( $desc_field ) ? $desc_field : ( $attachment instanceof \WP_Post ? get_post_field( 'post_content', $attachment_id ) : '' ); + /** + * Fires after reading this attachment's data, so integrations can + * restore the site context switched in + * `rtgodam_before_attachment_lookup`. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_after_attachment_lookup' ); return array( 'contentUrl' => $content_url, @@ -1016,7 +1082,7 @@ private function update_video_metadata_from_vimeo_info( $attachment_id, $video_i 'post_title' => $video_info['title'] ?? $video_info['orignal_file_name'] ?? '', 'post_content' => $video_info['description'] ?? '', ); - wp_update_post( $attachment_data ); + wp_update_post( $attachment_data ); // godam-coverage-ignore -- update_video_metadata_from_vimeo_info(): covered transitively — both call sites run inside create_attachment_from_vimeo_video()'s own before/after try/finally pair, same as the $wpdb->update() call below. // Update attachment metadata with dimensions. $metadata = array( @@ -1079,7 +1145,7 @@ private function update_video_metadata_from_vimeo_info( $attachment_id, $video_i // Change the guid of the attachment to the transcoded file path. global $wpdb; //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching - $wpdb->update( + $wpdb->update( // godam-coverage-ignore -- update_video_metadata_from_vimeo_info(): covered transitively — both call sites run inside create_attachment_from_vimeo_video()'s own before/after try/finally pair. $wpdb->posts, array( 'guid' => ! empty( $video_info['transcoded_mp4_url'] ) ? $video_info['transcoded_mp4_url'] : $video_info['transcoded_file_path'], @@ -1171,41 +1237,54 @@ public function create_attachment_from_vimeo_video( $vimeo_url ) { // Check if job ID exists in the response and look for existing attachment. $job_id = $video_info['name'] ?? null; - if ( ! empty( $job_id ) ) { - // Check if attachment with this job ID already exists. - if ( class_exists( 'RTGODAM_Transcoder_Handler' ) ) { - $transcoder_handler = new \RTGODAM_Transcoder_Handler(); - if ( method_exists( $transcoder_handler, 'get_post_id_by_meta_key_and_value' ) ) { - $existing_attachment_id = $transcoder_handler->get_post_id_by_meta_key_and_value( 'rtgodam_transcoding_job_id', $job_id ); - - if ( $existing_attachment_id ) { - // Replace all video metadata for existing attachment when JOB ID is present. - $this->update_video_metadata_from_vimeo_info( $existing_attachment_id, $video_info, $job_id ); - return $existing_attachment_id; + /** + * Fires before the dedupe lookup and the eventual wp_insert_attachment() + * call, so integrations that centralize media on another site can + * switch context first — deliberately fired only after the SaaS + * HTTP call above returns, so the switch isn't held open across it. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + try { + if ( ! empty( $job_id ) ) { + // Check if attachment with this job ID already exists. + if ( class_exists( 'RTGODAM_Transcoder_Handler' ) ) { + $transcoder_handler = new \RTGODAM_Transcoder_Handler(); + if ( method_exists( $transcoder_handler, 'get_post_id_by_meta_key_and_value' ) ) { + $existing_attachment_id = $transcoder_handler->get_post_id_by_meta_key_and_value( 'rtgodam_transcoding_job_id', $job_id ); + + if ( $existing_attachment_id ) { + // Replace all video metadata for existing attachment when JOB ID is present. + $this->update_video_metadata_from_vimeo_info( $existing_attachment_id, $video_info, $job_id ); + return $existing_attachment_id; + } } } } - } - // Prepare attachment data for new attachment. - $attachment = array( - 'post_mime_type' => 'video/mp4', - 'post_title' => $video_info['title'] ?? $video_info['orignal_file_name'] ?? '', - 'post_content' => $video_info['description'] ?? '', - 'post_status' => 'inherit', - ); + // Prepare attachment data for new attachment. + $attachment = array( + 'post_mime_type' => 'video/mp4', + 'post_title' => $video_info['title'] ?? $video_info['orignal_file_name'] ?? '', + 'post_content' => $video_info['description'] ?? '', + 'post_status' => 'inherit', + ); - // Insert the attachment. - $attachment_id = wp_insert_attachment( $attachment ); + // Insert the attachment. + $attachment_id = wp_insert_attachment( $attachment ); - if ( is_wp_error( $attachment_id ) ) { - return $attachment_id; - } + if ( is_wp_error( $attachment_id ) ) { + return $attachment_id; + } - // Update video metadata using the new reusable function. - $this->update_video_metadata_from_vimeo_info( $attachment_id, $video_info, $job_id ); + // Update video metadata using the new reusable function. + $this->update_video_metadata_from_vimeo_info( $attachment_id, $video_info, $job_id ); - return $attachment_id; + return $attachment_id; + } finally { + do_action( 'rtgodam_after_attachment_lookup' ); + } } /** diff --git a/inc/classes/rest-api/class-video-sync.php b/inc/classes/rest-api/class-video-sync.php index b6197b78a3..a0acc29cd5 100644 --- a/inc/classes/rest-api/class-video-sync.php +++ b/inc/classes/rest-api/class-video-sync.php @@ -91,15 +91,25 @@ public function verify_permission( $request ) { public function check_videos( $request ) { // Get all videos with job_id. global $wpdb; + + /** + * Fires before this direct $wpdb->postmeta query — just as + * site-scoped as get_post_meta() — so integrations that centralize + * media on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $results = $wpdb->get_results( " - SELECT post_id, meta_value - FROM {$wpdb->postmeta} + SELECT post_id, meta_value + FROM {$wpdb->postmeta} WHERE meta_key = 'rtgodam_transcoding_job_id' AND meta_value != '' " ); + do_action( 'rtgodam_after_attachment_lookup' ); $tuples = array(); foreach ( $results as $row ) { diff --git a/inc/classes/rest-api/class-virtual-media-migration.php b/inc/classes/rest-api/class-virtual-media-migration.php index a4b46e5aa4..57ea5fc827 100644 --- a/inc/classes/rest-api/class-virtual-media-migration.php +++ b/inc/classes/rest-api/class-virtual-media-migration.php @@ -73,13 +73,8 @@ public function verify_permission( $request ) { * @return \WP_REST_Response */ public function migrate_virtual_media( $request ) { - // Ensure the transcoder callback URL is defined. - if ( defined( 'RTGODAM_TRANSCODER_CALLBACK_URL' ) && ! empty( RTGODAM_TRANSCODER_CALLBACK_URL ) ) { - $transcoder_callback_url = RTGODAM_TRANSCODER_CALLBACK_URL; - } else { - include_once RTGODAM_PATH . 'admin/class-rtgodam-transcoder-rest-routes.php'; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingCustomConstant - $transcoder_callback_url = \RTGODAM_Transcoder_Rest_Routes::get_callback_url(); - } + include_once RTGODAM_PATH . 'admin/class-rtgodam-transcoder-rest-routes.php'; + $transcoder_callback_url = \RTGODAM_Transcoder_Rest_Routes::get_callback_url(); return new \WP_REST_Response( array( @@ -103,6 +98,16 @@ private function get_job_ids_for_migration() { if ( false === $job_ids ) { global $wpdb; + + /** + * Fires before querying attachment posts for their virtual-media job + * IDs, so integrations that centralize media on another site can + * switch context first. Reads postmeta joined to the posts table, + * filtered to post_type 'attachment' — squarely attachment-scoped. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $job_ids = $wpdb->get_col( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->prepare( "SELECT DISTINCT meta_value FROM {$wpdb->postmeta} pm @@ -112,6 +117,8 @@ private function get_job_ids_for_migration() { Virtual_Media_Registrar::META_ORIGINAL_ID, ) ); + do_action( 'rtgodam_after_attachment_lookup' ); + set_transient( 'rtgodam_virtual_media_job_ids', $job_ids, HOUR_IN_SECONDS ); } diff --git a/inc/classes/shortcodes/class-godam-document.php b/inc/classes/shortcodes/class-godam-document.php index 910985aee0..56e82634d6 100644 --- a/inc/classes/shortcodes/class-godam-document.php +++ b/inc/classes/shortcodes/class-godam-document.php @@ -65,7 +65,18 @@ public function render( $atts ) { // editor that would leave a silently empty element, so show the author why. // Callers that own their own editor messaging (the Elementor widget) check // before reaching this point. - if ( ! godam_is_supported_document( $atts['id'], $atts['src'] ) ) { + /** + * Fires before checking whether this attachment is a supported + * document type, so integrations that centralize media on another + * site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); + $is_supported_document = godam_is_supported_document( $atts['id'], $atts['src'] ); + do_action( 'rtgodam_after_attachment_lookup' ); + + if ( ! $is_supported_document ) { if ( function_exists( 'vc_is_inline' ) && vc_is_inline() ) { // The notice is styled by the block's stylesheet, which is normally // enqueued further down, so enqueue it here too since we return early. diff --git a/inc/classes/shortcodes/class-godam-player.php b/inc/classes/shortcodes/class-godam-player.php index 0d6e9c9f29..f9e5701579 100644 --- a/inc/classes/shortcodes/class-godam-player.php +++ b/inc/classes/shortcodes/class-godam-player.php @@ -64,7 +64,7 @@ public function get_video_cache_index_key( $post_id ) { */ public function invalidate_video_cache_on_meta_change( $meta_id, $object_id, $meta_key ) { // Only invalidate for attachment posts (GoDAM videos are stored as attachments). - if ( 'attachment' !== get_post_type( $object_id ) ) { + if ( 'attachment' !== get_post_type( $object_id ) ) { // godam-coverage-ignore -- invalidate_video_cache_on_meta_change(): updated_post_meta/added_post_meta/deleted_post_meta fire for every post type; this is the type-routing check that filters down to attachments — the actual work (invalidate_video_cache_for_post()) only clears a private cache key, not attachment data. return; } @@ -97,7 +97,7 @@ public function invalidate_video_cache_on_meta_change( $meta_id, $object_id, $me * @param int $post_id Post ID. */ public function invalidate_video_cache_for_post( $post_id ) { - if ( 'attachment' !== get_post_type( $post_id ) ) { + if ( 'attachment' !== get_post_type( $post_id ) ) { // godam-coverage-ignore -- invalidate_video_cache_for_post(): type-routing check (also reachable directly via edit_attachment/delete_attachment, which only ever fire for attachments); rtgodam_work_cache_index_clear() below only clears a private cache key, not attachment data. return; } @@ -254,11 +254,11 @@ public function maybe_enqueue_lightbox_runtime() { $godam_needs_runtime = false; if ( is_singular() ) { - $godam_post = get_post(); + $godam_post = get_post(); // godam-coverage-ignore -- maybe_enqueue_lightbox_runtime(): bare get_post() resolves to the current singular post, not an attachment. if ( $godam_post instanceof \WP_Post ) { // Elementor keeps its layout in post meta rather than post_content. - $godam_haystack = $godam_post->post_content . (string) get_post_meta( $godam_post->ID, '_elementor_data', true ); + $godam_haystack = $godam_post->post_content . (string) get_post_meta( $godam_post->ID, '_elementor_data', true ); // godam-coverage-ignore -- maybe_enqueue_lightbox_runtime(): reads the current post's own '_elementor_data', not attachment data. $godam_needs_runtime = false !== strpos( $godam_haystack, 'data-godam-lightbox' ) || false !== strpos( $godam_haystack, '#godam-video-' ); diff --git a/inc/classes/sureforms/class-assets.php b/inc/classes/sureforms/class-assets.php index aad929bcec..b8ea528e39 100644 --- a/inc/classes/sureforms/class-assets.php +++ b/inc/classes/sureforms/class-assets.php @@ -50,7 +50,7 @@ public function register_scripts() { /** * Get current post to check. */ - $current_post = get_post(); + $current_post = get_post(); // godam-coverage-ignore -- register_scripts(): bare get_post() resolves to the current post being rendered, not an attachment. $preview_page = get_query_var( 'godam_page' ); if ( $current_post instanceof WP_Post ) { diff --git a/inc/classes/sureforms/class-form-submit.php b/inc/classes/sureforms/class-form-submit.php index a0f331ab40..96bb678062 100644 --- a/inc/classes/sureforms/class-form-submit.php +++ b/inc/classes/sureforms/class-form-submit.php @@ -347,7 +347,7 @@ public function render_custom_field_markup( $markup, $value ) { * Fetch the transcoding URL from meta. */ $transcoded_url_meta_key = 'rtgodam_transcoded_url_sureforms_' . $form_id . '_' . $entry_id; - $transcoded_url = get_post_meta( $form_id, $transcoded_url_meta_key, true ); + $transcoded_url = get_post_meta( $form_id, $transcoded_url_meta_key, true ); // godam-coverage-ignore -- render_custom_field_markup(): $form_id is a SureForms form ID used as a postmeta key, not an attachment ID. $transcoded_url_output = ''; if ( ! empty( $transcoded_url ) ) { diff --git a/inc/classes/wpbakery-elements/class-wpb-godam-params.php b/inc/classes/wpbakery-elements/class-wpb-godam-params.php index 67bbe641a3..765e4894be 100644 --- a/inc/classes/wpbakery-elements/class-wpb-godam-params.php +++ b/inc/classes/wpbakery-elements/class-wpb-godam-params.php @@ -105,7 +105,15 @@ public function video_selector_settings_field( $settings, $value ) { // If a video is selected, show preview and remove button. if ( ! empty( $value ) && is_numeric( $value ) ) { + /** + * Fires before resolving this attachment's URL, so integrations + * that centralize media on another site can switch context first. + * + * @since 2.2.0 + */ + do_action( 'rtgodam_before_attachment_lookup' ); $attachment = wp_get_attachment_url( $value ); + do_action( 'rtgodam_after_attachment_lookup' ); if ( $attachment ) { $preview_html = '