← Back
Editing: as3-sdk-sync.php
<?php /* Plugin Name: UltraSync CDN Description: Seamlessly sync your WordPress media to AWS S3 and serve through CloudFront — images, video, backgrounds, all covered, concurrent, resumable sync for uploads directory with modern UI and live progress tracking. Version: 3.0.0 Author: Parth License: GPLv2+ */ if ( ! defined( 'ABSPATH' ) ) exit; // ── PHP version gate ────────────────────────────────────────────────────── // AWS SDK v3 requires PHP >= 8.1. Show a clear admin notice instead of // a fatal error when running on an older interpreter. if ( version_compare( PHP_VERSION, '8.1.0', '<' ) ) { add_action( 'admin_notices', function() { echo '<div class="notice notice-error"><p><strong>UltraSync CDN:</strong> ' . 'PHP 8.1 or higher is required (you are running ' . PHP_VERSION . '). ' . 'Please upgrade PHP before activating this plugin.</p></div>'; } ); return; } // --- Attempt to include AWS SDK autoloader --- $vendor_autoload_1 = __DIR__ . '/vendor/autoload.php'; $vendor_autoload_2 = __DIR__ . '/aws-autoloader.php'; if ( file_exists( $vendor_autoload_1 ) ) { require_once $vendor_autoload_1; } elseif ( file_exists( $vendor_autoload_2 ) ) { require_once $vendor_autoload_2; } // If AWS classes not available, show admin notice and stop early if ( ! class_exists( 'Aws\\S3\\S3Client' ) ) { add_action( 'admin_notices', function(){ echo '<div class="notice notice-error"><p><strong>UltraSync CDN:</strong> AWS SDK for PHP not found. Install dependency: <code>composer require aws/aws-sdk-php</code></p></div>'; } ); return; } use Aws\S3\S3Client; use Aws\Exception\AwsException; use Aws\MultipartUploader; use Aws\S3\Exception\S3Exception; use Aws\Result; use Aws\Credentials\Credentials; // Settings option name if ( ! defined( 'AS3_SDK_SYNC_OPTIONS' ) ) define( 'AS3_SDK_SYNC_OPTIONS', 'as3_sdk_sync_options' ); // Progress file constants if ( ! defined( 'AS3_PROGRESS_FILE' ) ) define( 'AS3_PROGRESS_FILE', __DIR__ . '/as3_sdk_progress.json' ); if ( ! defined( 'AS3_STATUS_FILE' ) ) define( 'AS3_STATUS_FILE', __DIR__ . '/as3_sdk_status.json' ); // Cached list of every file to sync — built once at start so chunks don't rescan the disk each time if ( ! defined( 'AS3_MANIFEST_FILE' ) ) define( 'AS3_MANIFEST_FILE', __DIR__ . '/as3_sdk_manifest.json' ); // How many files each browser-driven AJAX chunk uploads. Small = safe under any execution limit. if ( ! defined( 'AS3_CHUNK_SIZE' ) ) define( 'AS3_CHUNK_SIZE', 15 ); // Hard wall-clock budget (seconds) per chunk — second safety net against host timeouts. if ( ! defined( 'AS3_CHUNK_TIME_BUDGET' ) ) define( 'AS3_CHUNK_TIME_BUDGET', 18 ); // Add Admin Menu — top-level sidebar item add_action( 'admin_menu', function() { add_menu_page( 'UltraSync CDN', 'UltraSync CDN', 'manage_options', 'as3-sdk-sync', 'as3_sdk_sync_page', 'dashicons-cloud-upload', 80 ); } ); // ----------------------------------------------------------------------- // AUTO-UPLOAD IMAGES (original + ALL generated sizes) after WP finishes // generating thumbnails. Replaces the old add_attachment hook which fired // too early — before thumbnail variants existed on disk. // ----------------------------------------------------------------------- add_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id ) { $mime = get_post_mime_type( $attachment_id ); // Only handle images here; video poster is handled in its own hook below if ( strpos( $mime, 'image/' ) !== 0 ) { return $metadata; } define_predefined_as3_defaults(); $opts = get_option( AS3_SDK_SYNC_OPTIONS ); $bucket = AS3_DEFAULT_BUCKET; $folder = $opts['path'] ?? ''; $local_path = rtrim( $opts['local_path'] ?? '', '/' ); if ( empty( $bucket ) || empty( $local_path ) ) { error_log( 'UltraSync CDN auto-upload skipped: Missing bucket or local_path setting.' ); return $metadata; } $s3 = new Aws\S3\S3Client( [ 'version' => 'latest', 'region' => AS3_DEFAULT_REGION, 'credentials' => [ 'key' => AS3_DEFAULT_ACCESS_KEY, 'secret' => AS3_DEFAULT_SECRET_KEY ], ] ); // Build list of files: original + every generated thumbnail size $files_to_upload = []; $original_path = get_attached_file( $attachment_id ); if ( $original_path && file_exists( $original_path ) ) { $files_to_upload[] = $original_path; } // WordPress stores size filenames relative to the original's directory if ( ! empty( $metadata['sizes'] ) && ! empty( $original_path ) ) { $upload_dir = trailingslashit( dirname( $original_path ) ); foreach ( $metadata['sizes'] as $size ) { if ( ! empty( $size['file'] ) ) { $size_path = $upload_dir . $size['file']; if ( file_exists( $size_path ) ) { $files_to_upload[] = $size_path; } } } } $normalized_local = wp_normalize_path( $local_path ); foreach ( $files_to_upload as $file_path ) { $relative = ltrim( str_replace( $normalized_local, '', wp_normalize_path( $file_path ) ), '/' ); $s3_key = $folder ? rtrim( $folder, '/' ) . '/' . $relative : $relative; try { $s3->putObject( [ 'Bucket' => $bucket, 'Key' => $s3_key, 'SourceFile' => $file_path, 'CacheControl' => 'public,max-age=31536000,immutable', ] ); error_log( "UltraSync CDN auto-upload success: $s3_key" ); } catch ( Exception $e ) { error_log( "UltraSync CDN auto-upload error ($s3_key): " . $e->getMessage() ); } } return $metadata; }, 999, 2 ); // ----------------------------------------------------------------------- // CDN URL REWRITING — images, backgrounds, VIDEO, audio, all media // ----------------------------------------------------------------------- /** * Build the regex pattern that matches the uploads base URL * under both http:// and https://. * Cached per-request for performance. */ function as3_cdn_pattern() { static $pattern = null; if ( $pattern !== null ) return $pattern; $uploads_dir = wp_upload_dir(); $uploads_baseurl = rtrim( $uploads_dir['baseurl'], '/' ); // Strip scheme so we can match http:// OR https:// $no_scheme = preg_replace( '#^https?://#', '', $uploads_baseurl ); $pattern = '#https?://' . preg_quote( $no_scheme, '#' ) . '#i'; return $pattern; } /** * The uploads path *relative to the domain root*, e.g. "/wp-content/uploads". * Used to catch relative URLs (data-src="/wp-content/uploads/...") that * lazy-load page builders (X/Pro/Cornerstone, Elementor, etc.) emit and then * copy into the real src= via JavaScript on the client. */ function as3_cdn_uploads_relpath() { static $rel = null; if ( $rel !== null ) return $rel; $uploads_dir = wp_upload_dir(); $rel = rtrim( wp_parse_url( $uploads_dir['baseurl'], PHP_URL_PATH ) ?: '', '/' ); return $rel; } /** * Core URL rewriter — swaps any uploads URL to CDN. * Handles http/https mismatches and every attachment type * including mp4, webm, ogv, mp3, pdf, etc. */ /** * True if a URL/path points to a web font file. * Fonts are NEVER rewritten to the CDN: browsers enforce CORS on cross-origin * fonts, and if CloudFront doesn't send Access-Control-Allow-Origin the font is * blocked and any text using it renders invisible. Fonts stay on the origin. */ function as3_is_font_url( $url ) { if ( ! is_string( $url ) || $url === '' ) return false; $clean = preg_replace( '#[?\#].*$#', '', $url ); // drop query/fragment return (bool) preg_match( '#\.(woff2?|ttf|otf|eot)$#i', $clean ); } function as3_cdn_rewrite_url( $url ) { if ( empty( $url ) || ! is_string( $url ) ) return $url; // Never send fonts through the CDN (CORS). if ( as3_is_font_url( $url ) ) return $url; $opts = get_option( AS3_SDK_SYNC_OPTIONS ); // If CDN is disabled, return the original URL so local server is used as fallback. if ( empty( $opts['cdn_enabled'] ) ) return $url; $cdn_base = rtrim( trim( $opts['cdn_url'] ?? '' ), '/' ); if ( empty( $cdn_base ) ) return $url; return preg_replace( as3_cdn_pattern(), $cdn_base, $url ); } /** * Rewrite ALL upload URLs found anywhere in an HTML string: * <video src> <source src> <img src> srcset poster * style="background-image:url(…)" data-src data-bg etc. * * Catches THREE URL shapes so lazy-loaders can't slip through: * 1. Absolute https://site.com/wp-content/uploads/… * 2. Protocol-rel //site.com/wp-content/uploads/… * 3. Root-relative /wp-content/uploads/… (the data-src case in X/Pro/Cornerstone) */ function as3_cdn_rewrite_html( $html ) { if ( empty( $html ) || ! is_string( $html ) ) return $html; $opts = get_option( AS3_SDK_SYNC_OPTIONS ); // If CDN is disabled, leave URLs pointing to local server as safe fallback. if ( empty( $opts['cdn_enabled'] ) ) return $html; $cdn_base = rtrim( trim( $opts['cdn_url'] ?? '' ), '/' ); if ( empty( $cdn_base ) ) return $html; $uploads_dir = wp_upload_dir(); $uploads_baseurl = rtrim( $uploads_dir['baseurl'], '/' ); $no_scheme = preg_replace( '#^https?://#', '', $uploads_baseurl ); // host + /wp-content/uploads $rel = as3_cdn_uploads_relpath(); // /wp-content/uploads // 1 + 2: absolute and protocol-relative (https://, http://, //) // Capture the trailing path so we can leave font files on the origin (CORS). $html = preg_replace_callback( '#(?:https?:)?//' . preg_quote( $no_scheme, '#' ) . '(/[^"\')\s>]*)?#i', function ( $m ) use ( $cdn_base ) { $path = $m[1] ?? ''; if ( as3_is_font_url( $path ) ) return $m[0]; // keep fonts on origin return $cdn_base . $path; }, $html ); // 3: root-relative — but ONLY inside an attribute value (src/href/data-*/poster/srcset) // so we never touch things that merely contain the path as plain text. if ( $rel !== '' ) { $rel_q = preg_quote( $rel, '#' ); // matches ="/wp-content/uploads… or ='/wp-content/uploads… or =( for url(/wp-content/uploads…) $html = preg_replace_callback( '#([=\(]\s*["\']?)' . $rel_q . '(/[^"\')\s>]*)#i', function ( $m ) use ( $cdn_base ) { if ( as3_is_font_url( $m[2] ) ) return $m[0]; // keep fonts on origin return $m[1] . $cdn_base . $m[2]; }, $html ); } return $html; } // ── Output buffer: rewrites the ENTIRE page output ────────────────────── // This catches every src/href/url() including page-builder video layers. add_action( 'template_redirect', function() { if ( is_admin() ) return; if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) return; if ( defined( 'DOING_CRON' ) && DOING_CRON ) return; if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) return; $opts = get_option( AS3_SDK_SYNC_OPTIONS ); // Only buffer/rewrite when CDN is enabled AND a CDN URL is set. if ( empty( $opts['cdn_enabled'] ) ) return; if ( empty( trim( $opts['cdn_url'] ?? '' ) ) ) return; ob_start( 'as3_cdn_rewrite_html' ); } ); // ── All attachment types (images, video, audio, documents) ── add_filter( 'wp_get_attachment_url', 'as3_cdn_rewrite_url', 999 ); add_filter( 'wp_get_attachment_image_url', 'as3_cdn_rewrite_url', 999 ); // ── Image src + srcset ── add_filter( 'wp_get_attachment_image_src', function( $image ) { if ( ! empty( $image[0] ) ) $image[0] = as3_cdn_rewrite_url( $image[0] ); return $image; }, 999 ); add_filter( 'wp_calculate_image_srcset', function( $sources ) { foreach ( $sources as &$src ) { $src['url'] = as3_cdn_rewrite_url( $src['url'] ); } return $sources; }, 999 ); // ── Content + widget text ── add_filter( 'the_content', 'as3_cdn_rewrite_html', 999 ); add_filter( 'widget_text', 'as3_cdn_rewrite_html', 999 ); add_filter( 'widget_text_content', 'as3_cdn_rewrite_html', 999 ); // ── [video] and [audio] shortcode HTML output ── add_filter( 'wp_video_shortcode', 'as3_cdn_rewrite_html', 999 ); add_filter( 'wp_audio_shortcode', 'as3_cdn_rewrite_html', 999 ); // ── Gutenberg blocks: video, audio, image, cover, media-text, file ── add_filter( 'render_block', function( $block_content, $block ) { if ( empty( $block_content ) ) return $block_content; $rewrite_blocks = [ 'core/video', 'core/audio', 'core/image', 'core/cover', 'core/media-text', 'core/file', ]; if ( in_array( $block['blockName'] ?? '', $rewrite_blocks, true ) ) { return as3_cdn_rewrite_html( $block_content ); } return $block_content; }, 999, 2 ); // ── REST API responses (Gutenberg media library, block editor) ── add_filter( 'rest_prepare_attachment', function( $response ) { $data = $response->get_data(); if ( ! empty( $data['source_url'] ) ) { $data['source_url'] = as3_cdn_rewrite_url( $data['source_url'] ); } if ( ! empty( $data['media_details']['sizes'] ) ) { foreach ( $data['media_details']['sizes'] as &$size ) { if ( ! empty( $size['source_url'] ) ) { $size['source_url'] = as3_cdn_rewrite_url( $size['source_url'] ); } } } $response->set_data( $data ); return $response; }, 999 ); // ── Auto-upload VIDEO files (.mp4, .webm, etc.) + their poster frame to S3 ── // The image hook above fires for images only. This hook handles all video/* types, // uploading the raw video file AND its poster thumbnail (if generated by WP). add_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id ) { $mime = get_post_mime_type( $attachment_id ); if ( strpos( $mime, 'video/' ) !== 0 ) { return $metadata; // handled by the image hook above } define_predefined_as3_defaults(); $opts = get_option( AS3_SDK_SYNC_OPTIONS ); $bucket = AS3_DEFAULT_BUCKET; $folder = $opts['path'] ?? ''; $local_base = rtrim( $opts['local_path'] ?? '', '/' ); if ( empty( $bucket ) || empty( $local_base ) ) { error_log( 'UltraSync CDN video auto-upload skipped: Missing bucket or local_path setting.' ); return $metadata; } $s3 = new Aws\S3\S3Client( [ 'version' => 'latest', 'region' => AS3_DEFAULT_REGION, 'credentials' => [ 'key' => AS3_DEFAULT_ACCESS_KEY, 'secret' => AS3_DEFAULT_SECRET_KEY ], ] ); $files_to_upload = []; // 1. The actual video file $video_path = get_attached_file( $attachment_id ); if ( $video_path && file_exists( $video_path ) ) { $files_to_upload[] = [ 'path' => $video_path, 'mime' => $mime ]; } // 2. The poster/thumbnail frame WP may have generated if ( ! empty( $metadata['image']['filepath'] ) && file_exists( $metadata['image']['filepath'] ) ) { $files_to_upload[] = [ 'path' => $metadata['image']['filepath'], 'mime' => 'image/jpeg' ]; } $normalized_local = wp_normalize_path( $local_base ); foreach ( $files_to_upload as $item ) { $relative = ltrim( str_replace( $normalized_local, '', wp_normalize_path( $item['path'] ) ), '/' ); $s3_key = $folder ? rtrim( $folder, '/' ) . '/' . $relative : $relative; try { $s3->putObject( [ 'Bucket' => $bucket, 'Key' => $s3_key, 'SourceFile' => $item['path'], 'ContentType' => $item['mime'], // explicit MIME — critical for video playback 'CacheControl' => 'public,max-age=31536000,immutable', ] ); error_log( "UltraSync CDN video auto-upload success: $s3_key" ); } catch ( Exception $e ) { error_log( 'UltraSync CDN video auto-upload error (' . $s3_key . '): ' . $e->getMessage() ); } } return $metadata; }, 999, 2 ); // ----------------------------------------------------------------------- // FIX: safer relative-path calculation in auto-upload hook // (uses wp_normalize_path to avoid mismatches on symlinks / Windows paths) // ----------------------------------------------------------------------- // Register settings add_action( 'admin_init', function() { register_setting( 'as3_sdk_sync_group', AS3_SDK_SYNC_OPTIONS, [ 'sanitize_callback' => function( $input ) { define_predefined_as3_defaults(); $site_name = sanitize_title( $input['site_name'] ?? '' ); // Site Name is required — refuse to save without it and keep existing options. if ( empty( $site_name ) ) { add_settings_error( AS3_SDK_SYNC_OPTIONS, 'site_name_required', 'Please enter Site Name first — configuration was not saved.', 'error' ); $existing = get_option( AS3_SDK_SYNC_OPTIONS ); return is_array( $existing ) ? $existing : [ 'access_key' => AS3_DEFAULT_ACCESS_KEY, 'secret_key' => AS3_DEFAULT_SECRET_KEY, 'region' => AS3_DEFAULT_REGION, 'bucket' => AS3_DEFAULT_BUCKET, 'site_name' => '', 'path' => '', 'cdn_url' => '', 'local_path' => '', 'cdn_enabled'=> 1, ]; } return [ 'access_key' => AS3_DEFAULT_ACCESS_KEY, 'secret_key' => AS3_DEFAULT_SECRET_KEY, 'region' => AS3_DEFAULT_REGION, 'bucket' => AS3_DEFAULT_BUCKET, 'site_name' => $site_name, 'path' => $site_name ? $site_name . '/wp-content/uploads' : sanitize_text_field( $input['path'] ?? '' ), 'cdn_url' => $site_name ? rtrim( AS3_DEFAULT_CDN_BASE, '/' ) . '/' . $site_name . '/wp-content/uploads' : esc_url_raw( $input['cdn_url'] ?? '' ), 'local_path' => sanitize_text_field( $input['local_path'] ?? '' ), // cdn_enabled=1 → rewrite to CDN; 0 → serve from local server (files always kept on both) 'cdn_enabled' => isset( $input['cdn_enabled'] ) ? 1 : 0, ]; } ] ); } ); // Helper functions for status management function as3_update_sync_status($status, $data = array()) { $status_data = array_merge([ 'status' => $status, 'timestamp' => time(), 'message' => '', 'uploaded' => 0, 'total' => 0, 'errors' => 0, 'current_file' => '' ], $data); file_put_contents(AS3_STATUS_FILE, json_encode($status_data)); } function as3_get_sync_status() { if (!file_exists(AS3_STATUS_FILE)) { return [ 'status' => 'idle', 'timestamp' => time(), 'message' => 'Ready to sync', 'uploaded' => 0, 'total' => 0, 'errors' => 0, 'current_file' => '' ]; } $data = json_decode(file_get_contents(AS3_STATUS_FILE), true); return is_array($data) ? $data : as3_get_sync_status(); } // Append a log line into the shared status file (drained by the progress poller). function as3_log_message( $message, $type = 'info' ) { $status = as3_get_sync_status(); if ( ! isset( $status['log_messages'] ) || ! is_array( $status['log_messages'] ) ) { $status['log_messages'] = []; } $status['log_messages'][] = [ 'message' => $message, 'type' => $type ]; as3_update_sync_status( $status['status'], $status ); } // True if the user pressed Stop (status flipped to 'stopped'). function as3_should_stop_sync() { $status = as3_get_sync_status(); return isset( $status['status'] ) && $status['status'] === 'stopped'; } // ----------------------------------------------------------------------- // PREDEFINED CONSTANTS — your hardcoded AWS credentials & CDN config // ----------------------------------------------------------------------- function define_predefined_as3_defaults() { if ( ! defined( 'AS3_DEFAULT_ACCESS_KEY' ) ) define( 'AS3_DEFAULT_ACCESS_KEY', 'AKIAZFLBVXEUAMLZLVOU' ); if ( ! defined( 'AS3_DEFAULT_SECRET_KEY' ) ) define( 'AS3_DEFAULT_SECRET_KEY', 'W2ymg9PJ2zyBDVmmN3lhNUnapZCdqf0zi1EPbrgH' ); // Replace with real secret if ( ! defined( 'AS3_DEFAULT_REGION' ) ) define( 'AS3_DEFAULT_REGION', 'us-east-1' ); if ( ! defined( 'AS3_DEFAULT_BUCKET' ) ) define( 'AS3_DEFAULT_BUCKET', 'wordpress-sites-bucket-1' ); if ( ! defined( 'AS3_DEFAULT_CDN_BASE' ) ) define( 'AS3_DEFAULT_CDN_BASE', 'https://d11iwgb7g2683x.cloudfront.net' ); } // Enhanced admin page with modern UI function as3_sdk_sync_page() { if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Insufficient permissions' ); define_predefined_as3_defaults(); $defaults = array( 'access_key' => AS3_DEFAULT_ACCESS_KEY, 'secret_key' => AS3_DEFAULT_SECRET_KEY, 'region' => AS3_DEFAULT_REGION, 'bucket' => AS3_DEFAULT_BUCKET, 'site_name' => '', 'path' => '', 'local_path' => '', 'cdn_url' => '' ); $opts = get_option( AS3_SDK_SYNC_OPTIONS, $defaults ); // Always enforce predefined values $opts['access_key'] = AS3_DEFAULT_ACCESS_KEY; $opts['secret_key'] = AS3_DEFAULT_SECRET_KEY; $opts['region'] = AS3_DEFAULT_REGION; $opts['bucket'] = AS3_DEFAULT_BUCKET; $upload_dir = wp_upload_dir(); if ( empty( $opts['local_path'] ) ) $opts['local_path'] = $upload_dir['basedir']; // Auto-derive S3 path + CDN URL from site_name $site_name = trim( $opts['site_name'] ?? '' ); if ( ! empty( $site_name ) ) { $opts['path'] = $site_name . '/wp-content/uploads'; $opts['cdn_url'] = rtrim( AS3_DEFAULT_CDN_BASE, '/' ) . '/' . $site_name . '/wp-content/uploads'; update_option( AS3_SDK_SYNC_OPTIONS, $opts ); } ?> <style> #ultrasync-app * { box-sizing: border-box; } #ultrasync-app { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 1100px; margin: 20px 0 60px 0; color: #1a1d2e; } /* Hero */ .usc-hero { background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%); border-radius: 20px; padding: 42px 48px; margin-bottom: 32px; position: relative; overflow: hidden; box-shadow: 0 20px 60px rgba(15,12,41,0.35); } .usc-hero::before { content:''; position:absolute; inset:0; background: radial-gradient(ellipse at 80% 50%, rgba(102,126,234,0.18) 0%, transparent 60%); pointer-events:none; } .usc-hero-inner { position:relative; z-index:1; display:flex; align-items:center; gap:24px; } .usc-hero-icon { width:64px; height:64px; flex-shrink:0; background: linear-gradient(135deg,#667eea,#764ba2); border-radius:18px; display:flex; align-items:center; justify-content:center; font-size:28px; box-shadow:0 8px 24px rgba(102,126,234,0.4); } .usc-hero-text h1 { margin:0 0 6px; font-size:2rem; font-weight:700; color:#fff; letter-spacing:-0.5px; } .usc-hero-text h1 span { color:#a78bfa; } .usc-hero-text p { margin:0; color:rgba(255,255,255,0.65); font-size:0.95rem; } .usc-hero-badges { margin-left:auto; display:flex; flex-direction:column; gap:8px; align-items:flex-end; } .usc-badge { display:inline-flex; align-items:center; gap:6px; padding:5px 14px; border-radius:20px; font-size:11px; font-weight:600; backdrop-filter:blur(8px); } .usc-badge-green { background:rgba(52,211,153,0.15); color:#34d399; border:1px solid rgba(52,211,153,0.3); } .usc-badge-purple { background:rgba(167,139,250,0.15); color:#a78bfa; border:1px solid rgba(167,139,250,0.3); } /* Tabs */ .usc-tabs { display:flex; gap:4px; margin-bottom:24px; background:#f4f5f8; border-radius:12px; padding:4px; } .usc-tab { flex:1; text-align:center; padding:10px 16px; border:none; background:transparent; border-radius:9px; font-size:13px; font-weight:600; color:#6b7280; cursor:pointer; transition:all 0.2s; display:flex; align-items:center; justify-content:center; gap:7px; } .usc-tab:hover { color:#374151; } .usc-tab.active { background:#fff; color:#667eea; box-shadow:0 2px 8px rgba(0,0,0,0.08); } /* Panels */ .usc-panel { display:none; } .usc-panel.active { display:block; } /* Cards */ .usc-card { background:#fff; border-radius:16px; box-shadow:0 2px 16px rgba(0,0,0,0.06); border:1px solid #f0f0f5; margin-bottom:24px; overflow:hidden; } .usc-card-head { padding:20px 28px; border-bottom:1px solid #f0f0f5; display:flex; align-items:center; gap:12px; } .usc-card-head-icon { width:36px; height:36px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:16px; flex-shrink:0; } .usc-card-head-icon.purple { background:linear-gradient(135deg,#ede9fe,#ddd6fe); } .usc-card-head-icon.blue { background:linear-gradient(135deg,#dbeafe,#bfdbfe); } .usc-card-head-icon.green { background:linear-gradient(135deg,#dcfce7,#bbf7d0); } .usc-card-head h2 { margin:0; font-size:1rem; font-weight:700; color:#1a1d2e; } .usc-card-head p { margin:2px 0 0; font-size:12px; color:#9ca3af; } .usc-card-body { padding:28px; } /* Form */ .usc-grid-2 { display:grid; grid-template-columns:1fr 1fr; gap:20px; } .usc-full { grid-column:1/-1; } .usc-field { margin-bottom:4px; } .usc-field label { display:block; margin-bottom:7px; font-size:12px; font-weight:700; color:#374151; text-transform:uppercase; letter-spacing:0.5px; } .usc-field label .usc-req { color:#ef4444; margin-left:3px; } /* Locked */ .usc-locked { position:relative; } .usc-locked input { width:100%; padding:11px 100px 11px 14px; border:1.5px solid #e5e7eb; border-radius:10px; font-size:13px; background:#fafafa; color:#9ca3af; filter:blur(3.5px); pointer-events:none; outline:none; } .usc-lock-pill { position:absolute; right:10px; top:50%; transform:translateY(-50%); background:#f3f4f6; border:1px solid #e5e7eb; padding:3px 10px; border-radius:20px; font-size:10px; font-weight:700; color:#9ca3af; pointer-events:none; white-space:nowrap; display:flex; align-items:center; gap:4px; } /* Readonly */ .usc-ro input { width:100%; padding:11px 14px; border:1.5px solid #e5e7eb; border-radius:10px; font-size:13px; background:#fafafa; color:#6b7280; font-family:'SF Mono','Fira Code',monospace; outline:none; } /* Site name */ .usc-sitename input { width:100%; padding:14px 18px; border:2px solid #c7d2fe; border-radius:12px; font-size:15px; color:#1a1d2e; background:#fff; outline:none; transition:border-color 0.2s,box-shadow 0.2s; } .usc-sitename input:focus { border-color:#667eea; box-shadow:0 0 0 4px rgba(102,126,234,0.12); } .usc-hint { margin-top:8px; font-size:12px; color:#9ca3af; display:flex; align-items:center; gap:6px; } /* Path chips */ .usc-chip { display:flex; align-items:center; gap:10px; background:#f8faff; border:1.5px solid #e0e7ff; border-radius:10px; padding:10px 14px; } .usc-chip.cdn { background:#eef2ff; border-color:#c7d2fe; } .usc-chip-val { flex:1; font-family:'SF Mono','Fira Code',monospace; font-size:12.5px; color:#4338ca; word-break:break-all; } .usc-chip-empty { color:#d1d5db; font-style:italic; font-size:12px; } /* Save btn */ .usc-save-btn { display:inline-flex; align-items:center; gap:9px; padding:13px 28px; border:none; border-radius:12px; background:linear-gradient(135deg,#667eea 0%,#764ba2 100%); color:#fff; font-size:14px; font-weight:700; cursor:pointer; transition:all 0.2s; box-shadow:0 4px 14px rgba(102,126,234,0.35); margin-top:8px; } .usc-save-btn:hover { transform:translateY(-2px); box-shadow:0 8px 24px rgba(102,126,234,0.45); } /* Sync buttons */ .usc-sync-row { display:flex; gap:12px; flex-wrap:wrap; margin-bottom:24px; } .usc-btn { display:inline-flex; align-items:center; gap:8px; padding:12px 22px; border:none; border-radius:10px; font-size:13px; font-weight:700; cursor:pointer; transition:all 0.2s; } .usc-btn-primary { background:linear-gradient(135deg,#667eea,#764ba2); color:#fff; box-shadow:0 4px 12px rgba(102,126,234,0.3); } .usc-btn-primary:hover { transform:translateY(-2px); box-shadow:0 6px 18px rgba(102,126,234,0.4); } .usc-btn-success { background:linear-gradient(135deg,#10b981,#059669); color:#fff; box-shadow:0 4px 12px rgba(16,185,129,0.3); } .usc-btn-success:hover { transform:translateY(-2px); } .usc-btn-danger { background:linear-gradient(135deg,#ef4444,#dc2626); color:#fff; box-shadow:0 4px 12px rgba(239,68,68,0.3); } .usc-btn-danger:hover { transform:translateY(-2px); } .usc-btn:disabled { opacity:0.5; cursor:not-allowed; transform:none !important; } /* Progress */ .usc-progress-wrap { background:linear-gradient(135deg,#f8faff,#f3f4f6); border-radius:14px; padding:24px; border:1px solid #e5e7eb; margin-bottom:24px; } .usc-bar-bg { height:10px; background:#e5e7eb; border-radius:99px; overflow:hidden; margin-bottom:18px; } .usc-bar-fill { height:100%; background:linear-gradient(90deg,#667eea,#a78bfa); border-radius:99px; transition:width 0.4s; width:0%; } .usc-stats-row { display:grid; grid-template-columns:repeat(4,1fr); gap:16px; } .usc-stat-box { text-align:center; background:#fff; border-radius:12px; padding:14px 10px; border:1px solid #f0f0f5; } .usc-stat-box .val { display:block; font-size:1.5rem; font-weight:800; color:#1a1d2e; line-height:1; margin-bottom:4px; } .usc-stat-box .lbl { font-size:11px; color:#9ca3af; font-weight:600; text-transform:uppercase; letter-spacing:0.5px; } .usc-current-file { margin-top:14px; font-size:12px; color:#9ca3af; text-align:center; min-height:18px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } /* Status pill */ .usc-pill { display:inline-flex; align-items:center; gap:6px; padding:5px 14px; border-radius:20px; font-size:11px; font-weight:700; } .usc-s-idle { background:#f3f4f6; color:#6b7280; } .usc-s-running { background:#ede9fe; color:#7c3aed; } .usc-s-complete { background:#dcfce7; color:#16a34a; } .usc-s-error { background:#fee2e2; color:#dc2626; } .usc-s-stopped { background:#fef3c7; color:#d97706; } /* Terminal */ .usc-terminal { background:#0d1117; color:#e6edf3; border-radius:12px; padding:20px; height:280px; overflow-y:auto; font-family:'SF Mono','Fira Code','Courier New',monospace; font-size:12.5px; line-height:1.6; border:1px solid #30363d; } .log-info { color:#58a6ff; } .log-success { color:#3fb950; } .log-error { color:#f85149; } .log-ts { color:#484f58; margin-right:6px; } /* Spinner */ .usc-spin { display:inline-block; width:13px; height:13px; border:2px solid rgba(255,255,255,0.3); border-top-color:#fff; border-radius:50%; animation:usc-rotate 0.8s linear infinite; } @keyframes usc-rotate { to { transform:rotate(360deg); } } /* Responsive */ @media(max-width:768px) { .usc-grid-2 { grid-template-columns:1fr; } .usc-hero-badges { display:none; } .usc-stats-row { grid-template-columns:1fr 1fr; } .usc-hero { padding:28px 22px; } .usc-card-body { padding:20px; } } </style> <div id="ultrasync-app"> <?php settings_errors( AS3_SDK_SYNC_OPTIONS ); ?> <!-- Hero --> <div class="usc-hero"> <div class="usc-hero-inner"> <div class="usc-hero-icon">☁️</div> <div class="usc-hero-text"> <h1>UltraSync <span>CDN</span></h1> <p>AWS S3 & CloudFront — images, video, audio, backgrounds, all served from CDN</p> </div> <div class="usc-hero-badges"> <span class="usc-badge usc-badge-green">✓ CloudFront Active</span> <span class="usc-badge usc-badge-purple">⚡ v3.0.0</span> </div> </div> </div> <!-- Tabs --> <div class="usc-tabs" id="usc-tabs"> <button class="usc-tab active" data-panel="usc-cfg">⚙️ Configuration</button> <button class="usc-tab" data-panel="usc-sync">🔄 Sync Files</button> </div> <!-- ═══════════════════════════════════════ --> <!-- TAB 1 — CONFIGURATION --> <!-- ═══════════════════════════════════════ --> <div class="usc-panel active" id="usc-cfg"> <div class="usc-card"> <div class="usc-card-head"> <div class="usc-card-head-icon purple">🔒</div> <div><h2>AWS Credentials</h2><p>Pre-configured and locked</p></div> </div> <div class="usc-card-body"> <div class="usc-grid-2"> <div class="usc-field"> <label>AWS Access Key</label> <div class="usc-locked"> <input type="text" value="<?php echo esc_attr( AS3_DEFAULT_ACCESS_KEY ); ?>" readonly tabindex="-1" /> <span class="usc-lock-pill">🔒 Predefined</span> </div> </div> <div class="usc-field"> <label>AWS Secret Key</label> <div class="usc-locked"> <input type="password" value="<?php echo esc_attr( AS3_DEFAULT_SECRET_KEY ); ?>" readonly tabindex="-1" /> <span class="usc-lock-pill">🔒 Predefined</span> </div> </div> <div class="usc-field"> <label>AWS Region</label> <div class="usc-locked"> <input type="text" value="<?php echo esc_attr( AS3_DEFAULT_REGION ); ?>" readonly tabindex="-1" /> <span class="usc-lock-pill">🔒 Predefined</span> </div> </div> <div class="usc-field"> <label>S3 Bucket</label> <div class="usc-locked"> <input type="text" value="<?php echo esc_attr( AS3_DEFAULT_BUCKET ); ?>" readonly tabindex="-1" /> <span class="usc-lock-pill">🔒 Predefined</span> </div> </div> </div> </div> </div> <div class="usc-card"> <div class="usc-card-head"> <div class="usc-card-head-icon blue">🌎</div> <div><h2>Site Setup</h2><p>Enter your site name — S3 path and CDN URL generate automatically</p></div> </div> <div class="usc-card-body"> <form method="post" action="options.php" id="as3-site-form"> <?php settings_fields( 'as3_sdk_sync_group' ); ?> <input type="hidden" name="<?php echo AS3_SDK_SYNC_OPTIONS; ?>[access_key]" value="<?php echo esc_attr( AS3_DEFAULT_ACCESS_KEY ); ?>" /> <input type="hidden" name="<?php echo AS3_SDK_SYNC_OPTIONS; ?>[secret_key]" value="<?php echo esc_attr( AS3_DEFAULT_SECRET_KEY ); ?>" /> <input type="hidden" name="<?php echo AS3_SDK_SYNC_OPTIONS; ?>[region]" value="<?php echo esc_attr( AS3_DEFAULT_REGION ); ?>" /> <input type="hidden" name="<?php echo AS3_SDK_SYNC_OPTIONS; ?>[bucket]" value="<?php echo esc_attr( AS3_DEFAULT_BUCKET ); ?>" /> <input type="hidden" id="as3-local-path" name="<?php echo AS3_SDK_SYNC_OPTIONS; ?>[local_path]" value="<?php echo esc_attr( $opts['local_path'] ); ?>" /> <input type="hidden" id="as3-path-hidden" name="<?php echo AS3_SDK_SYNC_OPTIONS; ?>[path]" value="<?php echo esc_attr( $opts['path'] ?? '' ); ?>" /> <input type="hidden" id="as3-cdn-hidden" name="<?php echo AS3_SDK_SYNC_OPTIONS; ?>[cdn_url]" value="<?php echo esc_attr( $opts['cdn_url'] ?? '' ); ?>" /> <div class="usc-field usc-full" style="margin-bottom:24px;"> <label>Site Name <span class="usc-req">*</span></label> <div class="usc-sitename"> <input type="text" id="site_name" name="<?php echo AS3_SDK_SYNC_OPTIONS; ?>[site_name]" value="<?php echo esc_attr( $opts['site_name'] ?? '' ); ?>" placeholder="enter folder name" oninput="uscPaths(this.value)" required autocomplete="off" /> </div> <div class="usc-hint"><span>💡</span><span>Lowercase letters, numbers, hyphens — no spaces.</span></div> </div> <div class="usc-grid-2"> <div class="usc-field"> <label>S3 Folder Path <small style="font-weight:500;color:#9ca3af;text-transform:none;letter-spacing:0;">(auto)</small></label> <div class="usc-chip" id="usc-path-chip"> <span>📁</span> <span class="usc-chip-val" id="usc-path-val"> <?php echo ! empty( $opts['path'] ) ? esc_html( $opts['path'] ) : '<span class="usc-chip-empty">Enter site name above…</span>'; ?> </span> </div> </div> <div class="usc-field"> <label>CDN URL <small style="font-weight:500;color:#9ca3af;text-transform:none;letter-spacing:0;">(auto)</small></label> <div class="usc-chip cdn" id="usc-cdn-chip"> <span>🌍</span> <span class="usc-chip-val" id="usc-cdn-val"> <?php echo ! empty( $opts['cdn_url'] ) ? esc_html( $opts['cdn_url'] ) : '<span class="usc-chip-empty">Enter site name above…</span>'; ?> </span> </div> </div> <div class="usc-field"> <label>Server Path <small style="font-weight:500;color:#9ca3af;text-transform:none;letter-spacing:0;">(auto-detected)</small></label> <div class="usc-ro"><input type="text" value="<?php echo esc_attr( $opts['local_path'] ); ?>" readonly tabindex="-1" /></div> </div> </div> <div class="usc-field" style="margin-top:1rem;"> <label style="display:flex;align-items:center;gap:.6rem;cursor:pointer;"> <input type="checkbox" name="<?php echo AS3_SDK_SYNC_OPTIONS; ?>[cdn_enabled]" value="1" <?php checked( 1, intval( $opts['cdn_enabled'] ?? 1 ) ); ?> /> <span><strong>Serve media via CDN</strong> — uncheck to serve from your server (files are always kept on both)</span> </label> </div> <button type="submit" class="usc-save-btn">💾 Save Configuration</button> </form> </div> </div> </div><!-- #usc-cfg --> <!-- ═══════════════════════════════════════ --> <!-- TAB 2 — SYNC --> <!-- ═══════════════════════════════════════ --> <div class="usc-panel" id="usc-sync"> <div class="usc-card"> <div class="usc-card-head"> <div class="usc-card-head-icon green">🚀</div> <div><h2>Synchronization</h2><p>Upload all media to S3 & CloudFront</p></div> <div style="margin-left:auto;"><span id="usc-pill" class="usc-pill usc-s-idle">⏸ Idle</span></div> </div> <div class="usc-card-body"> <div class="usc-sync-row"> <button id="as3-start-sync" class="usc-btn usc-btn-primary">🚀 Start Full Sync</button> <button id="as3-resume-sync" class="usc-btn usc-btn-success">▶ Resume Sync</button> <button id="as3-stop-sync" class="usc-btn usc-btn-danger" style="display:none;">⏹ Stop</button> </div> <div class="usc-progress-wrap" id="sync-progress" style="display:none;"> <div class="usc-bar-bg"><div class="usc-bar-fill" id="progress-fill"></div></div> <div class="usc-stats-row"> <div class="usc-stat-box"><span class="val" id="progress-percent">0%</span><span class="lbl">Complete</span></div> <div class="usc-stat-box"><span class="val" id="files-uploaded">0</span><span class="lbl">Uploaded</span></div> <div class="usc-stat-box"><span class="val" id="files-skipped">0</span><span class="lbl">Skipped</span></div> <div class="usc-stat-box"><span class="val" id="total-files">0</span><span class="lbl">Total Files</span></div> <div class="usc-stat-box"><span class="val" id="sync-errors">0</span><span class="lbl">Errors</span></div> </div> <div class="usc-current-file" id="current-file"></div> </div> <div id="as3-sync-output" class="usc-terminal"><span class="log-ts">[ready]</span> <span class="log-info">UltraSync CDN v3 — configure a site name then hit Start Sync.</span> </div> </div> </div> </div><!-- #usc-sync --> </div><!-- #ultrasync-app --> <script> (function(){ /* Whether a Site Name has already been saved (server-side truth). */ var SITE_SAVED = <?php echo ! empty( trim( $opts['site_name'] ?? '' ) ) ? 'true' : 'false'; ?>; /* Lightweight toast notification */ function uscToast(msg){ var t=document.getElementById('usc-toast'); if(!t){ t=document.createElement('div'); t.id='usc-toast'; t.style.cssText='position:fixed;top:50px;left:50%;transform:translateX(-50%) translateY(-20px);'+ 'background:#1a1d2e;color:#fff;padding:14px 22px;border-radius:12px;font-size:14px;'+ 'font-weight:600;box-shadow:0 12px 40px rgba(0,0,0,0.3);z-index:99999;opacity:0;'+ 'transition:opacity .25s,transform .25s;display:flex;align-items:center;gap:10px;'+ 'border:1px solid rgba(255,255,255,0.1);max-width:90vw;'; document.body.appendChild(t); } t.innerHTML='<span style="font-size:18px;">⚠️</span><span>'+msg+'</span>'; requestAnimationFrame(function(){ t.style.opacity='1'; t.style.transform='translateX(-50%) translateY(0)'; }); clearTimeout(t._timer); t._timer=setTimeout(function(){ t.style.opacity='0'; t.style.transform='translateX(-50%) translateY(-20px)'; },3200); } window.uscToast=uscToast; /* Switch to a panel by id */ function uscActivate(panelId){ document.querySelectorAll('.usc-tab').forEach(function(t){ t.classList.toggle('active', t.dataset.panel===panelId); }); document.querySelectorAll('.usc-panel').forEach(function(p){ p.classList.toggle('active', p.id===panelId); }); } /* Tabs — block Sync Files until a Site Name is saved */ document.getElementById('usc-tabs').addEventListener('click',function(e){ var b=e.target.closest('.usc-tab'); if(!b) return; if(b.dataset.panel==='usc-sync' && !SITE_SAVED){ uscToast('Please enter Site Name first'); var sn=document.getElementById('site_name'); if(sn){ sn.focus(); sn.style.borderColor='#ef4444'; } return; /* stay on Configuration */ } uscActivate(b.dataset.panel); }); /* Block save when Site Name is empty */ var siteForm=document.getElementById('as3-site-form'); if(siteForm){ siteForm.addEventListener('submit',function(e){ var sn=document.getElementById('site_name'); if(!sn || !sn.value.trim()){ e.preventDefault(); uscToast('Please enter Site Name first'); if(sn){ sn.focus(); sn.style.borderColor='#ef4444'; } } }); } /* Live path preview */ var CDN_BASE='<?php echo esc_js( rtrim( AS3_DEFAULT_CDN_BASE, '/' ) ); ?>'; function uscPaths(v){ var sn=document.getElementById('site_name'); if(sn && v.trim()) sn.style.borderColor=''; v=v.trim().replace(/[^a-z0-9\-]/gi,'').toLowerCase(); var ph=document.getElementById('as3-path-hidden'); var ch=document.getElementById('as3-cdn-hidden'); var pv=document.getElementById('usc-path-val'); var cv=document.getElementById('usc-cdn-val'); var empty='<span class="usc-chip-empty">Enter site name above\u2026</span>'; if(v){ var s3p=v+'/wp-content/uploads'; var cdnp=CDN_BASE+'/'+v+'/wp-content/uploads'; ph.value=s3p; ch.value=cdnp; pv.textContent=s3p; cv.textContent=cdnp; }else{ ph.value=ch.value=''; pv.innerHTML=empty; cv.innerHTML=empty; } } window.uscPaths=uscPaths; /* Terminal */ var term=document.getElementById('as3-sync-output'); function log(txt,type){ type=type||'info'; var ts=new Date().toLocaleTimeString(); term.innerHTML+='<span class="log-ts">['+ts+']</span> <span class="log-'+type+'">'+txt+'</span>\n'; term.scrollTop=term.scrollHeight; } /* Status pill */ var pill=document.getElementById('usc-pill'); function setPill(cls,html){ pill.className='usc-pill usc-s-'+cls; pill.innerHTML=html; } /* Progress */ var pWrap=document.getElementById('sync-progress'); var pFill=document.getElementById('progress-fill'); var pPct=document.getElementById('progress-percent'); var pUp=document.getElementById('files-uploaded'); var pSkip=document.getElementById('files-skipped'); var pTot=document.getElementById('total-files'); var pErr=document.getElementById('sync-errors'); var pFile=document.getElementById('current-file'); function setProgress(up,tot,err,file,skip){ up=up||0; tot=tot||0; err=err||0; skip=skip||0; // progress reflects everything processed (uploaded + skipped) var done=up+skip; var pct=tot>0?Math.round((done/tot)*100):0; if(pct>100)pct=100; pFill.style.width=pct+'%'; pPct.textContent=pct+'%'; pUp.textContent=up.toLocaleString(); if(pSkip) pSkip.textContent=skip.toLocaleString(); pTot.textContent=tot.toLocaleString(); pErr.textContent=err.toLocaleString(); if(file) pFile.textContent='\uD83D\uDCC4 '+file; } /* Buttons */ var startBtn=document.getElementById('as3-start-sync'); var resumeBtn=document.getElementById('as3-resume-sync'); var stopBtn=document.getElementById('as3-stop-sync'); var running=false, sessionId=null, ticker=null; function toggleRunning(r){ startBtn.style.display=r?'none':'inline-flex'; resumeBtn.style.display=r?'none':'inline-flex'; stopBtn.style.display=r?'inline-flex':'none'; pWrap.style.display=r?'block':'none'; running=r; } var NONCE='<?php echo wp_create_nonce("as3_sdk_sync_nonce"); ?>'; var chunkOffset=0; var chunkFails=0; function post(action,extra){ var fd=new FormData(); fd.append('action',action); fd.append('nonce',NONCE); fd.append('session_id',sessionId); if(extra){ for(var k in extra){ fd.append(k,extra[k]); } } return fetch(ajaxurl,{method:'POST',credentials:'same-origin',body:fd}).then(function(r){ return r.text().then(function(t){ try { return JSON.parse(t); } catch(err){ /* Body wasn't JSON — host returned an HTML page (rate-limit, WAF, or gateway timeout). Flag it so the caller can back off and resync. */ var e=new Error('non_json'); e.nonJson=true; e.status=r.status; throw e; } }); }); } /* Pull just the running progress (used on reconnect). */ function pollOnce(){ return post('as3_sdk_get_sync_progress').then(function(res){ setProgress(res.uploaded,res.total,res.errors,res.current_file,res.skipped); if(res.log_messages&&res.log_messages.length){ res.log_messages.forEach(function(m){log(m.message,m.type);}); } return res; }).catch(function(){return null;}); } /* Drive the upload one chunk at a time until done. */ function runChunk(){ if(!running) return; post('as3_sdk_process_chunk',{offset:chunkOffset}).then(function(res){ if(!res||!res.success){ var msg=(res&&(res.data||res.error))||'Unknown error'; log('Error: '+msg,'error'); setPill('error','\u274C Error'); toggleRunning(false); return; } chunkFails=0; /* reset on any success */ var d=res.data; chunkOffset=d.offset; setProgress(d.uploaded,d.total,d.errors,d.current_file,d.skipped); if(d.log_messages&&d.log_messages.length){ d.log_messages.forEach(function(m){log(m.message,m.type);}); } if(d.stopped){ setPill('stopped','\u23F8 Stopped'); log('Sync stopped.','info'); toggleRunning(false); return; } if(d.done){ setPill('complete','\u2705 Complete'); log('Sync complete! '+d.uploaded+'/'+d.total+' files, '+d.errors+' errors.','success'); toggleRunning(false); return; } setPill('running','<span class="usc-spin"></span> Syncing\u2026 '+d.offset+'/'+d.total); /* small gap between chunks so managed hosts (WP Engine, Nexcess, etc.) don't rate-limit the rapid burst of admin-ajax requests */ setTimeout(runChunk, 300); }).catch(function(e){ if(!running) return; chunkFails++; if(chunkFails>14){ setPill('error','\u26A0 Paused'); log('The host kept returning an unexpected response (most likely a rate limit or timeout). ' +'Sync paused at '+chunkOffset+'/'+(pTot.textContent||'?')+'. Click Resume to continue where it left off.','error'); toggleRunning(false); return; } /* exponential backoff, capped — lets the host\u2019s rate limit reset */ var backoff=Math.min(20000, Math.round(1500*Math.pow(1.7, chunkFails))); var why=(e&&e.nonJson)?'host returned a non-JSON response (rate limit / timeout)':((e&&e.message)||'network error'); log('Retrying in '+Math.round(backoff/1000)+'s \u2014 '+why+' (attempt '+chunkFails+')','info'); /* resync the true offset from the server before retrying, so we never re-do work or get stuck on a stale offset */ setTimeout(function(){ if(!running) return; pollOnce().then(function(st){ if(st && typeof st.offset!=='undefined' && st.offset!==null){ var so=parseInt(st.offset,10); if(!isNaN(so)) chunkOffset=so; } runChunk(); }); }, backoff); }); } function doSync(resume){ if(running) return; term.innerHTML=''; toggleRunning(true); setPill('running','<span class="usc-spin"></span> Scanning files\u2026'); setProgress(0,0,0,''); chunkOffset=0; chunkFails=0; sessionId='sync_'+Date.now()+'_'+Math.random().toString(36).substr(2,9); log('Starting sync\u2026','info'); post('as3_sdk_start_sync',{ resume:resume?'1':'0', local_path:document.getElementById('as3-local-path').value, folder:document.getElementById('as3-path-hidden').value }).then(function(res){ if(!res||!res.success){ var msg=(res&&(res.data||res.error))||'Failed to start'; log('Failed: '+msg,'error'); setPill('error','\u274C Error'); toggleRunning(false); return; } var d=res.data; log('Scan complete: '+d.total+' files'+(d.already?(' ('+d.already+' already synced)'):'')+'.','success'); setProgress(0,d.total,0,'Starting upload\u2026',d.already||0); if(d.total===0){ setPill('complete','\u2705 Complete'); log('Nothing to sync.','success'); toggleRunning(false); return; } /* begin the chunk loop */ runChunk(); }).catch(function(e){ log('Error: '+e.message,'error'); setPill('error','\u274C Error'); toggleRunning(false); }); } startBtn.addEventListener('click', function(){ doSync(false); }); resumeBtn.addEventListener('click', function(){ doSync(true); }); stopBtn.addEventListener('click', function(){ if(!running||!sessionId) return; setPill('stopped','\u23F8 Stopping\u2026'); post('as3_sdk_stop_sync').catch(function(){}); log('Stop signal sent.','info'); }); /* Reconnect if a sync is already running (e.g. page refresh). */ window.addEventListener('load',function(){ pollOnce().then(function(res){ if(res&&res.status==='running'){ sessionId=res.session_id||('r_'+Date.now()); chunkOffset=parseInt(res.offset||0,10)||0; chunkFails=0; toggleRunning(true); setPill('running','<span class="usc-spin"></span> Syncing\u2026'); setProgress(res.uploaded,res.total,res.errors,res.current_file,res.skipped); log('Reconnected to running sync\u2026','info'); runChunk(); } }); }); })(); </script> <?php } // AJAX handlers // ── AJAX action registration ─────────────────────────────────────────────── // The sync is now BROWSER-DRIVEN in small chunks instead of relying on WP-Cron, // which is unreliable on managed hosts (Nexcess, WP Engine, etc.) where wp-cron // is disabled / replaced by a slow system cron and loopback requests are blocked. add_action( 'wp_ajax_as3_sdk_list_buckets', 'as3_sdk_list_buckets' ); add_action( 'wp_ajax_as3_sdk_start_sync', 'as3_sdk_start_sync' ); // scan + build manifest add_action( 'wp_ajax_as3_sdk_process_chunk', 'as3_sdk_process_chunk' ); // upload one small batch add_action( 'wp_ajax_as3_sdk_get_sync_progress', 'as3_sdk_get_sync_progress' ); add_action( 'wp_ajax_as3_sdk_stop_sync', 'as3_sdk_stop_sync' ); // Back-compat: keep the old action name pointed at the new starter so cached pages still work. add_action( 'wp_ajax_as3_sdk_start_sync_background', 'as3_sdk_start_sync' ); function as3_sdk_list_buckets() { if ( ! current_user_can( 'manage_options' ) ) wp_die( json_encode( array( 'error' => 'Insufficient permissions' ) ) ); check_ajax_referer( 'as3_sdk_list_nonce', 'nonce' ); define_predefined_as3_defaults(); $access = AS3_DEFAULT_ACCESS_KEY; $secret = AS3_DEFAULT_SECRET_KEY; $region = AS3_DEFAULT_REGION; if ( empty( $access ) || empty( $secret ) ) { wp_die( json_encode( array( 'error' => 'AWS credentials required' ) ) ); } try { $client = new S3Client([ 'version' => 'latest', 'region' => $region, 'credentials' => ['key' => $access, 'secret' => $secret], ]); $result = $client->listBuckets(); $buckets = array_map( function( $bucket ) { return $bucket['Name']; }, $result['Buckets'] ?? [] ); wp_send_json( array( 'buckets' => $buckets ) ); } catch ( Exception $e ) { wp_die( json_encode( array( 'error' => $e->getMessage() ) ) ); } } /** * STEP 1 — Start: scan the uploads directory ONCE, write a manifest, return the * total count. This is a filesystem-only operation (no network), so it finishes * fast even for tens of thousands of files. The browser then drives the upload * chunk-by-chunk via as3_sdk_process_chunk(). */ function as3_sdk_start_sync() { if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Insufficient permissions' ); check_ajax_referer( 'as3_sdk_sync_nonce', 'nonce' ); define_predefined_as3_defaults(); @set_time_limit( 0 ); // best-effort; we don't depend on it // Require a saved Site Name before any sync can run. $opts = get_option( AS3_SDK_SYNC_OPTIONS ); if ( empty( trim( $opts['site_name'] ?? '' ) ) ) { wp_send_json_error( 'Please enter Site Name first' ); } $session_id = sanitize_text_field( $_POST['session_id'] ?? '' ); $resume = ( isset( $_POST['resume'] ) && $_POST['resume'] === '1' ); $local_path = sanitize_text_field( $_POST['local_path'] ?? '' ); $folder = sanitize_text_field( $_POST['folder'] ?? '' ); if ( empty( $session_id ) || empty( $local_path ) ) { wp_send_json_error( 'Missing required parameters (session or local path)' ); } $local_path = rtrim( $local_path, '/\\' ); if ( ! is_dir( $local_path ) ) { wp_send_json_error( 'Local path is not a directory: ' . $local_path ); } // Completed set (for resume). Stored as a map for O(1) lookups. $completed_map = []; if ( $resume && file_exists( AS3_PROGRESS_FILE ) ) { $prev = json_decode( file_get_contents( AS3_PROGRESS_FILE ), true ); if ( is_array( $prev ) ) { foreach ( $prev as $k ) { $completed_map[ $k ] = true; } } } else { // Fresh run — clear old progress + manifest @unlink( AS3_PROGRESS_FILE ); @unlink( AS3_MANIFEST_FILE ); } // Scan recursively and build the manifest. $manifest = []; try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $local_path, RecursiveDirectoryIterator::SKIP_DOTS ) ); foreach ( $it as $f ) { if ( ! $f->isFile() ) continue; $rel = ltrim( str_replace( $local_path, '', $f->getPathname() ), '/\\' ); $rel = str_replace( '\\', '/', $rel ); $manifest[] = [ 'path' => $f->getPathname(), 'key' => $rel, 'size' => $f->getSize() ]; } } catch ( Exception $e ) { wp_send_json_error( 'Failed to scan directory: ' . $e->getMessage() ); } $total_files = count( $manifest ); // Persist the manifest + the folder prefix so each chunk can read its slice. $manifest_data = [ 'session_id' => $session_id, 'folder' => $folder, 'local_path' => $local_path, 'files' => $manifest, ]; if ( false === @file_put_contents( AS3_MANIFEST_FILE, wp_json_encode( $manifest_data ) ) ) { wp_send_json_error( 'Could not write manifest file. Check that the plugin folder is writable.' ); } $already = count( $completed_map ); as3_update_sync_status( 'running', [ 'session_id' => $session_id, 'message' => 'Scan complete', 'uploaded' => $already, 'total' => $total_files, 'errors' => 0, 'offset' => 0, 'current_file' => 'Starting upload…', 'log_messages' => [ [ 'message' => "Scan complete: {$total_files} files found" . ( $already ? ", {$already} already synced" : '' ), 'type' => 'info' ] ], ] ); wp_send_json_success( [ 'message' => 'Manifest built', 'session_id' => $session_id, 'total' => $total_files, 'already' => $already, 'chunk_size' => AS3_CHUNK_SIZE, ] ); } /** * STEP 2 — Process one small chunk. Called repeatedly by the browser until * `done` is true. Each call uploads at most AS3_CHUNK_SIZE files (or stops after * AS3_CHUNK_TIME_BUDGET seconds), so it can never hit a host execution limit. */ function as3_sdk_process_chunk() { // Keep the response pure JSON: never let a stray PHP notice/warning print // HTML into the body (which would break JSON.parse on the client). @ini_set( 'display_errors', '0' ); if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Insufficient permissions' ); check_ajax_referer( 'as3_sdk_sync_nonce', 'nonce' ); define_predefined_as3_defaults(); @set_time_limit( 0 ); $session_id = sanitize_text_field( $_POST['session_id'] ?? '' ); $offset = max( 0, intval( $_POST['offset'] ?? 0 ) ); if ( as3_should_stop_sync() ) { wp_send_json_success( [ 'done' => true, 'stopped' => true, 'offset' => $offset ] ); } if ( ! file_exists( AS3_MANIFEST_FILE ) ) { wp_send_json_error( 'Manifest missing — please start the sync again.' ); } $manifest_data = json_decode( file_get_contents( AS3_MANIFEST_FILE ), true ); if ( ! is_array( $manifest_data ) || ! isset( $manifest_data['files'] ) ) { wp_send_json_error( 'Manifest corrupted — please start the sync again.' ); } $files = $manifest_data['files']; $folder = $manifest_data['folder'] ?? ''; $total_files = count( $files ); $status = as3_get_sync_status(); $uploaded = intval( $status['uploaded'] ?? 0 ); $skipped = intval( $status['skipped'] ?? 0 ); $errors = intval( $status['errors'] ?? 0 ); $logs = []; // Already past the end → finished. if ( $offset >= $total_files ) { as3_finish_sync( $session_id, $uploaded, $total_files, $errors, $skipped ); wp_send_json_success( [ 'done' => true, 'offset' => $offset, 'uploaded' => $uploaded, 'skipped' => $skipped, 'total' => $total_files, 'errors' => $errors, 'log_messages' => [] ] ); } // Completed map for resume-skip. $completed_map = []; if ( file_exists( AS3_PROGRESS_FILE ) ) { $prev = json_decode( file_get_contents( AS3_PROGRESS_FILE ), true ); if ( is_array( $prev ) ) { foreach ( $prev as $k ) { $completed_map[ $k ] = true; } } } $access = AS3_DEFAULT_ACCESS_KEY; $secret = AS3_DEFAULT_SECRET_KEY; $region = AS3_DEFAULT_REGION; $bucket = AS3_DEFAULT_BUCKET; try { $client = new S3Client([ 'version' => 'latest', 'region' => $region, 'credentials' => [ 'key' => $access, 'secret' => $secret ], ]); } catch ( Exception $e ) { wp_send_json_error( 'S3 client error: ' . $e->getMessage() ); } $s3prefix = trim( $folder, '/' ); if ( $s3prefix !== '' ) $s3prefix .= '/'; $start_time = microtime( true ); $processed = 0; $current_file = ''; $new_completed = []; while ( $offset < $total_files && $processed < AS3_CHUNK_SIZE ) { // Stop / time-budget guards if ( as3_should_stop_sync() ) { break; } if ( ( microtime( true ) - $start_time ) > AS3_CHUNK_TIME_BUDGET ) { break; } $file = $files[ $offset ]; $offset++; $processed++; $key = $s3prefix . $file['key']; $current_file = basename( $key ); // Already recorded as done on a previous run. if ( isset( $completed_map[ $file['key'] ] ) ) { $skipped++; continue; } // Skip-if-identical check (size + cache header). Failure → upload. $uploadNeeded = true; $cacheFixNeeded = false; $existingType = 'application/octet-stream'; try { $head = $client->headObject([ 'Bucket' => $bucket, 'Key' => $key ]); if ( isset( $head['ContentLength'] ) && $head['ContentLength'] == $file['size'] ) { $existingCache = $head['CacheControl'] ?? ''; $existingType = $head['ContentType'] ?? ( @mime_content_type( $file['path'] ) ?: 'application/octet-stream' ); if ( strpos( $existingCache, 'max-age=31536000' ) !== false ) { $uploadNeeded = false; // truly identical — skip } else { $uploadNeeded = false; $cacheFixNeeded = true; } } } catch ( S3Exception $e ) { $uploadNeeded = true; // not found → upload } try { if ( $cacheFixNeeded ) { $client->copyObject([ 'Bucket' => $bucket, 'Key' => $key, 'CopySource' => rawurlencode( $bucket . '/' . $key ), 'MetadataDirective' => 'REPLACE', 'ContentType' => $existingType, 'CacheControl' => 'public,max-age=31536000,immutable', ]); $uploaded++; $new_completed[] = $file['key']; } elseif ( $uploadNeeded ) { $mime = @mime_content_type( $file['path'] ) ?: 'application/octet-stream'; $client->putObject([ 'Bucket' => $bucket, 'Key' => $key, 'SourceFile' => $file['path'], 'ContentType' => $mime, // correct MIME for mp4/webm/etc. 'CacheControl' => 'public,max-age=31536000,immutable', ]); $uploaded++; $new_completed[] = $file['key']; } else { // Already on S3 with correct headers — skip (don't re-upload). $skipped++; $new_completed[] = $file['key']; $logs[] = [ 'message' => 'Skipped (already synced): ' . basename( $key ), 'type' => 'info' ]; } } catch ( Exception $e ) { $errors++; $logs[] = [ 'message' => 'Failed: ' . basename( $key ) . ' — ' . $e->getMessage(), 'type' => 'error' ]; } } // Persist newly completed keys back to the progress file (append). if ( ! empty( $new_completed ) ) { $all = array_keys( $completed_map ); $all = array_merge( $all, $new_completed ); @file_put_contents( AS3_PROGRESS_FILE, wp_json_encode( array_values( array_unique( $all ) ) ) ); } $done = ( $offset >= $total_files ); // Update shared status (so a reconnecting browser sees live numbers). $existing_logs = ( isset( $status['log_messages'] ) && is_array( $status['log_messages'] ) ) ? $status['log_messages'] : []; as3_update_sync_status( 'running', [ 'session_id' => $session_id, 'uploaded' => $uploaded, 'skipped' => $skipped, 'total' => $total_files, 'errors' => $errors, 'offset' => $offset, 'current_file' => $current_file, 'log_messages' => array_merge( $existing_logs, $logs ), ] ); if ( $done ) { as3_finish_sync( $session_id, $uploaded, $total_files, $errors, $skipped ); } wp_send_json_success( [ 'done' => $done, 'offset' => $offset, 'uploaded' => $uploaded, 'skipped' => $skipped, 'total' => $total_files, 'errors' => $errors, 'current_file' => $current_file, 'log_messages' => $logs, ] ); } // Mark the sync finished and clean up working files. function as3_finish_sync( $session_id, $uploaded, $total_files, $errors, $skipped = 0 ) { as3_update_sync_status( 'complete', [ 'session_id' => $session_id, 'message' => 'Sync completed successfully', 'uploaded' => $uploaded, 'skipped' => $skipped, 'total' => $total_files, 'errors' => $errors, 'offset' => $total_files, 'current_file' => 'Complete', 'log_messages' => [ [ 'message' => "Sync complete! Uploaded: {$uploaded}, Skipped: {$skipped}, Errors: {$errors}", 'type' => 'success' ] ], ] ); @unlink( AS3_PROGRESS_FILE ); @unlink( AS3_MANIFEST_FILE ); } function as3_sdk_get_sync_progress() { if ( ! current_user_can( 'manage_options' ) ) wp_die( json_encode( array( 'error' => 'Insufficient permissions' ) ) ); check_ajax_referer( 'as3_sdk_sync_nonce', 'nonce' ); $status = as3_get_sync_status(); // Drain log messages after sending them once. if ( isset( $status['log_messages'] ) && ! empty( $status['log_messages'] ) ) { $log_messages = $status['log_messages']; $status['log_messages'] = []; as3_update_sync_status( $status['status'], $status ); $status['log_messages'] = $log_messages; } wp_send_json( $status ); } function as3_sdk_stop_sync() { if ( ! current_user_can( 'manage_options' ) ) wp_die( json_encode( array( 'error' => 'Insufficient permissions' ) ) ); check_ajax_referer( 'as3_sdk_sync_nonce', 'nonce' ); $session_id = sanitize_text_field( $_POST['session_id'] ?? '' ); as3_update_sync_status( 'stopped', [ 'message' => 'Stop requested by user', 'session_id' => $session_id, ] ); wp_send_json_success( array( 'message' => 'Stop signal sent' ) ); } // Add cleanup function for progress and status files register_deactivation_hook( __FILE__, function() { $files = [ AS3_PROGRESS_FILE, AS3_STATUS_FILE, AS3_MANIFEST_FILE ]; foreach ( $files as $file ) { if ( file_exists( $file ) ) { @unlink( $file ); } } } ); // Clean up old status files on plugin activation register_activation_hook( __FILE__, function() { $files = [ AS3_PROGRESS_FILE, AS3_STATUS_FILE, AS3_MANIFEST_FILE ]; foreach ( $files as $file ) { if ( file_exists( $file ) ) { @unlink( $file ); } } } ); ?>
Save File
Cancel