*/
function acscf_allowed_extensions() {
$allowed = array(
'jpg',
'jpeg',
'png',
'gif',
'webp',
'pdf',
'doc',
'docx',
'xls',
'xlsx',
'ppt',
'pptx',
'txt',
'csv',
'zip',
);
/**
* Filters the hard allow list of attachment extensions.
*
* @param array $allowed Lower case extensions.
*/
return (array) apply_filters( 'acscf_allowed_extensions', $allowed );
}
/**
* Hard upper bound for a single attachment, in bytes.
*
* @return int
*/
function acscf_max_upload_bytes() {
$limit = 20 * 1024 * 1024;
/**
* Filters the hard upper bound for a single attachment.
*
* @param int $limit Bytes.
*/
return (int) apply_filters( 'acscf_max_upload_bytes', $limit );
}
/**
* Base directory used to store attachments, created and protected on demand.
*
* @return array{path:string,url:string}
*/
function acscf_get_storage_dir() {
$uploads = wp_upload_dir();
$path = trailingslashit( $uploads['basedir'] ) . 'acs-contact-form';
if ( ! file_exists( $path ) ) {
wp_mkdir_p( $path );
}
$htaccess = trailingslashit( $path ) . '.htaccess';
if ( ! file_exists( $htaccess ) ) {
$rules = "# Files stored by ACS Contact Form are served through the admin only.\n";
$rules .= "\n\tRequire all denied\n\n";
$rules .= "\n\tOrder allow,deny\n\tDeny from all\n\n";
acscf_write_protection_file( $htaccess, $rules );
}
$index = trailingslashit( $path ) . 'index.php';
if ( ! file_exists( $index ) ) {
acscf_write_protection_file( $index, " $path,
'url' => trailingslashit( $uploads['baseurl'] ) . 'acs-contact-form',
);
}
/**
* Write a small protection file through the filesystem API.
*
* @param string $file Absolute path.
* @param string $contents File contents.
* @return void
*/
function acscf_write_protection_file( $file, $contents ) {
global $wp_filesystem;
if ( ! function_exists( 'WP_Filesystem' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
if ( ! $wp_filesystem ) {
WP_Filesystem();
}
if ( $wp_filesystem ) {
$wp_filesystem->put_contents( $file, $contents, FS_CHMOD_FILE );
}
}
/**
* Generate a random, unguessable file name.
*
* @param string $dir Target directory.
* @param string $name Original name.
* @param string $ext Extension including the leading dot.
* @return string
*/
function acscf_unique_filename( $dir, $name, $ext ) {
unset( $name );
$ext = strtolower( $ext );
do {
$candidate = 'acscf-' . gmdate( 'Ymd' ) . '-' . wp_generate_password( 16, false, false ) . $ext;
} while ( file_exists( trailingslashit( $dir ) . $candidate ) );
return $candidate;
}
/**
* Point wp_handle_upload() at the plugin's own storage directory.
*
* @param array $dirs Upload directory data.
* @return array
*/
function acscf_filter_upload_dir( $dirs ) {
// Derive the paths from what WordPress passes in. Calling wp_upload_dir()
// here would run this same filter again.
$base = trailingslashit( $dirs['basedir'] ) . 'acs-contact-form';
$url = trailingslashit( $dirs['baseurl'] ) . 'acs-contact-form';
$sub = '/' . gmdate( 'Y/m' );
$dirs['basedir'] = $base;
$dirs['baseurl'] = $url;
$dirs['subdir'] = $sub;
$dirs['path'] = $base . $sub;
$dirs['url'] = $url . $sub;
return $dirs;
}
/**
* Validate one attachment before it is moved into place.
*
* Kept separate from the upload loop so that the rules can be exercised on
* their own: size limit, per form extension allow list, and a check that the
* real contents match the claimed extension.
*
* @param string $original Original file name.
* @param string $tmp_name Temporary path of the uploaded file.
* @param int $size File size in bytes.
* @param array $form_allowed Lower case extensions accepted by this form.
* @param int $max_size_bytes Maximum size in bytes.
* @return true|WP_Error
*/
function acscf_validate_attachment( $original, $tmp_name, $size, $form_allowed, $max_size_bytes ) {
if ( (int) $size > (int) $max_size_bytes ) {
/* translators: %s: file name. */
return new WP_Error( 'file_too_large', sprintf( __( 'The file "%s" is too large.', 'acs-contact-form' ), $original ) );
}
$ext = strtolower( pathinfo( $original, PATHINFO_EXTENSION ) );
if ( '' === $ext || ! in_array( $ext, (array) $form_allowed, true ) || ! in_array( $ext, acscf_allowed_extensions(), true ) ) {
/* translators: %s: file name. */
return new WP_Error( 'invalid_file_type', sprintf( __( 'The file type of "%s" is not allowed.', 'acs-contact-form' ), $original ) );
}
$checked = wp_check_filetype_and_ext( $tmp_name, $original );
if ( empty( $checked['ext'] ) || empty( $checked['type'] ) || ! in_array( strtolower( $checked['ext'] ), (array) $form_allowed, true ) ) {
/* translators: %s: file name. */
return new WP_Error( 'invalid_file_content', sprintf( __( 'The contents of "%s" do not match its file extension.', 'acs-contact-form' ), $original ) );
}
return true;
}
/**
* Handle the uploaded attachments of one submission.
*
* @param int $form_id Form post ID.
* @param array $file_settings Per form attachment settings.
* @param array $files The $_FILES entry for the attachment input, already unslashed by the caller.
* @return array|WP_Error List of array( name, file, size ), or an error.
*/
function acscf_handle_uploads( $form_id, $file_settings, $files = array() ) {
unset( $form_id );
if ( ! is_array( $files ) || empty( $files['name'] ) || ! is_array( $files['name'] ) || '' === $files['name'][0] ) {
if ( isset( $file_settings['required'] ) && '1' === $file_settings['required'] ) {
return new WP_Error( 'file_required', __( 'No file was selected.', 'acs-contact-form' ) );
}
return array();
}
require_once ABSPATH . 'wp-admin/includes/file.php';
$names = array_map( 'sanitize_file_name', (array) $files['name'] );
$tmp_names = isset( $files['tmp_name'] ) ? array_map( 'sanitize_text_field', (array) $files['tmp_name'] ) : array();
$errors = isset( $files['error'] ) ? array_map( 'intval', (array) $files['error'] ) : array();
$sizes = isset( $files['size'] ) ? array_map( 'intval', (array) $files['size'] ) : array();
$types = isset( $files['type'] ) ? array_map( 'sanitize_text_field', (array) $files['type'] ) : array();
$max_count = isset( $file_settings['max_count'] ) ? (int) $file_settings['max_count'] : 3;
if ( $max_count < 1 ) {
$max_count = 3;
}
$max_size = isset( $file_settings['max_size'] ) ? (float) $file_settings['max_size'] : 5;
if ( $max_size <= 0 ) {
$max_size = 5;
}
$max_size_bytes = (int) min( $max_size * 1024 * 1024, acscf_max_upload_bytes() );
$hard_allowed = acscf_allowed_extensions();
$form_allowed = array();
$configured = isset( $file_settings['types'] ) ? (string) $file_settings['types'] : '';
foreach ( explode( ',', $configured ) as $ext ) {
$ext = strtolower( trim( str_replace( '.', '', $ext ) ) );
if ( '' !== $ext && in_array( $ext, $hard_allowed, true ) ) {
$form_allowed[] = $ext;
}
}
if ( empty( $form_allowed ) ) {
$form_allowed = array( 'jpg', 'jpeg', 'png', 'gif', 'pdf' );
}
$count = count( $names );
if ( $count > $max_count ) {
/* translators: %d: maximum number of attachments. */
return new WP_Error( 'too_many_files', sprintf( __( 'Too many attachments. You can attach up to %d files.', 'acs-contact-form' ), $max_count ) );
}
$stored = array();
// Make sure the protected directory exists before the filter is in place.
acscf_get_storage_dir();
add_filter( 'upload_dir', 'acscf_filter_upload_dir' );
for ( $i = 0; $i < $count; $i++ ) {
$error = isset( $errors[ $i ] ) ? $errors[ $i ] : UPLOAD_ERR_NO_FILE;
if ( UPLOAD_ERR_NO_FILE === $error ) {
continue;
}
$original = isset( $names[ $i ] ) ? $names[ $i ] : '';
$tmp_name = isset( $tmp_names[ $i ] ) ? $tmp_names[ $i ] : '';
$size = isset( $sizes[ $i ] ) ? $sizes[ $i ] : 0;
if ( UPLOAD_ERR_OK !== $error || '' === $tmp_name || ! is_uploaded_file( $tmp_name ) ) {
remove_filter( 'upload_dir', 'acscf_filter_upload_dir' );
acscf_delete_stored_files( $stored );
return new WP_Error( 'upload_failed', __( 'The upload failed. Please try again.', 'acs-contact-form' ) );
}
$validation = acscf_validate_attachment( $original, $tmp_name, $size, $form_allowed, $max_size_bytes );
if ( is_wp_error( $validation ) ) {
remove_filter( 'upload_dir', 'acscf_filter_upload_dir' );
acscf_delete_stored_files( $stored );
return $validation;
}
// wp_handle_upload() takes its first argument by reference.
$upload_data = array(
'name' => $original,
'type' => isset( $types[ $i ] ) ? $types[ $i ] : '',
'tmp_name' => $tmp_name,
'error' => $error,
'size' => $size,
);
$upload = wp_handle_upload(
$upload_data,
array(
'test_form' => false,
'mimes' => acscf_allowed_mimes( $form_allowed ),
'unique_filename_callback' => 'acscf_unique_filename',
)
);
if ( ! is_array( $upload ) || isset( $upload['error'] ) || empty( $upload['file'] ) ) {
remove_filter( 'upload_dir', 'acscf_filter_upload_dir' );
acscf_delete_stored_files( $stored );
return new WP_Error( 'upload_failed', __( 'The upload failed. Please try again.', 'acs-contact-form' ) );
}
$stored[] = array(
'name' => $original,
'file' => $upload['file'],
'size' => (int) $size,
);
}
remove_filter( 'upload_dir', 'acscf_filter_upload_dir' );
return $stored;
}
/**
* Build the mime map for the accepted extensions.
*
* @param array $extensions Lower case extensions.
* @return array
*/
function acscf_allowed_mimes( $extensions ) {
$all = wp_get_mime_types();
$mimes = array();
foreach ( $all as $pattern => $mime ) {
foreach ( explode( '|', $pattern ) as $ext ) {
if ( in_array( $ext, $extensions, true ) ) {
$mimes[ $pattern ] = $mime;
break;
}
}
}
return $mimes;
}
/**
* Delete one stored attachment, refusing anything outside the storage directory.
*
* @param string $file Absolute path.
* @return bool
*/
function acscf_delete_stored_file( $file ) {
if ( ! is_string( $file ) || '' === $file ) {
return false;
}
$storage = acscf_get_storage_dir();
$base = wp_normalize_path( trailingslashit( $storage['path'] ) );
$target = wp_normalize_path( $file );
if ( 0 !== strpos( $target, $base ) || false !== strpos( $target, '../' ) ) {
return false;
}
if ( ! file_exists( $target ) ) {
return false;
}
wp_delete_file( $target );
return true;
}
/**
* Delete a list of stored attachments.
*
* @param array $files List of array( file ) or plain paths.
* @return void
*/
function acscf_delete_stored_files( $files ) {
if ( ! is_array( $files ) ) {
return;
}
foreach ( $files as $file ) {
$path = is_array( $file ) && isset( $file['file'] ) ? $file['file'] : $file;
if ( is_string( $path ) ) {
acscf_delete_stored_file( $path );
}
}
}
/**
* Backwards compatible alias kept for sites that hooked into version 1.
*
* @param array $file_paths List of absolute paths.
* @return void
*/
function acscf_cleanup_temp_files( $file_paths ) {
acscf_delete_stored_files( $file_paths );
}