$upload_dir['basedir'] . $base_dir . $entity_id, 'baseurl' => $upload_dir['baseurl'] . $base_dir . $entity_id, ); } /** * Initialize the cache handler. */ public static function init() { // Only register local caching filter when caching is enabled. if ( self::is_enabled() ) { \add_filter( 'activitypub_remote_media_url', array( self::class, 'maybe_cache' ), 10, 4 ); // Clean up when post is deleted. \add_action( 'before_delete_post', array( self::class, 'maybe_cleanup' ) ); } } /** * Maybe cache a media URL. * * Hooked to the activitypub_remote_media_url filter. * Downloads and caches the file locally if not already cached. * * @param string $url The remote URL. * @param string $context The context ('avatar', 'media', 'emoji', etc.). * @param string|int $entity_id The entity identifier (post ID). * @param array $options Optional. Additional options. * * @return string The local URL if cached successfully, otherwise the original URL. */ public static function maybe_cache( $url, $context, $entity_id = null, $options = array() ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Required for filter signature. if ( self::CONTEXT !== $context || empty( $url ) || empty( $entity_id ) ) { return $url; } $cached_url = self::get_or_cache( $url, $entity_id ); return $cached_url ?: $url; } /** * Maybe clean up cached media when post is deleted. * * @param int $post_id The post ID being deleted. */ public static function maybe_cleanup( $post_id ) { if ( Remote_Posts::POST_TYPE !== \get_post_type( $post_id ) ) { return; } self::invalidate_entity( $post_id ); } /** * Invalidate cached media for a comment. * * @param int $comment_id The comment ID. * * @return bool True on success, false on failure. */ public static function invalidate_comment( $comment_id ) { $paths = self::get_storage_paths_for_context( $comment_id, self::CONTEXT_COMMENT ); return static::delete_directory( $paths['basedir'] ); } }