Refresh wp-asciiplayer with native block editor playback (#36)
Build and WordPress integration / PHP 7.4 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / PHP 8.3 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / WordPress 6.3 / PHP 7.4 (push) Canceled after 0s
Build and WordPress integration / WordPress latest / PHP 8.2 (push) Canceled after 0s

* Refresh player with native block editor preview and local assets

Preserve shortcode rendering, normalize options, bundle the player locally,
and add reproducible packaging and WordPress integration tests.

* Fix emitted frontend boot and verify bundled runtime initialization

* Record verified WordPress 7.1.3 compatibility

* Use WordPress readme major-version compatibility format

* Add responsive player layout, captions and native terminal sizing

* Keep editor caption geometry stable during block selection

* Respect WordPress editor gutters with border-box sizing

* Improve automatic previews and toolbar terminal sizing (1.2.1)

* Show native cast dimensions and add Media Library recordings (1.2.2)

* Fix Media Library test storage and scope sidebar selectors

* Document bounded temporary-upload stream exceptions

* Move block explanations into collapsed sidebar help (1.2.3)

* Add bundled English and Simplified Chinese UI translations (1.1.0-dev)

* Use native RichText labels and supported Chinese HTML language tags in locale tests
This commit is contained in:
2026-10-14 15:56:05 +08:00
committed by GitHub
parent 40e2bf0733
commit 85e5ffa0ec
109 changed files with 32680 additions and 2090 deletions
+150
View File
@@ -0,0 +1,150 @@
<?php
/**
* Minimal WordPress API doubles for focused, dependency-free plugin tests.
* These verify plugin contracts, not the implementation of WordPress sanitizers.
* Real WordPress/browser integration tests cover the latter separately.
*/
define( 'ABSPATH', __DIR__ . '/' );
define( 'PLUGIN_VERSION', 'some-other-plugin' );
$GLOBALS['ap_test'] = array();
function ap_record( $key, $value ) {
$GLOBALS['ap_test'][ $key ][] = $value;
}
function add_action( $hook, $callback, $priority = 10 ) {
ap_record( 'actions', array( $hook, $callback, $priority ) );
}
function add_filter( $hook, $callback, $priority = 10, $accepted_args = 1 ) {
ap_record( 'filters', array( $hook, $callback, $priority, $accepted_args ) );
}
function load_plugin_textdomain( $domain, $deprecated, $path ) {
ap_record( 'textdomains', array( $domain, $path ) );
}
function plugin_basename( $file ) {
return 'wp-asciiplayer/asciicast-player.php';
}
function __( $text, $domain = 'default' ) {
return $text;
}
function current_user_can( $capability ) {
return ! empty( $GLOBALS['ap_test']['capabilities'][ $capability ] );
}
function user_can( $user, $capability ) {
return ! empty( $GLOBALS['ap_test']['user_capabilities'][ $user ][ $capability ] );
}
function is_multisite() {
return ! empty( $GLOBALS['ap_test']['multisite'] );
}
function get_site_option( $key, $default = false ) {
return $GLOBALS['ap_test']['site_options'][ $key ] ?? $default;
}
function get_allowed_mime_types() {
return $GLOBALS['ap_test']['allowed_mimes'] ?? LamGC\Asciiplayer\allow_cast_upload_mime( array( 'txt' => 'text/plain', 'jpg' => 'image/jpeg' ) );
}
function wp_check_filetype( $filename, $mimes = null ) {
// Mirrors core's empty-map fallback to cover explicit MIME deny-lists.
if ( empty( $mimes ) ) {
$mimes = get_allowed_mime_types();
}
foreach ( $mimes as $extension => $mime ) {
if ( preg_match( '/\.(' . $extension . ')$/i', $filename, $matches ) ) {
return array( 'ext' => $matches[1], 'type' => $mime );
}
}
return array( 'ext' => false, 'type' => false );
}
function add_shortcode( $tag, $callback ) {
ap_record( 'shortcodes', array( $tag, $callback ) );
}
function add_option() {
throw new RuntimeException( 'Plugin must not write options on requests.' );
}
function update_option() {
throw new RuntimeException( 'Plugin must not write options on requests.' );
}
function plugin_dir_url( $file ) {
return 'https://wordpress.test/wp-content/plugins/wp-asciiplayer/';
}
function add_query_arg( $key, $value, $url ) {
return $url . ( false === strpos( $url, '?' ) ? '?' : '&' ) . rawurlencode( $key ) . '=' . rawurlencode( $value );
}
function wp_parse_url( $value ) {
return parse_url( $value );
}
function esc_url_raw( $value, $protocols = null ) {
return $value;
}
function esc_url( $value, $protocols = null ) {
return htmlspecialchars( $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' );
}
function esc_attr( $value ) {
return htmlspecialchars( $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' );
}
function get_block_wrapper_attributes( $attributes ) {
ap_record( 'block_wrappers', $attributes );
$output = array();
foreach ( $attributes as $key => $value ) {
if ( '' !== $value ) {
$output[] = $key . '="' . esc_attr( $value ) . '"';
}
}
return implode( ' ', $output );
}
function wp_kses( $value, $allowed ) {
// Contract-only double. Actual sanitizer coverage belongs to WP browser tests.
return strip_tags( $value, '<br>' );
}
function wp_json_encode( $value, $flags = 0 ) {
return json_encode( $value, $flags );
}
function safecss_filter_attr( $style ) {
ap_record( 'filtered_css', $style );
$safe = array();
foreach ( explode( ';', $style ) as $declaration ) {
if ( preg_match( '/^\s*(width|height|color)\s*:\s*([a-z0-9.%# -]+)\s*$/i', $declaration ) ) {
$safe[] = trim( $declaration );
}
}
return implode( ';', $safe );
}
function wp_register_script( $handle, $src, $deps, $version, $footer ) {
$GLOBALS['ap_test']['scripts'][ $handle ] = compact( 'src', 'deps', 'version', 'footer' );
}
function wp_register_style( $handle, $src, $deps, $version ) {
$GLOBALS['ap_test']['styles'][ $handle ] = compact( 'src', 'deps', 'version' );
}
function wp_add_inline_script( $handle, $source, $position ) {
ap_record( 'inline_scripts', compact( 'handle', 'source', 'position' ) );
}
function wp_set_script_translations( $handle, $domain, $path ) {
ap_record( 'translations', compact( 'handle', 'domain', 'path' ) );
}
function register_block_type( $path, $args ) {
ap_record( 'blocks', compact( 'path', 'args' ) );
}
function wp_enqueue_script( $handle ) {
$GLOBALS['ap_test']['enqueued_scripts'][ $handle ] = true;
}
function wp_enqueue_style( $handle ) {
$GLOBALS['ap_test']['enqueued_styles'][ $handle ] = true;
}
function wp_style_is( $handle, $status ) {
return ! empty( $GLOBALS['ap_test'][ 'done' === $status ? 'printed_styles' : 'enqueued_styles' ][ $handle ] );
}
function wp_print_styles( $handles ) {
foreach ( $handles as $handle ) {
$GLOBALS['ap_test']['printed_styles'][ $handle ] = true;
ap_record( 'style_print_calls', $handle );
}
}
function has_shortcode( $content, $tag ) {
return false !== strpos( $content, '[' . $tag );
}
function has_block( $name, $content ) {
return false !== strpos( $content, '<!-- wp:' . $name );
}
require dirname( __DIR__, 2 ) . '/asciicast-player.php';
+187
View File
@@ -0,0 +1,187 @@
<?php
/** Run with PHP 7.4+: php tests/php/run.php */
require __DIR__ . '/bootstrap.php';
use function LamGC\Asciiplayer\enqueue_content_assets;
use function LamGC\Asciiplayer\normalize_attributes;
use function LamGC\Asciiplayer\parse_boolean;
use function LamGC\Asciiplayer\parse_number;
use function LamGC\Asciiplayer\parse_time;
use function LamGC\Asciiplayer\player_options;
use function LamGC\Asciiplayer\player_style;
use function LamGC\Asciiplayer\print_late_styles;
use function LamGC\Asciiplayer\register_plugin;
use function LamGC\Asciiplayer\render_block;
use function LamGC\Asciiplayer\render_player;
use function LamGC\Asciiplayer\render_shortcode;
use function LamGC\Asciiplayer\sanitize_source;
$assertions = 0;
function same( $expected, $actual, $message ) {
global $assertions;
++$assertions;
if ( $expected !== $actual ) {
throw new RuntimeException( $message . '\nExpected: ' . var_export( $expected, true ) . '\nActual: ' . var_export( $actual, true ) );
}
}
function contains( $needle, $haystack, $message ) {
same( true, false !== strpos( $haystack, $needle ), $message );
}
function options_from( $html ) {
if ( ! preg_match( '/ data-ap-options="([^"]*)"/', $html, $matches ) ) {
throw new RuntimeException( 'Missing JSON data-ap-options.' );
}
return json_decode( html_entity_decode( $matches[1], ENT_QUOTES, 'UTF-8' ), true );
}
function reset_enqueues() {
$GLOBALS['ap_test']['enqueued_scripts'] = array();
$GLOBALS['ap_test']['enqueued_styles'] = array();
}
try {
// All registration happens in init, without global option writes/collisions.
same( 'some-other-plugin', PLUGIN_VERSION, 'No shared global version constant.' );
same( false, function_exists( 'is_assoc' ), 'No generic global helper functions.' );
same( 3, count( $GLOBALS['ap_test']['actions'] ), 'Register init, enqueue and late-style hooks.' );
foreach ( $GLOBALS['ap_test']['actions'] as $action ) {
same( true, is_callable( $action[1] ), 'Every registered callback is callable.' );
}
register_plugin();
same( array( 'wp-asciiplayer', 'wp-asciiplayer/languages' ), $GLOBALS['ap_test']['textdomains'][0], 'Bundled PHP catalogs register during init.' );
if ( file_exists( dirname( __DIR__, 2 ) . '/build/runtime.asset.php' ) ) {
$versions = require dirname( __DIR__, 2 ) . '/build/runtime.asset.php';
same( $versions['player.js'], $GLOBALS['ap_test']['scripts']['lamgc-asciiplayer-player']['version'], 'Player script uses its content hash.' );
foreach ( array( 'lamgc-asciiplayer-player-style' => 'player.css', 'lamgc-asciiplayer-style' => 'style-index.css', 'lamgc-asciiplayer-editor-style' => 'index.css' ) as $handle => $file ) {
same( $versions[ $file ], $GLOBALS['ap_test']['styles'][ $handle ]['version'], 'Each stylesheet uses its own content hash.' );
}
}
same( 'asciiplayer', $GLOBALS['ap_test']['shortcodes'][0][0], 'Legacy shortcode stays registered.' );
contains( '/build', $GLOBALS['ap_test']['blocks'][0]['path'], 'Block uses local metadata.' );
same( 'LamGC\\Asciiplayer\\render_block', $GLOBALS['ap_test']['blocks'][0]['args']['render_callback'], 'Block is server rendered.' );
foreach ( $GLOBALS['ap_test']['scripts'] as $script ) {
contains( 'https://wordpress.test/wp-content/plugins/wp-asciiplayer/build/', $script['src'], 'Runtime JavaScript is locally bundled.' );
same( true, $script['footer'], 'Scripts load in footer.' );
}
same( true, in_array( 'lamgc-asciiplayer-player', $GLOBALS['ap_test']['scripts']['lamgc-asciiplayer-view']['deps'], true ), 'Frontend adapter depends on local player.' );
same( true, in_array( 'wp-i18n', $GLOBALS['ap_test']['scripts']['lamgc-asciiplayer-view']['deps'], true ), 'Frontend translations dependency registered.' );
same( array( 'lamgc-asciiplayer-player-style' ), $GLOBALS['ap_test']['styles']['lamgc-asciiplayer-style']['deps'], 'Frontend style depends on player stylesheet.' );
contains( 'window.wpAsciiplayerSettings = ', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Editor iframe receives trusted runtime URLs.' );
same( 'before', $GLOBALS['ap_test']['inline_scripts'][0]['position'], 'Settings are available before editor boot.' );
contains( 'player.js?ver=' . $GLOBALS['ap_test']['scripts']['lamgc-asciiplayer-player']['version'], $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge JavaScript cache-buster matches registered asset version.' );
contains( 'player.css?ver=' . $GLOBALS['ap_test']['styles']['lamgc-asciiplayer-player-style']['version'], $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge CSS cache-buster matches registered asset version.' );
// Source validation covers script, HTML, credential and relative-URL attacks.
foreach ( array( '', 'javascript:alert(1)', 'data:text/html,test', 'file:///tmp/a.cast', '//evil.test/a.cast', '/\\evil.test/a.cast', "https://example.test/a\n.cast", 'https://x.test/" onmouseover="alert(1)', 'https://user:[email protected]/a.cast', 'https:///a.cast', 'a.cast', array( 'bad' ) ) as $source ) {
same( '', sanitize_source( $source ), 'Reject unsafe or unsupported source.' );
}
foreach ( array( 'https://example.test/a.cast', 'http://example.test:8080/a.cast?x=1&y=2', '/wp-content/uploads/demo.cast', '/cast/demo.cast?x=1&y=2' ) as $source ) {
same( $source, sanitize_source( $source ), 'Allow HTTP(S) or root-relative source.' );
}
same( 'https://example.test/a.cast?a=1&b=2', sanitize_source( ' https://example.test/a.cast?a=1&amp;b=2 ' ), 'Decode editor entities and trim outer whitespace.' );
foreach ( array( false, 'false', '0', 0, 'off', 'no' ) as $value ) {
same( false, parse_boolean( $value ), 'Explicit false remains false.' );
}
foreach ( array( true, 'true', '1', 1, 'on', 'yes' ) as $value ) {
same( true, parse_boolean( $value ), 'Recognized true values.' );
}
same( null, parse_boolean( 'garbage' ), 'Unrecognized bool is ignored.' );
same( null, parse_number( 'INF', 0, 100 ), 'Infinity is rejected.' );
same( null, parse_number( true, 0, 100 ), 'Boolean is not a numeric option.' );
same( null, parse_number( -1, 0, 100 ), 'Negative time is rejected.' );
same( 0.0, parse_time( '0' ), 'Zero start time is retained.' );
same( 123.0, parse_time( '2:03' ), 'Legacy mm:ss start time.' );
same( 3723.5, parse_time( '1:02:03.5' ), 'Legacy hh:mm:ss fractional time.' );
same( null, parse_time( '1:99' ), 'Invalid time components are rejected.' );
$attrs = normalize_attributes( array( 'autoplay' => 'false', 'startat' => '2:03', 'idle-time-limit' => '2', 'fontSize' => '15px', 'fontfamily' => "'Fira Code', monospace", 'lineheight' => 1.4, 'logger' => 'console', 'unknown' => 'bad', 0 => 'bare', 'rows' => array( 2 ) ) );
same( false, isset( $attrs['unknown'] ), 'Unknown attributes are discarded.' );
same( false, isset( $attrs['logger'] ), 'No executable logger objects.' );
same( false, isset( $attrs['rows'] ), 'Nested option values are discarded.' );
$options = player_options( $attrs );
same( false, $options['autoPlay'], 'Lowercase autoplay normalizes and respects false.' );
same( 123.0, $options['startAt'], 'Lowercase startAt normalizes.' );
same( 2.0, $options['idleTimeLimit'], 'Hyphenated idleTimeLimit normalizes.' );
same( '15px', $options['terminalFontSize'], 'Legacy font aliases map to current player options.' );
same( "'Fira Code', monospace", $options['terminalFontFamily'], 'Font lists survive safely.' );
same( 1.4, $options['terminalLineHeight'], 'Legacy lineHeight maps to current name.' );
$options = player_options( normalize_attributes( array( 'controls' => 'false', 'preload' => 'false', 'loop' => 'false', 'fit' => 'false' ) ) );
same( false, $options['controls'], 'controls=false is a boolean, never a truthy string.' );
same( false, $options['preload'], 'preload=false is retained.' );
same( false, $options['loop'], 'loop=false is retained.' );
same( 'none', $options['fit'], 'Legacy fit=false maps to none.' );
foreach ( array( 'always' => true, 'never' => false, 'auto' => 'auto' ) as $input => $expected ) {
same( $expected, player_options( array( 'controls' => $input ) )['controls'], 'Block control enum converts to player API.' );
}
same( 3, player_options( array( 'loop' => '3' ) )['loop'], 'Finite replay counts stay supported in shortcodes.' );
$options = player_options( array( 'speed' => -1, 'idleTimeLimit' => 0, 'cols' => 4.5, 'rows' => 1001, 'startAt' => -1, 'terminalFontSize' => '12px; color:red', 'terminalFontFamily' => 'url(https://bad.test)', 'theme' => 'x" onclick=bad', 'poster' => 'javascript:alert(1)' ) );
same( array( 'autoPlay' => false, 'preload' => true, 'fit' => 'width' ), $options, 'Invalid options omitted, safe defaults retained.' );
same( 'auto/dracula', player_options( array( 'theme' => 'auto/dracula' ) )['theme'], 'Player theme fallback syntax retained.' );
same( 'npt:1:23', player_options( array( 'poster' => 'npt:1:23' ) )['poster'], 'Safe NPT poster supported.' );
same( 'data:text/plain,<Hello>', player_options( array( 'poster' => 'data:text/plain,<Hello>' ) )['poster'], 'Plain terminal-text posters are supported.' );
reset_enqueues();
same( '', render_shortcode( array() ), 'Unclosed/empty shortcode returns no player.' );
same( '', render_player( array( 'source' => 'javascript:alert(1)' ) ), 'Invalid source emits no HTML.' );
same( array(), $GLOBALS['ap_test']['enqueued_scripts'], 'Invalid source does not enqueue assets.' );
$html = render_shortcode( array( 'controls' => 'false', 'autoPlay' => 'true', 'startAt' => '12', 'idleTimeLimit' => '2' ), 'https://example.test/demo.cast?a=1&b=2' );
contains( 'class="asciiplayer-container"', $html, 'Render adapter class.' );
contains( 'data-ap-src="https://example.test/demo.cast?a=1&amp;b=2"', $html, 'URL is escaped for an HTML attribute.' );
same( false, options_from( $html )['controls'], 'Markup has typed JSON false.' );
same( true, options_from( $html )['autoPlay'], 'CamelCase boolean handled.' );
same( 12, options_from( $html )['startAt'], 'JSON numeric startAt.' );
same( 2, options_from( $html )['idleTimeLimit'], 'JSON numeric idleTimeLimit.' );
same( true, isset( $GLOBALS['ap_test']['enqueued_scripts']['lamgc-asciiplayer-view'] ), 'Every valid render requests the frontend adapter.' );
same( true, isset( $GLOBALS['ap_test']['enqueued_styles']['lamgc-asciiplayer-style'] ), 'Every valid render requests CSS.' );
$html = render_block( array( 'source' => '/demo.cast', 'poster' => 'data:text/plain,"><script>alert(1)</script>', 'legacyStyle' => 'width:80%;color:red;background:url(javascript:alert(1))' ) );
same( false, false !== strpos( $html, '<script>' ), 'Poster cannot escape JSON/HTML attribute.' );
contains( 'style="color:red"', $html, 'Legacy player styles stay on the player mount point.' );
contains( 'style="width:80%;"', $html, 'Legacy width moves to the figure.' );
contains( 'background:url(javascript:alert(1))', end( $GLOBALS['ap_test']['filtered_css'] ), 'The original style is supplied to the WordPress sanitizer.' );
same( 'width:80%;height:200px;width:50%;', player_style( array( 'legacyStyle' => 'width:80%;height:200px', 'width' => '50%' ) ), 'Dedicated width control overrides legacy width.' );
same( '', player_style( array( 'width' => '100%;background:red' ) ), 'Width cannot inject extra declarations.' );
same( options_from( render_player( array( 'source' => '/demo.cast', 'speed' => 2 ) ) ), options_from( render_block( array( 'source' => '/demo.cast', 'speed' => 2 ) ) ), 'Block uses shared player options.' );
same( 'asciiplayer-block', end( $GLOBALS['ap_test']['block_wrappers'] )['class'], 'Block wrapper classes/layout pass through WordPress block supports.' );
$html = render_block( array( 'source' => '/demo.cast', 'width' => '480px', 'displayAlign' => 'right', 'caption' => 'Caption &amp; detail<br>second line' ) );
contains( '<figure ', $html, 'Block has semantic figure wrapper.' );
contains( 'asciiplayer-align-right', $html, 'Validated display alignment.' );
contains( 'width:480px;', $html, 'Display width belongs to figure.' );
contains( '<figcaption class="wp-element-caption">Caption &amp; detail<br>second line</figcaption>', $html, 'Caption is outside player mount point.' );
contains( '</div><figcaption', $html, 'Player cannot dispose caption.' );
$html = render_block( array( 'source' => '/demo.cast', 'displayAlign' => '\" onclick=alert(1)', 'caption' => '<img src=x onerror=alert(1)>Safe' ) );
contains( 'asciiplayer-align-center', $html, 'Invalid alignment falls back safely.' );
same( false, false !== strpos( $html, '<img' ), 'Caption does not allow image markup.' );
same( false, isset( player_options( array() )['cols'] ), 'Default columns come from recording.' );
same( false, isset( player_options( array() )['rows'] ), 'Default rows come from recording.' );
same( 120, player_options( array( 'cols' => 120 ) )['cols'], 'Explicit column override is retained.' );
same( false, isset( player_options( array( 'cols' => 120 ) )['rows'] ), 'One-axis override leaves other axis native.' );
$html = render_block( array( 'source' => '/demo.cast', 'legacyStyle' => 'height:200px;width:80%', 'caption' => 'Under player' ) );
contains( 'class="asciiplayer-container" style="height:200px"', $html, 'Legacy height remains on the player, so caption contributes to figure height.' );
// No is_single gate: query lookahead supports Pages and archive results.
reset_enqueues();
$GLOBALS['wp_query'] = (object) array( 'posts' => array( (object) array( 'post_content' => 'Ordinary content' ), (object) array( 'post_content' => '[asciiplayer]/demo.cast[/asciiplayer]' ) ) );
enqueue_content_assets();
same( true, isset( $GLOBALS['ap_test']['enqueued_scripts']['lamgc-asciiplayer-view'] ), 'Shortcode in any queried post receives assets.' );
reset_enqueues();
$GLOBALS['wp_query']->posts = array( (object) array( 'post_content' => '<!-- wp:lamgc/asciiplayer {"source":"/demo.cast"} /-->' ) );
enqueue_content_assets();
same( true, isset( $GLOBALS['ap_test']['enqueued_scripts']['lamgc-asciiplayer-view'] ), 'Block in query receives assets.' );
reset_enqueues();
$GLOBALS['wp_query']->posts = array( (object) array( 'post_content' => 'No players' ), 12 );
enqueue_content_assets();
same( array(), $GLOBALS['ap_test']['enqueued_scripts'], 'Ordinary content does not enqueue runtime.' );
render_shortcode( array(), '/widget.cast' );
print_late_styles();
print_late_styles();
same( array( 'lamgc-asciiplayer-style' ), $GLOBALS['ap_test']['style_print_calls'], 'Late/widget styles print once in the footer.' );
require __DIR__ . '/uploads.php';
echo "OK: {$assertions} assertions passed.\n";
} catch ( Throwable $error ) {
fwrite( STDERR, $error->getMessage() . "\n" );
exit( 1 );
}
+183
View File
@@ -0,0 +1,183 @@
<?php
/** Upload validation contracts. Included by run.php after its assertion helpers. */
use function LamGC\Asciiplayer\allow_cast_upload_mime;
use function LamGC\Asciiplayer\check_cast_filetype;
use function LamGC\Asciiplayer\is_valid_cast_file;
use function LamGC\Asciiplayer\validate_cast_upload;
use const LamGC\Asciiplayer\CAST_MAX_BYTES;
use const LamGC\Asciiplayer\CAST_MAX_EVENTS;
use const LamGC\Asciiplayer\CAST_MAX_LINE_BYTES;
use const LamGC\Asciiplayer\CAST_MAX_V1_BYTES;
use const LamGC\Asciiplayer\CAST_MIME;
function cast_contents_are_valid( $contents ) {
$path = tempnam( sys_get_temp_dir(), 'ap-cast-' );
try {
file_put_contents( $path, $contents );
return is_valid_cast_file( $path );
} finally {
unlink( $path );
}
}
$required_filters = array(
'upload_mimes' => array( 'LamGC\\Asciiplayer\\allow_cast_upload_mime', 2 ),
'wp_check_filetype_and_ext' => array( 'LamGC\\Asciiplayer\\check_cast_filetype', 5 ),
'wp_handle_upload_prefilter' => array( 'LamGC\\Asciiplayer\\validate_cast_upload', 1 ),
'wp_handle_sideload_prefilter' => array( 'LamGC\\Asciiplayer\\validate_cast_upload', 1 ),
);
foreach ( $GLOBALS['ap_test']['filters'] ?? array() as $filter ) {
if ( isset( $required_filters[ $filter[0] ] ) ) {
same( $required_filters[ $filter[0] ][0], $filter[1], 'Upload hook uses the intended callback.' );
same( $required_filters[ $filter[0] ][1], $filter[3], 'Upload hook receives all required arguments.' );
same( true, is_callable( $filter[1] ), 'Upload callback is callable.' );
unset( $required_filters[ $filter[0] ] );
}
}
same( array(), $required_filters, 'All safe-upload hooks are registered.' );
$mimes = array( 'jpg|jpeg' => 'image/jpeg', 'txt' => 'text/plain' );
same( $mimes, allow_cast_upload_mime( $mimes ), 'Anonymous/non-uploaders get no extra MIME permissions.' );
$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true );
same( array_merge( $mimes, array( 'cast' => CAST_MIME ) ), allow_cast_upload_mime( $mimes ), 'Only .cast receives the canonical MIME.' );
same( $mimes, allow_cast_upload_mime( $mimes, 42 ), 'Explicit non-uploading user does not inherit current user permissions.' );
$GLOBALS['ap_test']['user_capabilities'][42] = array( 'upload_files' => true );
same( CAST_MIME, allow_cast_upload_mime( $mimes, 42 )['cast'], 'An explicit eligible user can upload casts.' );
$GLOBALS['ap_test']['multisite'] = true;
$GLOBALS['ap_test']['site_options']['upload_filetypes'] = 'jpg jpeg txt';
same( $mimes, allow_cast_upload_mime( $mimes ), 'Multisite network extension restrictions remain in effect.' );
$GLOBALS['ap_test']['site_options']['upload_filetypes'] = "jpg\ncast txt";
same( CAST_MIME, allow_cast_upload_mime( $mimes )['cast'], 'Network-authorized cast uploads are available.' );
$GLOBALS['ap_test']['multisite'] = false;
$v2 = '{"version":2,"width":80,"height":24}';
$v3 = '{"version":3,"term":{"cols":100,"rows":30}}';
$v1 = array( 'version' => 1, 'width' => 80, 'height' => 24, 'duration' => 1.5, 'stdout' => array( array( 0.1, "Hello\r\n" ), array( 1.4, 'World' ) ) );
foreach ( array(
'pretty v1' => json_encode( $v1, JSON_PRETTY_PRINT ),
'v2 output' => $v2 . "\n[0.1,\"o\",\"Hello\\r\\n\"]\n",
'v3 relative events' => $v3 . "\n[5,\"o\",\"Hello\"]\n[0.1,\"r\",\"120x40\"]\n[0,\"x\",\"0\"]\n",
'v3 comments' => $v3 . "\n# comment before events\n[0,\"o\",\"ok\"]\n# trailing comment\n",
'v2 input markers resize extensions' => $v2 . "\n[0,\"i\",\"x\"]\n[0,\"m\",\"A\"]\n[1,\"r\",\"90x25\"]\n[1,\"future\",\"data\"]",
'CRLF' => $v2 . "\r\n[0,\"o\",\"hello\"]\r\n",
'header only' => $v2,
'unknown header fields' => '{"version":2,"width":80,"height":24,"future":{"key":true}}' . "\n[0,\"o\",\"ok\"]\n",
'literal terminal markup' => $v2 . "\n[0,\"o\",\"<script> is plain terminal output</script>\"]\n",
) as $description => $contents ) {
same( true, cast_contents_are_valid( $contents ), 'Accept valid ' . $description . '.' );
}
same( true, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/hello.cast' ), 'Accept repository hello recording.' );
same( true, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/resize.cast' ), 'Accept repository resize recording.' );
foreach ( array(
'empty' => '',
'plain text' => 'Hello world',
'JSON object' => '{"message":"arbitrary JSON"}',
'JSON list' => '[1,2,3]',
'HTML' => '<!doctype html><script>alert(1)</script>',
'SVG' => '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>',
'unsupported version' => '{"version":4,"width":80,"height":24}',
'string version' => '{"version":"2","width":80,"height":24}',
'zero width' => '{"version":2,"width":0,"height":24}',
'oversized width' => '{"version":2,"width":1001,"height":24}',
'negative height' => '{"version":2,"width":80,"height":-1}',
'fractional width' => '{"version":2,"width":80.5,"height":24}',
'string width' => '{"version":2,"width":"80","height":24}',
'v3 old dimensions' => '{"version":3,"width":80,"height":24}',
'v3 terminal array' => '{"version":3,"term":[100,30]}',
'v1 absent stdout' => "{\n\"version\":1,\"width\":80,\"height\":24\n}",
'v1 stdout object' => "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":{\"0\":[0,\"x\"]}\n}",
'compact v1 unsupported by bundled player' => json_encode( $v1 ),
'large compact v1 unsupported by bundled player' => json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_LINE_BYTES + 1 ) ) ) ),
'v1 negative delay' => json_encode( array_merge( $v1, array( 'stdout' => array( array( -1, 'x' ) ) ) ), JSON_PRETTY_PRINT ),
'v1 malformed later frame' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok' ), array( 0, array( 'x' ) ) ) ) ), JSON_PRETTY_PRINT ),
'v1 extra frame element' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok', 'extra' ) ) ) ), JSON_PRETTY_PRINT ),
'v1 bad duration' => json_encode( array_merge( $v1, array( 'duration' => '1' ) ), JSON_PRETTY_PRINT ),
'negative event time' => $v2 . "\n[-1,\"o\",\"bad\"]\n",
'string event time' => $v2 . "\n[\"0\",\"o\",\"bad\"]\n",
'boolean event time' => $v2 . "\n[false,\"o\",\"bad\"]\n",
'infinite time' => $v2 . "\n[1e999,\"o\",\"bad\"]\n",
'milliseconds overflow' => $v2 . "\n[1e308,\"o\",\"bad\"]\n",
'v3 cumulative milliseconds overflow' => $v3 . "\n[1e305,\"o\",\"first\"]\n[1e305,\"o\",\"second\"]\n",
'v2 out of order' => $v2 . "\n[2,\"o\",\"first\"]\n[1,\"o\",\"second\"]\n",
'event object' => $v2 . "\n{\"0\":0,\"1\":\"o\",\"2\":\"bad\"}\n",
'missing event data' => $v2 . "\n[0,\"o\"]\n",
'extra event element' => $v2 . "\n[0,\"o\",\"bad\",1]\n",
'event data array' => $v2 . "\n[0,\"o\",[\"bad\"]]\n",
'empty event type' => $v2 . "\n[0,\"\",\"bad\"]\n",
'zero resize' => $v2 . "\n[0,\"r\",\"0x20\"]\n",
'oversized resize' => $v2 . "\n[0,\"r\",\"2000x20\"]\n",
'malformed resize' => $v2 . "\n[0,\"r\",\"80,24\"]\n",
'bad later JSON' => $v2 . "\n[0,\"o\",\"ok\"]\n[1,\"o\",\"truncated\"\n",
'trailing HTML' => $v2 . "\n[0,\"o\",\"ok\"]\n<script>alert(1)</script>\n",
'trailing JSON object' => $v2 . "\n[0,\"o\",\"ok\"]\n{\"unrelated\":true}\n",
'blank event line' => $v2 . "\n\n",
'indented event ignored by bundled player' => $v2 . "\n [0,\"o\",\"invisible\"]\n",
'v2 comment' => $v2 . "\n# comment\n",
'v3 indented comment' => $v3 . "\n # not a comment\n",
'UTF-8 BOM' => "\xef\xbb\xbf" . $v2,
'invalid UTF-8' => $v2 . "\n[0,\"o\",\"\xff\"]\n",
'oversized JSONL line' => $v2 . "\n[0,\"o\",\"" . str_repeat( 'a', CAST_MAX_LINE_BYTES ) . "\"]\n",
'oversized comment line' => $v3 . "\n#" . str_repeat( 'a', CAST_MAX_LINE_BYTES ) . "\n",
'deep JSON' => $v2 . "\n[0,\"o\"," . str_repeat( '[', 20 ) . '0' . str_repeat( ']', 20 ) . "]\n",
) as $description => $contents ) {
same( false, cast_contents_are_valid( $contents ), 'Reject ' . $description . '.' );
}
same( false, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/malformed.cast' ), 'Reject repository malformed recording.' );
same( false, is_valid_cast_file( '/does-not-exist/asciicast.cast' ), 'Reject missing files.' );
same( false, is_valid_cast_file( __DIR__ ), 'Reject directories.' );
same( false, is_valid_cast_file( 'data://text/plain,' . $v2 ), 'Reject stream wrappers before opening.' );
same( false, is_valid_cast_file( null ), 'Reject missing temporary upload path.' );
same( true, cast_contents_are_valid( $v2 . "\n" . str_repeat( "[0,\"o\",\"x\"]\n", CAST_MAX_EVENTS ) ), 'Accept the documented event-count boundary.' );
same( false, cast_contents_are_valid( $v2 . "\n" . str_repeat( "[0,\"o\",\"x\"]\n", CAST_MAX_EVENTS + 1 ) ), 'Reject excessive event count.' );
same( false, cast_contents_are_valid( json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_V1_BYTES ) ) ), JSON_PRETTY_PRINT ) ), 'Bound whole-document legacy decoding.' );
$path = tempnam( sys_get_temp_dir(), 'ap-cast-' );
try {
$handle = fopen( $path, 'wb' );
ftruncate( $handle, CAST_MAX_BYTES + 1 );
fclose( $handle );
same( false, is_valid_cast_file( $path ), 'Reject files over the byte limit before reading their contents.' );
file_put_contents( $path, $v2 . "\n[0,\"o\",\"ok\"]\n" );
clearstatcache( true, $path );
$upload = array( 'name' => 'recording.cast', 'tmp_name' => $path, 'error' => 0, 'type' => 'text/plain', 'size' => 1 );
same( $upload, validate_cast_upload( $upload ), 'Valid content passes without trusting or changing browser MIME or size.' );
$denied = array( 'ext' => false, 'type' => false, 'proper_filename' => false );
$approved = array( 'ext' => 'cast', 'type' => CAST_MIME, 'proper_filename' => false );
foreach ( array( 'text/plain', 'application/json', 'application/octet-stream', false ) as $detected_mime ) {
same( $approved, check_cast_filetype( $denied, $path, 'recording.cast', null, $detected_mime ), 'Content validation safely handles generic fileinfo guesses.' );
}
same( $approved, check_cast_filetype( $denied, $path, 'recording.CAST' ), 'Uppercase cast extension is supported.' );
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array() ), 'An explicitly empty MIME allow-list stays empty.' );
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'txt' => 'text/plain' ) ), 'An explicit MIME allow-list excluding cast remains restricted.' );
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'cast' => 'text/plain' ) ), 'Only our canonical allowed type can receive the MIME override.' );
$GLOBALS['ap_test']['allowed_mimes'] = array( 'txt' => 'text/plain' );
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'cast' => CAST_MIME ) ), 'An explicit allow-list cannot bypass a later global MIME restriction.' );
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Prefilter also preserves later global MIME restrictions.' );
unset( $GLOBALS['ap_test']['allowed_mimes'] );
$unrelated = array( 'ext' => 'svg', 'type' => 'image/svg+xml', 'proper_filename' => 'x.svg' );
foreach ( array( 'x.json', 'x.html', 'x.svg', 'x.cast.php', "x.cast\n" ) as $filename ) {
same( $unrelated, check_cast_filetype( $unrelated, $path, $filename ), 'Other extensions and double-extension executables remain untouched.' );
}
same( true, is_string( validate_cast_upload( array_merge( $upload, array( 'tmp_name' => '/missing' ) ) )['error'] ), 'Missing temporary upload fails closed.' );
$GLOBALS['ap_test']['capabilities'] = array();
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Upload permissions are enforced for valid content too.' );
same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'MIME override never grants upload capability.' );
$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true, 'unfiltered_upload' => true );
file_put_contents( $path, $v2 . "\n<script>alert(1)</script>\n" );
clearstatcache( true, $path );
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Malformed content fails even with unfiltered_upload.' );
same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'Invalid content cannot keep a previous MIME approval.' );
$other_upload = array_merge( $upload, array( 'name' => 'ordinary.txt' ) );
same( $other_upload, validate_cast_upload( $other_upload ), 'Other extensions keep core upload behavior.' );
$existing_error = array_merge( $upload, array( 'error' => 'Rejected by another plugin.' ) );
same( $existing_error, validate_cast_upload( $existing_error ), 'Existing upload errors are preserved.' );
$php_error = array_merge( $upload, array( 'error' => 3 ) );
same( $php_error, validate_cast_upload( $php_error ), 'PHP partial-upload errors are preserved.' );
} finally {
unlink( $path );
}
unset( $GLOBALS['ap_test']['capabilities'], $GLOBALS['ap_test']['user_capabilities'], $GLOBALS['ap_test']['multisite'], $GLOBALS['ap_test']['site_options'], $GLOBALS['ap_test']['allowed_mimes'] );