settings = SnagglySettings::get_instance(); } /** * Debug logging helper * * @param string $message * @param array $context */ protected function debug_log($message, $context = array()) { $logger = SnagglyLogger::get_instance(); $logger->debug($message, $context); } /** * Defense-in-depth authorization check for a download attributed to a * specific post. Every AJAX entry point already gates on the plugin's * own required capability (manage_options by default, but filterable * down via snaggly_required_capability) — this additionally requires * that the current user can edit the specific post a download names, * so a site that lowers the plugin capability can't let a * lower-privileged user attribute downloads to arbitrary posts. * * Only enforced when there's an actual logged-in user to check against; * programmatic callers (WP-CLI, cron) run as user 0 and have nothing * for current_user_can() to evaluate, so they're left to whatever * authorization the calling context already applied. * * Also passes when the post no longer exists: WordPress's own * current_user_can('edit_post', $id) denies unconditionally (even for * administrators) once get_post($id) comes back empty, which would * otherwise turn "the source post was deleted between scan and * download" into a permissions error instead of just skipping the * (already no-op) content-attribution step. * * @param int $post_id * @return bool */ protected function can_access_post($post_id) { if (!get_current_user_id()) { return true; } if (!get_post($post_id)) { return true; } return current_user_can('edit_post', $post_id); } /** * Get SSL verification setting with security checks * * @since 1.0.0 * @return bool Whether to verify SSL certificates */ protected function get_ssl_verify_setting() { return SnagglyUrlValidator::should_verify_ssl(); } /** * Download a single file * * @param string $url * @param int $post_id * @param bool|null $auto_update_content * @return int|WP_Error Attachment ID on success. */ public function download_file($url, $post_id = 0, $auto_update_content = null) { if (get_current_user_id() && !current_user_can('upload_files')) { return new WP_Error('forbidden_upload', __('You do not have permission to upload files.', 'snaggly')); } $this->debug_log("Starting download for URL: {$url}"); if ($post_id > 0 && !$this->can_access_post($post_id)) { $this->debug_log("Download rejected: current user cannot edit post {$post_id}"); return new WP_Error('forbidden_post', __('You do not have permission to download files for the specified post', 'snaggly')); } if (!SnagglyUrlValidator::is_safe_remote_url($url)) { return new WP_Error('unsafe_url', __('Unsafe or private URL detected', 'snaggly')); } if ($auto_update_content === null) { $auto_update_content = $this->settings->should_auto_update_content(); } // Reuse an existing image and still replace the URL in this specific post. if ($this->settings->should_group_duplicate_urls()) { $existing = get_posts(array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => $this->get_allowed_mime_types(), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Required exact original-URL lookup; limited to one attachment; no core table schema changes are made. 'meta_key' => '_snaggly_original_url', 'meta_value' => $url, 'posts_per_page' => 1, 'fields' => 'ids', )); if ($existing) { $attachment_id = (int) $existing[0]; $attachment_url = wp_get_attachment_url($attachment_id); if ($attachment_url) { if ($auto_update_content && $post_id > 0) { $this->replace_urls_in_content($post_id, array($url => $attachment_url)); } return $attachment_id; } } } $attempts = max(0, intval($this->settings->get_retry_attempts())); $last_error = null; for ($try = 0; $try <= $attempts; $try++) { if ($try > 0) { $backoff = (int) (250000 * pow(2, $try - 1)); // 0.25s, 0.5s, 1s... $this->debug_log("Retry attempt {$try} for {$url} with backoff {$backoff}us"); usleep($backoff); } $validation_result = $this->validate_file($url); if (is_wp_error($validation_result)) { $last_error = $validation_result; $this->debug_log("Validation failed for {$url}: " . $validation_result->get_error_message()); if ($try < $attempts && $this->is_transient_download_error($validation_result->get_error_code())) { continue; } return $validation_result; } $this->debug_log("Validation passed for {$url}"); $temp_file = $this->download_to_temp($url); if (is_wp_error($temp_file)) { $last_error = $temp_file; $this->debug_log("Download failed for {$url}: " . $temp_file->get_error_message()); if ($try < $attempts && $this->is_transient_download_error($temp_file->get_error_code())) { continue; } return $temp_file; } $this->debug_log("Downloaded to temp file: {$temp_file}"); $attachment_id = $this->import_to_media_library($temp_file, $url, $post_id); $this->cleanup_temp_file($temp_file); if (is_wp_error($attachment_id)) { $last_error = $attachment_id; $this->debug_log("Media import failed for {$url}: " . $attachment_id->get_error_message()); if ($try < $attempts && $this->is_transient_download_error($attachment_id->get_error_code())) { continue; } return $attachment_id; } $this->debug_log("Successfully imported {$url} as attachment ID: {$attachment_id}"); if ($auto_update_content && $post_id > 0) { $attachment_url = wp_get_attachment_url($attachment_id); if ($attachment_url) { $this->debug_log("Auto-updating content for post $post_id - replacing $url with $attachment_url"); $replacement_result = $this->replace_urls_in_content($post_id, array($url => $attachment_url)); $this->debug_log("URL replacement result: " . ($replacement_result ? 'SUCCESS' : 'FAILED')); } else { $this->debug_log("Could not get attachment URL for attachment ID: $attachment_id"); } } do_action('snaggly_after_download', $attachment_id, $url, $post_id); return $attachment_id; } return $last_error ?: new WP_Error('download_failed', __('Download failed for unknown reasons', 'snaggly')); } /** * Determine if an error code is transient (retryable) * * @param string $code * @return bool */ protected function is_transient_download_error($code) { $retryable = array( 'dns_resolution_failed', 'connection_timeout', 'url_not_accessible', 'download_failed', 'empty_download', 'invalid_response', ); return in_array($code, $retryable, true); } /** * Validate file before download * * @param string $url * @return true|WP_Error */ protected function validate_file($url) { if (!SnagglyUrlValidator::is_safe_remote_url($url)) { return new WP_Error('unsafe_url', __('Unsafe or private URL detected', 'snaggly')); } $response = (function () use ($url) { $head_response = SnagglyUrlValidator::safe_request($url, array('method' => 'HEAD', 'timeout' => $this->settings->get_download_timeout(), 'user-agent' => $this->settings->get_user_agent(), 'redirection' => 5, 'sslverify' => $this->get_ssl_verify_setting(), )); $response_code = wp_remote_retrieve_response_code($head_response); if (is_wp_error($head_response) || $response_code === 405) { $this->debug_log("HEAD request failed for {$url}, trying GET request"); return SnagglyUrlValidator::safe_request($url, array( 'timeout' => $this->settings->get_download_timeout(), 'user-agent' => $this->settings->get_user_agent(), 'redirection' => 5, 'sslverify' => $this->get_ssl_verify_setting(), 'headers' => array('Range' => 'bytes=0-1023'), 'limit_response_size' => 1024, )); } return $head_response; })(); if (is_wp_error($response)) { return $this->translate_request_error($response, $url); } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200 && $response_code !== 206) { return new WP_Error('invalid_response', sprintf( // translators: %1$d is the response code, %2$s is the URL __('Invalid response code: %1$d for URL: %2$s', 'snaggly'), $response_code, $url )); } $size_error = $this->validate_file_size($response, $url); if (is_wp_error($size_error)) { return $size_error; } return $this->validate_content_type($response, $url); } /** * Translate a WP_Error from a validation request into a friendlier, * categorized error. * * @param WP_Error $response * @param string $url * @return WP_Error */ protected function translate_request_error(WP_Error $response, $url) { $error_message = $response->get_error_message(); if (strpos($error_message, 'Could not resolve host') !== false) { return new WP_Error('dns_resolution_failed', sprintf( // translators: %1$s is the URL, %2$s is the error message __('DNS resolution failed for URL: %1$s. This may be due to local development environment restrictions or server DNS configuration. Error: %2$s', 'snaggly'), $url, $error_message )); } if (strpos($error_message, 'Connection timed out') !== false) { return new WP_Error('connection_timeout', sprintf( // translators: %1$s is the URL, %2$s is the error message __('Connection timed out for URL: %1$s. The server may be slow or unreachable. Error: %2$s', 'snaggly'), $url, $error_message )); } return new WP_Error('url_not_accessible', sprintf( // translators: %s is the error message __('URL is not accessible: %s', 'snaggly'), $error_message )); } /** * Validate the Content-Length/Content-Range header against the * configured maximum file size. * * @param array $response * @param string $url * @return true|WP_Error */ protected function validate_file_size($response, $url) { $headers = wp_remote_retrieve_headers($response); $max_size = $this->settings->get_max_file_size(); $file_size = null; if (isset($headers['content-length'])) { $file_size = intval($headers['content-length']); } elseif (isset($headers['content-range']) && preg_match('/bytes \d+-\d+\/(\d+)/', $headers['content-range'], $matches)) { $file_size = intval($matches[1]); } if ($file_size !== null && $file_size > $max_size) { return new WP_Error('file_too_large', sprintf( // translators: %1$s is the file size, %2$s is the maximum allowed size __('File size (%1$s) exceeds maximum allowed size (%2$s)', 'snaggly'), size_format($file_size), size_format($max_size) )); } return true; } /** * Validate the Content-Type header against allowed MIME types/extensions. * * @param array $response * @param string $url * @return true|WP_Error */ protected function validate_content_type($response, $url) { $headers = wp_remote_retrieve_headers($response); if (!isset($headers['content-type'])) { return true; } $content_type = strtolower(trim(explode(';', $headers['content-type'])[0])); $allowed_types_lower = array_map('strtolower', $this->get_allowed_mime_types()); $file_ext = strtolower(pathinfo((string) wp_parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION)); $allowed_extensions = $this->settings->get_allowed_extensions(); if (in_array($content_type, $allowed_types_lower, true) || in_array($file_ext, $allowed_extensions, true) || SnagglyUrlValidator::looks_like_file_url($url)) { return true; } return new WP_Error('invalid_content_type', sprintf( // translators: %1$s is the content type, %2$s is the file extension, %3$s is the URL, %4$s is the list of allowed types __('Invalid content type: %1$s and extension: %2$s for URL: %3$s. Allowed types: %4$s', 'snaggly'), $content_type, $file_ext, $url, implode(', ', $this->get_allowed_mime_types()) )); } /** * Download file to temporary location * * @param string $url * @return string|WP_Error */ protected function download_to_temp($url) { if (!SnagglyUrlValidator::is_safe_remote_url($url)) { return new WP_Error('unsafe_url', __('Unsafe or private URL detected', 'snaggly')); } if (!function_exists('wp_tempnam')) { require_once ABSPATH . 'wp-admin/includes/file.php'; } $temp_file = wp_tempnam($url); if (!$temp_file) { return new WP_Error('temp_file_failed', __('Unable to create temporary download file.', 'snaggly')); } $response = SnagglyUrlValidator::safe_request($url, array( 'timeout' => $this->settings->get_download_timeout(), 'sslverify' => $this->get_ssl_verify_setting(), 'user-agent' => $this->settings->get_user_agent(), 'limit_response_size' => $this->settings->get_max_file_size() + 1, 'stream' => true, 'filename' => $temp_file, )); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { $this->cleanup_temp_file($temp_file); $temp_file = is_wp_error($response) ? $response : new WP_Error('invalid_response', __('Download returned an unexpected HTTP status.', 'snaggly')); } if (is_wp_error($temp_file)) { return new WP_Error('download_failed', sprintf( // translators: %1$s is the URL, %2$s is the error message __('Download failed for %1$s: %2$s', 'snaggly'), $url, $temp_file->get_error_message() )); } if (!$this->file_exists($temp_file) || $this->get_file_size($temp_file) === 0) { $this->cleanup_temp_file($temp_file); return new WP_Error('empty_download', sprintf( // translators: %s is the URL __('Downloaded file is empty or does not exist: %s', 'snaggly'), $url )); } if ($this->get_file_size($temp_file) > $this->settings->get_max_file_size()) { $this->cleanup_temp_file($temp_file); return new WP_Error('file_too_large', __('Downloaded file exceeds the configured maximum size.', 'snaggly')); } return $temp_file; } /** * Import file to media library * * @param string $temp_file * @param string $original_url * @param int $post_id * @return int|WP_Error */ protected function import_to_media_library($temp_file, $original_url, $post_id = 0) { if (!function_exists('media_handle_sideload')) { require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; } if ($this->get_file_size($temp_file) > $this->settings->get_max_file_size()) { return new WP_Error('file_too_large', __('Downloaded file exceeds the configured maximum size.', 'snaggly')); } $validation = $this->validate_downloaded_file($temp_file); if (is_wp_error($validation)) { return $validation; } $original_filename = basename((string) wp_parse_url($original_url, PHP_URL_PATH)); if (pathinfo($original_filename, PATHINFO_EXTENSION) === '') { $original_filename = $this->infer_download_filename($temp_file, $original_filename); } $filename = $this->generate_filename($original_filename, $original_url); $file_array = array( 'name' => $filename, 'tmp_name' => $temp_file, 'error' => 0, 'size' => $this->get_file_size($temp_file), ); $file_type = wp_check_filetype_and_ext($temp_file, $filename); if (empty($file_type['ext']) || empty($file_type['type']) || !in_array(strtolower($file_type['ext']), $this->settings->get_allowed_extensions(), true) || !in_array($file_type['type'], $this->get_allowed_mime_types(), true)) { return new WP_Error('unsupported_file_type', __('This file type is not allowed by WordPress or your Snaggly settings.', 'snaggly')); } $attachment_id = media_handle_sideload($file_array, $post_id); if (is_wp_error($attachment_id)) { return new WP_Error('media_import_failed', sprintf( // translators: %s is the error message __('Failed to import to media library: %s', 'snaggly'), $attachment_id->get_error_message() )); } update_post_meta($attachment_id, '_snaggly_original_url', $original_url); update_post_meta($attachment_id, '_snaggly_download_date', current_time('mysql')); $this->clear_download_caches($original_url); return $attachment_id; } /** Derive an extension for a direct extensionless response from its actual bytes. */ protected function infer_download_filename($temp_file, $basename) { $mime = wp_get_image_mime($temp_file); if (!$mime && class_exists('finfo')) { $detector = new finfo(FILEINFO_MIME_TYPE); $mime = $detector->file($temp_file); } // Do not turn an HTML download landing page into a Media Library import. if (!$mime || in_array($mime, array('text/html', 'application/xhtml+xml'), true) || !in_array($mime, $this->get_allowed_mime_types(), true)) { return $basename; } foreach (get_allowed_mime_types() as $extensions => $allowed_mime) { if ($mime !== $allowed_mime) { continue; } foreach (explode('|', $extensions) as $extension) { if ($this->settings->is_allowed_extension($extension)) { return (sanitize_file_name($basename) ?: 'remote-file') . '.' . $extension; } } } return $basename; } /** * Generate filename based on settings * * @param string $original_filename * @param string $url * @return string */ protected function generate_filename($original_filename, $url) { $convention = $this->settings->get_file_naming_convention(); switch ($convention) { case 'hash': $extension = pathinfo($original_filename, PATHINFO_EXTENSION); return md5($url) . ($extension ? '.' . $extension : ''); case 'sanitized': return sanitize_file_name($original_filename); case 'original': default: return $original_filename ?: basename($url); } } /** * Get allowed MIME types * * @return array */ protected function get_allowed_mime_types() { return array_values((array) apply_filters('snaggly_allowed_mime_types', array_values(get_allowed_mime_types()))); } /** * Check if file exists using WordPress Filesystem API * * @since 1.0.0 * @param string $file_path * @return bool */ protected function file_exists($file_path) { if (@is_file($file_path)) { return true; } global $wp_filesystem; if (empty($wp_filesystem)) { require_once ABSPATH . '/wp-admin/includes/file.php'; WP_Filesystem(); } return isset($wp_filesystem) && $wp_filesystem ? (bool) $wp_filesystem->exists($file_path) : @is_file($file_path); } /** * Get file size using WordPress Filesystem API * * @since 1.0.0 * @param string $file_path * @return int|false */ protected function get_file_size($file_path) { $native = @filesize($file_path); if ($native !== false && $native > 0) { return $native; } global $wp_filesystem; if (empty($wp_filesystem)) { require_once ABSPATH . '/wp-admin/includes/file.php'; WP_Filesystem(); } return isset($wp_filesystem) && $wp_filesystem ? $wp_filesystem->size($file_path) : $native; } /** * Clean up temporary file using WordPress Filesystem API * * @since 1.0.0 * @param string $file_path * @return bool */ protected function cleanup_temp_file($file_path) { if (@is_file($file_path)) { $ok = wp_delete_file($file_path); $this->debug_log(($ok ? 'Successfully' : 'Failed to') . " cleaned up temp file (WordPress): {$file_path}"); return true; // treat as cleaned even if deletion failed to avoid loops } global $wp_filesystem; if (empty($wp_filesystem)) { require_once ABSPATH . '/wp-admin/includes/file.php'; WP_Filesystem(); } if (isset($wp_filesystem) && $wp_filesystem->exists($file_path)) { $result = (bool) $wp_filesystem->delete($file_path); $this->debug_log(($result ? 'Successfully' : 'Failed to') . " cleaned up temp file: {$file_path}"); return $result; } return true; // File doesn't exist, consider it cleaned up } /** * Check if URL has already been downloaded * * @since 1.0.0 * @param string $url * @return bool */ public function is_url_already_downloaded($url) { $cache_key = 'snaggly_url_exists_' . md5($url); $cached_result = wp_cache_get($cache_key, 'snaggly'); if (false !== $cached_result) { return (bool) $cached_result; } global $wpdb; $query_start = microtime(true); /* phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query needed for performance; caching handled by wp_cache_get/set above */ $attachment_id = $wpdb->get_var($wpdb->prepare( "SELECT p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id WHERE p.post_type = 'attachment' AND p.post_status = 'inherit' AND pm.meta_key = '_snaggly_original_url' AND pm.meta_value = %s LIMIT 1", $url )); $query_time = microtime(true) - $query_start; if ($query_time > 0.1) { $this->debug_log("Slow query detected in is_url_already_downloaded(): {$query_time}s for URL: {$url}"); } $exists = !empty($attachment_id); wp_cache_set($cache_key, $exists, 'snaggly', HOUR_IN_SECONDS); return $exists; } /** * Clear download-related caches * * @since 1.0.0 * @param string|null $url * @return void */ protected function clear_download_caches($url = null) { delete_transient('snaggly_download_stats'); if ($url) { $cache_key = 'snaggly_url_exists_' . md5($url); wp_cache_delete($cache_key, 'snaggly'); } else { snaggly_flush_cache_group('snaggly'); } $this->debug_log("Download caches cleared" . ($url ? " for URL: {$url}" : " (all)")); } /** * Replace URLs in post content * * @param int $post_id * @param array $url_mappings * @return bool */ public function replace_urls_in_content($post_id, $url_mappings) { if (!$this->can_access_post($post_id)) { return false; } $post = get_post($post_id); if (!$post) { $this->debug_log("Could not find post with ID $post_id"); return false; } $content = $post->post_content; $preserve_originals = $this->settings->should_preserve_original_urls(); $original_comments = array(); // Build the full search => replace map up front and apply it in one // strtr() pass. strtr() matches the longest key first and never // re-scans already-substituted text, so one mapping's replacement // can't be corrupted by another mapping whose search/replace string // happens to be a substring of it - a real risk with the previous // sequential str_replace() calls (e.g. a resized/query-string // variant of a URL colliding with its base URL). $replace_map = array(); foreach ($url_mappings as $old_url => $new_url) { if ($old_url === '') { continue; } $variants = array_filter($this->url_replacement_variants($old_url, $new_url, $content), static function ($replacement, $search) use ($content) { return strpos($content, $search) !== false; }, ARRAY_FILTER_USE_BOTH); if (!$variants) { continue; } if ($preserve_originals) { $comment = ''; $original_comments[] = $comment; } $replace_map = array_merge($replace_map, $variants); } if (empty($replace_map)) { return false; } $content = strtr($content, $replace_map); if (!empty($original_comments)) { $content .= "\n" . implode("\n", $original_comments); } $result = wp_update_post(wp_slash(array( 'ID' => $post_id, 'post_content' => $content, ))); if (!$result || is_wp_error($result)) { $this->debug_log("Failed to update post: " . (is_wp_error($result) ? $result->get_error_message() : 'Unknown error')); return false; } $existing_mappings = get_post_meta($post_id, '_snaggly_url_mappings', true); if (!is_array($existing_mappings)) { $existing_mappings = array(); } $existing_mappings = array_merge($existing_mappings, $url_mappings); update_post_meta($post_id, '_snaggly_url_mappings', $existing_mappings); update_post_meta($post_id, '_snaggly_last_updated', current_time('mysql')); return true; } /** Match raw URLs, HTML attributes, and JSON-escaped Gutenberg attributes. */ protected function url_replacement_variants($old_url, $new_url, $content) { $variants = array($old_url => $new_url); // Match whole HTML attributes so JSON strings remain JSON, not HTML-escaped text. preg_match_all('/\\b(?:href|src|poster|data-src)\\s*=\\s*(["\'])(.*?)\\1/is', $content, $attributes, PREG_SET_ORDER); foreach ($attributes as $attribute) { if (html_entity_decode($attribute[2], ENT_QUOTES | ENT_HTML5, 'UTF-8') !== $old_url) { continue; } $prefix = substr($attribute[0], 0, strlen($attribute[0]) - strlen($attribute[2]) - 1); $variants[$attribute[0]] = $prefix . esc_attr($new_url) . $attribute[1]; } $json_old = substr(wp_json_encode($old_url), 1, -1); if ($json_old !== $old_url) { $variants[$json_old] = substr(wp_json_encode($new_url), 1, -1); } return $variants; } /** * Reverse every URL replacement Snaggly has made in a post's content * (i.e. undo replace_urls_in_content() for that post), restoring the * original remote URLs and clearing the recorded mapping. * * @param int $post_id * @return int|WP_Error Number of URLs reverted on success. */ public function rollback_url_replacements($post_id) { if (!$this->can_access_post($post_id)) { return new WP_Error('forbidden_post', __('You do not have permission to edit this post', 'snaggly')); } $post = get_post($post_id); if (!$post) { return new WP_Error('post_not_found', __('Post not found', 'snaggly')); } $mappings = get_post_meta($post_id, '_snaggly_url_mappings', true); if (empty($mappings) || !is_array($mappings)) { return new WP_Error('no_mappings', __('No recorded URL replacements found for this post', 'snaggly')); } $content = $post->post_content; // Same reasoning as replace_urls_in_content(): build the full // search => replace map up front and apply it in one strtr() pass, // rather than sequential str_replace() calls that risk one // mapping's reverted URL corrupting - or being corrupted by - // another mapping's search/replace string. Each mapping contributes // two candidate keys (the "preserve original URL" comment variant // and the bare URL); strtr() always tries the longer key first, so // the commented form wins when present. $replace_map = array(); $reverted = 0; foreach ($mappings as $old_url => $new_url) { if ($new_url === '') { continue; } $variants = array_filter($this->url_replacement_variants($new_url, $old_url, $content), static function ($replacement, $search) use ($content) { return strpos($content, $search) !== false; }, ARRAY_FILTER_USE_BOTH); if (!$variants) { continue; } $comment = ''; $replace_map["\n" . $comment] = ''; $replace_map[$new_url . ' ' . $comment] = $old_url; $replace_map = array_merge($replace_map, $variants); $reverted++; } if ($reverted === 0) { return new WP_Error('nothing_to_revert', __('None of the recorded replacement URLs were found in the current content', 'snaggly')); } $content = strtr($content, $replace_map); $result = wp_update_post(wp_slash(array( 'ID' => $post_id, 'post_content' => $content, ))); if (!$result || is_wp_error($result)) { $this->debug_log("Failed to update post during rollback: " . (is_wp_error($result) ? $result->get_error_message() : 'Unknown error')); return new WP_Error('update_failed', __('Failed to update post content', 'snaggly')); } delete_post_meta($post_id, '_snaggly_url_mappings'); update_post_meta($post_id, '_snaggly_last_updated', current_time('mysql')); return $reverted; } /** * Get download statistics with caching * * @since 1.0.0 * @return array */ public function get_download_stats() { $cache_key = 'snaggly_download_stats'; $cached_results = get_transient($cache_key); if (false !== $cached_results) { return $cached_results; } global $wpdb; $query_start = microtime(true); /* phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query needed for performance; caching handled by get_transient above */ $attachments = $wpdb->get_col( "SELECT DISTINCT p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} pm1 ON p.ID = pm1.post_id INNER JOIN {$wpdb->postmeta} pm2 ON p.ID = pm2.post_id WHERE p.post_type = 'attachment' AND p.post_status = 'inherit' AND pm1.meta_key = '_snaggly_original_url' AND pm2.meta_key = '_snaggly_download_date'" ); $query_time = microtime(true) - $query_start; if ($query_time > 0.5) { $this->debug_log("Slow query detected in get_download_stats(): {$query_time}s"); } $date_counts = array(); foreach ($attachments as $attachment_id) { $download_date = get_post_meta($attachment_id, '_snaggly_download_date', true); if (!empty($download_date)) { $date = gmdate('Y-m-d', strtotime($download_date)); $date_counts[$date] = ($date_counts[$date] ?? 0) + 1; } } $results = array(); foreach ($date_counts as $date => $count) { $results[] = (object) array( 'download_date' => $date, 'total_downloads' => $count, ); } usort($results, function ($a, $b) { return strtotime($b->download_date) - strtotime($a->download_date); }); $results = array_slice($results, 0, 30); set_transient($cache_key, $results, HOUR_IN_SECONDS); return $results; } protected function validate_downloaded_file($temp_file) { // WordPress validates the filename and file contents in media_handle_sideload(). if ($this->get_file_size($temp_file) > $this->settings->get_max_file_size()) { return new WP_Error('file_too_large', __('Downloaded file exceeds the configured maximum size.', 'snaggly')); } return true; } }