Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/weforms/assets/js-templates/spa-components.php
+++ b/weforms/assets/js-templates/spa-components.php
@@ -252,9 +252,9 @@
<button type="button" class="button button-small" style="margin-top: 8px;" @click.prevent="post_title_editing = false"><i class="fa fa-check"></i></button>
</span>
- <span class="form-id" title="<?php echo esc_attr_e( 'Click to copy shortcode', 'weforms' ); ?>" :data-clipboard-text='"[weforms id="" + post.ID + ""]"'><i class="fa fa-clipboard" aria-hidden="true"></i> #{{ post.ID }}</span>
+ <span class="form-id" title="<?php esc_attr_e( 'Click to copy shortcode', 'weforms' ); ?>" :data-clipboard-text='"[weforms id="" + post.ID + ""]"'><i class="fa fa-clipboard" aria-hidden="true"></i> #{{ post.ID }}</span>
- <span :class="{ sharing_on : settings.sharing_on }" class="ann-form-btn form-id" @click="shareForm( '<?php echo site_url( '/' ); ?>',post)" title="<?php echo esc_attr_e( 'Share Your Form', 'weforms' ); ?>">
+ <span :class="{ sharing_on : settings.sharing_on }" class="ann-form-btn form-id" @click="shareForm( '<?php echo site_url( '/' ); ?>',post)" title="<?php esc_attr_e( 'Share Your Form', 'weforms' ); ?>">
<i class="fa fa-share-alt" aria-hidden="true"></i>
<?php esc_html_e( 'Share', 'Share' ); ?>
</span>
--- a/weforms/includes/admin/class-shortcode-button.php
+++ b/weforms/includes/admin/class-shortcode-button.php
@@ -43,7 +43,7 @@
public function add_media_button( $editor_id ) {
?>
<a href="#TB_inline?width=480&inlineId=weforms-media-dialog" class="button thickbox insert-form" data-editor="<?php echo esc_attr( $editor_id ); ?>" title="<?php esc_html_e( 'Add a Form', 'weforms' ); ?>">
- <?php echo '<span class="wp-media-buttons-icon dashicons dashicons-welcome-widgets-menus"></span>' . esc_html_e( ' Add Contact Form', 'weforms' ); ?>
+ <?php echo '<span class="wp-media-buttons-icon dashicons dashicons-welcome-widgets-menus"></span>' . esc_html__( ' Add Contact Form', 'weforms' ); ?>
</a>
<?php
}
@@ -123,3 +123,4 @@
}
Weforms_Form_Button::init();
+
--- a/weforms/includes/admin/views/display-settings.php
+++ b/weforms/includes/admin/views/display-settings.php
@@ -41,9 +41,10 @@
</select>
<p class="description">
- <?php wp_kses_post( __( "Selecting <strong>Yes</strong> will use your theme's style for form fields.", "weforms" ) ) ?>
+ <?php echo wp_kses_post( __( "Selecting <strong>Yes</strong> will use your theme's style for form fields.", "weforms" ) ) ?>
</p>
</td>
</tr>
</table>
+
--- a/weforms/includes/admin/views/weforms-settings-general.php
+++ b/weforms/includes/admin/views/weforms-settings-general.php
@@ -47,7 +47,7 @@
<td>
<input type="text" v-model="settings.gateways.sparkpost" class="regular-text">
- <p class="description"><?php printf( wp_kses_post( 'Fill your SparkPost <a href="%s" target="_blank">API Key</a>.', 'weforms' ), 'https://app.sparkpost.com/account/credentials' ); ?></p>
+ <p class="description"><?php printf( wp_kses_post( __( 'Fill your SparkPost <a href="%s" target="_blank">API Key</a>.', 'weforms' ) ), 'https://app.sparkpost.com/account/credentials' ); ?></p>
</td>
</tr>
</template>
@@ -56,7 +56,7 @@
<td>
<label>
<input type="checkbox" v-model="settings.credit">
- <?php wp_kses_post( 'Show <em>powered by weForms</em> credit in form footer.', 'weforms' ); ?>
+ <?php echo wp_kses_post( __( 'Show <em>powered by weForms</em> credit in form footer.', 'weforms' ) ); ?>
</label>
</td>
</tr>
--- a/weforms/includes/api/class-weforms-uploads-controller.php
+++ b/weforms/includes/api/class-weforms-uploads-controller.php
@@ -22,6 +22,19 @@
protected $rest_base = 'uploads';
/**
+ * Size limit in KB for an upload field saved without `max_size`.
+ *
+ * Matches the form builder default for image fields. Uploads are also
+ * capped by wp_max_upload_size(), so a missing value never means
+ * "no limit".
+ *
+ * @since 1.6.30
+ *
+ * @var int
+ */
+ const DEFAULT_MAX_SIZE_KB = 1024;
+
+ /**
* Register all routes releated with forms
*
* @return void
@@ -77,7 +90,7 @@
[
'methods' => WP_REST_Server::DELETABLE,
'callback' => [ $this, 'delete_file' ],
- 'permission_callback' => [ $this, 'upload_permissions_check' ],
+ 'permission_callback' => [ $this, 'delete_permissions_check' ],
],
] );
}
@@ -110,56 +123,26 @@
*
* @since 1.4.2
*
- * @param string $param
- * @param WP_REST_Request $request
- * @param string $key
+ * @param WP_REST_Request $request Request.
*
- * @return bool
+ * @return bool|WP_Error True when the file matches one published upload field.
*/
public function is_file_validate( $request ) {
- $file_error = new WP_Error();
- $form = weforms()->form->get( (int) $request['form_id'] );
- $form_settings = $form->get_settings();
- $form_fields = $form->get_fields();
- $files = $request->get_file_params();
- $headers = $request->get_headers();
- $field_id = $request->get_param( 'field_id' );
-
- if ( !empty( $files ) ) {
- foreach ( $form_fields as $field ) {
- if ( 'image_upload' === $field['template'] && $field['id'] == $field_id ) {
- $allowed_extension = weforms_allowed_extensions();
- $allowed_file_type = explode( ',', $allowed_extension['images']['ext'] );
- $file_type = wp_check_filetype( $files['file']['name'], $mimes = null );
-
- if ( in_array( $file_type['ext'], $allowed_file_type ) ) {
- if ( $files['file']['size'] <= ( $field['max_size'] * 1024 ) ) {
- return true;
- } else {
- $file_error->add( 'rest_weforms_invalid_file_size', __( 'File Size exceeds limit!', 'weforms' ), [ 'status' => 404 ] );
- }
- }
- }
-
- if ( 'file_upload' === $field['template'] && $field['id'] == $field_id ) {
- $file_type = wp_check_filetype( $files['file']['name'], $mimes = null );
+ $files = $request->get_file_params();
+ $file = ( isset( $files['file'] ) && is_array( $files['file'] ) ) ? $files['file'] : [];
+ $result = weforms_authorize_upload(
+ (int) $request->get_param( 'form_id' ),
+ [
+ 'field_id' => absint( $request->get_param( 'field_id' ) ),
+ ],
+ $file
+ );
- if ( $this->is_allow_file_type( $field['extension'], $file_type['ext'] ) ) {
- if ( $files['file']['size'] <= ( $field['max_size'] * 1024 ) ) {
- return true;
- } else {
- $file_error->add( 'rest_weforms_invalid_file_size', __( 'File Size exceeds limit!', 'weforms' ), [ 'status' => 404 ] );
- }
- }
- }
- }
+ if ( is_wp_error( $result ) ) {
+ return new WP_Error( 'rest_weforms_upload', __( 'Upload could not be accepted.', 'weforms' ), [ 'status' => 400 ] );
}
- if ( count( $file_error->get_error_messages() ) > 0 ) {
- return $file_error;
- } else {
- return true;
- }
+ return true;
}
/**
@@ -174,15 +157,49 @@
public function upload_file( $request ) {
global $wp_rest_server;
+ $rejected = $this->reject_attachment_update_params( $request );
+
+ if ( is_wp_error( $rejected ) ) {
+ return $rejected;
+ }
+
+ $files = $request->get_file_params();
+ $file = ( isset( $files['file'] ) && is_array( $files['file'] ) ) ? $files['file'] : [];
+ $authorized = weforms_authorize_upload(
+ (int) $request->get_param( 'form_id' ),
+ [
+ 'field_id' => absint( $request->get_param( 'field_id' ) ),
+ ],
+ $file
+ );
+
+ if ( is_wp_error( $authorized ) ) {
+ return new WP_Error( 'rest_weforms_upload', __( 'Upload could not be accepted.', 'weforms' ), [ 'status' => 400 ] );
+ }
+
$endpoints = $wp_rest_server->get_routes();
$attachment_controller = $endpoints['/wp/v2/media'][0]['callback'][0];
- $files = $request->get_file_params();
- $headers = $request->get_headers();
- $attachment_response = $attachment_controller->create_item( $request );
+
+ $GLOBALS['weforms_upload_form_id'] = absint( $request->get_param( 'form_id' ) );
+ $GLOBALS['weforms_upload_field_name'] = sanitize_key( $authorized['name'] );
+
+ WeForms_Upload_Protection::begin();
+
+ try {
+ $attachment_response = $attachment_controller->create_item( $this->request_for_new_attachment( $request ) );
+ } finally {
+ WeForms_Upload_Protection::end();
+ unset( $GLOBALS['weforms_upload_form_id'], $GLOBALS['weforms_upload_field_name'] );
+ }
+
+ if ( is_wp_error( $attachment_response ) ) {
+ return $attachment_response;
+ }
if ( !empty( $attachment_response->data['id'] ) ) {
$form_id = $request->get_param( 'form_id' );
+ WeForms_Upload_Protection::protect( $attachment_response->data['id'], (string) $files['file']['name'] );
update_post_meta( $attachment_response->data['id'], 'attachment_form_id', $form_id );
weforms_register_uploaded_attachment( $attachment_response->data['id'] );
@@ -219,11 +236,26 @@
* @return WP_REST_Response|WP_Error response object on success, or WP_Error object on failure
*/
public function delete_file( $request ) {
+ $permission = $this->delete_permissions_check( $request );
+
+ if ( is_wp_error( $permission ) ) {
+ return $permission;
+ }
+
global $wp_rest_server;
- $endpoints = $wp_rest_server->get_routes();
- $attachment_controller = $endpoints['/wp/v2/media'][0]['callback'][0];
- $attachment_response = $attachment_controller->delete_item( $request );
+ $endpoints = $wp_rest_server->get_routes();
+ $attachment_controller = $endpoints['/wp/v2/media'][0]['callback'][0];
+ $attachment_response = $attachment_controller->delete_item( $request );
+
+ if ( is_wp_error( $attachment_response ) || empty( $attachment_response->data['previous']['id'] ) ) {
+ return new WP_Error(
+ 'rest_weforms_cannot_delete',
+ __( 'Sorry, you are not allowed to delete this file.', 'weforms' ),
+ [ 'status' => rest_authorization_required_code() ]
+ );
+ }
+
$data = [];
$data['id'] = $attachment_response->data['previous']['id'];
$data['message'] = 'File deleted successfully';
@@ -263,7 +295,7 @@
}
$html = '<li class="ui-state-default wpuf-image-wrap thumbnail">';
- $html .= sprintf( '<div class="attachment-name"><img src="%s" alt="%s" /></div>', $image, esc_attr( $attachment->post_title ) );
+ $html .= sprintf( '<div class="attachment-name"><img src="%s" alt="%s" /></div>', esc_url( $image ), esc_attr( $attachment->post_title ) );
$html .= sprintf( '<input type="hidden" name="wpuf_files[%s][]" value="%d">', $type, $attach_id );
$html .= '<div class="caption">';
$html .= sprintf( '<a href="#" class="attachment-delete" data-attach_id="%d"> <img src="%s" /></a>', $attach_id, WEFORMS_ASSET_URI . '/images/del-img.png' );
@@ -338,12 +370,18 @@
}
}
} else {
- if ( array_key_exists( $field_extensions, $allowd_extensions ) ) {
- foreach ( $allowd_extensions[ $field_extensions ][ 'ext' ] as $key => $allowd_extension ) {
- $extensions = explode( ',', $allowd_extension['ext'] );
+ /**
+ * A scalar value is one extension category. `ext` is a comma-separated
+ * list, not a list of category records.
+ */
+ $category = is_string( $field_extensions ) ? $field_extensions : '';
+
+ if ( isset( $allowd_extensions[ $category ]['ext'] ) && is_string( $allowd_extensions[ $category ]['ext'] ) ) {
+ foreach ( explode( ',', $allowd_extensions[ $category ]['ext'] ) as $extension ) {
+ $extension = trim( $extension );
- foreach ( $extensions as $key => $extension ) {
- array_push( $allowd_ext_array, $extension );
+ if ( '' !== $extension ) {
+ $allowd_ext_array[] = $extension;
}
}
}
@@ -352,16 +390,175 @@
return $allowd_ext_array;
}
+ /**
+ * Published image or file upload field with this ID.
+ *
+ * Fields nested in columns are included. An unknown ID does not match.
+ *
+ * @since 1.6.30
+ *
+ * @param int $form_id Form ID.
+ * @param int $field_id Field ID.
+ *
+ * @return array|null
+ */
+ protected function find_upload_field( $form_id, $field_id ) {
+ $form_id = absint( $form_id );
+ $field_id = absint( $field_id );
+
+ if ( ! $form_id || ! $field_id ) {
+ return null;
+ }
+
+ $fields = weforms()->form->get( $form_id )->get_fields();
+
+ if ( ! is_array( $fields ) ) {
+ return null;
+ }
+
+ $found = null;
+
+ $walk = function ( $field ) use ( &$walk, &$found, $field_id ) {
+ if ( null !== $found || ! is_array( $field ) ) {
+ return;
+ }
+
+ $template = isset( $field['template'] ) ? $field['template'] : '';
+ $id = isset( $field['id'] ) ? absint( $field['id'] ) : 0;
+
+ if ( $id === $field_id && in_array( $template, [ 'image_upload', 'file_upload' ], true ) ) {
+ $found = $field;
+
+ return;
+ }
+
+ if ( empty( $field['inner_fields'] ) || ! is_array( $field['inner_fields'] ) ) {
+ return;
+ }
+
+ foreach ( $field['inner_fields'] as $column_fields ) {
+ if ( ! is_array( $column_fields ) ) {
+ continue;
+ }
+
+ foreach ( $column_fields as $inner_field ) {
+ $walk( $inner_field );
+ }
+ }
+ };
+
+ foreach ( $fields as $field ) {
+ $walk( $field );
+ }
+
+ return $found;
+ }
+
+ /**
+ * Parameters that would edit an existing attachment.
+ *
+ * @since 1.6.30
+ *
+ * @return string[]
+ */
+ protected function attachment_update_params() {
+ return [ 'id', 'post', 'author', 'status' ];
+ }
+
+ /**
+ * Reject a create request that carries attachment-update parameters.
+ *
+ * @since 1.6.30
+ *
+ * @param WP_REST_Request $request Request.
+ *
+ * @return true|WP_Error
+ */
+ public function reject_attachment_update_params( $request ) {
+ foreach ( $this->attachment_update_params() as $key ) {
+ if ( $request->has_param( $key ) ) {
+ return new WP_Error(
+ 'rest_weforms_cannot_edit_attachment',
+ __( 'Sorry, you are not allowed to edit an existing file.', 'weforms' ),
+ [ 'status' => 400 ]
+ );
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Media request that contains only the uploaded file.
+ *
+ * @since 1.6.30
+ *
+ * @param WP_REST_Request $request Upload request.
+ *
+ * @return WP_REST_Request
+ */
+ protected function request_for_new_attachment( $request ) {
+ $clean = new WP_REST_Request( 'POST' );
+ $files = $request->get_file_params();
+ $file = ( isset( $files['file'] ) && is_array( $files['file'] ) ) ? $files['file'] : [];
+
+ $clean->set_file_params(
+ [
+ 'file' => $file,
+ ]
+ );
+
+ return $clean;
+ }
+
+ /**
+ * Whether the current user may delete this form attachment.
+ *
+ * @since 1.6.30
+ *
+ * @param WP_REST_Request $request Request.
+ *
+ * @return true|WP_Error
+ */
+ public function delete_permissions_check( $request ) {
+ $id = isset( $request['id'] ) ? absint( $request['id'] ) : 0;
+ $form_id = isset( $request['form_id'] ) ? absint( $request['form_id'] ) : 0;
+ $post = $id ? get_post( $id ) : null;
+
+ if ( ! $post || 'attachment' !== $post->post_type || ! $form_id ) {
+ return new WP_Error(
+ 'rest_weforms_cannot_delete',
+ __( 'Sorry, you are not allowed to delete this file.', 'weforms' ),
+ [ 'status' => rest_authorization_required_code() ]
+ );
+ }
+
+ $attach_form_id = absint( get_post_meta( $id, 'attachment_form_id', true ) );
+
+ if ( $attach_form_id !== $form_id || ! current_user_can( 'delete_post', $id ) ) {
+ return new WP_Error(
+ 'rest_weforms_cannot_delete',
+ __( 'Sorry, you are not allowed to delete this file.', 'weforms' ),
+ [ 'status' => rest_authorization_required_code() ]
+ );
+ }
+
+ return true;
+ }
+
public function upload_permissions_check( $request ) {
+ $rejected = $this->reject_attachment_update_params( $request );
+
+ if ( is_wp_error( $rejected ) ) {
+ return $rejected;
+ }
+
if ( !is_weforms_api_allowed_guest_submission() ) {
return new WP_Error( 'rest_weforms_cannot_upload', __( 'Sorry, you have no permission to upload File.', 'weforms' ), [ 'status' => rest_authorization_required_code() ] );
}
- $form = weforms()->form->get( (int) $request['form_id'] );
- $form_is_open = $form->is_submission_open();
-
- if ( is_wp_error( $form_is_open ) ) {
- return new WP_Error( 'rest_weforms_form_permission', $form_is_open->get_error_message(), [ 'status' => 404 ] );
+ if ( ! weforms_upload_form_is_open( (int) $request['form_id'] ) ) {
+ return new WP_Error( 'rest_weforms_upload', __( 'Upload could not be accepted.', 'weforms' ), [ 'status' => 400 ] );
}
$file_validations = $this->is_file_validate( $request );
--- a/weforms/includes/class-ajax-upload.php
+++ b/weforms/includes/class-ajax-upload.php
@@ -7,11 +7,26 @@
*/
class WeForms_Ajax_Upload {
+ /**
+ * Whether the shared upload request is for a weForms form.
+ *
+ * @since 1.6.30
+ *
+ * @var bool
+ */
+ private $protect_shared_upload = false;
+
public function __construct() {
add_action( 'add_attachment', [ $this, 'register_attachment_from_upload_request' ] );
+ add_filter( 'wp_handle_upload_prefilter', [ $this, 'reject_unverified_weforms_upload' ], 0 );
+ add_action( 'wp_ajax_wpuf_upload_file', [ $this, 'guard_weforms_upload' ], 0 );
+ add_action( 'wp_ajax_nopriv_wpuf_upload_file', [ $this, 'guard_weforms_upload' ], 0 );
// let WPUF handle the upload if installed
if ( class_exists( 'WPUF_Upload' ) ) {
+ add_action( 'wp_ajax_wpuf_upload_file', [ $this, 'protect_shared_upload_request' ], 0 );
+ add_action( 'wp_ajax_nopriv_wpuf_upload_file', [ $this, 'protect_shared_upload_request' ], 0 );
+
return;
}
@@ -42,6 +57,115 @@
}
weforms_register_uploaded_attachment( $attach_id );
+
+ if ( $this->protect_shared_upload ) {
+ $this->protect_shared_upload = false;
+
+ WeForms_Upload_Protection::end();
+ WeForms_Upload_Protection::protect( $attach_id );
+ }
+ }
+
+ /**
+ * Store a WPUF-handled upload for a weForms form in protected storage.
+ *
+ * Runs before the WPUF handler. Uploads for WPUF's own forms are left alone.
+ *
+ * @since 1.6.30
+ *
+ * @return void
+ */
+ public function protect_shared_upload_request() {
+ // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Only selects storage; the upload handler verifies the nonce.
+ $form_id = isset( $_POST['form_id'] ) && is_scalar( $_POST['form_id'] ) ? absint( $_POST['form_id'] ) : 0;
+
+ if ( ! $form_id || 'wpuf_contact_form' !== get_post_type( $form_id ) ) {
+ return;
+ }
+
+ $this->protect_shared_upload = true;
+
+ WeForms_Upload_Protection::begin();
+
+ add_action( 'wp_ajax_wpuf_upload_file', [ 'WeForms_Upload_Protection', 'end' ], PHP_INT_MAX );
+ add_action( 'wp_ajax_nopriv_wpuf_upload_file', [ 'WeForms_Upload_Protection', 'end' ], PHP_INT_MAX );
+ }
+
+ /**
+ * Stop a weForms upload that has not passed the field policy.
+ *
+ * Runs before WPUF when that plugin owns the handler.
+ *
+ * @since 1.6.30
+ *
+ * @return void
+ */
+ public function guard_weforms_upload() {
+ $nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ) : '';
+ $verified = wp_verify_nonce( $nonce, 'wpuf-upload-nonce' ) || wp_verify_nonce( $nonce, 'wpuf_nonce' );
+ $form_id = isset( $_POST['form_id'] ) ? absint( wp_unslash( $_POST['form_id'] ) ) : 0;
+
+ if ( ! weforms_upload_targets_weforms_form( $form_id ) ) {
+ return;
+ }
+
+ if ( ! $verified ) {
+ echo 'error';
+ exit;
+ }
+
+ // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- The path is authorized before anything is stored.
+ $file = isset( $_FILES['wpuf_file'] ) && is_array( $_FILES['wpuf_file'] ) ? $_FILES['wpuf_file'] : array();
+ $name = isset( $_REQUEST['type'] ) ? sanitize_key( wp_unslash( $_REQUEST['type'] ) ) : '';
+ $result = weforms_authorize_upload( $form_id, array( 'name' => $name ), $file );
+
+ if ( is_wp_error( $result ) ) {
+ echo 'error';
+ exit;
+ }
+ }
+
+ /**
+ * Reject a weForms file before WordPress stores it.
+ *
+ * @since 1.6.30
+ *
+ * @param array $file Upload array.
+ *
+ * @return array
+ */
+ public function reject_unverified_weforms_upload( $file ) {
+ $nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ) : '';
+ $verified = wp_verify_nonce( $nonce, 'wpuf-upload-nonce' ) || wp_verify_nonce( $nonce, 'wpuf_nonce' );
+ $form_id = isset( $_POST['form_id'] ) ? absint( wp_unslash( $_POST['form_id'] ) ) : 0;
+
+ if ( ! $form_id && isset( $GLOBALS['weforms_upload_form_id'] ) ) {
+ $form_id = absint( $GLOBALS['weforms_upload_form_id'] );
+ }
+
+ if ( ! weforms_upload_targets_weforms_form( $form_id ) ) {
+ return $file;
+ }
+
+ if ( ! $verified && ! isset( $GLOBALS['weforms_upload_form_id'] ) ) {
+ $file['error'] = __( 'Upload could not be accepted.', 'weforms' );
+
+ return $file;
+ }
+
+ if ( isset( $GLOBALS['weforms_upload_field_name'] ) ) {
+ $name = sanitize_key( (string) $GLOBALS['weforms_upload_field_name'] );
+ } else {
+ $name = isset( $_REQUEST['type'] ) ? sanitize_key( wp_unslash( $_REQUEST['type'] ) ) : '';
+ }
+
+ $result = weforms_authorize_upload( $form_id, array( 'name' => $name ), $file );
+
+ if ( is_wp_error( $result ) ) {
+ $file['error'] = __( 'Upload could not be accepted.', 'weforms' );
+ }
+
+ return $file;
}
/**
@@ -80,16 +204,25 @@
}
- $file = isset( $_FILES['wpuf_file'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_FILES['wpuf_file'] ) ) : [];
+ // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- The path is authorized before anything is stored.
+ $file = isset( $_FILES['wpuf_file'] ) && is_array( $_FILES['wpuf_file'] ) ? $_FILES['wpuf_file'] : array();
+ $field_name = isset( $_REQUEST['type'] ) ? sanitize_key( wp_unslash( $_REQUEST['type'] ) ) : '';
$upload = array(
- 'name' => isset( $file['name'] ) ? $file['name'] : '',
- 'type' => isset( $file['type'] ) ? $file['type'] : '',
+ 'name' => isset( $file['name'] ) ? sanitize_file_name( wp_unslash( $file['name'] ) ) : '',
+ 'type' => isset( $file['type'] ) ? sanitize_mime_type( wp_unslash( $file['type'] ) ) : '',
'tmp_name' => isset( $file['tmp_name'] ) ? $file['tmp_name'] : '',
- 'error' => isset( $file['error'] ) ? $file['error'] : '',
- 'size' => isset( $file['size'] ) ? $file['size'] : '',
+ 'error' => isset( $file['error'] ) ? absint( $file['error'] ) : 0,
+ 'size' => isset( $file['size'] ) ? absint( $file['size'] ) : 0,
);
+ $authorized = weforms_authorize_upload( $form_id, array( 'name' => $field_name ), $upload );
+
+ if ( is_wp_error( $authorized ) ) {
+ echo 'error';
+ exit;
+ }
+
// $upload = array(
// 'name' => isset( $_FILES['wpuf_file']['name'] ) ? sanitize_file_name( wp_unslash( $_FILES['wpuf_file']['name'] ) ) : '',
// 'type' => isset( $_FILES['wpuf_file']['type'] ) ? sanitize_mime_type( wp_unslash( $_FILES['wpuf_file']['type'] ) ) : '',
@@ -147,7 +280,13 @@
* @return bool|int attachment id on success, bool false instead
*/
public function handle_upload( $upload_data ) {
- $uploaded_file = wp_handle_upload( $upload_data, ['test_form' => false] );
+ WeForms_Upload_Protection::begin();
+
+ try {
+ $uploaded_file = wp_handle_upload( $upload_data, ['test_form' => false] );
+ } finally {
+ WeForms_Upload_Protection::end();
+ }
// If the wp_handle_upload call returned a local path for the image
if ( isset( $uploaded_file['file'] ) ) {
@@ -159,7 +298,7 @@
'post_mime_type' => $file_type['type'],
'post_title' => preg_replace( '/.[^.]+$/', '', basename( $file_name ) ),
'post_content' => '',
- 'post_status' => 'inherit',
+ 'post_status' => 'private',
];
$attach_id = wp_insert_attachment( $attachment, $file_loc );
@@ -171,6 +310,7 @@
$delete_token = wp_generate_password( 32, false );
update_post_meta( $attach_id, '_wpuf_delete_token', $delete_token );
weforms_register_uploaded_attachment( $attach_id );
+ WeForms_Upload_Protection::protect( $attach_id );
return ['success' => true, 'attach_id' => $attach_id];
}
@@ -213,7 +353,7 @@
}
$html = '<li class="ui-state-default wpuf-image-wrap thumbnail">';
- $html .= sprintf( '<div class="attachment-name"><img src="%s" alt="%s" /></div>', $image, esc_attr( $attachment->post_title ) );
+ $html .= sprintf( '<div class="attachment-name"><img src="%s" alt="%s" /></div>', esc_url( $image ), esc_attr( $attachment->post_title ) );
$html .= sprintf( '<input type="hidden" name="wpuf_files[%s][]" value="%d">', $type, $attach_id );
$html .= '<div class="caption">';
--- a/weforms/includes/class-dokan-integration.php
+++ b/weforms/includes/class-dokan-integration.php
@@ -18,10 +18,11 @@
public function add_settings_sections( $sections ) {
$sections[] = [
- 'id' => 'weforms_integration',
- 'title' => __( 'Vendor Contact Form', 'weforms' ),
- 'icon' => 'dashicons-admin-generic',
- ];
+ 'id' => 'weforms_integration',
+ 'title' => __( 'Vendor Contact Form', 'weforms' ),
+ 'settings_title' => __( 'Vendor Contact Form', 'weforms' ),
+ 'icon_url' => WEFORMS_ASSET_URI . '/images/icon-weforms.png',
+ ];
return $sections;
}
@@ -97,7 +98,7 @@
'name' => 'allow_vendor_contact_form',
'label' => __( 'Vendor Can Contact', 'weforms' ),
'desc' => __( 'Allow Vendors to contact admin from the dashbaord area', 'weforms' ),
- 'type' => 'checkbox',
+ 'type' => 'switcher',
'default' => 'off',
];
--- a/weforms/includes/class-frontend-form.php
+++ b/weforms/includes/class-frontend-form.php
@@ -144,19 +144,19 @@
<?php
if ( isset( $atts['modal'] ) && 'true' == esc_attr( $atts['modal'] ) ) {
if ( isset( $atts['link'] ) ) {
- printf( wp_kses_post( '<p><a href="#modal-form" rel="modal:open">%s</a></p>', $atts['link'] ) );
+ printf( '<p><a href="#modal-form" rel="modal:open">%s</a></p>', esc_html( $atts['link'] ) );
} else {
if ( isset( $atts['button'] ) ) {
$button_text = $atts['button'];
} else {
- $button_text = esc_html_e( 'Open Form', 'weforms' );
+ $button_text = esc_html__( 'Open Form', 'weforms' );
}
- printf( wp_kses_post( '<p><button><a href="#modal-form" rel="modal:open">%s</a></button></p>', $button_text ) );
+ printf( '<p><button><a href="#modal-form" rel="modal:open">%s</a></button></p>', esc_html( $button_text ) );
}
}
if ( $show_credit ) {
- printf( '<em>' . wp_kses_post( 'Powered by <a href="%s" target="_blank">weForms</a>', 'weforms' ) . '</em>', 'https://wordpress.org/plugins/weforms/' );
+ printf( '<em>' . wp_kses_post( __( 'Powered by <a href="%s" target="_blank">weForms</a>', 'weforms' ) ) . '</em>', 'https://wordpress.org/plugins/weforms/' );
}
weforms_track_form_view( $form->id );
@@ -203,3 +203,4 @@
<?php
}
}
+
--- a/weforms/includes/class-notification.php
+++ b/weforms/includes/class-notification.php
@@ -505,7 +505,9 @@
* Sales / sales@example.com
*
* Users need the ability to pass {field:department} and get "Support",
- * and {value:department} to get support@email.com
+ * and {value:department} to get support@email.com.
+ *
+ * Users can also pass {product:meta_name} for a multiple product field to get the names of the selected products.
*
* @param string $text The text to parse.
* @param int $entry_id The entry ID. Optional. Default null if tags to be replaced are on the frontend.
@@ -519,8 +521,9 @@
}
// Users looking for {field:something} or {value:something}, determine which one.
- $is_field = preg_match_all( '/{field:(w*)}/', $text, $matches_field );
- $is_value = preg_match_all( '/{value:(w*)}/', $text, $matches_value );
+ $is_field = preg_match_all( '/{field:(w*)}/', $text, $matches_field );
+ $is_value = preg_match_all( '/{value:(w*)}/', $text, $matches_value );
+ $is_product = preg_match_all( '/{product:(w*)}/', $text, $matches_product );
if ( $is_field ) {
$meta_keys = $matches_field[1];
@@ -528,11 +531,12 @@
$meta_values = array();
foreach ( $meta_keys as $meta_key ) {
$meta_value = weforms_get_entry_meta( $entry_id, $meta_key, true );
+ // Array values (checkboxes, multi-selects) must be flattened before replacing.
+ if ( is_array( $meta_value ) ) {
+ $meta_value = implode( WeForms::$field_separator, $meta_value );
+ }
// Add values to the array.
array_push( $meta_values, $meta_value );
- if ( is_array( $meta_value ) ) {
- $meta_value = implode( WeForms::$field_separator, $meta_value );
- }
}
// $text may include HTML tags, only replace tag that was matched. Replace all matches.
$text = str_replace( $matches_field[0], $meta_values, $text );
@@ -554,10 +558,86 @@
// $text may include HTML tags, only replace tag that was matched.
$text = str_replace( $matches_value[0], $modified_values, $text );
}
+ if ( $is_product ) {
+ $modified_values = array();
+ foreach ( $matches_product[1] as $meta_key ) {
+ array_push( $modified_values, self::get_product_tag_value( $entry_id, $meta_key ) );
+ }
+ // $text may include HTML tags, only replace tag that was matched.
+ $text = str_replace( $matches_product[0], $modified_values, $text );
+ }
+
+ /**
+ * Filters the notification text after the {field:}, {value:}, and {product:} tags are replaced.
+ *
+ * Allows custom templating snippets and field logic.
+ *
+ * @since 1.6.30
+ *
+ * @param string $text The text with field tags replaced.
+ * @param int $entry_id The entry ID.
+ */
+ $text = apply_filters( 'weforms_notification_replace_field_tags', $text, $entry_id );
+
return $text;
}
/**
+ * Get the {product:meta_name} replacement for a multiple product field.
+ *
+ * Returns the names of the selected products, joined by the field separator. A product is only included when
+ * its name is one of the field's configured options and its submitted quantity (when present) is at least 1.
+ * The names come from the form's options, never from the submitted value.
+ *
+ * @since 1.6.30
+ *
+ * @param int $entry_id The entry ID.
+ * @param string $meta_key The multiple product field's meta name.
+ *
+ * @return string The product names, or an empty string when none can be determined.
+ */
+ private static function get_product_tag_value( $entry_id, $meta_key ) {
+ $form = WeForms_Form_Entry::get_form( $entry_id );
+
+ if ( empty( $form ) ) {
+ return '';
+ }
+
+ $form_field_values = $form->get_field_values();
+
+ if ( empty( $form_field_values[ $meta_key ]['options'] ) || ! is_array( $form_field_values[ $meta_key ]['options'] ) ) {
+ return '';
+ }
+
+ $options = $form_field_values[ $meta_key ]['options'];
+ $meta_value = weforms_get_entry_meta( $entry_id, $meta_key, true );
+
+ if ( ! is_array( $meta_value ) ) {
+ return '';
+ }
+
+ // Multiple products are an array of arrays, so parse each selected product.
+ $product_names = array();
+ foreach ( $meta_value as $product ) {
+ if ( ! is_array( $product ) || ! isset( $product['product'] ) || ( ! is_string( $product['product'] ) && ! is_int( $product['product'] ) ) ) {
+ continue;
+ }
+
+ if ( isset( $product['quantity'] ) && (float) $product['quantity'] < 1 ) {
+ continue;
+ }
+
+ if ( ! array_key_exists( $product['product'], $options ) ) {
+ continue;
+ }
+
+ array_push( $product_names, (string) $product['product'] );
+ }
+
+ return implode( WeForms::$field_separator, $product_names );
+ }
+
+ /**
* Replace name tag with required value
*
* @param string $text
@@ -619,7 +699,7 @@
$attachments = is_array( $meta_value ) ? $meta_value : array( $meta_value );
foreach ( $attachments as $attachment_id ) {
- $file_url = wp_get_attachment_url( $attachment_id );
+ $file_url = WeForms_Upload_Protection::get_notification_url( $attachment_id );
if ( $file_url ) {
$files[] = $file_url;
@@ -684,8 +764,15 @@
}
$form = weforms()->form->get( $this->args['form_id'] );
- $entry = $form->entries()->get( $this->args['entry_id'] );
- $fields = $entry->get_fields();
+
+ WeForms_Upload_Protection::begin_signed_urls();
+
+ try {
+ $entry = $form->entries()->get( $this->args['entry_id'] );
+ $fields = $entry->get_fields();
+ } finally {
+ WeForms_Upload_Protection::end_signed_urls();
+ }
if ( !$fields ) {
return $text;
--- a/weforms/includes/class-upload-protection.php
+++ b/weforms/includes/class-upload-protection.php
@@ -0,0 +1,888 @@
+<?php
+/**
+ * Private storage for files uploaded through weForms forms.
+ *
+ * @package weForms
+ */
+
+/**
+ * Keeps form uploads out of public media queries and public upload URLs.
+ *
+ * Uploads are written to a deny-all directory under a random file name and
+ * saved as private attachments. Their URLs point to a download handler that
+ * checks access before streaming the file.
+ *
+ * @since 1.6.30
+ */
+class WeForms_Upload_Protection {
+
+ /**
+ * Directory under the uploads base directory.
+ *
+ * @since 1.6.30
+ *
+ * @var string
+ */
+ const DIR = 'weforms-uploads';
+
+ /**
+ * Attachment meta key marking a protected upload.
+ *
+ * @since 1.6.30
+ *
+ * @var string
+ */
+ const META = '_weforms_protected_upload';
+
+ /**
+ * AJAX action for the download handler.
+ *
+ * @since 1.6.30
+ *
+ * @var string
+ */
+ const ACTION = 'weforms_view_upload';
+
+ /**
+ * Option set once legacy uploads have been made private.
+ *
+ * @since 1.6.30
+ *
+ * @var string
+ */
+ const MIGRATED_OPTION = 'weforms_private_uploads_migrated';
+
+ /**
+ * Option set once legacy upload files have been moved.
+ *
+ * @since 1.6.30
+ *
+ * @var string
+ */
+ const FILES_MIGRATED_OPTION = 'weforms_protected_upload_files_migrated';
+
+ /**
+ * Attachment meta key for a legacy file that could not be moved.
+ *
+ * @since 1.6.30
+ *
+ * @var string
+ */
+ const MOVE_FAILED_META = '_weforms_protected_move_failed';
+
+ /**
+ * Seconds a signed no-login link stays valid (30 days).
+ *
+ * Users who can manage entries can still open the file after that.
+ *
+ * @since 1.6.30
+ *
+ * @var int
+ */
+ const SIGNED_URL_TTL = 30 * DAY_IN_SECONDS;
+
+ /**
+ * Nesting depth of begin_signed_urls() calls.
+ *
+ * @since 1.6.30
+ *
+ * @var int
+ */
+ private static $signing = 0;
+
+ /**
+ * Register hooks.
+ *
+ * @since 1.6.30
+ */
+ public function __construct() {
+ add_filter( 'wp_get_attachment_url', array( __CLASS__, 'filter_attachment_url' ), 10, 2 );
+ add_filter( 'image_downsize', array( __CLASS__, 'filter_image_downsize' ), 10, 3 );
+ add_filter( 'wp_calculate_image_srcset', array( __CLASS__, 'filter_image_srcset' ), 10, 5 );
+ add_filter( 'wp_prepare_attachment_for_js', array( __CLASS__, 'filter_attachment_for_js' ), 10, 2 );
+ add_action( 'wp_ajax_' . self::ACTION, array( __CLASS__, 'serve' ) );
+ add_action( 'wp_ajax_nopriv_' . self::ACTION, array( __CLASS__, 'serve' ) );
+ add_action( 'admin_init', array( __CLASS__, 'maybe_run_legacy_migration' ), 10, 0 );
+ }
+
+ /**
+ * Run the legacy upload migration for an administrator in wp-admin.
+ *
+ * admin_init also fires on admin-ajax.php and admin-post.php, which
+ * visitors who are not logged in can reach. AJAX, cron, and users who
+ * cannot manage_options are skipped so only an administrator's screen
+ * load does the work.
+ *
+ * @since 1.6.30
+ *
+ * @return void
+ */
+ public static function maybe_run_legacy_migration() {
+ if ( wp_doing_ajax() || wp_doing_cron() || ! current_user_can( 'manage_options' ) ) {
+ return;
+ }
+
+ self::maybe_migrate_legacy_uploads();
+ self::migrate_legacy_files();
+ }
+
+ /**
+ * Make attachment URLs built until end_signed_urls() signed links.
+ *
+ * Used while rendering notifications for recipients who are not logged in.
+ *
+ * @since 1.6.30
+ *
+ * @return void
+ */
+ public static function begin_signed_urls() {
+ ++self::$signing;
+ }
+
+ /**
+ * Stop signing attachment URLs.
+ *
+ * @since 1.6.30
+ *
+ * @return void
+ */
+ public static function end_signed_urls() {
+ self::$signing = max( 0, self::$signing - 1 );
+ }
+
+ /**
+ * Route uploads made until end() into the protected directory.
+ *
+ * @since 1.6.30
+ *
+ * @return void
+ */
+ public static function begin() {
+ add_filter( 'upload_dir', array( __CLASS__, 'filter_upload_dir' ) );
+ add_filter( 'wp_handle_upload_prefilter', array( __CLASS__, 'randomize_filename' ) );
+ add_filter( 'wp_handle_sideload_prefilter', array( __CLASS__, 'randomize_filename' ) );
+
+ self::ensure_directory();
+ }
+
+ /**
+ * Stop routing uploads into the protected directory.
+ *
+ * @since 1.6.30
+ *
+ * @return void
+ */
+ public static function end() {
+ remove_filter( 'upload_dir', array( __CLASS__, 'filter_upload_dir' ) );
+ remove_filter( 'wp_handle_upload_prefilter', array( __CLASS__, 'randomize_filename' ) );
+ remove_filter( 'wp_handle_sideload_prefilter', array( __CLASS__, 'randomize_filename' ) );
+ }
+
+ /**
+ * Point the upload path and URL at the protected directory.
+ *
+ * The base directory is left alone so the stored relative path still
+ * resolves through get_attached_file() after the filter is removed.
+ *
+ * @since 1.6.30
+ *
+ * @param array $uploads Upload directory data.
+ *
+ * @return array
+ */
+ public static function filter_upload_dir( $uploads ) {
+ $subdir = '/' . self::DIR . $uploads['subdir'];
+
+ $uploads['path'] = $uploads['basedir'] . $subdir;
+ $uploads['url'] = $uploads['baseurl'] . $subdir;
+ $uploads['subdir'] = $subdir;
+
+ return $uploads;
+ }
+
+ /**
+ * Replace the client file name with a random one, keeping the extension.
+ *
+ * @since 1.6.30
+ *
+ * @param array $file Upload data from $_FILES or a sideload.
+ *
+ * @return array
+ */
+ public static function randomize_filename( $file ) {
+ if ( ! is_array( $file ) || empty( $file['name'] ) || ! is_string( $file['name'] ) ) {
+ return $file;
+ }
+
+ $file['name'] = wp_generate_password( 32, false, false ) . self::extension( $file['name'] );
+
+ return $file;
+ }
+
+ /**
+ * Absolute path of the protected directory.
+ *
+ * @since 1.6.30
+ *
+ * @return string Empty string when uploads are unavailable.
+ */
+ public static function get_base_dir() {
+ $uploads = wp_upload_dir( null, false );
+
+ if ( ! empty( $uploads['error'] ) || empty( $uploads['basedir'] ) ) {
+ return '';
+ }
+
+ return trailingslashit( $uploads['basedir'] ) . self::DIR;
+ }
+
+ /**
+ * Create the protected directory and its deny rules.
+ *
+ * @since 1.6.30
+ *
+ * @return bool Whether the directory and deny rules exist.
+ */
+ public static function ensure_directory() {
+ $dir = self::get_base_dir();
+
+ if ( '' === $dir || ! wp_mkdir_p( $dir ) ) {
+ return false;
+ }
+
+ $files = array(
+ '.htaccess' => "# Files here are served by weForms after an access check.n<IfModule mod_authz_core.c>ntRequire all deniedn</IfModule>n<IfModule !mod_authz_core.c>ntOrder deny,allowntDeny from alln</IfModule>n",
+ 'web.config' => "<?xml version="1.0" encoding="UTF-8"?>n<configuration>nt<system.webServer>ntt<authorization>nttt<deny users="*" />ntt</authorization>nt</system.webServer>n</configuration>n",
+ 'index.php' => "<?phpn// Silence is golden.n",
+ );
+
+ $ok = true;
+
+ foreach ( $files as $name => $contents ) {
+ $path = $dir . '/' . $name;
+
+ if ( file_exists( $path ) ) {
+ continue;
+ }
+
+ // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
+ if ( false === file_put_contents( $path, $contents ) ) {
+ $ok = false;
+ }
+ }
+
+ return $ok;
+ }
+
+ /**
+ * Make a new form upload private and mark it for the download handler.
+ *
+ * @since 1.6.30
+ *
+ * @param int $attach_id Attachment ID.
+ * @param string $original_name Optional client file name to use as the title.
+ *
+ * @return void
+ */
+ public static function protect( $attach_id, $original_name = '' ) {
+ $attach_id = absint( $attach_id );
+ $attachment = $attach_id ? get_post( $attach_id ) : null;
+
+ if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
+ return;
+ }
+
+ $update = array();
+
+ if ( 'private' !== $attachment->post_status || 0 !== (int) $attachment->post_parent ) {
+ $update['post_status'] = 'private';
+ $update['post_parent'] = 0;
+ }
+
+ $title = is_string( $original_name ) ? sanitize_text_field( preg_replace( '/.[^.]+$/', '', wp_basename( $original_name ) ) ) : '';
+
+ if ( '' !== $title && $title !== $attachment->post_title ) {
+ $update['post_title'] = $title;
+ }
+
+ if ( $update ) {
+ $update['ID'] = $attach_id;
+ wp_update_post( wp_slash( $update ) );
+ }
+
+ if ( '' !== self::resolve_path( $attach_id ) ) {
+ update_post_meta( $attach_id, self::META, 1 );
+ }
+ }
+
+ /**
+ * Whether the attachment is stored in the protected directory.
+ *
+ * @since 1.6.30
+ *
+ * @param int $attach_id Attachment ID.
+ *
+ * @return bool
+ */
+ public static function is_protected( $attach_id ) {
+ $attach_id = absint( $attach_id );
+
+ return $attach_id && (bool) get_post_meta( $attach_id, self::META, true );
+ }
+
+ /**
+ * Download handler URL for a protected upload.
+ *
+ * @since 1.6.30
+ *
+ * @param int $attach_id Attachment ID.
+ * @param string $file Optional image size file name.
+ * @param bool $signed Whether to add a key that works without login
+ * until SIGNED_URL_TTL passes.
+ *
+ * @return string
+ */
+ public static function get_url( $attach_id, $file = '', $signed = false ) {
+ $args = array(
+ 'action' => self::ACTION,
+ 'id' => absint( $attach_id ),
+ );
+
+ if ( '' !== $file ) {
+ $args['file'] = wp_basename( $file );
+ }
+
+ if ( $signed ) {
+ $args['expires'] = time() + self::SIGNED_URL_TTL;
+ $args['key'] = self::sign( $attach_id, $args['expires'] );
+ }
+
+ return add_query_arg( rawurlencode_deep( $args ), admin_url( 'admin-ajax.php' ) );
+ }
+
+ /**
+ * URL to put in a notification email.
+ *
+ * Protected uploads get a signed link so recipients who are not logged in
+ * can still open the file.
+ *
+ * @since 1.6.30
+ *
+ * @param int $attach_id Attachment ID.
+ *
+ * @return string|false
+ */
+ public static function get_notification_url( $attach_id ) {
+ if ( self::is_protected( $attach_id ) ) {
+ return self::get_url( $attach_id, '', true );
+ }
+
+ return wp_get_attachment_url( $attach_id );
+ }
+
+ /**
+ * Signature for a no-login link to one attachment.
+ *
+ * @since 1.6.30
+ *
+ * @param int $attach_id Attachment ID.
+ * @param int $expires Unix time the link stops working.
+ *
+ * @return string
+ */
+ public static function sign( $attach_id, $expires ) {
+ return wp_hash( self::ACTION . '|' . absint( $attach_id ) . '|' . absint( $expires ) );
+ }
+
+ /**
+ * Whether the current request may read a protected upload.
+ *
+ * @since 1.6.30
+ *
+ * @param int $attach_id Attachment ID.
+ * @param string $key Signed key from a notification link.
+ * @param int $expires Expiry time from the same link.
+ *
+ * @return bool
+ */
+ public static function can_view( $attach_id, $key = '', $expires = 0 ) {
+ $attach_id = absint( $attach_id );
+
+ if ( ! self::is_protected( $attach_id ) ) {
+ return false;
+ }
+
+ if ( current_user_can( weforms_form_access_capability() ) || current_user_can( 'read_post', $attach_id ) ) {
+ return true;
+ }
+
+ $expires = absint( $expires );
+
+ if ( is_string( $key ) && '' !== $key && $expires >= time() && hash_equals( self::sign( $attach_id, $expires ), $key ) ) {
+ return true;
+ }
+
+ /**
+ * The visitor who uploaded the file may preview it until the entry
+ * that claims it is saved.
+ */
+ if ( absint( get_post_meta( $attach_id, '_weforms_entry_id', true ) ) ) {
+ return false;
+ }
+
+ $session = weforms_get_upload_session_key( false );
+ $stored = (string) get_post_meta( $attach_id, '_weforms_upload_key', true );
+
+ return $session && '' !== $stored && hash_equals( $stored, wp_hash( $session ) );
+ }
+
+ /**
+ * Absolute path of the original file or one of its image sizes.
+ *
+ * @since 1.6.30
+ *
+ * @param int $attach_id Attachment ID.
+ * @param string $file Optional image size file name.
+ *
+ * @return string Empty string when the file is missing or outside the protected directory.
+ */
+ public static function resolve_path( $attach_id, $file = '' ) {
+ $main = get_attached_file( $attach_id );
+ $base = self::get_base_dir();
+
+ if ( ! $main || '' === $base ) {
+ return '';
+ }
+
+ $allowed = array( wp_basename( $main ) );
+ $meta = wp_get_attachment_metadata( $attach_id );
+
+ if ( is_array( $meta ) ) {
+ if ( ! empty( $meta['original_image'] ) ) {
+ $allowed[] = wp_basename( $meta['original_image'] );
+ }
+
+ if ( ! empty( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
+ foreach ( $meta['sizes'] as $size ) {
+ if ( ! empty( $size['file'] ) ) {
+ $allowed[] = wp_basename( $size['file'] );
+ }
+ }
+ }
+ }
+
+ $name = '' === $file ? wp_basename( $main ) : wp_basename( $file );
+
+ if ( ! in_array( $name, $allowed, true ) ) {
+ return '';
+ }
+
+ $path = realpath( dirname( $main ) . '/' . $name );
+ $base_real = realpath( $base );
+
+ if ( ! $path || ! $base_real || 0 !== strpos( $path, $base_real . DIRECTORY_SEPARATOR ) || ! is_file( $path ) ) {
+ return '';
+ }
+
+ return $path;
+ }
+
+ /**
+ * Use the download handler for protected upload URLs.
+ *
+ * @since 1.6.30
+ *
+ * @param string $url Attachment URL.
+ * @param int $attach_id Attachment ID.
+ *
+ * @return string
+ */
+ public static function filter_attachment_url( $url, $attach_id ) {
+ return self::is_protected( $attach_id ) ? self::get_url( $attach_id, '', self::$signing > 0 ) : $url;
+ }
+
+ /**
+ * Resolve image sizes of protected uploads to download handler URLs.
+ *
+ * Core builds size URLs by swapping the file name at the end of the
+ * attachment URL, which does not work for a query-string URL.
+ *
+ * @since 1.6.30
+ *
+ * @param array|false $out Short-circuit value.
+ * @param int $attach_id Attachment ID.
+ * @param string|int[] $size Requested size.
+ *
+ * @return array|false
+ */
+ public static function filter_image_downsize( $out, $attach_id, $size ) {
+ if ( false !== $out || ! self::is_protected( $attach_id ) || ! wp_attachment_is_image( $attach_id ) ) {
+ return $out;
+ }
+
+ $meta = wp_get_attachment_metadata( $attach_id );
+
+ if ( ! is_array( $meta ) ) {
+ return $out;
+ }
+
+ $intermediate = 'full' === $size ? false : image_get_intermediate_size( $attach_id, $size );
+
+ if ( $intermediate && ! empty( $intermediate['file'] ) ) {
+ return array(
+ self::get_url( $attach_id, $intermediate['file'], self::$signing > 0 ),
+ (int) $intermediate['width'],
+ (int) $intermediate['height'],
+ true,
+ );
+ }
+
+ $width = isset( $meta['width'] ) ? (int) $meta['width'] : 0;
+ $height = isset( $meta['height'] ) ? (int) $meta['height'] : 0;
+
+ if ( $width && $height ) {
+ list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
+ }
+
+ return array( self::get_url( $attach_id, '', self::$signing > 0 ), $width, $height, false );
+ }
+
+ /**
+ * Drop srcset for protected uploads; core would build public URLs.
+ *
+ * @since 1.6.30
+ *
+ * @param array|false $sources Srcset sources.
+ * @param array $size_array Width and height.
+ * @param string $image_src Image src.
+ * @param array $image_meta Image meta.
+ * @param int $attachment_id Attachment ID.
+ *
+ * @return array|false
+ */
+ public static function filter_image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ) {
+ return self::is_protected( $attachment_id ) ? false : $sources;
+ }
+
+ /**
+ * Point Media Library size URLs of protected uploads at the handler.
+ *
+ * @since 1.6.30
+ *
+ * @param array $response Attachment data for JS.
+ * @param WP_Post $attachment Attachment post.
+ *
+ * @return array
+ */
+ public static function filter_attachment_for_js( $response, $attachment ) {
+ if ( empty( $response['sizes'] ) || ! is_array( $response['sizes'] ) || ! self::is_protected( $attachment->ID ) ) {
+ return $response;
+ }
+
+ $meta = wp_get_attachment_metadata( $attachment->ID );
+
+ foreach ( $response['sizes'] as $name => $data ) {
+ $file = '';
+
+ if ( 'full' !== $name && isset( $meta['sizes'][ $name ]['file'] ) ) {
+ $file = $meta['sizes'][ $name ]['file'];
+ }
+
+ $response['sizes'][ $name ]['url'] = self::get_url( $attachment->ID, $file );
+ }
+
+ return $response;
+ }
+
+ /**
+ * Stream a protected upload after the access check.
+ *
+ * @since 1.6.30
+ *
+ * @return void
+ */
+ public static function serve() {
+ // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only download; access is checked below.
+ $attach_id = isset( $_GET['id'] ) && is_scalar( $_GET['id'] ) ? absint( $_GET['id'] ) : 0;
+ $file = isset( $_GET['file'] ) && is_scalar( $_GET['file'] ) ? sanitize_file_name( wp_unslash( $_GET['file'] ) ) : '';
+ $key = isset( $_GET['key'] ) && is_scalar( $_GET['key'] ) ? sanitize_text_field( wp_unslash( $_GET['key'] ) ) : '';
+ $expires = isset( $_GET['expires'] ) && is_scalar( $_GET['expires'] ) ? absint( $_GET['expires'] ) : 0;
+ // phpcs:enable
+
+ $path = self::can_view( $attach_id, $key, $expires ) ? self::resolve_path( $attach_id, $file ) : '';
+
+ if ( '' === $path ) {
+ wp_die( esc_html__( 'File not found.', 'weforms' ), '', array( 'response' => 404 ) );
+ }
+
+ $type = wp_check_filetype( $path );
+ $mime = ! empty( $type['type'] ) ? $type['type'] : 'application/octet-stream';
+ $ext = ! empty( $type['ext'] ) ? '.' . $type['ext'] : '';
+
+ $inline = in_array( $mime, array( 'image/jpeg', 'image/png', 'image/gif', 'image/webp' ), true );
+ $title = sanitize_file_name( (string) get_post_field( 'post_title', $attach_id ) );
+ $name = ( '' !== $title ? $title : 'file' ) . $ext;
+
+ while ( ob_get_level() ) {
+ ob_end_clean();
+ }
+
+ nocache_headers();
+ header( 'Content-Type: ' . $mime );
+ header( 'Content-Disposition: ' . ( $inline ? 'inline' : 'attachment' ) . '; filename="' . $name . '"' );
+ header( 'Content-Length: ' . filesize( $path ) );
+ header( 'X-Content-Type-Options: nosniff' );
+ header( "Content-Security-Policy: default-src 'none'; sandbox" );
+
+ readfile( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile
+ exit;
+ }
+
+ /**
+ * Make existing form uploads private, up to $limit per call.
+ *
+ * This hides them from public media queries. Files that belong to a
+ * weForms form are then moved by migrate_legacy_files(). Updated rows
+ * leave the query, so the next call picks up where this one stopped.
+ *
+ * @since 1.6.30
+ *
+ * @param int $limit Attachments per call.
+ *
+ * @return void
+ */
+ public static function maybe_migrate_legacy_uploads( $limit = 200 ) {
+ if ( get_option( self::MIGRATED_OPTION ) ) {
+ return;
+ }
+
+ global $wpdb;
+
+ $limit = max( 1, absint( $limit ) );
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery
+ $ids = $wpdb->get_col(
+ $wpdb->prepare(
+ "SELECT DISTINCT p.ID FROM {$wpdb->posts} p
+ INNER JOIN {$wpdb->postmeta} m ON m.post_id = p.ID
+ WHERE p.post_type = 'attachment'
+ AND p.post_status = 'inherit'
+ AND p.post_parent = 0
+ AND m.meta_key IN ( '_weforms_upload_key', '_weforms_entry_id', 'attachment_form_id' )
+ ORDER BY p.ID
+ LIMIT %d",
+ $limit
+ )
+ );
+
+ foreach ( $ids as $id ) {
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery
+ $wpdb->update( $wpdb->posts, array( 'post_status' => 'private' ), array( 'ID' => (int) $id ) );
+ clean_post_cache( (int) $id );
+ }
+
+ if ( count( $ids ) < $limit ) {
+ update_option( self::MIGRATED_OPTION, 1 );
+ }
+ }
+
+ /**
+ * Move earlier form uploads into protected storage, in batches, for up to
+ * five seconds per admin request.
+ *
+ * Only attachments tied to a weForms entry or form are moved. Links to the
+ * old public path stop working; entry screens use the handler URL.
+ *
+ * @since 1.6.30
+ *
+ * @param int $limit Attachments per batch.
+ *
+ * @return void
+ */
+ public static function migrate_legacy_files( $limit = 20 ) {
+ if ( get_option( self::FILES_MIGRATED_OPTION ) || get_transient( self::FILES_MIGRATED_OPTION . '_lock' ) ) {
+ return;
+ }
+
+ set_transient( self::FILES_MIGRATED_OPTION . '_lock', 1, MINUTE_IN_SECONDS );
+
+ $started = microtime( true );
+
+ do {
+ $done = self::migrate_legacy_files_batch( $limit );
+ } while ( ! $done && microtime( true ) - $started < 5 );
+
+ if ( $done ) {
+ update_option( self::FILES_MIGRATED_OPTION, 1 );
+ }
+
+ delete_transient( self::FILES_MIGRATED_OPTION . '_lock' );
+ }
+
+ /**
+ * Move one batch of earlier form uploads.
+ *
+ * @since 1.6.30
+ *
+ * @param int $limit Attachments per batch.
+ *
+ * @return bool Whether no eligible attachments remain.
+ */
+ private static function migrate_legacy_files_batch( $limit ) {
+ global $wpdb;
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery
+ $ids = $wpdb->get_col(
+ $wpdb->prepare(
+ "SELECT DISTINCT p.ID FROM {$wpdb->posts} p
+ INNER JOIN {$wpdb->postmeta} m ON m.post_id = p.ID
+ WHERE p.post_type = 'attachment'
+ AND m.meta_key IN ( '_weforms_entry_id', 'attachment_form_id' )
+ AND NOT EXISTS (
+ SELECT 1 FROM {$wpdb->postmeta} x
+ WHERE x.post_id = p.ID AND x.meta_key IN ( %s, %s )
+ )
+ ORDER BY p.ID
+ LIMIT %d",
+ self::META,
+ self::MOVE_FAILED_META,
+ absint( $limit )
+ )
+ );
+
+ foreach ( $ids as $id ) {
+ if ( ! self::move_into_protected_storage( (int) $id ) ) {
+ update_post_meta( (int) $id, self::MOVE_FAILED_META, 1 );
+ }
+ }
+
+ return count( $ids ) < absint( $limit );
+ }
+
+ /**
+ * Move one attachment and its image sizes into protected storage.
+ *
+ * @since 1.6.30
+ *
+ * @param int $attach_id Attachment ID.
+ *
+ * @return bool Whether the attachment is now