\admin_url( 'admin-ajax.php' ),
'nonce' => \wp_create_nonce( 'afsrreloaded_import' ),
'processing' => __( 'Processing...', 'add-from-server-reloaded' ),
'complete' => __( 'Import Complete!', 'add-from-server-reloaded' ),
'error' => __( 'An error occurred. Please try again.', 'add-from-server-reloaded' ),
)
);
\add_filter( 'plugin_action_links_' . \plugin_basename( AFSRRELOADED_PLUGIN_FILE ), array( $this, 'add_upload_link' ) );
// Handle the path selection early.
$this->path_selection_cookie();
}
/**
* Register admin menu.
*
* @since 4.0.0
*/
public function admin_menu() {
$page_slug = \add_menu_page(
__( 'Add From Server Reloaded', 'add-from-server-reloaded' ),
__( 'Add From Server', 'add-from-server-reloaded' ),
'upload_files',
'add-from-server-reloaded',
array( $this, 'menu_page' ),
'dashicons-upload',
30
);
\add_action( 'load-' . $page_slug, function() {
\wp_enqueue_style( 'add-from-server-reloaded' );
\wp_enqueue_script( 'add-from-server-reloaded' );
// Handle settings save.
$this->handle_settings_save();
} );
// Set page title to avoid deprecation warnings.
\add_filter( 'admin_title', array( $this, 'set_admin_page_title' ), 10, 2 );
}
/**
* Set admin page title.
*
* @since 5.0.0
*
* @param string $admin_title The page title.
* @param string $title The original title.
* @return string
*/
public function set_admin_page_title( $admin_title, $title ) {
$screen = \get_current_screen();
if ( $screen && 'add-from-server-reloaded' === $screen->id ) {
return \__( 'Add From Server Reloaded', 'add-from-server-reloaded' ) . $admin_title;
}
return $admin_title;
}
/**
* Add plugin action links.
*
* @since 4.0.0
*
* @param array $links Plugin action links.
* @return array
*/
public function add_upload_link( $links ) {
if ( current_user_can( 'upload_files' ) ) {
array_unshift(
$links,
'' . __( 'Import Files', 'add-from-server-reloaded' ) . ''
);
}
return $links;
}
/**
* Render the menu page.
*
* @since 4.0.0
*/
public function menu_page() {
// Set page title.
global $title;
$title = \__( 'Add From Server Reloaded', 'add-from-server-reloaded' );
// Handle any imports.
$this->handle_imports();
echo '
';
echo '
' . esc_html__( 'Add From Server Reloaded', 'add-from-server-reloaded' ) . '
';
$this->outdated_options_notice();
$this->main_content();
echo '';
}
/**
* Get the root directory for file browsing.
*
* @since 4.0.0
*
* @return string|false Root path or false on error.
*/
public function get_root() {
// Priority order for root directory:
// 1. User-saved setting in WordPress options.
// 2. The 'ADD_FROM_SERVER_RELOADED' constant.
// 3. Their home directory.
// 4. The parent directory of the current install or wp-content directory.
$saved_root = \get_option( 'afsrreloaded_root_directory', '' );
if ( ! empty( $saved_root ) ) {
$root = $saved_root;
} elseif ( defined( 'ADD_FROM_SERVER_RELOADED' ) ) {
$root = ADD_FROM_SERVER_RELOADED;
} elseif ( defined( 'ADD_FROM_SERVER' ) ) {
// Backwards compatibility.
$root = ADD_FROM_SERVER;
} elseif ( str_starts_with( __FILE__, '/home/' ) ) {
$root = implode( '/', array_slice( explode( '/', __FILE__ ), 0, 3 ) );
} else {
if ( str_starts_with( WP_CONTENT_DIR, ABSPATH ) ) {
$root = dirname( ABSPATH );
} else {
$root = dirname( WP_CONTENT_DIR );
}
}
// Normalize separators and strip trailing slash for consistent comparisons.
$root = \untrailingslashit( \wp_normalize_path( $root ) );
// Precautions: Validate root path exists and is readable.
if ( ! \is_dir( $root ) || ! \is_readable( $root ) ) {
// Guessed path wasn't accessible (common on locked-down shared hosting).
// Fall back to ABSPATH — this is always readable since WP itself runs from here.
$root = \untrailingslashit( \wp_normalize_path( \ABSPATH ) );
if ( ! \is_dir( $root ) || ! \is_readable( $root ) ) {
// Last resort: uploads folder is always readable/writable by WP.
$uploads = \wp_upload_dir( null, false );
$root = ! empty( $uploads['basedir'] ) ? \untrailingslashit( \wp_normalize_path( $uploads['basedir'] ) ) : false;
}
}
// Canonicalize when possible so symlink / relative roots compare safely.
if ( $root ) {
$resolved_root = \realpath( $root );
if ( false !== $resolved_root ) {
$root = \untrailingslashit( \wp_normalize_path( $resolved_root ) );
}
}
// Additional security check for placeholder code.
if (
$root &&
str_contains( get_option( 'frmsvr_root', '%' ), '%' ) &&
! defined( 'ADD_FROM_SERVER_RELOADED' ) &&
! defined( 'ADD_FROM_SERVER' ) &&
! current_user_can( 'unfiltered_html' )
) {
$root = false;
}
/**
* Filters the root directory path.
*
* @since 4.0.0
*
* @param string|false $root Root directory path or false.
*/
return apply_filters( 'afsrreloaded_root_directory', $root );
}
/**
* Check whether a path is inside the allowed root directory.
*
* A plain "starts with root" check is not enough. If the root is `/path/app`,
* a sibling like `/path/app2/file` would incorrectly match. After resolving
* paths, we only allow the root itself or paths under `root/`.
*
* @since 5.2.2
*
* @param string $path Absolute filesystem path to validate.
* @param string|false $root Optional root directory. Defaults to get_root().
* @return bool True when the path is the root or inside it.
*/
public function is_path_within_root( $path, $root = null ) {
if ( null === $root ) {
$root = $this->get_root();
}
if ( ! \is_string( $path ) || '' === $path || ! \is_string( $root ) || '' === $root ) {
return false;
}
$root_real = \realpath( $root );
$path_real = \realpath( $path );
if ( false === $root_real || false === $path_real ) {
return false;
}
return self::path_has_root_boundary( $path_real, $root_real );
}
/**
* Compare resolved paths and require a real folder boundary under the root.
*
* Kept as a static helper so tests can cover this without loading a full
* WordPress request.
*
* @since 5.2.2
*
* @param string $path Absolute path (preferably from realpath()).
* @param string $root Absolute root path (preferably from realpath()).
* @return bool True when $path is $root or a child under $root/.
*/
public static function path_has_root_boundary( $path, $root ) {
if ( ! \is_string( $path ) || '' === $path || ! \is_string( $root ) || '' === $root ) {
return false;
}
$path = \wp_normalize_path( $path );
$root = \untrailingslashit( \wp_normalize_path( $root ) );
if ( '' === $root ) {
return false;
}
if ( $path === $root ) {
return true;
}
$root_with_boundary = $root . '/';
if ( \str_starts_with( $path, $root_with_boundary ) ) {
return true;
}
// Windows paths are case-insensitive.
if ( 'Windows' === \PHP_OS_FAMILY ) {
return (
0 === \strcasecmp( $path, $root )
|| 0 === \strncasecmp( $path, $root_with_boundary, \strlen( $root_with_boundary ) )
);
}
return false;
}
/**
* Handle settings save.
*
* @since 4.0.6
*/
protected function handle_settings_save() {
if ( ! isset( $_POST['afsrreloaded_save_settings'] ) ) {
return;
}
if ( ! \current_user_can( 'manage_options' ) ) {
return;
}
\check_admin_referer( 'afsrreloaded_settings' );
$new_root = isset( $_POST['afsrreloaded_root_directory'] ) ? \sanitize_text_field( \wp_unslash( $_POST['afsrreloaded_root_directory'] ) ) : '';
if ( empty( $new_root ) ) {
\delete_option( 'afsrreloaded_root_directory' );
\add_settings_error(
'afsrreloaded_settings',
'afsrreloaded_root_cleared',
__( 'Root directory reset to default.', 'add-from-server-reloaded' ),
'success'
);
return;
}
// Validate the path (normalize by removing trailing slash).
$new_root = \untrailingslashit( \wp_normalize_path( $new_root ) );
if ( ! \is_dir( $new_root ) ) {
\add_settings_error(
'afsrreloaded_settings',
'afsrreloaded_invalid_path',
\sprintf(
/* translators: %s: directory path */
__( 'Error: The directory "%s" does not exist on your server.', 'add-from-server-reloaded' ),
\esc_html( $new_root )
),
'error'
);
return;
}
if ( ! \is_readable( $new_root ) ) {
\add_settings_error(
'afsrreloaded_settings',
'afsrreloaded_not_readable',
\sprintf(
/* translators: %s: directory path */
__( 'Error: The directory "%s" is not readable. Please check file permissions.', 'add-from-server-reloaded' ),
\esc_html( $new_root )
),
'error'
);
return;
}
\update_option( 'afsrreloaded_root_directory', $new_root );
\add_settings_error(
'afsrreloaded_settings',
'afsrreloaded_root_saved',
\sprintf(
/* translators: %s: directory path */
__( 'Root directory updated! Now browsing: %s', 'add-from-server-reloaded' ),
'' . \esc_html( $new_root ) . ''
),
'success'
);
}
/**
* Handle path selection cookie.
*
* @since 4.0.0
*/
public function path_selection_cookie() {
if ( isset( $_REQUEST['path'] ) && current_user_can( 'upload_files' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
// Sanitize the path.
$path = sanitize_text_field( wp_unslash( $_REQUEST['path'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
// Verify path is within allowed root.
$root = $this->get_root();
if ( ! $root ) {
return;
}
$full_path = realpath( trailingslashit( $root ) . ltrim( $path, '/' ) );
// Security: Ensure the path is within root (directory boundary).
if ( ! $this->is_path_within_root( $full_path, $root ) ) {
return;
}
$_COOKIE[ COOKIE ] = $path;
$admin_url_parts = wp_parse_url( admin_url() );
setcookie(
COOKIE,
$path,
time() + 30 * DAY_IN_SECONDS,
isset( $admin_url_parts['path'] ) ? $admin_url_parts['path'] : '/',
isset( $admin_url_parts['host'] ) ? $admin_url_parts['host'] : '',
'https' === ( isset( $admin_url_parts['scheme'] ) ? $admin_url_parts['scheme'] : 'http' ),
true
);
}
}
/**
* Handle file imports.
*
* @since 4.0.0
*/
public function handle_imports() {
if ( empty( $_POST['files'] ) && empty( $_POST['folders'] ) ) {
return;
}
check_admin_referer( 'afsrreloaded_import' );
$files = isset( $_POST['files'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['files'] ) ) : array();
$folders = isset( $_POST['folders'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['folders'] ) ) : array();
$selected_files = $files;
$root = $this->get_root();
if ( ! $root ) {
wp_die( esc_html__( 'Unable to determine root directory. Please check your configuration.', 'add-from-server-reloaded' ) );
}
// Get all files from selected folders.
$folder_files = array();
$blocked_files = array();
foreach ( $folders as $folder ) {
$folder_path = trailingslashit( $root ) . ltrim( $folder, '/' );
$folder_files = array_merge( $folder_files, $this->get_files_from_folder( $folder_path, $root, $blocked_files ) );
}
// Merge folder files with individually selected files.
$files = array_merge( $files, $folder_files );
// Enable output buffering for progress updates.
if ( ! defined( 'DOING_AJAX' ) ) {
flush();
if ( function_exists( 'wp_ob_end_flush_all' ) ) {
wp_ob_end_flush_all();
}
}
$imported = 0;
$errors = 0;
$duplicates = 0;
$skipped_selected = array();
$error_files = array();
$imported_files = array();
$duplicate_files = array();
foreach ( (array) $files as $file ) {
$filename = trailingslashit( $root ) . ltrim( $file, '/' );
// Security: Verify the real path to prevent directory traversal / boundary bypass.
$realpath = realpath( $filename );
if ( ! $this->is_path_within_root( $realpath, $root ) ) {
$errors++;
$error_files[] = array(
'filename' => basename( $file ),
'message' => __( 'Security error: file is outside the allowed directory', 'add-from-server-reloaded' ),
);
continue;
}
// If user selected specific files, skip restricted ones with a clear message.
if ( ! empty( $selected_files ) && in_array( $file, $selected_files, true ) && $this->is_restricted_file( $realpath ) ) {
$skipped_selected[] = array(
'filename' => basename( $file ),
'message' => __( 'This file was not imported due to security restrictions.', 'add-from-server-reloaded' ),
);
continue;
}
$id = $this->handle_import_file( $realpath );
if ( \is_wp_error( $id ) ) {
if ( 'file_exists' === $id->get_error_code() ) {
$duplicates++;
$duplicate_files[] = array(
'filename' => basename( $file ),
'message' => $id->get_error_message(),
);
} else {
$errors++;
$error_files[] = array(
'filename' => basename( $file ),
'message' => $id->get_error_message(),
);
}
} else {
$imported++;
$imported_files[] = array(
'filename' => basename( $file ),
'id' => $id,
);
}
if ( ! defined( 'DOING_AJAX' ) ) {
flush();
}
}
// Single summary message.
if ( $imported > 0 || $errors > 0 || $duplicates > 0 || ! empty( $blocked_files ) || ! empty( $skipped_selected ) ) {
$message_class = ( $errors > 0 ) ? 'notice-warning' : 'notice-success';
echo '';
if ( $imported > 0 ) {
echo '';
echo sprintf(
/* translators: %d: number of files */
\esc_html( \_n( '%d file imported successfully.', '%d files imported successfully.', $imported, 'add-from-server-reloaded' ) ),
absint( $imported )
);
echo '';
if ( ! empty( $folders ) ) {
// Show uploaded folder names when folder import is used.
echo '
';
foreach ( $folders as $folder ) {
$folder_name = basename( $folder ) ?: $folder;
echo '' . esc_html( $folder_name ) . ' ' . esc_html__( 'folder uploaded.', 'add-from-server-reloaded' ) . '
';
}
echo '';
}
if ( ! empty( $imported_files ) ) {
// Show imported file names (works for folder and direct selection).
echo '
';
foreach ( $imported_files as $file ) {
$edit_link = admin_url( 'post.php?post=' . $file['id'] . '&action=edit' );
echo '' . esc_html( $file['filename'] ) . '
';
}
echo '';
}
}
if ( $duplicates > 0 ) {
if ( $imported > 0 ) {
echo '
';
}
echo '';
echo sprintf(
/* translators: %d: number of duplicates */
esc_html( _n( '%d file already exists in Media Library.', '%d files already exist in Media Library.', $duplicates, 'add-from-server-reloaded' ) ),
absint( $duplicates )
);
echo '';
if ( ! empty( $duplicate_files ) ) {
echo '
';
foreach ( $duplicate_files as $dup ) {
echo '' . esc_html( $dup['filename'] ) . ': ' . wp_kses_post( $dup['message'] ) . '
';
}
echo '';
}
}
if ( $errors > 0 ) {
if ( $imported > 0 ) {
echo '
';
}
echo '';
echo sprintf(
/* translators: %d: number of errors */
\esc_html( \_n( '%d file failed.', '%d files failed.', $errors, 'add-from-server-reloaded' ) ),
absint( $errors )
);
echo '';
// Show error details.
if ( ! empty( $error_files ) && empty( $folders ) && ! empty( $selected_files ) ) {
echo '
';
foreach ( $error_files as $error ) {
echo '' . \esc_html( $error['filename'] ) . ': ' . \wp_kses_post( $error['message'] ) . '
';
}
echo '';
}
}
if ( ! empty( $blocked_files ) ) {
if ( $imported > 0 || $errors > 0 || $duplicates > 0 ) {
echo '
';
}
echo '';
echo sprintf(
/* translators: %d: number of blocked files */
\esc_html( \_n( '%d file was skipped for security reasons.', '%d files were skipped for security reasons.', count( $blocked_files ), 'add-from-server-reloaded' ) ),
absint( count( $blocked_files ) )
);
echo '';
$restricted_list = implode( ', ', array_map( 'strtoupper', $this->get_restricted_extensions() ) );
echo '
';
echo sprintf(
/* translators: %s: comma-separated list of restricted extensions */
esc_html__( 'Some files in the selected folders were not imported because their file types are not allowed: %s.', 'add-from-server-reloaded' ),
esc_html( $restricted_list )
);
echo '';
}
if ( ! empty( $skipped_selected ) ) {
if ( $imported > 0 || $errors > 0 || $duplicates > 0 ) {
echo '
';
}
echo '' . esc_html__( 'Some files were skipped for security reasons.', 'add-from-server-reloaded' ) . '';
echo '
';
foreach ( $skipped_selected as $skip ) {
echo '' . esc_html( $skip['filename'] ) . ': ' . esc_html( $skip['message'] ) . '
';
}
echo '';
}
echo '
';
}
}
/**
* Get restricted file extensions.
*
* @since 5.0.1
*
* @return array
*/
protected function get_restricted_extensions() {
return array( 'php', 'phtml', 'phps', 'pht', 'phar', 'exe', 'sh', 'bat', 'cmd' );
}
/**
* Check if a file is restricted from import.
*
* @since 5.0.1
*
* @param string $path File path.
* @return bool True if restricted.
*/
protected function is_restricted_file( $path ) {
$dangerous_extensions = $this->get_restricted_extensions();
$ext = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) );
if ( in_array( $ext, $dangerous_extensions, true ) ) {
return true;
}
$wp_filetype = \wp_check_filetype( $path, null );
$type = $wp_filetype['type'];
$ext_check = $wp_filetype['ext'];
if ( ( ! $type || ! $ext_check ) && ! current_user_can( 'unfiltered_upload' ) ) {
return true;
}
return false;
}
/**
* Recursively get all files from a folder.
*
* @since 4.0.5
*
* @param string $folder_path Absolute folder path.
* @param string $root Root directory path.
* @return array Array of relative file paths.
*/
protected function get_files_from_folder( $folder_path, $root, &$blocked_files = array() ) {
$files = array();
// Security: Verify the real path (directory boundary).
$realpath = \realpath( $folder_path );
if ( ! $this->is_path_within_root( $realpath, $root ) ) {
return $files;
}
$items = \glob( $realpath . '/*' );
if ( ! $items ) {
return $files;
}
foreach ( $items as $item ) {
// Skip hidden files and directories.
if ( \basename( $item )[0] === '.' ) {
continue;
}
$relative_item = \str_replace( $root, '', $item );
$relative_item = \ltrim( $relative_item, '/' );
if ( \is_dir( $item ) ) {
// Recursively get files from subdirectory.
$files = \array_merge( $files, $this->get_files_from_folder( $item, $root, $blocked_files ) );
} elseif ( \is_file( $item ) ) {
if ( $this->is_restricted_file( $item ) ) {
$blocked_files[] = $relative_item;
continue;
}
$files[] = $relative_item;
}
}
return $files;
}
/**
* AJAX handler for batch imports.
*
* @since 4.0.0
*/
public function ajax_batch_import() {
check_ajax_referer( 'afsrreloaded_import', 'nonce' );
if ( ! current_user_can( 'upload_files' ) ) {
wp_send_json_error( array( 'message' => __( 'You do not have permission to upload files.', 'add-from-server-reloaded' ) ) );
}
$file = isset( $_POST['file'] ) ? sanitize_text_field( wp_unslash( $_POST['file'] ) ) : '';
if ( empty( $file ) ) {
wp_send_json_error( array( 'message' => __( 'No file specified.', 'add-from-server-reloaded' ) ) );
}
$root = $this->get_root();
if ( ! $root ) {
wp_send_json_error( array( 'message' => __( 'Unable to determine root directory.', 'add-from-server-reloaded' ) ) );
}
$filename = trailingslashit( $root ) . ltrim( $file, '/' );
$realpath = realpath( $filename );
// Security: Verify the real path (directory boundary).
if ( ! $this->is_path_within_root( $realpath, $root ) ) {
wp_send_json_error( array(
'message' => sprintf(
/* translators: %s: file name */
__( 'Security error: %s is outside the allowed directory.', 'add-from-server-reloaded' ),
basename( $file )
)
) );
}
$id = $this->handle_import_file( $realpath );
if ( is_wp_error( $id ) ) {
wp_send_json_error( array(
'message' => $id->get_error_message(),
'file' => basename( $file ),
) );
} else {
wp_send_json_success( array(
'message' => sprintf(
/* translators: %s: file name */
__( '%s imported successfully.', 'add-from-server-reloaded' ),
basename( $file )
),
'file' => basename( $file ),
'attachment_id' => $id,
) );
}
}
/**
* AJAX handler for checking duplicates.
*
* @since 4.0.0
*/
public function ajax_check_duplicate() {
check_ajax_referer( 'afsrreloaded_import', 'nonce' );
if ( ! current_user_can( 'upload_files' ) ) {
wp_send_json_error( array( 'message' => __( 'You do not have permission.', 'add-from-server-reloaded' ) ) );
}
$file = isset( $_POST['file'] ) ? sanitize_text_field( wp_unslash( $_POST['file'] ) ) : '';
if ( empty( $file ) ) {
wp_send_json_error( array( 'message' => __( 'No file specified.', 'add-from-server-reloaded' ) ) );
}
$duplicate = $this->check_if_duplicate( $file );
if ( $duplicate ) {
wp_send_json_success( array(
'is_duplicate' => true,
'message' => sprintf(
/* translators: 1: file name, 2: attachment ID */
__( '%1$s already exists in the media library (ID: %2$d).', 'add-from-server-reloaded' ),
basename( $file ),
$duplicate
),
) );
} else {
wp_send_json_success( array(
'is_duplicate' => false,
) );
}
}
/**
* Get file hash to detect duplicates reliably.
*
* @since 5.0.2
*
* @param string $file File path.
* @return string|false File MD5 hash or false on error.
*/
protected function get_file_hash( $file ) {
if ( ! file_exists( $file ) || ! is_readable( $file ) ) {
return false;
}
$hash = md5_file( $file );
return $hash ? $hash : false;
}
/**
* Check if file is already in media library.
*
* @since 4.0.0
*
* @param string $file File path.
* @return int|false Attachment ID if duplicate found, false otherwise.
*/
protected function check_if_duplicate( $file ) {
global $wpdb;
$file = \wp_normalize_path( $file );
$filename = \basename( $file );
// First, check by file hash (most reliable).
$file_hash = $this->get_file_hash( $file );
if ( $file_hash ) {
$attachment_id = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
"SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_afsrreloaded_file_hash' AND meta_value = %s LIMIT 1",
$file_hash
)
);
if ( $attachment_id ) {
return (int) $attachment_id;
}
}
// Also check by filename in uploads directory.
$uploads = \wp_upload_dir( null, false );
if ( preg_match( '|^' . preg_quote( \wp_normalize_path( $uploads['basedir'] ), '|' ) . '(.*)$|i', $file, $mat ) ) {
$attached_file = ltrim( $mat[1], '/' );
// Query for existing attachment by exact path.
$attachment_id = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
"SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attached_file' AND meta_value = %s LIMIT 1",
$attached_file
)
);
if ( $attachment_id ) {
return (int) $attachment_id;
}
}
// Check by filename in media library.
$attachment_id = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
"SELECT p.ID FROM {$wpdb->posts} p
WHERE p.post_type = 'attachment'
AND p.guid LIKE %s
LIMIT 1",
'%/' . $wpdb->esc_like( $filename )
)
);
return $attachment_id ? (int) $attachment_id : false;
}
/**
* Handle individual file import.
*
* @since 4.0.0
*
* @param string $file Full file path.
* @return int|WP_Error Attachment ID on success, WP_Error on failure.
*/
public function handle_import_file( $file ) {
set_time_limit( 60 ); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- Set reasonable time limit per file.
$file = wp_normalize_path( $file );
// Security: Verify file exists and is readable.
if ( ! file_exists( $file ) || ! is_readable( $file ) ) {
return new WP_Error( 'file_not_readable', __( 'The file does not exist or is not readable.', 'add-from-server-reloaded' ) );
}
// Security: Prevent importing of PHP files or other dangerous types.
$dangerous_extensions = $this->get_restricted_extensions();
$ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
if ( in_array( $ext, $dangerous_extensions, true ) ) {
return new WP_Error( 'dangerous_file_type', __( 'This file type cannot be imported for security reasons.', 'add-from-server-reloaded' ) );
}
// Base the time on the file's modified time when possible.
$time = filemtime( $file );
if ( ! $time || ! is_int( $time ) ) {
$time = time();
}
// Guard against invalid or extreme file dates.
$current_time = (int) current_time( 'timestamp' );
$current_year = (int) gmdate( 'Y', $current_time );
$time_year = (int) gmdate( 'Y', $time );
if ( $time_year < 1970 || $time_year > ( $current_year + 1 ) ) {
$time = $current_time;
}
// If the file path contains a valid YYYY/MM segment, use that date.
if ( preg_match( '~/(?P\d{4})/(?P0[1-9]|1[0-2])(?:/|$)~', wp_normalize_path( $file ), $datemat ) ) {
$year = (int) $datemat['year'];
$month = (int) $datemat['month'];
if ( $year >= 1970 && $year <= ( $current_year + 1 ) ) {
$time = mktime( 0, 0, 0, $month, 1, $year );
}
}
// Get uploads info without creating new year/month folders.
$uploads = wp_upload_dir( $time, false );
if ( ! empty( $uploads['error'] ) ) {
return new WP_Error( 'upload_error', $uploads['error'] );
}
$wp_filetype = \wp_check_filetype( $file, null );
$type = $wp_filetype['type'];
$ext_check = $wp_filetype['ext'];
if ( ( ! $type || ! $ext_check ) && ! current_user_can( 'unfiltered_upload' ) ) {
return new WP_Error( 'wrong_file_type', __( 'Sorry, this file type is not permitted for security reasons.', 'add-from-server-reloaded' ) );
}
// Check if file is already in media library (duplicate detection).
$duplicate = $this->check_if_duplicate( $file );
if ( $duplicate ) {
$edit_link = \admin_url( 'post.php?post=' . $duplicate . '&action=edit' );
return new WP_Error(
'file_exists',
sprintf(
/* translators: %s: link to edit attachment */
__( 'File already exists. View in Media Library', 'add-from-server-reloaded' ),
\esc_url( $edit_link )
)
);
}
// Is the file already in the uploads folder?
if ( preg_match( '|^' . preg_quote( wp_normalize_path( $uploads['basedir'] ), '|' ) . '(.*)$|i', $file, $mat ) ) {
$filename = basename( $file );
$time = filemtime( $file ) ?: $time;
// Ensure the destination uploads folder exists for copying (use plugin prefix).
$uploads = $this->get_import_uploads_dir( $time, true );
if ( ! empty( $uploads['error'] ) ) {
return new WP_Error( 'upload_error', $uploads['error'] );
}
$target_dir = wp_normalize_path( $uploads['path'] );
$current_dir = wp_normalize_path( dirname( $file ) );
// If the file is already in the target directory, keep it.
if ( $current_dir === $target_dir ) {
$new_file = $file;
$url = $uploads['url'] . '/' . $filename;
} else {
$filename = \wp_unique_filename( $uploads['path'], $filename );
$new_file = $uploads['path'] . '/' . $filename;
// Move the file into the plugin folder.
if ( ! @rename( $file, $new_file ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename
if ( false === @copy( $file, $new_file ) ) {
return new WP_Error( 'upload_error', __( 'The selected file could not be moved to the plugin folder.', 'add-from-server-reloaded' ) );
}
@unlink( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink
}
// Set correct file permissions.
$stat = stat( dirname( $new_file ) );
$perms = $stat['mode'] & 0000666;
chmod( $new_file, $perms ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
$url = $uploads['url'] . '/' . $filename;
}
} else {
// Ensure the destination uploads folder exists for copying (use plugin prefix).
$uploads = $this->get_import_uploads_dir( $time, true );
if ( ! empty( $uploads['error'] ) ) {
return new WP_Error( 'upload_error', $uploads['error'] );
}
// File is outside uploads directory - copy it.
$filename = \wp_unique_filename( $uploads['path'], basename( $file ) );
$new_file = $uploads['path'] . '/' . $filename;
if ( false === @copy( $file, $new_file ) ) {
return new WP_Error(
'upload_error',
sprintf(
/* translators: %s: upload directory path */
__( 'The selected file could not be copied to %s.', 'add-from-server-reloaded' ),
$uploads['path']
)
);
}
// Set correct file permissions.
$stat = stat( dirname( $new_file ) );
$perms = $stat['mode'] & 0000666;
chmod( $new_file, $perms ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
// Compute the URL.
$url = $uploads['url'] . '/' . $filename;
}
// Apply upload filters.
$return = apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'sideload' );
$new_file = $return['file'];
$url = $return['url'];
$type = $return['type'];
// Generate title from filename.
$title = preg_replace( '!\.[^.]+$!', '', basename( $file ) );
$content = '';
$excerpt = '';
// Extract metadata for audio files.
if ( preg_match( '#^audio#', $type ) ) {
$meta = \wp_read_audio_metadata( $new_file );
if ( ! empty( $meta['title'] ) ) {
$title = $meta['title'];
}
if ( ! empty( $title ) ) {
if ( ! empty( $meta['album'] ) && ! empty( $meta['artist'] ) ) {
/* translators: 1: audio track title, 2: album title, 3: artist name */
$content .= sprintf( __( '"%1$s" from %2$s by %3$s.', 'add-from-server-reloaded' ), $title, $meta['album'], $meta['artist'] );
} elseif ( ! empty( $meta['album'] ) ) {
/* translators: 1: audio track title, 2: album title */
$content .= sprintf( __( '"%1$s" from %2$s.', 'add-from-server-reloaded' ), $title, $meta['album'] );
} elseif ( ! empty( $meta['artist'] ) ) {
/* translators: 1: audio track title, 2: artist name */
$content .= sprintf( __( '"%1$s" by %2$s.', 'add-from-server-reloaded' ), $title, $meta['artist'] );
} else {
/* translators: %s: audio track title */
$content .= sprintf( __( '"%s".', 'add-from-server-reloaded' ), $title );
}
} elseif ( ! empty( $meta['album'] ) ) {
if ( ! empty( $meta['artist'] ) ) {
/* translators: 1: audio album title, 2: artist name */
$content .= sprintf( __( '%1$s by %2$s.', 'add-from-server-reloaded' ), $meta['album'], $meta['artist'] );
} else {
$content .= $meta['album'] . '.';
}
} elseif ( ! empty( $meta['artist'] ) ) {
$content .= $meta['artist'] . '.';
}
if ( ! empty( $meta['year'] ) ) {
/* translators: %d: release year */
$content .= ' ' . sprintf( __( 'Released: %d.', 'add-from-server-reloaded' ), $meta['year'] );
}
if ( ! empty( $meta['track_number'] ) ) {
$track_number = explode( '/', $meta['track_number'] );
if ( isset( $track_number[1] ) ) {
/* translators: 1: track number, 2: total tracks */
$content .= ' ' . sprintf( __( 'Track %1$s of %2$s.', 'add-from-server-reloaded' ), number_format_i18n( $track_number[0] ), number_format_i18n( $track_number[1] ) );
} else {
/* translators: %s: track number */
$content .= ' ' . sprintf( __( 'Track %s.', 'add-from-server-reloaded' ), number_format_i18n( $track_number[0] ) );
}
}
if ( ! empty( $meta['genre'] ) ) {
/* translators: %s: genre */
$content .= ' ' . sprintf( __( 'Genre: %s.', 'add-from-server-reloaded' ), $meta['genre'] );
}
// Use image exif/iptc data for title and caption defaults if possible.
} elseif ( 0 === strpos( $type, 'image/' ) ) {
$image_meta = @\wp_read_image_metadata( $new_file );
if ( $image_meta && ! empty( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
$title = $image_meta['title'];
}
if ( $image_meta && ! empty( $image_meta['caption'] ) ) {
$excerpt = $image_meta['caption'];
}
}
// Construct the attachment array.
$attachment_time_local = current_time( 'mysql' );
$attachment_time_gmt = get_gmt_from_date( $attachment_time_local );
$attachment = array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => 0,
'post_title' => $title,
'post_name' => $title,
'post_content' => $content,
'post_excerpt' => $excerpt,
'post_date' => $attachment_time_local,
'post_date_gmt' => $attachment_time_gmt,
);
/**
* Filters the attachment data before import.
*
* @since 4.0.0
*
* @param array $attachment Attachment data.
* @param string $file File path.
*/
$attachment = apply_filters( 'afsrreloaded_import_attachment_data', $attachment, $file );
// Backwards compatibility filter.
$attachment = apply_filters( 'afsrreloaded_import_details', $attachment, $file, 0, 'current' );
// Save the data.
$id = \wp_insert_attachment( $attachment, $new_file, 0 );
if ( ! \is_wp_error( $id ) ) {
// Generate attachment metadata.
$data = \wp_generate_attachment_metadata( $id, $new_file );
\wp_update_attachment_metadata( $id, $data );
// Store file hash for reliable duplicate detection.
$file_hash = $this->get_file_hash( $new_file );
if ( $file_hash ) {
\update_post_meta( $id, '_afsrreloaded_file_hash', $file_hash );
}
/**
* Fires after a file has been imported.
*
* @since 4.0.0
*
* @param int $id Attachment ID.
* @param string $file File path.
*/
do_action( 'afsrreloaded_file_imported', $id, $file );
}
return $id;
}
/**
* Get the default directory.
*
* @since 4.0.0
*
* @return string Default directory path.
*/
protected function get_default_dir() {
$root = $this->get_root();
if ( ! $root ) {
return '';
}
// Always start at the configured root directory.
return $root;
}
/**
* Create the main content for the page.
*
* @since 4.0.0
*/
public function main_content() {
$url = admin_url( 'admin.php?page=add-from-server-reloaded' );
$root = $this->get_root();
if ( ! $root ) {
echo '';
echo esc_html__( 'Unable to determine root directory. Please check your configuration.', 'add-from-server-reloaded' );
echo '
';
echo sprintf(
/* translators: %s: constant name */
esc_html__( 'You can define the %s constant in your wp-config.php file to set a custom root directory.', 'add-from-server-reloaded' ),
'ADD_FROM_SERVER_RELOADED'
);
echo '
';
return;
}
$cwd = $this->get_default_dir();
if ( ! empty( $_COOKIE[ COOKIE ] ) ) {
$cookie_path = sanitize_text_field( wp_unslash( $_COOKIE[ COOKIE ] ) );
$temp_cwd = realpath( trailingslashit( $root ) . $cookie_path );
// Validate the cookie path (directory boundary).
if ( $this->is_path_within_root( $temp_cwd, $root ) ) {
$cwd = $temp_cwd;
}
}
// Validate current directory.
if ( ! $this->is_path_within_root( $cwd, $root ) ) {
$cwd = $root;
}
// Keep separators consistent with get_root() for relative-path math.
$cwd = \untrailingslashit( \wp_normalize_path( $cwd ) );
$root = \untrailingslashit( \wp_normalize_path( $root ) );
$cwd_relative = substr( $cwd, strlen( $root ) );
// Build breadcrumb navigation.
$dirparts = array();
$dirparts[] = '' . esc_html( trailingslashit( $root ) ) . ' ';
$dir_path = '';
foreach ( array_filter( explode( '/', $cwd_relative ) ) as $dir ) {
$dir_path .= '/' . $dir;
$dirparts[] = '' . esc_html( $dir ?: basename( $root ) ) . '/ ';
}
$dirparts = implode( '', $dirparts );
// Sort function for case-insensitive alphabetical sorting.
$sort_by_text = function( $a, $b ) {
return strtolower( $a['text'] ) <=> strtolower( $b['text'] );
};
// Get a list of files to show.
$nodes = glob( rtrim( $cwd, '/' ) . '/*' ) ?: array();
$directories = array_flip( array_filter( $nodes, function( $node ) {
return is_dir( $node );
} ) );
// Recursive function to find importable root.
$get_import_root = function( $path ) use ( &$get_import_root ) {
if ( ! is_readable( $path ) ) {
return false;
}
$files = glob( $path . '/*' );
if ( ! $files ) {
return false;
}
$has_files = false;
foreach ( $files as $i => $file ) {
if ( is_file( $file ) ) {
$has_files = true;
break;
} else {
if ( $get_import_root( $file ) ) {
$has_files = true;
break;
} else {
unset( $files[ $i ] );
}
}
}
if ( ! $has_files ) {
return false;
}
// Rekey the array in case anything was removed.
$files = array_values( $files );
if ( 1 === count( $files ) && is_dir( $files[0] ) ) {
return $get_import_root( $files[0] );
}
return $path;
};
$get_root_relative_path = function( $path ) use ( $root ) {
$root_offset = strlen( $root );
if ( '/' !== $root ) {
$root_offset += 1;
}
return substr( $path, $root_offset );
};
array_walk( $directories, function( &$data, $path ) use ( $root, $cwd_relative, $get_import_root, $get_root_relative_path ) {
$import_root = $get_import_root( $path );
if ( ! $import_root ) {
// Unreadable, etc.
$data = false;
return;
}
$data = array(
'text' => substr(
$get_root_relative_path( $import_root ),
strlen( $cwd_relative )
) . '/',
'path' => $get_root_relative_path( $import_root ),
);
$data['text'] = ltrim( $data['text'], '/' );
} );
$directories = array_filter( $directories );
// Sort the directories case insensitively.
uasort( $directories, $sort_by_text );
// Prefix the parent directory.
$parent_dir = dirname( $cwd );
if ( $parent_dir !== $cwd && $this->is_path_within_root( $parent_dir, $root ) ) {
$directories = array_merge(
array(
$parent_dir => array(
'text' => __( 'Parent Folder', 'add-from-server-reloaded' ),
'path' => $get_root_relative_path( $parent_dir ) ?: '/',
),
),
$directories
);
}
$files = array_flip( array_filter( $nodes, function( $node ) {
return is_file( $node );
} ) );
array_walk( $files, function( &$data, $path ) use ( $root, $get_root_relative_path ) {
$importable = ( false !== \wp_check_filetype( $path )['type'] || current_user_can( 'unfiltered_upload' ) );
$readable = is_readable( $path );
// Get file modification time.
$file_date = '';
if ( $readable && file_exists( $path ) ) {
$file_date = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), filemtime( $path ) );
}
$data = array(
'text' => basename( $path ),
'file' => $get_root_relative_path( $path ),
'importable' => $importable,
'readable' => $readable,
'size' => $readable ? size_format( filesize( $path ) ) : 'N/A',
'date' => $file_date,
'error' => (
! $importable ? 'doesnt-meet-guidelines' : (
! $readable ? 'unreadable' : false
)
),
);
} );
// Sort case insensitively.
uasort( $files, $sort_by_text );
?>
' . esc_html( $root ) . ''
);
?>
' . esc_html( $root ) . ''
);
?>
%s
',
wp_kses_post(
/* translators: %username% and %role% are literal example text that users may have entered in settings, not string placeholders. The tag links to options.php page. */
__( 'You previously used the "Root Directory" option with a placeholder, such as %username% or %role%. Unfortunately this feature is no longer supported. As a result, Add From Server has been disabled for users who have restricted upload privileges. To make this warning go away, empty the "frmsvr_root" option on options.php.', 'add-from-server-reloaded' )
)
);
}
if ( $old_root && ! str_starts_with( $old_root, $this->get_root() ) ) {
printf(
'',
wp_kses_post(
sprintf(
/* translators: 1: old root path, 2: new root path */
__( 'Warning: Root Directory changed. You previously used %1$s as your "Root Directory", this has been changed to %2$s. To restore your previous settings, add the following line to your wp-config.php file: define( "ADD_FROM_SERVER_RELOADED", "%1$s" ); To make this warning go away, empty the "frmsvr_root" option on options.php.', 'add-from-server-reloaded' ),
esc_html( $old_root ),
esc_html( $this->get_root() )
)
)
);
}
}
}