PluginProbe
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… / 2.9.7
Vigilant – 100% Free Security Suite: Firewall, 2FA, Login, Headers, Scanner… v2.9.7
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.9.7, at assets/js/admin.js

4,227 lines 186.6 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
1250 var html = '<h2>' + strings.scanResults + '</h2>';
1251 html += '<div class="vigilante-scan-summary">';
1252 html += '<div class="vigilante-scan-stat vigilante-stat-ok">';
1253 html += '<span class="vigilante-stat-number">' + (results.ok || 0) + '</span>';
1254 html += '<span class="vigilante-stat-label">' + strings.ok + '</span>';
1255 html += '</div>';
1256 html += '<div class="vigilante-scan-stat vigilante-stat-modified">';
1257 html += '<span class="vigilante-stat-number">' + results.modified.length + '</span>';
1258 html += '<span class="vigilante-stat-label">' + strings.modified + '</span>';
1259 html += '</div>';
1260 html += '<div class="vigilante-scan-stat vigilante-stat-suspicious">';
1261 html += '<span class="vigilante-stat-number">' + results.suspicious.length + '</span>';
1262 html += '<span class="vigilante-stat-label">' + strings.suspicious + '</span>';
1263 html += '</div>';
1264 html += '<div class="vigilante-scan-stat vigilante-stat-extra">';
1265 html += '<span class="vigilante-stat-number">' + results.extra.length + '</span>';
1266 html += '<span class="vigilante-stat-label">' + (strings.extra || 'Extra') + '</span>';
1267 html += '</div>';
1268 if (ignoredCount > 0) {
1269 html += '<div class="vigilante-scan-stat vigilante-stat-ignored">';
1270 html += '<span class="vigilante-stat-number">' + ignoredCount + '</span>';
1271 html += '<span class="vigilante-stat-label">' + (strings.ignored || 'Ignored') + '</span>';
1272 html += '</div>';
1273 }
1274 html += '<div class="vigilante-scan-stat">';
1275 var computedTotal = (results.ok || 0) + results.modified.length + results.suspicious.length + results.extra.length + (ignoredCount || 0);
1276 html += '<span class="vigilante-stat-number">' + computedTotal + '</span>';
1277 html += '<span class="vigilante-stat-label">' + strings.totalScanned + '</span>';
1278 html += '</div>';
1279 html += '</div>';
1280
1281 var bulkBar = '<div class="vigilante-fi-bulk-bar">'
1282 + '<button type="button" class="button vigilante-bulk-ignore" disabled>' + (strings.bulkIgnoreSelected || 'Ignore selected') + '</button>'
1283 + '<span class="vigilante-fi-bulk-count" aria-live="polite"></span>'
1284 + '</div>';
1285 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>';
1286
1287 // Suspicious files table
1288 if (results.suspicious.length > 0) {
1289 html += '<div class="vigilante-file-list vigilante-suspicious-files vigilante-paginated-section" data-bulk-mode="ignore">';
1290 html += '<h3 style="color: #d63638;">' + strings.suspiciousFiles + '</h3>';
1291 html += '<p class="description" style="color: #d63638;">' + strings.suspiciousWarning + '</p>';
1292 html += bulkBar;
1293 html += '<div class="vigilante-fi-pagination-wrap"></div>';
1294 html += '<table class="wp-list-table widefat fixed striped vigilante-fi-paginated">';
1295 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>';
1296 html += '<tbody>';
1297 results.suspicious.forEach(function(file) {
1298 html += '<tr>';
1299 html += '<th scope="row" class="check-column"><input type="checkbox" class="vigilante-fi-cb" value="' + file.file + '"></th>';
1300 html += '<td><code style="color: #d63638;">' + file.file + '</code></td>';
1301 html += '<td>' + (file.reason || strings.unknown) + '</td>';
1302 html += '<td>' + (file.type || strings.unknown) + '</td>';
1303 html += '<td><button type="button" class="button button-small vigilante-ignore-file" data-file="' + file.file + '">' + (strings.ignore || 'Ignore') + '</button></td>';
1304 html += '</tr>';
1305 });
1306 html += '</tbody></table>';
1307 html += '</div>';
1308 }
1309
1310 // Extra files table
1311 if (results.extra.length > 0) {
1312 html += '<div class="vigilante-file-list vigilante-extra-files vigilante-paginated-section" data-bulk-mode="ignore">';
1313 html += '<h3 style="color: #b32d2e;">' + (strings.extraFiles || 'Extra Files') + '</h3>';
1314 html += '<p class="description">' + (strings.extraDescription || 'PHP files not in original distribution.') + '</p>';
1315 html += bulkBar;
1316 html += '<div class="vigilante-fi-pagination-wrap"></div>';
1317 html += '<table class="wp-list-table widefat fixed striped vigilante-fi-paginated">';
1318 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>';
1319 html += '<tbody>';
1320 results.extra.forEach(function(file) {
1321 html += '<tr>';
1322 html += '<th scope="row" class="check-column"><input type="checkbox" class="vigilante-fi-cb" value="' + file.file + '"></th>';
1323 html += '<td><code style="color: #b32d2e;">' + file.file + '</code></td>';
1324 html += '<td>' + (file.reason || strings.unknown) + '</td>';
1325 html += '<td>' + (file.type || strings.unknown) + '</td>';
1326 html += '<td><button type="button" class="button button-small vigilante-ignore-file" data-file="' + file.file + '">' + (strings.ignore || 'Ignore') + '</button></td>';
1327 html += '</tr>';
1328 });
1329 html += '</tbody></table>';
1330 html += '</div>';
1331 }
1332
1333 // Split critical config from regular modified
1334 var criticalModified = [];
1335 var regularModified = [];
1336 results.modified.forEach(function(file) {
1337 if (file.type === 'critical_config') {
1338 criticalModified.push(file);
1339 } else {
1340 regularModified.push(file);
1341 }
1342 });
1343
1344 // Critical config files section (same visual treatment as suspicious files)
1345 if (criticalModified.length > 0) {
1346 html += '<div class="vigilante-file-list vigilante-critical-config-files">';
1347 html += '<h3 style="color: #e36210;">' + (strings.criticalConfigTitle || 'Critical config files modified') + '</h3>';
1348 html += '<p class="description">' + (strings.criticalConfigDesc || '') + '</p>';
1349 html += '<table class="wp-list-table widefat fixed striped">';
1350 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>';
1351 html += '<tbody>';
1352
1353 var escHtml = function(s) { return $('<span>').text(s).html(); };
1354
1355 criticalModified.forEach(function(file) {
1356 var fileId = file.file.replace(/[^a-z0-9]/gi, '-');
1357 var baselineSize = file.baseline_size ? Number(file.baseline_size).toLocaleString() : '?';
1358 var currentSize = file.current_size ? Number(file.current_size).toLocaleString() : '?';
1359 var diff = file.diff || {};
1360 var added = diff.added || [];
1361 var removed = diff.removed || [];
1362 var diffUnavailable = !!diff.unavailable;
1363
1364 // Main row
1365 html += '<tr>';
1366 html += '<td><code style="color: #e36210;">' + file.file + '</code></td>';
1367 html += '<td>';
1368 if (!diffUnavailable) {
1369 html += '<span style="color: #007017;">+' + added.length + '</span> <span style="color: #b32d2e;">-' + removed.length + '</span> ' + (strings.diffLines || 'lines') + '<br>';
1370 }
1371 html += '<small style="color: #50575e;">' + baselineSize + ' &rarr; ' + currentSize + ' bytes</small>';
1372 html += '</td>';
1373 html += '<td>';
1374 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> ';
1375 html += '<button type="button" class="button button-small button-primary vigilante-approve-critical-file" data-file="' + file.file + '">' + (strings.approve || 'Approve') + '</button>';
1376 html += '</td>';
1377 html += '</tr>';
1378
1379 // Expandable diff row
1380 html += '<tr id="vigilante-critical-content-' + fileId + '" class="vigilante-critical-content-row" style="display:none;">';
1381 html += '<td colspan="3" style="padding: 0;">';
1382 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;">';
1383 if (diffUnavailable) {
1384 html += '<p style="color: #50575e; font-style: italic; margin: 0;">' + (strings.diffUnavailable || 'Diff not available.') + '</p>';
1385 } else if (added.length === 0 && removed.length === 0) {
1386 html += '<p style="color: #50575e; font-style: italic; margin: 0;">' + (strings.diffEmpty || 'No line changes detected.') + '</p>';
1387 } else {
1388 removed.forEach(function(rline) {
1389 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>';
1390 });
1391 added.forEach(function(aline) {
1392 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>';
1393 });
1394 }
1395 html += '</div>';
1396 html += '</td>';
1397 html += '</tr>';
1398 });
1399
1400 html += '</tbody></table>';
1401 html += '</div>';
1402 }
1403
1404 // Regular modified files table
1405 if (regularModified.length > 0) {
1406 html += '<div class="vigilante-file-list vigilante-paginated-section" data-bulk-mode="ignore">';
1407 html += '<h3>' + strings.modifiedFiles + '</h3>';
1408 html += '<p class="description">' + strings.modifiedDescription + '</p>';
1409 html += bulkBar;
1410 html += '<div class="vigilante-fi-pagination-wrap"></div>';
1411 html += '<table class="wp-list-table widefat fixed striped vigilante-fi-paginated">';
1412 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>';
1413 html += '<tbody>';
1414 regularModified.forEach(function(file) {
1415 html += '<tr>';
1416 html += '<th scope="row" class="check-column"><input type="checkbox" class="vigilante-fi-cb" value="' + file.file + '"></th>';
1417 html += '<td><code>' + file.file + '</code></td>';
1418 html += '<td>' + (file.type || strings.unknown) + '</td>';
1419 html += '<td><button type="button" class="button button-small vigilante-ignore-file" data-file="' + file.file + '">' + (strings.ignore || 'Ignore') + '</button></td>';
1420 html += '</tr>';
1421 });
1422 html += '</tbody></table>';
1423 html += '</div>';
1424 }
1425
1426 if (results.modified.length === 0 && results.suspicious.length === 0 && results.extra.length === 0) {
1427 html += '<div class="vigilante-all-clear"><span class="dashicons dashicons-yes-alt"></span> ' + strings.allClear + '</div>';
1428 }
1429
1430 $container.html(html).show();
1431
1432 // Initialize client-side pagination for file integrity tables
1433 this.initFileIntegrityPagination($container);
1434 },
1435
1436 /**
1437 * Initialize client-side pagination for file integrity tables
1438 * Works on both PHP-rendered (last results) and JS-rendered (live scan) tables
1439 *
1440 * @param {jQuery} $scope Optional scope to limit search (for live scan results)
1441 */
1442 initFileIntegrityPagination: function($scope) {
1443 var perPage = 20;
1444 var $context = $scope || $(document);
1445
1446 $context.find('table.vigilante-fi-paginated').each(function() {
1447 var $table = $(this);
1448 var $rows = $table.find('tbody tr');
1449 var total = $rows.length;
1450
1451 if (total === 0) {
1452 return;
1453 }
1454
1455 // Store state on the parent container
1456 var $container = $table.closest('.vigilante-paginated-section');
1457 $container.data('fi-page', 1);
1458 $container.data('fi-per-page', perPage);
1459 $container.data('fi-total', total);
1460
1461 // Hide rows beyond first page (only if more than perPage)
1462 if (total > perPage) {
1463 $rows.each(function(index) {
1464 $(this).toggle(index < perPage);
1465 });
1466 }
1467
1468 // Build pagination controls (always show count, buttons only when needed)
1469 var $wrap = $container.find('.vigilante-fi-pagination-wrap');
1470 var paginationHtml = Vigilante_Admin.buildFilePaginationHtml(1, perPage, total);
1471 $wrap.html(paginationHtml);
1472 });
1473 },
1474
1475 /**
1476 * Build pagination HTML for file integrity tables
1477 */
1478 buildFilePaginationHtml: function(page, perPage, total) {
1479 var totalPages = Math.ceil(total / perPage) || 1;
1480 var from = total > 0 ? ((page - 1) * perPage) + 1 : 0;
1481 var to = Math.min(page * perPage, total);
1482 var needsNav = total > perPage;
1483
1484 var text = total > 0
1485 ? (vigilanteAdmin.strings.paginationOf || '%1$d–%2$d of %3$d').replace('%1$d', from).replace('%2$d', to).replace('%3$d', total)
1486 : (vigilanteAdmin.strings.paginationEmpty || '0 items');
1487
1488 var prevDisabled = page <= 1 ? ' disabled' : '';
1489 var nextDisabled = page >= totalPages ? ' disabled' : '';
1490
1491 var html = '<span class="vigilante-pagination vigilante-fi-pagination">';
1492 if (needsNav) {
1493 html += '<button type="button" class="vigilante-page-first" title="First"' + prevDisabled + '>&laquo;</button>';
1494 html += '<button type="button" class="vigilante-page-prev" title="Previous"' + prevDisabled + '>&lsaquo;</button>';
1495 }
1496 html += '<span class="vigilante-page-info">' + text + '</span>';
1497 if (needsNav) {
1498 html += '<button type="button" class="vigilante-page-next" title="Next"' + nextDisabled + '>&rsaquo;</button>';
1499 html += '<button type="button" class="vigilante-page-last" title="Last"' + nextDisabled + '>&raquo;</button>';
1500 }
1501 html += '</span>';
1502
1503 return html;
1504 },
1505
1506 /**
1507 * Navigate file integrity table pages (client-side)
1508 */
1509 goToFilePage: function($container, direction) {
1510 var page = $container.data('fi-page') || 1;
1511 var perPage = $container.data('fi-per-page') || 20;
1512 var total = $container.data('fi-total') || 0;
1513 var totalPages = Math.ceil(total / perPage) || 1;
1514
1515 switch (direction) {
1516 case 'first': page = 1; break;
1517 case 'prev': page = Math.max(1, page - 1); break;
1518 case 'next': page = Math.min(totalPages, page + 1); break;
1519 case 'last': page = totalPages; break;
1520 }
1521
1522 $container.data('fi-page', page);
1523
1524 // Show/hide rows
1525 var start = (page - 1) * perPage;
1526 var end = start + perPage;
1527 $container.find('table.vigilante-fi-paginated tbody tr').each(function(index) {
1528 $(this).toggle(index >= start && index < end);
1529 });
1530
1531 // Update controls
1532 var $wrap = $container.find('.vigilante-fi-pagination-wrap');
1533 $wrap.html(this.buildFilePaginationHtml(page, perPage, total));
1534
1535 // Sync the "select all" header with what is now visible.
1536 // Selections in other pages remain checked and will be included
1537 // in any bulk action, but the header reflects only this page.
1538 var $allCb = $container.find('.vigilante-fi-cb-all');
1539 if ($allCb.length) {
1540 var $visible = $container.find('table.vigilante-fi-paginated tbody tr:visible .vigilante-fi-cb');
1541 var $checked = $visible.filter(':checked');
1542 $allCb.prop('checked', $visible.length > 0 && $checked.length === $visible.length);
1543 }
1544 },
1545
1546 /**
1547 * Refresh file integrity pagination after row removal (ignore)
1548 */
1549 refreshFilePagination: function($container) {
1550 var perPage = $container.data('fi-per-page') || 20;
1551 var $rows = $container.find('table.vigilante-fi-paginated tbody tr');
1552 var total = $rows.length;
1553
1554 $container.data('fi-total', total);
1555
1556 if (total === 0) {
1557 $container.find('.vigilante-fi-pagination-wrap').empty();
1558 return;
1559 }
1560
1561 if (total <= perPage) {
1562 // Show all rows, display count only
1563 $rows.show();
1564 $container.data('fi-page', 1);
1565 var $wrap = $container.find('.vigilante-fi-pagination-wrap');
1566 $wrap.html(this.buildFilePaginationHtml(1, perPage, total));
1567 return;
1568 }
1569
1570 // Ensure current page is still valid
1571 var page = $container.data('fi-page') || 1;
1572 var totalPages = Math.ceil(total / perPage);
1573 if (page > totalPages) {
1574 page = totalPages;
1575 }
1576 $container.data('fi-page', page);
1577
1578 // Show/hide rows for current page
1579 var start = (page - 1) * perPage;
1580 var end = start + perPage;
1581 $rows.each(function(index) {
1582 $(this).toggle(index >= start && index < end);
1583 });
1584
1585 var $wrap = $container.find('.vigilante-fi-pagination-wrap');
1586 $wrap.html(this.buildFilePaginationHtml(page, perPage, total));
1587 },
1588
1589 /**
1590 * Handle export settings
1591 */
1592 handleExportSettings: function(e) {
1593 e.preventDefault();
1594
1595 $.ajax({
1596 url: vigilanteAdmin.ajaxUrl,
1597 type: 'POST',
1598 data: {
1599 action: 'vigilante_export_settings',
1600 nonce: vigilanteAdmin.nonce
1601 },
1602 success: function(response) {
1603 if (response.success) {
1604 var blob = new Blob([response.data.content], { type: 'application/json' });
1605 var url = URL.createObjectURL(blob);
1606 var a = document.createElement('a');
1607 a.href = url;
1608 a.download = response.data.filename;
1609 document.body.appendChild(a);
1610 a.click();
1611 document.body.removeChild(a);
1612 URL.revokeObjectURL(url);
1613 } else {
1614 Vigilante_Admin.showNotice('error', response.data);
1615 }
1616 }
1617 });
1618 },
1619
1620 /**
1621 * Handle import settings click
1622 */
1623 handleImportSettings: function(e) {
1624 e.preventDefault();
1625 $('#vigilante-import-file').trigger('click');
1626 },
1627
1628 /**
1629 * Handle import file selection
1630 */
1631 handleImportFile: function(e) {
1632 var file = e.target.files[0];
1633 if (!file) return;
1634
1635 var reader = new FileReader();
1636 reader.onload = function(e) {
1637 if (!confirm(vigilanteAdmin.strings.confirm + ' ' + (vigilanteAdmin.strings.confirmOverwrite || 'This will overwrite your current settings.'))) {
1638 return;
1639 }
1640
1641 $.ajax({
1642 url: vigilanteAdmin.ajaxUrl,
1643 type: 'POST',
1644 data: {
1645 action: 'vigilante_import_settings',
1646 nonce: vigilanteAdmin.nonce,
1647 settings: e.target.result
1648 },
1649 success: function(response) {
1650 if (response.success) {
1651 Vigilante_Admin.showNotice('success', response.data);
1652 setTimeout(function() {
1653 location.reload();
1654 }, 1000);
1655 } else {
1656 Vigilante_Admin.showNotice('error', response.data || vigilanteAdmin.strings.importFailed);
1657 }
1658 },
1659 error: function() {
1660 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.importFailed);
1661 }
1662 });
1663 };
1664 reader.readAsText(file);
1665 },
1666
1667 /**
1668 * Handle reset settings
1669 */
1670 handleResetSettings: function(e) {
1671 e.preventDefault();
1672
1673 if (!confirm(vigilanteAdmin.strings.confirm + ' ' + (vigilanteAdmin.strings.confirmResetAll || 'This will reset ALL settings to defaults.'))) {
1674 return;
1675 }
1676
1677 $.ajax({
1678 url: vigilanteAdmin.ajaxUrl,
1679 type: 'POST',
1680 data: {
1681 action: 'vigilante_apply_preset',
1682 nonce: vigilanteAdmin.nonce,
1683 preset: 'reset'
1684 },
1685 success: function(response) {
1686 if (response.success) {
1687 Vigilante_Admin.showNotice('success', vigilanteAdmin.strings.settingsResetDefaults || 'Settings reset to defaults.');
1688 setTimeout(function() {
1689 location.reload();
1690 }, 1000);
1691 } else {
1692 Vigilante_Admin.showNotice('error', response.data);
1693 }
1694 }
1695 });
1696 },
1697
1698 /**
1699 * Handle test headers
1700 */
1701 handleTestHeaders: function(e) {
1702 e.preventDefault();
1703
1704 var $btn = $(e.currentTarget);
1705 var $results = $('#vigilante-headers-result');
1706
1707 $btn.prop('disabled', true).html(vigilanteAdmin.strings.testing + ' <span class="vigilante-spinner"></span>');
1708
1709 $.ajax({
1710 url: vigilanteAdmin.ajaxUrl,
1711 type: 'POST',
1712 data: {
1713 action: 'vigilante_test_headers',
1714 nonce: vigilanteAdmin.nonce
1715 },
1716 success: function(response) {
1717 if (response.success) {
1718 Vigilante_Admin.displayHeaderResults(response.data, $results);
1719 } else {
1720 Vigilante_Admin.showNotice('error', response.data);
1721 }
1722 },
1723 complete: function() {
1724 $btn.prop('disabled', false).text(vigilanteAdmin.strings.testHeaders);
1725 }
1726 });
1727 },
1728
1729 /**
1730 * Handle login URL notification button
1731 */
1732 handleNotifyLoginUrl: function(e) {
1733 e.preventDefault();
1734
1735 var $btn = $(e.currentTarget);
1736 var $status = $btn.siblings('.vigilante-login-url-notify-status');
1737
1738 $btn.prop('disabled', true).text(vigilanteAdmin.strings.sending || 'Sending...');
1739 $status.removeClass('success error').text('');
1740
1741 $.ajax({
1742 url: vigilanteAdmin.ajaxUrl,
1743 type: 'POST',
1744 data: {
1745 action: 'vigilante_notify_login_url',
1746 nonce: vigilanteAdmin.nonce
1747 },
1748 success: function(response) {
1749 if (response.success) {
1750 var msg = response.data.sent + ' ' + (vigilanteAdmin.strings.notificationsSent || 'notifications sent');
1751 if (response.data.failed > 0) {
1752 msg += ', ' + response.data.failed + ' ' + (vigilanteAdmin.strings.failed || 'failed');
1753 }
1754 $status.addClass('success').text(msg);
1755 } else {
1756 $status.addClass('error').text(response.data || 'Error');
1757 }
1758 },
1759 error: function() {
1760 $status.addClass('error').text('Error');
1761 },
1762 complete: function() {
1763 $btn.prop('disabled', false).text(vigilanteAdmin.strings.sendNotification || 'Send notification now');
1764 }
1765 });
1766 },
1767
1768 /**
1769 * Toggle login URL notification section based on URL input
1770 */
1771 handleLoginUrlToggle: function() {
1772 var hasUrl = $('#vigilante_custom_login_url').val().trim().length > 0;
1773 $('.vigilante-login-url-notify-wrapper').toggleClass('vigilante-login-url-notify-disabled', !hasUrl);
1774 $('.vigilante-login-url-preview').toggle(hasUrl);
1775 },
1776
1777 /**
1778 * Display header test results
1779 */
1780 displayHeaderResults: function(results, $container) {
1781 var gradeClass = 'vigilante-grade-' + results.grade.toLowerCase();
1782 var html = '<div class="vigilante-security-score" style="text-align: center; padding: 20px;">';
1783 html += '<div class="vigilante-score-circle ' + gradeClass + '">';
1784 html += '<span class="vigilante-grade">' + results.grade + '</span>';
1785 html += '</div>';
1786 html += '<p style="text-align: center;"><strong>' + vigilanteAdmin.strings.score + ':</strong> ' + Math.round(results.score) + '%</p>';
1787 html += '</div>';
1788
1789 if (results.headers.length > 0) {
1790 html += '<p><strong>' + vigilanteAdmin.strings.enabledHeaders + ':</strong></p><ul>';
1791 results.headers.forEach(function(header) {
1792 html += '<li class="enabled">&#10003; ' + header + '</li>';
1793 });
1794 html += '</ul>';
1795 }
1796
1797 if (results.missing.length > 0) {
1798 html += '<p><strong>' + vigilanteAdmin.strings.missingHeaders + ':</strong></p><ul>';
1799 results.missing.forEach(function(header) {
1800 html += '<li class="missing">&#10007; ' + header + '</li>';
1801 });
1802 html += '</ul>';
1803 }
1804
1805 if (results.warnings && results.warnings.length > 0) {
1806 html += '<p><strong>' + vigilanteAdmin.strings.warnings + ':</strong></p><ul>';
1807 results.warnings.forEach(function(warning) {
1808 html += '<li class="warning">&#9888; ' + warning + '</li>';
1809 });
1810 html += '</ul>';
1811 }
1812
1813 $container.html(html).addClass('visible');
1814 },
1815
1816 /**
1817 * Handle activity log filter
1818 */
1819 handleLogFilter: function() {
1820 this.logPage = 1;
1821 this.loadActivityLogs();
1822 },
1823
1824 /**
1825 * Handle activity log search with debounce (400ms, min 3 chars)
1826 */
1827 handleLogSearch: function() {
1828 var self = this;
1829 clearTimeout(this.logSearchTimer);
1830 this.logSearchTimer = setTimeout(function() {
1831 var term = $('#vigilante-log-search').val().trim();
1832 // Only search with 3+ chars, or clear search when empty
1833 if (term.length >= 3 || term.length === 0) {
1834 self.logPage = 1;
1835 self.loadActivityLogs();
1836 }
1837 }, 400);
1838 },
1839
1840 /**
1841 * Load activity logs via AJAX (with filters and pagination)
1842 */
1843 loadActivityLogs: function() {
1844 var type = $('#vigilante-log-type-filter').val();
1845 var severity = $('#vigilante-log-severity-filter').val();
1846 var method = $('#vigilante-log-method-filter').val();
1847 var search = $('#vigilante-log-search').val();
1848 var $refreshBtn = $('#vigilante-log-refresh');
1849
1850 // Visual feedback
1851 $refreshBtn.prop('disabled', true).addClass('updating-message');
1852
1853 var data = {
1854 action: 'vigilante_get_logs',
1855 nonce: vigilanteAdmin.nonce,
1856 per_page: this.logPerPage,
1857 page: this.logPage,
1858 type: type,
1859 severity: severity
1860 };
1861
1862 if (method) {
1863 data.request_method = method;
1864 }
1865
1866 if (search && search.trim().length >= 3) {
1867 data.search = search.trim();
1868 }
1869
1870 $.ajax({
1871 url: vigilanteAdmin.ajaxUrl,
1872 type: 'POST',
1873 data: data,
1874 success: function(response) {
1875 if (response.success) {
1876 Vigilante_Admin.renderLogTable(response.data.logs);
1877 Vigilante_Admin.updateLogPagination(response.data.total);
1878 } else {
1879 Vigilante_Admin.showNotice('error', response.data || vigilanteAdmin.strings.error);
1880 }
1881 },
1882 error: function() {
1883 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error || 'Request failed');
1884 },
1885 complete: function() {
1886 $refreshBtn.prop('disabled', false).removeClass('updating-message');
1887 }
1888 });
1889 },
1890
1891 /**
1892 * Navigate activity log pages
1893 */
1894 goToLogPage: function(direction) {
1895 var $pagination = $('#vigilante-log-pagination');
1896 var total = parseInt($pagination.attr('data-total'), 10) || 0;
1897 var totalPages = Math.ceil(total / this.logPerPage) || 1;
1898
1899 switch (direction) {
1900 case 'first': this.logPage = 1; break;
1901 case 'prev': this.logPage = Math.max(1, this.logPage - 1); break;
1902 case 'next': this.logPage = Math.min(totalPages, this.logPage + 1); break;
1903 case 'last': this.logPage = totalPages; break;
1904 }
1905
1906 this.loadActivityLogs();
1907 },
1908
1909 /**
1910 * Update activity log pagination controls
1911 */
1912 updateLogPagination: function(total) {
1913 var $pagination = $('#vigilante-log-pagination');
1914 total = parseInt(total, 10) || 0;
1915 var totalPages = Math.ceil(total / this.logPerPage) || 1;
1916 var needsNav = total > this.logPerPage;
1917
1918 $pagination.attr('data-total', total);
1919 $pagination.attr('data-page', this.logPage);
1920
1921 var from = total > 0 ? ((this.logPage - 1) * this.logPerPage) + 1 : 0;
1922 var to = Math.min(this.logPage * this.logPerPage, total);
1923
1924 var text = total > 0
1925 ? (vigilanteAdmin.strings.paginationOf || '%1$d–%2$d of %3$d').replace('%1$d', from).replace('%2$d', to).replace('%3$d', total)
1926 : (vigilanteAdmin.strings.paginationEmpty || '0 items');
1927
1928 var prevDisabled = this.logPage <= 1 ? ' disabled' : '';
1929 var nextDisabled = this.logPage >= totalPages ? ' disabled' : '';
1930
1931 var html = '';
1932 if (needsNav) {
1933 html += '<button type="button" class="vigilante-page-first"' + prevDisabled + '>&laquo;</button>';
1934 html += '<button type="button" class="vigilante-page-prev"' + prevDisabled + '>&lsaquo;</button>';
1935 }
1936 html += '<span class="vigilante-page-info">' + text + '</span>';
1937 if (needsNav) {
1938 html += '<button type="button" class="vigilante-page-next"' + nextDisabled + '>&rsaquo;</button>';
1939 html += '<button type="button" class="vigilante-page-last"' + nextDisabled + '>&raquo;</button>';
1940 }
1941
1942 $pagination.html(html);
1943 },
1944
1945 /**
1946 * Render log table
1947 */
1948 renderLogTable: function(logs) {
1949 var $tbody = $('#vigilante-activity-log-table tbody');
1950 $tbody.empty();
1951
1952 if (logs.length === 0) {
1953 $tbody.append('<tr><td colspan="8">' + (vigilanteAdmin.strings.noLogEntries || 'No log entries found.') + '</td></tr>');
1954 return;
1955 }
1956
1957 var self = this;
1958 var typeLabels = (vigilanteAdmin.strings && vigilanteAdmin.strings.eventTypeLabels) || {};
1959 var severityLabels = (vigilanteAdmin.strings && vigilanteAdmin.strings.severityLabels) || {};
1960
1961 logs.forEach(function(log) {
1962 var details = {
1963 id: log.id,
1964 type: log.event_type || '',
1965 action: log.event_action || '',
1966 message: log.event_message || '',
1967 user: log.user_login || '',
1968 ip: log.ip_address || '',
1969 user_agent: log.user_agent || '',
1970 request_method: log.request_method || '',
1971 date: log.created_at || '',
1972 severity: log.severity || 'info',
1973 is_ip_whitelisted: !!log.is_ip_whitelisted,
1974 is_ip_blacklisted: !!log.is_ip_blacklisted,
1975 is_ua_whitelisted: !!log.is_ua_whitelisted,
1976 is_ua_blacklisted: !!log.is_ua_blacklisted
1977 };
1978
1979 var displayType = typeLabels[log.event_type] || log.event_type;
1980 var displaySeverity = severityLabels[log.severity] || log.severity;
1981
1982 var methodHtml = '-';
1983 if (log.request_method) {
1984 methodHtml = '<span class="vigilante-method-label vigilante-method-' + self.escapeHtml(log.request_method.toLowerCase()) + '">' + self.escapeHtml(log.request_method) + '</span>';
1985 }
1986
1987 var row = '<tr class="vigilante-severity-' + self.escapeHtml(log.severity) + '">';
1988 row += '<td>' + self.escapeHtml(log.created_at) + '</td>';
1989 row += '<td>' + self.escapeHtml(displayType) + '</td>';
1990 row += '<td>' + methodHtml + '</td>';
1991 row += '<td><span class="vigilante-badge vigilante-badge-' + self.escapeHtml(log.severity) + '">' + self.escapeHtml(displaySeverity) + '</span></td>';
1992 row += '<td>' + self.escapeHtml(log.event_message) + '</td>';
1993 row += '<td>' + self.escapeHtml(log.user_login || '-') + '</td>';
1994 row += '<td><code>' + self.escapeHtml(log.ip_address) + '</code></td>';
1995 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>';
1996 row += '</tr>';
1997 $tbody.append(row);
1998 });
1999 },
2000
2001 /**
2002 * Handle export logs
2003 */
2004 handleExportLogs: function(e) {
2005 e.preventDefault();
2006
2007 var $btn = $(e.currentTarget);
2008 var type = $('#vigilante-log-type-filter').val();
2009 var severity = $('#vigilante-log-severity-filter').val();
2010 var method = $('#vigilante-log-method-filter').val();
2011 var search = $('#vigilante-log-search').val();
2012
2013 var data = {
2014 action: 'vigilante_get_logs',
2015 nonce: vigilanteAdmin.nonce,
2016 per_page: 9999
2017 };
2018
2019 // Only add filters if they have values
2020 if (type && type !== '') {
2021 data.type = type;
2022 }
2023 if (severity && severity !== '') {
2024 data.severity = severity;
2025 }
2026 if (method && method !== '') {
2027 data.request_method = method;
2028 }
2029 if (search && search.trim().length >= 3) {
2030 data.search = search.trim();
2031 }
2032
2033 $btn.prop('disabled', true).text(vigilanteAdmin.strings.exporting || 'Exporting...');
2034
2035 $.ajax({
2036 url: vigilanteAdmin.ajaxUrl,
2037 type: 'POST',
2038 data: data,
2039 success: function(response) {
2040 if (response.success && response.data.logs && response.data.logs.length > 0) {
2041 Vigilante_Admin.downloadCSV(response.data.logs);
2042 Vigilante_Admin.showNotice('success', (vigilanteAdmin.strings.logsExported || 'Logs exported (%d entries)').replace('%d', response.data.logs.length));
2043 } else {
2044 Vigilante_Admin.showNotice('warning', vigilanteAdmin.strings.noLogsToExport || 'No logs to export');
2045 }
2046 },
2047 error: function() {
2048 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.exportFailed || 'Export failed');
2049 },
2050 complete: function() {
2051 $btn.prop('disabled', false).text(vigilanteAdmin.strings.exportLogs || 'Export Logs');
2052 }
2053 });
2054 },
2055
2056 /**
2057 * Download logs as CSV
2058 */
2059 downloadCSV: function(logs) {
2060 var csv = 'Date,Type,Method,Severity,Message,User,IP\n';
2061
2062 logs.forEach(function(log) {
2063 csv += '"' + log.created_at + '",';
2064 csv += '"' + log.event_type + '",';
2065 csv += '"' + (log.request_method || '') + '",';
2066 csv += '"' + log.severity + '",';
2067 csv += '"' + (log.event_message || '').replace(/"/g, '""') + '",';
2068 csv += '"' + (log.user_login || '') + '",';
2069 csv += '"' + log.ip_address + '"\n';
2070 });
2071
2072 var blob = new Blob([csv], { type: 'text/csv' });
2073 var url = URL.createObjectURL(blob);
2074 var a = document.createElement('a');
2075 a.href = url;
2076 a.download = 'activity-log-' + new Date().toISOString().slice(0, 10) + '.csv';
2077 document.body.appendChild(a);
2078 a.click();
2079 document.body.removeChild(a);
2080 URL.revokeObjectURL(url);
2081 },
2082
2083 /**
2084 * Handle create backup
2085 */
2086 handleCreateBackup: function(e) {
2087 e.preventDefault();
2088
2089 var $btn = $(e.currentTarget);
2090 $btn.prop('disabled', true).html(vigilanteAdmin.strings.loading + ' <span class="vigilante-spinner"></span>');
2091
2092 // Direct file download via a hidden form (same pattern as the
2093 // database backup): the server streams a ZIP with wp-config.php and
2094 // .htaccess as an attachment.
2095 var $form = $('<form>', { method: 'POST', action: vigilanteAdmin.ajaxUrl });
2096 $form.append($('<input>', { type: 'hidden', name: 'action', value: 'vigilante_download_files_backup' }));
2097 $form.append($('<input>', { type: 'hidden', name: 'nonce', value: vigilanteAdmin.nonce }));
2098 $('body').append($form);
2099 $form.submit();
2100 $form.remove();
2101
2102 // Re-enable the button after a short delay (download runs in the background).
2103 setTimeout(function() {
2104 $btn.prop('disabled', false).text(vigilanteAdmin.strings.createBackupNow || 'Create Backup Now');
2105 }, 2000);
2106 },
2107
2108 // =================================================================
2109 // DATABASE BACKUP HANDLERS
2110 // =================================================================
2111
2112 /**
2113 * Toggle database backup panel and load tables
2114 */
2115 handleDbBackupToggle: function(e) {
2116 e.preventDefault();
2117
2118 var $panel = $('.vigilante-db-backup-panel');
2119 var $btn = $(e.currentTarget);
2120
2121 if ($panel.is(':visible')) {
2122 $panel.slideUp(200);
2123 return;
2124 }
2125
2126 $panel.slideDown(200);
2127
2128 // Load tables if not already loaded
2129 if ($panel.find('.vigilante-db-tables-content').is(':hidden')) {
2130 this.loadDbTables();
2131 }
2132 },
2133
2134 /**
2135 * Handle settings search input
2136 */
2137 searchActiveIndex: -1,
2138
2139 handleSettingsSearch: function(e) {
2140 var query = ($('#vigilante-settings-search').val() || '').trim().toLowerCase();
2141 var $results = $('#vigilante-settings-search-results');
2142 var index = (vigilanteAdmin.searchIndex || []);
2143
2144 if (query.length < 2) {
2145 $results.attr('hidden', true).empty();
2146 this.searchActiveIndex = -1;
2147 return;
2148 }
2149
2150 var matches = [];
2151 for (var i = 0; i < index.length; i++) {
2152 var entry = index[i];
2153 var label = (entry.label || '').toLowerCase();
2154 var labelEn = (entry.label_en || '').toLowerCase();
2155 var section = (entry.section || '').toLowerCase();
2156 var keywords = (entry.keywords || '').toLowerCase();
2157 if (label.indexOf(query) !== -1 || labelEn.indexOf(query) !== -1 || section.indexOf(query) !== -1 || keywords.indexOf(query) !== -1) {
2158 matches.push(entry);
2159 }
2160 if (matches.length >= 30) {
2161 break;
2162 }
2163 }
2164
2165 if (!matches.length) {
2166 $results.html('<div class="vigilante-search-empty">' + (vigilanteAdmin.strings.searchNoResults || 'No results') + '</div>').attr('hidden', false);
2167 this.searchActiveIndex = -1;
2168 return;
2169 }
2170
2171 // Group by tab
2172 var grouped = {};
2173 var tabOrder = [];
2174 for (var j = 0; j < matches.length; j++) {
2175 var m = matches[j];
2176 if (!grouped[m.tab]) {
2177 grouped[m.tab] = { label: m.tab_label, items: [] };
2178 tabOrder.push(m.tab);
2179 }
2180 grouped[m.tab].items.push(m);
2181 }
2182
2183 var html = '';
2184 var flatIdx = 0;
2185 for (var k = 0; k < tabOrder.length; k++) {
2186 var tab = tabOrder[k];
2187 var group = grouped[tab];
2188 html += '<div class="vigilante-search-group">';
2189 html += '<div class="vigilante-search-group-title">' + this.escapeHtml(group.label) + '</div>';
2190 for (var n = 0; n < group.items.length; n++) {
2191 var it = group.items[n];
2192 var base = (vigilanteAdmin.adminUrl || 'admin.php?page=vigilante');
2193 var href = base + '&tab=' + encodeURIComponent(it.tab) + '#' + encodeURIComponent(it.anchor);
2194 var activeClass = flatIdx === 0 ? ' vigilante-search-item-active' : '';
2195 html += '<a class="vigilante-search-item' + activeClass + '" data-idx="' + flatIdx + '" role="option" href="' + href + '">';
2196 html += '<span class="vigilante-search-item-label">' + this.escapeHtml(it.label) + '</span>';
2197 html += '<span class="vigilante-search-item-section">' + this.escapeHtml(it.section) + '</span>';
2198 html += '</a>';
2199 flatIdx++;
2200 }
2201 html += '</div>';
2202 }
2203
2204 $results.html(html).attr('hidden', false);
2205 this.searchActiveIndex = 0;
2206 },
2207
2208 /**
2209 * Handle keyboard navigation in search: arrows move highlight, Enter navigates, Escape closes
2210 */
2211 handleSettingsSearchKey: function(e) {
2212 var $items = $('#vigilante-settings-search-results .vigilante-search-item');
2213
2214 if (e.key === 'Escape') {
2215 $('#vigilante-settings-search-results').attr('hidden', true);
2216 $('#vigilante-settings-search').blur();
2217 return;
2218 }
2219
2220 if (!$items.length) return;
2221
2222 if (e.key === 'ArrowDown') {
2223 e.preventDefault();
2224 this.searchActiveIndex = Math.min(this.searchActiveIndex + 1, $items.length - 1);
2225 this.updateSearchActive();
2226 } else if (e.key === 'ArrowUp') {
2227 e.preventDefault();
2228 this.searchActiveIndex = Math.max(this.searchActiveIndex - 1, 0);
2229 this.updateSearchActive();
2230 } else if (e.key === 'Home') {
2231 e.preventDefault();
2232 this.searchActiveIndex = 0;
2233 this.updateSearchActive();
2234 } else if (e.key === 'End') {
2235 e.preventDefault();
2236 this.searchActiveIndex = $items.length - 1;
2237 this.updateSearchActive();
2238 } else if (e.key === 'Enter') {
2239 e.preventDefault();
2240 var idx = this.searchActiveIndex >= 0 ? this.searchActiveIndex : 0;
2241 var $target = $items.eq(idx);
2242 if ($target.length) {
2243 window.location.href = $target.attr('href');
2244 }
2245 }
2246 },
2247
2248 /**
2249 * Sync active highlight when user hovers a search result
2250 */
2251 handleSettingsSearchHover: function(e) {
2252 var idx = parseInt($(e.currentTarget).attr('data-idx'), 10);
2253 if (isNaN(idx)) return;
2254 this.searchActiveIndex = idx;
2255 this.updateSearchActive(false);
2256 },
2257
2258 /**
2259 * Apply the active class to the current index and scroll it into view
2260 */
2261 updateSearchActive: function(scroll) {
2262 var $items = $('#vigilante-settings-search-results .vigilante-search-item');
2263 $items.removeClass('vigilante-search-item-active');
2264 var $active = $items.eq(this.searchActiveIndex);
2265 if (!$active.length) return;
2266 $active.addClass('vigilante-search-item-active');
2267 if (scroll !== false && $active[0] && typeof $active[0].scrollIntoView === 'function') {
2268 $active[0].scrollIntoView({ block: 'nearest' });
2269 }
2270 },
2271
2272 /**
2273 * Format bytes as a human-readable size
2274 */
2275 formatBytes: function(bytes) {
2276 if (!bytes || bytes < 0) return '0 B';
2277 var units = ['B', 'KB', 'MB', 'GB', 'TB'];
2278 var i = 0;
2279 var n = bytes;
2280 while (n >= 1024 && i < units.length - 1) {
2281 n = n / 1024;
2282 i++;
2283 }
2284 return (i === 0 ? n.toFixed(0) : n.toFixed(1)) + ' ' + units[i];
2285 },
2286
2287 /**
2288 * Update DB tables info: count + total size
2289 */
2290 updateDbTablesInfo: function() {
2291 var $boxes = $('.vigilante-db-table-check');
2292 var total = $boxes.length;
2293 if (!total) {
2294 $('.vigilante-db-tables-info').text('');
2295 return;
2296 }
2297 var $checked = $boxes.filter(':checked');
2298 var checkedCount = $checked.length;
2299 var bytes = 0;
2300 $checked.each(function() {
2301 bytes += parseInt($(this).attr('data-bytes'), 10) || 0;
2302 });
2303 var sizeStr = Vigilante_Admin.formatBytes(bytes);
2304 var tpl;
2305 if (checkedCount === total) {
2306 tpl = vigilanteAdmin.strings.dbTablesTotal || '%1$d tables total (%2$s)';
2307 $('.vigilante-db-tables-info').text(tpl.replace('%1$d', total).replace('%2$s', sizeStr));
2308 } else {
2309 tpl = vigilanteAdmin.strings.dbTablesSelected || '%1$d tables selected (%2$s)';
2310 $('.vigilante-db-tables-info').text(tpl.replace('%1$d', checkedCount).replace('%2$s', sizeStr));
2311 }
2312 },
2313
2314 /**
2315 * Load database tables via AJAX
2316 */
2317 loadDbTables: function() {
2318 $.ajax({
2319 url: vigilanteAdmin.ajaxUrl,
2320 type: 'POST',
2321 data: {
2322 action: 'vigilante_get_db_tables',
2323 nonce: vigilanteAdmin.nonce
2324 },
2325 success: function(response) {
2326 if (!response.success) {
2327 Vigilante_Admin.showNotice('error', response.data);
2328 return;
2329 }
2330
2331 var data = response.data;
2332 var coreHtml = '';
2333 var otherHtml = '';
2334
2335 // Build core tables checkboxes
2336 if (data.core && data.core.length) {
2337 $.each(data.core, function(i, table) {
2338 coreHtml += '<label class="vigilante-db-table-label">';
2339 coreHtml += '<input type="checkbox" class="vigilante-db-table-check" value="' + table.name + '" data-bytes="' + (table.bytes || 0) + '" checked>';
2340 coreHtml += '<span class="vigilante-db-table-name" title="' + table.name + '">' + table.short + '</span>';
2341 coreHtml += '<span class="vigilante-db-table-meta">' + table.rows + ' rows &middot; ' + table.size + '</span>';
2342 coreHtml += '</label>';
2343 });
2344 }
2345
2346 // Build other tables checkboxes
2347 if (data.other && data.other.length) {
2348 $.each(data.other, function(i, table) {
2349 otherHtml += '<label class="vigilante-db-table-label">';
2350 otherHtml += '<input type="checkbox" class="vigilante-db-table-check" value="' + table.name + '" data-bytes="' + (table.bytes || 0) + '" checked>';
2351 otherHtml += '<span class="vigilante-db-table-name" title="' + table.name + '">' + table.short + '</span>';
2352 otherHtml += '<span class="vigilante-db-table-meta">' + table.rows + ' rows &middot; ' + table.size + '</span>';
2353 otherHtml += '</label>';
2354 });
2355 $('#vigilante-db-other-group').show();
2356 }
2357
2358 $('#vigilante-db-core-tables').html(coreHtml);
2359 $('#vigilante-db-other-tables').html(otherHtml);
2360
2361 Vigilante_Admin.updateDbTablesInfo();
2362
2363 $('.vigilante-db-tables-loading').hide();
2364 $('.vigilante-db-tables-content').show();
2365 }
2366 });
2367 },
2368
2369 /**
2370 * Select/deselect all tables
2371 */
2372 handleDbSelectAll: function(e) {
2373 var checked = $(e.currentTarget).prop('checked');
2374 $('.vigilante-db-table-check').prop('checked', checked);
2375 this.updateDbTablesInfo();
2376 },
2377
2378 /**
2379 * Update select-all state when individual checkbox changes
2380 */
2381 handleDbTableCheck: function() {
2382 var total = $('.vigilante-db-table-check').length;
2383 var checked = $('.vigilante-db-table-check:checked').length;
2384 $('#vigilante-db-select-all').prop('checked', total === checked);
2385 this.updateDbTablesInfo();
2386 },
2387
2388 /**
2389 * Download database backup
2390 */
2391 handleDbBackupDownload: function(e) {
2392 e.preventDefault();
2393
2394 var tables = [];
2395 $('.vigilante-db-table-check:checked').each(function() {
2396 tables.push($(this).val());
2397 });
2398
2399 if (tables.length === 0) {
2400 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.dbBackupNoTables);
2401 return;
2402 }
2403
2404 var $btn = $(e.currentTarget);
2405 $btn.prop('disabled', true).html(vigilanteAdmin.strings.dbBackupDownloading + ' <span class="vigilante-spinner"></span>');
2406
2407 // Submit via hidden form for direct file download
2408 var $form = $('<form>', {
2409 method: 'POST',
2410 action: vigilanteAdmin.ajaxUrl
2411 });
2412
2413 $form.append($('<input>', { type: 'hidden', name: 'action', value: 'vigilante_download_db_backup' }));
2414 $form.append($('<input>', { type: 'hidden', name: 'nonce', value: vigilanteAdmin.nonce }));
2415 $form.append($('<input>', { type: 'hidden', name: 'tables', value: tables.join(',') }));
2416
2417 $('body').append($form);
2418 $form.submit();
2419 $form.remove();
2420
2421 // Re-enable button after a delay (download starts in background)
2422 setTimeout(function() {
2423 $btn.prop('disabled', false).text($btn.data('original-text') || vigilanteAdmin.strings.downloadBackup || 'Download Backup (.zip)');
2424 Vigilante_Admin.showNotice('success', vigilanteAdmin.strings.dbBackupSuccess);
2425 }, 3000);
2426 },
2427
2428 // =================================================================
2429 // DATABASE PREFIX HANDLERS
2430 // =================================================================
2431
2432 /**
2433 * Regenerate random prefix
2434 */
2435 handleDbRegeneratePrefix: function(e) {
2436 e.preventDefault();
2437
2438 var $btn = $(e.currentTarget);
2439 $btn.prop('disabled', true);
2440
2441 $.ajax({
2442 url: vigilanteAdmin.ajaxUrl,
2443 type: 'POST',
2444 data: {
2445 action: 'vigilante_generate_prefix',
2446 nonce: vigilanteAdmin.nonce
2447 },
2448 success: function(response) {
2449 if (response.success) {
2450 $('#vigilante-new-prefix').text(response.data.prefix);
2451 } else {
2452 Vigilante_Admin.showNotice('error', response.data);
2453 }
2454 },
2455 complete: function() {
2456 $btn.prop('disabled', false);
2457 }
2458 });
2459 },
2460
2461 /**
2462 * Toggle the change prefix button based on checkbox
2463 */
2464 handleDbPrefixConfirmToggle: function(e) {
2465 var checked = $(e.currentTarget).prop('checked');
2466 $('.vigilante-db-change-prefix').prop('disabled', !checked);
2467 },
2468
2469 /**
2470 * Change database prefix
2471 */
2472 handleDbChangePrefix: function(e) {
2473 e.preventDefault();
2474
2475 // Verify checkbox is checked
2476 if (!$('#vigilante-prefix-backup-confirm').prop('checked')) {
2477 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.dbPrefixCheckbox);
2478 return;
2479 }
2480
2481 var newPrefix = $('#vigilante-new-prefix').text().trim();
2482
2483 if (!confirm(vigilanteAdmin.strings.dbPrefixConfirm)) {
2484 return;
2485 }
2486
2487 var $btn = $(e.currentTarget);
2488 $btn.prop('disabled', true).html(vigilanteAdmin.strings.dbPrefixChanging + ' <span class="vigilante-spinner"></span>');
2489
2490 $.ajax({
2491 url: vigilanteAdmin.ajaxUrl,
2492 type: 'POST',
2493 data: {
2494 action: 'vigilante_change_prefix',
2495 nonce: vigilanteAdmin.nonce,
2496 prefix: newPrefix
2497 },
2498 success: function(response) {
2499 if (response.success) {
2500 Vigilante_Admin.showNotice('success', vigilanteAdmin.strings.dbPrefixSuccess);
2501 // Reload page after prefix change (session will still work)
2502 setTimeout(function() {
2503 location.reload();
2504 }, 2000);
2505 } else {
2506 Vigilante_Admin.showNotice('error', response.data);
2507 $btn.prop('disabled', false).text($btn.data('original-text'));
2508 }
2509 },
2510 error: function() {
2511 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
2512 $btn.prop('disabled', false).text($btn.data('original-text'));
2513 }
2514 });
2515 },
2516
2517 /**
2518 * Show notice
2519 */
2520 showNotice: function(type, message) {
2521 // Remove any existing notices first.
2522 $('.vigilante-notice').remove();
2523
2524 var $notice = $('<div class="vigilante-notice vigilante-notice-' + type + '">' + message + '</div>');
2525 $('.vigilante-main').prepend($notice);
2526
2527 // Scroll to top of the settings area so user sees the notice.
2528 $('html, body').animate({
2529 scrollTop: $('.vigilante-admin-wrap').offset().top - 50
2530 }, 300);
2531
2532 setTimeout(function() {
2533 $notice.fadeOut(function() {
2534 $(this).remove();
2535 });
2536 }, 5000);
2537 },
2538
2539 /**
2540 * Handle view log details
2541 */
2542 handleViewLogDetails: function(e) {
2543 e.preventDefault();
2544 e.stopPropagation();
2545
2546 var $btn = $(e.currentTarget);
2547 var detailsStr = $btn.attr('data-details');
2548
2549 if (!detailsStr) {
2550 return;
2551 }
2552
2553 var details;
2554 try {
2555 details = JSON.parse(detailsStr);
2556 } catch (err) {
2557 return;
2558 }
2559
2560 var html = '';
2561
2562 var s = vigilanteAdmin.strings;
2563
2564 // -- Section: Request --
2565 html += '<div class="vigilante-popup-section">';
2566 html += '<h4 class="vigilante-popup-section-title">' + this.escapeHtml(s.logRequest || 'Request') + '</h4>';
2567 html += '<table class="vigilante-details-table">';
2568 html += '<tr><th>' + this.escapeHtml(s.logDate || 'Date') + '</th><td>' + this.escapeHtml(details.date) + '</td></tr>';
2569 if (details.request_method) {
2570 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>';
2571 }
2572 html += '<tr><th>' + this.escapeHtml(s.logType || 'Type') + '</th><td>' + this.escapeHtml(details.type) + '</td></tr>';
2573 html += '<tr><th>' + this.escapeHtml(s.logAction || 'Action') + '</th><td>' + this.escapeHtml(details.action || '-') + '</td></tr>';
2574 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>';
2575 html += '<tr><th>' + this.escapeHtml(s.logMessage || 'Message') + '</th><td>' + this.escapeHtml(details.message) + '</td></tr>';
2576 html += '</table>';
2577 html += '</div>';
2578
2579 // -- Section: Client --
2580 html += '<div class="vigilante-popup-section">';
2581 html += '<h4 class="vigilante-popup-section-title">' + this.escapeHtml(s.logClient || 'Client') + '</h4>';
2582 html += '<table class="vigilante-details-table">';
2583 html += '<tr><th>' + this.escapeHtml(s.logUser || 'User') + '</th><td>' + this.escapeHtml(details.user || '-') + '</td></tr>';
2584
2585 // IP with lookup link
2586 if (details.ip && details.ip !== '0.0.0.0') {
2587 var ipEscaped = this.escapeHtml(details.ip);
2588 html += '<tr><th>' + this.escapeHtml(s.logIpAddress || 'IP Address') + '</th><td>';
2589 html += '<code>' + ipEscaped + '</code> ';
2590 html += '<a href="https://abuseipdb.com/check/' + encodeURIComponent(details.ip) + '" target="_blank" rel="noopener noreferrer" class="vigilante-ip-lookup" title="Lookup IP">';
2591 html += '<span class="dashicons dashicons-search"></span></a>';
2592 html += '</td></tr>';
2593 } else {
2594 html += '<tr><th>' + this.escapeHtml(s.logIpAddress || 'IP Address') + '</th><td><code>' + this.escapeHtml(details.ip) + '</code></td></tr>';
2595 }
2596
2597 if (details.user_agent) {
2598 html += '<tr><th>' + this.escapeHtml(s.logUserAgent || 'User Agent') + '</th><td class="vigilante-ua-cell"><code>' + this.escapeHtml(details.user_agent) + '</code></td></tr>';
2599 }
2600 html += '</table>';
2601
2602 // Action buttons for IP and UA
2603 html += '<div class="vigilante-popup-actions">';
2604 if (details.ip && details.ip !== '0.0.0.0') {
2605 html += '<span class="vigilante-popup-actions-label">' + this.escapeHtml(s.logIpLabel || 'IP:') + '</span>';
2606 if (details.is_ip_whitelisted) {
2607 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> ';
2608 } else {
2609 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> ';
2610 }
2611 if (details.is_ip_blacklisted) {
2612 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> ';
2613 } else {
2614 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> ';
2615 }
2616 }
2617 if (details.user_agent) {
2618 html += '<span class="vigilante-popup-actions-label">' + this.escapeHtml(s.logUaLabel || 'UA:') + '</span>';
2619 if (details.is_ua_whitelisted) {
2620 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> ';
2621 } else {
2622 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> ';
2623 }
2624 if (details.is_ua_blacklisted) {
2625 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>';
2626 } else {
2627 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>';
2628 }
2629 }
2630 html += '</div>';
2631 html += '<div class="vigilante-popup-feedback" style="display:none;"></div>';
2632 html += '</div>';
2633
2634 // Event ID for reference
2635 html += '<div class="vigilante-popup-footer">';
2636 html += '<span class="vigilante-popup-id">ID: ' + this.escapeHtml(details.id) + '</span>';
2637 html += '</div>';
2638
2639 $('#vigilante-log-details-content').html(html);
2640 $('#vigilante-log-details-modal').fadeIn(200);
2641 },
2642
2643 /**
2644 * Handle adding IP or UA to firewall whitelist/blacklist
2645 */
2646 handleAddToFirewallList: function(e) {
2647 e.preventDefault();
2648 var $btn = $(e.currentTarget);
2649 var itemType = $btn.data('item-type');
2650 var listType = $btn.data('list-type');
2651 var value = $btn.data('value');
2652
2653 if (!itemType || !listType || !value) {
2654 return;
2655 }
2656
2657 $btn.prop('disabled', true);
2658
2659 var self = this;
2660 $.ajax({
2661 url: vigilanteAdmin.ajaxUrl,
2662 type: 'POST',
2663 data: {
2664 action: 'vigilante_add_to_firewall_list',
2665 nonce: vigilanteAdmin.nonce,
2666 item_type: itemType,
2667 list_type: listType,
2668 value: value
2669 },
2670 success: function(response) {
2671 var $feedback = $('.vigilante-popup-feedback');
2672 if (response.success) {
2673 $btn.text(vigilanteAdmin.strings.logAdded || 'Added!').addClass('vigilante-btn-added');
2674 $feedback.html('<span class="vigilante-popup-msg vigilante-popup-msg-success">' + response.data + '</span>').slideDown(150);
2675 } else {
2676 $btn.prop('disabled', false);
2677 $feedback.html('<span class="vigilante-popup-msg vigilante-popup-msg-warning">' + (response.data || vigilanteAdmin.strings.logErrorAddingToList || 'Error adding to list') + '</span>').slideDown(150);
2678 }
2679 },
2680 error: function() {
2681 $btn.prop('disabled', false);
2682 $('.vigilante-popup-feedback').html('<span class="vigilante-popup-msg vigilante-popup-msg-error">' + (vigilanteAdmin.strings.logRequestFailed || 'Request failed') + '</span>').slideDown(150);
2683 }
2684 });
2685 },
2686
2687 /**
2688 * Handle unblock firewall IP
2689 */
2690 handleUnblockFirewallIp: function(e) {
2691 var $btn = $(e.currentTarget);
2692 var ip = $btn.data('ip');
2693
2694 if (!confirm(vigilanteAdmin.strings.confirmUnblockIp || 'Unblock this IP?')) {
2695 return;
2696 }
2697
2698 $btn.prop('disabled', true).text(vigilanteAdmin.strings.loading || 'Loading...');
2699
2700 $.ajax({
2701 url: vigilanteAdmin.ajaxUrl,
2702 type: 'POST',
2703 data: {
2704 action: 'vigilante_unblock_firewall_ip',
2705 nonce: vigilanteAdmin.nonce,
2706 ip: ip
2707 },
2708 success: function(response) {
2709 if (response.success) {
2710 $btn.closest('tr').fadeOut(300, function() {
2711 var $tbody = $(this).closest('tbody');
2712 $(this).remove();
2713 // Hide the whole section if no more blocked IPs
2714 if ($tbody.children('tr').length === 0) {
2715 $tbody.closest('.vigilante-lockout-section').fadeOut(300);
2716 }
2717 });
2718 } else {
2719 alert(response.data || 'Error');
2720 $btn.prop('disabled', false).text(vigilanteAdmin.strings.unblock || 'Unblock');
2721 }
2722 },
2723 error: function() {
2724 $btn.prop('disabled', false).text(vigilanteAdmin.strings.unblock || 'Unblock');
2725 }
2726 });
2727 },
2728
2729 /**
2730 * Handle close modal
2731 */
2732 handleCloseModal: function(e) {
2733 if ($(e.target).hasClass('vigilante-modal') || $(e.target).hasClass('vigilante-modal-close')) {
2734 $('.vigilante-modal').hide();
2735 }
2736 },
2737
2738 /**
2739 * Escape HTML
2740 */
2741 escapeHtml: function(text) {
2742 if (text === null || text === undefined) return '';
2743 if (typeof text !== 'string') {
2744 text = String(text);
2745 }
2746 var div = document.createElement('div');
2747 div.textContent = text;
2748 return div.innerHTML;
2749 },
2750
2751 /**
2752 * Debounce function
2753 */
2754 debounce: function(func, wait) {
2755 var timeout;
2756 return function() {
2757 var context = this, args = arguments;
2758 clearTimeout(timeout);
2759 timeout = setTimeout(function() {
2760 func.apply(context, args);
2761 }, wait);
2762 };
2763 },
2764
2765 // =================================================================
2766 // Force Password Reset functionality
2767 // =================================================================
2768
2769 /**
2770 * Selected users for password reset
2771 */
2772 selectedPasswordResetUsers: [],
2773
2774 /**
2775 * Initialize password reset handlers
2776 */
2777 initPasswordReset: function() {
2778 var self = this;
2779
2780 // User search for password reset
2781 var searchTimeout;
2782 $(document).on('input', '#vigilante-password-reset-search', function() {
2783 var query = $(this).val();
2784 clearTimeout(searchTimeout);
2785
2786 if (query.length < 2) {
2787 $('#vigilante-password-reset-results').hide().empty();
2788 return;
2789 }
2790
2791 searchTimeout = setTimeout(function() {
2792 self.searchUsersForPasswordReset(query);
2793 }, 300);
2794 });
2795
2796 // Close search results when clicking outside
2797 $(document).on('click', function(e) {
2798 if (!$(e.target).closest('.vigilante-user-search-wrapper').length) {
2799 $('#vigilante-password-reset-results').hide();
2800 }
2801 });
2802
2803 // Reset selected users button
2804 $(document).on('click', '#vigilante-reset-selected-users', function(e) {
2805 e.preventDefault();
2806 self.forceResetSelectedUsers();
2807 });
2808
2809 // Reset all users button
2810 $(document).on('click', '#vigilante-reset-all-users', function(e) {
2811 e.preventDefault();
2812 self.forceResetAllUsers();
2813 });
2814
2815 // Reset by role - checkbox change
2816 $(document).on('change', '.vigilante-reset-role-checkbox', function() {
2817 self.updateRoleResetSummary();
2818 });
2819
2820 // Reset by role button
2821 $(document).on('click', '#vigilante-reset-by-role', function(e) {
2822 e.preventDefault();
2823 self.forceResetByRoles();
2824 });
2825 },
2826
2827 /**
2828 * Search users for password reset
2829 */
2830 searchUsersForPasswordReset: function(query) {
2831 var self = this;
2832 var $results = $('#vigilante-password-reset-results');
2833
2834 $.ajax({
2835 url: vigilanteAdmin.ajaxUrl,
2836 type: 'POST',
2837 data: {
2838 action: 'vigilante_search_users_password_reset',
2839 nonce: vigilanteAdmin.nonce,
2840 query: query
2841 },
2842 success: function(response) {
2843 if (response.success && response.data.length > 0) {
2844 var html = '<ul class="vigilante-user-search-list">';
2845 response.data.forEach(function(user) {
2846 var isSelected = self.selectedPasswordResetUsers.indexOf(user.ID) !== -1;
2847 html += '<li data-user-id="' + user.ID + '" class="' + (isSelected ? 'selected' : '') + '">';
2848 html += '<img src="' + self.escapeHtml(user.avatar) + '" alt="" class="vigilante-user-avatar">';
2849 html += '<div class="vigilante-user-info">';
2850 html += '<strong>' + self.escapeHtml(user.display_name) + '</strong>';
2851 html += '<br><small>' + self.escapeHtml(user.user_login) + ' - ' + self.escapeHtml(user.user_email) + '</small>';
2852 html += '<br><small class="vigilante-user-roles">' + self.escapeHtml(user.roles) + '</small>';
2853 html += '</div>';
2854 html += '</li>';
2855 });
2856 html += '</ul>';
2857 $results.html(html).show();
2858
2859 // Handle user selection
2860 $results.find('li').on('click', function() {
2861 var userId = parseInt($(this).data('user-id'));
2862 var userName = $(this).find('strong').text();
2863 var userEmail = $(this).find('small').first().text();
2864 self.togglePasswordResetUser(userId, userName, userEmail);
2865 $(this).toggleClass('selected');
2866 });
2867 } else {
2868 $results.html('<p class="vigilante-no-results">' + (vigilanteAdmin.strings.noUsersFoundSearch || 'No users found') + '</p>').show();
2869 }
2870 }
2871 });
2872 },
2873
2874 /**
2875 * Toggle user selection for password reset
2876 */
2877 togglePasswordResetUser: function(userId, userName, userEmail) {
2878 var index = this.selectedPasswordResetUsers.indexOf(userId);
2879 var $selectedContainer = $('#vigilante-password-reset-selected');
2880 var $list = $selectedContainer.find('.vigilante-selected-users-list');
2881 var $btn = $('#vigilante-reset-selected-users');
2882
2883 if (index === -1) {
2884 // Add user
2885 this.selectedPasswordResetUsers.push(userId);
2886 $list.append(
2887 '<li data-user-id="' + userId + '">' +
2888 '<span>' + this.escapeHtml(userName) + '</span>' +
2889 '<button type="button" class="vigilante-remove-user" title="Remove">&times;</button>' +
2890 '</li>'
2891 );
2892 } else {
2893 // Remove user
2894 this.selectedPasswordResetUsers.splice(index, 1);
2895 $list.find('li[data-user-id="' + userId + '"]').remove();
2896 }
2897
2898 // Update UI
2899 if (this.selectedPasswordResetUsers.length > 0) {
2900 $selectedContainer.show();
2901 $btn.prop('disabled', false);
2902 } else {
2903 $selectedContainer.hide();
2904 $btn.prop('disabled', true);
2905 }
2906
2907 // Handle remove button click
2908 $list.find('.vigilante-remove-user').off('click').on('click', function() {
2909 var uid = $(this).closest('li').data('user-id');
2910 var idx = Vigilante_Admin.selectedPasswordResetUsers.indexOf(uid);
2911 if (idx !== -1) {
2912 Vigilante_Admin.selectedPasswordResetUsers.splice(idx, 1);
2913 }
2914 $(this).closest('li').remove();
2915 $('#vigilante-password-reset-results').find('li[data-user-id="' + uid + '"]').removeClass('selected');
2916
2917 if (Vigilante_Admin.selectedPasswordResetUsers.length === 0) {
2918 $selectedContainer.hide();
2919 $btn.prop('disabled', true);
2920 }
2921 });
2922 },
2923
2924 /**
2925 * Force reset for selected users
2926 */
2927 forceResetSelectedUsers: function() {
2928 var self = this;
2929
2930 if (this.selectedPasswordResetUsers.length === 0) {
2931 return;
2932 }
2933
2934 var currentUserId = parseInt(vigilanteAdmin.currentUserId || 0);
2935 var resettingSelf = this.selectedPasswordResetUsers.indexOf(currentUserId) !== -1;
2936
2937 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);
2938 if (resettingSelf) {
2939 confirmMsg += '\n\n' + (vigilanteAdmin.strings.warningResettingSelf || 'WARNING: You are including yourself. Your session will end and you will need to set a new password.');
2940 }
2941
2942 if (!confirm(confirmMsg)) {
2943 return;
2944 }
2945
2946 var $btn = $('#vigilante-reset-selected-users');
2947 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
2948
2949 $.ajax({
2950 url: vigilanteAdmin.ajaxUrl,
2951 type: 'POST',
2952 data: {
2953 action: 'vigilante_force_password_reset',
2954 nonce: vigilanteAdmin.nonce,
2955 user_ids: this.selectedPasswordResetUsers
2956 },
2957 success: function(response) {
2958 if (response.success) {
2959 self.showNotice('success', response.data.message);
2960
2961 // Clear selection
2962 self.selectedPasswordResetUsers = [];
2963 $('#vigilante-password-reset-selected').hide().find('.vigilante-selected-users-list').empty();
2964 $('#vigilante-password-reset-search').val('');
2965 $('#vigilante-password-reset-results').hide().empty();
2966
2967 // Reload if resetting self
2968 if (response.data.resetting_self) {
2969 setTimeout(function() {
2970 window.location.href = vigilanteAdmin.logoutUrl || '/wp-login.php';
2971 }, 2000);
2972 } else {
2973 setTimeout(function() {
2974 location.reload();
2975 }, 1500);
2976 }
2977 } else {
2978 self.showNotice('error', response.data);
2979 }
2980 },
2981 error: function() {
2982 self.showNotice('error', vigilanteAdmin.strings.anErrorOccurred || 'An error occurred');
2983 },
2984 complete: function() {
2985 $btn.prop('disabled', false).text(vigilanteAdmin.strings.forceResetSelected || 'Force Reset for Selected Users');
2986 }
2987 });
2988 },
2989
2990 /**
2991 * Force reset for all users
2992 */
2993 forceResetAllUsers: function() {
2994 var self = this;
2995 var includeSelf = $('#vigilante-reset-all-include-self').is(':checked');
2996
2997 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?';
2998 if (includeSelf) {
2999 confirmMsg += '\n\n' + (vigilanteAdmin.strings.warningResettingSelfAll || 'WARNING: You are including yourself. Your session will end immediately.');
3000 }
3001
3002 if (!confirm(confirmMsg)) {
3003 return;
3004 }
3005
3006 var $btn = $('#vigilante-reset-all-users');
3007 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3008
3009 $.ajax({
3010 url: vigilanteAdmin.ajaxUrl,
3011 type: 'POST',
3012 data: {
3013 action: 'vigilante_force_password_reset_all',
3014 nonce: vigilanteAdmin.nonce,
3015 include_self: includeSelf ? 1 : 0
3016 },
3017 success: function(response) {
3018 if (response.success) {
3019 self.showNotice('success', response.data.message);
3020
3021 // Reload if resetting self
3022 if (response.data.resetting_self) {
3023 setTimeout(function() {
3024 window.location.href = vigilanteAdmin.logoutUrl || '/wp-login.php';
3025 }, 2000);
3026 } else {
3027 setTimeout(function() {
3028 location.reload();
3029 }, 1500);
3030 }
3031 } else {
3032 self.showNotice('error', response.data);
3033 }
3034 },
3035 error: function() {
3036 self.showNotice('error', vigilanteAdmin.strings.anErrorOccurred || 'An error occurred');
3037 },
3038 complete: function() {
3039 $btn.prop('disabled', false).text(vigilanteAdmin.strings.forceResetAll || 'Force Reset for ALL Users');
3040 }
3041 });
3042 },
3043
3044 /**
3045 * Update role reset summary when checkboxes change
3046 */
3047 updateRoleResetSummary: function() {
3048 var totalCount = 0;
3049 var includesSelf = false;
3050
3051 $('.vigilante-reset-role-checkbox:checked').each(function() {
3052 totalCount += parseInt($(this).data('count') || 0);
3053 if ($(this).closest('label').find('em').length > 0) {
3054 includesSelf = true;
3055 }
3056 });
3057
3058 var $summary = $('#vigilante-reset-role-summary');
3059 var $selfOption = $('#vigilante-reset-role-self-option');
3060 var $btn = $('#vigilante-reset-by-role');
3061
3062 if (totalCount > 0) {
3063 $('#vigilante-reset-role-count').text(totalCount);
3064 $summary.show();
3065 $btn.prop('disabled', false);
3066 } else {
3067 $summary.hide();
3068 $btn.prop('disabled', true);
3069 }
3070
3071 if (includesSelf) {
3072 $selfOption.show();
3073 } else {
3074 $selfOption.hide();
3075 $('#vigilante-reset-role-include-self').prop('checked', false);
3076 }
3077 },
3078
3079 /**
3080 * Force reset for users with selected roles
3081 */
3082 forceResetByRoles: function() {
3083 var self = this;
3084 var roles = [];
3085
3086 $('.vigilante-reset-role-checkbox:checked').each(function() {
3087 roles.push($(this).val());
3088 });
3089
3090 if (roles.length === 0) {
3091 self.showNotice('error', vigilanteAdmin.strings.noRolesSelected || 'Please select at least one role.');
3092 return;
3093 }
3094
3095 var totalCount = 0;
3096 $('.vigilante-reset-role-checkbox:checked').each(function() {
3097 totalCount += parseInt($(this).data('count') || 0);
3098 });
3099
3100 var includeSelf = $('#vigilante-reset-role-include-self').is(':checked');
3101
3102 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);
3103 if (includeSelf) {
3104 confirmMsg += '\n\n' + (vigilanteAdmin.strings.warningResettingSelfAll || 'WARNING: You are including yourself. Your session will end immediately.');
3105 }
3106
3107 if (!confirm(confirmMsg)) {
3108 return;
3109 }
3110
3111 var $btn = $('#vigilante-reset-by-role');
3112 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3113
3114 $.ajax({
3115 url: vigilanteAdmin.ajaxUrl,
3116 type: 'POST',
3117 data: {
3118 action: 'vigilante_force_password_reset_by_role',
3119 nonce: vigilanteAdmin.nonce,
3120 roles: roles,
3121 include_self: includeSelf ? 1 : 0
3122 },
3123 success: function(response) {
3124 if (response.success) {
3125 self.showNotice('success', response.data.message);
3126
3127 // Clear role checkboxes
3128 $('.vigilante-reset-role-checkbox').prop('checked', false);
3129 self.updateRoleResetSummary();
3130
3131 if (response.data.resetting_self) {
3132 setTimeout(function() {
3133 window.location.href = vigilanteAdmin.logoutUrl || '/wp-login.php';
3134 }, 2000);
3135 } else {
3136 setTimeout(function() {
3137 location.reload();
3138 }, 1500);
3139 }
3140 } else {
3141 self.showNotice('error', response.data);
3142 }
3143 },
3144 error: function() {
3145 self.showNotice('error', vigilanteAdmin.strings.anErrorOccurred || 'An error occurred');
3146 },
3147 complete: function() {
3148 $btn.prop('disabled', false).text(vigilanteAdmin.strings.forceResetByRole || 'Force Reset for Selected Roles');
3149 }
3150 });
3151 },
3152
3153 /**
3154 * Initialize user approval handlers
3155 */
3156 initUserApproval: function() {
3157 var self = this;
3158
3159 // Approve user
3160 $(document).on('click', '.vigilante-approve-user', function() {
3161 var $btn = $(this);
3162 var userId = $btn.data('user-id');
3163 var $row = $btn.closest('tr');
3164
3165 if (!confirm(vigilanteAdmin.strings.confirmApprove || 'Approve this user?')) {
3166 return;
3167 }
3168
3169 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3170
3171 $.ajax({
3172 url: vigilanteAdmin.ajaxUrl,
3173 type: 'POST',
3174 data: {
3175 action: 'vigilante_approve_user',
3176 nonce: vigilanteAdmin.nonce,
3177 user_id: userId
3178 },
3179 success: function(response) {
3180 if (response.success) {
3181 self.showNotice('success', response.data.message);
3182 $row.fadeOut(400, function() {
3183 $(this).remove();
3184 self.updatePendingCount();
3185 });
3186 } else {
3187 self.showNotice('error', response.data);
3188 $btn.prop('disabled', false).text(vigilanteAdmin.strings.approve || 'Approve');
3189 }
3190 },
3191 error: function() {
3192 self.showNotice('error', vigilanteAdmin.strings.error);
3193 $btn.prop('disabled', false).text(vigilanteAdmin.strings.approve || 'Approve');
3194 }
3195 });
3196 });
3197
3198 // Reject user
3199 $(document).on('click', '.vigilante-reject-user', function() {
3200 var $btn = $(this);
3201 var userId = $btn.data('user-id');
3202 var $row = $btn.closest('tr');
3203
3204 var reason = prompt(vigilanteAdmin.strings.rejectReason || 'Enter rejection reason (optional):');
3205 if (reason === null) {
3206 return; // Cancelled
3207 }
3208
3209 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3210
3211 $.ajax({
3212 url: vigilanteAdmin.ajaxUrl,
3213 type: 'POST',
3214 data: {
3215 action: 'vigilante_reject_user',
3216 nonce: vigilanteAdmin.nonce,
3217 user_id: userId,
3218 reason: reason
3219 },
3220 success: function(response) {
3221 if (response.success) {
3222 self.showNotice('success', response.data.message);
3223 $row.fadeOut(400, function() {
3224 $(this).remove();
3225 self.updatePendingCount();
3226 });
3227 } else {
3228 self.showNotice('error', response.data);
3229 $btn.prop('disabled', false).text(vigilanteAdmin.strings.reject || 'Reject');
3230 }
3231 },
3232 error: function() {
3233 self.showNotice('error', vigilanteAdmin.strings.error);
3234 $btn.prop('disabled', false).text(vigilanteAdmin.strings.reject || 'Reject');
3235 }
3236 });
3237 });
3238 },
3239
3240 /**
3241 * Update pending users count badge
3242 */
3243 updatePendingCount: function() {
3244 var $badge = $('.vigilante-pending-users-section .vigilante-badge-warning');
3245 var $table = $('.vigilante-pending-users-table tbody tr');
3246 var count = $table.length;
3247
3248 if (count === 0) {
3249 $badge.remove();
3250 $('.vigilante-pending-users-table').replaceWith(
3251 '<div class="vigilante-no-lockouts">' +
3252 '<span class="dashicons dashicons-yes-alt"></span>' +
3253 '<p>' + (vigilanteAdmin.strings.noPending || 'No pending registrations.') + '</p>' +
3254 '</div>'
3255 );
3256 } else {
3257 $badge.text(count);
3258 }
3259 },
3260
3261 /**
3262 * Initialize session management handlers
3263 */
3264 initSessionManagement: function() {
3265 var self = this;
3266 var searchTimer = null;
3267 this.selectedSessionUserId = null;
3268
3269 // Search users for session management
3270 $(document).on('input', '#vigilante-session-user-search', function() {
3271 var query = $(this).val();
3272 var $results = $('#vigilante-session-search-results');
3273
3274 clearTimeout(searchTimer);
3275
3276 if (query.length < 2) {
3277 $results.hide().empty();
3278 return;
3279 }
3280
3281 searchTimer = setTimeout(function() {
3282 $.ajax({
3283 url: vigilanteAdmin.ajaxUrl,
3284 type: 'POST',
3285 data: {
3286 action: 'vigilante_search_users_password_reset',
3287 nonce: vigilanteAdmin.nonce,
3288 query: query
3289 },
3290 success: function(response) {
3291 if (response.success && response.data.length > 0) {
3292 var html = '<ul class="vigilante-user-search-list">';
3293 $.each(response.data, function(i, user) {
3294 html += '<li data-user-id="' + user.ID + '">' +
3295 '<img src="' + user.avatar + '" class="vigilante-user-avatar" alt="">' +
3296 '<div class="vigilante-user-info">' +
3297 '<strong>' + self.escapeHtml(user.display_name) + '</strong><br>' +
3298 '<small>' + self.escapeHtml(user.user_email) + '</small>' +
3299 '</div>' +
3300 '</li>';
3301 });
3302 html += '</ul>';
3303 $results.html(html).show();
3304 } else {
3305 $results.html('<p class="vigilante-no-results">' + (vigilanteAdmin.strings.noUsers || 'No users found') + '</p>').show();
3306 }
3307 }
3308 });
3309 }, 300);
3310 });
3311
3312 // Click handler for user selection in session search
3313 $(document).on('click', '#vigilante-session-search-results li', function() {
3314 var userId = $(this).data('user-id');
3315 var userName = $(this).find('strong').text();
3316 self.loadUserSessions(userId, userName);
3317 $('#vigilante-session-search-results').hide();
3318 $('#vigilante-session-user-search').val(userName);
3319 });
3320
3321 // Revoke single session
3322 $(document).on('click', '.vigilante-revoke-session', function() {
3323 var $btn = $(this);
3324 var userId = $btn.attr('data-user-id');
3325 var token = $btn.attr('data-token');
3326 var $row = $btn.closest('tr');
3327 var $paginatedContainer = $btn.closest('.vigilante-paginated-section');
3328
3329 // Fallback to row token if button token is invalid
3330 if (!token || token.length < 32) {
3331 token = $row.attr('data-token');
3332 }
3333
3334 if (!token || token.length < 32) {
3335 self.showNotice('error', vigilanteAdmin.strings.error || 'Invalid session token');
3336 return;
3337 }
3338
3339 if (!confirm(vigilanteAdmin.strings.confirmRevoke || 'Revoke this session?')) {
3340 return;
3341 }
3342
3343 $btn.prop('disabled', true);
3344
3345 $.ajax({
3346 url: vigilanteAdmin.ajaxUrl,
3347 type: 'POST',
3348 data: {
3349 action: 'vigilante_revoke_session',
3350 nonce: vigilanteAdmin.nonce,
3351 user_id: userId,
3352 token: token
3353 },
3354 success: function(response) {
3355 if (response.success) {
3356 self.showNotice('success', response.data.message);
3357 $row.fadeOut(400, function() {
3358 $(this).remove();
3359 if ($paginatedContainer.length) {
3360 Vigilante_Admin.refreshFilePagination($paginatedContainer);
3361 }
3362 });
3363 } else {
3364 self.showNotice('error', response.data);
3365 $btn.prop('disabled', false);
3366 }
3367 },
3368 error: function() {
3369 self.showNotice('error', vigilanteAdmin.strings.error);
3370 $btn.prop('disabled', false);
3371 }
3372 });
3373 });
3374
3375 // Revoke all other sessions (current user)
3376 $(document).on('click', '.vigilante-revoke-other-sessions', function() {
3377 var $btn = $(this);
3378 var userId = $btn.data('user-id');
3379
3380 if (!confirm(vigilanteAdmin.strings.confirmRevokeAll || 'Revoke all other sessions?')) {
3381 return;
3382 }
3383
3384 $btn.prop('disabled', true).text(vigilanteAdmin.strings.processing || 'Processing...');
3385
3386 $.ajax({
3387 url: vigilanteAdmin.ajaxUrl,
3388 type: 'POST',
3389 data: {
3390 action: 'vigilante_revoke_all_sessions',
3391 nonce: vigilanteAdmin.nonce,
3392 user_id: userId,
3393 include_current: 0
3394 },
3395 success: function(response) {
3396 if (response.success) {
3397 self.showNotice('success', response.data.message);
3398 setTimeout(function() {
3399 location.reload();
3400 }, 1000);
3401 } else {
3402 self.showNotice('error', response.data);
3403 }
3404 },
3405 error: function() {
3406 self.showNotice('error', vigilanteAdmin.strings.error);
3407 },
3408 complete: function() {
3409 $btn.prop('disabled', false).text(vigilanteAdmin.strings.revokeOthers || 'Revoke All Other Sessions');
3410 }
3411 });
3412 });
3413
3414 // Revoke all sessions for a user (admin managing other users)
3415 $(document).on('click', '.vigilante-revoke-all-user-sessions', function() {
3416 var $btn = $(this);
3417
3418 if (!self.selectedSessionUserId) {
3419 return;
3420 }
3421
3422 if (!confirm(vigilanteAdmin.strings.confirmRevokeAllUser || 'Revoke ALL sessions for this user? They will be logged out everywhere.')) {
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_all_sessions',
3433 nonce: vigilanteAdmin.nonce,
3434 user_id: self.selectedSessionUserId,
3435 include_current: 1
3436 },
3437 success: function(response) {
3438 if (response.success) {
3439 self.showNotice('success', response.data.message);
3440 $('#vigilante-user-sessions-container').hide();
3441 $('#vigilante-session-user-search').val('');
3442 } else {
3443 self.showNotice('error', response.data);
3444 }
3445 },
3446 error: function() {
3447 self.showNotice('error', vigilanteAdmin.strings.error);
3448 },
3449 complete: function() {
3450 $btn.prop('disabled', false);
3451 }
3452 });
3453 });
3454 },
3455
3456 /**
3457 * Load sessions for a specific user
3458 */
3459 loadUserSessions: function(userId, userName) {
3460 var self = this;
3461 this.selectedSessionUserId = userId;
3462 var $container = $('#vigilante-user-sessions-container');
3463 var $list = $('#vigilante-user-sessions-list');
3464
3465 $list.html('<tr><td colspan="4">' + (vigilanteAdmin.strings.loading || 'Loading...') + '</td></tr>');
3466 $container.show();
3467 $('#vigilante-sessions-user-name').text((vigilanteAdmin.strings.sessionsFor || 'Sessions for: ') + userName);
3468
3469 $.ajax({
3470 url: vigilanteAdmin.ajaxUrl,
3471 type: 'POST',
3472 data: {
3473 action: 'vigilante_get_user_sessions',
3474 nonce: vigilanteAdmin.nonce,
3475 user_id: userId
3476 },
3477 success: function(response) {
3478 if (response.success) {
3479 var sessions = response.data.sessions;
3480 if (sessions.length === 0) {
3481 $list.html('<tr><td colspan="4">' + (vigilanteAdmin.strings.noSessions || 'No active sessions') + '</td></tr>');
3482 return;
3483 }
3484
3485 var html = '';
3486 $.each(sessions, function(i, session) {
3487 var loginTime = session.login ? self.timeAgo(session.login) : (vigilanteAdmin.strings.unknown || 'Unknown');
3488 html += '<tr data-token="' + session.token_hash + '">' +
3489 '<td>' + self.escapeHtml(session.browser) + '</td>' +
3490 '<td><code>' + self.escapeHtml(session.ip) + '</code></td>' +
3491 '<td>' + loginTime + '</td>' +
3492 '<td>' +
3493 '<button type="button" class="button button-small vigilante-revoke-session" ' +
3494 'data-user-id="' + userId + '" data-token="' + session.token_hash + '">' +
3495 (vigilanteAdmin.strings.revoke || 'Revoke') +
3496 '</button>' +
3497 '</td>' +
3498 '</tr>';
3499 });
3500 $list.html(html);
3501 } else {
3502 $list.html('<tr><td colspan="4">' + response.data + '</td></tr>');
3503 }
3504 },
3505 error: function() {
3506 $list.html('<tr><td colspan="4">' + vigilanteAdmin.strings.error + '</td></tr>');
3507 }
3508 });
3509 },
3510
3511 /**
3512 * Format timestamp as time ago
3513 */
3514 timeAgo: function(timestamp) {
3515 var seconds = Math.floor((Date.now() / 1000) - timestamp);
3516 var s = vigilanteAdmin.strings;
3517 var intervals = [
3518 { label: s.timeYear || 'year', labelPlural: s.timeYears || 'years', seconds: 31536000 },
3519 { label: s.timeMonth || 'month', labelPlural: s.timeMonths || 'months', seconds: 2592000 },
3520 { label: s.timeDay || 'day', labelPlural: s.timeDays || 'days', seconds: 86400 },
3521 { label: s.timeHour || 'hour', labelPlural: s.timeHours || 'hours', seconds: 3600 },
3522 { label: s.timeMinute || 'minute', labelPlural: s.timeMinutes || 'minutes', seconds: 60 }
3523 ];
3524
3525 for (var i = 0; i < intervals.length; i++) {
3526 var count = Math.floor(seconds / intervals[i].seconds);
3527 if (count >= 1) {
3528 var unit = count > 1 ? intervals[i].labelPlural : intervals[i].label;
3529 return (s.timeAgo || '%1$d %2$s ago').replace('%1$d', count).replace('%2$s', unit);
3530 }
3531 }
3532 return s.justNow || 'Just now';
3533 }
3534 };
3535
3536 /* ---------------------------------------------------------------------
3537 * Security Analyzer (Dashboard widget) — v2.1.0
3538 * ------------------------------------------------------------------ */
3539
3540 var VigilanteAnalyzer = {
3541
3542 $root: null,
3543
3544 init: function() {
3545 this.$root = $('#vigilante-analyzer');
3546 if (!this.$root.length) {
3547 // Widget not present on this page — still run hash focus in case a fix link was followed.
3548 this.hashFocusFlash();
3549 return;
3550 }
3551
3552 // Scan button — 2-phase AJAX.
3553 $(document).on('click', '#vigilante-analyzer-scan', this.handleScan.bind(this));
3554
3555 // Expand/collapse detailed breakdown.
3556 $(document).on('click', '.vigilante-analyzer-toggle', this.handleToggleDetails.bind(this));
3557
3558 // Save weekly cron + email toggle on change.
3559 $(document).on('change',
3560 '.vigilante-analyzer-weekly input[type="checkbox"]',
3561 this.handleSettingsChange.bind(this));
3562
3563 // Pulse the row we landed on if we came from a fix link.
3564 this.hashFocusFlash();
3565
3566 // Upgrade the server-rendered SVG (no-op if already correct).
3567 this.renderSparklineFromData();
3568 },
3569
3570 /**
3571 * Kick off a scan. Phase 'fast' first for instant feedback, then 'slow' for remote checks.
3572 */
3573 handleScan: function(e) {
3574 e.preventDefault();
3575 if (this.isScanning) {
3576 return;
3577 }
3578 this.isScanning = true;
3579
3580 var $btn = $('#vigilante-analyzer-scan');
3581 var originalHtml = $btn.html();
3582 $btn.data('original-html', originalHtml);
3583 $btn.prop('disabled', true)
3584 .html('<span class="dashicons dashicons-update vigilante-analyzer-spin"></span> '
3585 + (vigilanteAdmin.strings.analyzerFastPhase || 'Running fast checks…'));
3586
3587 var self = this;
3588
3589 // Expand the details section so the user sees results pour in.
3590 this.expandDetails(true);
3591
3592 this.runScanPhase('fast')
3593 .done(function(fastReport) {
3594 self.applyReport(fastReport);
3595 $btn.html('<span class="dashicons dashicons-update vigilante-analyzer-spin"></span> '
3596 + (vigilanteAdmin.strings.analyzerSlowPhase || 'Running remote checks…'));
3597
3598 self.runScanPhase('slow')
3599 .done(function(slowReport) {
3600 self.applyReport(slowReport);
3601 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
3602 Vigilante_Admin.showNotice('success',
3603 vigilanteAdmin.strings.analyzerScanComplete || 'Security scan complete.');
3604 }
3605 })
3606 .fail(function(msg) {
3607 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
3608 Vigilante_Admin.showNotice('error',
3609 msg || vigilanteAdmin.strings.analyzerScanFailed || 'Security scan failed.');
3610 }
3611 })
3612 .always(function() {
3613 $btn.prop('disabled', false).html($btn.data('original-html') || originalHtml);
3614 self.isScanning = false;
3615 });
3616 })
3617 .fail(function(msg) {
3618 $btn.prop('disabled', false).html($btn.data('original-html') || originalHtml);
3619 self.isScanning = false;
3620 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
3621 Vigilante_Admin.showNotice('error',
3622 msg || vigilanteAdmin.strings.analyzerScanFailed || 'Security scan failed.');
3623 }
3624 });
3625 },
3626
3627 runScanPhase: function(phase) {
3628 var deferred = $.Deferred();
3629 $.ajax({
3630 url: vigilanteAdmin.ajaxUrl,
3631 type: 'POST',
3632 timeout: 60000,
3633 data: {
3634 action: 'vigilante_analyzer_run',
3635 nonce: vigilanteAdmin.nonce,
3636 phase: phase
3637 }
3638 }).done(function(response) {
3639 if (response && response.success) {
3640 deferred.resolve(response.data);
3641 } else {
3642 deferred.reject(response && response.data ? response.data : null);
3643 }
3644 }).fail(function(xhr, status, err) {
3645 deferred.reject(err || status);
3646 });
3647 return deferred.promise();
3648 },
3649
3650 /**
3651 * Map a 0-100 score percentage to a quality tag {label, slug}, mirroring
3652 * Vigilante_Admin::analyzer_quality_tag() in PHP.
3653 */
3654 qualityTag: function(pct) {
3655 pct = Math.max(0, Math.min(100, parseInt(pct, 10) || 0));
3656 var s = vigilanteAdmin.strings || {};
3657 // "Excellent" is reserved for a perfect score — a single missing point drops to Good.
3658 if (pct === 100) { return { label: s.analyzerQualityExcellent || 'Excellent', slug: 'a' }; }
3659 if (pct >= 70) { return { label: s.analyzerQualityGood || 'Good', slug: 'b' }; }
3660 if (pct >= 50) { return { label: s.analyzerQualityFair || 'Fair', slug: 'c' }; }
3661 if (pct >= 30) { return { label: s.analyzerQualityPoor || 'Poor', slug: 'd' }; }
3662 return { label: s.analyzerQualityCritical || 'Critical', slug: 'e' };
3663 },
3664
3665 /**
3666 * Swap a {a,b,c,d,e} slug modifier class on an element.
3667 */
3668 setQualityClass: function($el, baseClass, slug) {
3669 $el.removeClass(function(i, cls) {
3670 return (cls.match(new RegExp('(^|\\s)' + baseClass + '-[abcde](?=\\s|$)', 'g')) || []).join(' ');
3671 });
3672 $el.addClass(baseClass + '-' + slug);
3673 },
3674
3675 /**
3676 * Merge a phase report into the widget DOM.
3677 */
3678 applyReport: function(report) {
3679 if (!report || typeof report !== 'object') {
3680 return;
3681 }
3682 var $root = this.$root;
3683 var self = this;
3684
3685 // Overall pass/warn/fail counts (summary).
3686 if (report.counts && typeof report.counts === 'object') {
3687 $root.find('[data-role="pass"]').text(report.counts.pass || 0);
3688 $root.find('[data-role="warn"]').text(report.counts.warn || 0);
3689 $root.find('[data-role="fail"]').text(report.counts.fail || 0);
3690 }
3691
3692 // Main score circle + quality tag.
3693 if (report.grade) {
3694 var $card = $root.find('.vigilante-analyzer-score-card');
3695 var $circle = $card.find('.vigilante-score-circle');
3696 var gradeLc = String(report.grade).toLowerCase();
3697 var scoreN = parseInt(report.score, 10) || 0;
3698
3699 if (!$circle.length || $circle.hasClass('vigilante-grade-empty')) {
3700 $circle.remove();
3701 $card.prepend(
3702 '<div class="vigilante-score-circle vigilante-grade-'
3703 + this.escAttr(gradeLc)
3704 + '">'
3705 + '<span class="vigilante-grade">' + this.esc(report.grade) + '</span>'
3706 + '<span class="vigilante-score-text">' + this.esc(scoreN) + '%</span>'
3707 + '</div>'
3708 );
3709 } else {
3710 $circle.removeClass(function(i, cls) {
3711 return (cls.match(/(^|\s)vigilante-grade-\S+/g) || []).join(' ');
3712 }).addClass('vigilante-grade-' + gradeLc);
3713 $circle.find('.vigilante-grade').text(report.grade);
3714 $circle.find('.vigilante-score-text').text(scoreN + '%');
3715 }
3716
3717 // Quality tag in the score card.
3718 var quality = this.qualityTag(scoreN);
3719 var $tag = $root.find('[data-role="quality-tag"]');
3720 if ($tag.length) {
3721 this.setQualityClass($tag, 'vigilante-analyzer-quality', quality.slug);
3722 $tag.text(quality.label);
3723 }
3724 }
3725
3726 // "Last scan" label in the header.
3727 if (report.ran_at) {
3728 var $ranAt = $root.find('[data-role="ran-at"]');
3729 var justNow = vigilanteAdmin.strings.analyzerLastScanJustNow
3730 || 'Last scan just now';
3731 $ranAt.html(
3732 '<span class="dashicons dashicons-clock" aria-hidden="true"></span>'
3733 + this.esc(justNow)
3734 );
3735 }
3736
3737 // Per-category rows: quality pill, state counts, score, bar, and check rows.
3738 if (report.categories && typeof report.categories === 'object') {
3739 $.each(report.categories, function(slug, cat) {
3740 var $cat = $root.find('.vigilante-analyzer-category[data-category="' + slug + '"]');
3741 if (!$cat.length) {
3742 return;
3743 }
3744
3745 var infoOnly = $cat.attr('data-info-only') === '1';
3746 var counts = (cat.counts && typeof cat.counts === 'object') ? cat.counts : {};
3747
3748 if (!infoOnly) {
3749 var earned = parseInt(cat.earned, 10) || 0;
3750 var max = parseInt(cat.max, 10) || 0;
3751 var pct = max > 0 ? Math.round((earned / max) * 100) : 0;
3752 var cq = self.qualityTag(pct);
3753
3754 $cat.find('[data-role="earned"]').text(earned);
3755
3756 var $catQuality = $cat.find('[data-role="category-quality"]');
3757 if ($catQuality.length) {
3758 self.setQualityClass($catQuality, 'vigilante-analyzer-quality', cq.slug);
3759 // Update only the label span; the pill also contains the
3760 // "X/Y tests" counter so a blanket .text() would wipe it.
3761 var $label = $catQuality.find('[data-role="category-quality-label"]');
3762 if ($label.length) {
3763 $label.text(cq.label);
3764 } else {
3765 $catQuality.text(cq.label);
3766 }
3767 }
3768
3769 // "X/Y tests" inside the pill. Total is everything that
3770 // scores (pass + warn + fail), info/skip are excluded
3771 // because they don't move the category score.
3772 var $tests = $cat.find('[data-role="category-tests"]');
3773 if ($tests.length) {
3774 var passed = parseInt(counts.pass, 10) || 0;
3775 var total = passed
3776 + (parseInt(counts.warn, 10) || 0)
3777 + (parseInt(counts.fail, 10) || 0);
3778 var tpl = (vigilanteAdmin.strings && vigilanteAdmin.strings.testsCounter)
3779 || '%1$d/%2$d tests';
3780 $tests.text(tpl.replace('%1$d', passed).replace('%2$d', total));
3781 $tests.attr('data-passed', passed);
3782 $tests.attr('data-total', total);
3783 }
3784
3785 // Progress bar (width + quality color).
3786 var $bar = $cat.find('[data-role="category-bar"]');
3787 if ($bar.length) {
3788 $bar.css('width', pct + '%');
3789 self.setQualityClass($bar, 'vigilante-analyzer-category-bar-fill', cq.slug);
3790 }
3791 }
3792
3793 // State counts — show each chip only when count > 0.
3794 // Info-only categories (like reputation) also show an info count.
3795 self.updateCategoryState($cat, 'pass', parseInt(counts.pass, 10) || 0);
3796 self.updateCategoryState($cat, 'warn', parseInt(counts.warn, 10) || 0);
3797 self.updateCategoryState($cat, 'fail', parseInt(counts.fail, 10) || 0);
3798 if (infoOnly) {
3799 self.updateCategoryState($cat, 'info', parseInt(counts.info, 10) || 0);
3800 // Info-only categories replace the progress bar with a status pill
3801 // ("All clear" when nothing actionable, "N findings" otherwise).
3802 self.updateInfoStatus($cat, counts);
3803 }
3804
3805 // Replace the check rows only for checks this phase actually returned.
3806 if (cat.checks && cat.checks.length) {
3807 var $list = $cat.find('[data-role="check-list"]');
3808 $list.find('.vigilante-analyzer-check-empty').remove();
3809
3810 $.each(cat.checks, function(i, check) {
3811 var $existing = $list.find('[data-check-id="' + check.id + '"]');
3812 var html = self.renderCheckRow(check);
3813 if ($existing.length) {
3814 $existing.replaceWith(html);
3815 } else {
3816 $list.append(html);
3817 }
3818 });
3819 }
3820 });
3821 }
3822 },
3823
3824 /**
3825 * Update a per-category state chip (pass/warn/fail). Adds the chip if it doesn't
3826 * exist yet, updates its number, or removes it when the count is zero.
3827 */
3828 updateCategoryState: function($cat, state, count) {
3829 var $wrap = $cat.find('[data-role="category-states"]');
3830 if (!$wrap.length) {
3831 return;
3832 }
3833 var selector = '.vigilante-analyzer-category-state--' + state;
3834 var $chip = $wrap.find(selector);
3835
3836 if (count > 0) {
3837 if (!$chip.length) {
3838 var iconMap = { pass: 'yes', warn: 'warning', fail: 'no', info: 'info-outline' };
3839 var titleMap = {
3840 pass: 'Passing',
3841 warn: 'Warning',
3842 fail: 'Failing',
3843 info: 'Informational'
3844 };
3845 var title = titleMap[state] || '';
3846 $chip = $(
3847 '<span class="vigilante-analyzer-category-state vigilante-analyzer-category-state--'
3848 + state + '" title="' + this.escAttr(title) + '">'
3849 + '<span data-role="state-' + state + '">0</span>'
3850 + '<span class="dashicons dashicons-' + iconMap[state] + '" aria-hidden="true"></span>'
3851 + '</span>'
3852 );
3853 // Keep order: pass → warn → fail → info.
3854 if (state === 'pass') {
3855 $wrap.prepend($chip);
3856 } else if (state === 'warn') {
3857 var $passChip = $wrap.find('.vigilante-analyzer-category-state--pass');
3858 if ($passChip.length) { $chip.insertAfter($passChip); } else { $wrap.prepend($chip); }
3859 } else if (state === 'fail') {
3860 var $infoChip = $wrap.find('.vigilante-analyzer-category-state--info');
3861 if ($infoChip.length) { $chip.insertBefore($infoChip); } else { $wrap.append($chip); }
3862 } else {
3863 $wrap.append($chip);
3864 }
3865 }
3866 $chip.find('[data-role="state-' + state + '"]').text(count);
3867 } else if ($chip.length) {
3868 $chip.remove();
3869 }
3870 },
3871
3872 /**
3873 * Refresh the "All clear" / "N findings" pill for an info-only category.
3874 * Runs after a scan replaces the counts on the server side.
3875 */
3876 updateInfoStatus: function($cat, counts) {
3877 var $status = $cat.find('[data-role="info-status"]');
3878 if (!$status.length) {
3879 return;
3880 }
3881 var warnN = parseInt(counts.warn, 10) || 0;
3882 var failN = parseInt(counts.fail, 10) || 0;
3883 var issues = warnN + failN;
3884 var strings = (vigilanteAdmin && vigilanteAdmin.strings) || {};
3885
3886 if (issues > 0) {
3887 var template = strings.analyzerInfoFindings || '%d findings';
3888 var label = template.replace('%d', issues);
3889 $status
3890 .removeClass('vigilante-analyzer-category-status--clear')
3891 .addClass('vigilante-analyzer-category-status--attention')
3892 .html(
3893 '<span class="dashicons dashicons-warning" aria-hidden="true"></span>'
3894 + this.esc(label)
3895 );
3896 } else {
3897 var clear = strings.analyzerInfoAllClear || 'All clear';
3898 $status
3899 .removeClass('vigilante-analyzer-category-status--attention')
3900 .addClass('vigilante-analyzer-category-status--clear')
3901 .html(
3902 '<span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>'
3903 + this.esc(clear)
3904 );
3905 }
3906 },
3907
3908 renderCheckRow: function(check) {
3909 var state = check.state || 'skip';
3910 var icons = {
3911 pass: 'yes-alt',
3912 warn: 'warning',
3913 fail: 'dismiss',
3914 info: 'info',
3915 skip: 'minus'
3916 };
3917 var icon = icons[state] || 'minus';
3918
3919 var scoreHtml = '';
3920 var max = parseInt(check.max, 10) || 0;
3921 if (max > 0 && state !== 'info' && state !== 'skip') {
3922 scoreHtml = '<span class="vigilante-analyzer-check-score">'
3923 + this.esc((parseInt(check.score, 10) || 0) + '/' + max)
3924 + '</span>';
3925 }
3926
3927 var fixHtml = '';
3928 if (check.fix_link && (state === 'fail' || state === 'warn')) {
3929 fixHtml = '<a href="' + this.escAttr(check.fix_link) + '" class="vigilante-analyzer-fix-link">'
3930 + this.esc(vigilanteAdmin.strings.analyzerGoToSetting || 'Go to setting')
3931 + '<span class="vigilante-analyzer-fix-arrow" aria-hidden="true">&rarr;</span></a>';
3932 } else if (check.fix_link && state === 'info') {
3933 var isExt = /^https?:\/\//i.test(check.fix_link);
3934 fixHtml = '<a href="' + this.escAttr(check.fix_link) + '" class="vigilante-analyzer-fix-link"'
3935 + (isExt ? ' target="_blank" rel="noopener noreferrer"' : '') + '>'
3936 + this.esc(vigilanteAdmin.strings.analyzerLearnMore || 'Learn more')
3937 + '<span class="vigilante-analyzer-fix-arrow" aria-hidden="true">&rarr;</span></a>';
3938 }
3939
3940 var detailHtml = '';
3941 if (check.detail) {
3942 detailHtml = '<p class="vigilante-analyzer-check-detail">' + this.esc(check.detail) + '</p>';
3943 }
3944
3945 return '<li class="vigilante-analyzer-check vigilante-analyzer-check--' + this.escAttr(state) + '"'
3946 + ' data-check-id="' + this.escAttr(check.id || '') + '">'
3947 + '<span class="vigilante-analyzer-check-icon dashicons dashicons-' + this.escAttr(icon) + '" aria-hidden="true"></span>'
3948 + '<div class="vigilante-analyzer-check-body">'
3949 + '<div class="vigilante-analyzer-check-label">'
3950 + '<span>' + this.esc(check.label || '') + '</span>'
3951 + scoreHtml
3952 + '</div>'
3953 + detailHtml
3954 + fixHtml
3955 + '</div>'
3956 + '</li>';
3957 },
3958
3959 /**
3960 * Expand or collapse the detailed breakdown section.
3961 */
3962 handleToggleDetails: function(e) {
3963 e.preventDefault();
3964 var $btn = $(e.currentTarget);
3965 var expanded = $btn.attr('aria-expanded') === 'true';
3966 this.expandDetails(!expanded);
3967 },
3968
3969 expandDetails: function(expand) {
3970 var $btn = this.$root.find('.vigilante-analyzer-toggle');
3971 var $details = this.$root.find('.vigilante-analyzer-details');
3972 var show = !!expand;
3973
3974 $btn.attr('aria-expanded', show ? 'true' : 'false');
3975
3976 var label = show
3977 ? (vigilanteAdmin.strings.analyzerHideDetails || 'Hide detailed breakdown')
3978 : (vigilanteAdmin.strings.analyzerShowDetails || 'Show detailed breakdown');
3979
3980 // Preserve the chevron element; only swap the label text.
3981 var $chevron = $btn.find('.vigilante-analyzer-toggle-chevron').detach();
3982 if (!$chevron.length) {
3983 $chevron = $('<span class="vigilante-analyzer-toggle-chevron" aria-hidden="true"></span>');
3984 }
3985 $btn.text(label).append(' ').append($chevron);
3986
3987 if (show) {
3988 $details.removeAttr('hidden');
3989 } else {
3990 $details.attr('hidden', 'hidden');
3991 }
3992 },
3993
3994 /**
3995 * Auto-save weekly scan + email toggles.
3996 */
3997 handleSettingsChange: function(e) {
3998 var $input = $(e.currentTarget);
3999 var $weekly = this.$root.find('input[name="security_analyzer[weekly_scan_enabled]"]');
4000 var $email = this.$root.find('input[name="security_analyzer[email_on_regression]"]');
4001
4002 $.ajax({
4003 url: vigilanteAdmin.ajaxUrl,
4004 type: 'POST',
4005 data: {
4006 action: 'vigilante_analyzer_save_settings',
4007 nonce: vigilanteAdmin.nonce,
4008 weekly_scan_enabled: $weekly.is(':checked') ? 1 : 0,
4009 email_on_regression: $email.is(':checked') ? 1 : 0
4010 },
4011 success: function(response) {
4012 if (response && response.success) {
4013 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
4014 Vigilante_Admin.showNotice('success',
4015 vigilanteAdmin.strings.analyzerSettingsSaved || 'Analyzer settings saved.');
4016 }
4017 } else {
4018 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
4019 Vigilante_Admin.showNotice('error',
4020 (response && response.data) || vigilanteAdmin.strings.error);
4021 }
4022 $input.prop('checked', !$input.is(':checked'));
4023 }
4024 },
4025 error: function() {
4026 if (typeof Vigilante_Admin !== 'undefined' && Vigilante_Admin.showNotice) {
4027 Vigilante_Admin.showNotice('error', vigilanteAdmin.strings.error);
4028 }
4029 $input.prop('checked', !$input.is(':checked'));
4030 }
4031 });
4032 },
4033
4034 /**
4035 * Re-render the sparkline from data-points (no-op if no points).
4036 */
4037 renderSparklineFromData: function() {
4038 var $wrap = this.$root.find('[data-role="sparkline"]');
4039 if (!$wrap.length) {
4040 return;
4041 }
4042 var raw = $wrap.attr('data-points');
4043 if (!raw) {
4044 return;
4045 }
4046 try {
4047 var points = JSON.parse(raw);
4048 if (!points || points.length < 2) {
4049 return;
4050 }
4051 // Only regenerate if the SVG is missing (e.g. server gave empty markup).
4052 if (!$wrap.find('svg').length) {
4053 $wrap.html(this.buildSparklineSvg(points));
4054 }
4055 this.attachSparklineHotspots($wrap, points);
4056 } catch (err) { /* ignore parse errors */ }
4057 },
4058
4059 /**
4060 * Inject invisible hot-spots over each sparkline point and wire up a tooltip
4061 * that shows the score on hover/focus.
4062 */
4063 attachSparklineHotspots: function($wrap, points) {
4064 if (!points || points.length < 2) {
4065 return;
4066 }
4067 // Idempotent: clear any previous hot-spots/tooltip first.
4068 $wrap.find('.vigilante-analyzer-sparkline-dot, .vigilante-analyzer-sparkline-tooltip').remove();
4069
4070 var SVG_W = 280, SVG_H = 60, PAD = 4;
4071 var usableW = SVG_W - PAD * 2;
4072 var usableH = SVG_H - PAD * 2;
4073 var step = usableW / Math.max(1, points.length - 1);
4074 var max = 100;
4075
4076 var $tooltip = $('<div class="vigilante-analyzer-sparkline-tooltip" aria-hidden="true"></div>');
4077 $wrap.append($tooltip);
4078
4079 for (var i = 0; i < points.length; i++) {
4080 var x = PAD + (i * step);
4081 var y = PAD + (usableH - ((points[i] / max) * usableH));
4082 var xPct = (x / SVG_W) * 100;
4083 var yPct = (y / SVG_H) * 100;
4084
4085 var $dot = $('<button type="button" class="vigilante-analyzer-sparkline-dot"></button>')
4086 .css({ left: xPct + '%', top: yPct + '%' })
4087 .attr('data-score', points[i])
4088 .attr('data-index', i)
4089 .attr('aria-label', String(points[i]));
4090 $wrap.append($dot);
4091 }
4092
4093 $wrap.off('.vigSpark');
4094 $wrap.on('mouseenter.vigSpark focus.vigSpark', '.vigilante-analyzer-sparkline-dot', function() {
4095 var $dot = $(this);
4096 $tooltip
4097 .text($dot.attr('data-score'))
4098 .css({ left: $dot.css('left'), top: $dot.css('top') })
4099 .addClass('is-visible');
4100 });
4101 $wrap.on('mouseleave.vigSpark blur.vigSpark', '.vigilante-analyzer-sparkline-dot', function() {
4102 $tooltip.removeClass('is-visible');
4103 });
4104 },
4105
4106 buildSparklineSvg: function(points) {
4107 var width = 280;
4108 var height = 60;
4109 var padding = 4;
4110 var usableW = width - (padding * 2);
4111 var usableH = height - (padding * 2);
4112 var count = points.length;
4113 var step = usableW / Math.max(1, count - 1);
4114 var max = 100;
4115
4116 var coords = [];
4117 for (var i = 0; i < count; i++) {
4118 var x = padding + (i * step);
4119 var y = padding + (usableH - ((points[i] / max) * usableH));
4120 coords.push(x.toFixed(2) + ',' + y.toFixed(2));
4121 }
4122 var path = 'M ' + coords.join(' L ');
4123 var lastX = padding + ((count - 1) * step);
4124 var lastY = padding + (usableH - ((points[count - 1] / max) * usableH));
4125
4126 return '<svg viewBox="0 0 ' + width + ' ' + height + '" preserveAspectRatio="none" '
4127 + 'role="img" focusable="false">'
4128 + '<path d="' + path + '" fill="none" stroke="currentColor" '
4129 + 'stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>'
4130 + '<circle cx="' + lastX.toFixed(2) + '" cy="' + lastY.toFixed(2) + '" r="3" fill="currentColor"/>'
4131 + '</svg>';
4132 },
4133
4134 /**
4135 * When landing on a fix link (#field-* or #vigilante-section-*),
4136 * scroll smoothly and flash-highlight the target.
4137 */
4138 hashFocusFlash: function() {
4139 var hash = window.location.hash;
4140 if (!hash || hash.length < 2) {
4141 return;
4142 }
4143 // Accept both section anchors and field anchors.
4144 if (!/^#(?:field-|vigilante-section-)/.test(hash)) {
4145 return;
4146 }
4147
4148 setTimeout(function() {
4149 var $target;
4150 try {
4151 $target = $(hash);
4152 } catch (err) { return; }
4153 if (!$target || !$target.length) {
4154 return;
4155 }
4156
4157 // Scroll to it smoothly.
4158 if ('scrollIntoView' in $target[0]) {
4159 $target[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
4160 }
4161
4162 // Flash — remove any previous flash first.
4163 $('.vigilante-focus-flash').removeClass('vigilante-focus-flash');
4164 $target.addClass('vigilante-focus-flash');
4165 setTimeout(function() {
4166 $target.removeClass('vigilante-focus-flash');
4167 }, 1800);
4168 }, 150);
4169 },
4170
4171 /** Escape text for HTML. */
4172 esc: function(str) {
4173 return String(str == null ? '' : str)
4174 .replace(/&/g, '&amp;')
4175 .replace(/</g, '&lt;')
4176 .replace(/>/g, '&gt;')
4177 .replace(/"/g, '&quot;')
4178 .replace(/'/g, '&#039;');
4179 },
4180
4181 /** Escape text for HTML attribute. */
4182 escAttr: function(str) {
4183 return this.esc(str);
4184 }
4185 };
4186
4187 // Initialize on document ready
4188 $(document).ready(function() {
4189 Vigilante_Admin.init();
4190 Vigilante_Admin.initPasswordReset();
4191 Vigilante_Admin.initUserApproval();
4192 Vigilante_Admin.initSessionManagement();
4193 VigilanteAnalyzer.init();
4194
4195 // Shared "Send test email" button (Notification settings, File Integrity, Audit Alerts).
4196 $(document).on('click', '.vigilante-test-email-btn', function(e) {
4197 e.preventDefault();
4198 var $btn = $(this);
4199 var $result = $btn.siblings('.vigilante-test-email-result');
4200 var original = $btn.data('original-text') || $btn.text();
4201 $btn.prop('disabled', true).text(vigilanteAdmin.strings.sendingTest || 'Sending...');
4202 $result.text('').css('color', '');
4203 $.ajax({
4204 url: vigilanteAdmin.ajaxUrl,
4205 type: 'POST',
4206 data: {
4207 action: 'vigilante_send_test_email',
4208 nonce: vigilanteAdmin.nonce
4209 },
4210 success: function(response) {
4211 if (response && response.success) {
4212 $result.css('color', '#00a32a').text((response.data && response.data.message) || '');
4213 } else {
4214 $result.css('color', '#d63638').text((response && response.data && response.data.message) || vigilanteAdmin.strings.error);
4215 }
4216 },
4217 error: function() {
4218 $result.css('color', '#d63638').text(vigilanteAdmin.strings.error);
4219 },
4220 complete: function() {
4221 $btn.prop('disabled', false).text(original);
4222 }
4223 });
4224 });
4225 });
4226
4227 })(jQuery);