Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions assets/src/video-player/web-components/__tests__/player.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Tests for the video player web component.
*/

describe( 'optimole-video-player', () => {
beforeAll( () => {
global.OMVideoPlayerBlock = {
play: 'Play',
pause: 'Pause',
mute: 'Mute',
unmute: 'Unmute',
fullscreen: 'Fullscreen',
exitFullscreen: 'Exit fullscreen'
};

require( '../player' );
});

afterEach( () => {
document.body.innerHTML = '';
});

const mount = ( src ) => {
const player = document.createElement( 'optimole-video-player' );
if ( src ) {
player.setAttribute( 'video-src', src );
}
document.body.appendChild( player );

return player.querySelector( 'video' );
};

test( 'uses the whole video-src attribute as the video source', () => {
const sources = [
'https://example.org/clip.mp4',
'https://example.org/clip.mp4?" data-extra="1'
];

sources.forEach( ( src ) => {
const video = mount( src );

expect( video.getAttribute( 'src' ) ).toBe( src );
expect( video.getAttributeNames().sort() ).toEqual([ 'class', 'src' ]);
});
});

test( 'leaves the video without a source when video-src is not set', () => {
expect( mount( null ).hasAttribute( 'src' ) ).toBe( false );
});
});
7 changes: 6 additions & 1 deletion assets/src/video-player/web-components/player.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ class OptimoleVideoPlayer extends HTMLElement {
render() {
this.innerHTML = `
<div class="optml-player-container">
<video src="${this.videoSrc}" class="optml-video ${this.hideClass}"></video>
<video class="optml-video ${this.hideClass}"></video>
<div class="optml-spinner"><span class="optml-ic">${this.getIcon( this.icons.spinner )}</span></div>
<button class="optml-video-lg-play ${this.hideClass}" aria-label="${this.strings.play}">${this.getIcon( this.icons.play )}</button>
<div class="optml-controls ${'true' === this.hideControls ? this.hideClass : ''}">
Expand All @@ -90,6 +90,11 @@ class OptimoleVideoPlayer extends HTMLElement {
</div>
</div>
`;

// The source is set on the element, so the URL is never read as markup.
if ( this.videoSrc ) {
this.querySelector( '.optml-video' ).setAttribute( 'src', this.videoSrc );
}
}

setupEventListeners() {
Expand Down
3 changes: 0 additions & 3 deletions inc/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,6 @@ private function build_args( $method, $url, $headers, $params ) {
'method' => $method,
'timeout' => 45,
'user-agent' => 'Optimle WP (v' . OPTML_VERSION . ') ',
'sslverify' => false,
'headers' => $headers,
];
if ( $method !== 'GET' ) {
Expand Down Expand Up @@ -297,7 +296,6 @@ public function call_onboard_api( $images = [] ) {
],
'timeout' => 60,
'blocking' => true,
'sslverify' => false,
'data_format' => 'body',
];
return wp_remote_post( $this->onboard_api_root, $options );
Expand Down Expand Up @@ -405,7 +403,6 @@ public function log_offload_error( $error_response ) {
'headers' => [ 'Content-Type' => 'application/json' ],
'timeout' => 15,
'blocking' => true,
'sslverify' => false,
'data_format' => 'body',
'body' => [
'error_body' => wp_json_encode( $body ),
Expand Down
58 changes: 45 additions & 13 deletions inc/lazyload_replacer.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ final class Optml_Lazyload_Replacer extends Optml_App_Replacer {
* attribute value starts with a backslash is not matched, so JSON-escaped iframe markup is left as written.
*/
private const TAG_ATTRIBUTE = self::TAG_ATTRIBUTE_SEPARATOR . '[^\s"\'>\/=]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s"\'>\\\\][^\s>]*))?';
/**
* One image tag attribute with its separator, whose value may be JSON-escaped, with quotes written as \" or \'.
*/
private const IMAGE_TAG_ATTRIBUTE = self::TAG_ATTRIBUTE_SEPARATOR . '[^\s"\'>\/=\\\\]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\\\\"[^"]*?\\\\"|\\\\\'[^\']*?\\\\\'|(?:[^\s"\'>\\\\]|\\\\(?!["\']))[^\s>]*))?';
/**
* If frame lazyload is present on page.
*
Expand Down Expand Up @@ -282,22 +286,26 @@ public function lazyload_tag_replace( $new_tag, $original_url, $new_url, $optml_
);
}

$loading = [];
// Most tags do not hold the word at all, and need no pattern.
$has_loading = stripos( $new_tag, 'loading' ) !== false && preg_match( $this->image_attribute_pattern( 'loading' ), $new_tag, $loading ) === 1;
// Only a quoted value that is not JSON-escaped is changed; any other loading attribute is kept as written.
$after_loading = isset( $loading[3] ) ? substr( $new_tag, strlen( $loading[0] ) ) : null;

if ( self::instance()->settings->get( 'native_lazyload' ) === 'enabled' ) {
// First check if loading attribute already exists
if ( strpos( $new_tag, 'loading=' ) !== false ) {
// Replace existing loading attribute with lazy
$loading_attr = $is_slashed ? 'loading=\"lazy\"' : 'loading="lazy"';
$new_tag = preg_replace( '/loading=(["\'])[^"\']*\1/i', $loading_attr, $new_tag );
} else {
$lazy_attr = $is_slashed ? 'loading=\"lazy\"' : 'loading="lazy"';
if ( ! $has_loading ) {
// No loading attribute exists, add it after <img
$loading_attr = $is_slashed ? ' loading=\"lazy\"' : ' loading="lazy"';
$new_tag = preg_replace( '/<img/i', '<img' . $loading_attr, $new_tag, 1 );
return preg_replace( '/<img/i', '<img ' . $lazy_attr, $new_tag, 1 );
}
return $new_tag;

return null === $after_loading ? $new_tag : $loading[1] . $loading[2] . $lazy_attr . $after_loading;
}

// we remove the loading attribute if it exists with strpos
$new_tag = preg_replace( '/loading=(["\'])[^"\']*\1/i', '', $new_tag );
// we remove the loading attribute if it exists
if ( null !== $after_loading ) {
$new_tag = $loading[1] . $loading[2] . $after_loading;
}

$should_ignore_rescale = ! $this->is_valid_mimetype_from_url( $original_url, [ 'gif' => true, 'svg' => true ] );

Expand Down Expand Up @@ -362,8 +370,11 @@ public function lazyload_tag_replace( $new_tag, $original_url, $new_url, $optml_
);

// We remove srcset and sizes attributes since our lazyload does not need them.
$pattern = '/\s+(?:srcset|sizes)=("[^"]*"|\'[^\']*\'|\\\\"[^\\\\"]*\\\\")/i';
$new_tag = preg_replace( $pattern, '', $new_tag );
foreach ( [ 'srcset', 'sizes' ] as $attribute ) {
if ( stripos( $new_tag, $attribute ) !== false ) {
$new_tag = preg_replace( $this->image_attribute_pattern( $attribute ), '$1', $new_tag, 1 ) ?? $new_tag;
}
}

// We keep this for srcset lazyload compatibility that might break our mechanism.
$new_tag = str_replace( 'srcset=', 'old-srcset=', $new_tag );
Expand All @@ -374,6 +385,27 @@ public function lazyload_tag_replace( $new_tag, $original_url, $new_url, $optml_

return $new_tag . '<noscript>' . $no_script_tag . '</noscript>';
}
/**
* Build the pattern that finds an attribute of an image tag.
*
* Every attribute before it is matched whole, so the same text inside another attribute's value is not taken
* for the attribute. Group 1 is the tag up to the attribute's separator and group 2 the separator. Group 3 is
* the value, set only when it is quoted and not JSON-escaped; a JSON-escaped value is matched when it is
* double-quoted and holds no backslash.
*
* @param string $name Attribute name.
*
* @return string The pattern.
*/
private function image_attribute_pattern( string $name ): string {
static $patterns = [];

if ( ! isset( $patterns[ $name ] ) ) {
$patterns[ $name ] = '#^((?:<noscript\s*>\s*)?<img(?>(?:(?!\s*' . $name . '\s*=)' . self::IMAGE_TAG_ATTRIBUTE . ')*))(' . self::TAG_ATTRIBUTE_SEPARATOR . ')' . $name . '\s*=\s*(?:("[^"]*"|\'[^\']*\')|\\\\"[^\\\\"]*\\\\"|[^\s"\'>\\\\][^\s>]*)#i';
}

return $patterns[ $name ];
}
/**
* Replaces video embeds with lazyload embeds.
*
Expand Down
75 changes: 67 additions & 8 deletions inc/logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ class Optml_Logger {

const LOG_SEPARATOR = '==========';

/**
* The option that holds the random part of this site's log file names.
*/
const FILE_TOKEN_OPTION = 'optml_log_file_token';

/**
* Upload directory.
*
Expand All @@ -18,9 +23,9 @@ class Optml_Logger {
private $upload_dir;

/**
* Log filenames.
* The log types, with the fixed file name each was stored under before file names carried a hash.
*
* @var array
* @var array<string, string>
*/
private $log_filenames = [
self::LOG_TYPE_OFFLOAD => 'offload.log',
Expand Down Expand Up @@ -64,8 +69,62 @@ private function __construct() {
}

add_action( 'wp_ajax_optml_fetch_logs', [ $this, 'fetch_logs_ajax_handler' ] );
add_action( 'admin_init', [ $this, 'protect_log_files' ] );
}

/**
* Get the path of a log file.
*
* The file name carries a random token stored for this site, so the log cannot be requested by guessing its
* URL. A log written under the earlier fixed name is moved to the new one.
*
* @param string $type Type of log (offload/rollback).
*
* @return string Absolute path of the log file.
*/
private function get_file_path( $type ) {
$token = get_option( self::FILE_TOKEN_OPTION );
if ( ! is_string( $token ) || '' === $token ) {
$token = wp_generate_password( 32, false );
update_option( self::FILE_TOKEN_OPTION, $token );
}

$legacy_path = $this->upload_dir . $this->log_filenames[ $type ];
$file_path = $this->upload_dir . $type . '-' . $token . '.log';

// A log that cannot be moved is deleted, so nothing stays under the old name.
if ( file_exists( $legacy_path ) && ( file_exists( $file_path ) || ! @rename( $legacy_path, $file_path ) ) ) {
wp_delete_file( $legacy_path );
}

return $file_path;
}

/**
* Move the logs written under the earlier fixed names, and add the files that keep a web server from listing
* or serving the log directory. A file that already exists is kept as it is.
*
* @return void
*/
public function protect_log_files() {
if ( ! $this->has_permission() ) {
return;
}

foreach ( array_keys( $this->log_filenames ) as $type ) {
$this->get_file_path( $type );
}

$files = [
'index.html' => '',
'.htaccess' => "<IfModule mod_authz_core.c>\n\tRequire all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\n\tDeny from all\n</IfModule>\n",
];
foreach ( $files as $name => $content ) {
if ( ! file_exists( $this->upload_dir . $name ) ) {
file_put_contents( $this->upload_dir . $name, $content );
}
}
}
/**
* Adds a log entry.
*
Expand All @@ -84,7 +143,7 @@ public function add_log( $type, $message ) {
return false;
}

$file_path = $this->upload_dir . $this->log_filenames[ $type ];
$file_path = $this->get_file_path( $type );
$handle = @fopen( $file_path, 'a' );

if ( $handle === false ) {
Expand All @@ -110,9 +169,9 @@ public function get_log( $type, $lines = 500, $separator = '' ) {
return false;
}

$file_path = $this->upload_dir . $this->log_filenames[ $type ];
$file_path = $this->get_file_path( $type );

if ( $this->has_logs( $type ) ) {
if ( file_exists( $file_path ) ) {
$data = $this->tailCustom( $file_path, $lines, true, $separator );
return nl2br( esc_textarea( $data ) );
}
Expand All @@ -131,7 +190,7 @@ public function has_logs( $type ) {
return false;
}

$file_path = $this->upload_dir . $this->log_filenames[ $type ];
$file_path = $this->get_file_path( $type );
return file_exists( $file_path );
}

Expand Down Expand Up @@ -215,8 +274,8 @@ private function tailCustom( $filepath, $lines = 1, $adaptive = true, $separator
*/
public function fetch_logs_ajax_handler() {
// Check for nonce security
$nonce = $_REQUEST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
$nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ) : '';
if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) || ! current_user_can( 'manage_options' ) ) {
wp_die( __( 'Security check failed', 'optimole-wp' ) );
}

Expand Down
2 changes: 1 addition & 1 deletion inc/manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ public function replace_content( $html, $partial = false ) {
$missing = $this->page_profiler->missing_devices( $profile_id );
$time = time();
$url = esc_url( esc_js( $this->get_current_url() ) );
$hmac = wp_hash( $profile_id . $time . $url, 'nonce' );
$hmac = Profile::sign( $profile_id, $time, $url );
$js_optimizer = str_replace(
[ Profile::PLACEHOLDER, Profile::PLACEHOLDER_MISSING, Profile::PLACEHOLDER_TIME, Profile::PLACEHOLDER_HMAC, Profile::PLACEHOLDER_URL ],
[ $profile_id, implode( ',', $missing ), strval( $time ), $hmac, $url ],
Expand Down
Loading
Loading