\d+)/upload', array( 'methods' => 'POST', 'permission_callback' => '__return_true', 'callback' => array( __CLASS__, 'rest_upload' ), ) ); register_rest_route( 'fwren/v1', '/file', array( 'methods' => 'GET', 'permission_callback' => '__return_true', 'callback' => array( __CLASS__, 'rest_download' ), ) ); } /** @return string[] Lower-case extensions from "pdf, .docx". */ public static function parse_types( $s ) { $bad = array( 'php', 'phtml', 'php3', 'php4', 'php5', 'php7', 'phar', 'exe', 'js', 'html', 'htm', 'svg', 'sh', 'bat', 'cgi', 'pl', 'py', 'asp', 'aspx', 'jsp', 'htaccess' ); $out = array(); foreach ( explode( ',', strtolower( (string) $s ) ) as $e ) { $e = trim( ltrim( trim( $e ), '.' ) ); if ( $e && preg_match( '/^[a-z0-9]{1,8}$/', $e ) && ! in_array( $e, $bad, true ) ) { $out[] = $e; } } return array_values( array_unique( $out ) ); } /** Upload one file to temp. */ public static function rest_upload( \WP_REST_Request $req ) { $form_id = (int) $req['id']; $key = sanitize_key( (string) $req->get_param( 'field' ) ); $f = Schema::field( $form_id, $key ); if ( ! $f || empty( $f['is_upload'] ) || 'publish' !== get_post_status( $form_id ) ) { return new \WP_Error( 'fwren_upload_field', __( 'Upload not allowed.', 'fieldwren' ), array( 'status' => 400 ) ); } $rl = 'fwren_up_' . md5( Submission::ip() ); $n = (int) get_transient( $rl ); if ( $n > 60 ) { return new \WP_Error( 'fwren_upload_rate', __( 'Too many uploads. Please wait a moment.', 'fieldwren' ), array( 'status' => 429 ) ); } set_transient( $rl, $n + 1, 10 * MINUTE_IN_SECONDS ); $files = $req->get_file_params(); $file = $files['file'] ?? null; if ( ! $file || ! empty( $file['error'] ) || ! is_uploaded_file( $file['tmp_name'] ) ) { return new \WP_Error( 'fwren_upload_error', __( 'The file could not be uploaded.', 'fieldwren' ), array( 'status' => 400 ) ); } $name = sanitize_file_name( wp_unslash( $file['name'] ) ); $ext = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) ); if ( ! in_array( $ext, (array) $f['allowed'], true ) ) { /* translators: %s file name */ return new \WP_Error( 'fwren_upload_type', sprintf( __( '%s is not an allowed file type.', 'fieldwren' ), $name ), array( 'status' => 400 ) ); } $check = wp_check_filetype_and_ext( $file['tmp_name'], $name ); if ( empty( $check['ext'] ) && ! in_array( $ext, array( 'csv', 'txt' ), true ) ) { /* translators: %s file name */ return new \WP_Error( 'fwren_upload_type', sprintf( __( '%s does not look like the file type its name says.', 'fieldwren' ), $name ), array( 'status' => 400 ) ); } if ( $file['size'] > $f['max_size'] * MB_IN_BYTES ) { /* translators: 1: file, 2: MB */ return new \WP_Error( 'fwren_upload_size', sprintf( __( '%1$s is larger than %2$s MB.', 'fieldwren' ), $name, $f['max_size'] ), array( 'status' => 400 ) ); } Install::protect_uploads(); $token = wp_generate_password( 24, false ) . '.' . $ext; $dest = Install::upload_dir() . '/temp/' . $token; if ( ! @move_uploaded_file( $file['tmp_name'], $dest ) ) { // phpcs:ignore return new \WP_Error( 'fwren_upload_move', __( 'The file could not be saved.', 'fieldwren' ), array( 'status' => 500 ) ); } file_put_contents( $dest . '.json', wp_json_encode( array( 'name' => $name, 'size' => (int) $file['size'], 'type' => $check['type'] ? $check['type'] : 'application/octet-stream', 'form' => $form_id, 'field' => $key ) ) ); // phpcs:ignore return rest_ensure_response( array( 'token' => $token, 'name' => $name, 'size' => (int) $file['size'] ) ); } /** @return bool Whether a temp upload exists for this field. */ public static function temp_exists( $token, array $f ) { $path = Install::upload_dir() . '/temp/' . basename( (string) $token ); if ( ! file_exists( $path ) || ! file_exists( $path . '.json' ) ) { return false; } $meta = json_decode( (string) file_get_contents( $path . '.json' ), true ); // phpcs:ignore return (int) ( $meta['form'] ?? 0 ) === (int) ( $f['form_id'] ?? 0 ) && ( $meta['field'] ?? '' ) === $f['name']; } /** * Move temp uploads into the entries folder. * * @param string[] $tokens Tokens. * @param array $f Field schema. * @param int $form_id Form id. * @return array Stored files. */ public static function finalize( array $tokens, array $f, $form_id ) { $out = array(); $sub = 'entries/' . (int) $form_id . '/' . gmdate( 'Y/m' ); $dir = Install::upload_dir() . '/' . $sub; wp_mkdir_p( $dir ); foreach ( $tokens as $token ) { $src = Install::upload_dir() . '/temp/' . basename( $token ); if ( ! file_exists( $src ) ) { continue; } $meta = json_decode( (string) @file_get_contents( $src . '.json' ), true ); // phpcs:ignore $name = sanitize_file_name( $meta['name'] ?? basename( $token ) ); $ext = pathinfo( $name, PATHINFO_EXTENSION ); $base = pathinfo( $name, PATHINFO_FILENAME ); $final = wp_unique_filename( $dir, substr( $base, 0, 60 ) . '-' . wp_generate_password( 8, false ) . '.' . $ext ); if ( ! @rename( $src, $dir . '/' . $final ) ) { // phpcs:ignore continue; } @unlink( $src . '.json' ); // phpcs:ignore $file = array( 'name' => $name, 'path' => $sub . '/' . $final, 'url' => Install::upload_url() . '/' . $sub . '/' . $final, 'size' => (int) ( $meta['size'] ?? 0 ), 'type' => (string) ( $meta['type'] ?? '' ), 'attachment_id' => 0, ); if ( ! empty( $f['media_library'] ) ) { $file['attachment_id'] = self::to_media_library( $dir . '/' . $final, $name, $file['type'] ); } $out[] = $file; } return $out; } /** Copy a stored file into the media library. */ private static function to_media_library( $path, $name, $type ) { $up = wp_upload_dir(); $dest = wp_unique_filename( $up['path'], $name ); if ( ! @copy( $path, $up['path'] . '/' . $dest ) ) { // phpcs:ignore return 0; } $id = wp_insert_attachment( array( 'post_mime_type' => $type, 'post_title' => pathinfo( $name, PATHINFO_FILENAME ), 'post_status' => 'inherit', ), $up['path'] . '/' . $dest ); if ( $id && ! is_wp_error( $id ) ) { require_once ABSPATH . 'wp-admin/includes/image.php'; wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $up['path'] . '/' . $dest ) ); return (int) $id; } return 0; } /** Save a signature data URL as PNG. @return array Stored files. */ public static function save_signature( $data_url, $form_id ) { $bin = base64_decode( substr( (string) $data_url, strlen( 'data:image/png;base64,' ) ), true ); if ( ! $bin || "\x89PNG" !== substr( $bin, 0, 4 ) ) { return array(); } $sub = 'entries/' . (int) $form_id . '/' . gmdate( 'Y/m' ); $dir = Install::upload_dir() . '/' . $sub; wp_mkdir_p( $dir ); $name = 'signature-' . wp_generate_password( 12, false ) . '.png'; file_put_contents( $dir . '/' . $name, $bin ); // phpcs:ignore return array( array( 'name' => 'signature.png', 'path' => $sub . '/' . $name, 'url' => Install::upload_url() . '/' . $sub . '/' . $name, 'size' => strlen( $bin ), 'type' => 'image/png', 'attachment_id' => 0, ), ); } /** @return string Signed download link for a stored file. */ public static function signed_url( $file ) { if ( ! is_array( $file ) || empty( $file['path'] ) ) { return is_array( $file ) ? (string) ( $file['url'] ?? '' ) : ''; } return add_query_arg( array( 'f' => rawurlencode( $file['path'] ), 'sig' => self::sign( $file['path'] ), ), rest_url( 'fwren/v1/file' ) ); } /** @return string */ private static function sign( $path ) { return substr( hash_hmac( 'sha256', $path, wp_salt( 'auth' ) ), 0, 24 ); } /** Stream a stored file. */ public static function rest_download( \WP_REST_Request $req ) { $path = rawurldecode( (string) $req->get_param( 'f' ) ); $sig = (string) $req->get_param( 'sig' ); if ( false !== strpos( $path, '..' ) || 0 !== strpos( $path, 'entries/' ) || ! hash_equals( self::sign( $path ), $sig ) ) { return new \WP_Error( 'fwren_file', __( 'File not found.', 'fieldwren' ), array( 'status' => 404 ) ); } $full = Install::upload_dir() . '/' . $path; if ( ! file_exists( $full ) ) { return new \WP_Error( 'fwren_file', __( 'File not found.', 'fieldwren' ), array( 'status' => 404 ) ); } $type = wp_check_filetype( $full ); $inline = in_array( $type['ext'], array( 'png', 'jpg', 'jpeg', 'gif', 'webp', 'pdf' ), true ); nocache_headers(); header( 'Content-Type: ' . ( $type['type'] ? $type['type'] : 'application/octet-stream' ) ); header( 'Content-Length: ' . filesize( $full ) ); header( 'X-Content-Type-Options: nosniff' ); header( 'Content-Disposition: ' . ( $inline ? 'inline' : 'attachment' ) . '; filename="' . basename( $full ) . '"' ); readfile( $full ); // phpcs:ignore exit; } /** @return string[] Absolute paths of an entry's files (for attachments). */ public static function entry_paths( array $values, array $schema ) { $out = array(); foreach ( $values as $k => $v ) { if ( ! empty( $schema['fields'][ $k ]['is_upload'] ) ) { foreach ( (array) $v as $file ) { if ( is_array( $file ) && ! empty( $file['path'] ) && file_exists( Install::upload_dir() . '/' . $file['path'] ) ) { $out[] = Install::upload_dir() . '/' . $file['path']; } } } } return $out; } /** Delete an entry's files. */ public static function delete_files( array $values ) { array_walk_recursive( $values, static function ( $v, $k ) { if ( 'path' === $k && is_string( $v ) && 0 === strpos( $v, 'entries/' ) && false === strpos( $v, '..' ) ) { $p = Install::upload_dir() . '/' . $v; if ( file_exists( $p ) ) { @unlink( $p ); // phpcs:ignore } } } ); } /** Remove temp files older than a day. */ public static function cleanup_temp() { foreach ( (array) glob( Install::upload_dir() . '/temp/*' ) as $p ) { if ( is_file( $p ) && 'index.php' !== basename( $p ) && '.htaccess' !== basename( $p ) && filemtime( $p ) < time() - DAY_IN_SECONDS ) { @unlink( $p ); // phpcs:ignore } } } }