PluginProbe
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… / 2.11.4
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… v2.11.4
3.0.0 2.11.12 2.11.11 2.11.10 2.11.9 2.11.7 2.11.8 2.11.6 2.11.5 2.11.4 2.11.3 2.11.1 2.11.2 2.11.0 2.10.5 2.10.4 2.10.3 2.10.2 2.10.1 2.10.0 2.9.9 2.9.8 2.9.6 2.9.7 2.9.5 All 88 releases
vigilante / assets / js / admin.js

admin.js in Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… 2.11.4, at assets/js/admin.js

4,373 lines 193.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /**
2 * Vigilante Admin JavaScript
3 *
4 * @package Vigilante
5 */
6
7 (function($) {
8 'use strict';
9
10 var Vigilante_Admin = {
11
12 /**
13 * Initialize
14 */
15 init: function() {
16 this.bindEvents();
17 this.initModuleToggles();
18 this.initFileIntegrityPagination();
19
20 // Activity log pagination state
21 this.logPage = 1;
22 this.logPerPage = 20;
23 this.logSearchTimer = null;
24 },
25
26 /**
27 * Bind events
28 */
29 bindEvents: function() {
30 // Save settings forms
31 $(document).on('submit', '.vigilante-settings-form', this.handleFormSubmit.bind(this));
32
33 // Module toggles in dashboard
34 $(document).on('change', '.vigilante-module-item input[type="checkbox"]', this.handleModuleToggle.bind(this));
35
36 // Apply preset
37 $(document).on('click', '.vigilante-preset-btn', this.handleApplyPreset.bind(this));
38
39 // Reset section to defaults
40 $(document).on('click', '.vigilante-reset-section-btn', this.handleResetSection.bind(this));
41
42 // Clear lockouts
43 $(document).on('click', '.vigilante-clear-lockout', this.handleClearLockout.bind(this));
44 $(document).on('click', '.vigilante-clear-all-lockouts', this.handleClearAllLockouts.bind(this));
45
46 // Unblock firewall rate-limited IPs
47 $(document).on('click', '.vigilante-unblock-firewall-ip', this.handleUnblockFirewallIp.bind(this));
48
49 // Clear logs
50 $(document).on('click', '.vigilante-clear-logs', this.handleClearLogs.bind(this));
51
52 // Run scan
53 $(document).on('click', '.vigilante-run-scan', this.handleRunScan.bind(this));
54 $(document).on('click', '.vigilante-ignore-file', this.handleIgnoreFile.bind(this));
55 $(document).on('click', '.vigilante-unignore-file', this.handleUnignoreFile.bind(this));
56 $(document).on('click', '.vigilante-clear-ignored', this.handleClearIgnored.bind(this));
57
58 // Closed plugins ignore controls (separate slug-based list, not file paths).
59 $(document).on('click', '.vigilante-ignore-closed-plugin', this.handleIgnoreClosedPlugin.bind(this));
60 $(document).on('click', '.vigilante-unignore-closed-plugin', this.handleUnignoreClosedPlugin.bind(this));
61 $(document).on('click', '.vigilante-clear-ignored-closed-plugins', this.handleClearIgnoredClosedPlugins.bind(this));
62
63 // Bulk selection inside file integrity tables
64 $(document).on('change', '.vigilante-fi-cb-all', this.handleFiSelectAll.bind(this));
65 $(document).on('change', '.vigilante-fi-cb', this.handleFiCheckboxChange.bind(this));
66 $(document).on('click', '.vigilante-bulk-ignore', this.handleBulkIgnore.bind(this));
67 $(document).on('click', '.vigilante-bulk-unignore', this.handleBulkUnignore.bind(this));
68
69 // Clear scan results
70 $(document).on('click', '.vigilante-clear-scan', this.handleClearScan.bind(this));
71
72 // Critical config file actions
73 $(document).on('click', '.vigilante-approve-critical-file', this.handleApproveCriticalFile.bind(this));
74 $(document).on('click', '.vigilante-toggle-critical-content', this.handleToggleCriticalContent.bind(this));
75
76 // Export/Import settings
77 $(document).on('click', '.vigilante-export-settings', this.handleExportSettings.bind(this));
78 $(document).on('click', '.vigilante-import-settings', this.handleImportSettings.bind(this));
79 $(document).on('change', '#vigilante-import-file', this.handleImportFile.bind(this));
80
81 // Reset settings
82 $(document).on('click', '.vigilante-reset-settings', this.handleResetSettings.bind(this));
83
84 // Test headers
85 $(document).on('click', '.vigilante-test-headers', this.handleTestHeaders.bind(this));
86
87 // Login URL notification
88 $(document).on('click', '#vigilante_notify_login_url', this.handleNotifyLoginUrl.bind(this));
89 $(document).on('input', '#vigilante_custom_login_url', this.handleLoginUrlToggle.bind(this));
90
91 // Activity log filters
92 $(document).on('change', '#vigilante-log-type-filter, #vigilante-log-severity-filter, #vigilante-log-method-filter', this.handleLogFilter.bind(this));
93 $(document).on('click', '#vigilante-log-refresh', this.handleLogFilter.bind(this));
94
95 // Activity log search (debounced, min 3 chars)
96 $(document).on('input', '#vigilante-log-search', this.handleLogSearch.bind(this));
97
98 // Activity log pagination
99 $(document).on('click', '#vigilante-log-pagination .vigilante-page-first', function() { Vigilante_Admin.goToLogPage('first'); });
100 $(document).on('click', '#vigilante-log-pagination .vigilante-page-prev', function() { Vigilante_Admin.goToLogPage('prev'); });
101 $(document).on('click', '#vigilante-log-pagination .vigilante-page-next', function() { Vigilante_Admin.goToLogPage('next'); });
102 $(document).on('click', '#vigilante-log-pagination .vigilante-page-last', function() { Vigilante_Admin.goToLogPage('last'); });
103
104 // File integrity client-side pagination
105 $(document).on('click', '.vigilante-fi-pagination .vigilante-page-first', function() { Vigilante_Admin.goToFilePage($(this).closest('.vigilante-paginated-section'), 'first'); });
106 $(document).on('click', '.vigilante-fi-pagination .vigilante-page-prev', function() { Vigilante_Admin.goToFilePage($(this).closest('.vigilante-paginated-section'), 'prev'); });
107 $(document).on('click', '.vigilante-fi-pagination .vigilante-page-next', function() { Vigilante_Admin.goToFilePage($(this).closest('.vigilante-paginated-section'), 'next'); });
108 $(document).on('click', '.vigilante-fi-pagination .vigilante-page-last', function() { Vigilante_Admin.goToFilePage($(this).closest('.vigilante-paginated-section'), 'last'); });
109
110 // Export logs
111 $(document).on('click', '.vigilante-export-logs', this.handleExportLogs.bind(this));
112
113 // Create backup
114 $(document).on('click', '.vigilante-create-backup', this.handleCreateBackup.bind(this));
115
116 // View log details modal
117 $(document).on('click', '.vigilante-view-log-details', this.handleViewLogDetails.bind(this));
118 $(document).on('click', '.vigilante-modal-close, .vigilante-modal', this.handleCloseModal.bind(this));
119 $(document).on('click', '.vigilante-add-to-list', this.handleAddToFirewallList.bind(this));
120 $(document).on('click', '.vigilante-modal-content', function(e) {
121 e.stopPropagation();
122 });
123
124 // Under Attack mode
125 $(document).on('click', '.vigilante-ua-activate', this.handleUnderAttackActivate.bind(this));
126 $(document).on('click', '.vigilante-ua-deactivate', this.handleUnderAttackDeactivate.bind(this));
127
128 // Database backup
129 $(document).on('click', '.vigilante-db-backup-toggle', this.handleDbBackupToggle.bind(this));
130 $(document).on('click', '.vigilante-db-backup-download', this.handleDbBackupDownload.bind(this));
131 $(document).on('change', '#vigilante-db-select-all', this.handleDbSelectAll.bind(this));
132 $(document).on('change', '.vigilante-db-table-check', this.handleDbTableCheck.bind(this));
133
134 // Database prefix
135 $(document).on('click', '.vigilante-db-regenerate-prefix', this.handleDbRegeneratePrefix.bind(this));
136 $(document).on('change', '#vigilante-prefix-backup-confirm', this.handleDbPrefixConfirmToggle.bind(this));
137 $(document).on('click', '.vigilante-db-change-prefix', this.handleDbChangePrefix.bind(this));
138
139 // Settings search
140 $(document).on('input', '#vigilante-settings-search', this.handleSettingsSearch.bind(this));
141 $(document).on('focus', '#vigilante-settings-search', this.handleSettingsSearch.bind(this));
142 $(document).on('keydown', '#vigilante-settings-search', this.handleSettingsSearchKey.bind(this));
143 $(document).on('mouseenter', '.vigilante-search-item', this.handleSettingsSearchHover.bind(this));
144 $(document).on('click', function(e) {
145 if (!$(e.target).closest('.vigilante-search-wrapper').length) {
146 $('#vigilante-settings-search-results').attr('hidden', true);
147 }
148 });
149 // Global "/" shortcut to focus search
150 $(document).on('keydown', function(e) {
151 if (e.key !== '/') return;
152 var $t = $(e.target);
153 if ($t.is('input, textarea, select') || $t.is('[contenteditable="true"]')) return;
154 var $search = $('#vigilante-settings-search');
155 if (!$search.length) return;
156 e.preventDefault();
157 $search.focus().select();
158 });
159
160 // Start Under Attack countdown if active
161 this.initUnderAttackCountdown();
162 },
163
164 /**
165 * Initialize module toggles
166 */
167 initModuleToggles: function() {
168 $(document).on('change', '.vigilante-module-item input[type="checkbox"]', function() {
169 var $item = $(this).closest('.vigilante-module-item');
170 var module = $(this).data('module');
171 var enabled = $(this).is(':checked');
172
173 $item.toggleClass('enabled', enabled).toggleClass('disabled', !enabled);
174
175 // Save module state
176 Vigilante_Admin.saveModuleState(module, enabled);
177 });
178 },
179
180 /**
181 * Save module state
182 */
183 saveModuleState: function(module, enabled) {
184 var $item = $('.vigilante-module-item input[data-module="' + module + '"]').closest('.vigilante-module-item');
185
186 // Show saving state
187 $item.addClass('vigilante-saving');
188
189 $.ajax({
190 url: vigilanteAdmin.ajaxUrl,
191 type: 'POST',
192 data: {
193 action: 'vigilante_save_settings',
194 nonce: vigilanteAdmin.nonce,
195 section: 'modules',
196 data: 'modules[' + module + ']=' + (enabled ? '1' : '0')
197 },
198 success: function(response) {
199 if (response.success) {
200 $item.removeClass('vigilante-saving').addClass('vigilante-saved');
201 // Show success then reload to update recommendations and all UI
202 Vigilante_Admin.showNotice('success', vigilanteAdmin.strings.saved);
203 setTimeout(function() {
204 location.reload();
205 }, 800);
206 } else {
207 $item.removeClass('vigilante-saving');
208 Vigilante_Admin.showNotice('error', response.data || vigilanteAdmin.strings.error);
209 }
210 },
211 error: function() {
212 $item.removeClass('vigilante-saving');
213 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
214 }
215 });
216 },
217
218 /**
219 * Update security score after module toggle
220 */
221 updateSecurityScore: function() {
222 var total = $('.vigilante-module-item').length;
223 var enabled = $('.vigilante-module-item.enabled').length;
224 var score = total > 0 ? Math.round((enabled / total) * 100) : 0;
225
226 // Grade thresholds: A (90+), B (70-89), C (50-69), D (30-49), E (0-29)
227 var grade;
228 if (score >= 90) {
229 grade = 'A';
230 } else if (score >= 70) {
231 grade = 'B';
232 } else if (score >= 50) {
233 grade = 'C';
234 } else if (score >= 30) {
235 grade = 'D';
236 } else {
237 grade = 'E';
238 }
239
240 // Update score display
241 $('.vigilante-score-text').text(score + '%');
242 $('.vigilante-grade').text(grade);
243 $('.vigilante-score-circle').removeClass('vigilante-grade-a vigilante-grade-b vigilante-grade-c vigilante-grade-d vigilante-grade-e')
244 .addClass('vigilante-grade-' + grade.toLowerCase());
245
246 // Update modules count text - use fixed string to prevent text accumulation
247 var $countText = $('.vigilante-security-score p');
248 if ($countText.length) {
249 var modulesText = (vigilanteAdmin.strings.modulesEnabled || '%1$d / %2$d modules enabled').replace('%1$d', enabled).replace('%2$d', total);
250 $countText.text(modulesText);
251 }
252 },
253
254 /**
255 * Update configuration status badge
256 */
257 updateConfigBadge: function(preset) {
258 var $badge = $('.vigilante-config-status .vigilante-preset-badge');
259 if ($badge.length) {
260 $badge.removeClass('vigilante-preset-standard vigilante-preset-maximum vigilante-preset-custom vigilante-preset-under-attack');
261
262 if (vigilanteAdmin.underAttack && vigilanteAdmin.underAttack.active) {
263 $badge.addClass('vigilante-preset-under-attack').text(vigilanteAdmin.strings.underAttackLabel || 'Under Attack');
264 } else if (preset === 'standard') {
265 $badge.addClass('vigilante-preset-standard').text(vigilanteAdmin.strings.standardLabel || 'Standard');
266 } else if (preset === 'maximum') {
267 $badge.addClass('vigilante-preset-maximum').text(vigilanteAdmin.strings.maximumLabel || 'Maximum Security');
268 } else {
269 $badge.addClass('vigilante-preset-custom').text(vigilanteAdmin.strings.customConfig || 'Custom Configuration');
270 }
271 }
272 },
273
274 /**
275 * Handle form submit
276 */
277 handleFormSubmit: function(e) {
278 e.preventDefault();
279
280 var $form = $(e.currentTarget);
281 var $btn = $form.find('.vigilante-save-btn');
282 var section = $form.data('section');
283
284 $btn.prop('disabled', true).text(vigilanteAdmin.strings.saving);
285 $form.addClass('vigilante-loading');
286
287 // Build form data including unchecked checkboxes
288 var formData = Vigilante_Admin.serializeFormWithCheckboxes($form);
289
290 $.ajax({
291 url: vigilanteAdmin.ajaxUrl,
292 type: 'POST',
293 data: {
294 action: 'vigilante_save_settings',
295 nonce: vigilanteAdmin.nonce,
296 section: section,
297 data: formData
298 },
299 success: function(response) {
300 if (response.success) {
301 var msg = response.data && response.data.message ? response.data.message : (response.data || vigilanteAdmin.strings.saved);
302 Vigilante_Admin.showNotice('success', msg);
303 } else {
304 Vigilante_Admin.showNotice('error', response.data || vigilanteAdmin.strings.error);
305 }
306 },
307 error: function(xhr, status, error) {
308 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
309 },
310 complete: function() {
311 $btn.prop('disabled', false).text($btn.data('original-text') || vigilanteAdmin.strings.saved);
312 $form.removeClass('vigilante-loading');
313
314 // Reset button text after delay
315 setTimeout(function() {
316 $btn.text($btn.data('original-text') || vigilanteAdmin.strings.saveSettings || 'Save Settings');
317 }, 2000);
318 }
319 });
320 },
321
322 /**
323 * Handle module toggle in dashboard
324 */
325 handleModuleToggle: function(e) {
326 var $checkbox = $(e.currentTarget);
327 var module = $checkbox.data('module');
328 var enabled = $checkbox.is(':checked');
329 var $item = $checkbox.closest('.vigilante-module-item');
330
331 // Visual feedback
332 $item.addClass('vigilante-loading');
333
334 // Build data for modules section
335 var formData = 'modules[' + module + ']=' + (enabled ? '1' : '0');
336
337 $.ajax({
338 url: vigilanteAdmin.ajaxUrl,
339 type: 'POST',
340 data: {
341 action: 'vigilante_save_settings',
342 nonce: vigilanteAdmin.nonce,
343 section: 'modules',
344 data: formData
345 },
346 success: function(response) {
347 if (response.success) {
348 // Update visual state
349 if (enabled) {
350 $item.removeClass('disabled').addClass('enabled');
351 } else {
352 $item.removeClass('enabled').addClass('disabled');
353 }
354 Vigilante_Admin.updateSecurityScore();
355 Vigilante_Admin.showNotice('success', vigilanteAdmin.strings.saved);
356
357 // Update config badge to Custom (since settings were manually changed)
358 Vigilante_Admin.updateConfigBadge('custom');
359
360 // Clear active preset indicator
361 $('.vigilante-preset-card').removeClass('vigilante-preset-active');
362 $('.vigilante-active-indicator').remove();
363 } else {
364 // Revert checkbox on error
365 $checkbox.prop('checked', !enabled);
366 Vigilante_Admin.showNotice('error', response.data || vigilanteAdmin.strings.error);
367 }
368 },
369 error: function() {
370 // Revert checkbox on error
371 $checkbox.prop('checked', !enabled);
372 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
373 },
374 complete: function() {
375 $item.removeClass('vigilante-loading');
376 }
377 });
378 },
379
380 /**
381 * Serialize form including unchecked checkboxes
382 */
383 serializeFormWithCheckboxes: function($form) {
384 var data = $form.serializeArray();
385 var checkboxNames = [];
386
387 // Find all checkboxes and add unchecked ones with value 0
388 $form.find('input[type="checkbox"]').each(function() {
389 var name = $(this).attr('name');
390 if (name && checkboxNames.indexOf(name) === -1) {
391 checkboxNames.push(name);
392 if (!$(this).is(':checked')) {
393 data.push({ name: name, value: '0' });
394 }
395 }
396 });
397
398 // Convert to query string
399 return $.param(data);
400 },
401
402 /**
403 * Handle apply preset
404 */
405 handleApplyPreset: function(e) {
406 e.preventDefault();
407
408 var preset = $(e.currentTarget).data('preset');
409
410 if (!confirm(vigilanteAdmin.strings.confirm + ' ' + (vigilanteAdmin.strings.confirmApplyPreset || 'Apply the "%s" preset?').replace('%s', preset))) {
411 return;
412 }
413
414 $.ajax({
415 url: vigilanteAdmin.ajaxUrl,
416 type: 'POST',
417 data: {
418 action: 'vigilante_apply_preset',
419 nonce: vigilanteAdmin.nonce,
420 preset: preset
421 },
422 success: function(response) {
423 if (response.success) {
424 Vigilante_Admin.showNotice('success', response.data);
425 setTimeout(function() {
426 location.reload();
427 }, 1000);
428 } else {
429 Vigilante_Admin.showNotice('error', response.data);
430 }
431 },
432 error: function() {
433 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
434 }
435 });
436 },
437
438 /**
439 * Handle Under Attack mode activation
440 */
441 handleUnderAttackActivate: function(e) {
442 e.preventDefault();
443
444 if (!confirm(vigilanteAdmin.strings.underAttackConfirmActivate)) {
445 return;
446 }
447
448 var $btn = $(e.currentTarget);
449 $btn.prop('disabled', true).text(vigilanteAdmin.strings.underAttackActivating);
450
451 $.ajax({
452 url: vigilanteAdmin.ajaxUrl,
453 type: 'POST',
454 data: {
455 action: 'vigilante_activate_under_attack',
456 nonce: vigilanteAdmin.nonce
457 },
458 success: function(response) {
459 if (response.success) {
460 Vigilante_Admin.showNotice('success', response.data.message);
461 setTimeout(function() {
462 location.reload();
463 }, 1000);
464 } else {
465 Vigilante_Admin.showNotice('error', response.data);
466 $btn.prop('disabled', false).text(vigilanteAdmin.strings.underAttackActivate || 'Activate for 4 hours');
467 }
468 },
469 error: function() {
470 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
471 $btn.prop('disabled', false).text(vigilanteAdmin.strings.underAttackActivate || 'Activate for 4 hours');
472 }
473 });
474 },
475
476 /**
477 * Handle Under Attack mode deactivation
478 */
479 handleUnderAttackDeactivate: function(e) {
480 e.preventDefault();
481
482 if (!confirm(vigilanteAdmin.strings.underAttackConfirmDeactivate)) {
483 return;
484 }
485
486 var $btn = $(e.currentTarget);
487 $btn.prop('disabled', true).text(vigilanteAdmin.strings.underAttackDeactivating);
488
489 $.ajax({
490 url: vigilanteAdmin.ajaxUrl,
491 type: 'POST',
492 data: {
493 action: 'vigilante_deactivate_under_attack',
494 nonce: vigilanteAdmin.nonce
495 },
496 success: function(response) {
497 if (response.success) {
498 Vigilante_Admin.showNotice('success', response.data);
499 setTimeout(function() {
500 location.reload();
501 }, 1000);
502 } else {
503 Vigilante_Admin.showNotice('error', response.data);
504 $btn.prop('disabled', false).text(vigilanteAdmin.strings.deactivate || 'Deactivate');
505 }
506 },
507 error: function() {
508 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
509 $btn.prop('disabled', false).text(vigilanteAdmin.strings.deactivate || 'Deactivate');
510 }
511 });
512 },
513
514 /**
515 * Initialize Under Attack countdown timer
516 */
517 initUnderAttackCountdown: function() {
518 var $countdown = $('.vigilante-ua-countdown');
519 if (!$countdown.length) {
520 return;
521 }
522
523 var expiresAt = parseInt($countdown.data('expires'), 10);
524 if (!expiresAt) {
525 return;
526 }
527
528 var $timeEl = $countdown.find('.vigilante-ua-time');
529
530 var updateCountdown = function() {
531 var now = Math.floor(Date.now() / 1000);
532 var remaining = expiresAt - now;
533
534 if (remaining <= 0) {
535 location.reload();
536 return;
537 }
538
539 var hours = Math.floor(remaining / 3600);
540 var mins = Math.floor((remaining % 3600) / 60);
541
542 var text = vigilanteAdmin.strings.underAttackRemaining || '%1$dh %2$dm remaining';
543 text = text.replace('%1$d', hours).replace('%2$d', mins);
544 $timeEl.text(text);
545 };
546
547 // Run immediately, then update every minute
548 updateCountdown();
549 setInterval(updateCountdown, 60000);
550 },
551
552 /**
553 * Handle reset section to defaults
554 */
555 handleResetSection: function(e) {
556 e.preventDefault();
557
558 var $btn = $(e.currentTarget);
559 var $form = $btn.closest('form');
560 var section = $form.data('section');
561
562 if (!section) {
563 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.couldNotDetermineSection || 'Could not determine section.');
564 return;
565 }
566
567 if (!confirm(vigilanteAdmin.strings.confirmResetSection || 'Reset this section to default values? This cannot be undone.')) {
568 return;
569 }
570
571 var originalText = $btn.data('original-text') || $btn.text();
572 $btn.prop('disabled', true).html(vigilanteAdmin.strings.loading + ' <span class="vigilante-spinner"></span>');
573
574 $.ajax({
575 url: vigilanteAdmin.ajaxUrl,
576 type: 'POST',
577 data: {
578 action: 'vigilante_reset_section',
579 nonce: vigilanteAdmin.nonce,
580 section: section
581 },
582 success: function(response) {
583 if (response.success) {
584 Vigilante_Admin.showNotice('success', response.data.message || vigilanteAdmin.strings.sectionResetDefaults || 'Section reset to defaults.');
585 setTimeout(function() {
586 location.reload();
587 }, 1000);
588 } else {
589 Vigilante_Admin.showNotice('error', response.data);
590 }
591 },
592 error: function() {
593 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
594 },
595 complete: function() {
596 $btn.prop('disabled', false).text(originalText);
597 }
598 });
599 },
600
601 /**
602 * Handle clear single lockout
603 */
604 handleClearLockout: function(e) {
605 e.preventDefault();
606
607 var $btn = $(e.currentTarget);
608 var ip = $btn.data('ip');
609
610 $.ajax({
611 url: vigilanteAdmin.ajaxUrl,
612 type: 'POST',
613 data: {
614 action: 'vigilante_clear_lockouts',
615 nonce: vigilanteAdmin.nonce,
616 ip: ip
617 },
618 success: function(response) {
619 if (response.success) {
620 var $container = $btn.closest('.vigilante-paginated-section');
621 $btn.closest('tr').fadeOut(function() {
622 $(this).remove();
623 Vigilante_Admin.refreshFilePagination($container);
624 });
625 } else {
626 Vigilante_Admin.showNotice('error', response.data);
627 }
628 }
629 });
630 },
631
632 /**
633 * Handle clear all lockouts
634 */
635 handleClearAllLockouts: function(e) {
636 e.preventDefault();
637
638 if (!confirm(vigilanteAdmin.strings.confirm)) {
639 return;
640 }
641
642 $.ajax({
643 url: vigilanteAdmin.ajaxUrl,
644 type: 'POST',
645 data: {
646 action: 'vigilante_clear_lockouts',
647 nonce: vigilanteAdmin.nonce
648 },
649 success: function(response) {
650 if (response.success) {
651 location.reload();
652 } else {
653 Vigilante_Admin.showNotice('error', response.data);
654 }
655 }
656 });
657 },
658
659 /**
660 * Handle clear logs
661 */
662 handleClearLogs: function(e) {
663 e.preventDefault();
664
665 if (!confirm(vigilanteAdmin.strings.confirm + ' ' + (vigilanteAdmin.strings.confirmClearLogs || 'This will delete all activity logs.'))) {
666 return;
667 }
668
669 $.ajax({
670 url: vigilanteAdmin.ajaxUrl,
671 type: 'POST',
672 data: {
673 action: 'vigilante_clear_logs',
674 nonce: vigilanteAdmin.nonce
675 },
676 success: function(response) {
677 if (response.success) {
678 location.reload();
679 } else {
680 Vigilante_Admin.showNotice('error', response.data);
681 }
682 }
683 });
684 },
685
686 /**
687 * Handle run scan
688 */
689 handleRunScan: function(e) {
690 e.preventDefault();
691 e.stopPropagation();
692
693 var $btn = $(e.currentTarget);
694 var $results = $('#vigilante-scan-results');
695 var $lastResults = $('#vigilante-last-scan-results').closest('.vigilante-settings-section');
696
697 // Hide previous results section
698 $lastResults.hide();
699 $results.empty().hide();
700
701 $btn.prop('disabled', true).html(vigilanteAdmin.strings.scanning + ' <span class="vigilante-spinner"></span>');
702
703 $.ajax({
704 url: vigilanteAdmin.ajaxUrl,
705 type: 'POST',
706 timeout: 120000,
707 data: {
708 action: 'vigilante_run_scan',
709 nonce: vigilanteAdmin.nonce
710 },
711 success: function(response) {
712 if (response.success) {
713 // Reload the page so the server-side render shows ALL findings
714 // in their canonical sections (Suspicious, Extra, Critical Config,
715 // Closed + Removed Plugins, Modified). The legacy in-place JS
716 // render only knows the file-level categories and would leave
717 // the Closed + Removed subsection hidden after a scan.
718 Vigilante_Admin.showNotice('success', vigilanteAdmin.strings.scanComplete);
719 setTimeout(function() { location.reload(); }, 600);
720 } else {
721 Vigilante_Admin.showNotice('error', response.data || vigilanteAdmin.strings.scanFailed || 'Scan failed');
722 $btn.prop('disabled', false).text(vigilanteAdmin.strings.runScanNow || 'Run Scan Now');
723 }
724 },
725 error: function(xhr, status, error) {
726 Vigilante_Admin.showNotice('error', (vigilanteAdmin.strings.scanError || 'Scan error: %s').replace('%s', error));
727 $btn.prop('disabled', false).text(vigilanteAdmin.strings.runScanNow || 'Run Scan Now');
728 }
729 });
730 },
731
732 /**
733 * Handle clear scan results
734 */
735 handleClearScan: function(e) {
736 e.preventDefault();
737 e.stopPropagation();
738
739 if (!confirm(vigilanteAdmin.strings.confirmClearScan || 'Are you sure you want to clear all scan results?')) {
740 return;
741 }
742
743 var $btn = $(e.currentTarget);
744 var originalText = $btn.text();
745 $btn.prop('disabled', true).text(vigilanteAdmin.strings.clearing || 'Clearing...');
746
747 $.ajax({
748 url: vigilanteAdmin.ajaxUrl,
749 type: 'POST',
750 data: {
751 action: 'vigilante_clear_scan',
752 nonce: vigilanteAdmin.nonce
753 },
754 success: function(response) {
755 if (response.success) {
756 // Hide all scan results
757 $('#vigilante-scan-results').empty().hide();
758 $('#vigilante-last-scan-results').closest('.vigilante-settings-section').fadeOut();
759 Vigilante_Admin.showNotice('success', vigilanteAdmin.strings.scanResultsCleared || 'Scan results cleared. Page will reload...');
760 // Reload page to reflect changes
761 setTimeout(function() {
762 location.reload();
763 }, 1000);
764 } else {
765 Vigilante_Admin.showNotice('error', response.data || vigilanteAdmin.strings.failedClearResults || 'Failed to clear results');
766 $btn.prop('disabled', false).text(originalText);
767 }
768 },
769 error: function(xhr, status, error) {
770 Vigilante_Admin.showNotice('error', (vigilanteAdmin.strings.ajaxError || 'AJAX Error: %s').replace('%s', error));
771 $btn.prop('disabled', false).text(originalText);
772 },
773 complete: function() {
774 // Button text restored in success/error handlers
775 }
776 });
777 },
778
779 /**
780 * Handle toggle critical file content viewer
781 */
782 handleToggleCriticalContent: function(e) {
783 e.preventDefault();
784 var $btn = $(e.currentTarget);
785 var targetId = $btn.data('target');
786 var $content = $('#' + targetId);
787
788 // Use toggle instead of slideUp/slideDown because target can be a TR
789 // (animations on table rows are inconsistent across browsers)
790 if ($content.is(':visible')) {
791 $content.hide();
792 $btn.text($btn.data('label-show'));
793 } else {
794 $content.show();
795 $btn.text($btn.data('label-hide'));
796 }
797 },
798
799 /**
800 * Handle approve critical file button click
801 */
802 handleApproveCriticalFile: function(e) {
803 e.preventDefault();
804 var $btn = $(e.currentTarget);
805 var file = $btn.data('file');
806 var strings = vigilanteAdmin.strings;
807 var originalText = $btn.text();
808
809 // The POST carries an opaque key, never the file name: WAFs like
810 // ModSecurity (OWASP CRS 930130) block any request argument
811 // containing the literal "wp-config.php", which made Approve fail
812 // with a generic AJAX error on hardened hostings. The PHP handler
813 // maps the key back against its own whitelist.
814 var fileKey = { 'wp-config.php': 'cfg', '.htaccess': 'hta' }[ file ] || '';
815
816 $btn.prop('disabled', true).text(strings.approving || 'Approving...');
817
818 $.ajax({
819 url: vigilanteAdmin.ajaxUrl,
820 type: 'POST',
821 data: {
822 action: 'vigilante_approve_critical_file',
823 nonce: vigilanteAdmin.nonce,
824 file_key: fileKey
825 },
826 success: function(response) {
827 if (response.success) {
828 // Remove the approved file row and its diff row from the table.
829 // The diff row carries an id derived from the file name (same as
830 // sanitize_html_class() on PHP side), so we target it directly
831 // instead of relying on adjacency in the DOM.
832 var $row = $btn.closest('tr');
833 var fileId = String(file).replace(/[^a-z0-9_-]/gi, '-');
834 $('#vigilante-critical-content-' + fileId).remove();
835 $row.fadeOut(300, function() {
836 $(this).remove();
837 // If no more critical config rows, remove the entire section
838 if ($('.vigilante-critical-config-files tbody tr').length === 0) {
839 $('.vigilante-critical-config-files').fadeOut(300, function() { $(this).remove(); });
840 }
841 });
842 Vigilante_Admin.showNotice('success', strings.criticalApproved || response.data.message);
843 } else {
844 Vigilante_Admin.showNotice('error', response.data || 'Failed to approve.');
845 $btn.prop('disabled', false).text(originalText);
846 }
847 },
848 error: function(xhr, status, error) {
849 Vigilante_Admin.showNotice('error', (strings.ajaxError || 'AJAX Error: %s').replace('%s', error));
850 $btn.prop('disabled', false).text(originalText);
851 }
852 });
853 },
854
855 /**
856 * Handle ignore file button click
857 */
858 handleIgnoreFile: function(e) {
859 e.preventDefault();
860 var $btn = $(e.currentTarget);
861 var file = $btn.data('file');
862 var strings = vigilanteAdmin.strings;
863
864 $btn.prop('disabled', true).text(strings.ignoring || 'Ignoring...');
865
866 $.ajax({
867 url: vigilanteAdmin.ajaxUrl,
868 type: 'POST',
869 data: {
870 action: 'vigilante_ignore_file',
871 nonce: vigilanteAdmin.nonce,
872 file: file
873 },
874 success: function(response) {
875 if (response.success) {
876 var $container = $btn.closest('.vigilante-paginated-section');
877 // Remove the row from the table
878 $btn.closest('tr').fadeOut(300, function() {
879 $(this).remove();
880 // Refresh pagination after row removal
881 Vigilante_Admin.refreshFilePagination($container);
882 });
883 Vigilante_Admin.showNotice('success', strings.fileIgnored || 'File added to ignored list.');
884 } else {
885 Vigilante_Admin.showNotice('error', response.data || 'Failed to ignore file');
886 $btn.prop('disabled', false).text(strings.ignore || 'Ignore');
887 }
888 },
889 error: function() {
890 $btn.prop('disabled', false).text(strings.ignore || 'Ignore');
891 }
892 });
893 },
894
895 /**
896 * Handle stop ignoring file
897 */
898 handleUnignoreFile: function(e) {
899 e.preventDefault();
900 var $btn = $(e.currentTarget);
901 var file = $btn.data('file');
902 var strings = vigilanteAdmin.strings;
903
904 $.ajax({
905 url: vigilanteAdmin.ajaxUrl,
906 type: 'POST',
907 data: {
908 action: 'vigilante_unignore_file',
909 nonce: vigilanteAdmin.nonce,
910 file: file
911 },
912 success: function(response) {
913 if (response.success) {
914 var $container = $btn.closest('.vigilante-paginated-section');
915 $btn.closest('tr').fadeOut(300, function() {
916 $(this).remove();
917 Vigilante_Admin.refreshFilePagination($container);
918 });
919 Vigilante_Admin.showNotice('success', strings.fileUnignored || 'File removed from ignored list.');
920 } else {
921 Vigilante_Admin.showNotice('error', response.data || 'Failed');
922 }
923 }
924 });
925 },
926
927 /**
928 * Handle clear all ignored files
929 */
930 handleClearIgnored: function(e) {
931 e.preventDefault();
932 var strings = vigilanteAdmin.strings;
933
934 if (!confirm(strings.confirmClearIgnored || 'Remove all files from the ignored list?')) {
935 return;
936 }
937
938 $.ajax({
939 url: vigilanteAdmin.ajaxUrl,
940 type: 'POST',
941 data: {
942 action: 'vigilante_clear_ignored',
943 nonce: vigilanteAdmin.nonce
944 },
945 success: function(response) {
946 if (response.success) {
947 Vigilante_Admin.showNotice('success', strings.ignoredCleared || 'Ignored files list cleared. Page will reload...');
948 setTimeout(function() {
949 location.reload();
950 }, 1000);
951 }
952 }
953 });
954 },
955
956 /**
957 * Ignore a closed/removed plugin slug. Reloads to refresh the section.
958 */
959 handleIgnoreClosedPlugin: function(e) {
960 e.preventDefault();
961 var $btn = $(e.currentTarget);
962 var slug = $btn.data('slug');
963 var strings = vigilanteAdmin.strings || {};
964
965 $btn.prop('disabled', true).text(strings.ignoring || 'Ignoring…');
966
967 $.ajax({
968 url: vigilanteAdmin.ajaxUrl,
969 type: 'POST',
970 data: {
971 action: 'vigilante_ignore_closed_plugin',
972 nonce: vigilanteAdmin.nonce,
973 slug: slug
974 },
975 success: function(response) {
976 if (response && response.success) {
977 Vigilante_Admin.showNotice('success', (response.data) || 'Plugin ignored.');
978 setTimeout(function() { location.reload(); }, 600);
979 } else {
980 Vigilante_Admin.showNotice('error', (response && response.data) || 'Failed.');
981 $btn.prop('disabled', false).text(strings.ignore || 'Ignore');
982 }
983 },
984 error: function(xhr, status, error) {
985 Vigilante_Admin.showNotice('error', (strings.ajaxError || 'AJAX Error: %s').replace('%s', error));
986 $btn.prop('disabled', false).text(strings.ignore || 'Ignore');
987 }
988 });
989 },
990
991 /**
992 * Stop ignoring a closed/removed plugin slug.
993 */
994 handleUnignoreClosedPlugin: function(e) {
995 e.preventDefault();
996 var $btn = $(e.currentTarget);
997 var slug = $btn.data('slug');
998 var strings = vigilanteAdmin.strings || {};
999
1000 $btn.prop('disabled', true).text(strings.unignoring || 'Restoring…');
1001
1002 $.ajax({
1003 url: vigilanteAdmin.ajaxUrl,
1004 type: 'POST',
1005 data: {
1006 action: 'vigilante_unignore_closed_plugin',
1007 nonce: vigilanteAdmin.nonce,
1008 slug: slug
1009 },
1010 success: function(response) {
1011 if (response && response.success) {
1012 Vigilante_Admin.showNotice('success', (response.data) || 'Plugin restored to the active list.');
1013 setTimeout(function() { location.reload(); }, 600);
1014 } else {
1015 Vigilante_Admin.showNotice('error', (response && response.data) || 'Failed.');
1016 $btn.prop('disabled', false).text(strings.stopIgnoring || 'Stop ignoring');
1017 }
1018 },
1019 error: function(xhr, status, error) {
1020 Vigilante_Admin.showNotice('error', (strings.ajaxError || 'AJAX Error: %s').replace('%s', error));
1021 $btn.prop('disabled', false).text(strings.stopIgnoring || 'Stop ignoring');
1022 }
1023 });
1024 },
1025
1026 /**
1027 * Clear the entire ignored closed plugins list.
1028 */
1029 handleClearIgnoredClosedPlugins: function(e) {
1030 e.preventDefault();
1031 var strings = vigilanteAdmin.strings || {};
1032
1033 if (!confirm(strings.confirmClearIgnoredClosedPlugins || 'Remove all plugins from the ignored closed plugins list? They will reappear in the main list and in email alerts.')) {
1034 return;
1035 }
1036
1037 $.ajax({
1038 url: vigilanteAdmin.ajaxUrl,
1039 type: 'POST',
1040 data: {
1041 action: 'vigilante_clear_ignored_closed_plugins',
1042 nonce: vigilanteAdmin.nonce
1043 },
1044 success: function(response) {
1045 if (response && response.success) {
1046 Vigilante_Admin.showNotice('success', (response.data) || 'Ignored closed plugins list cleared.');
1047 setTimeout(function() { location.reload(); }, 1000);
1048 }
1049 }
1050 });
1051 },
1052
1053 /**
1054 * Toggle all checkboxes inside a file integrity table when the
1055 * header "select all" checkbox changes. Only operates on visible
1056 * rows so it plays nice with client-side pagination.
1057 */
1058 handleFiSelectAll: function(e) {
1059 var $cb = $(e.currentTarget);
1060 var $section = $cb.closest('.vigilante-paginated-section');
1061 $section.find('table.vigilante-fi-paginated tbody tr:visible .vigilante-fi-cb').prop('checked', $cb.prop('checked'));
1062 this.refreshBulkBar($section);
1063 },
1064
1065 /**
1066 * Refresh bulk bar state after individual checkbox change.
1067 */
1068 handleFiCheckboxChange: function(e) {
1069 var $section = $(e.currentTarget).closest('.vigilante-paginated-section');
1070 this.refreshBulkBar($section);
1071
1072 // Sync the header "select all" with the current visible state
1073 var $allCb = $section.find('.vigilante-fi-cb-all');
1074 var $visible = $section.find('table.vigilante-fi-paginated tbody tr:visible .vigilante-fi-cb');
1075 var $checked = $visible.filter(':checked');
1076 $allCb.prop('checked', $visible.length > 0 && $checked.length === $visible.length);
1077 },
1078
1079 /**
1080 * Update the count label and enable/disable the bulk action button.
1081 */
1082 refreshBulkBar: function($section) {
1083 var strings = vigilanteAdmin.strings;
1084 var mode = $section.data('bulk-mode'); // 'ignore' or 'unignore'
1085 var $checked = $section.find('.vigilante-fi-cb:checked');
1086 var count = $checked.length;
1087 var $btn = $section.find(mode === 'unignore' ? '.vigilante-bulk-unignore' : '.vigilante-bulk-ignore');
1088 var $count = $section.find('.vigilante-fi-bulk-count');
1089
1090 $btn.prop('disabled', count === 0);
1091
1092 if (count === 0) {
1093 $count.text('');
1094 } else {
1095 var template = (strings.bulkSelectedCount || '%d selected');
1096 $count.text(template.replace('%d', count));
1097 }
1098 },
1099
1100 /**
1101 * Collect the file paths checked inside a section.
1102 */
1103 collectSelectedFiles: function($section) {
1104 var files = [];
1105 $section.find('.vigilante-fi-cb:checked').each(function() {
1106 var v = $(this).val();
1107 if (v) {
1108 files.push(v);
1109 }
1110 });
1111 return files;
1112 },
1113
1114 /**
1115 * Bulk add to ignored list.
1116 */
1117 handleBulkIgnore: function(e) {
1118 e.preventDefault();
1119 var self = this;
1120 var strings = vigilanteAdmin.strings;
1121 var $btn = $(e.currentTarget);
1122 var $section = $btn.closest('.vigilante-paginated-section');
1123 var files = this.collectSelectedFiles($section);
1124
1125 if (files.length === 0) {
1126 Vigilante_Admin.showNotice('error', strings.bulkNoSelection || 'Select at least one file first.');
1127 return;
1128 }
1129
1130 if (!confirm(strings.bulkConfirmIgnore || 'Ignore the selected files?')) {
1131 return;
1132 }
1133
1134 var originalText = $btn.text();
1135 $btn.prop('disabled', true).text(strings.bulkProcessing || 'Processing...');
1136
1137 $.ajax({
1138 url: vigilanteAdmin.ajaxUrl,
1139 type: 'POST',
1140 data: {
1141 action: 'vigilante_bulk_ignore_files',
1142 nonce: vigilanteAdmin.nonce,
1143 files: files
1144 },
1145 success: function(response) {
1146 if (response.success) {
1147 // Remove processed rows from this section
1148 files.forEach(function(file) {
1149 $section.find('.vigilante-fi-cb').filter(function() {
1150 return $(this).val() === file;
1151 }).closest('tr').remove();
1152 });
1153 $section.find('.vigilante-fi-cb-all').prop('checked', false);
1154 Vigilante_Admin.refreshFilePagination($section);
1155 self.refreshBulkBar($section);
1156 Vigilante_Admin.showNotice('success', (response.data && response.data.message) || strings.fileIgnored);
1157 } else {
1158 Vigilante_Admin.showNotice('error', (response.data && response.data.message) || response.data || 'Failed to ignore files');
1159 $btn.prop('disabled', false).text(originalText);
1160 }
1161 },
1162 error: function() {
1163 $btn.prop('disabled', false).text(originalText);
1164 },
1165 // Restore the label on success too. refreshBulkBar() re-derives the
1166 // disabled state from the remaining selection but never rewrites the
1167 // button text, so without this the button stays on "Processing...".
1168 complete: function() {
1169 $btn.text(originalText);
1170 }
1171 });
1172 },
1173
1174 /**
1175 * Bulk remove from ignored list.
1176 */
1177 handleBulkUnignore: function(e) {
1178 e.preventDefault();
1179 var self = this;
1180 var strings = vigilanteAdmin.strings;
1181 var $btn = $(e.currentTarget);
1182 var $section = $btn.closest('.vigilante-paginated-section');
1183 var files = this.collectSelectedFiles($section);
1184
1185 if (files.length === 0) {
1186 Vigilante_Admin.showNotice('error', strings.bulkNoSelection || 'Select at least one file first.');
1187 return;
1188 }
1189
1190 if (!confirm(strings.bulkConfirmUnignore || 'Remove the selected files from ignored list?')) {
1191 return;
1192 }
1193
1194 var originalText = $btn.text();
1195 $btn.prop('disabled', true).text(strings.bulkProcessing || 'Processing...');
1196
1197 $.ajax({
1198 url: vigilanteAdmin.ajaxUrl,
1199 type: 'POST',
1200 data: {
1201 action: 'vigilante_bulk_unignore_files',
1202 nonce: vigilanteAdmin.nonce,
1203 files: files
1204 },
1205 success: function(response) {
1206 if (response.success) {
1207 files.forEach(function(file) {
1208 $section.find('.vigilante-fi-cb').filter(function() {
1209 return $(this).val() === file;
1210 }).closest('tr').remove();
1211 });
1212 $section.find('.vigilante-fi-cb-all').prop('checked', false);
1213 Vigilante_Admin.refreshFilePagination($section);
1214 self.refreshBulkBar($section);
1215 Vigilante_Admin.showNotice('success', (response.data && response.data.message) || strings.fileUnignored);
1216
1217 // If the ignored table is now empty, hide its section.
1218 if ($section.find('table.vigilante-fi-paginated tbody tr').length === 0) {
1219 $('#vigilante-section-fi-ignored').fadeOut(300, function() { $(this).remove(); });
1220 }
1221 } else {
1222 Vigilante_Admin.showNotice('error', (response.data && response.data.message) || response.data || 'Failed');
1223 $btn.prop('disabled', false).text(originalText);
1224 }
1225 },
1226 error: function() {
1227 $btn.prop('disabled', false).text(originalText);
1228 },
1229 // Restore the label on success too. refreshBulkBar() re-derives the
1230 // disabled state from the remaining selection but never rewrites the
1231 // button text, so without this the button stays on "Processing...".
1232 complete: function() {
1233 $btn.text(originalText);
1234 }
1235 });
1236 },
1237
1238 /**
1239 * Display scan results
1240 */
1241 displayScanResults: function(results, $container, ignoredCount) {
1242 // Ensure arrays exist
1243 results.modified = results.modified || [];
1244 results.suspicious = results.suspicious || [];
1245 results.extra = results.extra || [];
1246 results.missing = results.missing || [];
1247
1248 var strings = vigilanteAdmin.strings;
1249 var esc = Vigilante_Admin.escapeHtml;
1250
1251 var html = '<h2>' + strings.scanResults + '</h2>';
1252 html += '<div class="vigilante-scan-summary">';
1253 html += '<div class="vigilante-scan-stat vigilante-stat-ok">';
1254 html += '<span class="vigilante-stat-number">' + (results.ok || 0) + '</span>';
1255 html += '<span class="vigilante-stat-label">' + strings.ok + '</span>';
1256 html += '</div>';
1257 html += '<div class="vigilante-scan-stat vigilante-stat-modified">';
1258 html += '<span class="vigilante-stat-number">' + results.modified.length + '</span>';
1259 html += '<span class="vigilante-stat-label">' + strings.modified + '</span>';
1260 html += '</div>';
1261 html += '<div class="vigilante-scan-stat vigilante-stat-suspicious">';
1262 html += '<span class="vigilante-stat-number">' + results.suspicious.length + '</span>';
1263 html += '<span class="vigilante-stat-label">' + strings.suspicious + '</span>';
1264 html += '</div>';
1265 html += '<div class="vigilante-scan-stat vigilante-stat-extra">';
1266 html += '<span class="vigilante-stat-number">' + results.extra.length + '</span>';
1267 html += '<span class="vigilante-stat-label">' + (strings.extra || 'Extra') + '</span>';
1268 html += '</div>';
1269 if (ignoredCount > 0) {
1270 html += '<div class="vigilante-scan-stat vigilante-stat-ignored">';
1271 html += '<span class="vigilante-stat-number">' + ignoredCount + '</span>';
1272 html += '<span class="vigilante-stat-label">' + (strings.ignored || 'Ignored') + '</span>';
1273 html += '</div>';
1274 }
1275 html += '<div class="vigilante-scan-stat">';
1276 var computedTotal = (results.ok || 0) + results.modified.length + results.suspicious.length + results.extra.length + (ignoredCount || 0);
1277 html += '<span class="vigilante-stat-number">' + computedTotal + '</span>';
1278 html += '<span class="vigilante-stat-label">' + strings.totalScanned + '</span>';
1279 html += '</div>';
1280 html += '</div>';
1281
1282 var bulkBar = '<div class="vigilante-fi-bulk-bar">'
1283 + '<button type="button" class="button vigilante-bulk-ignore" disabled>' + (strings.bulkIgnoreSelected || 'Ignore selected') + '</button>'
1284 + '<span class="vigilante-fi-bulk-count" aria-live="polite"></span>'
1285 + '</div>';
1286 var selectAllCell = '<td class="manage-column column-cb check-column"><input type="checkbox" class="vigilante-fi-cb-all" aria-label="' + (strings.selectAll || 'Select all') + '"></td>';
1287
1288 // Suspicious files table
1289 if (results.suspicious.length > 0) {
1290 html += '<div class="vigilante-file-list vigilante-suspicious-files vigilante-paginated-section" data-bulk-mode="ignore">';
1291 html += '<h3 style="color: #d63638;">' + strings.suspiciousFiles + '</h3>';
1292 html += '<p class="description" style="color: #d63638;">' + strings.suspiciousWarning + '</p>';
1293 html += bulkBar;
1294 html += '<div class="vigilante-fi-pagination-wrap"></div>';
1295 html += '<table class="wp-list-table widefat fixed striped vigilante-fi-paginated">';
1296 html += '<thead><tr>' + selectAllCell + '<th>' + strings.file + '</th><th style="width: 250px;">' + strings.reason + '</th><th style="width: 120px;">' + strings.type + '</th><th style="width: 80px;">' + (strings.actions || 'Actions') + '</th></tr></thead>';
1297 html += '<tbody>';
1298 results.suspicious.forEach(function(file) {
1299 html += '<tr>';
1300 html += '<th scope="row" class="check-column"><input type="checkbox" class="vigilante-fi-cb" value="' + esc(file.file) + '"></th>';
1301 html += '<td><code style="color: #d63638;">' + esc(file.file) + '</code></td>';
1302 html += '<td>' + esc(file.reason || strings.unknown) + '</td>';
1303 html += '<td>' + esc(file.type || strings.unknown) + '</td>';
1304 html += '<td><button type="button" class="button button-small vigilante-ignore-file" data-file="' + esc(file.file) + '">' + (strings.ignore || 'Ignore') + '</button></td>';
1305 html += '</tr>';
1306 });
1307 html += '</tbody></table>';
1308 html += '</div>';
1309 }
1310
1311 // Extra files table
1312 if (results.extra.length > 0) {
1313 html += '<div class="vigilante-file-list vigilante-extra-files vigilante-paginated-section" data-bulk-mode="ignore">';
1314 html += '<h3 style="color: #b32d2e;">' + (strings.extraFiles || 'Extra Files') + '</h3>';
1315 html += '<p class="description">' + (strings.extraDescription || 'PHP files not in original distribution.') + '</p>';
1316 html += bulkBar;
1317 html += '<div class="vigilante-fi-pagination-wrap"></div>';
1318 html += '<table class="wp-list-table widefat fixed striped vigilante-fi-paginated">';
1319 html += '<thead><tr>' + selectAllCell + '<th>' + strings.file + '</th><th style="width: 250px;">' + strings.reason + '</th><th style="width: 120px;">' + strings.type + '</th><th style="width: 80px;">' + (strings.actions || 'Actions') + '</th></tr></thead>';
1320 html += '<tbody>';
1321 results.extra.forEach(function(file) {
1322 html += '<tr>';
1323 html += '<th scope="row" class="check-column"><input type="checkbox" class="vigilante-fi-cb" value="' + esc(file.file) + '"></th>';
1324 html += '<td><code style="color: #b32d2e;">' + esc(file.file) + '</code></td>';
1325 html += '<td>' + esc(file.reason || strings.unknown) + '</td>';
1326 html += '<td>' + esc(file.type || strings.unknown) + '</td>';
1327 html += '<td><button type="button" class="button button-small vigilante-ignore-file" data-file="' + esc(file.file) + '">' + (strings.ignore || 'Ignore') + '</button></td>';
1328 html += '</tr>';
1329 });
1330 html += '</tbody></table>';
1331 html += '</div>';
1332 }
1333
1334 // Split critical config from regular modified
1335 var criticalModified = [];
1336 var regularModified = [];
1337 results.modified.forEach(function(file) {
1338 if (file.type === 'critical_config') {
1339 criticalModified.push(file);
1340 } else {
1341 regularModified.push(file);
1342 }
1343 });
1344
1345 // Critical config files section (same visual treatment as suspicious files)
1346 if (criticalModified.length > 0) {
1347 html += '<div class="vigilante-file-list vigilante-critical-config-files">';
1348 html += '<h3 style="color: #e36210;">' + (strings.criticalConfigTitle || 'Critical config files modified') + '</h3>';
1349 html += '<p class="description">' + (strings.criticalConfigDesc || '') + '</p>';
1350 html += '<table class="wp-list-table widefat fixed striped">';
1351 html += '<thead><tr><th>' + strings.file + '</th><th style="width: 200px;">' + (strings.changes || 'Changes') + '</th><th style="width: 220px;">' + (strings.actions || 'Actions') + '</th></tr></thead>';
1352 html += '<tbody>';
1353
1354 // Delega en el escapador del objeto, que codifica comillas. La
1355 // version anterior era $('<span>').text(s).html(), que no las toca:
1356 // aqui solo se usa en posicion de texto, pero es el patron del
1357 // CVE-2026-81754 esperando a que alguien lo mueva a un atributo.
1358 var escHtml = Vigilante_Admin.escapeHtml;
1359
1360 criticalModified.forEach(function(file) {
1361 var fileId = file.file.replace(/[^a-z0-9]/gi, '-');
1362 var baselineSize = file.baseline_size ? Number(file.baseline_size).toLocaleString() : '?';
1363 var currentSize = file.current_size ? Number(file.current_size).toLocaleString() : '?';
1364 var diff = file.diff || {};
1365 var added = diff.added || [];
1366 var removed = diff.removed || [];
1367 var diffUnavailable = !!diff.unavailable;
1368
1369 // Main row
1370 html += '<tr>';
1371 html += '<td><code style="color: #e36210;">' + esc(file.file) + '</code></td>';
1372 html += '<td>';
1373 if (!diffUnavailable) {
1374 html += '<span style="color: #007017;">+' + added.length + '</span> <span style="color: #b32d2e;">-' + removed.length + '</span> ' + (strings.diffLines || 'lines') + '<br>';
1375 }
1376 html += '<small style="color: #50575e;">' + baselineSize + ' &rarr; ' + currentSize + ' bytes</small>';
1377 html += '</td>';
1378 html += '<td>';
1379 html += '<button type="button" class="button button-small vigilante-toggle-critical-content" data-target="vigilante-critical-content-' + fileId + '" data-label-show="' + (strings.reviewChanges || 'Review changes') + '" data-label-hide="' + (strings.hideChanges || 'Hide changes') + '">' + (strings.reviewChanges || 'Review changes') + '</button> ';
1380
1381 // Same gate as the AJAX handler behind the button, and as the
1382 // first render in PHP. Since 2.11.3 approving these two files
1383 // takes a network administrator, so painting the button to
1384 // anybody else buys them a Permission denied and no reason why.
1385 //
1386 // Truthy test on purpose: wp_localize_script() casts every
1387 // scalar to a string, so the PHP boolean arrives here as "1"
1388 // or "" and never as true. Measured on the network, admin of
1389 // a subsite against network admin. A === true would gate
1390 // nobody and would look right.
1391 if (vigilanteAdmin.approvalLocked) {
1392 html += '<span class="description" style="display:block;margin-top:4px;">' + escHtml(strings.approvalLockedNotice || '') + '</span>';
1393 } else {
1394 html += '<button type="button" class="button button-small button-primary vigilante-approve-critical-file" data-file="' + esc(file.file) + '">' + (strings.approve || 'Approve') + '</button>';
1395 }
1396 html += '</td>';
1397 html += '</tr>';
1398
1399 // Expandable diff row
1400 html += '<tr id="vigilante-critical-content-' + fileId + '" class="vigilante-critical-content-row" style="display:none;">';
1401 html += '<td colspan="3" style="padding: 0;">';
1402 html += '<div class="vigilante-critical-content" style="max-height: 400px; overflow: auto; background: #fff; padding: 10px; font-size: 12px; line-height: 1.5; font-family: Consolas, Monaco, monospace; border-top: 1px solid #c3c4c7;">';
1403 if (diffUnavailable) {
1404 html += '<p style="color: #50575e; font-style: italic; margin: 0;">' + (strings.diffUnavailable || 'Diff not available.') + '</p>';
1405 } else if (added.length === 0 && removed.length === 0) {
1406 html += '<p style="color: #50575e; font-style: italic; margin: 0;">' + (strings.diffEmpty || 'No line changes detected.') + '</p>';
1407 } else {
1408 removed.forEach(function(rline) {
1409 html += '<div style="background: #fbeaea; color: #b32d2e; padding: 1px 4px; white-space: pre-wrap; word-wrap: break-word;"><span style="display: inline-block; width: 50px; color: #999; user-select: none;">' + (rline.line || 0) + '</span>- ' + escHtml(rline.content || '') + '</div>';
1410 });
1411 added.forEach(function(aline) {
1412 html += '<div style="background: #e6f4e9; color: #007017; padding: 1px 4px; white-space: pre-wrap; word-wrap: break-word;"><span style="display: inline-block; width: 50px; color: #999; user-select: none;">' + (aline.line || 0) + '</span>+ ' + escHtml(aline.content || '') + '</div>';
1413 });
1414 }
1415 html += '</div>';
1416 html += '</td>';
1417 html += '</tr>';
1418 });
1419
1420 html += '</tbody></table>';
1421 html += '</div>';
1422 }
1423
1424 // Regular modified files table
1425 if (regularModified.length > 0) {
1426 html += '<div class="vigilante-file-list vigilante-paginated-section" data-bulk-mode="ignore">';
1427 html += '<h3>' + strings.modifiedFiles + '</h3>';
1428 html += '<p class="description">' + strings.modifiedDescription + '</p>';
1429 html += bulkBar;
1430 html += '<div class="vigilante-fi-pagination-wrap"></div>';
1431 html += '<table class="wp-list-table widefat fixed striped vigilante-fi-paginated">';
1432 html += '<thead><tr>' + selectAllCell + '<th>' + strings.file + '</th><th style="width: 100px;">' + strings.type + '</th><th style="width: 80px;">' + (strings.actions || 'Actions') + '</th></tr></thead>';
1433 html += '<tbody>';
1434 regularModified.forEach(function(file) {
1435 html += '<tr>';
1436 html += '<th scope="row" class="check-column"><input type="checkbox" class="vigilante-fi-cb" value="' + esc(file.file) + '"></th>';
1437 html += '<td><code>' + esc(file.file) + '</code></td>';
1438 html += '<td>' + esc(file.type || strings.unknown) + '</td>';
1439 html += '<td><button type="button" class="button button-small vigilante-ignore-file" data-file="' + esc(file.file) + '">' + (strings.ignore || 'Ignore') + '</button></td>';
1440 html += '</tr>';
1441 });
1442 html += '</tbody></table>';
1443 html += '</div>';
1444 }
1445
1446 if (results.modified.length === 0 && results.suspicious.length === 0 && results.extra.length === 0) {
1447 html += '<div class="vigilante-all-clear"><span class="dashicons dashicons-yes-alt"></span> ' + strings.allClear + '</div>';
1448 }
1449
1450 $container.html(html).show();
1451
1452 // Initialize client-side pagination for file integrity tables
1453 this.initFileIntegrityPagination($container);
1454 },
1455
1456 /**
1457 * Initialize client-side pagination for file integrity tables
1458 * Works on both PHP-rendered (last results) and JS-rendered (live scan) tables
1459 *
1460 * @param {jQuery} $scope Optional scope to limit search (for live scan results)
1461 */
1462 initFileIntegrityPagination: function($scope) {
1463 var perPage = 20;
1464 var $context = $scope || $(document);
1465
1466 $context.find('table.vigilante-fi-paginated').each(function() {
1467 var $table = $(this);
1468 var $rows = $table.find('tbody tr');
1469 var total = $rows.length;
1470
1471 if (total === 0) {
1472 return;
1473 }
1474
1475 // Store state on the parent container
1476 var $container = $table.closest('.vigilante-paginated-section');
1477 $container.data('fi-page', 1);
1478 $container.data('fi-per-page', perPage);
1479 $container.data('fi-total', total);
1480
1481 // Hide rows beyond first page (only if more than perPage)
1482 if (total > perPage) {
1483 $rows.each(function(index) {
1484 $(this).toggle(index < perPage);
1485 });
1486 }
1487
1488 // Build pagination controls (always show count, buttons only when needed)
1489 var $wrap = $container.find('.vigilante-fi-pagination-wrap');
1490 var paginationHtml = Vigilante_Admin.buildFilePaginationHtml(1, perPage, total);
1491 $wrap.html(paginationHtml);
1492 });
1493 },
1494
1495 /**
1496 * Build pagination HTML for file integrity tables
1497 */
1498 buildFilePaginationHtml: function(page, perPage, total) {
1499 var totalPages = Math.ceil(total / perPage) || 1;
1500 var from = total > 0 ? ((page - 1) * perPage) + 1 : 0;
1501 var to = Math.min(page * perPage, total);
1502 var needsNav = total > perPage;
1503
1504 var text = total > 0
1505 ? (vigilanteAdmin.strings.paginationOf || '%1$d–%2$d of %3$d').replace('%1$d', from).replace('%2$d', to).replace('%3$d', total)
1506 : (vigilanteAdmin.strings.paginationEmpty || '0 items');
1507
1508 var prevDisabled = page <= 1 ? ' disabled' : '';
1509 var nextDisabled = page >= totalPages ? ' disabled' : '';
1510
1511 var html = '<span class="vigilante-pagination vigilante-fi-pagination">';
1512 if (needsNav) {
1513 html += '<button type="button" class="vigilante-page-first" title="First"' + prevDisabled + '>&laquo;</button>';
1514 html += '<button type="button" class="vigilante-page-prev" title="Previous"' + prevDisabled + '>&lsaquo;</button>';
1515 }
1516 html += '<span class="vigilante-page-info">' + text + '</span>';
1517 if (needsNav) {
1518 html += '<button type="button" class="vigilante-page-next" title="Next"' + nextDisabled + '>&rsaquo;</button>';
1519 html += '<button type="button" class="vigilante-page-last" title="Last"' + nextDisabled + '>&raquo;</button>';
1520 }
1521 html += '</span>';
1522
1523 return html;
1524 },
1525
1526 /**
1527 * Navigate file integrity table pages (client-side)
1528 */
1529 goToFilePage: function($container, direction) {
1530 var page = $container.data('fi-page') || 1;
1531 var perPage = $container.data('fi-per-page') || 20;
1532 var total = $container.data('fi-total') || 0;
1533 var totalPages = Math.ceil(total / perPage) || 1;
1534
1535 switch (direction) {
1536 case 'first': page = 1; break;
1537 case 'prev': page = Math.max(1, page - 1); break;
1538 case 'next': page = Math.min(totalPages, page + 1); break;
1539 case 'last': page = totalPages; break;
1540 }
1541
1542 $container.data('fi-page', page);
1543
1544 // Show/hide rows
1545 var start = (page - 1) * perPage;
1546 var end = start + perPage;
1547 $container.find('table.vigilante-fi-paginated tbody tr').each(function(index) {
1548 $(this).toggle(index >= start && index < end);
1549 });
1550
1551 // Update controls
1552 var $wrap = $container.find('.vigilante-fi-pagination-wrap');
1553 $wrap.html(this.buildFilePaginationHtml(page, perPage, total));
1554
1555 // Sync the "select all" header with what is now visible.
1556 // Selections in other pages remain checked and will be included
1557 // in any bulk action, but the header reflects only this page.
1558 var $allCb = $container.find('.vigilante-fi-cb-all');
1559 if ($allCb.length) {
1560 var $visible = $container.find('table.vigilante-fi-paginated tbody tr:visible .vigilante-fi-cb');
1561 var $checked = $visible.filter(':checked');
1562 $allCb.prop('checked', $visible.length > 0 && $checked.length === $visible.length);
1563 }
1564 },
1565
1566 /**
1567 * Refresh file integrity pagination after row removal (ignore)
1568 */
1569 refreshFilePagination: function($container) {
1570 var perPage = $container.data('fi-per-page') || 20;
1571 var $rows = $container.find('table.vigilante-fi-paginated tbody tr');
1572 var total = $rows.length;
1573
1574 $container.data('fi-total', total);
1575
1576 if (total === 0) {
1577 $container.find('.vigilante-fi-pagination-wrap').empty();
1578 return;
1579 }
1580
1581 if (total <= perPage) {
1582 // Show all rows, display count only
1583 $rows.show();
1584 $container.data('fi-page', 1);
1585 var $wrap = $container.find('.vigilante-fi-pagination-wrap');
1586 $wrap.html(this.buildFilePaginationHtml(1, perPage, total));
1587 return;
1588 }
1589
1590 // Ensure current page is still valid
1591 var page = $container.data('fi-page') || 1;
1592 var totalPages = Math.ceil(total / perPage);
1593 if (page > totalPages) {
1594 page = totalPages;
1595 }
1596 $container.data('fi-page', page);
1597
1598 // Show/hide rows for current page
1599 var start = (page - 1) * perPage;
1600 var end = start + perPage;
1601 $rows.each(function(index) {
1602 $(this).toggle(index >= start && index < end);
1603 });
1604
1605 var $wrap = $container.find('.vigilante-fi-pagination-wrap');
1606 $wrap.html(this.buildFilePaginationHtml(page, perPage, total));
1607 },
1608
1609 /**
1610 * Handle export settings
1611 */
1612 handleExportSettings: function(e) {
1613 e.preventDefault();
1614
1615 $.ajax({
1616 url: vigilanteAdmin.ajaxUrl,
1617 type: 'POST',
1618 data: {
1619 action: 'vigilante_export_settings',
1620 nonce: vigilanteAdmin.nonce
1621 },
1622 success: function(response) {
1623 if (response.success) {
1624 var blob = new Blob([response.data.content], { type: 'application/json' });
1625 var url = URL.createObjectURL(blob);
1626 var a = document.createElement('a');
1627 a.href = url;
1628 a.download = response.data.filename;
1629 document.body.appendChild(a);
1630 a.click();
1631 document.body.removeChild(a);
1632 URL.revokeObjectURL(url);
1633 } else {
1634 Vigilante_Admin.showNotice('error', response.data);
1635 }
1636 }
1637 });
1638 },
1639
1640 /**
1641 * Handle import settings click
1642 */
1643 handleImportSettings: function(e) {
1644 e.preventDefault();
1645 $('#vigilante-import-file').trigger('click');
1646 },
1647
1648 /**
1649 * Handle import file selection
1650 */
1651 handleImportFile: function(e) {
1652 var file = e.target.files[0];
1653 if (!file) return;
1654
1655 var reader = new FileReader();
1656 reader.onload = function(e) {
1657 if (!confirm(vigilanteAdmin.strings.confirm + ' ' + (vigilanteAdmin.strings.confirmOverwrite || 'This will overwrite your current settings.'))) {
1658 return;
1659 }
1660
1661 $.ajax({
1662 url: vigilanteAdmin.ajaxUrl,
1663 type: 'POST',
1664 data: {
1665 action: 'vigilante_import_settings',
1666 nonce: vigilanteAdmin.nonce,
1667 settings: e.target.result
1668 },
1669 success: function(response) {
1670 if (response.success) {
1671 Vigilante_Admin.showNotice('success', response.data);
1672 setTimeout(function() {
1673 location.reload();
1674 }, 1000);
1675 } else {
1676 Vigilante_Admin.showNotice('error', response.data || vigilanteAdmin.strings.importFailed);
1677 }
1678 },
1679 error: function() {
1680 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.importFailed);
1681 }
1682 });
1683 };
1684 reader.readAsText(file);
1685 },
1686
1687 /**
1688 * Handle reset settings
1689 */
1690 handleResetSettings: function(e) {
1691 e.preventDefault();
1692
1693 if (!confirm(vigilanteAdmin.strings.confirm + ' ' + (vigilanteAdmin.strings.confirmResetAll || 'This will reset ALL settings to defaults.'))) {
1694 return;
1695 }
1696
1697 $.ajax({
1698 url: vigilanteAdmin.ajaxUrl,
1699 type: 'POST',
1700 data: {
1701 action: 'vigilante_apply_preset',
1702 nonce: vigilanteAdmin.nonce,
1703 preset: 'reset'
1704 },
1705 success: function(response) {
1706 if (response.success) {
1707 Vigilante_Admin.showNotice('success', vigilanteAdmin.strings.settingsResetDefaults || 'Settings reset to defaults.');
1708 setTimeout(function() {
1709 location.reload();
1710 }, 1000);
1711 } else {
1712 Vigilante_Admin.showNotice('error', response.data);
1713 }
1714 }
1715 });
1716 },
1717
1718 /**
1719 * Handle test headers
1720 */
1721 handleTestHeaders: function(e) {
1722 e.preventDefault();
1723
1724 var $btn = $(e.currentTarget);
1725 var $results = $('#vigilante-headers-result');
1726
1727 $btn.prop('disabled', true).html(vigilanteAdmin.strings.testing + ' <span class="vigilante-spinner"></span>');
1728
1729 $.ajax({
1730 url: vigilanteAdmin.ajaxUrl,
1731 type: 'POST',
1732 data: {
1733 action: 'vigilante_test_headers',
1734 nonce: vigilanteAdmin.nonce
1735 },
1736 success: function(response) {
1737 if (response.success) {
1738 Vigilante_Admin.displayHeaderResults(response.data, $results);
1739 } else {
1740 Vigilante_Admin.showNotice('error', response.data);
1741 }
1742 },
1743 complete: function() {
1744 $btn.prop('disabled', false).text(vigilanteAdmin.strings.testHeaders);
1745 }
1746 });
1747 },
1748
1749 /**
1750 * Handle login URL notification button
1751 */
1752 handleNotifyLoginUrl: function(e) {
1753 e.preventDefault();
1754
1755 var $btn = $(e.currentTarget);
1756 var $status = $btn.siblings('.vigilante-login-url-notify-status');
1757
1758 $btn.prop('disabled', true).text(vigilanteAdmin.strings.sending || 'Sending...');
1759 $status.removeClass('success error').text('');
1760
1761 $.ajax({
1762 url: vigilanteAdmin.ajaxUrl,
1763 type: 'POST',
1764 data: {
1765 action: 'vigilante_notify_login_url',
1766 nonce: vigilanteAdmin.nonce
1767 },
1768 success: function(response) {
1769 if (response.success) {
1770 var msg = response.data.sent + ' ' + (vigilanteAdmin.strings.notificationsSent || 'notifications sent');
1771 if (response.data.failed > 0) {
1772 msg += ', ' + response.data.failed + ' ' + (vigilanteAdmin.strings.failed || 'failed');
1773 }
1774 $status.addClass('success').text(msg);
1775 } else {
1776 $status.addClass('error').text(response.data || 'Error');
1777 }
1778 },
1779 error: function() {
1780 $status.addClass('error').text('Error');
1781 },
1782 complete: function() {
1783 $btn.prop('disabled', false).text(vigilanteAdmin.strings.sendNotification || 'Send notification now');
1784 }
1785 });
1786 },
1787
1788 /**
1789 * Toggle login URL notification section based on URL input
1790 */
1791 handleLoginUrlToggle: function() {
1792 var hasUrl = $('#vigilante_custom_login_url').val().trim().length > 0;
1793 $('.vigilante-login-url-notify-wrapper').toggleClass('vigilante-login-url-notify-disabled', !hasUrl);
1794 $('.vigilante-login-url-preview').toggle(hasUrl);
1795 },
1796
1797 /**
1798 * Display header test results
1799 */
1800 displayHeaderResults: function(results, $container) {
1801 var gradeClass = 'vigilante-grade-' + results.grade.toLowerCase();
1802 var html = '<div class="vigilante-security-score" style="text-align: center; padding: 20px;">';
1803 html += '<div class="vigilante-score-circle ' + gradeClass + '">';
1804 html += '<span class="vigilante-grade">' + results.grade + '</span>';
1805 html += '</div>';
1806 html += '<p style="text-align: center;"><strong>' + vigilanteAdmin.strings.score + ':</strong> ' + Math.round(results.score) + '%</p>';
1807 html += '</div>';
1808
1809 if (results.headers.length > 0) {
1810 html += '<p><strong>' + vigilanteAdmin.strings.enabledHeaders + ':</strong></p><ul>';
1811 results.headers.forEach(function(header) {
1812 html += '<li class="enabled">&#10003; ' + header + '</li>';
1813 });
1814 html += '</ul>';
1815 }
1816
1817 if (results.missing.length > 0) {
1818 html += '<p><strong>' + vigilanteAdmin.strings.missingHeaders + ':</strong></p><ul>';
1819 results.missing.forEach(function(header) {
1820 html += '<li class="missing">&#10007; ' + header + '</li>';
1821 });
1822 html += '</ul>';
1823 }
1824
1825 if (results.warnings && results.warnings.length > 0) {
1826 html += '<p><strong>' + vigilanteAdmin.strings.warnings + ':</strong></p><ul>';
1827 results.warnings.forEach(function(warning) {
1828 html += '<li class="warning">&#9888; ' + warning + '</li>';
1829 });
1830 html += '</ul>';
1831 }
1832
1833 $container.html(html).addClass('visible');
1834 },
1835
1836 /**
1837 * Handle activity log filter
1838 */
1839 handleLogFilter: function() {
1840 this.logPage = 1;
1841 this.loadActivityLogs();
1842 },
1843
1844 /**
1845 * Handle activity log search with debounce (400ms, min 3 chars)
1846 */
1847 handleLogSearch: function() {
1848 var self = this;
1849 clearTimeout(this.logSearchTimer);
1850 this.logSearchTimer = setTimeout(function() {
1851 var term = $('#vigilante-log-search').val().trim();
1852 // Only search with 3+ chars, or clear search when empty
1853 if (term.length >= 3 || term.length === 0) {
1854 self.logPage = 1;
1855 self.loadActivityLogs();
1856 }
1857 }, 400);
1858 },
1859
1860 /**
1861 * Load activity logs via AJAX (with filters and pagination)
1862 */
1863 loadActivityLogs: function() {
1864 var type = $('#vigilante-log-type-filter').val();
1865 var severity = $('#vigilante-log-severity-filter').val();
1866 var method = $('#vigilante-log-method-filter').val();
1867 var search = $('#vigilante-log-search').val();
1868 var $refreshBtn = $('#vigilante-log-refresh');
1869
1870 // Visual feedback
1871 $refreshBtn.prop('disabled', true).addClass('updating-message');
1872
1873 var data = {
1874 action: 'vigilante_get_logs',
1875 nonce: vigilanteAdmin.nonce,
1876 per_page: this.logPerPage,
1877 page: this.logPage,
1878 type: type,
1879 severity: severity
1880 };
1881
1882 if (method) {
1883 data.request_method = method;
1884 }
1885
1886 if (search && search.trim().length >= 3) {
1887 data.search = search.trim();
1888 }
1889
1890 $.ajax({
1891 url: vigilanteAdmin.ajaxUrl,
1892 type: 'POST',
1893 data: data,
1894 success: function(response) {
1895 if (response.success) {
1896 Vigilante_Admin.renderLogTable(response.data.logs);
1897 Vigilante_Admin.updateLogPagination(response.data.total);
1898 } else {
1899 Vigilante_Admin.showNotice('error', response.data || vigilanteAdmin.strings.error);
1900 }
1901 },
1902 error: function() {
1903 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error || 'Request failed');
1904 },
1905 complete: function() {
1906 $refreshBtn.prop('disabled', false).removeClass('updating-message');
1907 }
1908 });
1909 },
1910
1911 /**
1912 * Navigate activity log pages
1913 */
1914 goToLogPage: function(direction) {
1915 var $pagination = $('#vigilante-log-pagination');
1916 var total = parseInt($pagination.attr('data-total'), 10) || 0;
1917 var totalPages = Math.ceil(total / this.logPerPage) || 1;
1918
1919 switch (direction) {
1920 case 'first': this.logPage = 1; break;
1921 case 'prev': this.logPage = Math.max(1, this.logPage - 1); break;
1922 case 'next': this.logPage = Math.min(totalPages, this.logPage + 1); break;
1923 case 'last': this.logPage = totalPages; break;
1924 }
1925
1926 this.loadActivityLogs();
1927 },
1928
1929 /**
1930 * Update activity log pagination controls
1931 */
1932 updateLogPagination: function(total) {
1933 var $pagination = $('#vigilante-log-pagination');
1934 total = parseInt(total, 10) || 0;
1935 var totalPages = Math.ceil(total / this.logPerPage) || 1;
1936 var needsNav = total > this.logPerPage;
1937
1938 $pagination.attr('data-total', total);
1939 $pagination.attr('data-page', this.logPage);
1940
1941 var from = total > 0 ? ((this.logPage - 1) * this.logPerPage) + 1 : 0;
1942 var to = Math.min(this.logPage * this.logPerPage, total);
1943
1944 var text = total > 0
1945 ? (vigilanteAdmin.strings.paginationOf || '%1$d–%2$d of %3$d').replace('%1$d', from).replace('%2$d', to).replace('%3$d', total)
1946 : (vigilanteAdmin.strings.paginationEmpty || '0 items');
1947
1948 var prevDisabled = this.logPage <= 1 ? ' disabled' : '';
1949 var nextDisabled = this.logPage >= totalPages ? ' disabled' : '';
1950
1951 var html = '';
1952 if (needsNav) {
1953 html += '<button type="button" class="vigilante-page-first"' + prevDisabled + '>&laquo;</button>';
1954 html += '<button type="button" class="vigilante-page-prev"' + prevDisabled + '>&lsaquo;</button>';
1955 }
1956 html += '<span class="vigilante-page-info">' + text + '</span>';
1957 if (needsNav) {
1958 html += '<button type="button" class="vigilante-page-next"' + nextDisabled + '>&rsaquo;</button>';
1959 html += '<button type="button" class="vigilante-page-last"' + nextDisabled + '>&raquo;</button>';
1960 }
1961
1962 $pagination.html(html);
1963 },
1964
1965 /**
1966 * Render log table
1967 */
1968 renderLogTable: function(logs) {
1969 var $tbody = $('#vigilante-activity-log-table tbody');
1970 $tbody.empty();
1971
1972 if (logs.length === 0) {
1973 $tbody.append('<tr><td colspan="8">' + (vigilanteAdmin.strings.noLogEntries || 'No log entries found.') + '</td></tr>');
1974 return;
1975 }
1976
1977 var self = this;
1978 var typeLabels = (vigilanteAdmin.strings && vigilanteAdmin.strings.eventTypeLabels) || {};
1979 var severityLabels = (vigilanteAdmin.strings && vigilanteAdmin.strings.severityLabels) || {};
1980
1981 logs.forEach(function(log) {
1982 var details = {
1983 id: log.id,
1984 type: log.event_type || '',
1985 action: log.event_action || '',
1986 message: log.event_message || '',
1987 user: log.user_login || '',
1988 ip: log.ip_address || '',
1989 user_agent: log.user_agent || '',
1990 request_method: log.request_method || '',
1991 request_uri: log.request_uri || '',
1992 date: log.created_at || '',
1993 severity: log.severity || 'info',
1994 is_ip_whitelisted: !!log.is_ip_whitelisted,
1995 is_ip_blacklisted: !!log.is_ip_blacklisted,
1996 is_ua_whitelisted: !!log.is_ua_whitelisted,
1997 is_ua_blacklisted: !!log.is_ua_blacklisted
1998 };
1999
2000 var displayType = typeLabels[log.event_type] || log.event_type;
2001 var displaySeverity = severityLabels[log.severity] || log.severity;
2002
2003 var methodHtml = '-';
2004 if (log.request_method) {
2005 methodHtml = '<span class="vigilante-method-label vigilante-method-' + self.escapeHtml(log.request_method.toLowerCase()) + '">' + self.escapeHtml(log.request_method) + '</span>';
2006 }
2007
2008 var row = '<tr class="vigilante-severity-' + self.escapeHtml(log.severity) + '">';
2009 row += '<td>' + self.escapeHtml(log.created_at) + '</td>';
2010 row += '<td>' + self.escapeHtml(displayType) + '</td>';
2011 row += '<td>' + methodHtml + '</td>';
2012 row += '<td><span class="vigilante-badge vigilante-badge-' + self.escapeHtml(log.severity) + '">' + self.escapeHtml(displaySeverity) + '</span></td>';
2013 row += '<td>' + self.escapeHtml(log.event_message) + '</td>';
2014 row += '<td>' + self.escapeHtml(log.user_login || '-') + '</td>';
2015 row += '<td><code>' + self.escapeHtml(log.ip_address) + '</code></td>';
2016 row += '<td><button type="button" class="button button-small vigilante-view-log-details" data-details=\'' + self.escapeHtml(JSON.stringify(details)) + '\'>' + (vigilanteAdmin.strings.view || 'View') + '</button></td>';
2017 row += '</tr>';
2018 $tbody.append(row);
2019 });
2020 },
2021
2022 /**
2023 * Handle export logs
2024 */
2025 handleExportLogs: function(e) {
2026 e.preventDefault();
2027
2028 var $btn = $(e.currentTarget);
2029 var type = $('#vigilante-log-type-filter').val();
2030 var severity = $('#vigilante-log-severity-filter').val();
2031 var method = $('#vigilante-log-method-filter').val();
2032 var search = $('#vigilante-log-search').val();
2033
2034 var data = {
2035 action: 'vigilante_get_logs',
2036 nonce: vigilanteAdmin.nonce,
2037 per_page: 9999
2038 };
2039
2040 // Only add filters if they have values
2041 if (type && type !== '') {
2042 data.type = type;
2043 }
2044 if (severity && severity !== '') {
2045 data.severity = severity;
2046 }
2047 if (method && method !== '') {
2048 data.request_method = method;
2049 }
2050 if (search && search.trim().length >= 3) {
2051 data.search = search.trim();
2052 }
2053
2054 $btn.prop('disabled', true).text(vigilanteAdmin.strings.exporting || 'Exporting...');
2055
2056 $.ajax({
2057 url: vigilanteAdmin.ajaxUrl,
2058 type: 'POST',
2059 data: data,
2060 success: function(response) {
2061 if (response.success && response.data.logs && response.data.logs.length > 0) {
2062 Vigilante_Admin.downloadCSV(response.data.logs);
2063 Vigilante_Admin.showNotice('success', (vigilanteAdmin.strings.logsExported || 'Logs exported (%d entries)').replace('%d', response.data.logs.length));
2064 } else {
2065 Vigilante_Admin.showNotice('warning', vigilanteAdmin.strings.noLogsToExport || 'No logs to export');
2066 }
2067 },
2068 error: function() {
2069 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.exportFailed || 'Export failed');
2070 },
2071 complete: function() {
2072 $btn.prop('disabled', false).text(vigilanteAdmin.strings.exportLogs || 'Export Logs');
2073 }
2074 });
2075 },
2076
2077 /**
2078 * Download logs as CSV
2079 *
2080 * Every cell goes through csvCell(): quotes are doubled in all columns,
2081 * not only the message, and a value starting with = + - @ or a control
2082 * character gets an apostrophe in front so a spreadsheet shows it
2083 * instead of running it as a formula (S12). Action, address and
2084 * User-Agent were added for B38: the columns that help diagnose an
2085 * entry were exactly the ones the export left out.
2086 */
2087 downloadCSV: function(logs) {
2088 var csvCell = function(value) {
2089 var s = (value === null || value === undefined) ? '' : String(value);
2090 if (/^[=+\-@\t\r]/.test(s)) {
2091 s = "'" + s;
2092 }
2093 return '"' + s.replace(/"/g, '""') + '"';
2094 };
2095 var csv = 'Date,Type,Action,Method,Severity,Message,User,IP,Address,User Agent\n';
2096
2097 logs.forEach(function(log) {
2098 csv += [
2099 csvCell(log.created_at),
2100 csvCell(log.event_type),
2101 csvCell(log.event_action),
2102 csvCell(log.request_method),
2103 csvCell(log.severity),
2104 csvCell(log.event_message),
2105 csvCell(log.user_login),
2106 csvCell(log.ip_address),
2107 csvCell(log.request_uri),
2108 csvCell(log.user_agent)
2109 ].join(',') + '\n';
2110 });
2111
2112 var blob = new Blob([csv], { type: 'text/csv' });
2113 var url = URL.createObjectURL(blob);
2114 var a = document.createElement('a');
2115 a.href = url;
2116 a.download = 'activity-log-' + new Date().toISOString().slice(0, 10) + '.csv';
2117 document.body.appendChild(a);
2118 a.click();
2119 document.body.removeChild(a);
2120 URL.revokeObjectURL(url);
2121 },
2122
2123 /**
2124 * Handle create backup
2125 */
2126 handleCreateBackup: function(e) {
2127 e.preventDefault();
2128
2129 var $btn = $(e.currentTarget);
2130 $btn.prop('disabled', true).html(vigilanteAdmin.strings.loading + ' <span class="vigilante-spinner"></span>');
2131
2132 // Direct file download via a hidden form (same pattern as the
2133 // database backup): the server streams a ZIP with wp-config.php and
2134 // .htaccess as an attachment.
2135 var $form = $('<form>', { method: 'POST', action: vigilanteAdmin.ajaxUrl });
2136 $form.append($('<input>', { type: 'hidden', name: 'action', value: 'vigilante_download_files_backup' }));
2137 $form.append($('<input>', { type: 'hidden', name: 'nonce', value: vigilanteAdmin.nonce }));
2138 $('body').append($form);
2139 $form.submit();
2140 $form.remove();
2141
2142 // Re-enable the button after a short delay (download runs in the background).
2143 setTimeout(function() {
2144 $btn.prop('disabled', false).text(vigilanteAdmin.strings.createBackupNow || 'Create Backup Now');
2145 }, 2000);
2146 },
2147
2148 // =================================================================
2149 // DATABASE BACKUP HANDLERS
2150 // =================================================================
2151
2152 /**
2153 * Toggle database backup panel and load tables
2154 */
2155 handleDbBackupToggle: function(e) {
2156 e.preventDefault();
2157
2158 var $panel = $('.vigilante-db-backup-panel');
2159 var $btn = $(e.currentTarget);
2160
2161 if ($panel.is(':visible')) {
2162 $panel.slideUp(200);
2163 return;
2164 }
2165
2166 $panel.slideDown(200);
2167
2168 // Load tables if not already loaded
2169 if ($panel.find('.vigilante-db-tables-content').is(':hidden')) {
2170 this.loadDbTables();
2171 }
2172 },
2173
2174 /**
2175 * Handle settings search input
2176 */
2177 searchActiveIndex: -1,
2178
2179 handleSettingsSearch: function(e) {
2180 var query = ($('#vigilante-settings-search').val() || '').trim().toLowerCase();
2181 var $results = $('#vigilante-settings-search-results');
2182 var index = (vigilanteAdmin.searchIndex || []);
2183
2184 if (query.length < 2) {
2185 $results.attr('hidden', true).empty();
2186 this.searchActiveIndex = -1;
2187 return;
2188 }
2189
2190 // Score every entry and sort before cutting. It used to stop at the
2191 // first 30 matches in index order, so a broad query ("password"
2192 // already returns 19) could hide the very row the user was after
2193 // behind whatever happened to be declared first.
2194 var scored = [];
2195 for (var i = 0; i < index.length; i++) {
2196 var entry = index[i];
2197 var label = (entry.label || '').toLowerCase();
2198 var labelEn = (entry.label_en || '').toLowerCase();
2199 var section = (entry.section || '').toLowerCase();
2200 var tabLabel = (entry.tab_label || '').toLowerCase();
2201 var keywords = (entry.keywords || '').toLowerCase();
2202 var score = 0;
2203
2204 if (label === query || labelEn === query) {
2205 score = 100;
2206 } else if (label.indexOf(query) === 0 || labelEn.indexOf(query) === 0) {
2207 score = 80;
2208 } else if (label.indexOf(query) !== -1 || labelEn.indexOf(query) !== -1) {
2209 score = 60;
2210 } else if (section.indexOf(query) !== -1) {
2211 score = 40;
2212 } else if (tabLabel.indexOf(query) !== -1) {
2213 score = 35;
2214 } else if (keywords.indexOf(query) !== -1) {
2215 score = 30;
2216 }
2217
2218 if (score > 0) {
2219 scored.push({ entry: entry, score: score, order: i });
2220 }
2221 }
2222
2223 scored.sort(function(a, b) {
2224 return (b.score - a.score) || (a.order - b.order);
2225 });
2226
2227 var matches = [];
2228 for (var t = 0; t < scored.length && matches.length < 30; t++) {
2229 matches.push(scored[t].entry);
2230 }
2231 var hiddenCount = scored.length - matches.length;
2232
2233 if (!matches.length) {
2234 $results.html('<div class="vigilante-search-empty">' + (vigilanteAdmin.strings.searchNoResults || 'No results') + '</div>').attr('hidden', false);
2235 this.searchActiveIndex = -1;
2236 return;
2237 }
2238
2239 // Group by tab
2240 var grouped = {};
2241 var tabOrder = [];
2242 for (var j = 0; j < matches.length; j++) {
2243 var m = matches[j];
2244 if (!grouped[m.tab]) {
2245 grouped[m.tab] = { label: m.tab_label, items: [] };
2246 tabOrder.push(m.tab);
2247 }
2248 grouped[m.tab].items.push(m);
2249 }
2250
2251 var html = '';
2252 var flatIdx = 0;
2253 for (var k = 0; k < tabOrder.length; k++) {
2254 var tab = tabOrder[k];
2255 var group = grouped[tab];
2256 html += '<div class="vigilante-search-group">';
2257 html += '<div class="vigilante-search-group-title">' + this.escapeHtml(group.label) + '</div>';
2258 for (var n = 0; n < group.items.length; n++) {
2259 var it = group.items[n];
2260 var base = (vigilanteAdmin.adminUrl || 'admin.php?page=vigilante');
2261 var href = base + '&tab=' + encodeURIComponent(it.tab) + '#' + encodeURIComponent(it.anchor);
2262 var activeClass = flatIdx === 0 ? ' vigilante-search-item-active' : '';
2263 html += '<a class="vigilante-search-item' + activeClass + '" data-idx="' + flatIdx + '" role="option" href="' + href + '">';
2264 html += '<span class="vigilante-search-item-label">' + this.escapeHtml(it.label) + '</span>';
2265 html += '<span class="vigilante-search-item-section">' + this.escapeHtml(it.section) + '</span>';
2266 html += '</a>';
2267 flatIdx++;
2268 }
2269 html += '</div>';
2270 }
2271
2272 if (hiddenCount > 0) {
2273 var moreTpl = vigilanteAdmin.strings.searchMoreResults || '%d more results, refine the search';
2274 html += '<div class="vigilante-search-more">' + this.escapeHtml(moreTpl.replace('%d', hiddenCount)) + '</div>';
2275 }
2276
2277 $results.html(html).attr('hidden', false);
2278 this.searchActiveIndex = 0;
2279 },
2280
2281 /**
2282 * Handle keyboard navigation in search: arrows move highlight, Enter navigates, Escape closes
2283 */
2284 handleSettingsSearchKey: function(e) {
2285 var $items = $('#vigilante-settings-search-results .vigilante-search-item');
2286
2287 if (e.key === 'Escape') {
2288 $('#vigilante-settings-search-results').attr('hidden', true);
2289 $('#vigilante-settings-search').blur();
2290 return;
2291 }
2292
2293 if (!$items.length) return;
2294
2295 if (e.key === 'ArrowDown') {
2296 e.preventDefault();
2297 this.searchActiveIndex = Math.min(this.searchActiveIndex + 1, $items.length - 1);
2298 this.updateSearchActive();
2299 } else if (e.key === 'ArrowUp') {
2300 e.preventDefault();
2301 this.searchActiveIndex = Math.max(this.searchActiveIndex - 1, 0);
2302 this.updateSearchActive();
2303 } else if (e.key === 'Home') {
2304 e.preventDefault();
2305 this.searchActiveIndex = 0;
2306 this.updateSearchActive();
2307 } else if (e.key === 'End') {
2308 e.preventDefault();
2309 this.searchActiveIndex = $items.length - 1;
2310 this.updateSearchActive();
2311 } else if (e.key === 'Enter') {
2312 e.preventDefault();
2313 var idx = this.searchActiveIndex >= 0 ? this.searchActiveIndex : 0;
2314 var $target = $items.eq(idx);
2315 if ($target.length) {
2316 window.location.href = $target.attr('href');
2317 }
2318 }
2319 },
2320
2321 /**
2322 * Sync active highlight when user hovers a search result
2323 */
2324 handleSettingsSearchHover: function(e) {
2325 var idx = parseInt($(e.currentTarget).attr('data-idx'), 10);
2326 if (isNaN(idx)) return;
2327 this.searchActiveIndex = idx;
2328 this.updateSearchActive(false);
2329 },
2330
2331 /**
2332 * Apply the active class to the current index and scroll it into view
2333 */
2334 updateSearchActive: function(scroll) {
2335 var $items = $('#vigilante-settings-search-results .vigilante-search-item');
2336 $items.removeClass('vigilante-search-item-active');
2337 var $active = $items.eq(this.searchActiveIndex);
2338 if (!$active.length) return;
2339 $active.addClass('vigilante-search-item-active');
2340 if (scroll !== false && $active[0] && typeof $active[0].scrollIntoView === 'function') {
2341 $active[0].scrollIntoView({ block: 'nearest' });
2342 }
2343 },
2344
2345 /**
2346 * Format bytes as a human-readable size
2347 */
2348 formatBytes: function(bytes) {
2349 if (!bytes || bytes < 0) return '0 B';
2350 var units = ['B', 'KB', 'MB', 'GB', 'TB'];
2351 var i = 0;
2352 var n = bytes;
2353 while (n >= 1024 && i < units.length - 1) {
2354 n = n / 1024;
2355 i++;
2356 }
2357 return (i === 0 ? n.toFixed(0) : n.toFixed(1)) + ' ' + units[i];
2358 },
2359
2360 /**
2361 * Update DB tables info: count + total size
2362 */
2363 updateDbTablesInfo: function() {
2364 var $boxes = $('.vigilante-db-table-check');
2365 var total = $boxes.length;
2366 if (!total) {
2367 $('.vigilante-db-tables-info').text('');
2368 return;
2369 }
2370 var $checked = $boxes.filter(':checked');
2371 var checkedCount = $checked.length;
2372 var bytes = 0;
2373 $checked.each(function() {
2374 bytes += parseInt($(this).attr('data-bytes'), 10) || 0;
2375 });
2376 var sizeStr = Vigilante_Admin.formatBytes(bytes);
2377 var tpl;
2378 if (checkedCount === total) {
2379 tpl = vigilanteAdmin.strings.dbTablesTotal || '%1$d tables total (%2$s)';
2380 $('.vigilante-db-tables-info').text(tpl.replace('%1$d', total).replace('%2$s', sizeStr));
2381 } else {
2382 tpl = vigilanteAdmin.strings.dbTablesSelected || '%1$d tables selected (%2$s)';
2383 $('.vigilante-db-tables-info').text(tpl.replace('%1$d', checkedCount).replace('%2$s', sizeStr));
2384 }
2385 },
2386
2387 /**
2388 * Load database tables via AJAX
2389 */
2390 loadDbTables: function() {
2391 $.ajax({
2392 url: vigilanteAdmin.ajaxUrl,
2393 type: 'POST',
2394 data: {
2395 action: 'vigilante_get_db_tables',
2396 nonce: vigilanteAdmin.nonce
2397 },
2398 success: function(response) {
2399 if (!response.success) {
2400 Vigilante_Admin.showNotice('error', response.data);
2401 return;
2402 }
2403
2404 var data = response.data;
2405 var coreHtml = '';
2406 var otherHtml = '';
2407
2408 // Build core tables checkboxes
2409 if (data.core && data.core.length) {
2410 $.each(data.core, function(i, table) {
2411 coreHtml += '<label class="vigilante-db-table-label">';
2412 coreHtml += '<input type="checkbox" class="vigilante-db-table-check" value="' + table.name + '" data-bytes="' + (table.bytes || 0) + '" checked>';
2413 coreHtml += '<span class="vigilante-db-table-name" title="' + table.name + '">' + table.short + '</span>';
2414 coreHtml += '<span class="vigilante-db-table-meta">' + table.rows + ' rows &middot; ' + table.size + '</span>';
2415 coreHtml += '</label>';
2416 });
2417 }
2418
2419 // Build other tables checkboxes
2420 if (data.other && data.other.length) {
2421 $.each(data.other, function(i, table) {
2422 otherHtml += '<label class="vigilante-db-table-label">';
2423 otherHtml += '<input type="checkbox" class="vigilante-db-table-check" value="' + table.name + '" data-bytes="' + (table.bytes || 0) + '" checked>';
2424 otherHtml += '<span class="vigilante-db-table-name" title="' + table.name + '">' + table.short + '</span>';
2425 otherHtml += '<span class="vigilante-db-table-meta">' + table.rows + ' rows &middot; ' + table.size + '</span>';
2426 otherHtml += '</label>';
2427 });
2428 $('#vigilante-db-other-group').show();
2429 }
2430
2431 $('#vigilante-db-core-tables').html(coreHtml);
2432 $('#vigilante-db-other-tables').html(otherHtml);
2433
2434 Vigilante_Admin.updateDbTablesInfo();
2435
2436 $('.vigilante-db-tables-loading').hide();
2437 $('.vigilante-db-tables-content').show();
2438 }
2439 });
2440 },
2441
2442 /**
2443 * Select/deselect all tables
2444 */
2445 handleDbSelectAll: function(e) {
2446 var checked = $(e.currentTarget).prop('checked');
2447 $('.vigilante-db-table-check').prop('checked', checked);
2448 this.updateDbTablesInfo();
2449 },
2450
2451 /**
2452 * Update select-all state when individual checkbox changes
2453 */
2454 handleDbTableCheck: function() {
2455 var total = $('.vigilante-db-table-check').length;
2456 var checked = $('.vigilante-db-table-check:checked').length;
2457 $('#vigilante-db-select-all').prop('checked', total === checked);
2458 this.updateDbTablesInfo();
2459 },
2460
2461 /**
2462 * Download database backup
2463 */
2464 handleDbBackupDownload: function(e) {
2465 e.preventDefault();
2466
2467 var tables = [];
2468 $('.vigilante-db-table-check:checked').each(function() {
2469 tables.push($(this).val());
2470 });
2471
2472 if (tables.length === 0) {
2473 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.dbBackupNoTables);
2474 return;
2475 }
2476
2477 var $btn = $(e.currentTarget);
2478 $btn.prop('disabled', true).html(vigilanteAdmin.strings.dbBackupDownloading + ' <span class="vigilante-spinner"></span>');
2479
2480 // Submit via hidden form for direct file download
2481 var $form = $('<form>', {
2482 method: 'POST',
2483 action: vigilanteAdmin.ajaxUrl
2484 });
2485
2486 $form.append($('<input>', { type: 'hidden', name: 'action', value: 'vigilante_download_db_backup' }));
2487 $form.append($('<input>', { type: 'hidden', name: 'nonce', value: vigilanteAdmin.nonce }));
2488 $form.append($('<input>', { type: 'hidden', name: 'tables', value: tables.join(',') }));
2489
2490 $('body').append($form);
2491 $form.submit();
2492 $form.remove();
2493
2494 // Re-enable button after a delay (download starts in background)
2495 setTimeout(function() {
2496 $btn.prop('disabled', false).text($btn.data('original-text') || vigilanteAdmin.strings.downloadBackup || 'Download Backup (.zip)');
2497 Vigilante_Admin.showNotice('success', vigilanteAdmin.strings.dbBackupSuccess);
2498 }, 3000);
2499 },
2500
2501 // =================================================================
2502 // DATABASE PREFIX HANDLERS
2503 // =================================================================
2504
2505 /**
2506 * Regenerate random prefix
2507 */
2508 handleDbRegeneratePrefix: function(e) {
2509 e.preventDefault();
2510
2511 var $btn = $(e.currentTarget);
2512 $btn.prop('disabled', true);
2513
2514 $.ajax({
2515 url: vigilanteAdmin.ajaxUrl,
2516 type: 'POST',
2517 data: {
2518 action: 'vigilante_generate_prefix',
2519 nonce: vigilanteAdmin.nonce
2520 },
2521 success: function(response) {
2522 if (response.success) {
2523 $('#vigilante-new-prefix').text(response.data.prefix);
2524 } else {
2525 Vigilante_Admin.showNotice('error', response.data);
2526 }
2527 },
2528 complete: function() {
2529 $btn.prop('disabled', false);
2530 }
2531 });
2532 },
2533
2534 /**
2535 * Toggle the change prefix button based on checkbox
2536 */
2537 handleDbPrefixConfirmToggle: function(e) {
2538 var checked = $(e.currentTarget).prop('checked');
2539 $('.vigilante-db-change-prefix').prop('disabled', !checked);
2540 },
2541
2542 /**
2543 * Change database prefix
2544 */
2545 handleDbChangePrefix: function(e) {
2546 e.preventDefault();
2547
2548 // Verify checkbox is checked
2549 if (!$('#vigilante-prefix-backup-confirm').prop('checked')) {
2550 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.dbPrefixCheckbox);
2551 return;
2552 }
2553
2554 var newPrefix = $('#vigilante-new-prefix').text().trim();
2555
2556 if (!confirm(vigilanteAdmin.strings.dbPrefixConfirm)) {
2557 return;
2558 }
2559
2560 var $btn = $(e.currentTarget);
2561 $btn.prop('disabled', true).html(vigilanteAdmin.strings.dbPrefixChanging + ' <span class="vigilante-spinner"></span>');
2562
2563 $.ajax({
2564 url: vigilanteAdmin.ajaxUrl,
2565 type: 'POST',
2566 data: {
2567 action: 'vigilante_change_prefix',
2568 nonce: vigilanteAdmin.nonce,
2569 prefix: newPrefix
2570 },
2571 success: function(response) {
2572 if (response.success) {
2573 Vigilante_Admin.showNotice('success', vigilanteAdmin.strings.dbPrefixSuccess);
2574 // Reload page after prefix change (session will still work)
2575 setTimeout(function() {
2576 location.reload();
2577 }, 2000);
2578 } else {
2579 Vigilante_Admin.showNotice('error', response.data);
2580 $btn.prop('disabled', false).text($btn.data('original-text'));
2581 }
2582 },
2583 error: function() {
2584 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
2585 $btn.prop('disabled', false).text($btn.data('original-text'));
2586 }
2587 });
2588 },
2589
2590 /**
2591 * Show notice
2592 */
2593 showNotice: function(type, message) {
2594 // Remove any existing notices first.
2595 $('.vigilante-notice').remove();
2596
2597 var $notice = $('<div class="vigilante-notice vigilante-notice-' + type + '">' + message + '</div>');
2598 $('.vigilante-main').prepend($notice);
2599
2600 // Scroll to top of the settings area so user sees the notice.
2601 $('html, body').animate({
2602 scrollTop: $('.vigilante-admin-wrap').offset().top - 50
2603 }, 300);
2604
2605 setTimeout(function() {
2606 $notice.fadeOut(function() {
2607 $(this).remove();
2608 });
2609 }, 5000);
2610 },
2611
2612 /**
2613 * Handle view log details
2614 */
2615 handleViewLogDetails: function(e) {
2616 e.preventDefault();
2617 e.stopPropagation();
2618
2619 var $btn = $(e.currentTarget);
2620 var detailsStr = $btn.attr('data-details');
2621
2622 if (!detailsStr) {
2623 return;
2624 }
2625
2626 var details;
2627 try {
2628 details = JSON.parse(detailsStr);
2629 } catch (err) {
2630 return;
2631 }
2632
2633 var html = '';
2634
2635 var s = vigilanteAdmin.strings;
2636
2637 // -- Section: Request --
2638 html += '<div class="vigilante-popup-section">';
2639 html += '<h4 class="vigilante-popup-section-title">' + this.escapeHtml(s.logRequest || 'Request') + '</h4>';
2640 html += '<table class="vigilante-details-table">';
2641 html += '<tr><th>' + this.escapeHtml(s.logDate || 'Date') + '</th><td>' + this.escapeHtml(details.date) + '</td></tr>';
2642 if (details.request_method) {
2643 html += '<tr><th>' + this.escapeHtml(s.logMethod || 'Method') + '</th><td><span class="vigilante-method-label vigilante-method-' + this.escapeHtml(details.request_method.toLowerCase()) + '">' + this.escapeHtml(details.request_method) + '</span></td></tr>';
2644 }
2645 html += '<tr><th>' + this.escapeHtml(s.logType || 'Type') + '</th><td>' + this.escapeHtml(details.type) + '</td></tr>';
2646 html += '<tr><th>' + this.escapeHtml(s.logAction || 'Action') + '</th><td>' + this.escapeHtml(details.action || '-') + '</td></tr>';
2647 html += '<tr><th>' + this.escapeHtml(s.logSeverity || 'Severity') + '</th><td><span class="vigilante-badge vigilante-badge-' + this.escapeHtml(details.severity || 'info') + '">' + this.escapeHtml(details.severity || 'info') + '</span></td></tr>';
2648 html += '<tr><th>' + this.escapeHtml(s.logMessage || 'Message') + '</th><td>' + this.escapeHtml(details.message) + '</td></tr>';
2649 if (details.request_uri) {
2650 html += '<tr><th>' + this.escapeHtml(s.logRequestUri || 'Address') + '</th><td class="vigilante-ua-cell"><code>' + this.escapeHtml(details.request_uri) + '</code></td></tr>';
2651 }
2652 html += '</table>';
2653 html += '</div>';
2654
2655 // -- Section: Client --
2656 html += '<div class="vigilante-popup-section">';
2657 html += '<h4 class="vigilante-popup-section-title">' + this.escapeHtml(s.logClient || 'Client') + '</h4>';
2658 html += '<table class="vigilante-details-table">';
2659 html += '<tr><th>' + this.escapeHtml(s.logUser || 'User') + '</th><td>' + this.escapeHtml(details.user || '-') + '</td></tr>';
2660
2661 // IP with lookup link
2662 if (details.ip && details.ip !== '0.0.0.0') {
2663 var ipEscaped = this.escapeHtml(details.ip);
2664 html += '<tr><th>' + this.escapeHtml(s.logIpAddress || 'IP Address') + '</th><td>';
2665 html += '<code>' + ipEscaped + '</code> ';
2666 html += '<a href="https://abuseipdb.com/check/' + encodeURIComponent(details.ip) + '" target="_blank" rel="noopener noreferrer" class="vigilante-ip-lookup" title="Lookup IP">';
2667 html += '<span class="dashicons dashicons-search"></span></a>';
2668 html += '</td></tr>';
2669 } else {
2670 html += '<tr><th>' + this.escapeHtml(s.logIpAddress || 'IP Address') + '</th><td><code>' + this.escapeHtml(details.ip) + '</code></td></tr>';
2671 }
2672
2673 if (details.user_agent) {
2674 html += '<tr><th>' + this.escapeHtml(s.logUserAgent || 'User Agent') + '</th><td class="vigilante-ua-cell"><code>' + this.escapeHtml(details.user_agent) + '</code></td></tr>';
2675 }
2676 html += '</table>';
2677
2678 // Action buttons for IP and UA
2679 html += '<div class="vigilante-popup-actions">';
2680 if (details.ip && details.ip !== '0.0.0.0') {
2681 html += '<span class="vigilante-popup-actions-label">' + this.escapeHtml(s.logIpLabel || 'IP:') + '</span>';
2682 if (details.is_ip_whitelisted) {
2683 html += '<button type="button" class="button button-small vigilante-btn-added" disabled><span class="dashicons dashicons-yes-alt"></span> ' + this.escapeHtml(s.logInWhitelist || 'In whitelist') + '</button> ';
2684 } else {
2685 html += '<button type="button" class="button button-small vigilante-add-to-list" data-item-type="ip" data-list-type="whitelist" data-value="' + this.escapeHtml(details.ip) + '"><span class="dashicons dashicons-yes-alt"></span> ' + this.escapeHtml(s.logWhitelist || 'Whitelist') + '</button> ';
2686 }
2687 if (details.is_ip_blacklisted) {
2688 html += '<button type="button" class="button button-small vigilante-btn-added" disabled><span class="dashicons dashicons-dismiss"></span> ' + this.escapeHtml(s.logInBlacklist || 'In blacklist') + '</button> ';
2689 } else {
2690 html += '<button type="button" class="button button-small vigilante-add-to-list vigilante-btn-danger" data-item-type="ip" data-list-type="blacklist" data-value="' + this.escapeHtml(details.ip) + '"><span class="dashicons dashicons-dismiss"></span> ' + this.escapeHtml(s.logBlacklist || 'Blacklist') + '</button> ';
2691 }
2692 }
2693 if (details.user_agent) {
2694 html += '<span class="vigilante-popup-actions-label">' + this.escapeHtml(s.logUaLabel || 'UA:') + '</span>';
2695 if (details.is_ua_whitelisted) {
2696 html += '<button type="button" class="button button-small vigilante-btn-added" disabled><span class="dashicons dashicons-yes-alt"></span> ' + this.escapeHtml(s.logInWhitelist || 'In whitelist') + '</button> ';
2697 } else {
2698 html += '<button type="button" class="button button-small vigilante-add-to-list" data-item-type="ua" data-list-type="whitelist" data-value="' + this.escapeHtml(details.user_agent) + '"><span class="dashicons dashicons-yes-alt"></span> ' + this.escapeHtml(s.logWhitelist || 'Whitelist') + '</button> ';
2699 }
2700 if (details.is_ua_blacklisted) {
2701 html += '<button type="button" class="button button-small vigilante-btn-added" disabled><span class="dashicons dashicons-dismiss"></span> ' + this.escapeHtml(s.logInBlacklist || 'In blacklist') + '</button>';
2702 } else {
2703 html += '<button type="button" class="button button-small vigilante-add-to-list vigilante-btn-danger" data-item-type="ua" data-list-type="blacklist" data-value="' + this.escapeHtml(details.user_agent) + '"><span class="dashicons dashicons-dismiss"></span> ' + this.escapeHtml(s.logBlacklist || 'Blacklist') + '</button>';
2704 }
2705 }
2706 html += '</div>';
2707 html += '<div class="vigilante-popup-feedback" style="display:none;"></div>';
2708 html += '</div>';
2709
2710 // Event ID for reference
2711 html += '<div class="vigilante-popup-footer">';
2712 html += '<span class="vigilante-popup-id">ID: ' + this.escapeHtml(details.id) + '</span>';
2713 html += '</div>';
2714
2715 $('#vigilante-log-details-content').html(html);
2716 $('#vigilante-log-details-modal').fadeIn(200);
2717 },
2718
2719 /**
2720 * Handle adding IP or UA to firewall whitelist/blacklist
2721 */
2722 handleAddToFirewallList: function(e) {
2723 e.preventDefault();
2724 var $btn = $(e.currentTarget);
2725 var itemType = $btn.data('item-type');
2726 var listType = $btn.data('list-type');
2727 // attr(), not data(): jQuery runs JSON.parse on values that look like
2728 // JSON, so a User-Agent such as {"a":1} would arrive as an object.
2729 var value = $btn.attr('data-value');
2730
2731 if (!itemType || !listType || !value) {
2732 return;
2733 }
2734
2735 $btn.prop('disabled', true);
2736
2737 var self = this;
2738 $.ajax({
2739 url: vigilanteAdmin.ajaxUrl,
2740 type: 'POST',
2741 data: {
2742 action: 'vigilante_add_to_firewall_list',
2743 nonce: vigilanteAdmin.nonce,
2744 item_type: itemType,
2745 list_type: listType,
2746 value: value
2747 },
2748 success: function(response) {
2749 var $feedback = $('.vigilante-popup-feedback');
2750 if (response.success) {
2751 $btn.text(vigilanteAdmin.strings.logAdded || 'Added!').addClass('vigilante-btn-added');
2752 $feedback.html('<span class="vigilante-popup-msg vigilante-popup-msg-success">' + response.data + '</span>').slideDown(150);
2753 } else {
2754 $btn.prop('disabled', false);
2755 $feedback.html('<span class="vigilante-popup-msg vigilante-popup-msg-warning">' + (response.data || vigilanteAdmin.strings.logErrorAddingToList || 'Error adding to list') + '</span>').slideDown(150);
2756 }
2757 },
2758 error: function() {
2759 $btn.prop('disabled', false);
2760 $('.vigilante-popup-feedback').html('<span class="vigilante-popup-msg vigilante-popup-msg-error">' + (vigilanteAdmin.strings.logRequestFailed || 'Request failed') + '</span>').slideDown(150);
2761 }
2762 });
2763 },
2764
2765 /**
2766 * Handle unblock firewall IP
2767 */
2768 handleUnblockFirewallIp: function(e) {
2769 var $btn = $(e.currentTarget);
2770 var ip = $btn.data('ip');
2771
2772 if (!confirm(vigilanteAdmin.strings.confirmUnblockIp || 'Unblock this IP?')) {
2773 return;
2774 }
2775
2776 $btn.prop('disabled', true).text(vigilanteAdmin.strings.loading || 'Loading...');
2777
2778 $.ajax({
2779 url: vigilanteAdmin.ajaxUrl,
2780 type: 'POST',
2781 data: {
2782 action: 'vigilante_unblock_firewall_ip',
2783 nonce: vigilanteAdmin.nonce,
2784 ip: ip
2785 },
2786 success: function(response) {
2787 if (response.success) {
2788 $btn.closest('tr').fadeOut(300, function() {
2789 var $tbody = $(this).closest('tbody');
2790 $(this).remove();
2791 // Hide the whole section if no more blocked IPs
2792 if ($tbody.children('tr').length === 0) {
2793 $tbody.closest('.vigilante-lockout-section').fadeOut(300);
2794 }
2795 });
2796 } else {
2797 alert(response.data || 'Error');
2798 $btn.prop('disabled', false).text(vigilanteAdmin.strings.unblock || 'Unblock');
2799 }
2800 },
2801 error: function() {
2802 $btn.prop('disabled', false).text(vigilanteAdmin.strings.unblock || 'Unblock');
2803 }
2804 });
2805 },
2806
2807 /**
2808 * Handle close modal
2809 */
2810 handleCloseModal: function(e) {
2811 if ($(e.target).hasClass('vigilante-modal') || $(e.target).hasClass('vigilante-modal-close')) {
2812 $('.vigilante-modal').hide();
2813 }
2814 },
2815
2816 /**
2817 * Escape HTML
2818 */
2819 escapeHtml: function(text) {
2820 if (text === null || text === undefined) return '';
2821 if (typeof text !== 'string') {
2822 text = String(text);
2823 }
2824 // Quotes must be encoded too: this helper is also used in attribute
2825 // position, where an unescaped quote closes the attribute early.
2826 return text
2827 .replace(/&/g, '&amp;')
2828 .replace(/</g, '&lt;')
2829 .replace(/>/g, '&gt;')
2830 .replace(/"/g, '&quot;')
2831 .replace(/'/g, '&#039;');
2832 },
2833
2834 /**
2835 * Debounce function
2836 */
2837 debounce: function(func, wait) {
2838 var timeout;
2839 return function() {
2840 var context = this, args = arguments;
2841 clearTimeout(timeout);
2842 timeout = setTimeout(function() {
2843 func.apply(context, args);
2844 }, wait);
2845 };
2846 },
2847
2848 // =================================================================
2849 // Force Password Reset functionality
2850 // =================================================================
2851
2852 /**
2853 * Selected users for password reset
2854 */
2855 selectedPasswordResetUsers: [],
2856
2857 /**
2858 * Initialize password reset handlers
2859 */
2860 initPasswordReset: function() {
2861 var self = this;
2862
2863 // User search for password reset
2864 var searchTimeout;
2865 $(document).on('input', '#vigilante-password-reset-search', function() {
2866 var query = $(this).val();
2867 clearTimeout(searchTimeout);
2868
2869 if (query.length < 2) {
2870 $('#vigilante-password-reset-results').hide().empty();
2871 return;
2872 }
2873
2874 searchTimeout = setTimeout(function() {
2875 self.searchUsersForPasswordReset(query);
2876 }, 300);
2877 });
2878
2879 // Close search results when clicking outside
2880 $(document).on('click', function(e) {
2881 if (!$(e.target).closest('.vigilante-user-search-wrapper').length) {
2882 $('#vigilante-password-reset-results').hide();
2883 }
2884 });
2885
2886 // Reset selected users button
2887 $(document).on('click', '#vigilante-reset-selected-users', function(e) {
2888 e.preventDefault();
2889 self.forceResetSelectedUsers();
2890 });
2891
2892 // Reset all users button
2893 $(document).on('click', '#vigilante-reset-all-users', function(e) {
2894 e.preventDefault();
2895 self.forceResetAllUsers();
2896 });
2897
2898 // Reset by role - checkbox change
2899 $(document).on('change', '.vigilante-reset-role-checkbox', function() {
2900 self.updateRoleResetSummary();
2901 });
2902
2903 // Reset by role button
2904 $(document).on('click', '#vigilante-reset-by-role', function(e) {
2905 e.preventDefault();
2906 self.forceResetByRoles();
2907 });
2908 },
2909
2910 /**
2911 * Search users for password reset
2912 */
2913 searchUsersForPasswordReset: function(query) {
2914 var self = this;
2915 var $results = $('#vigilante-password-reset-results');
2916
2917 $.ajax({
2918 url: vigilanteAdmin.ajaxUrl,
2919 type: 'POST',
2920 data: {
2921 action: 'vigilante_search_users_password_reset',
2922 nonce: vigilanteAdmin.nonce,
2923 query: query
2924 },
2925 success: function(response) {
2926 if (response.success && response.data.length > 0) {
2927 var html = '<ul class="vigilante-user-search-list">';
2928 response.data.forEach(function(user) {
2929 var isSelected = self.selectedPasswordResetUsers.indexOf(user.ID) !== -1;
2930 html += '<li data-user-id="' + user.ID + '" class="' + (isSelected ? 'selected' : '') + '">';
2931 html += '<img src="' + self.escapeHtml(user.avatar) + '" alt="" class="vigilante-user-avatar">';
2932 html += '<div class="vigilante-user-info">';
2933 html += '<strong>' + self.escapeHtml(user.display_name) + '</strong>';
2934 html += '<br><small>' + self.escapeHtml(user.user_login) + ' - ' + self.escapeHtml(user.user_email) + '</small>';
2935 html += '<br><small class="vigilante-user-roles">' + self.escapeHtml(user.roles) + '</small>';
2936 html += '</div>';
2937 html += '</li>';
2938 });
2939 html += '</ul>';
2940 $results.html(html).show();
2941
2942 // Handle user selection
2943 $results.find('li').on('click', function() {
2944 var userId = parseInt($(this).data('user-id'));
2945 var userName = $(this).find('strong').text();
2946 var userEmail = $(this).find('small').first().text();
2947 self.togglePasswordResetUser(userId, userName, userEmail);
2948 $(this).toggleClass('selected');
2949 });
2950 } else {
2951 $results.html('<p class="vigilante-no-results">' + (vigilanteAdmin.strings.noUsersFoundSearch || 'No users found') + '</p>').show();
2952 }
2953 }
2954 });
2955 },
2956
2957 /**
2958 * Toggle user selection for password reset
2959 */
2960 togglePasswordResetUser: function(userId, userName, userEmail) {
2961 var index = this.selectedPasswordResetUsers.indexOf(userId);
2962 var $selectedContainer = $('#vigilante-password-reset-selected');
2963 var $list = $selectedContainer.find('.vigilante-selected-users-list');
2964 var $btn = $('#vigilante-reset-selected-users');
2965
2966 if (index === -1) {
2967 // Add user
2968 this.selectedPasswordResetUsers.push(userId);
2969 $list.append(
2970 '<li data-user-id="' + userId + '">' +
2971 '<span>' + this.escapeHtml(userName) + '</span>' +
2972 '<button type="button" class="vigilante-remove-user" title="Remove">&times;</button>' +
2973 '</li>'
2974 );
2975 } else {
2976 // Remove user
2977 this.selectedPasswordResetUsers.splice(index, 1);
2978 $list.find('li[data-user-id="' + userId + '"]').remove();
2979 }
2980
2981 // Update UI
2982 if (this.selectedPasswordResetUsers.length > 0) {
2983 $selectedContainer.show();
2984 $btn.prop('disabled', false);
2985 } else {
2986 $selectedContainer.hide();
2987 $btn.prop('disabled', true);
2988 }
2989
2990 // Handle remove button click
2991 $list.find('.vigilante-remove-user').off('click').on('click', function() {
2992 var uid = $(this).closest('li').data('user-id');
2993 var idx = Vigilante_Admin.selectedPasswordResetUsers.indexOf(uid);
2994 if (idx !== -1) {
2995 Vigilante_Admin.selectedPasswordResetUsers.splice(idx, 1);
2996 }
2997 $(this).closest('li').remove();
2998 $('#vigilante-password-reset-results').find('li[data-user-id="' + uid + '"]').removeClass('selected');
2999
3000 if (Vigilante_Admin.selectedPasswordResetUsers.length === 0) {
3001 $selectedContainer.hide();
3002 $btn.prop('disabled', true);
3003 }
3004 });
3005 },
3006
3007 /**
3008 * Force reset for selected users
3009 */
3010 forceResetSelectedUsers: function() {
3011 var self = this;
3012
3013 if (this.selectedPasswordResetUsers.length === 0) {
3014 return;
3015 }
3016
3017 var currentUserId = parseInt(vigilanteAdmin.currentUserId || 0);
3018 var resettingSelf = this.selectedPasswordResetUsers.indexOf(currentUserId) !== -1;
3019
3020 var confirmMsg = (vigilanteAdmin.strings.confirmForceReset || 'Force password reset for %d user(s)? A password reset email will be sent to each user.').replace('%d', this.selectedPasswordResetUsers.length);
3021 if (resettingSelf) {
3022 confirmMsg += '\n\n' + (vigilanteAdmin.strings.warningResettingSelf || 'WARNING: You are including yourself. Your session will end and you will need to set a new password.');
3023 }
3024
3025 if (!confirm(confirmMsg)) {
3026 return;
3027 }
3028
3029 var $btn = $('#vigilante-reset-selected-users');
3030 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3031
3032 $.ajax({
3033 url: vigilanteAdmin.ajaxUrl,
3034 type: 'POST',
3035 data: {
3036 action: 'vigilante_force_password_reset',
3037 nonce: vigilanteAdmin.nonce,
3038 user_ids: this.selectedPasswordResetUsers
3039 },
3040 success: function(response) {
3041 if (response.success) {
3042 self.showNotice('success', response.data.message);
3043
3044 // Clear selection
3045 self.selectedPasswordResetUsers = [];
3046 $('#vigilante-password-reset-selected').hide().find('.vigilante-selected-users-list').empty();
3047 $('#vigilante-password-reset-search').val('');
3048 $('#vigilante-password-reset-results').hide().empty();
3049
3050 // Reload if resetting self
3051 if (response.data.resetting_self) {
3052 setTimeout(function() {
3053 window.location.href = vigilanteAdmin.logoutUrl || '/wp-login.php';
3054 }, 2000);
3055 } else {
3056 setTimeout(function() {
3057 location.reload();
3058 }, 1500);
3059 }
3060 } else {
3061 self.showNotice('error', response.data);
3062 }
3063 },
3064 error: function() {
3065 self.showNotice('error', vigilanteAdmin.strings.anErrorOccurred || 'An error occurred');
3066 },
3067 complete: function() {
3068 $btn.prop('disabled', false).text(vigilanteAdmin.strings.forceResetSelected || 'Force Reset for Selected Users');
3069 }
3070 });
3071 },
3072
3073 /**
3074 * Force reset for all users
3075 */
3076 forceResetAllUsers: function() {
3077 var self = this;
3078 var includeSelf = $('#vigilante-reset-all-include-self').is(':checked');
3079
3080 var confirmMsg = vigilanteAdmin.strings.confirmForceResetAll || 'This will force ALL users to reset their password. All users will receive a password reset email. Are you sure you want to continue?';
3081 if (includeSelf) {
3082 confirmMsg += '\n\n' + (vigilanteAdmin.strings.warningResettingSelfAll || 'WARNING: You are including yourself. Your session will end immediately.');
3083 }
3084
3085 if (!confirm(confirmMsg)) {
3086 return;
3087 }
3088
3089 var $btn = $('#vigilante-reset-all-users');
3090 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3091
3092 $.ajax({
3093 url: vigilanteAdmin.ajaxUrl,
3094 type: 'POST',
3095 data: {
3096 action: 'vigilante_force_password_reset_all',
3097 nonce: vigilanteAdmin.nonce,
3098 include_self: includeSelf ? 1 : 0
3099 },
3100 success: function(response) {
3101 if (response.success) {
3102 self.showNotice('success', response.data.message);
3103
3104 // Reload if resetting self
3105 if (response.data.resetting_self) {
3106 setTimeout(function() {
3107 window.location.href = vigilanteAdmin.logoutUrl || '/wp-login.php';
3108 }, 2000);
3109 } else {
3110 setTimeout(function() {
3111 location.reload();
3112 }, 1500);
3113 }
3114 } else {
3115 self.showNotice('error', response.data);
3116 }
3117 },
3118 error: function() {
3119 self.showNotice('error', vigilanteAdmin.strings.anErrorOccurred || 'An error occurred');
3120 },
3121 complete: function() {
3122 $btn.prop('disabled', false).text(vigilanteAdmin.strings.forceResetAll || 'Force Reset for ALL Users');
3123 }
3124 });
3125 },
3126
3127 /**
3128 * Update role reset summary when checkboxes change
3129 */
3130 updateRoleResetSummary: function() {
3131 var totalCount = 0;
3132 var includesSelf = false;
3133
3134 $('.vigilante-reset-role-checkbox:checked').each(function() {
3135 totalCount += parseInt($(this).data('count') || 0);
3136 if ($(this).closest('label').find('em').length > 0) {
3137 includesSelf = true;
3138 }
3139 });
3140
3141 var $summary = $('#vigilante-reset-role-summary');
3142 var $selfOption = $('#vigilante-reset-role-self-option');
3143 var $btn = $('#vigilante-reset-by-role');
3144
3145 if (totalCount > 0) {
3146 $('#vigilante-reset-role-count').text(totalCount);
3147 $summary.show();
3148 $btn.prop('disabled', false);
3149 } else {
3150 $summary.hide();
3151 $btn.prop('disabled', true);
3152 }
3153
3154 if (includesSelf) {
3155 $selfOption.show();
3156 } else {
3157 $selfOption.hide();
3158 $('#vigilante-reset-role-include-self').prop('checked', false);
3159 }
3160 },
3161
3162 /**
3163 * Force reset for users with selected roles
3164 */
3165 forceResetByRoles: function() {
3166 var self = this;
3167 var roles = [];
3168
3169 $('.vigilante-reset-role-checkbox:checked').each(function() {
3170 roles.push($(this).val());
3171 });
3172
3173 if (roles.length === 0) {
3174 self.showNotice('error', vigilanteAdmin.strings.noRolesSelected || 'Please select at least one role.');
3175 return;
3176 }
3177
3178 var totalCount = 0;
3179 $('.vigilante-reset-role-checkbox:checked').each(function() {
3180 totalCount += parseInt($(this).data('count') || 0);
3181 });
3182
3183 var includeSelf = $('#vigilante-reset-role-include-self').is(':checked');
3184
3185 var confirmMsg = (vigilanteAdmin.strings.confirmForceResetByRole || 'Force password reset for %d user(s) with the selected roles? A password reset email will be sent to each user.').replace('%d', totalCount);
3186 if (includeSelf) {
3187 confirmMsg += '\n\n' + (vigilanteAdmin.strings.warningResettingSelfAll || 'WARNING: You are including yourself. Your session will end immediately.');
3188 }
3189
3190 if (!confirm(confirmMsg)) {
3191 return;
3192 }
3193
3194 var $btn = $('#vigilante-reset-by-role');
3195 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3196
3197 $.ajax({
3198 url: vigilanteAdmin.ajaxUrl,
3199 type: 'POST',
3200 data: {
3201 action: 'vigilante_force_password_reset_by_role',
3202 nonce: vigilanteAdmin.nonce,
3203 roles: roles,
3204 include_self: includeSelf ? 1 : 0
3205 },
3206 success: function(response) {
3207 if (response.success) {
3208 self.showNotice('success', response.data.message);
3209
3210 // Clear role checkboxes
3211 $('.vigilante-reset-role-checkbox').prop('checked', false);
3212 self.updateRoleResetSummary();
3213
3214 if (response.data.resetting_self) {
3215 setTimeout(function() {
3216 window.location.href = vigilanteAdmin.logoutUrl || '/wp-login.php';
3217 }, 2000);
3218 } else {
3219 setTimeout(function() {
3220 location.reload();
3221 }, 1500);
3222 }
3223 } else {
3224 self.showNotice('error', response.data);
3225 }
3226 },
3227 error: function() {
3228 self.showNotice('error', vigilanteAdmin.strings.anErrorOccurred || 'An error occurred');
3229 },
3230 complete: function() {
3231 $btn.prop('disabled', false).text(vigilanteAdmin.strings.forceResetByRole || 'Force Reset for Selected Roles');
3232 }
3233 });
3234 },
3235
3236 /**
3237 * Initialize user approval handlers
3238 */
3239 initUserApproval: function() {
3240 var self = this;
3241
3242 // Approve user
3243 $(document).on('click', '.vigilante-approve-user', function() {
3244 var $btn = $(this);
3245 var userId = $btn.data('user-id');
3246 var $row = $btn.closest('tr');
3247
3248 if (!confirm(vigilanteAdmin.strings.confirmApprove || 'Approve this user?')) {
3249 return;
3250 }
3251
3252 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3253
3254 $.ajax({
3255 url: vigilanteAdmin.ajaxUrl,
3256 type: 'POST',
3257 data: {
3258 action: 'vigilante_approve_user',
3259 nonce: vigilanteAdmin.nonce,
3260 user_id: userId
3261 },
3262 success: function(response) {
3263 if (response.success) {
3264 self.showNotice('success', response.data.message);
3265 $row.fadeOut(400, function() {
3266 $(this).remove();
3267 self.updatePendingCount();
3268 });
3269 } else {
3270 self.showNotice('error', response.data);
3271 $btn.prop('disabled', false).text(vigilanteAdmin.strings.approve || 'Approve');
3272 }
3273 },
3274 error: function() {
3275 self.showNotice('error', vigilanteAdmin.strings.error);
3276 $btn.prop('disabled', false).text(vigilanteAdmin.strings.approve || 'Approve');
3277 }
3278 });
3279 });
3280
3281 // Reject user
3282 $(document).on('click', '.vigilante-reject-user', function() {
3283 var $btn = $(this);
3284 var userId = $btn.data('user-id');
3285 var $row = $btn.closest('tr');
3286
3287 var reason = prompt(vigilanteAdmin.strings.rejectReason || 'Enter rejection reason (optional):');
3288 if (reason === null) {
3289 return; // Cancelled
3290 }
3291
3292 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3293
3294 $.ajax({
3295 url: vigilanteAdmin.ajaxUrl,
3296 type: 'POST',
3297 data: {
3298 action: 'vigilante_reject_user',
3299 nonce: vigilanteAdmin.nonce,
3300 user_id: userId,
3301 reason: reason
3302 },
3303 success: function(response) {
3304 if (response.success) {
3305 self.showNotice('success', response.data.message);
3306 $row.fadeOut(400, function() {
3307 $(this).remove();
3308 self.updatePendingCount();
3309 });
3310 } else {
3311 self.showNotice('error', response.data);
3312 $btn.prop('disabled', false).text(vigilanteAdmin.strings.reject || 'Reject');
3313 }
3314 },
3315 error: function() {
3316 self.showNotice('error', vigilanteAdmin.strings.error);
3317 $btn.prop('disabled', false).text(vigilanteAdmin.strings.reject || 'Reject');
3318 }
3319 });
3320 });
3321 },
3322
3323 /**
3324 * Update pending users count badge
3325 */
3326 updatePendingCount: function() {
3327 var $badge = $('.vigilante-pending-users-section .vigilante-badge-warning');
3328 var $table = $('.vigilante-pending-users-table tbody tr');
3329 var count = $table.length;
3330
3331 if (count === 0) {
3332 $badge.remove();
3333 $('.vigilante-pending-users-table').replaceWith(
3334 '<div class="vigilante-no-lockouts">' +
3335 '<span class="dashicons dashicons-yes-alt"></span>' +
3336 '<p>' + (vigilanteAdmin.strings.noPending || 'No pending registrations.') + '</p>' +
3337 '</div>'
3338 );
3339 } else {
3340 $badge.text(count);
3341 }
3342 },
3343
3344 /**
3345 * Initialize session management handlers
3346 */
3347 initSessionManagement: function() {
3348 var self = this;
3349 var searchTimer = null;
3350 this.selectedSessionUserId = null;
3351
3352 // Search users for session management
3353 $(document).on('input', '#vigilante-session-user-search', function() {
3354 var query = $(this).val();
3355 var $results = $('#vigilante-session-search-results');
3356
3357 clearTimeout(searchTimer);
3358
3359 if (query.length < 2) {
3360 $results.hide().empty();
3361 return;
3362 }
3363
3364 searchTimer = setTimeout(function() {
3365 $.ajax({
3366 url: vigilanteAdmin.ajaxUrl,
3367 type: 'POST',
3368 data: {
3369 action: 'vigilante_search_users_password_reset',
3370 nonce: vigilanteAdmin.nonce,
3371 query: query
3372 },
3373 success: function(response) {
3374 if (response.success && response.data.length > 0) {
3375 var html = '<ul class="vigilante-user-search-list">';
3376 $.each(response.data, function(i, user) {
3377 html += '<li data-user-id="' + user.ID + '">' +
3378 '<img src="' + self.escapeHtml(user.avatar) + '" class="vigilante-user-avatar" alt="">' +
3379 '<div class="vigilante-user-info">' +
3380 '<strong>' + self.escapeHtml(user.display_name) + '</strong><br>' +
3381 '<small>' + self.escapeHtml(user.user_email) + '</small>' +
3382 '</div>' +
3383 '</li>';
3384 });
3385 html += '</ul>';
3386 $results.html(html).show();
3387 } else {
3388 $results.html('<p class="vigilante-no-results">' + (vigilanteAdmin.strings.noUsers || 'No users found') + '</p>').show();
3389 }
3390 }
3391 });
3392 }, 300);
3393 });
3394
3395 // Click handler for user selection in session search
3396 $(document).on('click', '#vigilante-session-search-results li', function() {
3397 var userId = $(this).data('user-id');
3398 var userName = $(this).find('strong').text();
3399 self.loadUserSessions(userId, userName);
3400 $('#vigilante-session-search-results').hide();
3401 $('#vigilante-session-user-search').val(userName);
3402 });
3403
3404 // Revoke single session
3405 $(document).on('click', '.vigilante-revoke-session', function() {
3406 var $btn = $(this);
3407 var userId = $btn.attr('data-user-id');
3408 var token = $btn.attr('data-token');
3409 var $row = $btn.closest('tr');
3410 var $paginatedContainer = $btn.closest('.vigilante-paginated-section');
3411
3412 // Fallback to row token if button token is invalid
3413 if (!token || token.length < 32) {
3414 token = $row.attr('data-token');
3415 }
3416
3417 if (!token || token.length < 32) {
3418 self.showNotice('error', vigilanteAdmin.strings.error || 'Invalid session token');
3419 return;
3420 }
3421
3422 if (!confirm(vigilanteAdmin.strings.confirmRevoke || 'Revoke this session?')) {
3423 return;
3424 }
3425
3426 $btn.prop('disabled', true);
3427
3428 $.ajax({
3429 url: vigilanteAdmin.ajaxUrl,
3430 type: 'POST',
3431 data: {
3432 action: 'vigilante_revoke_session',
3433 nonce: vigilanteAdmin.nonce,
3434 user_id: userId,
3435 token: token
3436 },
3437 success: function(response) {
3438 if (response.success) {
3439 self.showNotice('success', response.data.message);
3440 $row.fadeOut(400, function() {
3441 $(this).remove();
3442 if ($paginatedContainer.length) {
3443 Vigilante_Admin.refreshFilePagination($paginatedContainer);
3444 }
3445 });
3446 } else {
3447 self.showNotice('error', response.data);
3448 $btn.prop('disabled', false);
3449 }
3450 },
3451 error: function() {
3452 self.showNotice('error', vigilanteAdmin.strings.error);
3453 $btn.prop('disabled', false);
3454 }
3455 });
3456 });
3457
3458 // Revoke all other sessions (current user)
3459 $(document).on('click', '.vigilante-revoke-other-sessions', function() {
3460 var $btn = $(this);
3461 var userId = $btn.data('user-id');
3462
3463 if (!confirm(vigilanteAdmin.strings.confirmRevokeAll || 'Revoke all other sessions?')) {
3464 return;
3465 }
3466
3467 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3468
3469 $.ajax({
3470 url: vigilanteAdmin.ajaxUrl,
3471 type: 'POST',
3472 data: {
3473 action: 'vigilante_revoke_all_sessions',
3474 nonce: vigilanteAdmin.nonce,
3475 user_id: userId,
3476 include_current: 0
3477 },
3478 success: function(response) {
3479 if (response.success) {
3480 self.showNotice('success', response.data.message);
3481 setTimeout(function() {
3482 location.reload();
3483 }, 1000);
3484 } else {
3485 self.showNotice('error', response.data);
3486 }
3487 },
3488 error: function() {
3489 self.showNotice('error', vigilanteAdmin.strings.error);
3490 },
3491 complete: function() {
3492 $btn.prop('disabled', false).text(vigilanteAdmin.strings.revokeOthers || 'Revoke All Other Sessions');
3493 }
3494 });
3495 });
3496
3497 // Revoke all sessions for a user (admin managing other users)
3498 $(document).on('click', '.vigilante-revoke-all-user-sessions', function() {
3499 var $btn = $(this);
3500
3501 if (!self.selectedSessionUserId) {
3502 return;
3503 }
3504
3505 if (!confirm(vigilanteAdmin.strings.confirmRevokeAllUser || 'Revoke ALL sessions for this user? They will be logged out everywhere.')) {
3506 return;
3507 }
3508
3509 $btn.prop('disabled', true);
3510
3511 $.ajax({
3512 url: vigilanteAdmin.ajaxUrl,
3513 type: 'POST',
3514 data: {
3515 action: 'vigilante_revoke_all_sessions',
3516 nonce: vigilanteAdmin.nonce,
3517 user_id: self.selectedSessionUserId,
3518 include_current: 1
3519 },
3520 success: function(response) {
3521 if (response.success) {
3522 self.showNotice('success', response.data.message);
3523 $('#vigilante-user-sessions-container').hide();
3524 $('#vigilante-session-user-search').val('');
3525 } else {
3526 self.showNotice('error', response.data);
3527 }
3528 },
3529 error: function() {
3530 self.showNotice('error', vigilanteAdmin.strings.error);
3531 },
3532 complete: function() {
3533 $btn.prop('disabled', false);
3534 }
3535 });
3536 });
3537 },
3538
3539 /**
3540 * Load sessions for a specific user
3541 */
3542 loadUserSessions: function(userId, userName) {
3543 var self = this;
3544 this.selectedSessionUserId = userId;
3545 var $container = $('#vigilante-user-sessions-container');
3546 var $list = $('#vigilante-user-sessions-list');
3547
3548 $list.html('<tr><td colspan="4">' + (vigilanteAdmin.strings.loading || 'Loading...') + '</td></tr>');
3549 $container.show();
3550 $('#vigilante-sessions-user-name').text((vigilanteAdmin.strings.sessionsFor || 'Sessions for: ') + userName);
3551
3552 $.ajax({
3553 url: vigilanteAdmin.ajaxUrl,
3554 type: 'POST',
3555 data: {
3556 action: 'vigilante_get_user_sessions',
3557 nonce: vigilanteAdmin.nonce,
3558 user_id: userId
3559 },
3560 success: function(response) {
3561 if (response.success) {
3562 var sessions = response.data.sessions;
3563 if (sessions.length === 0) {
3564 $list.html('<tr><td colspan="4">' + (vigilanteAdmin.strings.noSessions || 'No active sessions') + '</td></tr>');
3565 return;
3566 }
3567
3568 var html = '';
3569 $.each(sessions, function(i, session) {
3570 var loginTime = session.login ? self.timeAgo(session.login) : (vigilanteAdmin.strings.unknown || 'Unknown');
3571 html += '<tr data-token="' + session.token_hash + '">' +
3572 '<td>' + self.escapeHtml(session.browser) + '</td>' +
3573 '<td><code>' + self.escapeHtml(session.ip) + '</code></td>' +
3574 '<td>' + loginTime + '</td>' +
3575 '<td>' +
3576 '<button type="button" class="button button-small vigilante-revoke-session" ' +
3577 'data-user-id="' + userId + '" data-token="' + session.token_hash + '">' +
3578 (vigilanteAdmin.strings.revoke || 'Revoke') +
3579 '</button>' +
3580 '</td>' +
3581 '</tr>';
3582 });
3583 $list.html(html);
3584 } else {
3585 $list.html('<tr><td colspan="4">' + response.data + '</td></tr>');
3586 }
3587 },
3588 error: function() {
3589 $list.html('<tr><td colspan="4">' + vigilanteAdmin.strings.error + '</td></tr>');
3590 }
3591 });
3592 },
3593
3594 /**
3595 * Format timestamp as time ago
3596 */
3597 timeAgo: function(timestamp) {
3598 var seconds = Math.floor((Date.now() / 1000) - timestamp);
3599 var s = vigilanteAdmin.strings;
3600 var intervals = [
3601 { label: s.timeYear || 'year', labelPlural: s.timeYears || 'years', seconds: 31536000 },
3602 { label: s.timeMonth || 'month', labelPlural: s.timeMonths || 'months', seconds: 2592000 },
3603 { label: s.timeDay || 'day', labelPlural: s.timeDays || 'days', seconds: 86400 },
3604 { label: s.timeHour || 'hour', labelPlural: s.timeHours || 'hours', seconds: 3600 },
3605 { label: s.timeMinute || 'minute', labelPlural: s.timeMinutes || 'minutes', seconds: 60 }
3606 ];
3607
3608 for (var i = 0; i < intervals.length; i++) {
3609 var count = Math.floor(seconds / intervals[i].seconds);
3610 if (count >= 1) {
3611 var unit = count > 1 ? intervals[i].labelPlural : intervals[i].label;
3612 return (s.timeAgo || '%1$d %2$s ago').replace('%1$d', count).replace('%2$s', unit);
3613 }
3614 }
3615 return s.justNow || 'Just now';
3616 }
3617 };
3618
3619 /* ---------------------------------------------------------------------
3620 * Security Analyzer (Dashboard widget) — v2.1.0
3621 * ------------------------------------------------------------------ */
3622
3623 var VigilanteAnalyzer = {
3624
3625 $root: null,
3626
3627 init: function() {
3628 this.$root = $('#vigilante-analyzer');
3629 if (!this.$root.length) {
3630 // Widget not present on this page — still run hash focus in case a fix link was followed.
3631 this.hashFocusFlash();
3632 return;
3633 }
3634
3635 // Scan button — 2-phase AJAX.
3636 $(document).on('click', '#vigilante-analyzer-scan', this.handleScan.bind(this));
3637
3638 // Expand/collapse detailed breakdown.
3639 $(document).on('click', '.vigilante-analyzer-toggle', this.handleToggleDetails.bind(this));
3640
3641 // Save weekly cron + email toggle on change.
3642 $(document).on('change',
3643 '.vigilante-analyzer-weekly input[type="checkbox"]',
3644 this.handleSettingsChange.bind(this));
3645
3646 // Pulse the row we landed on if we came from a fix link.
3647 this.hashFocusFlash();
3648
3649 // Upgrade the server-rendered SVG (no-op if already correct).
3650 this.renderSparklineFromData();
3651 },
3652
3653 /**
3654 * Kick off a scan. Phase 'fast' first for instant feedback, then 'slow' for remote checks.
3655 */
3656 handleScan: function(e) {
3657 e.preventDefault();
3658 if (this.isScanning) {
3659 return;
3660 }
3661 this.isScanning = true;
3662
3663 var $btn = $('#vigilante-analyzer-scan');
3664 var originalHtml = $btn.html();
3665 $btn.data('original-html', originalHtml);
3666 $btn.prop('disabled', true)
3667 .html('<span class="dashicons dashicons-update vigilante-analyzer-spin"></span> '
3668 + (vigilanteAdmin.strings.analyzerFastPhase || 'Running fast checks…'));
3669
3670 var self = this;
3671
3672 // Expand the details section so the user sees results pour in.
3673 this.expandDetails(true);
3674
3675 this.runScanPhase('fast')
3676 .done(function(fastReport) {
3677 self.applyReport(fastReport);
3678 $btn.html('<span class="dashicons dashicons-update vigilante-analyzer-spin"></span> '
3679 + (vigilanteAdmin.strings.analyzerSlowPhase || 'Running remote checks…'));
3680
3681 self.runScanPhase('slow')
3682 .done(function(slowReport) {
3683 self.applyReport(slowReport);
3684 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
3685 Vigilante_Admin.showNotice('success',
3686 vigilanteAdmin.strings.analyzerScanComplete || 'Security scan complete.');
3687 }
3688 })
3689 .fail(function(msg) {
3690 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
3691 Vigilante_Admin.showNotice('error',
3692 msg || vigilanteAdmin.strings.analyzerScanFailed || 'Security scan failed.');
3693 }
3694 })
3695 .always(function() {
3696 $btn.prop('disabled', false).html($btn.data('original-html') || originalHtml);
3697 self.isScanning = false;
3698 });
3699 })
3700 .fail(function(msg) {
3701 $btn.prop('disabled', false).html($btn.data('original-html') || originalHtml);
3702 self.isScanning = false;
3703 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
3704 Vigilante_Admin.showNotice('error',
3705 msg || vigilanteAdmin.strings.analyzerScanFailed || 'Security scan failed.');
3706 }
3707 });
3708 },
3709
3710 runScanPhase: function(phase) {
3711 var deferred = $.Deferred();
3712 $.ajax({
3713 url: vigilanteAdmin.ajaxUrl,
3714 type: 'POST',
3715 timeout: 60000,
3716 data: {
3717 action: 'vigilante_analyzer_run',
3718 nonce: vigilanteAdmin.nonce,
3719 phase: phase
3720 }
3721 }).done(function(response) {
3722 if (response && response.success) {
3723 deferred.resolve(response.data);
3724 } else {
3725 deferred.reject(response && response.data ? response.data : null);
3726 }
3727 }).fail(function(xhr, status, err) {
3728 deferred.reject(err || status);
3729 });
3730 return deferred.promise();
3731 },
3732
3733 /**
3734 * Map a 0-100 score percentage to a quality tag {label, slug}, mirroring
3735 * Vigilante_Admin::analyzer_quality_tag() in PHP.
3736 */
3737 qualityTag: function(pct) {
3738 pct = Math.max(0, Math.min(100, parseInt(pct, 10) || 0));
3739 var s = vigilanteAdmin.strings || {};
3740 // "Excellent" is reserved for a perfect score — a single missing point drops to Good.
3741 if (pct === 100) { return { label: s.analyzerQualityExcellent || 'Excellent', slug: 'a' }; }
3742 if (pct >= 70) { return { label: s.analyzerQualityGood || 'Good', slug: 'b' }; }
3743 if (pct >= 50) { return { label: s.analyzerQualityFair || 'Fair', slug: 'c' }; }
3744 if (pct >= 30) { return { label: s.analyzerQualityPoor || 'Poor', slug: 'd' }; }
3745 return { label: s.analyzerQualityCritical || 'Critical', slug: 'e' };
3746 },
3747
3748 /**
3749 * Swap a {a,b,c,d,e} slug modifier class on an element.
3750 */
3751 setQualityClass: function($el, baseClass, slug) {
3752 $el.removeClass(function(i, cls) {
3753 return (cls.match(new RegExp('(^|\\s)' + baseClass + '-[abcde](?=\\s|$)', 'g')) || []).join(' ');
3754 });
3755 $el.addClass(baseClass + '-' + slug);
3756 },
3757
3758 /**
3759 * Merge a phase report into the widget DOM.
3760 */
3761 applyReport: function(report) {
3762 if (!report || typeof report !== 'object') {
3763 return;
3764 }
3765 var $root = this.$root;
3766 var self = this;
3767
3768 // Overall pass/warn/fail counts (summary).
3769 if (report.counts && typeof report.counts === 'object') {
3770 $root.find('[data-role="pass"]').text(report.counts.pass || 0);
3771 $root.find('[data-role="warn"]').text(report.counts.warn || 0);
3772 $root.find('[data-role="fail"]').text(report.counts.fail || 0);
3773 }
3774
3775 // Main score circle + quality tag.
3776 if (report.grade) {
3777 var $card = $root.find('.vigilante-analyzer-score-card');
3778 var $circle = $card.find('.vigilante-score-circle');
3779 var gradeLc = String(report.grade).toLowerCase();
3780 var scoreN = parseInt(report.score, 10) || 0;
3781
3782 if (!$circle.length || $circle.hasClass('vigilante-grade-empty')) {
3783 $circle.remove();
3784 $card.prepend(
3785 '<div class="vigilante-score-circle vigilante-grade-'
3786 + this.escAttr(gradeLc)
3787 + '">'
3788 + '<span class="vigilante-grade">' + this.esc(report.grade) + '</span>'
3789 + '<span class="vigilante-score-text">' + this.esc(scoreN) + '%</span>'
3790 + '</div>'
3791 );
3792 } else {
3793 $circle.removeClass(function(i, cls) {
3794 return (cls.match(/(^|\s)vigilante-grade-\S+/g) || []).join(' ');
3795 }).addClass('vigilante-grade-' + gradeLc);
3796 $circle.find('.vigilante-grade').text(report.grade);
3797 $circle.find('.vigilante-score-text').text(scoreN + '%');
3798 }
3799
3800 // Quality tag in the score card.
3801 var quality = this.qualityTag(scoreN);
3802 var $tag = $root.find('[data-role="quality-tag"]');
3803 if ($tag.length) {
3804 this.setQualityClass($tag, 'vigilante-analyzer-quality', quality.slug);
3805 $tag.text(quality.label);
3806 }
3807 }
3808
3809 // "Last scan" label in the header.
3810 if (report.ran_at) {
3811 var $ranAt = $root.find('[data-role="ran-at"]');
3812 var justNow = vigilanteAdmin.strings.analyzerLastScanJustNow
3813 || 'Last scan just now';
3814 $ranAt.html(
3815 '<span class="dashicons dashicons-clock" aria-hidden="true"></span>'
3816 + this.esc(justNow)
3817 );
3818 }
3819
3820 // Per-category rows: quality pill, state counts, score, bar, and check rows.
3821 if (report.categories && typeof report.categories === 'object') {
3822 $.each(report.categories, function(slug, cat) {
3823 var $cat = $root.find('.vigilante-analyzer-category[data-category="' + slug + '"]');
3824 if (!$cat.length) {
3825 return;
3826 }
3827
3828 var infoOnly = $cat.attr('data-info-only') === '1';
3829 var counts = (cat.counts && typeof cat.counts === 'object') ? cat.counts : {};
3830
3831 if (!infoOnly) {
3832 var earned = parseInt(cat.earned, 10) || 0;
3833 var max = parseInt(cat.max, 10) || 0;
3834 var pct = max > 0 ? Math.round((earned / max) * 100) : 0;
3835 var cq = self.qualityTag(pct);
3836
3837 $cat.find('[data-role="earned"]').text(earned);
3838
3839 var $catQuality = $cat.find('[data-role="category-quality"]');
3840 if ($catQuality.length) {
3841 self.setQualityClass($catQuality, 'vigilante-analyzer-quality', cq.slug);
3842 // Update only the label span; the pill also contains the
3843 // "X/Y tests" counter so a blanket .text() would wipe it.
3844 var $label = $catQuality.find('[data-role="category-quality-label"]');
3845 if ($label.length) {
3846 $label.text(cq.label);
3847 } else {
3848 $catQuality.text(cq.label);
3849 }
3850 }
3851
3852 // "X/Y tests" inside the pill. Total is everything that
3853 // scores (pass + warn + fail), info/skip are excluded
3854 // because they don't move the category score.
3855 var $tests = $cat.find('[data-role="category-tests"]');
3856 if ($tests.length) {
3857 var passed = parseInt(counts.pass, 10) || 0;
3858 var total = passed
3859 + (parseInt(counts.warn, 10) || 0)
3860 + (parseInt(counts.fail, 10) || 0);
3861 var tpl = (vigilanteAdmin.strings && vigilanteAdmin.strings.testsCounter)
3862 || '%1$d/%2$d tests';
3863 $tests.text(tpl.replace('%1$d', passed).replace('%2$d', total));
3864 $tests.attr('data-passed', passed);
3865 $tests.attr('data-total', total);
3866 }
3867
3868 // Progress bar (width + quality color).
3869 var $bar = $cat.find('[data-role="category-bar"]');
3870 if ($bar.length) {
3871 $bar.css('width', pct + '%');
3872 self.setQualityClass($bar, 'vigilante-analyzer-category-bar-fill', cq.slug);
3873 }
3874 }
3875
3876 // State counts — show each chip only when count > 0.
3877 // Info-only categories (like reputation) also show an info count.
3878 self.updateCategoryState($cat, 'pass', parseInt(counts.pass, 10) || 0);
3879 self.updateCategoryState($cat, 'warn', parseInt(counts.warn, 10) || 0);
3880 self.updateCategoryState($cat, 'fail', parseInt(counts.fail, 10) || 0);
3881 if (infoOnly) {
3882 self.updateCategoryState($cat, 'info', parseInt(counts.info, 10) || 0);
3883 // Info-only categories replace the progress bar with a status pill
3884 // ("All clear" when nothing actionable, "N findings" otherwise).
3885 self.updateInfoStatus($cat, counts);
3886 }
3887
3888 // Replace the check rows only for checks this phase actually returned.
3889 if (cat.checks && cat.checks.length) {
3890 var $list = $cat.find('[data-role="check-list"]');
3891 $list.find('.vigilante-analyzer-check-empty').remove();
3892
3893 $.each(cat.checks, function(i, check) {
3894 var $existing = $list.find('[data-check-id="' + check.id + '"]');
3895 var html = self.renderCheckRow(check);
3896 if ($existing.length) {
3897 $existing.replaceWith(html);
3898 } else {
3899 $list.append(html);
3900 }
3901 });
3902 }
3903 });
3904 }
3905 },
3906
3907 /**
3908 * Update a per-category state chip (pass/warn/fail). Adds the chip if it doesn't
3909 * exist yet, updates its number, or removes it when the count is zero.
3910 */
3911 updateCategoryState: function($cat, state, count) {
3912 var $wrap = $cat.find('[data-role="category-states"]');
3913 if (!$wrap.length) {
3914 return;
3915 }
3916 var selector = '.vigilante-analyzer-category-state--' + state;
3917 var $chip = $wrap.find(selector);
3918
3919 if (count > 0) {
3920 if (!$chip.length) {
3921 var iconMap = { pass: 'yes', warn: 'warning', fail: 'no', info: 'info-outline' };
3922 var titleMap = {
3923 pass: 'Passing',
3924 warn: 'Warning',
3925 fail: 'Failing',
3926 info: 'Informational'
3927 };
3928 var title = titleMap[state] || '';
3929 $chip = $(
3930 '<span class="vigilante-analyzer-category-state vigilante-analyzer-category-state--'
3931 + state + '" title="' + this.escAttr(title) + '">'
3932 + '<span data-role="state-' + state + '">0</span>'
3933 + '<span class="dashicons dashicons-' + iconMap[state] + '" aria-hidden="true"></span>'
3934 + '</span>'
3935 );
3936 // Keep order: pass → warn → fail → info.
3937 if (state === 'pass') {
3938 $wrap.prepend($chip);
3939 } else if (state === 'warn') {
3940 var $passChip = $wrap.find('.vigilante-analyzer-category-state--pass');
3941 if ($passChip.length) { $chip.insertAfter($passChip); } else { $wrap.prepend($chip); }
3942 } else if (state === 'fail') {
3943 var $infoChip = $wrap.find('.vigilante-analyzer-category-state--info');
3944 if ($infoChip.length) { $chip.insertBefore($infoChip); } else { $wrap.append($chip); }
3945 } else {
3946 $wrap.append($chip);
3947 }
3948 }
3949 $chip.find('[data-role="state-' + state + '"]').text(count);
3950 } else if ($chip.length) {
3951 $chip.remove();
3952 }
3953 },
3954
3955 /**
3956 * Refresh the "All clear" / "N findings" pill for an info-only category.
3957 * Runs after a scan replaces the counts on the server side.
3958 */
3959 updateInfoStatus: function($cat, counts) {
3960 var $status = $cat.find('[data-role="info-status"]');
3961 if (!$status.length) {
3962 return;
3963 }
3964 var warnN = parseInt(counts.warn, 10) || 0;
3965 var failN = parseInt(counts.fail, 10) || 0;
3966 var issues = warnN + failN;
3967 var strings = (vigilanteAdmin && vigilanteAdmin.strings) || {};
3968
3969 if (issues > 0) {
3970 var template = strings.analyzerInfoFindings || '%d findings';
3971 var label = template.replace('%d', issues);
3972 $status
3973 .removeClass('vigilante-analyzer-category-status--clear')
3974 .addClass('vigilante-analyzer-category-status--attention')
3975 .html(
3976 '<span class="dashicons dashicons-warning" aria-hidden="true"></span>'
3977 + this.esc(label)
3978 );
3979 } else {
3980 var clear = strings.analyzerInfoAllClear || 'All clear';
3981 $status
3982 .removeClass('vigilante-analyzer-category-status--attention')
3983 .addClass('vigilante-analyzer-category-status--clear')
3984 .html(
3985 '<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>'
3986 + this.esc(clear)
3987 );
3988 }
3989 },
3990
3991 renderCheckRow: function(check) {
3992 var state = check.state || 'skip';
3993 var icons = {
3994 pass: 'yes-alt',
3995 warn: 'warning',
3996 fail: 'dismiss',
3997 info: 'info',
3998 skip: 'minus'
3999 };
4000 var icon = icons[state] || 'minus';
4001
4002 var scoreHtml = '';
4003 var max = parseInt(check.max, 10) || 0;
4004 if (max > 0 && state !== 'info' && state !== 'skip') {
4005 scoreHtml = '<span class="vigilante-analyzer-check-score">'
4006 + this.esc((parseInt(check.score, 10) || 0) + '/' + max)
4007 + '</span>';
4008 }
4009
4010 var fixHtml = '';
4011 if (check.fix_link && (state === 'fail' || state === 'warn')) {
4012 fixHtml = '<a href="' + this.escAttr(check.fix_link) + '" class="vigilante-analyzer-fix-link">'
4013 + this.esc(vigilanteAdmin.strings.analyzerGoToSetting || 'Go to setting')
4014 + '<span class="vigilante-analyzer-fix-arrow" aria-hidden="true">&rarr;</span></a>';
4015 } else if (check.fix_link && state === 'info') {
4016 var isExt = /^https?:\/\//i.test(check.fix_link);
4017 fixHtml = '<a href="' + this.escAttr(check.fix_link) + '" class="vigilante-analyzer-fix-link"'
4018 + (isExt ? ' target="_blank" rel="noopener noreferrer"' : '') + '>'
4019 + this.esc(vigilanteAdmin.strings.analyzerLearnMore || 'Learn more')
4020 + '<span class="vigilante-analyzer-fix-arrow" aria-hidden="true">&rarr;</span></a>';
4021 }
4022
4023 var detailHtml = '';
4024 if (check.detail) {
4025 detailHtml = '<p class="vigilante-analyzer-check-detail">' + this.esc(check.detail) + '</p>';
4026 }
4027
4028 return '<li class="vigilante-analyzer-check vigilante-analyzer-check--' + this.escAttr(state) + '"'
4029 + ' data-check-id="' + this.escAttr(check.id || '') + '">'
4030 + '<span class="vigilante-analyzer-check-icon dashicons dashicons-' + this.escAttr(icon) + '" aria-hidden="true"></span>'
4031 + '<div class="vigilante-analyzer-check-body">'
4032 + '<div class="vigilante-analyzer-check-label">'
4033 + '<span>' + this.esc(check.label || '') + '</span>'
4034 + scoreHtml
4035 + '</div>'
4036 + detailHtml
4037 + fixHtml
4038 + '</div>'
4039 + '</li>';
4040 },
4041
4042 /**
4043 * Expand or collapse the detailed breakdown section.
4044 */
4045 handleToggleDetails: function(e) {
4046 e.preventDefault();
4047 var $btn = $(e.currentTarget);
4048 var expanded = $btn.attr('aria-expanded') === 'true';
4049 this.expandDetails(!expanded);
4050 },
4051
4052 expandDetails: function(expand) {
4053 var $btn = this.$root.find('.vigilante-analyzer-toggle');
4054 var $details = this.$root.find('.vigilante-analyzer-details');
4055 var show = !!expand;
4056
4057 $btn.attr('aria-expanded', show ? 'true' : 'false');
4058
4059 var label = show
4060 ? (vigilanteAdmin.strings.analyzerHideDetails || 'Hide detailed breakdown')
4061 : (vigilanteAdmin.strings.analyzerShowDetails || 'Show detailed breakdown');
4062
4063 // Preserve the chevron element; only swap the label text.
4064 var $chevron = $btn.find('.vigilante-analyzer-toggle-chevron').detach();
4065 if (!$chevron.length) {
4066 $chevron = $('<span class="vigilante-analyzer-toggle-chevron" aria-hidden="true"></span>');
4067 }
4068 $btn.text(label).append(' ').append($chevron);
4069
4070 if (show) {
4071 $details.removeAttr('hidden');
4072 } else {
4073 $details.attr('hidden', 'hidden');
4074 }
4075 },
4076
4077 /**
4078 * Auto-save weekly scan + email toggles.
4079 */
4080 handleSettingsChange: function(e) {
4081 var $input = $(e.currentTarget);
4082 var $weekly = this.$root.find('input[name="security_analyzer[weekly_scan_enabled]"]');
4083 var $email = this.$root.find('input[name="security_analyzer[email_on_regression]"]');
4084
4085 $.ajax({
4086 url: vigilanteAdmin.ajaxUrl,
4087 type: 'POST',
4088 data: {
4089 action: 'vigilante_analyzer_save_settings',
4090 nonce: vigilanteAdmin.nonce,
4091 weekly_scan_enabled: $weekly.is(':checked') ? 1 : 0,
4092 email_on_regression: $email.is(':checked') ? 1 : 0
4093 },
4094 success: function(response) {
4095 if (response && response.success) {
4096 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
4097 Vigilante_Admin.showNotice('success',
4098 vigilanteAdmin.strings.analyzerSettingsSaved || 'Analyzer settings saved.');
4099 }
4100 } else {
4101 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
4102 Vigilante_Admin.showNotice('error',
4103 (response && response.data) || vigilanteAdmin.strings.error);
4104 }
4105 $input.prop('checked', !$input.is(':checked'));
4106 }
4107 },
4108 error: function() {
4109 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
4110 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
4111 }
4112 $input.prop('checked', !$input.is(':checked'));
4113 }
4114 });
4115 },
4116
4117 /**
4118 * Re-render the sparkline from data-points (no-op if no points).
4119 */
4120 renderSparklineFromData: function() {
4121 var $wrap = this.$root.find('[data-role="sparkline"]');
4122 if (!$wrap.length) {
4123 return;
4124 }
4125 var raw = $wrap.attr('data-points');
4126 if (!raw) {
4127 return;
4128 }
4129 try {
4130 var points = JSON.parse(raw);
4131 if (!points || points.length < 2) {
4132 return;
4133 }
4134 // Only regenerate if the SVG is missing (e.g. server gave empty markup).
4135 if (!$wrap.find('svg').length) {
4136 $wrap.html(this.buildSparklineSvg(points));
4137 }
4138 this.attachSparklineHotspots($wrap, points);
4139 } catch (err) { /* ignore parse errors */ }
4140 },
4141
4142 /**
4143 * Inject invisible hot-spots over each sparkline point and wire up a tooltip
4144 * that shows the score on hover/focus.
4145 */
4146 attachSparklineHotspots: function($wrap, points) {
4147 if (!points || points.length < 2) {
4148 return;
4149 }
4150 // Idempotent: clear any previous hot-spots/tooltip first.
4151 $wrap.find('.vigilante-analyzer-sparkline-dot, .vigilante-analyzer-sparkline-tooltip').remove();
4152
4153 var SVG_W = 280, SVG_H = 60, PAD = 4;
4154 var usableW = SVG_W - PAD * 2;
4155 var usableH = SVG_H - PAD * 2;
4156 var step = usableW / Math.max(1, points.length - 1);
4157 var max = 100;
4158
4159 var $tooltip = $('<div class="vigilante-analyzer-sparkline-tooltip" aria-hidden="true"></div>');
4160 $wrap.append($tooltip);
4161
4162 for (var i = 0; i < points.length; i++) {
4163 var x = PAD + (i * step);
4164 var y = PAD + (usableH - ((points[i] / max) * usableH));
4165 var xPct = (x / SVG_W) * 100;
4166 var yPct = (y / SVG_H) * 100;
4167
4168 var $dot = $('<button type="button" class="vigilante-analyzer-sparkline-dot"></button>')
4169 .css({ left: xPct + '%', top: yPct + '%' })
4170 .attr('data-score', points[i])
4171 .attr('data-index', i)
4172 .attr('aria-label', String(points[i]));
4173 $wrap.append($dot);
4174 }
4175
4176 $wrap.off('.vigSpark');
4177 $wrap.on('mouseenter.vigSpark focus.vigSpark', '.vigilante-analyzer-sparkline-dot', function() {
4178 var $dot = $(this);
4179 $tooltip
4180 .text($dot.attr('data-score'))
4181 .css({ left: $dot.css('left'), top: $dot.css('top') })
4182 .addClass('is-visible');
4183 });
4184 $wrap.on('mouseleave.vigSpark blur.vigSpark', '.vigilante-analyzer-sparkline-dot', function() {
4185 $tooltip.removeClass('is-visible');
4186 });
4187 },
4188
4189 buildSparklineSvg: function(points) {
4190 var width = 280;
4191 var height = 60;
4192 var padding = 4;
4193 var usableW = width - (padding * 2);
4194 var usableH = height - (padding * 2);
4195 var count = points.length;
4196 var step = usableW / Math.max(1, count - 1);
4197 var max = 100;
4198
4199 var coords = [];
4200 for (var i = 0; i < count; i++) {
4201 var x = padding + (i * step);
4202 var y = padding + (usableH - ((points[i] / max) * usableH));
4203 coords.push(x.toFixed(2) + ',' + y.toFixed(2));
4204 }
4205 var path = 'M ' + coords.join(' L ');
4206 var lastX = padding + ((count - 1) * step);
4207 var lastY = padding + (usableH - ((points[count - 1] / max) * usableH));
4208
4209 return '<svg viewBox="0 0 ' + width + ' ' + height + '" preserveAspectRatio="none" '
4210 + 'role="img" focusable="false">'
4211 + '<path d="' + path + '" fill="none" stroke="currentColor" '
4212 + 'stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>'
4213 + '<circle cx="' + lastX.toFixed(2) + '" cy="' + lastY.toFixed(2) + '" r="3" fill="currentColor"/>'
4214 + '</svg>';
4215 },
4216
4217 /**
4218 * When landing on a fix link (#field-*, #vigilante-section-* or any
4219 * other #vigilante-* target), scroll smoothly and flash-highlight it.
4220 *
4221 * The pattern used to name the two families literally, which left the
4222 * one anchor that follows neither out in the cold: the weekly report
4223 * email links to #vigilante-analyzer, so that link landed on the
4224 * dashboard with no scroll and no flash. Widened in 2.11.1 to the
4225 * whole vigilante- prefix, which is still narrow enough that a hash
4226 * written by anything else on the page cannot reach the selector.
4227 */
4228 hashFocusFlash: function() {
4229 var hash = window.location.hash;
4230 if (!hash || hash.length < 2) {
4231 return;
4232 }
4233 // Accept field anchors and every anchor the plugin owns.
4234 if (!/^#(?:field-|vigilante-)/.test(hash)) {
4235 return;
4236 }
4237
4238 setTimeout(function() {
4239 var $target;
4240 try {
4241 $target = $(hash);
4242 } catch (err) { return; }
4243 if (!$target || !$target.length) {
4244 return;
4245 }
4246
4247 // Scroll to it smoothly.
4248 if ('scrollIntoView' in $target[0]) {
4249 $target[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
4250 }
4251
4252 // Flash — remove any previous flash first.
4253 $('.vigilante-focus-flash').removeClass('vigilante-focus-flash');
4254 $target.addClass('vigilante-focus-flash');
4255 setTimeout(function() {
4256 $target.removeClass('vigilante-focus-flash');
4257 }, 1800);
4258 }, 150);
4259 },
4260
4261 /** Escape text for HTML. */
4262 esc: function(str) {
4263 return String(str == null ? '' : str)
4264 .replace(/&/g, '&amp;')
4265 .replace(/</g, '&lt;')
4266 .replace(/>/g, '&gt;')
4267 .replace(/"/g, '&quot;')
4268 .replace(/'/g, '&#039;');
4269 },
4270
4271 /** Escape text for HTML attribute. */
4272 escAttr: function(str) {
4273 return this.esc(str);
4274 }
4275 };
4276
4277 // Initialize on document ready
4278 $(document).ready(function() {
4279 Vigilante_Admin.init();
4280 Vigilante_Admin.initPasswordReset();
4281 Vigilante_Admin.initUserApproval();
4282 Vigilante_Admin.initSessionManagement();
4283 VigilanteAnalyzer.init();
4284
4285 // Shared "Send test email" button (Notification settings, File Integrity, Audit Alerts).
4286 $(document).on('click', '.vigilante-test-email-btn', function(e) {
4287 e.preventDefault();
4288 var $btn = $(this);
4289 var $result = $btn.siblings('.vigilante-test-email-result');
4290 var original = $btn.data('original-text') || $btn.text();
4291 $btn.prop('disabled', true).text(vigilanteAdmin.strings.sendingTest || 'Sending...');
4292 $result.text('').css('color', '');
4293 $.ajax({
4294 url: vigilanteAdmin.ajaxUrl,
4295 type: 'POST',
4296 data: {
4297 action: 'vigilante_send_test_email',
4298 nonce: vigilanteAdmin.nonce
4299 },
4300 success: function(response) {
4301 if (response && response.success) {
4302 $result.css('color', '#00a32a').text((response.data && response.data.message) || '');
4303 } else {
4304 $result.css('color', '#d63638').text((response && response.data && response.data.message) || vigilanteAdmin.strings.error);
4305 }
4306 },
4307 error: function() {
4308 $result.css('color', '#d63638').text(vigilanteAdmin.strings.error);
4309 },
4310 complete: function() {
4311 $btn.prop('disabled', false).text(original);
4312 }
4313 });
4314 });
4315 });
4316
4317 /**
4318 * Security Headers settings recovery (2.10.0).
4319 *
4320 * Both buttons are disabled together while the request is in flight, so a
4321 * second click cannot fire a second restore. The page reloads afterwards
4322 * because the whole tab is rendered from the settings that just changed.
4323 */
4324 $(function() {
4325 var SELECTOR = '#vigilante-recovery-restore, #vigilante-recovery-dismiss';
4326
4327 function recoveryRun(action) {
4328 $(SELECTOR).prop('disabled', true);
4329
4330 $.ajax({
4331 url: vigilanteAdmin.ajaxUrl,
4332 type: 'POST',
4333 data: {
4334 action: action,
4335 nonce: vigilanteAdmin.nonce
4336 },
4337 success: function(response) {
4338 if (response.success) {
4339 Vigilante_Admin.showNotice('success', response.data);
4340 setTimeout(function() {
4341 location.reload();
4342 }, 1200);
4343 return;
4344 }
4345
4346 Vigilante_Admin.showNotice('error', response.data);
4347 $(SELECTOR).prop('disabled', false);
4348 },
4349 error: function() {
4350 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
4351 $(SELECTOR).prop('disabled', false);
4352 }
4353 });
4354 }
4355
4356 $(document).on('click', '#vigilante-recovery-restore', function(e) {
4357 e.preventDefault();
4358 recoveryRun('vigilante_headers_recovery_restore');
4359 });
4360
4361 $(document).on('click', '#vigilante-recovery-dismiss', function(e) {
4362 e.preventDefault();
4363 recoveryRun('vigilante_headers_recovery_dismiss');
4364 });
4365
4366 $(document).on('click', '#vigilante-recovery-undo', function(e) {
4367 e.preventDefault();
4368 $(this).prop('disabled', true);
4369 recoveryRun('vigilante_headers_recovery_undo');
4370 });
4371 });
4372
4373 })(jQuery);