'application/pdf', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'svg' => 'image/svg+xml', ]; /** * MIME types accepted for each extension. Adobe formats are detected * inconsistently across platforms, so they tolerate more than one type. */ private const ACCEPTED = [ 'pdf' => [ 'application/pdf' ], 'ai' => [ 'application/postscript', 'application/illustrator', 'application/pdf', 'application/octet-stream' ], 'eps' => [ 'application/postscript', 'application/octet-stream' ], 'png' => [ 'image/png' ], 'jpg' => [ 'image/jpeg' ], 'jpeg' => [ 'image/jpeg' ], 'tif' => [ 'image/tiff' ], 'tiff' => [ 'image/tiff' ], 'svg' => [ 'image/svg+xml' ], ]; /** * Extensions that must never appear before the final segment. */ private const DANGEROUS_EXTS = [ 'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'phar', 'pht', 'cgi', 'pl', 'py', 'rb', 'jsp', 'jspx', 'asp', 'aspx', 'ashx', 'sh', 'bash', 'exe', 'com', 'bat', 'cmd', 'js', 'mjs', 'html', 'htm', 'shtml', 'htaccess', ]; /** * Files the private directory relies on; never purged. */ private const PROTECTED_FILES = [ '.htaccess', 'index.php', 'web.config' ]; /** * Minimum age before an unreferenced file may be purged. * * Longer than the 72-hour signed upload token lifetime by a full day of * cron jitter, so a live descriptor can never point at a purged file. */ private const PURGE_MIN_HOURS = 96; /** * Avoid logging a missing finfo extension on every validation. */ private static bool $logged_finfo_fallback = false; /** * Validate a single $_FILES entry against global and per-product limits. * * The global setting is always a hard ceiling: a product config can only * narrow the size and extension allow-list. * * @param array $file $_FILES entry. * @param int $product_id Product id; 0 uses global settings only. * @return bool|\WP_Error True when the file may be stored. */ public static function validate( array $file, int $product_id = 0 ): bool|\WP_Error { $limits = self::limits( $product_id ); $max_bytes = $limits['max_bytes']; $extensions = $limits['extensions']; foreach ( [ 'tmp_name', 'name', 'size', 'error' ] as $key ) { if ( ! array_key_exists( $key, $file ) ) { return self::failed_error(); } } $upload_error = (int) $file['error']; if ( UPLOAD_ERR_OK !== $upload_error ) { return self::upload_error( $upload_error ); } $size = (int) $file['size']; if ( $size <= 0 ) { return self::error( 'proofkit_upload_empty', __( 'The file is empty. Please choose another file.', 'proofkit' ) ); } if ( $size > $max_bytes ) { return self::size_error( $max_bytes ); } $raw_name = (string) $file['name']; if ( '' === $raw_name || str_contains( $raw_name, "\0" ) || str_contains( $raw_name, '/' ) || str_contains( $raw_name, '\\' ) ) { return self::error( 'proofkit_upload_type', __( 'The file name contains invalid characters.', 'proofkit' ) ); } $name = self::sanitize_name( $raw_name ); if ( self::has_dangerous_segment( $name ) ) { return self::error( 'proofkit_upload_type', __( 'The file name uses a disallowed double extension.', 'proofkit' ) ); } $ext = strtolower( (string) pathinfo( $name, PATHINFO_EXTENSION ) ); if ( '' === $ext || ! in_array( $ext, $extensions, true ) ) { return self::error( 'proofkit_upload_type', sprintf( /* translators: %s: comma-separated list of file extensions. */ __( 'This file type is not allowed. Allowed types: %s.', 'proofkit' ), implode( ', ', array_map( 'strtoupper', $extensions ) ) ) ); } if ( 'svg' === $ext && 1 !== (int) Settings::get( 'enable_svg', 0 ) ) { return self::error( 'proofkit_upload_type', __( 'SVG uploads are not enabled.', 'proofkit' ) ); } $tmp = (string) $file['tmp_name']; if ( '' === $tmp || ! is_file( $tmp ) ) { return self::failed_error(); } $detected = self::detected_mime( $tmp ); $checked = wp_check_filetype_and_ext( $tmp, $name, self::MIMES ); $type = isset( $checked['type'] ) ? strtolower( (string) $checked['type'] ) : ''; $accepted = self::ACCEPTED[ $ext ] ?? []; $mime_ok = ( '' !== $type && in_array( $type, $accepted, true ) ); if ( ! $mime_ok && in_array( $ext, [ 'ai', 'eps' ], true ) ) { // Adobe formats frequently fail wp_check_filetype_and_ext; the // magic-byte check below still decides whether the bytes are real. $adobe_types = ( 'ai' === $ext ) ? [ 'application/postscript', 'application/octet-stream', 'application/pdf' ] : [ 'application/postscript', 'application/octet-stream' ]; $mime_ok = '' !== $detected && in_array( $detected, $adobe_types, true ); } if ( ! $mime_ok || ! self::magic_matches( $tmp, $ext ) ) { return self::error( 'proofkit_upload_type', __( 'The file contents do not match the file extension.', 'proofkit' ) ); } if ( 'svg' === $ext && ! self::looks_like_svg_safe( $tmp ) ) { return self::error( 'proofkit_upload_type', __( 'The SVG contains unsafe elements or external references.', 'proofkit' ) ); } return true; } /** * Move a validated upload into private storage. * * @param array $file $_FILES entry. * @param int $product_id Product id; 0 uses global settings only. * @return array|\WP_Error Descriptor: path, name, mime, size, sha256. */ public static function store( array $file, int $product_id = 0 ): array|\WP_Error { $valid = self::validate( $file, $product_id ); if ( is_wp_error( $valid ) ) { return $valid; } $dir = self::ensure_dir(); if ( '' === $dir ) { return self::failed_error(); } $tmp_dir = $dir . 'tmp/'; if ( ! wp_mkdir_p( $tmp_dir ) ) { return self::failed_error(); } try { $tmp = $tmp_dir . 'pk-' . bin2hex( random_bytes( 16 ) ) . '.part'; } catch ( \Throwable ) { return self::failed_error(); } $source = (string) $file['tmp_name']; $is_test = defined( 'PROOFKIT_UNIT_TESTS' ) && PROOFKIT_UNIT_TESTS; if ( $is_test ) { if ( ! @copy( $source, $tmp ) ) { return self::failed_error(); } } else { // Never relax this in production: only a real HTTP upload is moved, // and it goes through wp_handle_upload() rather than a raw rename. if ( ! is_uploaded_file( $source ) ) { return self::failed_error(); } if ( ! function_exists( 'wp_handle_upload' ) ) { require_once ABSPATH . 'wp-admin/includes/file.php'; } $tmp_name = basename( $tmp ); $tmp_target = rtrim( $tmp_dir, '/' ); $upload_dir = static function ( array $dirs ) use ( $tmp_target ): array { $dirs['path'] = $tmp_target; $dirs['basedir'] = $tmp_target; $dirs['subdir'] = ''; $dirs['url'] = ''; $dirs['baseurl'] = ''; $dirs['error'] = false; return $dirs; }; add_filter( 'upload_dir', $upload_dir ); $moved = wp_handle_upload( $file, [ 'test_form' => false, 'test_type' => false, 'unique_filename_callback' => static function () use ( $tmp_name ) { return $tmp_name; }, ] ); remove_filter( 'upload_dir', $upload_dir ); // wp_upload_dir() caches its result per request; drop the filtered // private path so the rest of the request sees the real uploads dir. wp_upload_dir( null, false, true ); if ( ! is_array( $moved ) || ! empty( $moved['error'] ) || empty( $moved['file'] ) ) { return self::failed_error(); } $tmp = (string) $moved['file']; } if ( ! is_file( $tmp ) ) { return self::failed_error(); } $hash = hash_file( 'sha256', $tmp ); $size = filesize( $tmp ); if ( false === $hash || false === $size || $size <= 0 ) { wp_delete_file( $tmp ); return self::failed_error(); } $limits = self::limits( $product_id ); if ( $size > $limits['max_bytes'] ) { wp_delete_file( $tmp ); return self::size_error( $limits['max_bytes'] ); } $name = self::sanitize_name( (string) $file['name'] ); $ext = strtolower( (string) pathinfo( $name, PATHINFO_EXTENSION ) ); if ( '' === $ext ) { wp_delete_file( $tmp ); return self::error( 'proofkit_upload_type', __( 'The file name contains invalid characters.', 'proofkit' ) ); } $relative = substr( $hash, 0, 2 ) . '/' . substr( $hash, 2, 2 ) . '/' . $hash . '.' . $ext; $target = $dir . $relative; $mime = self::mime_for( $ext, $tmp ); $descriptor = [ 'path' => $relative, 'name' => $name, 'mime' => $mime, 'size' => (int) $size, 'sha256' => $hash, ]; if ( file_exists( $target ) || is_link( $target ) ) { $existing = is_link( $target ) ? false : hash_file( 'sha256', $target ); wp_delete_file( $tmp ); if ( false !== $existing && hash_equals( $hash, $existing ) ) { return $descriptor; } return self::failed_error(); } if ( ! wp_mkdir_p( dirname( $target ) ) ) { wp_delete_file( $tmp ); return self::failed_error(); } if ( ! self::move_file( $tmp, $target ) ) { // Another request may have promoted the same content first. $existing = is_file( $target ) && ! is_link( $target ) ? hash_file( 'sha256', $target ) : false; wp_delete_file( $tmp ); if ( false !== $existing && hash_equals( $hash, $existing ) ) { return $descriptor; } return self::failed_error(); } return $descriptor; } /** * Resolve a stored relative path inside the private directory. * * @param string $relative Relative path from the proofs table. * @return string Absolute path, or '' when the path is unsafe or missing. */ public static function path( string $relative ): string { if ( '' === $relative || strlen( $relative ) > 255 ) { return ''; } if ( str_contains( $relative, "\0" ) || str_contains( $relative, '\\' ) ) { return ''; } if ( str_starts_with( $relative, '/' ) || preg_match( '#^[A-Za-z]:#', $relative ) ) { return ''; } foreach ( explode( '/', $relative ) as $segment ) { if ( '' === $segment || '.' === $segment || '..' === $segment ) { return ''; } } $base = Install::private_dir(); if ( '' === $base ) { return ''; } $real_base = realpath( $base ); if ( false === $real_base ) { return ''; } $candidate = $base . $relative; if ( is_link( $candidate ) ) { return ''; } $parent = realpath( dirname( $candidate ) ); if ( false === $parent ) { return ''; } $prefix = rtrim( $real_base, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR; if ( ! str_starts_with( $parent . DIRECTORY_SEPARATOR, $prefix ) ) { return ''; } $full = $parent . DIRECTORY_SEPARATOR . basename( $candidate ); if ( is_link( $full ) ) { return ''; } return $full; } /** * Whether a stored relative path exists. */ public static function exists( string $relative ): bool { $path = self::path( $relative ); return '' !== $path && is_file( $path ); } /** * Verify a stored file against its recorded SHA-256. */ public static function verify( string $relative, string $expected_sha256 ): bool { if ( ! preg_match( '/^[a-f0-9]{64}$/i', $expected_sha256 ) ) { return false; } $path = self::path( $relative ); if ( '' === $path || ! is_file( $path ) ) { return false; } $actual = hash_file( 'sha256', $path ); return false !== $actual && hash_equals( strtolower( $expected_sha256 ), $actual ); } /** * Delete a stored file. Never touches anything outside the private dir. */ public static function delete( string $relative ): bool { if ( in_array( basename( $relative ), self::PROTECTED_FILES, true ) ) { return false; } $path = self::path( $relative ); if ( '' === $path || ! is_file( $path ) || is_link( $path ) ) { return false; } wp_delete_file( $path ); return ! file_exists( $path ); } /** * Move a file into place through WP_Filesystem instead of a raw rename(). * * @param string $from Source path. * @param string $to Destination path. * @return bool */ private static function move_file( string $from, string $to ): bool { if ( ! class_exists( '\WP_Filesystem_Direct' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php'; require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php'; } $fs = new \WP_Filesystem_Direct( null ); return (bool) $fs->move( $from, $to, true ); } /** * Stream a stored file inline or as an attachment. The caller authorises access. * * Only raster images and PDFs may ever be served inline. SVG, AI, EPS and * every other type stay attachment-only (SVG is for download/print, never * preview), and an unknown uploader-supplied MIME cannot force inline. * * @param string $relative Stored relative path. * @param string $download_name Suggested download filename. * @param string $mime Recorded MIME type. * @param string $disposition 'attachment' (default) or 'inline'. */ public static function send_file( string $relative, string $download_name, string $mime = '', string $disposition = 'attachment' ): void { $path = self::path( $relative ); if ( '' === $path || ! is_file( $path ) ) { status_header( 404 ); exit; } nocache_headers(); $mime = strtolower( trim( $mime ) ); if ( '' === $mime || ! preg_match( '#^[a-z0-9][a-z0-9.+-]*/[a-z0-9][a-z0-9.+-]*$#', $mime ) ) { $detected = self::detected_mime( $path ); $mime = ( '' !== $detected && preg_match( '#^[a-z0-9][a-z0-9.+-]*/[a-z0-9][a-z0-9.+-]*$#', $detected ) ) ? $detected : 'application/octet-stream'; } $previewable = [ 'image/png', 'image/jpeg', 'image/tiff', 'application/pdf' ]; $ext = strtolower( (string) pathinfo( $download_name, PATHINFO_EXTENSION ) ); if ( '' === $ext ) { $ext = strtolower( (string) pathinfo( $relative, PATHINFO_EXTENSION ) ); } $inline = 'inline' === strtolower( trim( $disposition ) ) && in_array( $mime, $previewable, true ) && ! in_array( $ext, [ 'svg', 'svgz', 'ai', 'eps' ], true ); $name = self::sanitize_name( $download_name ); if ( '' === $name ) { $name = 'artwork'; } $utf8_name = trim( preg_replace( '/[\r\n"]+/', '', $name ) ); $ascii = remove_accents( $utf8_name ); $ascii = trim( preg_replace( '/[^A-Za-z0-9._-]+/', '_', $ascii ), '._-' ); if ( '' === $ascii ) { $ascii = 'artwork'; } header( 'Content-Type: ' . $mime ); header( 'Content-Length: ' . (string) filesize( $path ) ); header( 'Content-Disposition: ' . ( $inline ? 'inline' : 'attachment' ) . '; filename="' . $ascii . '"; filename*=UTF-8\'\'' . rawurlencode( $utf8_name ) ); header( 'X-Content-Type-Options: nosniff' ); header( 'X-Frame-Options: ' . ( $inline ? 'SAMEORIGIN' : 'DENY' ) ); if ( $inline ) { header( "Content-Security-Policy: default-src 'none'; sandbox" ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile -- Streams files up to the 25 MB cap; WP_Filesystem::get_contents() would load the whole file into memory. readfile( $path ); exit; } /** * Create the private directory, its tmp/ staging area and deny rules. */ public static function ensure_dir(): string { $dir = Install::private_dir(); if ( '' === $dir ) { self::log( 'The WordPress uploads directory is unavailable; refusing to store artwork.' ); return ''; } if ( ! wp_mkdir_p( $dir ) ) { self::log( 'Could not create the ProofKit private directory.' ); } if ( ! wp_mkdir_p( $dir . 'tmp/' ) ) { self::log( 'Could not create the ProofKit tmp directory.' ); } Install::protect_dir( $dir ); return $dir; } /** * Delete unreferenced old files plus abandoned staging files. * * The age is floored at 96 hours (see PURGE_MIN_HOURS) so even a caller * that still passes the old 72-hour value cannot delete a file whose * signed descriptor is still valid. Staging files in tmp/ are always * cleaned after 12 hours. * * @param int $hours Age in hours before an unreferenced file is removed. * @return int Number of deleted files. */ public static function purge_abandoned( int $hours = 96 ): int { $base = Install::private_dir(); if ( ! is_dir( $base ) ) { return 0; } $hours = max( self::PURGE_MIN_HOURS, $hours ); $file_cutoff = time() - ( $hours * HOUR_IN_SECONDS ); $tmp_cutoff = time() - ( 12 * HOUR_IN_SECONDS ); $deleted = 0; $scanned = 0; $candidates = []; try { $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $base, \FilesystemIterator::SKIP_DOTS ), \RecursiveIteratorIterator::LEAVES_ONLY, \RecursiveIteratorIterator::CATCH_GET_CHILD ); foreach ( $iterator as $info ) { if ( ++$scanned > 5000 ) { break; } if ( ! $info instanceof \SplFileInfo || $info->isLink() || ! $info->isFile() ) { continue; } if ( in_array( $info->getFilename(), self::PROTECTED_FILES, true ) ) { continue; } $absolute = $info->getPathname(); $relative = str_replace( DIRECTORY_SEPARATOR, '/', substr( $absolute, strlen( $base ) ) ); if ( '' === $relative ) { continue; } $mtime = $info->getMTime(); if ( str_starts_with( $relative, 'tmp/' ) ) { if ( $mtime < $tmp_cutoff ) { wp_delete_file( $absolute ); if ( ! file_exists( $absolute ) ) { ++$deleted; } } continue; } if ( $mtime < $file_cutoff ) { $candidates[] = $relative; } } } catch ( \Throwable ) { self::log( 'ProofKit abandoned-file scan failed.' ); return $deleted; } foreach ( array_chunk( $candidates, 200 ) as $chunk ) { $referenced = self::referenced_paths( $chunk ); foreach ( $chunk as $relative ) { if ( isset( $referenced[ $relative ] ) ) { continue; } if ( self::delete( $relative ) ) { ++$deleted; } } } return $deleted; } /** * Sanitise an original filename, keeping a usable fallback. */ public static function sanitize_name( string $name ): string { $name = str_replace( "\0", '', $name ); $name = wp_basename( str_replace( '\\', '/', $name ) ); $name = sanitize_file_name( $name ); $name = trim( $name ); if ( '' === $name || '.' === $name || '..' === $name ) { return 'artwork'; } if ( strlen( $name ) > 200 ) { $ext = (string) pathinfo( $name, PATHINFO_EXTENSION ); $base = (string) pathinfo( $name, PATHINFO_FILENAME ); $keep = 200 - ( '' !== $ext ? strlen( $ext ) + 1 : 0 ); $name = substr( $base, 0, max( 1, $keep ) ) . ( '' !== $ext ? '.' . $ext : '' ); } return $name; } /** * Configured global maximum upload size in bytes. */ public static function max_bytes(): int { return max( 1, (int) Settings::max_bytes() ); } /** * Effective limits for a product. The global setting is a hard ceiling. * * @param int $product_id Product id; 0 uses global settings only. * @return array{max_bytes:int,extensions:string[]} */ private static function limits( int $product_id ): array { $max_bytes = self::max_bytes(); $extensions = array_values( array_map( 'strtolower', (array) Settings::allowed_extensions() ) ); // The stub harness may not load the Product class. if ( $product_id > 0 && class_exists( Product::class ) ) { if ( is_callable( [ Product::class, 'max_bytes' ] ) ) { $product_max = (int) Product::max_bytes( $product_id ); if ( $product_max > 0 ) { $max_bytes = min( $max_bytes, $product_max ); } } if ( is_callable( [ Product::class, 'allowed_extensions' ] ) ) { $product_exts = array_values( array_filter( array_map( 'strtolower', (array) Product::allowed_extensions( $product_id ) ), 'strlen' ) ); if ( [] !== $product_exts ) { // Fail closed: a product list that does not overlap the // global list allows nothing, rather than widening back to // the global list. $extensions = array_values( array_intersect( $extensions, $product_exts ) ); } } } return [ 'max_bytes' => max( 1, $max_bytes ), 'extensions' => $extensions, ]; } /** * Error for a failed PHP upload code. */ private static function upload_error( int $code ): \WP_Error { switch ( $code ) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: return self::size_error(); case UPLOAD_ERR_NO_FILE: return self::error( 'proofkit_upload_empty', __( 'No file was uploaded. Please choose a file.', 'proofkit' ) ); case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_TMP_DIR: case UPLOAD_ERR_CANT_WRITE: case UPLOAD_ERR_EXTENSION: default: return self::failed_error(); } } /** * A filename with more than one extension is only rejected when an * intermediate segment is executable (e.g. logo.php.pdf). */ private static function has_dangerous_segment( string $name ): bool { $segments = array_values( array_filter( explode( '.', strtolower( $name ) ), 'strlen' ) ); if ( count( $segments ) < 3 ) { return false; } $intermediate = array_slice( $segments, 0, -1 ); return (bool) array_intersect( $intermediate, self::DANGEROUS_EXTS ); } /** * Read the magic bytes for an extension. */ private static function magic_matches( string $path, string $ext ): bool { $length = ( 'svg' === $ext ) ? 8192 : 8; // WP_Filesystem has no partial-read API, and loading a 25 MB file to // read a handful of magic bytes would be wasteful. // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fread,WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- No partial-read API in WP_Filesystem. $handle = @fopen( $path, 'rb' ); if ( false === $handle ) { return false; } $head = fread( $handle, $length ); fclose( $handle ); // phpcs:enable if ( false === $head ) { return false; } switch ( $ext ) { case 'pdf': case 'ai': case 'eps': return str_starts_with( $head, '%PDF' ) || str_starts_with( $head, '%!PS' ); case 'png': return str_starts_with( $head, "\x89PNG" ); case 'jpg': case 'jpeg': return str_starts_with( $head, "\xFF\xD8\xFF" ); case 'tif': case 'tiff': return str_starts_with( $head, "II*\x00" ) || str_starts_with( $head, "MM\x00*" ); case 'svg': if ( str_starts_with( $head, "\xEF\xBB\xBF" ) ) { $head = substr( $head, 3 ); } $head = ltrim( $head ); return 0 === stripos( $head, ' */ private static function referenced_paths( array $paths ): array { global $wpdb; if ( [] === $paths ) { return []; } $rows = $wpdb->get_col( // The %s list is generated from $paths at runtime, so WPCS cannot // count the replacements statically. // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $wpdb->prepare( 'SELECT file_path FROM %i WHERE file_path IN (' . implode( ',', array_fill( 0, count( $paths ), '%s' ) ) . ')', Install::table( 'proofs' ), ...$paths ) ); if ( '' !== $wpdb->last_error || ! is_array( $rows ) ) { return array_fill_keys( $paths, true ); } $referenced = []; foreach ( $rows as $row ) { $referenced[ (string) $row ] = true; } return $referenced; } /** * Generic failure. */ private static function failed_error(): \WP_Error { return self::error( 'proofkit_upload_failed', __( 'The upload could not be processed. Please try again.', 'proofkit' ) ); } /** * Size cap failure. * * @param int|null $max_bytes Effective limit, or null for the global one. */ private static function size_error( ?int $max_bytes = null ): \WP_Error { return self::error( 'proofkit_upload_size', sprintf( /* translators: %s: maximum upload size, e.g. "25 MB". */ __( 'The file is larger than the %s upload limit.', 'proofkit' ), Util::human_size( null === $max_bytes ? self::max_bytes() : max( 1, $max_bytes ) ) ) ); } /** * Build a WP_Error from a code and message. */ private static function error( string $code, string $message ): \WP_Error { return new \WP_Error( $code, $message ); } /** * Log through Util without ever letting logging break an upload. */ private static function log( string $message, array $context = [] ): void { try { Util::log( $message, $context ); } catch ( \Throwable ) { // Logging is best-effort only. } } }