init_hooks(); } /** * Initialize AJAX hooks */ protected function init_hooks() { add_action('wp_ajax_snaggly_dismiss_pro_callout', array($this, 'handle_dismiss_pro_callout')); add_action('wp_ajax_snaggly_scan', array($this, 'handle_scan')); add_action('wp_ajax_snaggly_start_progressive_scan', array($this, 'handle_start_progressive_scan')); add_action('wp_ajax_snaggly_continue_scan', array($this, 'handle_continue_scan')); add_action('wp_ajax_snaggly_download', array($this, 'handle_download')); add_action('wp_ajax_snaggly_get_file_info', array($this, 'handle_get_file_info')); add_action('wp_ajax_snaggly_diagnostic', array($this, 'handle_diagnostic')); add_action('wp_ajax_snaggly_cancel_scan', array($this, 'handle_cancel_scan')); add_action('wp_ajax_snaggly_rollback_replacements', array($this, 'handle_rollback_replacements')); add_action('wp_ajax_snaggly_clear_rate_limit', array($this, 'handle_clear_rate_limit')); add_action('wp_ajax_snaggly_clear_logs', array($this, 'handle_clear_logs')); // Settings management actions add_action('wp_ajax_snaggly_reset_settings', array($this, 'handle_reset_settings')); add_action('wp_ajax_snaggly_export_settings', array($this, 'handle_export_settings')); add_action('wp_ajax_snaggly_import_settings', array($this, 'handle_import_settings')); } /** Save only the current user's preference; no user ID is accepted from input. */ public function handle_dismiss_pro_callout() { $this->verify_nonce_and_capability(); $user_id = get_current_user_id(); if (!$user_id) { wp_send_json_error(array('message' => __('Insufficient permissions', 'snaggly')), 403); return; } update_user_meta($user_id, '_snaggly_pro_callout_dismissed', '1'); if (!get_user_meta($user_id, '_snaggly_pro_callout_dismissed', true)) { wp_send_json_error(array('message' => __('Could not dismiss the callout. Please try again.', 'snaggly'))); return; } wp_send_json_success(array('dismissed' => true)); } /** * Handle scan request */ public function handle_scan() { try { $this->verify_nonce_and_capability(); $this->check_rate_limiting('scan'); $settings = SnagglySettings::get_instance(); $scanner = snaggly_scanner(); $post_types = $settings->get_scan_post_types(); $total_posts = $scanner->get_total_scannable_posts($post_types); $is_large_site = $total_posts > $settings->get_large_site_threshold(); $start_time = microtime(true); if ($is_large_site && !$settings->get_auto_progressive_for_large_sites()) { wp_send_json_error(array( 'message' => sprintf( // translators: %d is the total number of posts on the site __('Large site detected (%d posts). Please use the Progressive Scan feature for better performance and to avoid timeouts.', 'snaggly'), $total_posts ), 'total_posts' => $total_posts, 'is_large_site' => true, 'recommend_progressive' => true, )); return; } $this->extend_execution_time_for_scan($settings->get_max_scan_time()); $links = $scanner->scan_all_posts(); $execution_time = round(microtime(true) - $start_time, 2); $memory_peak = memory_get_peak_usage(true); if ($settings->should_log_performance_metrics() && defined('WP_DEBUG') && WP_DEBUG && function_exists('wp_debug_log')) { wp_debug_log("Snaggly: Scan completed in {$execution_time}s. Peak memory: " . size_format($memory_peak)); } do_action('snaggly_after_scan', $links); $response_data = array( 'links' => $links, 'count' => count($links), // translators: %d is the number of remote links found 'message' => sprintf(__('Found %d remote links', 'snaggly'), count($links)), 'total_posts_scanned' => $total_posts, 'execution_time' => $execution_time, 'memory_usage' => size_format($memory_peak), 'is_large_site' => $is_large_site, ); if ($execution_time > 30) { $response_data['performance_warning'] = __('Scan took longer than expected. Consider using Progressive Scan for better performance.', 'snaggly'); } wp_send_json_success($response_data); } catch (Exception $e) { wp_send_json_error(array( 'message' => __('Scan failed: ', 'snaggly') . $e->getMessage(), 'error_type' => get_class($e), )); } } /** * Best-effort extension of the script's own execution time limit for * large scans. (Note: there is no WordPress filter that changes PHP's * execution timeout — this must be done directly via set_time_limit().) * * @param int $seconds */ protected function extend_execution_time_for_scan($seconds) { if ($seconds > 0 && function_exists('set_time_limit')) { // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged,WordPress.PHP.DiscouragedPHPFunctions.runtime_configuration_set_time_limit -- deliberate, user-configured, capped scan timeout @set_time_limit((int) $seconds); } } /** * Handle start progressive scan */ public function handle_start_progressive_scan() { try { $this->verify_nonce_and_capability(); $this->check_rate_limiting('scan'); $scanner = snaggly_scanner(); $scan_session = $scanner->start_progressive_scan(); if (is_wp_error($scan_session)) { wp_send_json_error(array('message' => $scan_session->get_error_message())); return; } wp_send_json_success(array( 'session_id' => $scan_session['session_id'], 'total_posts' => $scan_session['total_posts'], // translators: %d is the total number of posts to be scanned 'message' => sprintf(__('Starting scan of %d posts...', 'snaggly'), $scan_session['total_posts']), )); } catch (Exception $e) { wp_send_json_error(array('message' => __('Failed to start scan: ', 'snaggly') . $e->getMessage())); } } /** * Handle continue scan request */ public function handle_continue_scan() { try { $this->verify_nonce_and_capability(); // Nonce verified above, safe to access $_POST data // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce_and_capability() $session_id = isset($_POST['session_id']) && is_string($_POST['session_id']) ? sanitize_text_field(wp_unslash($_POST['session_id'])) : ''; if (empty($session_id)) { wp_send_json_error(array('message' => __('Invalid session ID', 'snaggly'))); return; } $scanner = snaggly_scanner(); $scan_session = $scanner->continue_progressive_scan($session_id); if (is_wp_error($scan_session)) { wp_send_json_error(array('message' => $scan_session->get_error_message())); return; } $progress_percentage = 0; if ($scan_session['total_posts'] > 0) { $progress_percentage = ($scan_session['processed_posts'] / $scan_session['total_posts']) * 100; } $response_data = array( 'session_id' => $session_id, 'processed_posts' => $scan_session['processed_posts'], 'total_posts' => $scan_session['total_posts'], 'progress_percentage' => round($progress_percentage, 1), 'found_links' => count($scan_session['found_links']), 'is_complete' => $scan_session['is_complete'], // translators: %1$d is the number of processed posts, %2$d is the total number of posts 'message' => sprintf(__('Scanned %1$d of %2$d posts...', 'snaggly'), $scan_session['processed_posts'], $scan_session['total_posts']), ); if ($scan_session['is_complete']) { $response_data['links'] = $scan_session['found_links']; // translators: %d is the number of remote links found $response_data['message'] = sprintf(__('Scan complete! Found %d remote links.', 'snaggly'), count($scan_session['found_links'])); do_action('snaggly_after_scan', $scan_session['found_links']); } wp_send_json_success($response_data); } catch (Exception $e) { wp_send_json_error(array('message' => __('Scan failed: ', 'snaggly') . $e->getMessage())); } } /** * Handle download request */ public function handle_download() { $url = ''; try { $this->verify_nonce_and_capability(); $this->check_rate_limiting('download'); // Nonce verified above, safe to access $_POST data // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce_and_capability() $url = isset($_POST['url']) && is_string($_POST['url']) ? esc_url_raw(wp_unslash($_POST['url'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce_and_capability() $post_id = isset($_POST['post_id']) && is_scalar($_POST['post_id']) ? absint($_POST['post_id']) : 0; if (empty($url)) { wp_send_json_error(array('message' => __('Invalid URL', 'snaggly'))); return; } $downloader = snaggly_downloader(); $result = $downloader->download_file($url, $post_id); if (is_wp_error($result)) { wp_send_json_error(array( 'message' => $result->get_error_message(), 'url' => $url, )); return; } wp_send_json_success(array( 'attachment_id' => $result, 'attachment_url' => wp_get_attachment_url($result), 'original_url' => $url, 'message' => __('File downloaded successfully', 'snaggly'), )); } catch (Exception $e) { wp_send_json_error(array( 'message' => __('Download failed: ', 'snaggly') . $e->getMessage(), 'url' => $url, )); } } /** * Handle get file info request */ public function handle_get_file_info() { $this->verify_nonce_and_capability(); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce_and_capability() $url = isset($_POST['url']) && is_string($_POST['url']) ? esc_url_raw(wp_unslash($_POST['url'])) : ''; if (empty($url)) { wp_send_json_error(array('message' => __('Invalid URL', 'snaggly'))); return; } if (!SnagglyUrlValidator::is_safe_remote_url($url)) { wp_send_json_error(array('message' => __('Unsafe or private URL detected', 'snaggly'))); return; } try { $cache_key = 'snaggly_file_info_' . md5($url); $cached = get_transient($cache_key); if ($cached && is_array($cached)) { wp_send_json_success($cached); return; } $scanner = snaggly_scanner(); $file_size = $scanner->get_remote_file_size($url); $response = SnagglyUrlValidator::safe_request($url, array('method' => 'HEAD', 'timeout' => 10, 'user-agent' => 'Snaggly Plugin', 'sslverify' => apply_filters('snaggly_ajax_sslverify', true), )); $headers = array(); $content_type = ''; if (!is_wp_error($response)) { $headers = wp_remote_retrieve_headers($response); $content_type = isset($headers['content-type']) ? $headers['content-type'] : ''; } $filename = basename((string) wp_parse_url($url, PHP_URL_PATH)); $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); $payload = array( 'url' => $url, 'filename' => $filename, 'extension' => $extension, 'file_size' => $file_size, 'file_size_formatted' => $file_size ? size_format($file_size) : __('Unknown', 'snaggly'), 'content_type' => $content_type, 'headers' => $headers, ); set_transient($cache_key, $payload, 5 * MINUTE_IN_SECONDS); wp_send_json_success($payload); } catch (Exception $e) { wp_send_json_error(array('message' => __('Failed to get file info: ', 'snaggly') . $e->getMessage())); } } /** * Handle rollback of Snaggly's URL replacements in a post's content. */ public function handle_rollback_replacements() { try { $this->verify_nonce_and_capability(); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce_and_capability() $post_id = isset($_POST['post_id']) && is_scalar($_POST['post_id']) ? absint($_POST['post_id']) : 0; if ($post_id <= 0) { wp_send_json_error(array('message' => __('Invalid post ID', 'snaggly'))); return; } // Check existence before capability: current_user_can('edit_post', ...) // denies unconditionally for a nonexistent post, which would // otherwise report a misleading "permission" error for what is // really just an invalid/stale post ID. if (!get_post($post_id)) { wp_send_json_error(array('message' => __('Post not found', 'snaggly'))); return; } if (!current_user_can('edit_post', $post_id)) { wp_send_json_error(array('message' => __('You do not have permission to edit this post', 'snaggly'))); return; } $downloader = snaggly_downloader(); $result = $downloader->rollback_url_replacements($post_id); if (is_wp_error($result)) { wp_send_json_error(array('message' => $result->get_error_message())); return; } wp_send_json_success(array( 'reverted' => $result, // translators: %d is the number of URLs reverted 'message' => sprintf(__('Reverted %d URL(s) back to their original remote address.', 'snaggly'), $result), )); } catch (Exception $e) { wp_send_json_error(array('message' => __('Rollback failed: ', 'snaggly') . $e->getMessage())); } } /** * Clear the current user's own Snaggly rate-limit state, for when * testing/heavy use has tripped it and they don't want to wait out the * block window. */ public function handle_clear_rate_limit() { try { $this->verify_nonce_and_capability(); $rate_limiter = SnagglyRateLimiter::get_instance(); $rate_limiter->clear_rate_limits(get_current_user_id()); wp_send_json_success(array('message' => __('Your rate limit has been cleared.', 'snaggly'))); } catch (Exception $e) { wp_send_json_error(array('message' => __('Failed to clear rate limit: ', 'snaggly') . $e->getMessage())); } } /** * Clear Snaggly's debug log files. */ public function handle_clear_logs() { try { $this->verify_nonce_and_capability(); SnagglyLogger::get_instance()->clear_logs(); wp_send_json_success(array('message' => __('Debug logs cleared.', 'snaggly'))); } catch (Exception $e) { wp_send_json_error(array('message' => __('Failed to clear logs: ', 'snaggly') . $e->getMessage())); } } /** * Handle diagnostic request */ public function handle_diagnostic() { $this->verify_nonce_and_capability(); try { $diagnostic_info = $this->gather_diagnostic_info(); wp_send_json_success(array( 'diagnostic' => $diagnostic_info, 'message' => __('Diagnostic completed', 'snaggly'), )); } catch (Exception $e) { if (class_exists('SnagglyLogger')) { SnagglyLogger::get_instance()->error('Diagnostic failed', array( 'exception' => $e->getMessage(), 'trace' => $e->getTraceAsString(), )); } wp_send_json_error(array('message' => __('Diagnostic failed: ', 'snaggly') . $e->getMessage())); } } /** * Handle cancel scan request */ public function handle_cancel_scan() { $this->verify_nonce_and_capability(); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce_and_capability() $session_id = isset($_POST['session_id']) && is_string($_POST['session_id']) ? sanitize_text_field(wp_unslash($_POST['session_id'])) : ''; if (!empty($session_id)) { $scanner = snaggly_scanner(); $cancelled = $scanner->cancel_scan($session_id); if (is_wp_error($cancelled)) { wp_send_json_error(array('message' => $cancelled->get_error_message())); return; } } wp_send_json_success(array('message' => __('Scan cancelled', 'snaggly'))); } /** * Gather diagnostic information * * @return array */ protected function gather_diagnostic_info() { global $wp_version; $diagnostic_data = array(); try { $diagnostic_data['wordpress'] = array( 'wp_version' => $wp_version, 'php_version' => PHP_VERSION, 'memory_limit' => ini_get('memory_limit'), 'max_execution_time' => ini_get('max_execution_time'), 'upload_max_filesize' => ini_get('upload_max_filesize'), 'post_max_size' => ini_get('post_max_size'), 'is_multisite' => is_multisite(), 'active_theme' => get_template(), 'wp_debug' => defined('WP_DEBUG') && WP_DEBUG, ); } catch (Exception $e) { $diagnostic_data['wordpress'] = array('error' => 'Failed to gather WordPress info: ' . $e->getMessage()); } try { $settings = SnagglySettings::get_instance(); $plugin_settings = $settings->get_all(); $diagnostic_data['plugin'] = array( 'plugin_version' => SNAGGLY_VERSION, 'plugin_file' => SNAGGLY_PLUGIN_FILE, 'plugin_dir' => SNAGGLY_PLUGIN_DIR, 'plugin_url' => SNAGGLY_PLUGIN_URL, 'settings_count' => count($plugin_settings), ); $diagnostic_data['settings'] = $plugin_settings; } catch (Exception $e) { $diagnostic_data['plugin'] = array('error' => 'Failed to gather plugin info: ' . $e->getMessage()); $diagnostic_data['settings'] = array('error' => 'Failed to gather settings: ' . $e->getMessage()); } try { $diagnostic_data['database'] = SnagglyDBOptimizer::get_instance()->get_database_stats(); } catch (Exception $e) { $diagnostic_data['database'] = array('error' => 'Failed to gather database stats: ' . $e->getMessage()); } try { $diagnostic_data['connectivity'] = $this->test_connectivity(); } catch (Exception $e) { $diagnostic_data['connectivity'] = array('error' => 'Failed to test connectivity: ' . $e->getMessage()); } try { $diagnostic_data['logging'] = SnagglyLogger::get_instance()->get_log_stats(); } catch (Exception $e) { $diagnostic_data['logging'] = array('error' => 'Failed to gather log stats: ' . $e->getMessage()); } try { $rate_limiter = SnagglyRateLimiter::get_instance(); $diagnostic_data['rate_limiting'] = array( 'settings' => $rate_limiter->get_settings(), 'current_user' => array( 'scan' => $rate_limiter->get_rate_limit_stats('scan', get_current_user_id()), 'download' => $rate_limiter->get_rate_limit_stats('download', get_current_user_id()), ), ); } catch (Exception $e) { $diagnostic_data['rate_limiting'] = array('error' => 'Failed to gather rate limit stats: ' . $e->getMessage()); } try { $diagnostic_data['filesystem'] = $this->check_filesystem(); } catch (Exception $e) { $diagnostic_data['filesystem'] = array('error' => 'Failed to check filesystem: ' . $e->getMessage()); } $diagnostic_data['timestamp'] = current_time('mysql'); return $diagnostic_data; } /** * Test external connectivity. * * The URL list is filterable so site owners/agencies can point this at * their own infrastructure instead of (or in addition to) third-party * services, or disable it entirely by returning an empty array. * * @return array */ protected function test_connectivity() { $test_urls = apply_filters('snaggly_diagnostic_connectivity_urls', array( 'https://www.google.com', )); $results = array(); foreach ($test_urls as $url) { try { $start_time = microtime(true); $response = SnagglyUrlValidator::safe_request($url, array( 'timeout' => 10, 'user-agent' => 'Snaggly Plugin Diagnostic', 'limit_response_size' => 1024, )); $end_time = microtime(true); $results[$url] = array( 'success' => !is_wp_error($response), 'response_code' => is_wp_error($response) ? 0 : wp_remote_retrieve_response_code($response), 'response_time' => round(($end_time - $start_time) * 1000, 2) . 'ms', 'error' => is_wp_error($response) ? $response->get_error_message() : null, ); } catch (Exception $e) { $results[$url] = array( 'success' => false, 'response_code' => 0, 'response_time' => '0ms', 'error' => 'Exception: ' . $e->getMessage(), ); } } return $results; } /** * Check filesystem permissions * * @return array */ protected function check_filesystem() { $filesystem_info = array(); try { $upload_dir = wp_upload_dir(); $filesystem_info['upload_dir'] = $upload_dir['basedir']; $filesystem_info['upload_url'] = $upload_dir['baseurl']; } catch (Exception $e) { $filesystem_info['upload_dir'] = 'Error: ' . $e->getMessage(); $filesystem_info['upload_url'] = 'Error: ' . $e->getMessage(); } try { if (!function_exists('WP_Filesystem')) { require_once ABSPATH . 'wp-admin/includes/file.php'; } // WP_Filesystem() itself returns a bool (success/failure); the // actual filesystem instance is only ever available via the // $wp_filesystem global, which is what must be checked here. $initialized = WP_Filesystem(); global $wp_filesystem; $filesystem_info['filesystem_available'] = $initialized && is_object($wp_filesystem); if ($filesystem_info['filesystem_available']) { $filesystem_info['upload_writable'] = $wp_filesystem->is_writable($upload_dir['basedir']); $filesystem_info['temp_writable'] = $wp_filesystem->is_writable(get_temp_dir()); } else { $filesystem_info['upload_writable'] = false; $filesystem_info['temp_writable'] = false; $filesystem_info['filesystem_error'] = 'WP_Filesystem() did not initialize the $wp_filesystem global'; } } catch (Exception $e) { $filesystem_info['filesystem_available'] = false; $filesystem_info['upload_writable'] = false; $filesystem_info['temp_writable'] = false; $filesystem_info['filesystem_error'] = $e->getMessage(); } try { $filesystem_info['temp_dir'] = get_temp_dir(); $filesystem_info['plugin_dir_readable'] = is_readable(SNAGGLY_PLUGIN_DIR); } catch (Exception $e) { $filesystem_info['temp_dir'] = 'Error: ' . $e->getMessage(); $filesystem_info['plugin_dir_readable'] = false; } return $filesystem_info; } /** * Verify nonce and capability. Halts the request (via wp_send_json_error() * -> wp_die()) on failure, so callers can treat a normal return as "OK". */ protected function verify_nonce_and_capability() { $nonce = isset($_POST['nonce']) && is_string($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : ''; if (!wp_verify_nonce($nonce, 'snaggly_ajax_nonce')) { wp_send_json_error(array('message' => __('Security check failed', 'snaggly'))); } if (!current_user_can(function_exists('snaggly_required_cap') ? snaggly_required_cap() : 'manage_options')) { wp_send_json_error(array('message' => __('Insufficient permissions', 'snaggly'))); } } /** * Check rate limiting. Halts the request on failure (see above). * * @param string $endpoint * @return true */ protected function check_rate_limiting($endpoint) { // SnagglyRateLimiter itself honors the rate_limiting_enabled setting // (returns "allowed" immediately when disabled), so there's no need // to duplicate that check here. $rate_limiter = SnagglyRateLimiter::get_instance(); $rate_limit_status = $rate_limiter->check_rate_limit($endpoint, get_current_user_id()); if (!$rate_limit_status['allowed']) { $message = __('Rate limit exceeded. Please try again later.', 'snaggly'); if (isset($rate_limit_status['retry_after'])) { // translators: %d is the number of seconds to wait before retrying $message .= ' ' . sprintf(__('Retry after %d seconds.', 'snaggly'), $rate_limit_status['retry_after']); } wp_send_json_error(array( 'message' => $message, 'rate_limit_exceeded' => true, 'retry_after' => $rate_limit_status['retry_after'] ?? 0, )); } return true; } /** * Reset settings to defaults */ public function handle_reset_settings() { try { $this->verify_nonce_and_capability(); $settings = SnagglySettings::get_instance(); if ($settings->reset()) { wp_send_json_success(array('message' => __('Settings reset to defaults', 'snaggly'))); return; } wp_send_json_error(array('message' => __('Failed to reset settings', 'snaggly'))); } catch (Exception $e) { wp_send_json_error(array('message' => $e->getMessage())); } } /** * Export current settings */ public function handle_export_settings() { try { $this->verify_nonce_and_capability(); $settings = SnagglySettings::get_instance()->get_all(); wp_send_json_success(array('settings' => $settings)); } catch (Exception $e) { wp_send_json_error(array('message' => $e->getMessage())); } } /** * Import settings JSON */ public function handle_import_settings() { try { $this->verify_nonce_and_capability(); // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce verified in verify_nonce_and_capability(), payload validated via validate_settings() below $raw = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : ''; if (!is_string($raw) || strlen($raw) > 65536 || substr(ltrim($raw), 0, 1) !== '{') { wp_send_json_error(array('message' => __('Invalid settings payload', 'snaggly'))); return; } $data = json_decode($raw, true, 8); if (!is_array($data)) { wp_send_json_error(array('message' => __('Invalid settings payload', 'snaggly'))); return; } $settings_instance = SnagglySettings::get_instance(); $validated = $settings_instance->validate_settings(SnagglySettings::sanitize_input($data)); $saved = update_option('snaggly_settings', $validated); if ($saved) { $settings_instance->reload_settings(); } if (!$saved && get_option('snaggly_settings') !== $validated) { wp_send_json_error(array('message' => __('Failed to import settings', 'snaggly'))); return; } wp_send_json_success(array('message' => $saved ? __('Settings imported successfully', 'snaggly') : __('Settings already up to date', 'snaggly'))); } catch (Exception $e) { wp_send_json_error(array('message' => $e->getMessage())); } } }