diff --git a/inc/wplf-ajax.php b/inc/wplf-ajax.php index 1bcebe6..93530bb 100644 --- a/inc/wplf-ajax.php +++ b/inc/wplf-ajax.php @@ -65,6 +65,11 @@ function wplf_ajax_submit_handler() { $should_store_images_in_medialibrary = get_post_meta( $form->ID, '_wplf_media_library', true ); $counter = 0; foreach ( $_FILES as $key => $file ) { + // Optional file inputs may be submitted without a file. + if ( isset( $file['error'] ) && UPLOAD_ERR_NO_FILE === $file['error'] ) { + continue; + } + // Is this enough security wise? // Currenly only supports 1 file per input if ( $should_store_images_in_medialibrary ) { @@ -77,11 +82,24 @@ function wplf_ajax_submit_handler() { add_post_meta( $post_id, $key . '_attachment', $attach_id ); } } else { - $name = 'lf_' . date( 'ymdhs' ) . '-' . $counter . '-' . sanitize_file_name( $file['name'] ); + if ( ! function_exists( 'wp_handle_upload' ) ) { + require_once ABSPATH . 'wp-admin/includes/file.php'; + } + + // Keep WordPress's upload, size and allowed-type checks enabled. + $file['name'] = 'lf_' . date( 'ymdhs' ) . '-' . $counter . '-' . sanitize_file_name( $file['name'] ); + $uploaded = wp_handle_upload( $file, array( 'test_form' => false ) ); + + if ( isset( $uploaded['error'] ) ) { + $return->ok = 0; + $return->error = $uploaded['error']; + wp_send_json( $return ); + wp_die(); + return; + } - move_uploaded_file( $file['tmp_name'], $uploads_path['path'] . '/' . $name ); - add_post_meta( $post_id, $key . '_attachment', $uploads_path['url'] . '/' . $name ); - $counter++; + add_post_meta( $post_id, $key . '_attachment', $uploaded['url'] ); + $counter++; } }