name = 'upload_file';
$this->label = __( 'Upload File', 'frontend-admin' );
$this->public = false;
$this->defaults = array(
'return_format' => 'array',
'preview_size' => 'thumbnail',
'library' => 'all',
'min_width' => 0,
'min_height' => 0,
'min_size' => 0,
'max_width' => 0,
'max_height' => 0,
'max_size' => 0,
'mime_types' => '',
'show_preview' => true,
'button_text' => __( 'Add File', 'frontend-admin' ),
'no_file_text' => __( 'No file selected', 'frontend-admin' ),
);
// actions
add_action( 'wp_ajax_acf/fields/upload_file/add_attachment', array( $this, 'ajax_add_attachment' ) );
add_action( 'wp_ajax_nopriv_acf/fields/upload_file/add_attachment', array( $this, 'ajax_add_attachment' ) );
//atachment metadata
add_action( 'wp_ajax_acf/fields/upload_file/update_meta', array( $this, 'update_meta' ) );
add_action( 'wp_ajax_nopriv_acf/fields/upload_file/update_meta', array( $this, 'update_meta' ) );
add_action( 'pre_get_posts', [ $this, 'hide_uploads_media_list_view' ] );
add_filter( 'ajax_query_attachments_args', [ $this, 'hide_uploads_media_overlay_view' ] );
$file_fields = array( 'file', 'image', 'upload_file', 'featured_image', 'main_image', 'site_logo', 'upload_image' );
foreach ( $file_fields as $type ) {
add_filter( 'acf/prepare_field/type=' . $type, array( $this, 'prepare_image_or_file_field' ), 5 );
add_filter( 'acf/pre_update_value/type=' . $type, array( $this, 'update_file_value' ), 8, 4 );
add_filter( 'acf/pre_update_value/type=' . $type, array( $this, 'move_single_file' ), 9, 4 );
add_filter( 'acf/validate_value/type=' . $type, array( $this, 'validate_file_value' ), 5, 4 );
add_action( 'acf/render_field_settings/type=' . $type, array( $this, 'upload_button_text_setting' ) );
add_action( 'acf/render_field_settings/type=' . $type, array( $this, 'extra_file_settings' ) );
if( 'image' == $type || 'upload_image' == $type ){
add_filter( 'acf/update_field/type='.$type, [ $this, 'update_local_avatar' ] );
add_action( 'acf/render_field_settings/type=' . $type, array( $this, 'local_avatar_setting' ) );
}
}
$gallery_fields = array( 'gallery', 'product_images', 'upload_files' );
foreach ( $gallery_fields as $type ) {
add_action( 'acf/render_field_settings/type=' . $type, array( $this, 'extra_file_settings' ) );
add_filter( 'acf/pre_update_value/type=' . $type, array( $this, 'move_folders' ), 9, 4 );
}
$file_fields = array_merge( $file_fields, $gallery_fields );
if ( defined( 'HAPPYFILES_VERSION' ) ) {
foreach ( $file_fields as $type ) {
add_action( 'acf/render_field_settings/type=' . $type, array( $this, 'happy_folders_setting' ) );
}
add_filter( 'ajax_query_attachments_args', array( $this, 'happy_files_folder' ) );
}
add_action('init', [$this, 'handle_file_upload_request']);
}
function handle_file_upload_request() {
// Check if it's a file upload request.
if ( empty($_GET['fea-file-upload']) || empty( $_GET['file'] ) ) return;
$file = sanitize_text_field(wp_unslash($_GET['file']));
//check nonce
if ( empty( $_GET['nonce'] ) || wp_verify_nonce( $_GET['nonce'], 'fea-file-upload_'. $file ) === false ) {
wp_die(esc_html__('Invalid nonce.', 'frontend-admin'), '403 Forbidden', ['response' => 403]);
}
$upload_dir = wp_upload_dir();
$file_path = $upload_dir['basedir'] . '/' . $file;
$real_file_path = realpath( $file_path );
if ($real_file_path === false || strpos($real_file_path, $upload_dir['basedir']) !== 0) {
wp_die(esc_html__('Invalid file path.', 'frontend-admin'), '400 Bad Request', ['response' => 400]);
}
// Ensure the file exists.
if (!file_exists( $real_file_path )) {
wp_die(esc_html__('File not found.', 'frontend-admin'), '404 Not Found', ['response' => 404]);
}
// Check permissions.
$attachment_id = attachment_url_to_postid($upload_dir['baseurl'] . '/' . $file);
$uploader_id = get_post_field('post_author', $attachment_id);
$current_user = wp_get_current_user();
if (
!$current_user->exists() || // User not logged in
($uploader_id != $current_user->ID && !current_user_can('administrator') && !current_user_can('editor'))
) {
wp_die(esc_html__('Unauthorized access.', 'frontend-admin'), '403 Forbidden', ['response' => 403]);
}
// Serve the file with proper headers.
header('Content-Type: ' . mime_content_type($real_file_path));
header('Content-Disposition: inline; filename="' . basename($real_file_path) . '"');
readfile($real_file_path); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile -- streams a protected upload after the access checks above.
exit;
}
/**
* Hide attachment files from the Media Library's overlay (modal) view
* if they have a certain meta key set.
*
* @param array $args An array of query variables.
*/
function hide_uploads_media_overlay_view( $args ) {
// Bail if this is not the admin area.
if ( ! is_admin() ) {
return $args;
}
// Modify the query.
$args['meta_query'] = [
[
'key' => '_hide_from_library',
'compare' => 'NOT EXISTS',
]
];
return $args;
}
/**
* Hide attachment files from the Media Library's list view
* if they have a certain meta key set.
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
function hide_uploads_media_list_view( $query ) {
// Bail if this is not the admin area.
if ( ! is_admin() ) {
return;
}
// Bail if this is not the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Only proceed if this the attachment upload screen.
$screen = get_current_screen();
if ( ! $screen || 'upload' !== $screen->id || 'attachment' !== $screen->post_type ) {
return;
}
// Modify the query.
$query->set( 'meta_query', [
[
'key' => '_hide_from_library',
'compare' => 'NOT EXISTS',
]
] );
return;
}
function extra_file_settings( $field ) {
acf_render_field_setting(
$field,
array(
'label' => __( 'Custom Directory', 'frontend-admin' ),
'name' => 'custom_directory',
'type' => 'true_false',
'ui' => 1,
'instructions' => __( "Save files in a custom directory under the wp-content/uploads directory", 'frontend-admin' ),
)
);
acf_render_field_setting(
$field,
array(
'label' => __( 'Folder Name', 'frontend-admin' ),
'placeholder' => '[post:type]',
'type' => 'text',
'dynamic_value_choices' => 1,
'name' => 'custom_directory_name',
'conditions' => array(
array(
array(
'field' => 'custom_directory',
'operator' => '==',
'value' => 1,
),
),
),
)
);
if( fea_instance()->is_license_active() ){
acf_render_field_setting(
$field,
array(
'label' => __( 'Secure Directory', 'frontend-admin' ),
'name' => 'secure_directory',
'type' => 'true_false',
'ui' => 1,
'instructions' => __( "Block external access to this directory. (Takes affect when file is added. Requires .htaccess support)", 'frontend-admin' ),
'conditions' => array(
array(
array(
'field' => 'custom_directory',
'operator' => '==',
'value' => 1,
),
),
),
)
);
}
acf_render_field_setting(
$field,
array(
'label' => __( 'Hide from library', 'frontend-admin' ),
'name' => 'hide_from_library',
'type' => 'true_false',
'ui' => 1,
'instructions' => __( "Files will not appear in the WP library", 'frontend-admin' ),
)
);
if( 'file' !== $field['type'] && 'image' !== $field['type'] ){
// allowed types
acf_render_field_setting(
$field,
array(
'label' => __( 'Allowed file types', 'frontend-admin' ),
'instructions' => __( 'Comma separated list. Leave blank for all types', 'frontend-admin' ),
'type' => 'text',
'default_value' => 'php',
'name' => 'mime_types',
)
);
}
}
function happy_folders_setting( $field ) {
acf_render_field_setting(
$field,
array(
'label' => __( 'Happy Files Folder', 'frontend-admin' ),
'instructions' => __( 'Limit the media library choice to specific Happy Files Categories', 'frontend-admin' ),
'type' => 'radio',
'name' => 'happy_files_folder',
'layout' => 'horizontal',
'default_value' => 'all',
'choices' => $this->get_happy_files_folders(),
)
);
}
function get_happy_files_folders() {
$folders = array( 'all' => __( 'All Folders', 'frontend-admin' ) );
$taxonomies = get_terms(
array(
'taxonomy' => 'happyfiles_category',
'hide_empty' => false,
)
);
if ( empty( $taxonomies ) ) {
return $folders;
}
foreach ( $taxonomies as $category ) {
$folders[ $category->name ] = ucfirst( esc_html( $category->name ) );
}
return $folders;
}
function happy_files_folder( $query ) {
if ( empty( $query['_acfuploader'] ) ) {
return $query;
}
// load field
$field = acf_get_field( $query['_acfuploader'] );
if ( ! $field ) {
return $query;
}
if ( ! isset( $field['happy_files_folder'] ) || $field['happy_files_folder'] == 'all' ) {
return $query;
}
if ( isset( $query['tax_query'] ) ) {
$tax_query = $query['tax_query'];
} else {
$tax_query = array();
}
$tax_query[] = array(
'taxonomy' => 'happyfiles_category',
'field' => 'name',
'terms' => $field['happy_files_folder'],
);
$query['tax_query'] = $tax_query;
return $query;
}
public function upload_file( $path, $filename, $secure = false){
$pos = strrpos($filename, '.');
$ext = substr($filename, $pos);
$newname = substr($filename, 0, $pos);
if( $secure ){
$newname .= '-' . uniqid() . '';
}
$newpath = $path.'/'.$newname . $ext;
$counter = 1;
while (file_exists($newpath)) {
$newname = $newname .'-'. $counter;
$newpath = $path.'/'.$newname . $ext;
$counter++;
}
return $newpath;
}
/**
* validate_attachment
*
* This function will validate an attachment based on a field's restrictions and return an array of errors
*
* @since 5.2.3
*
* @param $attachment (array) attachment data. Changes based on context
* @param $field (array) field settings containing restrictions
* @param context (string) $file is different when uploading / preparing
* @return $errors (array)
*/
function validate_attachment( $attachment, $field, $context = 'prepare' ) {
// vars
$errors = array();
$file = array(
'type' => '',
'width' => 0,
'height' => 0,
'size' => 0,
);
// upload
if ( $context == 'upload' ) {
// vars
$file['type'] = pathinfo( $attachment['name'], PATHINFO_EXTENSION );
$file['size'] = filesize( $attachment['tmp_name'] );
if ( strpos( $attachment['type'], 'image' ) !== false ) {
$size = getimagesize( $attachment['tmp_name'] );
$file['width'] = feadmin_maybe_get( $size, 0 );
$file['height'] = feadmin_maybe_get( $size, 1 );
}
// prepare
} elseif ( $context == 'prepare' ) {
$use_path = isset( $attachment['filename'] ) ? $attachment['filename'] : $attachment['url'];
$file['type'] = pathinfo( $use_path, PATHINFO_EXTENSION );
$file['size'] = feadmin_maybe_get( $attachment, 'filesizeInBytes', 0 );
$file['width'] = feadmin_maybe_get( $attachment, 'width', 0 );
$file['height'] = feadmin_maybe_get( $attachment, 'height', 0 );
// custom
} else {
$file = array_merge( $file, $attachment );
$use_path = isset( $attachment['filename'] ) ? $attachment['filename'] : $attachment['url'];
$file['type'] = pathinfo( $use_path, PATHINFO_EXTENSION );
}
// image
if ( $file['width'] || $file['height'] ) {
// width
$min_width = (int) feadmin_maybe_get( $field, 'min_width', 0 );
$max_width = (int) feadmin_maybe_get( $field, 'max_width', 0 );
if ( $file['width'] ) {
if ( $min_width && $file['width'] < $min_width ) {
// min width
$errors['min_width'] = sprintf( /* translators: %d: number */ __( 'Image width must be at least %dpx.', 'frontend-admin' ), $min_width );
} elseif ( $max_width && $file['width'] > $max_width ) {
// min width
$errors['max_width'] = sprintf( /* translators: %d: number */ __( 'Image width must not exceed %dpx.', 'frontend-admin' ), $max_width );
}
}
// height
$min_height = (int) feadmin_maybe_get( $field, 'min_height', 0 );
$max_height = (int) feadmin_maybe_get( $field, 'max_height', 0 );
if ( $file['height'] ) {
if ( $min_height && $file['height'] < $min_height ) {
// min height
$errors['min_height'] = sprintf( /* translators: %d: number */ __( 'Image height must be at least %dpx.', 'frontend-admin' ), $min_height );
} elseif ( $max_height && $file['height'] > $max_height ) {
// min height
$errors['max_height'] = sprintf( /* translators: %d: number */ __( 'Image height must not exceed %dpx.', 'frontend-admin' ), $max_height );
}
}
}
// file size
if ( $file['size'] ) {
$min_size = feadmin_maybe_get( $field, 'min_size', 0 );
$max_size = feadmin_maybe_get( $field, 'max_size', 0 );
if ( $min_size && $file['size'] < acf_get_filesize( $min_size ) ) {
// min width
$errors['min_size'] = sprintf( /* translators: %s: value */ __( 'File size must be at least %s.', 'frontend-admin' ), acf_format_filesize( $min_size ) );
} elseif ( $max_size && $file['size'] > acf_get_filesize( $max_size ) ) {
// min width
$errors['max_size'] = sprintf( /* translators: %s: value */ __( 'File size must not exceed %s.', 'frontend-admin' ), acf_format_filesize( $max_size ) );
}
}
// a file with no extension can not be checked, so it is never accepted
if ( 'upload' === $context && ! $file['type'] ) {
$errors['mime_types'] = __( 'This file type is not allowed.', 'frontend-admin' );
}
// file type
if ( $file['type'] ) {
$mime_types = feadmin_maybe_get( $field, 'mime_types', '' );
// lower case
$file['type'] = strtolower( $file['type'] );
$mime_types = strtolower( $mime_types );
// explode
$mime_types = str_replace( array( ' ', '.' ), '', $mime_types );
$mime_types = explode( ',', $mime_types ); // split pieces
$mime_types = array_filter( $mime_types ); // remove empty pieces
if ( ! empty( $mime_types ) && ! in_array( $file['type'], $mime_types ) ) {
// glue together last 2 types
if ( count( $mime_types ) > 1 ) {
$last1 = array_pop( $mime_types );
$last2 = array_pop( $mime_types );
$mime_types[] = $last2 . ' ' . __( 'or', 'frontend-admin' ) . ' ' . $last1;
}
$errors['mime_types'] = sprintf( /* translators: %s: value */ __( 'File type must be %s.', 'frontend-admin' ), implode( ', ', $mime_types ) );
}else{
$wp_filetype = wp_check_filetype( basename( $attachment['name'] ), null );
$allowed_types = get_allowed_mime_types();
if( ! in_array( $wp_filetype['type'], $allowed_types ) ){
$errors['mime_types'] = sprintf( /* translators: %s: value */ __( 'Cannot upload %s files.', 'frontend-admin' ), $file['type'] );
}
}
}
/**
* Filters the errors for a file before it is uploaded or displayed in the media modal.
*
* @since 5.2.3
*
* @param array $errors An array of errors.
* @param array $file An array of data for a single file.
* @param array $attachment An array of attachment data which differs based on the context.
* @param array $field The field array.
* @param string $context The curent context (uploading, preparing)
*/
$errors = apply_filters( "frontend_admin/validate_attachment/type={$field['type']}", $errors, $file, $attachment, $field, $context );
$errors = apply_filters( "frontend_admin/validate_attachment/name={$field['_name']}", $errors, $file, $attachment, $field, $context );
$errors = apply_filters( "frontend_admin/validate_attachment/key={$field['key']}", $errors, $file, $attachment, $field, $context );
$errors = apply_filters( 'frontend_admin/validate_attachment', $errors, $file, $attachment, $field, $context );
// return
return $errors;
}
function ajax_add_attachment() {
$args = acf_parse_args(
$_POST,
array(
'field_key' => '',
'nonce' => '',
)
);
// validate nonce
if ( ! feadmin_verify_ajax() ) {
wp_send_json_error( __( 'Authentication Error. Please try refreshing the page.', 'frontend-admin' ) );
}
// bail early if no attachments
if ( empty( $_FILES['file']['name'] ) ) {
wp_send_json_error( __( 'Missing file name', 'frontend-admin' ) );
}
// TO dos: validate file types, sizes, and dimensions
// Add loading bar for each image
$field = $args['field_key'] ? fea_instance()->frontend->get_field( $args['field_key'] ) : false;
// only accept files for an actual file or image field
if ( empty( $field['type'] ) || ! in_array( $field['type'], feadmin_get_upload_field_types(), true ) ) {
wp_send_json_error( __( 'Invalid Key', 'frontend-admin' ) );
}
$file = $_FILES['file'];
//sanitize file name
$file['name'] = sanitize_file_name( $file['name'] );
// The file must have an extension WordPress allows for the current user, and
// for images the content must match it. A file with no extension, or one
// WordPress does not allow (HTML, JavaScript, SVG...), is never stored.
$checked_type = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'] );
if ( empty( $checked_type['ext'] ) || empty( $checked_type['type'] ) || ! in_array( $checked_type['type'], get_allowed_mime_types(), true ) ) {
wp_send_json_error( __( 'This file type is not allowed.', 'frontend-admin' ) );
}
if ( ! empty( $checked_type['proper_filename'] ) ) {
$file['name'] = sanitize_file_name( $checked_type['proper_filename'] );
}
// get errors
$errors = $this->validate_attachment( $file, $field, 'upload' );
// append error
if ( ! empty( $errors ) ) {
$data = implode( "\n", $errors );
wp_send_json_error( $data );
}
$wp_filetype = array( 'type' => $checked_type['type'] );
$wp_upload_dir = wp_upload_dir();
$submissions_dir = $this->maybe_mkdir( $wp_upload_dir['basedir'] . '/fea-submissions', true );
$url = $this->upload_file($submissions_dir,$file['name'], true);
if ( ! move_uploaded_file( $file['tmp_name'], $url ) ) { // phpcs:ignore Generic.PHP.ForbiddenFunctions.Found -- moves the validated upload into the submissions folder.
wp_send_json_error( __( 'The file could not be saved.', 'frontend-admin' ) );
}
$attachment = array(
'guid' => $url,
'post_mime_type' => $wp_filetype['type'],
'post_status' => 'inherit',
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file['name'] ) ),
);
$attach_id = wp_insert_attachment( $attachment, $url );
$attach_url = wp_get_attachment_url( $attach_id );
if ( ! empty( $field['hide_from_library'] ) ) {
update_post_meta( $attach_id, '_hide_from_library', true );
}
if( $attach_id instanceof WP_Error ){
wp_send_json_error( $attach_id->get_error_message() );
}
feadmin_mark_upload_owner( $attach_id );
if ( ! empty( $value['alt'] ) ) {
update_post_meta( $attach_id, '_wp_attachment_image_alt', $value['alt'] );
}
wp_send_json_success( [ 'id' => $attach_id, 'url' => $attach_url ] );
}
function update_meta() {
$args = acf_parse_args(
$_POST,
array(
'attach_id' => '',
'url' => '',
'nonce' => '',
)
);
// validate nonce
if ( ! feadmin_verify_ajax() ) {
wp_send_json_error( __( 'Authentication Error. Please try refreshing the page.', 'frontend-admin' ) );
}
// bail early if no attachments
if ( empty( $args['attach_id'] ) ) {
wp_send_json_error( __( 'Missing attachment id', 'frontend-admin' ) );
}
$attach_id = (int) $args['attach_id'];
if ( ! feadmin_can_edit_uploaded_attachment( $attach_id ) ) {
wp_send_json_error( __( 'You do not have permission to edit this file.', 'frontend-admin' ) );
}
$path = get_attached_file( $attach_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $path );
wp_update_attachment_metadata( $attach_id, $attach_data );
wp_send_json_success();
}
function maybe_mkdir( $submissions_dir, $secure = false ){
if ( ! is_dir( $submissions_dir ) ) {
wp_mkdir_p( $submissions_dir );
//add index.php file to prevent directory listing
if( $secure ){
if ( ! file_exists( $submissions_dir . '/index.php' ) ) {
touch( $submissions_dir . '/index.php' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_touch -- empty index.php that stops directory listing.
}
}else{
if ( file_exists( $submissions_dir . '/index.php' ) ) {
wp_delete_file( $submissions_dir . '/index.php' );
}
}
}
// Uploaded files are served with the type their extension maps to and are
// never sniffed, so nothing in this folder can be rendered as HTML.
// This replaces the legacy redirect rules that used to live here.
$_htaccess = $submissions_dir . '/.htaccess';
$rules = "